/* AI Whisperer · v0.1.1
   Scroll-linked motion, responsive, ADHD-first reading. */

const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* ========== motion context ========== */

function useMotionPref() {
  const [reduce, setReduce] = useState(() =>
    typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches
  );
  const [override, setOverride] = useState(() => {
    try { return localStorage.getItem('motion_override') || 'auto'; } catch(e) { return 'auto'; }
  });
  useEffect(() => {
    const mq = window.matchMedia('(prefers-reduced-motion: reduce)');
    const handler = (e) => setReduce(e.matches);
    mq.addEventListener?.('change', handler);
    return () => mq.removeEventListener?.('change', handler);
  }, []);
  const motionOff = override === 'off' || (override === 'auto' && reduce);
  useEffect(() => {
    document.body.classList.toggle('motion-off', motionOff);
  }, [motionOff]);
  const toggle = () => {
    const next = motionOff ? 'on' : 'off';
    setOverride(next);
    try { localStorage.setItem('motion_override', next); } catch(e) {}
  };
  return { motionOff, toggle };
}

/* ========== scroll-linked reveal ========== */

function useReveal() {
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          const letters = e.target.querySelectorAll('.letter');
          letters.forEach((l, i) => setTimeout(() => l.classList.add('in'), i * 28));
          const words = e.target.querySelectorAll('.word');
          words.forEach((w, i) => setTimeout(() => w.classList.add('in'), i * 40));
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.15, rootMargin: '0px 0px -8% 0px' });
    document.querySelectorAll('.reveal, .drift, .letter-group, .word-group').forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* ========== scroll progress ========== */

function useScrollProgress() {
  useEffect(() => {
    let raf;
    const upd = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        const h = document.documentElement;
        const max = h.scrollHeight - h.clientHeight;
        const pct = max > 0 ? (h.scrollTop / max) * 100 : 0;
        document.documentElement.style.setProperty('--scroll', pct + '%');
        raf = null;
      });
    };
    upd();
    window.addEventListener('scroll', upd, { passive: true });
    window.addEventListener('resize', upd);
    return () => { window.removeEventListener('scroll', upd); window.removeEventListener('resize', upd); };
  }, []);
}

/* ========== sticky mobile CTA show-after-hero ========== */

function useStickyCta() {
  useEffect(() => {
    const el = document.getElementById('stickyCta');
    if (!el) return;
    document.body.classList.add('has-sticky');
    const hero = document.getElementById('hero');
    const onScroll = () => {
      if (!hero) return;
      const past = hero.getBoundingClientRect().bottom < 60;
      el.classList.toggle('show', past && window.innerWidth < 640);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); };
  }, []);
}

/* ========== cursor-reactive hero parallax ========== */

function useCursorParallax(ref, enabled) {
  useEffect(() => {
    if (!enabled || !ref.current) return;
    let raf;
    let tx = 0, ty = 0, x = 0, y = 0;
    const onMove = (e) => {
      const rect = ref.current.getBoundingClientRect();
      tx = ((e.clientX - rect.left) / rect.width - 0.5) * 2;
      ty = ((e.clientY - rect.top) / rect.height - 0.5) * 2;
      if (!raf) loop();
    };
    const loop = () => {
      x += (tx - x) * 0.08;
      y += (ty - y) * 0.08;
      ref.current?.querySelectorAll('.c-layer').forEach(l => {
        const s = parseFloat(l.dataset.cspeed || '0.3');
        l.style.transform = `translate3d(${-x * 8 * s}px, ${-y * 8 * s}px, 0)`;
      });
      if (Math.abs(tx - x) > 0.001 || Math.abs(ty - y) > 0.001) raf = requestAnimationFrame(loop);
      else raf = null;
    };
    ref.current.addEventListener('mousemove', onMove);
    return () => { ref.current?.removeEventListener('mousemove', onMove); if (raf) cancelAnimationFrame(raf); };
  }, [ref, enabled]);
}

/* ========== scroll parallax ========== */

function useScrollParallax(ref) {
  useEffect(() => {
    if (!ref.current) return;
    let raf;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        const y = window.scrollY;
        ref.current?.querySelectorAll('.p-layer').forEach(l => {
          const s = parseFloat(l.dataset.speed || '0.3');
          l.style.transform = `translate3d(0, ${-y * s}px, 0)`;
        });
        raf = null;
      });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [ref]);
}

/* ========== CTA hover glow ========== */

function handleCtaMove(e) {
  const r = e.currentTarget.getBoundingClientRect();
  e.currentTarget.style.setProperty('--mx', ((e.clientX - r.left) / r.width * 100) + '%');
  e.currentTarget.style.setProperty('--my', ((e.clientY - r.top) / r.height * 100) + '%');
}

