import {
  createContext,
  useContext,
  useState,
  useEffect,
  useLayoutEffect,
  type ReactNode,
} from "react";
import { flushSync } from "react-dom";

interface ThemeContextValue {
  theme: string;
  toggleTheme: () => void;
}

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

/**
 * The first-paint theme fallback used before any stored preference is read.
 *
 * SINGLE SOURCE OF TRUTH for the default mode. `MuiProvider`'s
 * `<ThemeProvider defaultMode="…">` MUST use this same value (import it from
 * here) — if the two defaults drift, MUI and this context pick different modes
 * on the first frame and the page/toggle desync until a reload. The two
 * `localStorage.getItem("mui-mode")` fallbacks below both reference this so
 * they can never diverge from each other either.
 */
export const DEFAULT_THEME_MODE: ThemeMode = "dark";

const ThemeContext = createContext<ThemeContextValue | null>(null);

function readStoredTheme(): ThemeMode {
  // Single source of truth = MUI's own mode key. MUI's cssVariables provider
  // reads `mui-mode` on mount and sets `data-theme` from it, so we read/write
  // that SAME key (no separate boha-theme) — page and toggle stay in sync
  // across reloads. Fall back to the legacy key for pre-existing sessions.
  const stored =
    localStorage.getItem("mui-mode") || localStorage.getItem("boha-theme");
  return stored === "light" || stored === "dark" ? stored : DEFAULT_THEME_MODE;
}

type ViewTransitionDocument = Document & {
  startViewTransition?: (callback: () => void) => unknown;
};

export function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<ThemeMode>(() => {
    if (typeof window === "undefined") return DEFAULT_THEME_MODE;
    return readStoredTheme();
  });

  // Apply synchronously (layout effect) so the `data-theme` attribute flips
  // inside the View Transition's flushSync below — letting the browser capture
  // the "after" snapshot and cross-fade to it.
  useLayoutEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    localStorage.setItem("mui-mode", theme);
    localStorage.removeItem("boha-theme"); // retire the duplicate legacy key
    const themeColor = theme === "dark" ? "#12121a" : "#ffffff";
    document
      .querySelector('meta[name="theme-color"]')
      ?.setAttribute("content", themeColor);
  }, [theme]);

  // Cross-tab sync: when another tab toggles the theme it writes `mui-mode`,
  // which fires a `storage` event here. Mirror the new value (instant — no
  // View Transition, since this tab didn't initiate the change) so all open
  // tabs stay visually consistent without a reload.
  useEffect(() => {
    const onStorage = (e: StorageEvent) => {
      if (e.key !== "mui-mode") return;
      const next = e.newValue;
      if (next === "light" || next === "dark") {
        setTheme((prev) => (prev === next ? prev : next));
      }
    };
    window.addEventListener("storage", onStorage);
    return () => window.removeEventListener("storage", onStorage);
  }, []);

  const toggleTheme = () => {
    const apply = () =>
      setTheme((prev) => (prev === "dark" ? "light" : "dark"));

    const doc = document as ViewTransitionDocument;
    const reduceMotion =
      typeof window !== "undefined" &&
      !!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

    // View Transitions API: the browser cross-fades a GPU-composited snapshot of
    // the whole page — smooth at any element count — instead of repainting every
    // node's colors (which stutters). Falls back to an instant switch where the
    // API is unavailable or the user prefers reduced motion.
    if (doc.startViewTransition && !reduceMotion) {
      doc.startViewTransition(() => flushSync(apply));
    } else {
      apply();
    }
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

export function useTheme(): ThemeContextValue {
  const context = useContext(ThemeContext);
  if (!context) throw new Error("useTheme must be used within a ThemeProvider");
  return context;
}
