// Clean-Rail theme: persisted `.dark` class on <html>. Default follows the
// system preference; user-toggle persists to localStorage and wins over it.

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

const STORAGE_KEY = 'netralax.theme';

function readStoredTheme(): Theme | null {
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY);
    if (raw === 'light' || raw === 'dark') return raw;
  } catch {
    /* localStorage unavailable (private mode / sandbox) */
  }
  return null;
}

function writeStoredTheme(theme: Theme): void {
  try {
    window.localStorage.setItem(STORAGE_KEY, theme);
  } catch {
    /* localStorage unavailable */
  }
}

function systemPrefersDark(): boolean {
  return typeof window !== 'undefined'
    && typeof window.matchMedia === 'function'
    && window.matchMedia('(prefers-color-scheme: dark)').matches;
}

export function getInitialTheme(): Theme {
  return readStoredTheme() ?? (systemPrefersDark() ? 'dark' : 'light');
}

export function applyTheme(theme: Theme): void {
  const root = document.documentElement;
  root.classList.toggle('dark', theme === 'dark');
}

export function setThemePersisted(theme: Theme): void {
  writeStoredTheme(theme);
  applyTheme(theme);
}
