// Sections D: Self-Correction strip, Who Is Fongos, Moments (replacing UseCases).

// ─── SELF-CORRECTION STRIP ────────────────────────────────────────
// Plays once when scrolled into view. Small, quiet, no controls.
function SelfCorrectionStrip() {
  const [shown, setShown] = React.useState(0); // how many lines printed
  const [charCount, setCharCount] = React.useState(0); // typed chars on current line
  const [started, setStarted] = React.useState(false);
  const hostRef = React.useRef(null);

  const lines = [
    { k: 'plan', t: 'plan generated — 7 steps' },
    { k: 'warn', t: '⚠ 5 of 7 tools don\u2019t exist. 71% hallucinated.' },
    { k: 'fix',  t: 'regenerating with grounded tool list.' },
    { k: 'ok',   t: '✓ plan v2 valid. dispatching.' },
  ];

  // IntersectionObserver trigger
  React.useEffect(() => {
    if (!hostRef.current) return;
    const io = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) { setStarted(true); io.disconnect(); }
    }, { threshold: 0.4 });
    io.observe(hostRef.current);
    return () => io.disconnect();
  }, []);

  // Step through lines — reveal each fully then pause, then next
  React.useEffect(() => {
    if (!started) return;
    if (shown >= lines.length) return;
    const current = lines[shown].t;
    if (charCount < current.length) {
      const id = setTimeout(() => setCharCount(c => c + 1), 22);
      return () => clearTimeout(id);
    }
    // line complete — pause, then advance
    const pause = lines[shown].k === 'warn' ? 900 : 450;
    const id = setTimeout(() => { setShown(s => s + 1); setCharCount(0); }, pause);
    return () => clearTimeout(id);
  }, [started, shown, charCount]);

  const colorFor = (k) => ({
    plan: FONGOS.inkDim,
    warn: '#fbbf24',
    fix:  FONGOS.purpleSoft,
    ok:   '#4ade80',
  }[k] || FONGOS.inkDim);

  return (
    <section ref={hostRef} style={{
      padding: '48px 40px 56px', borderBottom: `1px solid ${FONGOS.line}`,
      background: FONGOS.bg, position: 'relative',
    }}>
      <div style={{ maxWidth: 860, margin: '0 auto' }}>
        <div style={{
          background: '#05060a', border: `1px solid ${FONGOS.line}`,
          padding: '22px 26px', fontFamily: FONGOS.mono, fontSize: 13,
          lineHeight: 1.9, minHeight: 150,
          boxShadow: `0 20px 60px -20px rgba(0,0,0,0.5)`,
        }}>
          {lines.map((ln, i) => {
            if (i > shown) return null;
            const text = i === shown ? ln.t.slice(0, charCount) : ln.t;
            const done = i < shown;
            return (
              <div key={i} style={{ color: colorFor(ln.k), opacity: done ? 1 : 0.95 }}>
                <span style={{ color: FONGOS.inkFaint, marginRight: 10 }}>›</span>
                {text}
                {i === shown && charCount < ln.t.length && (
                  <span style={{ display:'inline-block', width: 7, height: 13, background: FONGOS.ink, verticalAlign:'middle', marginLeft: 2, animation: 'fongosBlink 1s step-end infinite' }}/>
                )}
              </div>
            );
          })}
        </div>
        <p style={{
          textAlign: 'center', marginTop: 20,
          fontSize: 13, color: FONGOS.inkDim, lineHeight: 1.6, maxWidth: 620,
          margin: '20px auto 0',
        }}>
          This is who Fongos is when nobody's watching — catching himself before he breaks anything.
        </p>
      </div>
    </section>
  );
}

