/* global React, ReactDOM, TOUKI_ShoreshGraph, TOUKI_DATA */

const { useState: useStateA, useEffect: useEffectA, useMemo: useMemoA } = React;

// Accents cyan / or / crimson
const PALETTES = {
  cyan:   { name: 'Cyan',    accent: '#6EF2FF', accent2: '#2AB8FF', warn: '#FFB347', bg: '#020812', ink: '#CFF7FF' },
  gold:   { name: 'Or',      accent: '#FFC857', accent2: '#FF6B3D', warn: '#6EF2FF', bg: '#100800', ink: '#FFE8B8' },
  crimson:{ name: 'Crimson', accent: '#FF4D5E', accent2: '#FFB347', warn: '#6EF2FF', bg: '#120205', ink: '#FFD5DA' }
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "cyan",
  "showScanlines": true
}/*EDITMODE-END*/;

// ============ Reusable HUD primitives ============
function Corner({ size = 14, thickness = 1.2, color }) {
  return (
    <svg width={size} height={size} style={{ display: 'block' }}>
      <path d={`M 0 ${size} L 0 0 L ${size} 0`} fill="none" stroke={color} strokeWidth={thickness} />
    </svg>
  );
}

function HudFrame({ children, color, label, style, padding = 20 }) {
  return (
    <div style={{
      position: 'relative',
      border: `1px solid ${color}30`,
      background: `linear-gradient(180deg, ${color}06, transparent)`,
      padding,
      ...style
    }}>
      <div style={{ position: 'absolute', top: -1, left: -1 }}><Corner color={color} /></div>
      <div style={{ position: 'absolute', top: -1, right: -1, transform: 'scaleX(-1)' }}><Corner color={color} /></div>
      <div style={{ position: 'absolute', bottom: -1, left: -1, transform: 'scaleY(-1)' }}><Corner color={color} /></div>
      <div style={{ position: 'absolute', bottom: -1, right: -1, transform: 'scale(-1,-1)' }}><Corner color={color} /></div>
      {label && (
        <div style={{
          position: 'absolute', top: -8, left: 16,
          background: '#020812', padding: '0 8px',
          fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
          letterSpacing: '.2em', color: color, textTransform: 'uppercase'
        }}>{label}</div>
      )}
      {children}
    </div>
  );
}

function Readout({ label, value, color, align = 'left' }) {
  return (
    <div style={{ textAlign: align, fontFamily: 'JetBrains Mono, monospace' }}>
      <div style={{ fontSize: 9, letterSpacing: '.25em', color: `${color}99`, textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontSize: 16, color: color, marginTop: 4, fontWeight: 500, letterSpacing: '.05em' }}>{value}</div>
    </div>
  );
}

function Ticker({ color, items }) {
  return (
    <div style={{
      display: 'flex', gap: 24, overflow: 'hidden',
      fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
      color: `${color}AA`, letterSpacing: '.15em', textTransform: 'uppercase',
      padding: '6px 0'
    }}>
      {items.map((it, i) => (
        <span key={i} style={{ whiteSpace: 'nowrap', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 6, height: 6, background: color, borderRadius: '50%' }} />
          {it}
        </span>
      ))}
    </div>
  );
}

