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

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

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;
  setTheme: (theme: Theme) => void;
  toggleTheme: () => void;
  setActiveCampaign: (id: string | null) => void;
  setActiveEncounter: (id: string | null) => void;
}

export const useUiStore = create<UiState>()(
  persist(
    (set, get) => ({
      theme: 'dark',
      activeCampaignId: null,
      activeEncounterId: null,
      setTheme: (theme) => {
        applyTheme(theme);
        set({ theme });
      },
      toggleTheme: () => get().setTheme(get().theme === 'dark' ? 'light' : 'dark'),
      setActiveCampaign: (id) => set({ activeCampaignId: id, activeEncounterId: null }),
      setActiveEncounter: (id) => set({ activeEncounterId: id }),
    }),
    {
      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;
}
