// Sections 2-7 — The rest of the Attora page
// Section 2: The New Shape of Acquisition (scroll-tied CAC graph)
// Section 3: The Trident Method
// Section 4: Inside the System (Intelligence w/ dossier profiles | Conversation)
// Section 5: The Moat
// Section 6: Proof
// Section 7: Closing CTA + Footer

const { useState: useStateX, useEffect: useEffectX, useRef: useRefX, useMemo: useMemoX } = React;

/* ---------- Section 2: Shape ---------- */
function CACGraph() {
  const [ref, inView] = useInView(0.25);
  const [p, setP] = useStateX(0);
  useEffectX(() => {
    if (!inView) return;
    const start = performance.now();
    let raf;
    const tick = (t) => {
      const k = Math.min(1, (t - start) / 2400);
      setP(k);
      if (k < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [inView]);

  // Baseline CAC path — climbs, plateaus, climbs again (3 cycles)
  const W = 1000, H = 360;
  const baselinePts = useMemoX(() => {
    const pts = [];
    for (let i = 0; i <= 100; i++) {
      const x = (i / 100) * W;
      // three rising steps
      const base = 260 - i * 1.8;
      const wiggle = Math.sin(i * 0.35) * 8 + Math.sin(i * 0.11) * 14;
      const steps = i < 33 ? 0 : i < 66 ? -18 : -34;
      pts.push([x, base + wiggle + steps]);
    }
    return pts;
  }, []);
  // Attora divergence — emerges from baseline with matching wiggle, peels off smoothly
  const DIVERGE_AT = 60;
  const attoraPts = useMemoX(() => {
    const pts = [];
    // Zero out the wiggle at the divergence point so the first sample matches baseline exactly
    const baseWiggle = Math.sin(DIVERGE_AT * 0.33) * 5 + Math.sin(DIVERGE_AT * 0.12) * 9;
    const anchorY = baselinePts[DIVERGE_AT][1];
    for (let i = DIVERGE_AT; i <= 100; i++) {
      const x = (i / 100) * W;
      const k = i - DIVERGE_AT;
      // Same-character wiggle as baseline, softer amplitude, zeroed at divergence
      const wiggle = (Math.sin(i * 0.33) * 5 + Math.sin(i * 0.12) * 9) - baseWiggle;
      // Wiggle fades in over first ~5 points so the line doesn't jitter right at the kink
      const wiggleFade = Math.min(1, k / 5);
      // Smoothstep drop: starts at zero slope, eases into descent
      const t = k / 40; // 0 at divergence, 1 at chart end
      const eased = t * t * (3 - 2 * t); // smoothstep
      const drop = eased * 140;
      pts.push([x, anchorY + wiggle * wiggleFade + drop]);
    }
    return pts;
  }, [baselinePts]);

  const toPath = (pts, frac) => {
    const n = Math.max(1, Math.floor(pts.length * frac));
    return pts.slice(0, n).map((p, i) => (i === 0 ? 'M' : 'L') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
  };

  return (
    <div ref={ref} style={{
      position: 'relative', width: '100%', marginTop: 64,
      border: '1px solid var(--line)',
      padding: '24px 24px 28px',
      background: 'linear-gradient(180deg, rgba(245,243,238,0.015), transparent)',
    }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16,
        fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em',
        textTransform: 'uppercase', color: 'var(--fg-dim)',
      }}>
        <span>CPA · Q1 2023 → Q4 2026</span>
        <span>% CHANGE · COST PER CONVERSION</span>
      </div>

      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block', overflow: 'visible' }}>
        {/* grid */}
        {[0, 1, 2, 3, 4].map(i => (
          <line key={i} x1={0} x2={W} y1={i * (H / 4)} y2={i * (H / 4)} stroke="rgba(245,243,238,0.04)" strokeWidth="1" />
        ))}
        {/* baseline path */}
        <path d={toPath(baselinePts, Math.min(1, p * 1.5))} fill="none"
              stroke="rgba(245,243,238,0.5)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        {/* attora path — dashed */}
        <path d={toPath(attoraPts, Math.max(0, (p - 0.5) * 2))} fill="none"
              stroke="var(--accent)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
              strokeDasharray="5 4" />
        {/* Divergence marker + annotation */}
        {p > 0.55 && (
          <g style={{ opacity: Math.min(1, (p - 0.55) * 4), transition: 'opacity 300ms ease' }}>
            <line x1={baselinePts[DIVERGE_AT][0]} y1={baselinePts[DIVERGE_AT][1] - 4}
                  x2={baselinePts[DIVERGE_AT][0]} y2={baselinePts[DIVERGE_AT][1] - 52}
                  stroke="var(--accent)" strokeWidth="1" strokeDasharray="2 3" />
            <circle cx={baselinePts[DIVERGE_AT][0]} cy={baselinePts[DIVERGE_AT][1]} r="4"
                    fill="none" stroke="var(--accent)" strokeWidth="1.5" />
            <text x={baselinePts[DIVERGE_AT][0] + 8} y={baselinePts[DIVERGE_AT][1] - 58}
                  fontFamily="var(--font-mono)" fontSize="10" fill="var(--accent)"
                  letterSpacing="0.18em">ATTORA ACTIVATED</text>
          </g>
        )}
        {/* attora endpoint dot + label */}
        {p > 0.95 && (
          <g>
            <circle cx={attoraPts[attoraPts.length - 1][0]} cy={attoraPts[attoraPts.length - 1][1]} r="4" fill="var(--accent)" />
            <text x={attoraPts[attoraPts.length - 1][0] - 10}
                  y={attoraPts[attoraPts.length - 1][1] + 22}
                  textAnchor="end"
                  fontFamily="var(--font-display)" fontSize="18" fontWeight="500"
                  fill="var(--accent)" letterSpacing="-0.02em">−32%</text>
            <text x={attoraPts[attoraPts.length - 1][0] - 10}
                  y={attoraPts[attoraPts.length - 1][1] + 38}
                  textAnchor="end"
                  fontFamily="var(--font-mono)" fontSize="9" fill="rgba(245,243,238,0.5)"
                  letterSpacing="0.18em">BETA COHORT CPA</text>
          </g>
        )}
      </svg>

      <div style={{
        display: 'flex', justifyContent: 'space-between', marginTop: 14,
        fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.12em',
        color: 'var(--fg-dim)',
      }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 14, height: 1.5, background: 'rgba(245,243,238,0.5)' }} />
          INDUSTRY BASELINE
        </span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8, color: 'var(--accent)' }}>
          <span style={{ width: 14, height: 2, background: 'var(--accent)', backgroundImage: 'repeating-linear-gradient(90deg, var(--accent) 0 5px, transparent 5px 9px)' }} />
          ATTORA COHORT
        </span>
      </div>
    </div>
  );
}

