import { createContext, useContext, useState, useEffect, useCallback } from 'react';

const ThemeContext = createContext(null);

export function ThemeProvider({ children }) {
  const [theme, setThemeState] = useState(() => {
    // Personal preference > last known branding default > hardcoded fallback
    return localStorage.getItem('theme') || localStorage.getItem('branding-default-theme') || 'dark';
  });

  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);

  // Called by user intentionally (Settings page etc.) — saves as personal preference
  const setTheme = useCallback((newTheme) => {
    localStorage.setItem('theme', newTheme);
    setThemeState(newTheme);
  }, []);

  // Called by BrandingContext after loading the admin-configured default theme.
  // Only takes effect when the user has no personal preference stored.
  const applyBrandingDefault = useCallback((newDefault) => {
    if (!newDefault) return;
    localStorage.setItem('branding-default-theme', newDefault);
    if (!localStorage.getItem('theme')) {
      setThemeState(newDefault);
      document.documentElement.setAttribute('data-theme', newDefault);
    }
  }, []);

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

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