// V1 SeamFlow — Tweaks panel
// Surfaces CSS variable controls wired up in index.html TWEAK_DEFAULTS.
// Activated by the host's Tweaks toggle.

(function () {
  const { useState, useEffect, useRef } = React;

  // ============================================================
  // HOST PROTOCOL: register listener FIRST, then announce available
  // ============================================================
  const listeners = new Set();
  let visible = false;

  window.addEventListener('message', (e) => {
    const d = e.data || {};
    if (d.type === '__activate_edit_mode') { visible = true; listeners.forEach(l => l(true)); }
    if (d.type === '__deactivate_edit_mode') { visible = false; listeners.forEach(l => l(false)); }
  });
  // Announce — only after listener is live.
  try { window.parent.postMessage({ type: '__edit_mode_available' }, '*'); } catch (_) {}

  // ============================================================
  // State plumbing
  // ============================================================
  const defaults = window.__V1_TWEAKS || {};

  const fontStack = (f) => ({
    'Space Grotesk': '"Space Grotesk", -apple-system, sans-serif',
    'Inter': 'Inter, -apple-system, sans-serif',
    'Fraunces': '"Fraunces", Georgia, serif',
    'Instrument Serif': '"Instrument Serif", Georgia, serif',
  }[f] || f);

  function applyTweak(key, val) {
    const r = document.documentElement;
    const map = {
      bgDepth:      () => r.style.setProperty('--v1-bg', val),
      panel:        () => r.style.setProperty('--v1-panel', val),
      accent:       () => { r.style.setProperty('--v1-accent', val); r.style.setProperty('--v1-accent-dim', val + '59'); },
      ink:          () => r.style.setProperty('--v1-ink', val),
      ink2:         () => r.style.setProperty('--v1-ink2', val),
      displayFont:  () => r.style.setProperty('--v1-font-display', fontStack(val)),
      bodyFont:     () => r.style.setProperty('--v1-font-body', fontStack(val)),
      h1Scale:      () => r.style.setProperty('--v1-h1-scale', val),
      h1Weight:     () => r.style.setProperty('--v1-h1-weight', val),
      h1Tracking:   () => r.style.setProperty('--v1-h1-tracking', val + 'px'),
      maxWidth:     () => r.style.setProperty('--v1-max-width', val + 'px'),
      sectionPadding: () => r.style.setProperty('--v1-section-pad', val),
      cardRadius:   () => r.style.setProperty('--v1-card-radius', val + 'px'),
      animSpeed:    () => r.style.setProperty('--v1-anim-speed', val),
      // boolean toggles (CSS rules in index.html read data-tw-* attributes)
      reveal:     () => r.setAttribute('data-tw-reveal', val ? 'on' : 'off'),
      grid:       () => r.setAttribute('data-tw-grid', val ? 'on' : 'off'),
      orbs:       () => r.setAttribute('data-tw-orbs', val ? 'on' : 'off'),
      ticker:     () => r.setAttribute('data-tw-ticker', val ? 'on' : 'off'),
      sweep:      () => r.setAttribute('data-tw-sweep', val ? 'on' : 'off'),
      kpis:       () => r.setAttribute('data-tw-kpis', val ? 'on' : 'off'),
      scripture:  () => r.setAttribute('data-tw-scripture', val ? 'on' : 'off'),
      dashboard:  () => r.setAttribute('data-tw-dashboard', val ? 'on' : 'off'),
      navpills:   () => r.setAttribute('data-tw-navpills', val ? 'on' : 'off'),
      h1italic:   () => r.setAttribute('data-tw-h1italic', val ? 'on' : 'off'),
      numerals:   () => r.setAttribute('data-tw-numerals', val),
      recommendedTier: () => r.setAttribute('data-tw-rec', val),
      accentIntensity: () => r.style.setProperty('--v1-accent-intensity', val),
    };
    if (map[key]) map[key]();
  }

  // ============================================================
  // Persistence → host
  // ============================================================
  function persist(patch) {
    try {
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*');
    } catch (_) {}
  }

  // ============================================================
  // Panel UI
  // ============================================================
  const P = {
    bg: 'rgba(14,14,18,0.92)',
    border: 'rgba(255,255,255,0.08)',
    borderHi: 'rgba(255,255,255,0.14)',
    ink: '#EDEDEF',
    ink2: '#9A9AA0',
    ink3: '#6A6A70',
    panel: 'rgba(255,255,255,0.03)',
    accent: '#FAC761',
  };

  function Panel() {
    const [show, setShow] = useState(false);
    const [state, setState] = useState(() => ({ ...defaults }));
    const [tab, setTab] = useState('look');
    const [collapsed, setCollapsed] = useState({}); // section collapse state

    useEffect(() => {
      const l = (v) => setShow(v);
      listeners.add(l);
      return () => listeners.delete(l);
    }, []);

    function set(key, val) {
      setState(s => ({ ...s, [key]: val }));
      applyTweak(key, val);
      persist({ [key]: val });
    }

    function reset() {
      const defs = window.__V1_TWEAKS || {};
      Object.keys(defs).forEach(k => applyTweak(k, defs[k]));
      setState({ ...defs });
      persist({ ...defs });
    }

    if (!show) return null;

    return (
      <div style={{
        position: 'fixed',
        bottom: 16, right: 16,
        width: 340,
        maxHeight: 'calc(100vh - 32px)',
        background: P.bg,
        backdropFilter: 'blur(24px) saturate(1.2)',
        WebkitBackdropFilter: 'blur(24px) saturate(1.2)',
        border: `1px solid ${P.border}`,
        borderRadius: 14,
        color: P.ink,
        fontFamily: 'Inter, -apple-system, sans-serif',
        fontSize: 12,
        boxShadow: '0 30px 80px -20px rgba(0,0,0,0.8), 0 0 0 1px rgba(255,255,255,0.02)',
        display: 'flex',
        flexDirection: 'column',
        zIndex: 999999,
        overflow: 'hidden',
      }}>
        {/* Header */}
        <div style={{
          padding: '14px 16px 12px',
          borderBottom: `1px solid ${P.border}`,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}>
          <div>
            <div style={{
              fontFamily: '"Space Grotesk", sans-serif',
              fontSize: 13,
              fontWeight: 600,
              letterSpacing: '-0.01em',
            }}>Tweaks</div>
            <div style={{ fontSize: 10, color: P.ink3, marginTop: 2, letterSpacing: '0.08em', textTransform: 'uppercase' }}>V1 · SeamFlow</div>
          </div>
          <button onClick={reset} style={{
            background: 'transparent',
            border: `1px solid ${P.border}`,
            color: P.ink2,
            padding: '4px 8px',
            fontSize: 10,
            borderRadius: 6,
            cursor: 'pointer',
            fontFamily: 'inherit',
            letterSpacing: '0.05em',
            textTransform: 'uppercase',
          }}>Reset</button>
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', borderBottom: `1px solid ${P.border}`, padding: '0 8px' }}>
          {[
            ['look', 'Look'],
            ['type', 'Type'],
            ['layout', 'Layout'],
            ['motion', 'Motion'],
            ['content', 'Content'],
          ].map(([k, label]) => (
            <button key={k} onClick={() => setTab(k)} style={{
              background: 'transparent',
              border: 'none',
              color: tab === k ? P.ink : P.ink3,
              padding: '10px 10px',
              fontSize: 11,
              cursor: 'pointer',
              fontFamily: 'inherit',
              letterSpacing: '0.04em',
              borderBottom: tab === k ? `1px solid ${P.accent}` : '1px solid transparent',
              marginBottom: -1,
              fontWeight: tab === k ? 600 : 400,
            }}>{label}</button>
          ))}
        </div>

        {/* Body */}
        <div style={{
          flex: 1,
          overflowY: 'auto',
          padding: '14px 16px 18px',
        }}>
          {tab === 'look' && (
            <>
              <Group title="Palette">
                <Color label="Background" value={state.bgDepth} onChange={v => set('bgDepth', v)}
                  swatches={['#050506', '#0A0A0C', '#0C0F14', '#100A0A', '#12100A', '#0A100C']} />
                <Color label="Panel" value={state.panel} onChange={v => set('panel', v)}
                  swatches={['#0C0C10', '#111115', '#141418', '#0F1216', '#161212', '#0E1410']} />
                <Color label="Accent" value={state.accent} onChange={v => set('accent', v)}
                  swatches={['#FAC761', '#D97757', '#B5A482', '#7AA8A3', '#E5484D', '#8B6F47', '#EDEDEF']} />
                <Color label="Ink" value={state.ink} onChange={v => set('ink', v)}
                  swatches={['#EDEDEF', '#FFFFFF', '#E8E6E1', '#D8D6D1', '#C8C6C1']} />
                <Color label="Ink secondary" value={state.ink2} onChange={v => set('ink2', v)}
                  swatches={['#B8B8BC', '#9A9AA0', '#8A8A90', '#A89E8E']} />
              </Group>
            </>
          )}

          {tab === 'type' && (
            <>
              <Group title="Fonts">
                <Select label="Display" value={state.displayFont} onChange={v => set('displayFont', v)}
                  options={['Space Grotesk', 'Fraunces', 'Instrument Serif', 'Inter']} />
                <Select label="Body" value={state.bodyFont} onChange={v => set('bodyFont', v)}
                  options={['Inter', 'Space Grotesk']} />
              </Group>
              <Group title="H1">
                <Slider label="Scale" value={state.h1Scale} min={0.75} max={1.35} step={0.01}
                  onChange={v => set('h1Scale', v)} format={v => v.toFixed(2) + '×'} />
                <Slider label="Weight" value={state.h1Weight} min={300} max={700} step={50}
                  onChange={v => set('h1Weight', v)} format={v => v} />
                <Slider label="Tracking" value={state.h1Tracking} min={-4} max={0} step={0.1}
                  onChange={v => set('h1Tracking', v)} format={v => v.toFixed(1) + 'px'} />
                <Toggle label="Italic saffron emphasis" value={state.h1italic} onChange={v => set('h1italic', v)} />
              </Group>
              <Group title="Signal numerals">
                <Segmented label="Style" value={state.numerals} onChange={v => set('numerals', v)}
                  options={[['large','Large'],['small','Small'],['hidden','Off']]} />
              </Group>
            </>
          )}

          {tab === 'layout' && (
            <>
              <Group title="Frame">
                <Slider label="Max width" value={state.maxWidth} min={960} max={1440} step={20}
                  onChange={v => set('maxWidth', v)} format={v => v + 'px'} />
                <Slider label="Section padding" value={state.sectionPadding} min={0.6} max={1.4} step={0.05}
                  onChange={v => set('sectionPadding', v)} format={v => v.toFixed(2) + '×'} />
                <Slider label="Card radius" value={state.cardRadius} min={0} max={28} step={1}
                  onChange={v => set('cardRadius', v)} format={v => v + 'px'} />
              </Group>
              <Group title="Recommended tier badge">
                <Segmented label="Tier" value={state.recommendedTier} onChange={v => set('recommendedTier', v)}
                  options={[['OPERATOR','Operator'],['TEAM','Team'],['COMMAND','Command']]} />
              </Group>
            </>
          )}

          {tab === 'motion' && (
            <>
              <Group title="Tempo">
                <Slider label="Animation speed" value={state.animSpeed} min={0} max={2} step={0.1}
                  onChange={v => set('animSpeed', v)} format={v => v === 0 ? 'off' : v.toFixed(1) + '×'} />
                <Toggle label="Scroll reveal" value={state.reveal} onChange={v => set('reveal', v)} />
                <Toggle label="Sweep shimmers" value={state.sweep} onChange={v => set('sweep', v)} />
              </Group>
              <Group title="Ambient">
                <Toggle label="Grid lines" value={state.grid} onChange={v => set('grid', v)} />
                <Toggle label="Glow orbs" value={state.orbs} onChange={v => set('orbs', v)} />
                <Toggle label="Marquee ticker" value={state.ticker} onChange={v => set('ticker', v)} />
              </Group>
            </>
          )}

          {tab === 'content' && (
            <>
              <Group title="Hero / foundation blocks">
                <Toggle label="Live dashboard mock" value={state.dashboard} onChange={v => set('dashboard', v)} />
                <Toggle label="KPI row" value={state.kpis} onChange={v => set('kpis', v)} />
                <Toggle label="Scripture mark" value={state.scripture} onChange={v => set('scripture', v)} />
                <Toggle label="Hero nav pills" value={state.navpills} onChange={v => set('navpills', v)} />
              </Group>
              <div style={{
                marginTop: 12,
                padding: 10,
                border: `1px dashed ${P.border}`,
                borderRadius: 8,
                color: P.ink3,
                fontSize: 10,
                lineHeight: 1.5,
              }}>
                Toggles hide feature blocks via CSS selector. Some blocks don't have hooks wired yet — they'll activate once class names land on the relevant components.
              </div>
            </>
          )}
        </div>
      </div>
    );
  }

  // ============================================================
  // Primitives
  // ============================================================
  function Group({ title, children }) {
    return (
      <div style={{ marginBottom: 18 }}>
        <div style={{
          fontSize: 9,
          fontWeight: 600,
          letterSpacing: '0.18em',
          textTransform: 'uppercase',
          color: P.ink3,
          marginBottom: 10,
        }}>{title}</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>{children}</div>
      </div>
    );
  }

  function Row({ label, children }) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ flex: '0 0 90px', color: P.ink2, fontSize: 11 }}>{label}</div>
        <div style={{ flex: 1, minWidth: 0, display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 6 }}>
          {children}
        </div>
      </div>
    );
  }

  function Color({ label, value, onChange, swatches = [] }) {
    const [open, setOpen] = useState(false);
    return (
      <div>
        <Row label={label}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 6,
            border: `1px solid ${P.border}`,
            borderRadius: 6,
            padding: '3px 6px 3px 3px',
            background: 'rgba(255,255,255,0.02)',
          }}>
            <input type="color" value={value} onChange={e => onChange(e.target.value)}
              style={{
                width: 20, height: 20, border: 'none', padding: 0,
                borderRadius: 4, background: 'transparent', cursor: 'pointer',
              }} />
            <input type="text" value={value} onChange={e => onChange(e.target.value)}
              style={{
                width: 70, fontFamily: '"JetBrains Mono", monospace',
                fontSize: 10, background: 'transparent', border: 'none',
                color: P.ink, outline: 'none',
              }} />
            <button onClick={() => setOpen(o => !o)} style={{
              background: 'transparent', border: 'none', color: P.ink3,
              cursor: 'pointer', padding: '0 2px', fontSize: 10,
            }}>{open ? '▴' : '▾'}</button>
          </div>
        </Row>
        {open && swatches.length > 0 && (
          <div style={{
            marginTop: 6,
            display: 'flex',
            flexWrap: 'wrap',
            gap: 4,
            paddingLeft: 98,
          }}>
            {swatches.map(s => (
              <button key={s} onClick={() => onChange(s)} title={s} style={{
                width: 18, height: 18, borderRadius: 4,
                background: s,
                border: value.toLowerCase() === s.toLowerCase() ? `1px solid ${P.accent}` : `1px solid ${P.border}`,
                cursor: 'pointer',
                padding: 0,
              }} />
            ))}
          </div>
        )}
      </div>
    );
  }

  function Slider({ label, value, min, max, step, onChange, format }) {
    return (
      <Row label={label}>
        <input type="range" min={min} max={max} step={step} value={value}
          onChange={e => onChange(parseFloat(e.target.value))}
          style={{ flex: 1, minWidth: 0, accentColor: P.accent }} />
        <div style={{
          flex: '0 0 52px',
          textAlign: 'right',
          fontFamily: '"JetBrains Mono", monospace',
          fontSize: 10,
          color: P.ink2,
        }}>{format ? format(value) : value}</div>
      </Row>
    );
  }

  function Select({ label, value, onChange, options }) {
    return (
      <Row label={label}>
        <select value={value} onChange={e => onChange(e.target.value)}
          style={{
            flex: 1,
            background: 'rgba(255,255,255,0.03)',
            border: `1px solid ${P.border}`,
            color: P.ink,
            padding: '4px 8px',
            borderRadius: 6,
            fontSize: 11,
            fontFamily: 'inherit',
            outline: 'none',
          }}>
          {options.map(o => <option key={o} value={o} style={{ background: '#0C0C10' }}>{o}</option>)}
        </select>
      </Row>
    );
  }

  function Toggle({ label, value, onChange }) {
    return (
      <Row label={label}>
        <button onClick={() => onChange(!value)} style={{
          position: 'relative',
          width: 30, height: 16,
          border: `1px solid ${value ? P.accent : P.border}`,
          background: value ? 'rgba(250,199,97,0.15)' : 'rgba(255,255,255,0.02)',
          borderRadius: 10,
          cursor: 'pointer',
          padding: 0,
          transition: 'all .18s',
        }}>
          <span style={{
            position: 'absolute',
            top: 1, left: value ? 15 : 1,
            width: 12, height: 12,
            borderRadius: '50%',
            background: value ? P.accent : P.ink2,
            transition: 'left .18s, background .18s',
          }} />
        </button>
      </Row>
    );
  }

  function Segmented({ label, value, onChange, options }) {
    return (
      <Row label={label}>
        <div style={{
          display: 'flex',
          border: `1px solid ${P.border}`,
          borderRadius: 6,
          overflow: 'hidden',
        }}>
          {options.map(([k, l], i) => (
            <button key={k} onClick={() => onChange(k)} style={{
              background: value === k ? 'rgba(250,199,97,0.12)' : 'transparent',
              border: 'none',
              borderLeft: i === 0 ? 'none' : `1px solid ${P.border}`,
              color: value === k ? P.accent : P.ink2,
              padding: '4px 8px',
              fontSize: 10,
              cursor: 'pointer',
              fontFamily: 'inherit',
              fontWeight: value === k ? 600 : 400,
              letterSpacing: '0.04em',
            }}>{l}</button>
          ))}
        </div>
      </Row>
    );
  }

  // ============================================================
  // Mount
  // ============================================================
  const root = document.getElementById('tweaks-root');
  if (root) {
    ReactDOM.createRoot(root).render(<Panel />);
  }
})();