function ShapeSection() {
  return (
    <Section id="shape" label="02 · THE NEW SHAPE">
      <div style={{ maxWidth: 820 }}>
        <h2 style={headingStyle}>Every funnel is optimizing the same 3%.</h2>
        <div style={{ marginTop: 28, display: 'flex', flexDirection: 'column', gap: 20, maxWidth: 680 }}>
          <p style={bodyStyle}>Your Meta ads. Your Google campaigns. Your email flows. Every tool in your stack is chasing the same small group of buyers who are ready to buy today.</p>
          <p style={bodyStyle}>Everyone else leaves. No second chance. No second message. Nothing waiting for them when they come back in three weeks.</p>
          <p style={bodyStyle}>Your CAC goes up every quarter because the 3% is getting more expensive to win, and because you're ignoring the 97% who could convert with the right touch at the right time.</p>
          <p style={{ ...bodyStyle, color: 'var(--fg)' }}>The shape of your acquisition is the problem.</p>
        </div>
      </div>
      <CACGraph />
    </Section>
  );
}

/* ---------- Section 3: Trident ---------- */
function TridentColumn({ num, title, body, delayOffset }) {
  const [ref, inView] = useInView(0.3);
  return (
    <div ref={ref} style={{
      opacity: inView ? 1 : 0,
      transform: inView ? 'translateY(0)' : 'translateY(12px)',
      transition: `opacity 700ms ease ${delayOffset}ms, transform 700ms ease ${delayOffset}ms`,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.22em',
        color: 'var(--accent)', marginBottom: 20,
      }}>
        <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }} className="hb" />
        {num} / {title.toUpperCase()}
      </div>
      <h3 style={{
        fontFamily: 'var(--font-display)', fontWeight: 500,
        fontSize: 'clamp(28px, 3vw, 40px)', letterSpacing: '-0.028em',
        margin: 0, color: 'var(--fg)', lineHeight: 1.1,
      }}>{title}</h3>
      <p style={{ ...bodyStyle, marginTop: 18, fontSize: 15 }}>{body}</p>

      {/* mini signal line */}
      <div style={{ marginTop: 28, height: 32, opacity: 0.5 }}>
        <SignalLine seed={num.charCodeAt(0)} stroke="rgba(232,168,85,0.5)" strokeWidth="0.4" amplitude={4} />
      </div>
    </div>
  );
}

