import {
  atomWithLocalStorage,
  getLocalStorageItem,
  setLocalStorageItem,
} from './utils/atomWithLocalStorage';

export const THREAD_DRAWER_WIDTH_KEY = 'vojo_thread_drawer_width';
// Match the prior static `clamp(320, 28%, 420)` lower bound so users on
// narrow viewports keep the same minimum they had pre-resize.
export const THREAD_DRAWER_WIDTH_MIN = 320;
// Upper end of the prior clamp — pleasant default for typical desktops.
export const THREAD_DRAWER_WIDTH_DEFAULT = 420;

const readThreadDrawerWidth = (key: string): number => {
  const raw = getLocalStorageItem<unknown>(key, THREAD_DRAWER_WIDTH_DEFAULT);
  const value =
    typeof raw === 'number' && Number.isFinite(raw) ? raw : THREAD_DRAWER_WIDTH_DEFAULT;
  return Math.max(THREAD_DRAWER_WIDTH_MIN, Math.round(value));
};

export const threadDrawerWidthAtom = atomWithLocalStorage<number>(
  THREAD_DRAWER_WIDTH_KEY,
  readThreadDrawerWidth,
  setLocalStorageItem
);

// Symmetric with `clampSidebarWidth` — max = viewport/3 with a MIN floor
// so single-window-fraction viewports don't collapse the drawer below
// what's readable.
export const clampThreadDrawerWidth = (px: number, viewportWidth: number): number => {
  const max = Math.max(THREAD_DRAWER_WIDTH_MIN, Math.floor(viewportWidth / 3));
  return Math.max(THREAD_DRAWER_WIDTH_MIN, Math.min(max, Math.round(px)));
};
