/* NeuralVault — theme.jsx
   Theme context + toggle. Persists to localStorage and reflects on <html data-theme>. */

const { createContext, useContext, useState, useEffect } = React;

const ThemeContext = createContext({ theme: "dark", toggle: () => {}, setTheme: () => {} });
const useTheme = () => useContext(ThemeContext);

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState(() => {
    if (typeof window === "undefined") return "dark";
    return localStorage.getItem("nv-theme") || document.documentElement.getAttribute("data-theme") || "dark";
  });

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    localStorage.setItem("nv-theme", theme);
  }, [theme]);

  const toggle = () => setTheme((t) => (t === "dark" ? "light" : "dark"));

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

function ThemeToggle() {
  const { toggle, theme } = useTheme();
  return (
    <button
      className="theme"
      onClick={toggle}
      aria-label={`Switch to ${theme === "dark" ? "light" : "dark"} mode`}
    >
      <Icon name="sun" className="sun" />
      <Icon name="moon" className="moon" />
    </button>
  );
}

Object.assign(window, { ThemeContext, useTheme, ThemeProvider, ThemeToggle });
