import { startTransition, useEffect, useState } from 'react';
import type { ResearchDensityMode } from '../types/research';

interface ResearchLayoutPrefs {
  density: ResearchDensityMode;
  showInspector: boolean;
  showGhostRail: boolean;
  memoPreview: boolean;
}

const STORAGE_KEY = 'mosaiciq.research.layout';

const defaultPrefs: ResearchLayoutPrefs = {
  density: 'comfortable',
  showInspector: true,
  showGhostRail: true,
  memoPreview: true,
};

export const useResearchLayoutPrefs = () => {
  const [prefs, setPrefs] = useState<ResearchLayoutPrefs>(defaultPrefs);

  useEffect(() => {
    try {
      const rawValue = localStorage.getItem(STORAGE_KEY);
      if (!rawValue) {
        return;
      }
      const parsed = JSON.parse(rawValue) as Partial<ResearchLayoutPrefs>;
      setPrefs({ ...defaultPrefs, ...parsed });
    } catch (error) {
      console.error('Failed to load research layout prefs:', error);
    }
  }, []);

  useEffect(() => {
    document.documentElement.dataset.density = prefs.density;
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(prefs));
    } catch (error) {
      console.error('Failed to persist research layout prefs:', error);
    }
  }, [prefs]);

  const updatePrefs = (patch: Partial<ResearchLayoutPrefs>) => {
    startTransition(() => {
      setPrefs((current) => ({ ...current, ...patch }));
    });
  };

  return {
    prefs,
    setDensity: (density: ResearchDensityMode) => updatePrefs({ density }),
    toggleInspector: () => updatePrefs({ showInspector: !prefs.showInspector }),
    toggleGhostRail: () => updatePrefs({ showGhostRail: !prefs.showGhostRail }),
    toggleMemoPreview: () => updatePrefs({ memoPreview: !prefs.memoPreview }),
  };
};
