export type ThemeMode = "light" | "dark" | "system";

type DocWithVT = Document & { startViewTransition?: (cb: () => void) => { finished: Promise<void> } };

/**
 * Applies a theme and persists it in a cookie. When the browser supports the
 * View Transitions API the new palette is revealed with a soft circular wipe
 * from `origin` (defaults to the account menu, top-right).
 */
export function applyTheme(t: ThemeMode, origin?: { x: number; y: number }) {
  document.cookie = `lj_theme=${t}; path=/; max-age=31536000; samesite=lax`;
  const dark = t === "dark" || (t === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches);
  const root = document.documentElement;
  const swap = () => {
    root.classList.toggle("dark", dark);
    root.dataset.theme = t;
  };
  const doc = document as DocWithVT;
  const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  if (!doc.startViewTransition || reduced || root.classList.contains("dark") === dark) return swap();
  root.style.setProperty("--vt-x", origin ? `${origin.x}px` : "calc(100% - 44px)");
  root.style.setProperty("--vt-y", origin ? `${origin.y}px` : "28px");
  doc.startViewTransition(swap);
}