function TridentSection() {
  return (
    <Section id="trident" label="03 · THE TRIDENT METHOD">
      <div style={{ maxWidth: 820, marginBottom: 80 }}>
        <h2 style={headingStyle}>Capture. Nurture. Convert.<br/>Compounding.</h2>
        <p style={{ ...bodyStyle, marginTop: 28, maxWidth: 640 }}>
          Most platforms pick one of these. Attora runs all three as a single system, and every conversation makes the next one smarter.
        </p>
      </div>
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(3, 1fr)',
        gap: 'clamp(24px, 4vw, 64px)',
      }} className="trident-grid">
        <TridentColumn num="A" title="Capture" delayOffset={0}
          body="Capitalizes on every piece of brand traffic — organic, paid, or first-party data you've already collected. Every visitor becomes a captured signal instead of a lost session."
        />
        <TridentColumn num="B" title="Nurture" delayOffset={150}
          body="One-to-one AI conversations across every channel your buyer already lives in. Instagram, iMessage, TikTok, Facebook, WhatsApp, SMS. Personal, responsive, paced to them."
        />
        <TridentColumn num="C" title="Convert" delayOffset={300}
          body="Each visitor runs through Attora's profiling framework: intent depth, buyer archetype, decision style, objection pattern. The conversation branches off that profile, so a tire-kicker and a ready-to-buy never see the same path."
        />
      </div>
      <style>{`@media (max-width: 900px) { .trident-grid { grid-template-columns: 1fr !important; } }`}</style>
    </Section>
  );
}

/* ---------- Section 4: Inside the System (w/ dossier profiles) ---------- */
const PROFILES = [
  {
    id: 'VIS_8841', label: 'Weekend outfitter',
    session: '4 sessions · 6d dormant',
    signals: [
      ['Scroll depth', '86%'],
      ['Exit velocity', 'Low'],
      ['Cart value', '$218'],
      ['Return pattern', '2 of last 7d'],
    ],
    readout: 'Patient researcher · price-sensitive · likely responder on SMS within 48h',
    channel: 'SMS',
  },
  {
    id: 'VIS_2304', label: 'Style-first researcher',
    session: '7 sessions · 6h dormant',
    signals: [
      ['Scroll depth', '94%'],
      ['PDP visits', '12'],
      ['Cart value', '$485'],
      ['Return pattern', '3 of last 3d'],
    ],
    readout: 'High-intent deliberation phase · responds to detail, not discount',
    channel: 'EMAIL',
  },
  {
    id: 'VIS_9912', label: 'Loyalty-curious',
    session: '12 sessions · 3d dormant',
    signals: [
      ['Scroll depth', '71%'],
      ['Micro-conv.', '4'],
      ['Cart value', '$188'],
      ['Return pattern', '5 of last 14d'],
    ],
    readout: 'Returning buyer · needs reassurance, not pitch · DM-native',
    channel: 'IG DM',
  },
];

