// Theme — auto/light/dark with CSS vars + sun/moon toggle.
// Written so components that reference CSS variables (color: 'var(--fg)')
// automatically reflow. A scoped <style> layer provides overrides for
// components that still use hardcoded colors.

const { useEffect: useThemeEffect, useState: useThemeState } = React;

function useTheme() {
  // Resolves initial theme synchronously so first paint matches the <head>
  // script's decision (stored choice → system preference → dark).
  const [theme, setTheme] = useThemeState(() => {
    try {
      const raw = localStorage.getItem('fs-theme');
      if (raw === 'light' || raw === 'dark') return raw;
    } catch (e) {}
    return 'dark';
  });

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

  return [theme, setTheme];
}

// Sun/moon toggle — single click flips light ↔ dark instantly.
function ThemeToggle({ style }) {
  const [theme, setTheme] = useTheme();
  const isLight = theme === 'light';
  const next = isLight ? 'dark' : 'light';
  return (
    <button
      onClick={() => setTheme(next)}
      aria-label={`Switch to ${next} mode`}
      title={`Switch to ${next} mode`}
      style={{
        width: 40, height: 40, borderRadius: '50%',
        background: 'var(--surface-2)',
        border: '1px solid var(--border)',
        color: 'var(--fg)',
        cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        transition: 'all 200ms',
        position: 'relative',
        ...style,
      }}>
      {/* Sun */}
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{
        position: 'absolute',
        opacity: isLight ? 1 : 0,
        transform: isLight ? 'rotate(0deg) scale(1)' : 'rotate(-90deg) scale(0.5)',
        transition: 'all 300ms cubic-bezier(0.4, 0, 0.2, 1)',
      }}>
        <circle cx="12" cy="12" r="4"/>
        <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/>
      </svg>
      {/* Moon */}
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{
        position: 'absolute',
        opacity: isLight ? 0 : 1,
        transform: isLight ? 'rotate(90deg) scale(0.5)' : 'rotate(0deg) scale(1)',
        transition: 'all 300ms cubic-bezier(0.4, 0, 0.2, 1)',
      }}>
        <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/>
      </svg>
    </button>
  );
}

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