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

/**
 * ThemeContext
 *  - mode : 'light' | 'dark' | 'system'  (préférence utilisateur, persistée)
 *  - resolved : 'light' | 'dark'         (thème effectivement appliqué)
 *
 * Le thème effectif est appliqué via l'attribut data-theme sur <html>.
 * En mode 'system', on écoute les changements du media query prefers-color-scheme.
 */

const ThemeCtx = createContext(null);

const STORAGE_KEY = 'cl_theme';

function getSystemTheme() {
  if (typeof window === 'undefined') return 'light';
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}

function applyTheme(theme) {
  const root = document.documentElement;
  root.setAttribute('data-theme', theme);
  // Inform the browser (form controls, scrollbars) of the active scheme
  root.style.colorScheme = theme;
}

export function ThemeProvider({ children }) {
  const [mode, setMode] = useState(() => localStorage.getItem(STORAGE_KEY) || 'system');
  const [systemTheme, setSystemTheme] = useState(getSystemTheme);

  // Listen to OS preference changes when in 'system' mode
  useEffect(() => {
    const mq = window.matchMedia('(prefers-color-scheme: dark)');
    const onChange = (e) => setSystemTheme(e.matches ? 'dark' : 'light');
    mq.addEventListener('change', onChange);
    return () => mq.removeEventListener('change', onChange);
  }, []);

  const resolved = mode === 'system' ? systemTheme : mode;

  // Apply the resolved theme to <html>
  useEffect(() => { applyTheme(resolved); }, [resolved]);

  const setThemeMode = useCallback((m) => {
    setMode(m);
    localStorage.setItem(STORAGE_KEY, m);
  }, []);

  const value = useMemo(
    () => ({ mode, resolved, setMode: setThemeMode }),
    [mode, resolved, setThemeMode],
  );

  return <ThemeCtx.Provider value={value}>{children}</ThemeCtx.Provider>;
}

export const useTheme = () => useContext(ThemeCtx);