function DossierPanel() {
  const [idx, setIdx] = useStateX(0);
  const [auto, setAuto] = useStateX(true);
  useEffectX(() => {
    if (!auto) return;
    const t = setInterval(() => setIdx(i => (i + 1) % PROFILES.length), 5000);
    return () => clearInterval(t);
  }, [auto]);

  const p = PROFILES[idx];
  const hb = useHeartbeat();

  return (
    <div style={{
      border: '1px solid var(--line-strong)',
      background: 'linear-gradient(180deg, rgba(245,243,238,0.02), transparent)',
      fontFamily: 'var(--font-display)',
    }}>
      {/* Header w/ profile tabs */}
      <div style={{
        display: 'flex', borderBottom: '1px solid var(--line)',
      }}>
        {PROFILES.map((prof, i) => (
          <button key={prof.id}
            onClick={() => { setIdx(i); setAuto(false); }}
            style={{
              flex: 1,
              padding: '14px 16px',
              background: i === idx ? 'rgba(232,168,85,0.06)' : 'transparent',
              border: 0,
              borderBottom: '2px solid ' + (i === idx ? 'var(--accent)' : 'transparent'),
              borderRight: i < PROFILES.length - 1 ? '1px solid var(--line)' : 0,
              fontFamily: 'var(--font-mono)',
              fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase',
              color: i === idx ? 'var(--accent)' : 'var(--fg-dim)',
              cursor: 'pointer',
              transition: 'all 200ms ease',
              textAlign: 'left',
            }}>
            <div>{prof.id}</div>
            <div style={{ marginTop: 4, color: i === idx ? 'var(--fg-mute)' : 'var(--fg-dim)', fontSize: 9 }}>
              {prof.label}
            </div>
          </button>
        ))}
      </div>

      {/* Body */}
      <div key={p.id} style={{ padding: '22px 22px', animation: 'fadeSlide 400ms ease' }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          marginBottom: 16,
          fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em',
          textTransform: 'uppercase', color: 'var(--fg-dim)',
        }}>
          <span>SIGNALS · {p.session}</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--accent)', opacity: hb ? 1 : 0.3 }} />
            LIVE
          </span>
        </div>

        {/* Signal rows */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '0 28px' }}>
          {p.signals.map(([k, v], i) => (
            <div key={i} style={{
              display: 'flex', justifyContent: 'space-between', padding: '9px 0',
              borderBottom: '1px dashed var(--line)',
              fontSize: 13,
            }}>
              <span style={{ color: 'var(--fg-dim)', fontFamily: 'var(--font-mono)', fontSize: 11 }}>{k}</span>
              <span style={{ color: 'var(--fg)', fontVariantNumeric: 'tabular-nums' }}>{v}</span>
            </div>
          ))}
        </div>

        {/* Readout */}
        <div style={{
          marginTop: 22, padding: '14px 16px',
          background: 'rgba(232,168,85,0.04)',
          border: '1px solid rgba(232,168,85,0.22)',
          fontSize: 13, lineHeight: 1.5, color: 'var(--fg)',
        }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.2em',
            color: 'var(--accent)', marginBottom: 8,
          }}>READOUT →</div>
          {p.readout}
        </div>

        {/* Channel */}
        <div style={{
          marginTop: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em',
          textTransform: 'uppercase', color: 'var(--fg-dim)',
        }}>
          <span>RECOMMENDED CHANNEL</span>
          <span style={{ color: 'var(--accent)' }}>→ {p.channel}</span>
        </div>
      </div>

      <style>{`
        @keyframes fadeSlide {
          from { opacity: 0; transform: translateY(4px); }
          to { opacity: 1; transform: translateY(0); }
        }
      `}</style>
    </div>
  );
}

