/**
 * Column Visibility Store (Zustand)
 * Manages column visibility settings per page with localStorage persistence
 * Uses the same pattern as siteStore and sectorStore
 * Stores preferences per user for multi-user support
 */
import { create } from 'zustand';
import { persist, createJSONStorage, StateStorage } from 'zustand/middleware';
import { useAuthStore } from './authStore';

interface ColumnVisibilityState {
  // Map of page pathname to Set of visible column keys
  pageColumns: Record<string, string[]>;
  
  // Actions
  setPageColumns: (pathname: string, columnKeys: string[]) => void;
  getPageColumns: (pathname: string) => string[];
  toggleColumn: (pathname: string, columnKey: string) => void;
  resetPageColumns: (pathname: string) => void;
}

// Custom storage that uses user-specific keys
const userSpecificStorage: StateStorage = {
  getItem: (name: string) => {
    const user = useAuthStore.getState().user;
    const userId = user?.id || 'anonymous';
    const key = `igny8-column-visibility-user-${userId}`;
    const value = localStorage.getItem(key);
    return value;
  },
  setItem: (name: string, value: string) => {
    const user = useAuthStore.getState().user;
    const userId = user?.id || 'anonymous';
    const key = `igny8-column-visibility-user-${userId}`;
    localStorage.setItem(key, value);
  },
  removeItem: (name: string) => {
    const user = useAuthStore.getState().user;
    const userId = user?.id || 'anonymous';
    const key = `igny8-column-visibility-user-${userId}`;
    localStorage.removeItem(key);
  },
};

export const useColumnVisibilityStore = create<ColumnVisibilityState>()(
  persist<ColumnVisibilityState>(
    (set, get) => ({
      pageColumns: {},
      
      setPageColumns: (pathname: string, columnKeys: string[]) => {
        set((state) => ({
          pageColumns: {
            ...state.pageColumns,
            [pathname]: columnKeys,
          },
        }));
      },
      
      getPageColumns: (pathname: string) => {
        return get().pageColumns[pathname] || [];
      },
      
      toggleColumn: (pathname: string, columnKey: string) => {
        set((state) => {
          const currentColumns = state.pageColumns[pathname] || [];
          const newColumns = currentColumns.includes(columnKey)
            ? currentColumns.filter((key) => key !== columnKey)
            : [...currentColumns, columnKey];
          
          return {
            pageColumns: {
              ...state.pageColumns,
              [pathname]: newColumns,
            },
          };
        });
      },
      
      resetPageColumns: (pathname: string) => {
        set((state) => {
          const newPageColumns = { ...state.pageColumns };
          delete newPageColumns[pathname];
          return { pageColumns: newPageColumns };
        });
      },
    }),
    {
      name: 'igny8-column-visibility',
      storage: createJSONStorage(() => userSpecificStorage),
      partialize: (state) => ({
        pageColumns: state.pageColumns,
      }),
    }
  )
);

