import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface UIStore {
  sidebarCollapsed: boolean;
  currentPortId: string | null;
  currentPortSlug: string | null;
  toggleSidebar: () => void;
  setPort: (portId: string, portSlug: string) => void;
}

export const useUIStore = create<UIStore>()(
  persist(
    (set) => ({
      sidebarCollapsed: false,
      currentPortId: null,
      currentPortSlug: null,
      toggleSidebar: () => set((s) => ({ sidebarCollapsed: !s.sidebarCollapsed })),
      setPort: (portId, portSlug) => set({ currentPortId: portId, currentPortSlug: portSlug }),
    }),
    {
      name: 'pn-crm-ui',
      // currentPortId/Slug are URL-derived, not user preferences. PortProvider
      // re-populates them from the route on every navigation. Persisting them
      // creates a hydration race where queries fire with a stale port id from
      // the previous session before the URL-derived effect runs.
      partialize: (state) => ({
        sidebarCollapsed: state.sidebarCollapsed,
      }),
    },
  ),
);

// Alias for port-specific access
export const usePortStore = useUIStore;
