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

export type Theme = 'dark' | 'light';

export interface Handout { title: string; body: string; image?: string }

interface UiState {
  theme: Theme;
  /** id of the campaign currently in focus across feature screens */
  activeCampaignId: string | null;
  /** encounter currently open in the combat tracker (so the bestiary can target it) */
  activeEncounterId: string | null;
  /** map currently projected to the player view */
  activeMapId: string | null;
  /** a handout currently shown to players (title/body/optional image) */
  activeHandout: Handout | null;
  /** whether the docked session sidebar is open (persisted) */
  sessionDockOpen: boolean;
  /** whether the left nav rail is collapsed to icons (persisted) */
  railCollapsed: boolean;
  setTheme: (theme: Theme) => void;
  toggleTheme: () => void;
  setActiveCampaign: (id: string | null) => void;
  setActiveEncounter: (id: string | null) => void;
  setActiveMap: (id: string | null) => void;
  setActiveHandout: (h: Handout | null) => void;
  setSessionDock: (open: boolean) => void;
  toggleRail: () => void;
}

export const useUiStore = create<UiState>()(
  persist(
    (set, get) => ({
      theme: 'dark',
      activeCampaignId: null,
      activeEncounterId: null,
      activeMapId: null,
      activeHandout: null,
      sessionDockOpen: false,
      railCollapsed: false,
      setTheme: (theme) => {
        applyTheme(theme);
        set({ theme });
      },
      toggleTheme: () => get().setTheme(get().theme === 'dark' ? 'light' : 'dark'),
      setActiveCampaign: (id) => set({ activeCampaignId: id, activeEncounterId: null, activeMapId: null, activeHandout: null }),
      setActiveEncounter: (id) => set({ activeEncounterId: id }),
      setActiveMap: (id) => set({ activeMapId: id }),
      setActiveHandout: (activeHandout) => set({ activeHandout }),
      setSessionDock: (sessionDockOpen) => set({ sessionDockOpen }),
      toggleRail: () => set((s) => ({ railCollapsed: !s.railCollapsed })),
    }),
    {
      name: 'ttrpg-ui',
      onRehydrateStorage: () => (state) => {
        applyTheme(state?.theme ?? 'dark');
      },
    },
  ),
);

/** Reflect the theme on <html>. The old app's light theme was a no-op; this isn't. */
export function applyTheme(theme: Theme): void {
  const root = document.documentElement;
  root.classList.toggle('dark', theme === 'dark');
  root.style.colorScheme = theme;
}
