// ThemeToggle — sits in the nav. Click to open a small popover with three
// options: System / Light / Dark. Persists via localStorage (handled by
// theme.js); listens for hf-theme-change to re-render the button label
// when the OS preference shifts on a "system" choice.
//
// Visual: a small pill with the current state's icon + label. The popover
// is anchored under the trigger and dismisses on outside click or Escape.

const { useState: useStateTT, useEffect: useEffectTT, useRef: useRefTT } = React;

function SunIcon({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <circle cx="8" cy="8" r="3" stroke="currentColor" strokeWidth="1.5" />
      <g stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
        <line x1="8" y1="1.5" x2="8" y2="3" />
        <line x1="8" y1="13" x2="8" y2="14.5" />
        <line x1="1.5" y1="8" x2="3" y2="8" />
        <line x1="13" y1="8" x2="14.5" y2="8" />
        <line x1="3.3" y1="3.3" x2="4.3" y2="4.3" />
        <line x1="11.7" y1="11.7" x2="12.7" y2="12.7" />
        <line x1="3.3" y1="12.7" x2="4.3" y2="11.7" />
        <line x1="11.7" y1="4.3" x2="12.7" y2="3.3" />
      </g>
    </svg>
  );
}

function MoonIcon({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path d="M13 9.5A5.5 5.5 0 0 1 6.5 3a5.5 5.5 0 1 0 6.5 6.5z"
            stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" />
    </svg>
  );
}

function SystemIcon({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <rect x="1.5" y="3" width="13" height="8.5" rx="1.5" stroke="currentColor" strokeWidth="1.5" />
      <line x1="5.5" y1="14" x2="10.5" y2="14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
      <line x1="8" y1="11.5" x2="8" y2="14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  );
}

const PREFS = [
  { id: 'system', label: 'System', Icon: SystemIcon, desc: 'Match my OS setting' },
  { id: 'light',  label: 'Light',  Icon: SunIcon,    desc: 'Always light' },
  { id: 'dark',   label: 'Dark',   Icon: MoonIcon,   desc: 'Always dark' },
];

function ThemeToggle() {
  const [pref, setPref] = useStateTT(() => (window.HFTheme ? window.HFTheme.get() : 'system'));
  const [resolved, setResolved] = useStateTT(() => (window.HFTheme ? window.HFTheme.resolve() : 'light'));
  const [open, setOpen] = useStateTT(false);
  const popRef = useRefTT(null);
  const btnRef = useRefTT(null);

  // Re-sync if theme changes externally (storage event, system pref shift).
  useEffectTT(() => {
    const onChange = (e) => {
      setPref(e.detail.pref);
      setResolved(e.detail.theme);
    };
    window.addEventListener('hf-theme-change', onChange);
    return () => window.removeEventListener('hf-theme-change', onChange);
  }, []);

  // Dismiss popover on outside click / Escape.
  useEffectTT(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (popRef.current && !popRef.current.contains(e.target) && btnRef.current && !btnRef.current.contains(e.target)) {
        setOpen(false);
      }
    };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => { document.removeEventListener('mousedown', onDoc); document.removeEventListener('keydown', onKey); };
  }, [open]);

  const choose = (id) => {
    if (window.HFTheme) window.HFTheme.set(id);
    setOpen(false);
  };

  // Trigger shows the *effective* state icon (sun in light, moon in dark)
  // but the label reflects the user's *preference* (System/Light/Dark) so it
  // accurately tells them what choice is active.
  const TriggerIcon = resolved === 'dark' ? MoonIcon : SunIcon;
  const triggerLabel = pref === 'system' ? 'Auto' : (pref === 'dark' ? 'Dark' : 'Light');

  return (
    <div style={{ position: 'relative' }}>
      <button
        ref={btnRef}
        onClick={() => setOpen(o => !o)}
        className="hf-btn"
        aria-label="Theme"
        aria-haspopup="true"
        aria-expanded={open}
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          padding: '6px 10px 6px 9px', borderRadius: 999,
          background: 'var(--bg-subtle)',
          border: '1px solid var(--line)',
          color: 'var(--fg)',
          fontSize: 12, fontWeight: 600,
        }}
      >
        <TriggerIcon size={14} />
        <span style={{ minWidth: 28 }}>{triggerLabel}</span>
      </button>

      {open && (
        <div
          ref={popRef}
          role="menu"
          style={{
            position: 'absolute', top: 'calc(100% + 8px)', right: 0,
            minWidth: 220,
            background: 'var(--bg-elevated)',
            border: '1px solid var(--line)',
            borderRadius: 12,
            boxShadow: 'var(--shadow-card)',
            padding: 6,
            zIndex: 100,
          }}>
          <div className="mono" style={{
            padding: '8px 10px 6px', fontSize: 10, letterSpacing: '0.18em',
            textTransform: 'uppercase', color: 'var(--fg-muted)',
          }}>
            Appearance
          </div>
          {PREFS.map(p => {
            const isActive = pref === p.id;
            return (
              <button
                key={p.id}
                role="menuitemradio"
                aria-checked={isActive}
                onClick={() => choose(p.id)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  width: '100%', padding: '10px 10px',
                  background: isActive ? 'rgba(194,97,31,0.10)' : 'transparent',
                  border: 'none', borderRadius: 8,
                  color: 'var(--fg)', textAlign: 'left',
                  cursor: 'pointer',
                  transition: 'background .12s',
                }}
                onMouseEnter={(e) => { if (!isActive) e.currentTarget.style.background = 'var(--bg-subtle)'; }}
                onMouseLeave={(e) => { if (!isActive) e.currentTarget.style.background = 'transparent'; }}
              >
                <span style={{
                  width: 28, height: 28, borderRadius: 8,
                  background: isActive ? 'var(--ember)' : 'var(--bg)',
                  color: isActive ? '#fff' : 'var(--fg)',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  flex: '0 0 28px',
                }}>
                  <p.Icon size={14} />
                </span>
                <span style={{ display: 'flex', flexDirection: 'column', gap: 1, flex: 1 }}>
                  <span style={{ fontSize: 13, fontWeight: 600 }}>{p.label}</span>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--fg-muted)', letterSpacing: '0.04em' }}>{p.desc}</span>
                </span>
                {isActive && (
                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
                    <path d="M3 7.5L6 10.5L11 4.5" stroke="var(--ember)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                )}
              </button>
            );
          })}
          {pref === 'system' && (
            <div className="mono" style={{
              padding: '8px 10px 6px', fontSize: 10, color: 'var(--fg-muted)',
              borderTop: '1px solid var(--line)', marginTop: 4, paddingTop: 8,
              letterSpacing: '0.06em',
            }}>
              // currently <span style={{ color: 'var(--ember)' }}>{resolved}</span> · follows your OS
            </div>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ThemeToggle });
