import { Monitor, Sun, Moon } from "lucide-react";
import { createContext, useContext, useEffect, useLayoutEffect, useId, useState, type ReactNode } from "react";
import { resolveTheme, THEME_STORAGE_KEY, themePreference, type Theme, type ThemePreference } from "../lib/theme";
const ThemeContext = createContext<{ theme: Theme; preference: ThemePreference; setPreference: (value: ThemePreference) => void }>({ theme: "light", preference: "system", setPreference: () => {} });
export const useTheme = () => useContext(ThemeContext);
export function ThemeProvider({ children }: { children: ReactNode }) {
  const [preference, setValue] = useState<ThemePreference>(() => {
    try { return themePreference(localStorage.getItem(THEME_STORAGE_KEY)); } catch { return "system"; }
  });
  const [systemDark, setSystemDark] = useState(() => typeof matchMedia === "function" && matchMedia("(prefers-color-scheme: dark)").matches);
  const theme = resolveTheme(preference, systemDark);
  useLayoutEffect(() => {
    document.documentElement.dataset.theme = theme;
    document.documentElement.classList.toggle("dark", theme === "dark");
    document.documentElement.style.colorScheme = theme;
  }, [theme]);
  useEffect(() => {
    const media = window.matchMedia?.("(prefers-color-scheme: dark)");
    const change = () => setSystemDark(media?.matches ?? false);
    const storage = (event: StorageEvent) => { if (event.key === THEME_STORAGE_KEY || event.key === null) setValue(themePreference(event.newValue)); };
    change(); media?.addEventListener("change", change); window.addEventListener("storage", storage);
    return () => { media?.removeEventListener("change", change); window.removeEventListener("storage", storage); };
  }, []);
  const setPreference = (value: ThemePreference) => {
    setValue(value);
    try { localStorage.setItem(THEME_STORAGE_KEY, value); } catch { /* Theme still works when browser storage is unavailable. */ }
  };
  return <ThemeContext value={{ theme, preference, setPreference }}>{children}</ThemeContext>;
}
export function ThemeControl({ disabled = false }: { disabled?: boolean }) {
  const { preference, setPreference } = useTheme();
  const id = useId();
  return (
    <div className="ds-theme-control" role="group" aria-label="Theme">
      {([
        { value: "system", label: "System", Icon: Monitor },
        { value: "light", label: "Light", Icon: Sun },
        { value: "dark", label: "Dark", Icon: Moon },
      ] as const).map(({ value, label, Icon }) => (
        <label className="ds-theme-option" key={value}>
          <input type="radio" name={`theme-${id}`} value={value} checked={preference === value} disabled={disabled} onChange={() => setPreference(value)} />
          <span><Icon size={16} strokeWidth={1.75} aria-hidden="true" />{label}</span>
        </label>
      ))}
    </div>
  );
}