function InsideSection() {
  return (
    <Section id="inside" label="04 · INSIDE THE SYSTEM">
      <div style={{ maxWidth: 820, marginBottom: 64 }}>
        <h2 style={headingStyle}>Two layers. One system.</h2>
        <p style={{ ...bodyStyle, marginTop: 24, maxWidth: 640 }}>
          Every competitor picks one side of the problem. Attora runs Intelligence and Conversation as a single loop, each feeding the other.
        </p>
      </div>

      <div style={{
        display: 'grid',
        gridTemplateColumns: '1fr 1px 1fr',
        gap: 'clamp(24px, 4vw, 64px)',
        alignItems: 'start',
      }} className="inside-grid">
        {/* Intelligence */}
        <div>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.22em',
            color: 'var(--accent)', marginBottom: 20,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }} className="hb" />
            INTELLIGENCE
          </div>
          <h3 style={subheadingStyle}>Reads every signal your analytics can't.</h3>
          <p style={{ ...bodyStyle, marginTop: 16, fontSize: 15 }}>
            Scroll depth, exit velocity, return patterns, micro-conversions. The patterns your dashboard was never built to capture.
          </p>
          <p style={{ ...bodyStyle, marginTop: 12, fontSize: 15 }}>
            Cross-referenced against proprietary third-party data that tells the system who each visitor really is, beyond what they'll ever give you directly.
          </p>
          <div style={{ marginTop: 32 }}>
            <DossierPanel />
          </div>
        </div>

        {/* Center rule */}
        <div style={{
          alignSelf: 'stretch',
          position: 'relative',
          background: 'var(--line)',
          minHeight: 400,
        }} className="inside-divider">
          <span style={{
            position: 'absolute', top: '50%', left: '50%',
            transform: 'translate(-50%, -50%)',
            width: 8, height: 8, borderRadius: '50%',
            background: 'var(--accent)',
            boxShadow: '0 0 14px var(--accent)',
          }} className="hb" />
        </div>

        {/* Conversation */}
        <div>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.22em',
            color: 'var(--accent)', marginBottom: 20,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }} className="hb" />
            CONVERSATION
          </div>
          <h3 style={subheadingStyle}>Turns every signal into a reply they want to get.</h3>
          <p style={{ ...bodyStyle, marginTop: 16, fontSize: 15 }}>
            Personal, paced, channel-native. Instagram, iMessage, TikTok, Facebook, WhatsApp, SMS — wherever your buyer actually is.
          </p>
          <p style={{ ...bodyStyle, marginTop: 12, fontSize: 15 }}>
            Every conversation improves the system. <span style={{ color: 'var(--fg)' }}>Your CAC today is the worst it will ever be.</span>
          </p>
          <div style={{ marginTop: 32 }}>
            <ConversationPanel />
          </div>
        </div>
      </div>

      <div style={{
        marginTop: 72, paddingTop: 32,
        borderTop: '1px solid var(--line)',
        textAlign: 'center',
      }}>
        <p style={{
          fontFamily: 'var(--font-display)', fontWeight: 400,
          fontSize: 'clamp(20px, 2vw, 28px)', letterSpacing: '-0.02em',
          color: 'var(--fg)', margin: 0,
        }}>
          The two halves are the product. Nobody else has both.
        </p>
      </div>

      <style>{`
        @media (max-width: 1024px) {
          .inside-grid { grid-template-columns: 1fr !important; }
          .inside-divider { display: none; }
        }
      `}</style>
    </Section>
  );
}

