import { useState, useEffect } from 'react';

const STORAGE_KEY = 'queue-filter-panel-collapsed';

interface UseFilterPanelStateReturn {
  isCollapsed: boolean;
  toggle: () => void;
  setCollapsed: (value: boolean) => void;
}

/**
 * Hook to manage filter panel collapsed/expanded state
 * Syncs with localStorage for persistence across sessions
 */
export function useFilterPanelState(): UseFilterPanelStateReturn {
  const [isCollapsed, setIsCollapsed] = useState<boolean>(() => {
    // Initialize from localStorage on mount
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      // Default to collapsed on mobile (width < 768px)
      const isMobile = window.innerWidth < 768;
      return stored ? JSON.parse(stored) : isMobile;
    } catch (error) {
      console.error('Error reading filter panel state from localStorage:', error);
      return window.innerWidth < 768;
    }
  });

  // Sync to localStorage when state changes
  useEffect(() => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(isCollapsed));
    } catch (error) {
      console.error('Error saving filter panel state to localStorage:', error);
    }
  }, [isCollapsed]);

  const toggle = () => setIsCollapsed(prev => !prev);
  
  const setCollapsed = (value: boolean) => setIsCollapsed(value);

  return {
    isCollapsed,
    toggle,
    setCollapsed,
  };
}
