import { writable } from 'svelte/store';
import { browser } from '$app/environment';

export type ThemePreference = 'light' | 'dark' | 'system';
export type ResolvedTheme = 'light' | 'dark';

const STORAGE_KEY = 'theme';

// Dark mode is strictly opt-in. Light is the default and the OS colour scheme is
// deliberately ignored: only an explicit stored 'dark' resolves to dark, so the
// app never loads dark on its own. The legacy 'system' value collapses to light.
function resolve(pref: ThemePreference): ResolvedTheme {
  return pref === 'dark' ? 'dark' : 'light';
}

function readPreference(): ThemePreference {
  if (!browser) return 'light';
  const stored = window.localStorage.getItem(STORAGE_KEY);
  return stored === 'light' || stored === 'dark' || stored === 'system' ? stored : 'light';
}

function applyResolved(theme: ResolvedTheme) {
  if (browser) {
    document.documentElement.dataset.theme = theme;
  }
}

/** The user's stored choice (may be the legacy 'system'). */
export const themePreference = writable<ThemePreference>(readPreference());

/** The theme actually painted right now. */
export const resolvedTheme = writable<ResolvedTheme>(resolve(readPreference()));

if (browser) {
  themePreference.subscribe((pref) => {
    window.localStorage.setItem(STORAGE_KEY, pref);
    const next = resolve(pref);
    resolvedTheme.set(next);
    applyResolved(next);
  });
}

/** Flip between light and dark, committing to an explicit preference. */
export function toggleTheme() {
  themePreference.update((pref) => (resolve(pref) === 'dark' ? 'light' : 'dark'));
}