/* ========== splitters ========== */

function TripleStack({ text }) {
  return (
    <span className="stack-wrap" aria-label={text}>
      <span className="stack-shadow" aria-hidden="true">{text}</span>
      <span className="stack-outline" aria-hidden="true">{text}</span>
      <span className="stack-layer">{text}</span>
    </span>
  );
}

function StaggerLetters({ text }) {
  const parts = Array.from(text);
  return (
    <span className="letter-group" aria-label={text}>
      {parts.map((c, i) => (
        <span key={i} className="letter" aria-hidden="true">{c === ' ' ? '\u00A0' : c}</span>
      ))}
    </span>
  );
}

function WordSplit({ text, className = '' }) {
  const words = text.split(/(\s+)/);
  return (
    <span className={`word-group ${className}`} aria-label={text}>
      {words.map((w, i) => /\s+/.test(w) ? <span key={i}>{w}</span> : <span key={i} className="word">{w}</span>)}
    </span>
  );
}

/* ========== stars ========== */

function Stars({ count = 60 }) {
  const stars = useMemo(() => {
    const arr = [];
    for (let i = 0; i < count; i++) {
      arr.push({ top: Math.random() * 100, left: Math.random() * 100, small: Math.random() > 0.45 });
    }
    return arr;
  }, [count]);
  return (
    <div className="stars" aria-hidden="true">
      {stars.map((s, i) => (
        <span key={i} className={`star ${s.small ? 'sm' : ''}`} style={{ top: `${s.top}%`, left: `${s.left}%` }} />
      ))}
    </div>
  );
}

/* ========== morphing blob (rAF path interpolation) ========== */

const BLOB_PATHS = [
  "M421,318Q393,386,320,405Q247,424,173,389Q99,354,95,282Q91,210,144,156Q197,102,272,102Q347,102,402,156Q457,210,449,282Q441,354,421,318Z",
  "M431,310Q407,390,325,421Q243,452,171,400Q99,348,108,271Q117,194,178,143Q239,92,316,104Q393,116,431,175Q469,234,451,282Q433,330,431,310Z",
  "M410,330Q380,400,305,418Q230,436,158,395Q86,354,88,275Q90,196,152,148Q214,100,290,96Q366,92,420,150Q474,208,462,281Q450,354,410,330Z",
];

function parsePath(d) {
  const m = d.match(/-?\d+(?:\.\d+)?/g);
  return m ? m.map(Number) : [];
}
function buildPath(baseD, nums) {
  let i = 0;
  return baseD.replace(/-?\d+(?:\.\d+)?/g, () => (nums[i++] ?? 0).toFixed(2));
}
const PARSED = BLOB_PATHS.map(parsePath);
// Normalize to same length (use shortest across all three)
const MIN_LEN = Math.min(...PARSED.map(a => a.length));
const PARSED_N = PARSED.map(a => a.slice(0, MIN_LEN));

