import { useCallback, useEffect, useState } from "react";

export type Appearance = "system" | "light" | "dark";
export const APPEARANCE_MODES: Appearance[] = ["system", "light", "dark"];

const KEY = "flighttube.appearance";
const media = window.matchMedia("(prefers-color-scheme: dark)");

function stored(): Appearance {
  try {
    const v = localStorage.getItem(KEY);
    return v === "light" || v === "dark" || v === "system" ? v : "system";
  } catch {
    return "system";
  }
}

const effective = (mode: Appearance) =>
  mode === "system" ? (media.matches ? "dark" : "light") : mode;

/**
 * Three states, not two. "System" keeps following the OS if it changes
 * mid-session; light and dark are explicit overrides.
 */
export function useAppearance() {
  const [mode, setMode] = useState<Appearance>(stored);
  const [shown, setShown] = useState<"light" | "dark">(() => effective(stored()));

  const apply = useCallback((m: Appearance) => {
    const next = effective(m);
    document.documentElement.classList.toggle("dark", next === "dark");
    setShown(next);
  }, []);

  useEffect(() => {
    apply(mode);
    try {
      localStorage.setItem(KEY, mode);
    } catch {
      /* storage blocked */
    }
  }, [mode, apply]);

  useEffect(() => {
    const onChange = () => {
      if (mode === "system") apply(mode);
    };
    media.addEventListener("change", onChange);
    return () => media.removeEventListener("change", onChange);
  }, [mode, apply]);

  return { mode, setMode, shown };
}
