import { create } from 'zustand';

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

interface ThemeState {
  theme: Theme;
  toggleTheme: () => void;
  setTheme: (t: Theme) => void;
}

const STORAGE_KEY = 'airdrama-theme';

const readInitialTheme = (): Theme => {
  if (typeof window === 'undefined') return 'dark';
  try {
    const stored = window.localStorage.getItem(STORAGE_KEY);
    if (stored === 'light' || stored === 'dark') return stored;
  } catch {
    // localStorage unavailable (incognito / disabled) — fall through to default
  }
  return 'dark';
};

const applyThemeToDom = (t: Theme): void => {
  if (typeof document === 'undefined') return;
  document.documentElement.dataset.theme = t;
};

const persistTheme = (t: Theme): void => {
  try {
    window.localStorage.setItem(STORAGE_KEY, t);
  } catch {
    // localStorage unavailable — silent fallback (theme still applies for the session)
  }
};

const initial = readInitialTheme();
applyThemeToDom(initial);

export const useThemeStore = create<ThemeState>((set, get) => ({
  theme: initial,
  toggleTheme: () => {
    const next: Theme = get().theme === 'dark' ? 'light' : 'dark';
    applyThemeToDom(next);
    persistTheme(next);
    set({ theme: next });
  },
  setTheme: (t) => {
    applyThemeToDom(t);
    persistTheme(t);
    set({ theme: t });
  },
}));
