// theme-bridge.jsx — React hooks + theme toggle bridging window.CS_TOKENS
//
// Usage in components:
//   const T = useTokens();      // re-renders on theme change
//   const [theme, setTheme] = useTheme();
//
// The actual token data lives in tokens.js (window.CS_THEMES + window.CS_setTheme).
// This file is the React adapter + UI for switching themes.
// It also persists the choice to localStorage and keeps document.documentElement
// in sync via [data-theme="dark"|"light"] for CSS-var consumers.

(() => {
  // Hydrate from storage before any render
  const stored = (() => {
    try { return localStorage.getItem('cs-theme'); } catch { return null; }
  })();
  if (stored === 'light' || stored === 'dark') {
    window.CS_setTheme(stored);
  }
  document.documentElement.setAttribute('data-theme', window.CS_getTheme());
})();

// ── React hooks ───────────────────────────────────────────
function useTokens() {
  const [, force] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => window.CS_subscribeTheme(force), []);
  return window.CS_TOKENS;
}

function useTheme() {
  const [theme, setLocal] = React.useState(window.CS_getTheme());
  React.useEffect(() =>
    window.CS_subscribeTheme(t => setLocal(t)),
  []);
  const set = React.useCallback((t) => {
    window.CS_setTheme(t);
    document.documentElement.setAttribute('data-theme', t);
    try { localStorage.setItem('cs-theme', t); } catch {}
  }, []);
  return [theme, set];
}

// ── ThemeToggle component ─────────────────────────────────
function ThemeToggle({ compact = false }) {
  const T = useTokens();
  const [theme, setTheme] = useTheme();
  const isDark = theme === 'dark';

  return (
    <button
      onClick={() => setTheme(isDark ? 'light' : 'dark')}
      aria-label={`Switch to ${isDark ? 'light' : 'dark'} mode`}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        padding: compact ? '6px 10px' : '8px 12px',
        background: 'transparent',
        border: `1px solid ${T.border}`,
        color: T.text,
        fontFamily: T.mono, fontSize: 10, letterSpacing: 1.5,
        textTransform: 'uppercase', cursor: 'pointer',
        transition: 'all 0.18s',
      }}
      onMouseEnter={e => { e.currentTarget.style.borderColor = T.amber; }}
      onMouseLeave={e => { e.currentTarget.style.borderColor = T.border; }}>
      {/* Two-state icon */}
      <span style={{
        width: 14, height: 14, position: 'relative',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {isDark ? (
          /* Moon */
          <svg width="13" height="13" viewBox="0 0 14 14" fill="none">
            <path d="M11 8.5 A5 5 0 1 1 5.5 3 A4 4 0 0 0 11 8.5 Z"
              fill={T.amber} stroke={T.amber} strokeWidth="0.5" strokeLinejoin="round"/>
          </svg>
        ) : (
          /* Sun */
          <svg width="13" height="13" viewBox="0 0 14 14" fill="none">
            <circle cx="7" cy="7" r="3" fill={T.amber}/>
            <g stroke={T.amber} strokeWidth="1.2" strokeLinecap="round">
              <line x1="7" y1="1" x2="7" y2="2.5"/>
              <line x1="7" y1="11.5" x2="7" y2="13"/>
              <line x1="1" y1="7" x2="2.5" y2="7"/>
              <line x1="11.5" y1="7" x2="13" y2="7"/>
              <line x1="2.5" y1="2.5" x2="3.6" y2="3.6"/>
              <line x1="10.4" y1="10.4" x2="11.5" y2="11.5"/>
              <line x1="2.5" y1="11.5" x2="3.6" y2="10.4"/>
              <line x1="10.4" y1="3.6" x2="11.5" y2="2.5"/>
            </g>
          </svg>
        )}
      </span>
      {!compact && (
        <span>{isDark ? 'DARK' : 'LIGHT'}</span>
      )}
    </button>
  );
}

window.useTokens = useTokens;
window.useTheme = useTheme;
window.ThemeToggle = ThemeToggle;
