/* global React */
// Bevri theme: persists light/dark, applies data-theme to <html>, exposes <ThemeToggle/>.
const THEME_KEY = 'bevri_theme';

function getTheme() {
  try { return localStorage.getItem(THEME_KEY) || 'light'; } catch { return 'light'; }
}
function applyTheme(t) {
  document.documentElement.setAttribute('data-theme', t);
}
// apply immediately on load (init script in <head> handles first paint; this is a safety net)
applyTheme(getTheme());

function ThemeToggle() {
  const [theme, setTheme] = React.useState(getTheme());
  const toggle = () => {
    const next = theme === 'dark' ? 'light' : 'dark';
    setTheme(next);
    applyTheme(next);
    try { localStorage.setItem(THEME_KEY, next); } catch {}
  };
  const dark = theme === 'dark';
  return (
    <button className="theme-toggle" onClick={toggle} title={dark ? 'Switch to light mode' : 'Switch to dark mode'} aria-label="Toggle dark mode">
      {dark
        ? <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="4.2" /><path d="M12 2.5v2.5M12 19v2.5M4.6 4.6l1.8 1.8M17.6 17.6l1.8 1.8M2.5 12H5M19 12h2.5M4.6 19.4l1.8-1.8M17.6 6.4l1.8-1.8" /></svg>
        : <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.8A8.5 8.5 0 1 1 11.2 3a6.6 6.6 0 0 0 9.8 9.8z" /></svg>}
    </button>
  );
}

window.ThemeToggle = ThemeToggle;