// ============ TOP BAR ============
function ShoreshHeader({ p, now }) {
  const time = new Date(now).toLocaleTimeString('fr-FR', { hour12: false });
  const date = new Date(now).toISOString().slice(0, 10);
  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50,
      display: 'grid', gridTemplateColumns: '1fr auto 1fr',
      padding: '14px 28px', gap: 24,
      background: 'linear-gradient(180deg, rgba(2,8,18,.95), rgba(2,8,18,.5))',
      borderBottom: `1px solid ${p.accent}22`,
      backdropFilter: 'blur(10px)',
      fontFamily: 'JetBrains Mono, monospace'
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <img src="assets/logo-alef.png" alt="" style={{ width: 36, height: 36, filter: `drop-shadow(0 0 8px ${p.accent}88)` }} />
        <div>
          <div style={{ fontSize: 14, color: p.accent, letterSpacing: '.2em', fontWeight: 500 }}>T·O·U·K·I</div>
          <div style={{ fontSize: 9, color: `${p.accent}88`, letterSpacing: '.25em', marginTop: 2 }}>
            HEBREW LEXICAL GRAPH · v2.6.1
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 20, fontSize: 10, color: `${p.accent}BB`, letterSpacing: '.15em' }}>
        <span>⊙ SYS::ONLINE</span>
        <span style={{ width: 1, height: 14, background: `${p.accent}33` }} />
        <span>{date}</span>
        <span style={{ width: 1, height: 14, background: `${p.accent}33` }} />
        <span style={{ color: p.accent, fontWeight: 500 }}>{time}</span>
        <span style={{ width: 1, height: 14, background: `${p.accent}33` }} />
        <span>STATUS::NOMINAL</span>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 12, justifyContent: 'flex-end' }}>
        <div style={{ fontSize: 9, color: `${p.accent}AA`, letterSpacing: '.2em' }}>USER::TOUKI</div>
        <button style={{
          background: 'transparent', border: `1px solid ${p.accent}66`,
          color: p.accent, padding: '8px 16px', fontFamily: 'inherit', fontSize: 10,
          letterSpacing: '.2em', cursor: 'pointer', clipPath: 'polygon(8px 0, 100% 0, 100% calc(100% - 8px), calc(100% - 8px) 100%, 0 100%, 0 8px)'
        }}>⟐ ENGAGE</button>
      </div>
    </header>
  );
}

