/* global React */
/* BoldBrandz — Theme Context
 * Loaded FIRST — before 00-lang-context.jsx and 00-copy.jsx.
 * Exposes window.ThemeProvider and window.useTheme()
 * Usage: const { theme, toggleTheme } = window.useTheme();
 */
(function(){

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

const STORAGE_KEY = 'boldbrandz_theme';
const ThemeContext = createContext({ theme: 'dark', setTheme: () => {}, toggleTheme: () => {} });

function ThemeProvider({ children }) {
  const [theme, setThemeState] = useState(() => {
    try { return localStorage.getItem(STORAGE_KEY) || 'dark'; }
    catch { return 'dark'; }
  });

  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    try { localStorage.setItem(STORAGE_KEY, theme); } catch {}
  }, [theme]);

  function setTheme(next) {
    document.documentElement.classList.add('theme-transitioning');
    setTimeout(() => document.documentElement.classList.remove('theme-transitioning'), 300);
    setThemeState(next);
  }

  function toggleTheme() {
    setTheme(theme === 'dark' ? 'light' : 'dark');
  }

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

function useTheme() {
  return useContext(ThemeContext);
}

/* Apply saved theme immediately to <html> before React mounts — prevents FOUC */
(function initTheme() {
  try {
    const saved = localStorage.getItem(STORAGE_KEY) || 'dark';
    document.documentElement.setAttribute('data-theme', saved);
  } catch {
    document.documentElement.setAttribute('data-theme', 'dark');
  }
})();

window.ThemeProvider = ThemeProvider;
window.useTheme = useTheme;

})();
