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

export const HUES = [
  { name: 'بنفش',       h: 277, c: 0.177 },
  { name: 'آبی پزشکی',  h: 256, c: 0.15 },
  { name: 'فیروزه‌ای',  h: 205, c: 0.12 },
  { name: 'سبز سلامت', h: 162, c: 0.13 },
  { name: 'نیلی',       h: 272, c: 0.16 },
] as const;

export type BrandHue = (typeof HUES)[number];

interface UiState {
  sidebarOpen: boolean;
  darkMode: boolean;
  density: 'comfortable' | 'compact';
  brandHue: BrandHue;
  settingsPanelOpen: boolean;
  toggleSidebar: () => void;
  setSidebarOpen: (open: boolean) => void;
  toggleDarkMode: () => void;
  setDensity: (density: 'comfortable' | 'compact') => void;
  setBrandHue: (hue: BrandHue) => void;
  toggleSettingsPanel: () => void;
}

function applyTheme(state: Pick<UiState, 'darkMode' | 'density' | 'brandHue'>) {
  const root = document.documentElement;
  root.classList.toggle('dark', state.darkMode);
  root.setAttribute('data-theme', state.darkMode ? 'dark' : 'light');
  root.setAttribute('data-density', state.density);
  root.style.setProperty('--brand-h', String(state.brandHue.h));
  root.style.setProperty('--brand-c', String(state.brandHue.c));
}

export const useUiStore = create<UiState>()(
  persist(
    (set, get) => ({
      sidebarOpen: true,
      darkMode: false,
      density: 'comfortable',
      brandHue: HUES[0],
      settingsPanelOpen: false,

      toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })),
      setSidebarOpen: (open) => set({ sidebarOpen: open }),

      toggleDarkMode: () => {
        const next = !get().darkMode;
        set({ darkMode: next });
        applyTheme({ ...get(), darkMode: next });
      },

      setDensity: (density) => {
        set({ density });
        applyTheme({ ...get(), density });
      },

      setBrandHue: (brandHue) => {
        set({ brandHue });
        applyTheme({ ...get(), brandHue });
      },

      toggleSettingsPanel: () => set((s) => ({ settingsPanelOpen: !s.settingsPanelOpen })),
    }),
    {
      name: 'clinicpro-ui',
      onRehydrateStorage: () => (state) => {
        if (state) {
          applyTheme({
            darkMode:  state.darkMode  ?? false,
            density:   state.density   ?? 'comfortable',
            brandHue:  state.brandHue  ?? HUES[0],
          });
        }
      },
    },
  ),
);