// ============ HERO ============
function ShoreshHero({ p, onSelect, selectedId }) {
  const [size, setSize] = useStateA({ w: 800, h: 600 });
  useEffectA(() => {
    const update = () => {
      const el = document.getElementById('j-graph-slot');
      if (el) { const r = el.getBoundingClientRect(); setSize({ w: Math.floor(r.width), h: Math.floor(r.height) }); }
    };
    update();
    window.addEventListener('resize', update);
    return () => window.removeEventListener('resize', update);
  }, []);

  return (
    <section style={{ padding: '76px 20px 20px', maxWidth: 1920, margin: '0 auto' }}>
      {/* Top title bar */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 24, alignItems: 'center',
        marginBottom: 14, fontFamily: 'JetBrains Mono, monospace'
      }}>
        <div style={{ fontSize: 10, color: `${p.accent}99`, letterSpacing: '.3em' }}>
          ▸ PROJECT::אוּלְפָּן · INITIATIVE 001
        </div>
        <div style={{ height: 1, background: `linear-gradient(90deg, ${p.accent}66, transparent)` }} />
        <div style={{ fontSize: 10, color: `${p.accent}99`, letterSpacing: '.3em' }}>
          ◂ CLEARANCE :: ALEF
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '280px 1fr 280px', gap: 16, height: 'calc(100vh - 140px)', minHeight: 820 }}>
        {/* LEFT — mission brief */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, overflow: 'auto' }}>
          <HudFrame color={p.accent} label="MISSION BRIEF">
            <div style={{
              fontFamily: 'Instrument Serif, serif', fontSize: 44, lineHeight: 0.96,
              color: p.ink, letterSpacing: '-0.01em', fontWeight: 400
            }}>
              Cartographier<br />
              <em style={{ color: p.accent, fontStyle: 'italic' }}>la langue vivante.</em>
            </div>
            <div style={{
              marginTop: 16, fontFamily: 'JetBrains Mono, monospace',
              fontSize: 11, color: `${p.ink}AA`, lineHeight: 1.7, letterSpacing: '.02em'
            }}>
              Chaque mot hébreu est un nœud.<br />
              Les racines communes forment les liens.<br />
              Les champs sémantiques dessinent le relief.<br />
              <span style={{ color: p.accent }}>// Touki rend la structure visible.</span>
            </div>
          </HudFrame>

          <HudFrame color={p.accent} label="VITAL SIGNS">
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Readout label="NODES" value="3,184" color={p.accent} />
              <Readout label="ROOTS" value="812" color={p.accent} />
              <Readout label="FIELDS" value="42" color={p.accent} />
              <Readout label="EDGES" value="11,207" color={p.accent} />
            </div>
            <div style={{ marginTop: 14, height: 40, position: 'relative' }}>
              <svg width="100%" height="40" viewBox="0 0 240 40" preserveAspectRatio="none">
                <polyline
                  points={Array.from({ length: 30 }).map((_, i) =>
                    `${i * 8},${20 + Math.sin(i * 0.7) * 10 + Math.sin(i * 2.1) * 4}`
                  ).join(' ')}
                  fill="none" stroke={p.accent} strokeWidth="1"
                />
                <line x1="0" y1="20" x2="240" y2="20" stroke={`${p.accent}22`} strokeDasharray="2 4" />
              </svg>
              <div style={{
                position: 'absolute', top: 0, right: 0,
                fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
                color: `${p.accent}AA`, letterSpacing: '.15em'
              }}>NODE_ACTIVITY</div>
            </div>
          </HudFrame>

          <HudFrame color={p.accent} label="CONTROLS">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: `${p.ink}AA` }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span>◉ CLICK</span><span style={{ color: p.accent }}>→ isoler le nœud</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span>◉ DRAG</span><span style={{ color: p.accent }}>→ déplacer</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span>◉ SCROLL</span><span style={{ color: p.accent }}>→ zoom</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span>◉ PAN</span><span style={{ color: p.accent }}>→ fond</span>
              </div>
            </div>
          </HudFrame>
        </div>

        {/* CENTER — Graph */}
        <HudFrame color={p.accent} label="LEXICAL GRAPH · LIVE" padding={0} style={{ overflow: 'hidden', height: '100%' }}>
          <div id="j-graph-slot" style={{ width: '100%', height: '100%', minHeight: 820, position: 'relative' }}>
            <TOUKI_ShoreshGraph
              width={size.w} height={size.h}
              accent={p.accent}
              onSelect={onSelect} selectedId={selectedId}
            />
            {/* Top inset labels */}
            <div style={{
              position: 'absolute', top: 14, left: 18,
              fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
              color: `${p.accent}BB`, letterSpacing: '.25em', pointerEvents: 'none'
            }}>
              FIG.01 · גרף השורשים
            </div>
            <div style={{
              position: 'absolute', top: 14, right: 18,
              fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
              color: `${p.accent}BB`, letterSpacing: '.25em', pointerEvents: 'none',
              display: 'flex', alignItems: 'center', gap: 8
            }}>
              <span style={{ width: 6, height: 6, background: p.accent, borderRadius: '50%', boxShadow: `0 0 6px ${p.accent}` }} />
              REC · LIVE
            </div>
          </div>
        </HudFrame>

        {/* RIGHT — selection + legend */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, overflow: 'auto' }}>
          <HudFrame color={p.accent} label="SELECTION">
            <SelectionPanel selectedId={selectedId} p={p} />
          </HudFrame>
          <HudFrame color={p.accent} label="LEGEND">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: `${p.ink}CC` }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <svg width="30" height="10"><line x1="0" y1="5" x2="30" y2="5" stroke={p.accent} strokeWidth="1.2" /></svg>
                SHORESH · même racine
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <svg width="30" height="10"><line x1="0" y1="5" x2="30" y2="5" stroke={p.accent} strokeWidth="1" strokeDasharray="3 4" /></svg>
                SADE · même champ
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 4 }}>
                <svg width="18" height="18"><circle cx="9" cy="9" r="6" fill={p.accent} opacity=".2" stroke={p.accent} strokeWidth="1.2" /></svg>
                RACINE (shoresh)
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <svg width="18" height="18"><circle cx="9" cy="9" r="5" fill="#061820" stroke={p.accent} strokeWidth="1" /></svg>
                MOT (milah)
              </div>
            </div>
          </HudFrame>

          <HudFrame color={p.accent} label="TELEMETRY">
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, color: `${p.accent}99`, lineHeight: 2, letterSpacing: '.08em' }}>
              <div>{`> init graph.shoresh(כ·ת·ב)`}</div>
              <div>{`> resolved 6 derivatives`}</div>
              <div>{`> bridging field :: communication`}</div>
              <div>{`> stream ok · latency 12ms`}</div>
              <div style={{ color: p.accent }}>{`> awaiting operator input_`}</div>
            </div>
          </HudFrame>
        </div>
      </div>

      {/* Bottom ticker */}
      <div style={{
        marginTop: 16,
        border: `1px solid ${p.accent}22`,
        padding: '4px 14px',
        background: `${p.accent}04`
      }}>
        <Ticker color={p.accent} items={[
          'SHORESH · כ-ת-ב · WRITE',
          'SHORESH · ל-מ-ד · LEARN',
          'SHORESH · ש-ל-מ · PEACE',
          'SHORESH · א-ה-ב · LOVE',
          'SHORESH · ד-ב-ר · SPEAK',
          'BINYAN CATALOG :: 7/7 LOADED',
          'DICT REV · 2026.04',
          'OPERATOR :: TOUKI'
        ]} />
      </div>
    </section>
  );
}

