// App root — Tweaks panel + page composition
const { useState, useEffect, useMemo } = React;

const DEFAULT_TWEAKS = window.__TWEAKS__ || { heroVariant: 'editorial', typePair: 'grotesk-inter' };

const TYPE_PAIRS = {
  'grotesk-inter':   { display: "'Space Grotesk', system-ui, sans-serif",   body: "'Inter', system-ui, sans-serif",   mono: "'JetBrains Mono', ui-monospace, monospace", weight: 600, tracking: '-0.025em', label: 'Space Grotesk + Inter' },
  'fraunces-manrope':{ display: "'Fraunces', Georgia, serif",               body: "'Manrope', system-ui, sans-serif", mono: "'JetBrains Mono', ui-monospace, monospace", weight: 500, tracking: '-0.02em',  label: 'Fraunces + Manrope'   },
  'grotesk-dm':      { display: "'Space Grotesk', system-ui, sans-serif",   body: "'DM Sans', system-ui, sans-serif",  mono: "'JetBrains Mono', ui-monospace, monospace", weight: 600, tracking: '-0.025em', label: 'Space Grotesk + DM Sans' },
  'instrument-inter':{ display: "'Instrument Serif', Georgia, serif",       body: "'Inter', system-ui, sans-serif",    mono: "'JetBrains Mono', ui-monospace, monospace", weight: 400, tracking: '-0.015em', label: 'Instrument Serif + Inter' },
};

const HERO_VARIANTS = [
  { id: 'editorial',  label: 'Editorial' },
  { id: 'poster',     label: 'Poster' },
  { id: 'split',      label: 'Split + elevation' },
  { id: 'full-phone', label: 'Full phone stack' },
];

function App() {
  const [tweaks, setTweaks] = useState(DEFAULT_TWEAKS);
  const [editOpen, setEditOpen] = useState(false);
  const [editAvailable, setEditAvailable] = useState(false);

  // Apply type vars
  useEffect(() => {
    const p = TYPE_PAIRS[tweaks.typePair] || TYPE_PAIRS['grotesk-inter'];
    const r = document.documentElement.style;
    r.setProperty('--font-display', p.display);
    r.setProperty('--font-body', p.body);
    r.setProperty('--font-mono', p.mono);
    r.setProperty('--display-weight', p.weight);
    r.setProperty('--display-tracking', p.tracking);
  }, [tweaks.typePair]);

  // Edit-mode protocol
  useEffect(() => {
    function handler(e) {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setEditOpen(true);
      if (e.data.type === '__deactivate_edit_mode') setEditOpen(false);
    }
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    setEditAvailable(true);
    return () => window.removeEventListener('message', handler);
  }, []);

  function update(key, value) {
    const next = { ...tweaks, [key]: value };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: value } }, '*');
  }

  return (
    <>
      <Nav/>
      <Hero variant={tweaks.heroVariant}/>
      <hr className="rule"/>
      <Features/>
      <HowItWorks/>
      <BigQuote/>
      <Screens/>
      <DownloadCTA/>
      <Footer/>

      {editOpen && (
        <TweaksPanel tweaks={tweaks} onChange={update} onClose={() => setEditOpen(false)}/>
      )}
    </>
  );
}

function TweaksPanel({ tweaks, onChange, onClose }) {
  return (
    <div style={{
      position:'fixed', right: 24, bottom: 24, zIndex: 100,
      width: 320, background:'var(--cream)',
      border:'1px solid rgba(22,19,15,0.15)', borderRadius: 18,
      boxShadow: '0 30px 60px -20px rgba(0,0,0,0.3), 0 10px 20px -10px rgba(0,0,0,0.15)',
      fontFamily:'var(--font-body)', overflow:'hidden'
    }}>
      <div style={{
        display:'flex', alignItems:'center', justifyContent:'space-between',
        padding:'14px 18px', borderBottom:'1px solid rgba(22,19,15,0.1)',
        background:'var(--paper)'
      }}>
        <div style={{display:'flex', alignItems:'center', gap: 10}}>
          <div style={{width: 8, height: 8, borderRadius: 999, background:'var(--brand)'}}/>
          <span style={{fontFamily:'var(--font-display)', fontWeight: 600, fontSize: 15}}>Tweaks</span>
        </div>
        <button onClick={onClose} style={{background:'none', border:0, cursor:'pointer', color:'var(--ink-3)', fontSize: 14}}>close</button>
      </div>

      <div style={{padding: 18, display:'flex', flexDirection:'column', gap: 22}}>
        <TweakGroup label="Hero variant">
          {HERO_VARIANTS.map(v => (
            <SegBtn key={v.id} active={tweaks.heroVariant === v.id} onClick={() => onChange('heroVariant', v.id)}>
              {v.label}
            </SegBtn>
          ))}
        </TweakGroup>

        <TweakGroup label="Typography pair">
          {Object.entries(TYPE_PAIRS).map(([id, p]) => (
            <SegBtn key={id} active={tweaks.typePair === id} onClick={() => onChange('typePair', id)}>
              <span style={{display:'inline-block', fontFamily: p.display, fontSize: 14, fontWeight: p.weight}}>
                {p.label.split(' + ')[0]}
              </span>
              <span style={{opacity: 0.5, margin:'0 4px'}}>+</span>
              <span style={{display:'inline-block', fontFamily: p.body, fontSize: 13}}>
                {p.label.split(' + ')[1]}
              </span>
            </SegBtn>
          ))}
        </TweakGroup>
      </div>
    </div>
  );
}

function TweakGroup({ label, children }) {
  return (
    <div>
      <div className="mono" style={{marginBottom: 10}}>{label}</div>
      <div style={{display:'flex', flexDirection:'column', gap: 6}}>{children}</div>
    </div>
  );
}

function SegBtn({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      textAlign:'left', padding:'9px 12px',
      background: active ? 'var(--brand)' : 'transparent',
      color: active ? '#fff' : 'var(--ink)',
      border: '1px solid ' + (active ? 'var(--brand)' : 'rgba(22,19,15,0.15)'),
      borderRadius: 10, cursor:'pointer',
      fontFamily:'var(--font-body)', fontSize: 13,
      transition: 'background .15s ease'
    }}>{children}</button>
  );
}

const root = ReactDOM.createRoot(document.getElementById('app'));
root.render(<App/>);
