import { useCallback, useEffect, useState } from 'react';
import { api } from '@/api';

const SETTING_KEY = 'search_bars_collapsed';

function settingToBool(value: unknown): boolean {
  return value === true || value === 'true' || value === '1' || value === 1;
}

export function useSearchPanelPreference(): [boolean, (nextCollapsed: boolean) => void] {
  const [collapsed, setCollapsed] = useState(false);

  useEffect(() => {
    let mounted = true;
    api.settings()
      .then(settings => {
        if (mounted && settings?.[SETTING_KEY] !== undefined && settings?.[SETTING_KEY] !== null) {
          setCollapsed(settingToBool(settings[SETTING_KEY]));
        }
      })
      .catch(() => {});

    return () => { mounted = false; };
  }, []);

  const saveCollapsed = useCallback((nextCollapsed: boolean) => {
    setCollapsed(nextCollapsed);
    api.saveSettings({ [SETTING_KEY]: nextCollapsed ? 'true' : 'false' }).catch(() => {});
  }, []);

  return [collapsed, saveCollapsed];
}