// ============ Selection panel ============
function SelectionPanel({ selectedId, p }) {
  if (!selectedId) {
    return (
      <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: `${p.ink}77`, letterSpacing: '.1em', lineHeight: 1.8 }}>
        <div style={{ color: `${p.accent}`, marginBottom: 10 }}>// NO TARGET</div>
        <div>Sélectionne un nœud dans le graphe pour ouvrir sa fiche.</div>
        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 6 }}>
          {TOUKI_DATA.roots.map(r => (
            <div key={r.id} style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              padding: '6px 8px', border: `1px solid ${p.accent}18`
            }}>
              <span style={{ fontFamily: 'Frank Ruhl Libre, serif', fontSize: 15, color: p.accent, direction: 'rtl' }}>{r.letters}</span>
              <span style={{ fontSize: 9, color: `${p.ink}99`, letterSpacing: '.1em' }}>{r.meaning.toUpperCase()}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  const [kind, id] = selectedId.split(':');
  let root = null, word = null;
  if (kind === 'root') root = TOUKI_DATA.roots.find(r => r.id === id);
  else for (const r of TOUKI_DATA.roots) { const w = r.words.find(w => w.id === id); if (w) { word = w; root = r; break; } }

  return (
    <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: `${p.ink}CC` }}>
      <div style={{ fontSize: 9, color: `${p.accent}99`, letterSpacing: '.2em', marginBottom: 6 }}>
        {word ? `TARGET::WORD` : 'TARGET::ROOT'}
      </div>
      <div style={{
        fontFamily: 'Frank Ruhl Libre, serif', fontSize: 54,
        color: p.accent, direction: 'rtl', lineHeight: 1,
        textShadow: `0 0 20px ${p.accent}66`
      }}>{word ? word.he : root.letters}</div>

      <div style={{ marginTop: 10, color: p.ink, fontFamily: 'Instrument Serif, serif', fontSize: 22, fontStyle: 'italic' }}>
        « {word ? word.fr : root.meaning} »
      </div>
      {word && (
        <div style={{ marginTop: 4, fontSize: 11, color: `${p.accent}BB`, letterSpacing: '.1em' }}>
          /{word.translit}/ · {word.form}
        </div>
      )}

      <div style={{ height: 1, background: `${p.accent}22`, margin: '16px 0' }} />

      <div style={{ fontSize: 9, letterSpacing: '.2em', color: `${p.accent}99`, marginBottom: 8 }}>
        SHORESH ▸ {root.letters_plain} · {root.words.length} DERIVATIVES
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        {root.words.map(w => (
          <div key={w.id} style={{
            display: 'grid', gridTemplateColumns: '1fr auto',
            gap: 10, padding: '6px 8px',
            background: word && word.id === w.id ? `${p.accent}18` : 'transparent',
            border: `1px solid ${word && word.id === w.id ? p.accent + '66' : p.accent + '10'}`
          }}>
            <span style={{ fontFamily: 'Frank Ruhl Libre, serif', fontSize: 16, color: p.ink, direction: 'rtl', textAlign: 'right' }}>{w.he}</span>
            <span style={{ fontSize: 10, color: `${p.ink}99` }}>{w.fr}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============ HOW IT WORKS (HUD diagram) ============
function ShoreshHow({ p }) {
  const root = TOUKI_DATA.roots.find(r => r.id === 'ktv');
  return (
    <section style={{ padding: '80px 28px', maxWidth: 1600, margin: '0 auto' }}>
      <div style={{
        display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 24, alignItems: 'center',
        marginBottom: 30, fontFamily: 'JetBrains Mono, monospace'
      }}>
        <div style={{ fontSize: 10, color: `${p.accent}99`, letterSpacing: '.3em' }}>▸ SECTION 02</div>
        <div style={{ height: 1, background: `linear-gradient(90deg, ${p.accent}66, transparent)` }} />
        <div style={{ fontSize: 10, color: `${p.accent}99`, letterSpacing: '.3em' }}>◂ PROTOCOL // SHORESH</div>
      </div>

      <div style={{
        fontFamily: 'Instrument Serif, serif',
        fontSize: 'clamp(42px, 5.5vw, 72px)', lineHeight: 1, letterSpacing: '-0.02em',
        color: p.ink, maxWidth: 900, marginBottom: 50, fontWeight: 400
      }}>
        En hébreu, <em style={{ color: p.accent, fontStyle: 'italic' }}>trois lettres</em> portent tout un monde.
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.3fr', gap: 24 }}>
        <HudFrame color={p.accent} label="ANATOMY · SHORESH">
          <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: `${p.accent}AA`, letterSpacing: '.2em' }}>
            SPECIMEN_001 · כ-ת-ב
          </div>
          <div style={{
            marginTop: 20,
            fontFamily: 'Frank Ruhl Libre, serif',
            fontSize: 180, lineHeight: 1, color: p.accent,
            direction: 'rtl', textAlign: 'center',
            textShadow: `0 0 40px ${p.accent}66, 0 0 12px ${p.accent}`,
            fontWeight: 700
          }}>
            {root.letters}
          </div>

          {/* labeled letters */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginTop: 20 }}>
            {[
              { he: 'כ', n: 'KAF',  idx: '01' },
              { he: 'ת', n: 'TAV',  idx: '02' },
              { he: 'ב', n: 'BET',  idx: '03' }
            ].map(l => (
              <div key={l.idx} style={{
                border: `1px solid ${p.accent}30`, padding: 12, textAlign: 'center',
                background: `${p.accent}04`
              }}>
                <div style={{ fontFamily: 'Frank Ruhl Libre, serif', fontSize: 30, color: p.accent }}>{l.he}</div>
                <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, color: `${p.ink}99`, letterSpacing: '.2em', marginTop: 6 }}>
                  {l.idx} · {l.n}
                </div>
              </div>
            ))}
          </div>

          <div style={{
            marginTop: 20, fontFamily: 'Instrument Serif, serif',
            fontSize: 22, fontStyle: 'italic', color: p.ink, textAlign: 'center'
          }}>
            « écrire · trace · inscription »
          </div>
        </HudFrame>

        <HudFrame color={p.accent} label="DERIVATIVES · LIVE DECODE">
          <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: `${p.accent}AA`, letterSpacing: '.2em', marginBottom: 14 }}>
            {root.words.length} WORDS RESOLVED FROM ROOT
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {root.words.map((w, i) => (
              <div key={w.id} style={{
                display: 'grid',
                gridTemplateColumns: '50px 120px 1fr 120px',
                gap: 14, alignItems: 'center',
                padding: '14px 16px',
                border: `1px solid ${p.accent}20`,
                background: i % 2 === 0 ? `${p.accent}05` : 'transparent'
              }}>
                <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: `${p.accent}88`, letterSpacing: '.15em' }}>
                  {String(i + 1).padStart(2, '0')}
                </span>
                <span style={{
                  fontFamily: 'Frank Ruhl Libre, serif', fontSize: 28,
                  color: p.accent, direction: 'rtl', textAlign: 'right',
                  textShadow: `0 0 10px ${p.accent}55`
                }}>{w.he}</span>
                <span style={{ fontFamily: 'Instrument Serif, serif', fontSize: 18, fontStyle: 'italic', color: p.ink }}>
                  {w.fr}
                </span>
                <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: `${p.ink}77`, letterSpacing: '.1em', textAlign: 'right' }}>
                  {w.form.toUpperCase()}
                </span>
              </div>
            ))}
          </div>
        </HudFrame>
      </div>

      {/* 3 step cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20, marginTop: 40 }}>
        {[
          { n: '01', t: 'IDENTIFY', fr: 'Tu cliques un mot.', d: 'Touki isole le nœud ciblé dans le réseau. Tout le reste passe en second plan.' },
          { n: '02', t: 'RESOLVE', fr: 'Sa racine s\'allume.', d: 'Le shoresh à trois lettres est extrait. La famille entière — verbes, noms, formes — s\'illumine.' },
          { n: '03', t: 'BRIDGE', fr: 'Les voisins apparaissent.', d: 'Les liens sémantiques (pointillés) relient des racines différentes qui partagent un champ.' }
        ].map(s => (
          <HudFrame key={s.n} color={p.accent} label={`STEP ${s.n} · ${s.t}`}>
            <div style={{
              fontFamily: 'Instrument Serif, serif', fontSize: 30, color: p.ink,
              letterSpacing: '-0.01em', lineHeight: 1.05, fontWeight: 400
            }}>{s.fr}</div>
            <div style={{
              marginTop: 14, fontFamily: 'JetBrains Mono, monospace',
              fontSize: 11, color: `${p.ink}99`, lineHeight: 1.7
            }}>{s.d}</div>
          </HudFrame>
        ))}
      </div>
    </section>
  );
}

// ============ CTA ============
function ShoreshCTA({ p }) {
  return (
    <section style={{ padding: '60px 28px 100px', maxWidth: 1600, margin: '0 auto' }}>
      <HudFrame color={p.accent} label="DEPLOY">
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 40, alignItems: 'center', padding: '30px 10px' }}>
          <div>
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: `${p.accent}AA`, letterSpacing: '.3em', marginBottom: 14 }}>
              ▸ READY_TO_LAUNCH
            </div>
            <div style={{
              fontFamily: 'Instrument Serif, serif',
              fontSize: 'clamp(36px, 4.5vw, 60px)', lineHeight: 1.02,
              color: p.ink, letterSpacing: '-0.02em', fontWeight: 400
            }}>
              L'hébreu ne se mémorise pas.<br />
              <em style={{ color: p.accent, fontStyle: 'italic' }}>Il se décode.</em>
            </div>
            <div style={{
              marginTop: 20, fontFamily: 'JetBrains Mono, monospace',
              fontSize: 12, color: `${p.ink}AA`, lineHeight: 1.7, maxWidth: 520
            }}>
              Rejoins les opérateurs qui tissent leur vocabulaire au lieu de l'empiler.
              <span style={{ color: p.accent }}> // Signal ouvert · 24/7.</span>
            </div>
            <div style={{ marginTop: 30, display: 'flex', gap: 14 }}>
              <button style={{
                background: p.accent, color: '#020812', border: 'none',
                padding: '14px 28px', fontFamily: 'JetBrains Mono, monospace',
                fontSize: 12, letterSpacing: '.2em', fontWeight: 600, cursor: 'pointer',
                clipPath: 'polygon(10px 0, 100% 0, 100% calc(100% - 10px), calc(100% - 10px) 100%, 0 100%, 0 10px)',
                boxShadow: `0 0 20px ${p.accent}66`
              }}>⟐ INITIATE SESSION</button>
              <button style={{
                background: 'transparent', color: p.accent, border: `1px solid ${p.accent}66`,
                padding: '14px 28px', fontFamily: 'JetBrains Mono, monospace',
                fontSize: 12, letterSpacing: '.2em', cursor: 'pointer'
              }}>◉ WATCH DEMO</button>
            </div>
          </div>
          <div style={{ position: 'relative', height: 260 }}>
            <img src="assets/logo-alef.png" alt="" style={{
              position: 'absolute', inset: 0, margin: 'auto',
              width: 220, height: 220,
              filter: `drop-shadow(0 0 30px ${p.accent}99) drop-shadow(0 0 60px ${p.accent}55)`
            }} />
            {/* rotating rings */}
            <svg width="100%" height="100%" style={{ position: 'absolute', inset: 0 }} viewBox="0 0 400 260">
              <g transform="translate(200 130)">
                <circle r="120" fill="none" stroke={p.accent} strokeWidth="0.6" opacity=".3" strokeDasharray="2 8" />
                <circle r="140" fill="none" stroke={p.accent} strokeWidth="0.4" opacity=".2" />
                {Array.from({ length: 36 }).map((_, i) => {
                  const a = (i / 36) * Math.PI * 2;
                  return (
                    <line key={i}
                      x1={Math.cos(a) * 125} y1={Math.sin(a) * 125}
                      x2={Math.cos(a) * (i % 3 === 0 ? 135 : 130)} y2={Math.sin(a) * (i % 3 === 0 ? 135 : 130)}
                      stroke={p.accent} strokeWidth="0.6" opacity={i % 3 === 0 ? .6 : .25}
                    />
                  );
                })}
              </g>
            </svg>
          </div>
        </div>
      </HudFrame>

      <div style={{
        marginTop: 30,
        display: 'flex', justifyContent: 'space-between',
        fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
        color: `${p.accent}88`, letterSpacing: '.2em'
      }}>
        <span>TOUKI · HEBREW_LEXICAL_GRAPH · ©2026</span>
        <span>SIGNAL :: STRONG · 127.0.0.1</span>
        <span>VERIFY :: OK ⟐</span>
      </div>
    </section>
  );
}

