/**
 * useColumnPreferences Hook
 * Manages column visibility persistence in localStorage per page
 */

import { useState, useEffect, useCallback } from 'react';

interface UseColumnPreferencesOptions {
  storageKey: string; // Unique key for each page (e.g., 'writer_tasks_columns')
  defaultColumns: string[]; // Default visible column keys
}

export function useColumnPreferences({ storageKey, defaultColumns }: UseColumnPreferencesOptions) {
  // Initialize visible columns from localStorage or defaults
  const [visibleColumns, setVisibleColumns] = useState<string[]>(() => {
    try {
      const stored = localStorage.getItem(storageKey);
      if (stored) {
        const parsed = JSON.parse(stored);
        if (Array.isArray(parsed) && parsed.length > 0) {
          return parsed;
        }
      }
    } catch (error) {
      console.warn('Failed to load column preferences from localStorage:', error);
    }
    return defaultColumns;
  });

  // Save to localStorage whenever visibleColumns changes
  useEffect(() => {
    try {
      localStorage.setItem(storageKey, JSON.stringify(visibleColumns));
    } catch (error) {
      console.warn('Failed to save column preferences to localStorage:', error);
    }
  }, [storageKey, visibleColumns]);

  // Toggle column visibility
  const toggleColumn = useCallback((columnKey: string) => {
    setVisibleColumns((prev) => {
      if (prev.includes(columnKey)) {
        // Don't allow hiding the last column
        if (prev.length === 1) {
          return prev;
        }
        return prev.filter((key) => key !== columnKey);
      } else {
        return [...prev, columnKey];
      }
    });
  }, []);

  // Check if a column is visible
  const isColumnVisible = useCallback(
    (columnKey: string) => visibleColumns.includes(columnKey),
    [visibleColumns]
  );

  // Reset to defaults
  const resetToDefaults = useCallback(() => {
    setVisibleColumns(defaultColumns);
  }, [defaultColumns]);

  return {
    visibleColumns,
    toggleColumn,
    isColumnVisible,
    resetToDefaults,
  };
}