function ConversationPanel() {
  const [ref, inView] = useInView(0.25);
  const turns = [
    { who: 'attora', text: "You've been back to the Mojave boots twice this week — your size is still live. Still deciding?", delay: 200 },
    { who: 'user', text: 'yeah, torn between those and the ridge', delay: 1600 },
    { who: 'attora', text: "Main diff: Mojave is cushier for long days on foot. Ridge is waterproof. Where are you wearing them most?", delay: 2800 },
    { who: 'user', text: 'hiking mostly, pnw', delay: 4200 },
    { who: 'attora', text: "Ridge is the call. Here's the exact pair in your size, free returns if you want to test both:", delay: 5400 },
  ];
  return (
    <div ref={ref} style={{
      border: '1px solid var(--line-strong)',
      background: 'linear-gradient(180deg, rgba(245,243,238,0.02), transparent)',
    }}>
      <div style={{
        padding: '14px 20px',
        borderBottom: '1px solid var(--line)',
        fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em',
        textTransform: 'uppercase', color: 'var(--fg-dim)',
        display: 'flex', justifyContent: 'space-between',
      }}>
        <span>CH · SMS · VIS_8841</span>
        <span style={{ color: 'var(--accent)' }}>→ NURTURE</span>
      </div>
      <div style={{ padding: '20px 20px 24px', display: 'flex', flexDirection: 'column', gap: 10, minHeight: 300 }}>
        {turns.map((t, i) => (
          <div key={i} style={{
            alignSelf: t.who === 'user' ? 'flex-end' : 'flex-start',
            maxWidth: '80%',
            padding: '10px 14px',
            background: t.who === 'user' ? 'rgba(245,243,238,0.06)' : 'rgba(232,168,85,0.08)',
            border: '1px solid ' + (t.who === 'user' ? 'var(--line-strong)' : 'rgba(232,168,85,0.25)'),
            fontSize: 13, lineHeight: 1.45, color: 'var(--fg)',
            opacity: inView ? 1 : 0,
            transform: inView ? 'translateY(0)' : 'translateY(6px)',
            transition: `opacity 500ms ease ${t.delay}ms, transform 500ms ease ${t.delay}ms`,
          }}>
            {t.text}
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- Section 5: Moat ---------- */
const MOAT_CLUSTERS = [
  { cx: 24, cy: 36, r: 13, n: 22, color: '#E8A855', label: 'META-FATIGUED' },
  { cx: 66, cy: 28, r: 10, n: 15, color: '#C85A3D', label: 'FIRST-TIME' },
  { cx: 28, cy: 72, r: 11, n: 18, color: '#9E3838', label: 'SIX-WEEK DORMANT' },
  { cx: 72, cy: 70, r: 12, n: 21, color: '#D9A65C', label: 'ACTIVE DELIBERATOR' },
];

function MoatCluster() {
  const [view, setView] = useStateX('competitor'); // 'competitor' | 'attora'
  const [ref, inView] = useInView(0.3);

  // Auto-flip to "attora" view 1.6s after scroll-in
  useEffectX(() => {
    if (!inView) return;
    const t = setTimeout(() => setView('attora'), 1600);
    return () => clearTimeout(t);
  }, [inView]);

  // Build both states for every dot — identical count, paired by index
  const dots = useMemoX(() => {
    const make = (seed) => {
      let s = seed;
      return () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
    };
    const aRnd = make(1);
    const cRnd = make(7);
    const out = [];
    MOAT_CLUSTERS.forEach((cl) => {
      for (let i = 0; i < cl.n; i++) {
        // Attora state — tight cluster, colored
        const aAng = aRnd() * Math.PI * 2;
        const aDist = Math.sqrt(aRnd()) * cl.r;
        const size = 0.65 + aRnd() * 0.85;
        // Competitor state — uniform random gray scatter across canvas
        const cAng = cRnd() * Math.PI * 2;
        const cDist = Math.sqrt(cRnd()) * 34;
        out.push({
          a: { x: cl.cx + Math.cos(aAng) * aDist, y: cl.cy + Math.sin(aAng) * aDist, color: cl.color, size },
          c: { x: 50 + Math.cos(cAng) * cDist, y: 50 + Math.sin(cAng) * cDist, color: 'rgba(245, 243, 238, 0.32)', size: 0.9 },
        });
      }
    });
    return out;
  }, []);

  return (
    <div ref={ref} style={{ width: '100%', maxWidth: 560 }}>
      {/* Toggle tabs */}
      <div style={{
        display: 'flex',
        marginBottom: 20,
        border: '1px solid var(--line)',
      }}>
        {[
          { id: 'competitor', label: 'Competitors see' },
          { id: 'attora', label: 'Attora sees' },
        ].map((tab, i) => (
          <button key={tab.id}
            onClick={() => setView(tab.id)}
            style={{
              flex: 1,
              padding: '12px 14px',
              background: view === tab.id ? 'rgba(232,168,85,0.06)' : 'transparent',
              border: 0,
              borderLeft: i > 0 ? '1px solid var(--line)' : 0,
              borderBottom: '2px solid ' + (view === tab.id ? 'var(--accent)' : 'transparent'),
              fontFamily: 'var(--font-mono)',
              fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase',
              color: view === tab.id ? 'var(--accent)' : 'var(--fg-dim)',
              cursor: 'pointer',
              transition: 'all 200ms ease',
            }}>
            {tab.label}
          </button>
        ))}
      </div>

      <div style={{ position: 'relative', aspectRatio: '1/1' }}>
        <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet"
          style={{ width: '100%', height: '100%', display: 'block' }}>
          {dots.map((d, i) => {
            const s = view === 'attora' ? d.a : d.c;
            return (
              <circle key={i}
                cx={s.x} cy={s.y} r={s.size}
                fill={s.color}
                style={{
                  opacity: inView ? 0.9 : 0,
                  transition: 'cx 1100ms cubic-bezier(0.22,0.9,0.25,1), cy 1100ms cubic-bezier(0.22,0.9,0.25,1), r 700ms ease, fill 800ms ease, opacity 600ms ease',
                }}
              />
            );
          })}
        </svg>

        {/* Cluster labels — only render in Attora view */}
        {view === 'attora' && MOAT_CLUSTERS.map((cl, i) => (
          <div key={i} style={{
            position: 'absolute',
            left: `${cl.cx}%`, top: `${cl.cy}%`,
            transform: 'translate(-50%, calc(-50% - ' + (cl.r + 8) + 'px))',
            fontFamily: 'var(--font-mono)',
            fontSize: 9, letterSpacing: '0.16em', textTransform: 'uppercase',
            color: cl.color,
            padding: '3px 8px',
            background: 'rgba(10,10,10,0.78)',
            border: `1px solid ${cl.color}`,
            whiteSpace: 'nowrap',
            pointerEvents: 'none',
            animation: 'fadeInLabel 600ms ease 900ms backwards',
          }}>{cl.label}</div>
        ))}
      </div>

      <style>{`
        @keyframes fadeInLabel {
          from { opacity: 0; transform: translate(-50%, calc(-50% - 18px)); }
          to { opacity: 1; }
        }
      `}</style>
    </div>
  );
}

function MoatSection() {
  return (
    <Section id="moat" label="05 · THE MOAT">
      <div style={{
        display: 'grid',
        gridTemplateColumns: '1.1fr 1fr',
        gap: 'clamp(32px, 5vw, 96px)',
        alignItems: 'center',
      }} className="moat-grid">
        <div>
          <h2 style={headingStyle}>The AI layer isn't the advantage anymore.</h2>
          <div style={{ marginTop: 28, display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 560 }}>
            <p style={bodyStyle}>Every platform will have AI. The advantage is what you feed it.</p>
            <p style={bodyStyle}>Attora runs every piece of brand traffic through its profiling framework. That's how the system knows which anonymous visitor is a Meta-fatigued buyer from a competitor, which one is a first-time researcher, and which one has been looking for six weeks and just needs to talk to someone.</p>
            <p style={{ ...bodyStyle, color: 'var(--fg)' }}>The profile is the product. The AI layer is just the interface that speaks it.</p>
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <MoatCluster />
        </div>
      </div>
      <style>{`@media (max-width: 900px) { .moat-grid { grid-template-columns: 1fr !important; } }`}</style>
    </Section>
  );
}

/* Section 6 (Proof) removed — beta stat surfaces on CAC graph. */

/* ---------- Section 7: Closing CTA ---------- */
function CTASection({ openWaitlist }) {
  const hb = useHeartbeat();
  return (
    <Section id="beta" label="06 · THE INVITATION" style={{ paddingBottom: 120 }}>
      <div style={{
        maxWidth: 920, margin: '0 auto',
        textAlign: 'center',
        display: 'flex', flexDirection: 'column', alignItems: 'center',
      }}>
        <div style={{
          width: 14, height: 14, borderRadius: '50%',
          background: 'var(--accent)',
          opacity: hb ? 1 : 0.35,
          boxShadow: hb ? '0 0 24px var(--accent)' : '0 0 0 var(--accent)',
          transition: 'opacity 600ms ease, box-shadow 600ms ease',
          marginBottom: 40,
        }} />
        <h2 style={{
          ...headingStyle,
          fontSize: 'clamp(36px, 5vw, 68px)',
          textWrap: 'balance',
        }}>
          We're onboarding operators who are ready to stop optimizing the same 3%.
        </h2>
        <p style={{ ...bodyStyle, marginTop: 28, maxWidth: 560 }}>
          We are currently accepting a limited number of brands for our beta. Apply below.
        </p>
        <div style={{ marginTop: 40, display: 'flex', gap: 20, alignItems: 'center', flexWrap: 'wrap', justifyContent: 'center' }}>
          <button className="btn-primary" onClick={openWaitlist}>
            Apply for Beta
            <span className="arrow">→</span>
          </button>
          <a href="mailto:hello@attora.ai" style={{
            fontFamily: 'var(--font-mono)',
            fontSize: 12,
            letterSpacing: '0.12em',
            color: 'var(--fg-mute)',
            textDecoration: 'none',
          }}>
            or reach out directly · hello@attora.ai
          </a>
        </div>
      </div>
    </Section>
  );
}

function Footer() {
  return (
    <footer style={{
      borderTop: '1px solid var(--line)',
      padding: '32px clamp(24px, 6vw, 96px)',
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em',
      textTransform: 'uppercase', color: 'var(--fg-dim)',
    }}>
      <Wordmark size={14} />
      <div style={{ display: 'flex', gap: 24 }}>
        <a href="mailto:hello@attora.ai" style={{ color: 'var(--fg-dim)', textDecoration: 'none' }}>Contact</a>
        <span>© 2026</span>
      </div>
    </footer>
  );
}

/* ---------- Shared styles ---------- */
const headingStyle = {
  fontFamily: 'var(--font-display)',
  fontWeight: 500,
  fontSize: 'clamp(34px, 4.6vw, 68px)',
  lineHeight: 1.05,
  letterSpacing: '-0.03em',
  margin: 0,
  color: 'var(--fg)',
  textWrap: 'balance',
};
const subheadingStyle = {
  fontFamily: 'var(--font-display)',
  fontWeight: 500,
  fontSize: 'clamp(22px, 2.2vw, 30px)',
  letterSpacing: '-0.025em',
  lineHeight: 1.15,
  margin: 0,
  color: 'var(--fg)',
};
const bodyStyle = {
  fontFamily: 'var(--font-display)',
  fontSize: 16,
  lineHeight: 1.6,
  color: 'var(--fg-mute)',
  margin: 0,
  textWrap: 'pretty',
};

Object.assign(window, {
  ShapeSection, TridentSection, InsideSection, MoatSection, CTASection, Footer,
});