// ============ APP ============
function App() {
  const [tweaks, setTweaks] = useStateA(TWEAK_DEFAULTS);
  const [tweaksVisible, setTweaksVisible] = useStateA(false);
  const [selectedId, setSelectedId] = useStateA(null);
  const [now, setNow] = useStateA(Date.now());

  useEffectA(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);

  const p = PALETTES[tweaks.palette] || PALETTES.cyan;

  useEffectA(() => {
    const handler = (e) => {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setTweaksVisible(true);
      if (e.data.type === '__deactivate_edit_mode') setTweaksVisible(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

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

  return (
    <div style={{
      background: p.bg, minHeight: '100vh', color: p.ink,
      position: 'relative', overflow: 'hidden'
    }}>
      {/* Ambient grid + noise */}
      <div style={{
        position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 0,
        backgroundImage: `
          linear-gradient(${p.accent}08 1px, transparent 1px),
          linear-gradient(90deg, ${p.accent}08 1px, transparent 1px)
        `,
        backgroundSize: '48px 48px'
      }} />
      {/* vignette */}
      <div style={{
        position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 0,
        background: `radial-gradient(ellipse at center, transparent 30%, ${p.bg} 90%)`
      }} />
      {/* scanlines */}
      {tweaks.showScanlines && (
        <div style={{
          position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 2,
          backgroundImage: `repeating-linear-gradient(0deg, transparent 0, transparent 2px, ${p.accent}04 2px, ${p.accent}04 3px)`,
          mixBlendMode: 'screen'
        }} />
      )}
      {/* animated beam */}
      <div className="j-beam" style={{
        position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 1,
        background: `linear-gradient(180deg, transparent 0%, ${p.accent}08 50%, transparent 100%)`,
        height: '20vh'
      }} />

      <div style={{ position: 'relative', zIndex: 3 }}>
        <ShoreshHeader p={p} now={now} />
        <ShoreshHero p={p} onSelect={setSelectedId} selectedId={selectedId} />
        <ShoreshHow p={p} />
        <ShoreshCTA p={p} />
      </div>

      {tweaksVisible && (
        <div style={{
          position: 'fixed', bottom: 24, left: 24, zIndex: 100,
          background: '#020812EE', border: `1px solid ${p.accent}55`,
          padding: 20, width: 260,
          fontFamily: 'JetBrains Mono, monospace', color: p.ink,
          boxShadow: `0 0 40px ${p.accent}33`,
          clipPath: 'polygon(14px 0, 100% 0, 100% calc(100% - 14px), calc(100% - 14px) 100%, 0 100%, 0 14px)'
        }}>
          <div style={{ fontSize: 10, color: p.accent, letterSpacing: '.3em', marginBottom: 14 }}>⟐ TWEAKS</div>
          <div style={{ fontSize: 9, color: `${p.ink}99`, letterSpacing: '.2em', marginBottom: 8 }}>PALETTE</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 14 }}>
            {Object.entries(PALETTES).map(([k, pal]) => (
              <button key={k} onClick={() => updateTweak('palette', k)} style={{
                background: 'transparent', color: pal.accent,
                border: `1px solid ${tweaks.palette === k ? pal.accent : pal.accent + '33'}`,
                padding: '8px 12px', fontFamily: 'inherit', fontSize: 10,
                letterSpacing: '.2em', textAlign: 'left', cursor: 'pointer',
                display: 'flex', justifyContent: 'space-between'
              }}>
                <span>{pal.name.toUpperCase()}</span>
                <span style={{ width: 12, height: 12, background: pal.accent, boxShadow: `0 0 8px ${pal.accent}` }} />
              </button>
            ))}
          </div>
          <button onClick={() => updateTweak('showScanlines', !tweaks.showScanlines)} style={{
            width: '100%', background: 'transparent', color: p.accent,
            border: `1px solid ${p.accent}44`, padding: '8px 12px',
            fontFamily: 'inherit', fontSize: 10, letterSpacing: '.2em', cursor: 'pointer',
            display: 'flex', justifyContent: 'space-between'
          }}>
            <span>SCANLINES</span>
            <span>{tweaks.showScanlines ? 'ON' : 'OFF'}</span>
          </button>
        </div>
      )}

      <style>{`
        @keyframes jbeam { 0% { transform: translateY(-100%); } 100% { transform: translateY(600%); } }
        .j-beam { animation: jbeam 8s linear infinite; }
        @keyframes jflicker { 0%, 100% { opacity: 1; } 97% { opacity: 1; } 98% { opacity: .8; } 99% { opacity: 1; } }
        ::selection { background: ${p.accent}; color: ${p.bg}; }
      `}</style>
    </div>
  );
}

window.TOUKI_ShoreshApp = App;
