/**
 * Column Visibility Store (Zustand)
 * Simple localStorage-based column visibility per page per user
 */
import { create } from 'zustand';

interface ColumnVisibilityState {
  getVisibleColumns: (pathname: string) => string[];
  setVisibleColumns: (pathname: string, columns: string[]) => void;
}

// Get user ID from auth storage
const getUserId = (): string => {
  try {
    const authData = localStorage.getItem('auth-storage');
    if (authData) {
      const parsed = JSON.parse(authData);
      return String(parsed?.state?.user?.id || 'anonymous');
    }
  } catch (e) {
    // ignore
  }
  return 'anonymous';
};

// Build storage key
const getStorageKey = (pathname: string): string => {
  return `columns-${getUserId()}-${pathname}`;
};

export const useColumnVisibilityStore = create<ColumnVisibilityState>((set, get) => ({
  getVisibleColumns: (pathname: string) => {
    try {
      const key = getStorageKey(pathname);
      const stored = localStorage.getItem(key);
      if (stored) {
        return JSON.parse(stored);
      }
    } catch (e) {
      // ignore
    }
    return [];
  },
  
  setVisibleColumns: (pathname: string, columns: string[]) => {
    try {
      const key = getStorageKey(pathname);
      localStorage.setItem(key, JSON.stringify(columns));
    } catch (e) {
      // ignore
    }
  },
}));
