import { useEffect, useState } from 'react';

const HEIGHT_KEY = 'dashboard.listHeightPct';
const COLLAPSED_KEY = 'dashboard.collapsed';

const DEFAULT_LIST_PCT = 65;

export function useSidePanelLayout() {
  const [listHeightPct, setListHeightPct] = useState<number>(() => {
    const raw = localStorage.getItem(HEIGHT_KEY);
    const n = raw ? Number(raw) : NaN;
    return Number.isFinite(n) && n >= 20 && n <= 85 ? n : DEFAULT_LIST_PCT;
  });
  const [collapsed, setCollapsed] = useState<boolean>(
    () => localStorage.getItem(COLLAPSED_KEY) === '1',
  );

  useEffect(() => {
    localStorage.setItem(HEIGHT_KEY, String(listHeightPct));
  }, [listHeightPct]);

  useEffect(() => {
    localStorage.setItem(COLLAPSED_KEY, collapsed ? '1' : '0');
  }, [collapsed]);

  return {
    listHeightPct,
    setListHeightPct,
    collapsed,
    toggleCollapsed: () => setCollapsed((c) => !c),
    resetHeight: () => setListHeightPct(DEFAULT_LIST_PCT),
  };
}