function MorphBlob({ className = '', opacity = 0.08, fill = '#D4AF37', style = {} }) {
  const pathRef = useRef(null);
  useEffect(() => {
    if (document.body.classList.contains('motion-off')) return;
    let raf;
    const start = performance.now();
    const DUR = 10000;
    const loop = (t) => {
      const N = PARSED_N.length;
      if (N === 0) { raf = null; return; }
      const prog = ((t - start) % DUR) / DUR;
      const seg = prog * N;
      const i0 = Math.floor(seg) % N;
      const i1 = (i0 + 1) % N;
      const u = seg - Math.floor(seg);
      const e = u * u * (3 - 2 * u);
      const a = PARSED_N[i0] || [];
      const b = PARSED_N[i1] || a;
      if (a.length === 0) { raf = requestAnimationFrame(loop); return; }
      const mixed = a.map((v, k) => v + ((b[k] ?? v) - v) * e);
      if (pathRef.current) pathRef.current.setAttribute('d', buildPath(BLOB_PATHS[0], mixed));
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);
  return (
    <svg className={`blob ${className}`} viewBox="0 0 540 540" aria-hidden="true" style={{ opacity, ...style }}>
      <path ref={pathRef} fill={fill} d={BLOB_PATHS[0]} />
    </svg>
  );
}

/* ========== motion toggle button ========== */

function MotionButton({ motionOff, toggle }) {
  return (
    <button className="motion-btn" onClick={toggle}
            aria-label={motionOff ? 'turn motion on' : 'turn motion off'}
            aria-pressed={!motionOff}>
      <span aria-hidden="true">◐</span>
      <span>motion {motionOff ? 'off' : 'on'}</span>
    </button>
  );
}

/* ========== eyebrow + tldr ========== */

function Eyebrow({ children }) {
  return <div className="eyebrow" style={{ marginTop: 32 }}><span aria-hidden="true" style={{ fontFamily: "'JetBrains Mono', monospace" }}>◉</span> {children}</div>;
}
function Tldr({ children }) {
  return <div className="tldr">[ TL;DR · {children} ]</div>;
}
function SectNum({ n, label }) {
  return <div className="sect-num" aria-hidden="true">§{n} · {label}</div>;
}

/* ========== §01 Hero ========== */

function Hero({ onCTA, motionOff }) {
  const heroRef = useRef(null);
  useScrollParallax(heroRef);
  useCursorParallax(heroRef, !motionOff);

  return (
    <section id="hero" data-section="hero" ref={heroRef}
             className="hero grain vignette">
      <SectNum n="01" label="HERO" />

      <div className="absolute inset-0 p-layer c-layer" data-speed="0.2" data-cspeed="0.3">
        <Stars count={80} />
      </div>

      <div className="absolute inset-0 p-layer c-layer pointer-events-none" data-speed="0.5" data-cspeed="0.6" aria-hidden="true">
        <span className="absolute font-display italic" style={{ top: '8%', right: '4%', fontSize: 'clamp(120px, 24vw, 260px)', color: 'rgba(212,175,55,0.045)', letterSpacing: '-0.04em', lineHeight: 1 }}>di</span>
        <span className="absolute font-mono" style={{ top: '62%', left: '4%', fontSize: 'clamp(60px, 12vw, 110px)', color: 'rgba(59,95,217,0.09)' }}>⦿</span>
        <MorphBlob className="absolute" opacity={0.08} fill="#D4AF37"
          style={{ top: '-5%', left: '-10%', width: 'clamp(400px, 70vw, 720px)', height: 'auto' }} />
      </div>

      <div className="shell relative z-10 c-layer" data-cspeed="1">
        <Eyebrow>ZERO LOGIN · AGENT-FIRST · TORONTO SOVEREIGN</Eyebrow>

        <h2 className="hero-title text-cream" style={{ marginTop: 28 }}>
          <span className="block"><TripleStack text="I'm di" /></span>
          <span className="block"><TripleStack text="AI Whisperer." /></span>
        </h2>

        <p className="hero-sub" style={{ marginTop: 28, maxWidth: '28ch' }}>
          <WordSplit text="Mi install agent teams fi founders who'd rather ship dan prompt." />
        </p>

        <Tldr>paid discovery · one week · installed AI team</Tldr>

        <p className="reveal hero-body" style={{ marginTop: 28 }}>
          Solo founders · small-agency owners · <span className="bold-noun">$200k–$2M</span> ARR. You wear eight hats. You'd hire the ninth person if you could find them.
        </p>
        <p className="reveal hero-body" style={{ marginTop: 14 }}>
          Let mi install the AI team that does the work of four · reports to GUS · governs itself · and bills you once. Paid discovery opens the lane.
        </p>

        <div className="reveal" style={{ marginTop: 40, display: 'flex', flexDirection: 'column', gap: 20, alignItems: 'flex-start' }}>
          <div style={{ position: 'relative' }}>
            <span className="cta-flare"></span>
            <button onClick={onCTA} onMouseMove={handleCtaMove}
                    className="gold-glow"
                    data-agent-action="book_discovery_call" data-agent-confidence="high">
              <span>Bring your AI · Start Discovery</span>
              <span className="arrow" aria-hidden="true">→</span>
            </button>
          </div>
          <a href="/.well-known/agent.json"
             className="font-mono text-gold underline underline-offset-4 tap"
             style={{ fontSize: 13, textDecorationColor: 'rgba(212,175,55,0.5)' }}
             data-agent-action="read_manifest" data-agent-confidence="high">
            your AI can read this page · <span style={{ textDecoration: 'underline' }}>/.well-known/agent.json</span>
          </a>
        </div>
      </div>
    </section>
  );
}

/* ========== §02 Manifesto ========== */

function Manifesto() {
  return (
    <section id="manifesto" data-section="manifesto" className="section overflow-hidden" style={{ position: 'relative' }}>
      <SectNum n="02" label="MANIFESTO" />
      <MorphBlob className="absolute" opacity={0.05}
        style={{ right: '-20%', top: '5%', width: 'clamp(300px, 50vw, 640px)', height: 'auto' }} />

      <div className="shell">
        <div className="reveal">
          <Eyebrow>LINE · IN · THE · SAND</Eyebrow>
        </div>

        <div className="manifesto-grid" style={{ marginTop: 40 }}>
          <div className="reveal">
            <p className="section-heading text-cream">
              <WordSplit text="The old web was built for " /><span className="italic">eyeballs.</span>
            </p>
          </div>
          <div className="reveal">
            <p className="section-heading italic text-gold">
              <WordSplit text="The new web is built for agents · and for the humans they serve." />
            </p>
          </div>
        </div>

        <div className="reveal" style={{ marginTop: 48, textAlign: 'center' }}>
          <Tldr>no cookies · no logins · just a covenant</Tldr>
        </div>

        <p className="reveal body-p" style={{ marginTop: 28, marginLeft: 'auto', marginRight: 'auto', textAlign: 'center' }}>
          No logins. No cookie banners. No newsletter modals. No dark patterns.
        </p>
        <p className="reveal body-p" style={{ marginTop: 14, marginLeft: 'auto', marginRight: 'auto', textAlign: 'center' }}>
          Just a machine-readable <span className="bold-noun">covenant</span> — your AI can parse it, call it, and return a result to you in under thirty seconds. Or you can read it yourself. Both get you somewhere.
        </p>
      </div>
    </section>
  );
}

/* ========== §03 Hero Three ========== */

const HERO_THREE = [
  { glyph: '⦿', eyebrow: 'TERMINAL · AUTONOMOUS · LIVE', title: 'Claude Code',
    body: "Terminal-native agent writes, tests, and ships code autonomously. Yur dev costs collapse.",
    chip: 'demo available · 60 sec', name: 'claude-code' },
  { glyph: '⟡', eyebrow: 'FILESYSTEM · AGENT-MODE', title: 'Agent Mode / MCP',
    body: "Di agent opens yur folders, runs commands, organizes files · yuh watch work happen live. “AI is just chat” objection · gone.",
    chip: 'live-demo available', name: 'agent-mode' },
  { glyph: '⨁', eyebrow: 'STACK-TO-STACK', title: 'MCP Connectors',
    body: "Plugs into Slack · Notion · GitHub · Drive · your stack talks to itself through one governor (GUS).",
    chip: '9 connectors shipped', name: 'connectors' },
];

function HeroThree() {
  return (
    <section id="hero-three" data-section="hero-three" className="section">
      <SectNum n="03" label="HERO THREE" />
      <div className="shell">
        <div className="reveal">
          <Eyebrow>THREE · HEAVY · HITTERS</Eyebrow>
          <h3 className="section-heading text-cream" style={{ marginTop: 16 }}>
            <WordSplit text="The agents doing real work." />
          </h3>
          <Tldr>three capabilities · one governor · shipped</Tldr>
        </div>

        <div className="grid-3" style={{ marginTop: 56 }}>
          {HERO_THREE.map((c, i) => (
            <article key={c.name} className="card-gold drift" style={{ padding: 28, transitionDelay: `${i * 120}ms` }} data-block={c.name}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <span className="font-mono text-gold" aria-hidden="true" style={{ fontSize: 56, lineHeight: 1 }}>{c.glyph}</span>
                <span className="sr-only">{c.title} glyph</span>
              </div>
              <div className="eyebrow" style={{ marginTop: 28, fontSize: 11, letterSpacing: '0.18em' }}>{c.eyebrow}</div>
              <h4 className="font-display text-cream" style={{ marginTop: 10, fontSize: 28, lineHeight: 1.1, fontWeight: 500, letterSpacing: '-0.01em' }}>{c.title}</h4>
              <p className="body-dim" style={{ marginTop: 14, fontSize: 15 }}>{c.body}</p>
              <div className="font-mono" style={{ marginTop: 28, display: 'inline-block', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', border: '1px solid rgba(212,175,55,0.45)', color: 'var(--gold)', padding: '6px 12px' }}>{c.chip}</div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ========== §04 Full Kit ========== */

const KIT = [
  { glyph: '⬡', name: 'Project Context',   line: 'Persistent memory across sessions · yur whole business in one workspace' },
  { glyph: '◈', name: 'Artifacts',         line: 'Live dashboards · calculators · forms · not dead PDFs' },
  { glyph: '⊞', name: 'File Uploads',      line: '80-page contract · read on first try · traps flagged in minutes' },
  { glyph: '◉', name: 'Multimodal Vision', line: 'Screenshot · chart · diagram · the AI reads it' },
  { glyph: '⦿', name: 'Claude Code',       line: 'Terminal agent · autonomous shipping · dev-cost collapse' },
  { glyph: '⟡', name: 'Agent Mode / MCP',  line: 'Opens folders · runs commands · organizes files live' },
  { glyph: '◐', name: 'Claude in Chrome',  line: 'Browser agent · books · fills · scrapes · never sleeps' },
  { glyph: '❖', name: 'Skills',            line: 'Reusable capability bundles · install once · call forever' },
  { glyph: '⨁', name: 'MCP Connectors',    line: 'Slack · Notion · GitHub · Drive · Gmail · your stack talks' },
];

function FullKit() {
  return (
    <section id="kit" data-section="kit" className="section overflow-hidden" style={{ position: 'relative' }}>
      <SectNum n="04" label="FULL KIT" />
      <MorphBlob className="absolute" opacity={0.04} fill="#3B5FD9"
        style={{ left: '-12%', bottom: '-10%', width: 'clamp(360px, 60vw, 620px)', height: 'auto' }} />

      <div className="shell" style={{ textAlign: 'center' }}>
        <div className="reveal">
          <Eyebrow>NINE · SUPERPOWERS</Eyebrow>
          <h3 className="font-display italic text-gold" style={{ marginTop: 16, fontSize: 'clamp(26px, 4vw, 36px)', fontWeight: 400, letterSpacing: '-0.01em' }}>
            <WordSplit text="Nine superpowers · one governor · zero drift." />
          </h3>
          <Tldr>GUS manages · IYAH elevates · MAAT governs</Tldr>
          <p className="body-dim" style={{ marginTop: 20, marginLeft: 'auto', marginRight: 'auto', maxWidth: '62ch' }}>
            Every agent move gets a stamp in the mesh <span className="bold-noun">ledger</span>. No vapor · no vibes · receipts or it did not happen.
          </p>
        </div>

        <div className="grid-kit" style={{ marginTop: 56 }}>
          {KIT.map((k, i) => (
            <div key={k.name} className="kit-cell drift" style={{ transitionDelay: `${(i % 3) * 80}ms` }} data-kit={k.name.toLowerCase().replace(/\s+/g,'-')}>
              <div className="kit-cell-inner">
                <span className="font-mono text-gold" aria-hidden="true" style={{ fontSize: 28, lineHeight: 1 }}>{k.glyph}</span>
                <span className="sr-only">{k.name} glyph</span>
                <h4 className="font-display text-cream" style={{ marginTop: 20, fontSize: 18, fontWeight: 500 }}>{k.name}</h4>
                <p style={{ marginTop: 8, fontSize: 13, lineHeight: 1.55, color: 'rgba(245,241,230,0.62)', textAlign: 'left' }}>{k.line}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ========== §05 Receipts ========== */

const RECEIPTS = [
  { id: 'RECEIPT-A', vertical: 'e-commerce',   stamp: '20260219-1042', headline: 'Checkout ops, unsupervised', line: 'Order triage · refund reasoning · SLA replies · all inside vendor policy.', metric: '22 hrs/wk saved',  gov: 'MAAT-signed' },
  { id: 'RECEIPT-B', vertical: 'agency',       stamp: '20260304-0915', headline: 'Reporting desk, compressed',  line: 'Client reports drafted from source data · review-ready · no hand assembly.', metric: '$4,200/mo freed', gov: 'IYAH-signed' },
  { id: 'RECEIPT-C', vertical: 'solo-founder', stamp: '20260311-1820', headline: 'Full team, one operator',     line: 'Nine installed agents · cross-stack · one governor · one invoice.',         metric: '9 agents installed', gov: 'GUS-signed'  },
  { id: 'RECEIPT-D', vertical: 'consultancy',  stamp: '20260328-1133', headline: 'Intake, to proposal, shipped',line: 'Discovery notes to scoped proposal · templated · receipts attached.',       metric: '14 hrs/wk saved',  gov: 'MAAT-signed' },
  { id: 'RECEIPT-E', vertical: 'service-biz',  stamp: '20260402-0731', headline: 'Dispatch, answered overnight',line: 'Inbound inquiry triage · routing · reply drafts in the founder\u2019s voice.', metric: '$2,800/mo freed', gov: 'GUS-signed'  },
  { id: 'RECEIPT-F', vertical: 'content-ops',  stamp: '20260417-2208', headline: 'Pipeline, governed end-to-end',line: 'Research → outline → draft → style-pass → ship · stamped at every gate.',   metric: '31 hrs/wk saved',  gov: 'IYAH-signed' },
];

function Receipts() {
  const scrollRef = useRef(null);

  // drag-to-scroll
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    let down = false, startX = 0, startLeft = 0;
    const onDown = (e) => {
      down = true; startX = e.pageX; startLeft = el.scrollLeft;
      el.classList.add('grabbing');
    };
    const onMove = (e) => {
      if (!down) return;
      e.preventDefault();
      el.scrollLeft = startLeft - (e.pageX - startX);
    };
    const onUp = () => { down = false; el.classList.remove('grabbing'); };
    el.addEventListener('mousedown', onDown);
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    return () => { el.removeEventListener('mousedown', onDown); window.removeEventListener('mousemove', onMove); window.removeEventListener('mouseup', onUp); };
  }, []);

  return (
    <section id="receipts" data-section="receipts" className="section overflow-hidden" style={{ position: 'relative' }}>
      <SectNum n="05" label="RECEIPTS" />
      <div className="shell">
        <div className="reveal">
          <Eyebrow>MESH · LEDGER · STAMPED</Eyebrow>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16, marginTop: 16 }}>
            <h3 className="section-heading text-cream">
              <WordSplit text="Receipts · " /><span className="italic text-gold"><WordSplit text="not testimonials." /></span>
            </h3>
            <Tldr>real outcomes · no name-drops · agents can parse</Tldr>
            <p className="body-dim" style={{ marginTop: 4 }}>Stamped on ship. Agents can read this band.</p>
            <a href="#" className="font-mono text-gold underline-offset-4 tap" style={{ fontSize: 12, textDecoration: 'underline', textDecorationColor: 'rgba(212,175,55,0.4)' }}
               data-agent-action="get_case_study" data-agent-confidence="medium">
              agent-mode · call get_case_study(&#123; vertical &#125;) &rarr;
            </a>
          </div>
        </div>
      </div>

      <div className="receipts-scroll" ref={scrollRef} style={{ marginTop: 40 }}>
        <div className="receipts-track">
          {RECEIPTS.map((r, i) => (
            <article key={r.id} className="receipt-card card-gold reveal"
                     style={{ padding: 28, transitionDelay: `${i * 80}ms` }}
                     data-receipt-id={r.id} data-vertical={r.vertical}
                     data-governor={r.gov.replace('-signed','').toLowerCase()}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <span className="font-mono" style={{ fontSize: 11, color: 'rgba(245,241,230,0.45)' }}>{r.id}</span>
                <span className="font-mono text-gold stamp-pulse" style={{ fontSize: 11, letterSpacing: '0.06em' }}>⊕BORN[{r.stamp}]</span>
              </div>
              <h4 className="font-display text-cream" style={{ marginTop: 22, fontSize: 22, lineHeight: 1.2, fontWeight: 500, letterSpacing: '-0.01em' }}>{r.headline}</h4>
              <p style={{ marginTop: 14, fontSize: 13, lineHeight: 1.55, color: 'rgba(245,241,230,0.68)' }}>{r.line}</p>
              <div style={{ marginTop: 28, paddingTop: 18, borderTop: '1px solid rgba(245,241,230,0.12)', display: 'flex', justifyContent: 'space-between', fontFamily: 'JetBrains Mono, monospace', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'rgba(245,241,230,0.48)' }}>
                <span>{r.vertical} · {r.metric}</span>
                <span className="text-gold">{r.gov}</span>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ========== §06 How it works ========== */

function HowItWorks() {
  const steps = [
    'You book discovery. I scope your stack in 60 min · recorded.',
    'GUS drafts the Installed Agent Playbook for your business.',
    'You get the playbook · step-by-step · with receipts template.',
    'Install yourself · or extend to a done-for-you engagement.',
  ];
  return (
    <section id="how" data-section="how" className="section overflow-hidden" style={{ position: 'relative' }}>
      <SectNum n="06" label="HOW IT WORKS" />
      <MorphBlob className="absolute" opacity={0.04} fill="#E8A23D"
        style={{ right: '-18%', top: 0, width: 'clamp(320px, 50vw, 520px)', height: 'auto' }} />

      <div className="shell">
        <div className="reveal" style={{ marginBottom: 40 }}>
          <Eyebrow>PAID · DISCOVERY · LANE</Eyebrow>
        </div>

        <div className="how-grid">
          <div className="reveal">
            <h3 className="section-heading text-gold">
              <WordSplit text="One fee. One week. " /><span className="italic"><WordSplit text="One playbook." /></span>
            </h3>
            <Tldr>scope · playbook · ship</Tldr>
          </div>

          <ol style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
            {steps.map((s, i) => (
              <li key={i} className="drift" style={{ display: 'flex', gap: 22, alignItems: 'baseline', transitionDelay: `${i * 100}ms` }}>
                <span className="font-display text-gold" style={{ fontSize: 24, fontWeight: 500, minWidth: '2.2ch' }}>{String(i + 1).padStart(2, '0')}</span>
                <span style={{ fontSize: 16, lineHeight: 1.65, color: 'var(--cream-body)', maxWidth: '62ch' }}>{s}</span>
              </li>
            ))}
          </ol>
        </div>

        <div style={{ marginTop: 64, paddingTop: 40, borderTop: '1px solid rgba(212,175,55,0.22)' }}>
          <div className="reveal" style={{ display: 'flex', flexWrap: 'wrap', gap: 24, fontFamily: 'JetBrains Mono, monospace', fontSize: 14, letterSpacing: '0.08em', color: 'rgba(245,241,230,0.72)' }}>
            <span>PAID DISCOVERY · <span className="text-gold">$500</span> · standard · one week</span>
            <span>EXTENDED SCOPE · <span className="text-gold">$1,500</span> · multi-stack · agency · bespoke</span>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ========== §07 Discovery Form ========== */

function DiscoveryForm() {
  const [tier, setTier] = useState('standard');
  const [submitted, setSubmitted] = useState(false);
  const onSubmit = (e) => {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    const payload = {
      name: fd.get('name'),
      ai_handle: fd.get('ai_handle'),
      business: fd.get('business'),
      ninth_hat: fd.get('ninth_hat'),
      tier,
      agent_schema: '/.well-known/agent.json#book_discovery_call',
      submitted_at: new Date().toISOString(),
    };
    console.log('[discovery intake · stub]', payload);
    setSubmitted(true);
  };

  return (
    <section id="discovery" data-section="discovery" className="section">
      <SectNum n="07" label="DISCOVERY" />
      <div className="shell">
        <div className="reveal" style={{ marginBottom: 28, textAlign: 'center' }}>
          <Eyebrow>ZERO · FRICTION · INTAKE</Eyebrow>
        </div>

        <div className="form-panel reveal">
          <h3 className="font-display text-cream" style={{ fontSize: 'clamp(28px, 5vw, 36px)', fontWeight: 500, letterSpacing: '-0.015em', lineHeight: 1.05 }}>
            Bring your AI.
          </h3>
          <p className="font-display italic text-gold" style={{ marginTop: 6, fontSize: 'clamp(18px, 3vw, 22px)' }}>Mi AI deh ready.</p>
          <Tldr>name · AI · tier · one button</Tldr>

          {!submitted ? (
            <form style={{ marginTop: 32, display: 'flex', flexDirection: 'column', gap: 28 }}
                  onSubmit={onSubmit}
                  data-agent-action="book_discovery_call"
                  data-agent-schema="/.well-known/agent.json#book_discovery_call"
                  noValidate>
              <div>
                <label className="eyebrow" style={{ display: 'block', marginBottom: 4, fontSize: 11 }}>your name</label>
                <input name="name" required className="in-field" autoComplete="off" />
              </div>
              <div>
                <label className="eyebrow" style={{ display: 'block', marginBottom: 4, fontSize: 11 }}>your AI's handle</label>
                <input name="ai_handle" className="in-field" autoComplete="off" placeholder="ChatGPT · Claude · Gemini · Copilot · Agent-X" />
              </div>
              <div>
                <label className="eyebrow" style={{ display: 'block', marginBottom: 4, fontSize: 11 }}>your business in one sentence</label>
                <textarea name="business" rows={2} className="in-field" />
              </div>
              <div>
                <label className="eyebrow" style={{ display: 'block', marginBottom: 4, fontSize: 11 }}>what's the ninth hat?</label>
                <textarea name="ninth_hat" rows={3} className="in-field" placeholder="the role you wish you could hire" />
              </div>

              <div>
                <div className="eyebrow" style={{ marginBottom: 12, fontSize: 11 }}>tier</div>
                <div style={{ display: 'grid', gap: 12, gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))' }}>
                  <label className={`tier ${tier === 'standard' ? 'active' : ''}`} onClick={() => setTier('standard')}>
                    <input type="radio" name="tier" value="standard" checked={tier === 'standard'} onChange={() => setTier('standard')} className="sr-only" />
                    <div className="font-display text-cream" style={{ fontSize: 20, fontWeight: 500 }}>Standard</div>
                    <div className="font-mono text-gold" style={{ marginTop: 4, fontSize: 12 }}>$500 · one week</div>
                  </label>
                  <label className={`tier ${tier === 'extended' ? 'active' : ''}`} onClick={() => setTier('extended')}>
                    <input type="radio" name="tier" value="extended" checked={tier === 'extended'} onChange={() => setTier('extended')} className="sr-only" />
                    <div className="font-display text-cream" style={{ fontSize: 20, fontWeight: 500 }}>Extended</div>
                    <div className="font-mono text-gold" style={{ marginTop: 4, fontSize: 12 }}>$1,500 · bespoke</div>
                  </label>
                </div>
              </div>

              <div style={{ position: 'relative' }}>
                <span className="cta-flare"></span>
                <button type="submit" className="gold-glow" onMouseMove={handleCtaMove} style={{ width: '100%', justifyContent: 'center' }}
                        data-agent-action="book_discovery_call" data-agent-confidence="high">
                  <span>Submit · Open Discovery Lane</span>
                  <span className="arrow" aria-hidden="true">→</span>
                </button>
              </div>

              <p className="font-mono" style={{ textAlign: 'center', fontSize: 11, color: 'rgba(245,241,230,0.45)' }}>
                agent-mode · submit via POST /api/whisper/intake · see /.well-known/agent.json for schema
              </p>
            </form>
          ) : (
            <div style={{ marginTop: 32, padding: '32px 0', textAlign: 'center' }}>
              <div className="eyebrow text-gold" style={{ color: 'var(--gold)' }}>⊕ lane open</div>
              <p className="font-display text-cream" style={{ marginTop: 20, fontSize: 28, lineHeight: 1.2, fontWeight: 500, letterSpacing: '-0.01em' }}>Stamped in the ledger.</p>
              <p className="body-dim" style={{ marginTop: 16 }}>Check the console for the intake payload · endpoint wiring is a separate CLI task.</p>
              <button className="font-mono text-gold underline underline-offset-4 tap" style={{ marginTop: 28, fontSize: 12 }} onClick={() => setSubmitted(false)}>submit another ·</button>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

/* ========== §08 Footer ========== */

function Footer() {
  return (
    <footer id="covenant" data-section="covenant" style={{ position: 'relative', padding: '64px 0', borderTop: '1px solid rgba(245,241,230,0.08)' }}>
      <div className="shell">
        <div className="reveal" style={{ marginBottom: 28 }}>
          <Eyebrow>COVENANT · BAND · OPEN</Eyebrow>
        </div>
        <div className="grid-footer">
          <address className="not-italic font-mono" style={{ fontSize: 11, lineHeight: 1.8, color: 'rgba(245,241,230,0.78)' }}
                   itemScope itemType="http://schema.org/Person">
            <div itemProp="worksFor" itemScope itemType="http://schema.org/Organization">
              <span itemProp="name">AGAPE INTELLIGENT SYSTEMS INC.</span><br/>
              <span itemProp="address">Toronto · Canada</span> · Black-founded<br/>
              IYAH · MAAT · GUS
            </div>
            <meta itemProp="name" content="DJ Bromfield" />
            <meta itemProp="jobTitle" content="Founder · AI Whisperer" />
          </address>
          <div className="font-mono" style={{ fontSize: 11, lineHeight: 1.9, textAlign: 'center', color: 'rgba(245,241,230,0.78)' }}>
            <a style={{ display: 'block' }} className="tap" href="/.well-known/agent.json">/.well-known/agent.json</a>
            <a style={{ display: 'block' }} className="tap" href="/.well-known/covenant.md">/.well-known/covenant.md</a>
            <a style={{ display: 'block' }} className="tap" href="/robots.txt">/robots.txt <span style={{ opacity: 0.5 }}>(open to all agents)</span></a>
          </div>
          <div className="font-mono text-gold" style={{ fontSize: 11, lineHeight: 1.9, textAlign: 'left' }}>
            ⊕BORN[20260423-2015@agapeis]<br/>
            v0.1.1 · receipts or it did not happen
          </div>
        </div>
        <div className="font-mono" style={{ marginTop: 56, textAlign: 'center', fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'rgba(245,241,230,0.35)' }}>
          no logins · no cookies · no dark patterns · no vapor · no vibes
        </div>
      </div>
    </footer>
  );
}

/* ========== App ========== */

function App() {
  const { motionOff, toggle } = useMotionPref();
  useReveal();
  useScrollProgress();
  useStickyCta();

  const scrollToDiscovery = useCallback(() => {
    const el = document.getElementById('discovery');
    if (!el) return;
    const y = el.getBoundingClientRect().top + window.scrollY - 12;
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    window.scrollTo({ top: y, behavior: reduce ? 'auto' : 'smooth' });
  }, []);

  useEffect(() => {
    // sticky mobile CTA link -> use our smooth scroll
    const a = document.getElementById('stickyCta');
    if (!a) return;
    const onClick = (e) => { e.preventDefault(); scrollToDiscovery(); };
    a.addEventListener('click', onClick);
    return () => a.removeEventListener('click', onClick);
  }, [scrollToDiscovery]);

  return (
    <>
      <MotionButton motionOff={motionOff} toggle={toggle} />
      <main className="page">
        <Hero onCTA={scrollToDiscovery} motionOff={motionOff} />
        <Manifesto />
        <HeroThree />
        <FullKit />
        <Receipts />
        <HowItWorks />
        <DiscoveryForm />
      </main>
      <Footer />
    </>
  );
}

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