// ─── WHO IS FONGOS ───────────────────────────────────────────────
function WhoIsFongos() {
  const quotes = [
    {
      text: '"The mount plate is bending-governed. Safety factor 1.38. I can shave 18% mass with a triangular lightening pocket without dropping under 1.2. Want me to try?"',
      caption: 'NEMA 23 session · 04.18',
      tag: 'precise · proactive',
    },
    {
      text: '"71% of these tools don\u2019t exist. I\u2019m regenerating the plan before anything runs."',
      caption: 'self-correction · 04.18',
      tag: 'honest about himself',
    },
    {
      text: '"You asked about column H last Tuesday. Here\u2019s what changed since."',
      caption: 'spreadsheet audit · 04.15',
      tag: 'memory',
    },
  ];

  const principles = [
    'If I\u2019m less than 70% confident, I stop and say so.',
    'Every mistake becomes a rule so I don\u2019t make it twice.',
    'The simplest solution that works is the correct one.',
    'I don\u2019t guess. If I don\u2019t know, I ask.',
  ];

  return (
    <section id="who" style={{
      padding: '140px 40px', borderBottom: `1px solid ${FONGOS.line}`,
      position: 'relative',
      background: `radial-gradient(ellipse at 30% 20%, ${FONGOS.purple}0a 0%, transparent 55%)`,
    }}>
      <div style={{ maxWidth: 1180, margin: '0 auto' }}>
        <SectionLabel num="02" name="Who is Fongos"/>

        {/* 4a. Name origin + mushroom */}
        <div style={{
          display: 'grid', gridTemplateColumns: '140px 1fr', gap: 32,
          alignItems: 'center', marginBottom: 96,
          maxWidth: 820,
        }} className="fg-who-origin">
          <svg width="140" height="140" style={{ animation: 'fongosMushroomFloat 5s ease-in-out infinite' }}>
            <use href="#mushroom-logo"/>
          </svg>
          <div>
            <Headline size={32} style={{ marginBottom: 14, fontWeight: 300, color: FONGOS.ink }}>
              Fongos — from the Greek root for fungus.
            </Headline>
            <p style={{ fontSize: 16, color: FONGOS.inkDim, lineHeight: 1.6, margin: 0, maxWidth: 540 }}>
              Mushrooms are networks that grow underground. What you see on screen is the smallest part.
            </p>
          </div>
        </div>

        {/* 4b. Voice cards */}
        <div style={{ marginBottom: 120 }}>
          <Headline size={44} style={{ marginBottom: 36 }}>His voice.</Headline>
          <div className="fg-who-voices" style={{
            display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18,
          }}>
            {quotes.map((q, i) => (
              <div key={i} style={{
                background: FONGOS.surface, border: `1px solid ${FONGOS.line}`,
                padding: '26px 24px 22px', display: 'flex', flexDirection: 'column',
                minHeight: 240,
              }}>
                <div style={{
                  fontFamily: FONGOS.mono, fontSize: 10, letterSpacing: '0.22em',
                  color: FONGOS.purpleSoft, textTransform: 'uppercase', marginBottom: 18,
                }}>{q.tag}</div>
                <p style={{
                  fontFamily: FONGOS.mono, fontSize: 14, lineHeight: 1.6,
                  color: FONGOS.ink, margin: 0, flexGrow: 1, letterSpacing: '-0.005em',
                }}>{q.text}</p>
                <div style={{
                  marginTop: 22, paddingTop: 14, borderTop: `1px solid ${FONGOS.line}`,
                  fontFamily: FONGOS.mono, fontSize: 10, letterSpacing: '0.18em',
                  color: FONGOS.inkFaint, textTransform: 'uppercase',
                }}>{q.caption}</div>
              </div>
            ))}
          </div>
        </div>

        {/* 4c. Principles */}
        <div>
          <Headline size={44} style={{ marginBottom: 48 }}>How he thinks.</Headline>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 28, maxWidth: 980 }}>
            {principles.map((p, i) => (
              <div key={i} style={{
                display: 'grid', gridTemplateColumns: '64px 1fr', gap: 24,
                alignItems: 'baseline', paddingBottom: 28,
                borderBottom: i < principles.length - 1 ? `1px solid ${FONGOS.line}` : 'none',
              }} className="fg-principle">
                <span style={{
                  fontFamily: FONGOS.mono, fontSize: 13, letterSpacing: '0.18em',
                  color: FONGOS.purpleSoft,
                }}>0{i + 1}</span>
                <span style={{
                  fontSize: 'clamp(28px, 4.2vw, 44px)', fontWeight: 200,
                  lineHeight: 1.25, letterSpacing: '-0.02em', color: FONGOS.ink,
                  textWrap: 'balance',
                }}>{p}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ─── MOMENTS (replacing UseCases) ─────────────────────────────────
function Moments() {
  const moments = [
    {
      tag: 'self-correction',
      when: '04-18 · 2m',
      t: 'The day he caught his own hallucination mid-flight.',
      p: 'Seven steps into a plan, he flagged that five of the tools didn\u2019t exist. Stopped. Regenerated. Finished in two minutes.',
      visual: 'selfcorrect',
    },
    {
      tag: 'long memory',
      when: '04-15 · 4.2s',
      t: 'The Tuesday he remembered a question I\u2019d forgotten I asked.',
      p: 'Three weeks later, when I opened the same spreadsheet, he had the answer ready.',
      visual: 'memory',
    },
    {
      tag: 'self-repair',
      when: '04-07 · 11m',
      t: 'He found the bug in his own evaluation system.',
      p: 'Proposed the patch. Waited for my approval before touching anything. Next session, the bug was gone.',
      visual: 'commit',
    },
    {
      tag: 'unprompted initiative',
      when: '04-02 · 2m',
      t: 'The newsletter he wrote without being asked.',
      p: '3.6KB of clean copy, stitched from three conversations I\u2019d forgotten.',
      visual: 'text',
    },
    {
      tag: 'he redesigns himself',
      when: '04-18 · 47m',
      t: 'He watched his own dashboard crash on mobile.',
      p: 'Proposed a lighter version. Shipped the replacement that same night.',
      visual: 'design',
    },
    {
      tag: 'follow-through',
      when: '04-18 · continued',
      t: 'After finishing the motor mount, he asked — "want me to try saving 18% mass?"',
      p: 'Nobody asked him to.',
      visual: 'cad',
    },
  ];

  const Thumb = ({ kind }) => {
    const common = { width: '100%', height: 130, background: FONGOS.bg2, borderBottom: `1px solid ${FONGOS.line}`, position: 'relative', overflow: 'hidden' };

    if (kind === 'selfcorrect') return (
      <div style={{...common, padding: 14, fontFamily: FONGOS.mono, fontSize: 10, lineHeight: 1.7 }}>
        <div style={{ color: FONGOS.inkDim }}>› plan v1 · 7 steps</div>
        <div style={{ color: '#fbbf24' }}>⚠ 5/7 tools hallucinated</div>
        <div style={{ color: FONGOS.purpleSoft }}>› regenerating...</div>
        <div style={{ color: '#4ade80' }}>✓ plan v2 valid</div>
      </div>
    );
    if (kind === 'memory') return (
      <div style={common}>
        <svg viewBox="0 0 200 100" style={{ width: '100%', height: '100%' }}>
          {[18, 14, 10, 6].map((r, i) => (
            <circle key={i} cx="100" cy="50" r={r * 4} fill="none" stroke={FONGOS.purple} strokeOpacity={0.2 + i * 0.1} strokeWidth="0.8"/>
          ))}
          <circle cx="100" cy="50" r="5" fill={FONGOS.purpleSoft}/>
          <text x="100" y="86" textAnchor="middle" fontFamily={FONGOS.mono} fontSize="8" fill={FONGOS.inkFaint} letterSpacing="1.5">TUE 04-15 · COLUMN H</text>
        </svg>
      </div>
    );
    if (kind === 'commit') return (
      <div style={{...common, padding: 14, fontFamily: FONGOS.mono, fontSize: 10, color: FONGOS.inkDim, lineHeight: 1.7 }}>
        <div style={{ color: '#f87171' }}>- score = correct / total</div>
        <div style={{ color: '#4ade80' }}>+ score = correct / max(total, 1)</div>
        <div style={{ color: FONGOS.inkFaint, marginTop: 6 }}>@@ eval.py @@</div>
        <div style={{ color: FONGOS.purpleSoft }}>awaiting review ·</div>
      </div>
    );
    if (kind === 'text') return (
      <div style={{...common, padding: 16 }}>
        {[100, 96, 88, 72, 100, 92, 80].map((w, i) => (
          <div key={i} style={{ height: 3.5, width: `${w}%`, background: i < 2 ? FONGOS.ink : FONGOS.inkGhost, marginBottom: 6 }}/>
        ))}
      </div>
    );
    if (kind === 'design') return (
      <div style={common}>
        <svg viewBox="0 0 200 100" style={{ width: '100%', height: '100%' }}>
          <rect x="20" y="15" width="70" height="70" fill="none" stroke={FONGOS.line} strokeDasharray="3 3"/>
          <text x="55" y="55" textAnchor="middle" fontFamily={FONGOS.mono} fontSize="8" fill={FONGOS.inkFaint}>v1</text>
          <text x="100" y="52" fontFamily={FONGOS.mono} fontSize="10" fill={FONGOS.purpleSoft}>→</text>
          <rect x="115" y="15" width="60" height="70" fill="none" stroke={FONGOS.purpleSoft}/>
          <circle cx="145" cy="50" r="11" fill="none" stroke={FONGOS.cyan}/>
          <text x="145" y="78" textAnchor="middle" fontFamily={FONGOS.mono} fontSize="8" fill={FONGOS.cyanSoft}>v2</text>
        </svg>
      </div>
    );
    if (kind === 'cad') return (
      <div style={common}>
        <svg viewBox="0 0 200 100" style={{ width: '100%', height: '100%' }}>
          {[...Array(8)].map((_, i) => <line key={i} x1={20 + i * 22} y1="15" x2={20 + i * 22} y2="85" stroke={FONGOS.line} strokeWidth="0.5"/>)}
          <polygon points="50,30 150,30 160,45 160,75 70,75 40,60 40,45" fill={FONGOS.purple} fillOpacity="0.15" stroke={FONGOS.purpleSoft} strokeWidth="1"/>
          <circle cx="75" cy="50" r="4" fill="none" stroke={FONGOS.cyanSoft}/>
          <circle cx="125" cy="50" r="4" fill="none" stroke={FONGOS.cyanSoft}/>
          <text x="100" y="95" textAnchor="middle" fontFamily={FONGOS.mono} fontSize="7" fill={FONGOS.inkFaint} letterSpacing="1.5">−18% MASS · SF 1.22</text>
        </svg>
      </div>
    );
    return <div style={common}/>;
  };

  return (
    <section id="moments" style={{
      padding: '120px 40px', borderBottom: `1px solid ${FONGOS.line}`,
    }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <SectionLabel num="03" name="Moments"/>
        <Headline size={56} style={{ marginBottom: 20, maxWidth: 760 }}>
          Six things he did this month.<br/>
          <span style={{ color: FONGOS.inkDim }}>Nobody asked him to.</span>
        </Headline>
        <p style={{ fontSize: 15, color: FONGOS.inkDim, maxWidth: 540, margin: '0 0 52px', lineHeight: 1.6 }}>
          Not a feature list. Moments from real sessions, logged.
        </p>

        <div className="fg-cases" style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 1,
          background: FONGOS.line, border: `1px solid ${FONGOS.line}`,
        }}>
          {moments.map((m) => (
            <div key={m.t} style={{
              background: FONGOS.bg, padding: 0, position: 'relative',
              transition: 'background 0.2s ease',
            }} className="fg-case">
              <Thumb kind={m.visual}/>
              <div style={{ padding: '22px 24px 24px' }}>
                <div style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  marginBottom: 14,
                }}>
                  <div style={{
                    fontFamily: FONGOS.mono, fontSize: 10, letterSpacing: '0.2em',
                    color: FONGOS.purpleSoft, textTransform: 'uppercase',
                  }}>{m.tag}</div>
                  <div style={{
                    fontFamily: FONGOS.mono, fontSize: 10, letterSpacing: '0.15em',
                    color: FONGOS.inkFaint,
                  }}>{m.when}</div>
                </div>
                <div style={{ fontSize: 19, color: FONGOS.ink, fontWeight: 400, lineHeight: 1.3, letterSpacing: '-0.015em', marginBottom: 12 }}>
                  {m.t}
                </div>
                <p style={{ fontSize: 13.5, color: FONGOS.inkDim, lineHeight: 1.6, margin: 0 }}>{m.p}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { SelfCorrectionStrip, WhoIsFongos, Moments });
