const { Card, Pill, Wordmark } = window.CammusDesignSystem_2ef585;

/* THE SOLUTION — choreography (per sketch): the 3 brand inputs pop in →
   dotted flows fade in and their dots march continuously down into the
   Cammus wordmark ("Intelligence") → THE lime arrow of this section draws
   down → the database card lands → "Ready to produce content".
   Connector geometry is measured from real node positions (refs) and
   redrawn on resize. Exactly one lime element in this viewport: the arrow. */

const LINE = 'var(--cam-border-strong)';
const FLOW = 'var(--cam-text-inactive)';

function TriRight({ style, className }) {
  return <span className={className} aria-hidden="true" style={{
    width: 0, height: 0, borderTop: '5px solid transparent',
    borderBottom: '5px solid transparent', borderLeft: '7px solid var(--cam-accent-olive)',
    ...style,
  }} />;
}

/* Database cylinder — thin geometric line drawing, per the DS shape vocabulary */
function DbIcon() {
  return (
    <svg aria-hidden="true" width="30" height="34" viewBox="0 0 30 34" fill="none" style={{ display: 'block', flex: 'none' }}>
      <ellipse cx="15" cy="6.5" rx="11.5" ry="4.5" stroke="var(--cam-text-secondary)" strokeWidth="1.5" />
      <path d="M3.5 6.5 V27 C3.5 29.8 8.65 32 15 32 C21.35 32 26.5 29.8 26.5 27 V6.5" stroke="var(--cam-text-secondary)" strokeWidth="1.5" />
      <path d="M3.5 16.75 C3.5 19.55 8.65 21.75 15 21.75 C21.35 21.75 26.5 19.55 26.5 16.75" stroke="var(--cam-text-secondary)" strokeWidth="1.5" />
    </svg>
  );
}

/* ---- Chat demo: one information-packed input → every format ---- */

const CHAT_MSG = "New offer: brand-audit sprint. 3 clients, +212% qualified leads in 45 days. I want to announce it.";
const CHAT_PLACEHOLDER = 'Describe the post: topic, context, or point of view.';
const CHAT_FORMATS = [
  { k: 'post', label: 'Post', meta: 'LinkedIn' },
  { k: 'onepager', label: 'One-pager', meta: 'LinkedIn' },
  { k: 'carousel', label: 'Carousel', meta: 'Instagram' },
  { k: 'reels', label: 'Reels script', meta: 'Instagram' },
  { k: 'magnet', label: 'Lead magnet', meta: 'Capture' },
];

/* Thin geometric format glyphs — rects, lines, triangles only */
function FormatGlyph({ kind }) {
  const S = 'var(--cam-text-auxiliary)';
  const common = { fill: 'none', stroke: S, strokeWidth: 1.5, strokeLinecap: 'round' };
  return (
    <svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24" style={{ display: 'block', flex: 'none' }}>
      {kind === 'post' && <g {...common}>
        <rect x="3.5" y="4.5" width="17" height="15" rx="2" />
        <line x1="7.5" y1="10" x2="16.5" y2="10" />
        <line x1="7.5" y1="14" x2="13" y2="14" />
      </g>}
      {kind === 'onepager' && <g {...common}>
        <rect x="6" y="3" width="12" height="18" rx="1.5" />
        <line x1="9" y1="7.5" x2="15" y2="7.5" />
        <line x1="9" y1="11" x2="15" y2="11" />
        <line x1="9" y1="14.5" x2="12.5" y2="14.5" />
      </g>}
      {kind === 'carousel' && <g {...common}>
        <path d="M8.5 6 V5 a1.5 1.5 0 0 1 1.5 -1.5 h9 a1.5 1.5 0 0 1 1.5 1.5 v9 a1.5 1.5 0 0 1 -1.5 1.5 h-1" />
        <rect x="3.5" y="7.5" width="13" height="13" rx="1.5" />
      </g>}
      {kind === 'reels' && <g>
        <rect x="3.5" y="4.5" width="17" height="15" rx="2.5" fill="none" stroke={S} strokeWidth="1.5" />
        <polygon points="10.5,9 15,12 10.5,15" fill={S} />
      </g>}
      {kind === 'magnet' && <g {...common}>
        <line x1="12" y1="3.5" x2="12" y2="12.5" />
        <polyline points="8.5,9.5 12,13 15.5,9.5" />
        <polyline points="4,15.5 4,19.5 20,19.5 20,15.5" />
      </g>}
    </svg>
  );
}

/* Looping choreography: type → send → think → five formats cascade → hold → reset.
   Runs only while on screen; prefers-reduced-motion renders the final state, static.
   Elements are always in flow (opacity/transform only) so the panel never reflows. */
function ChatDemo() {
  const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const panelRef = React.useRef(null);
  const [active, setActive] = React.useState(false);
  const [phase, setPhase] = React.useState(reduce ? 4 : 0); /* 0 idle · 1 typing · 2 sent · 3 thinking · 4 delivered · 5 fading */
  const [typed, setTyped] = React.useState('');

  React.useEffect(() => {
    const el = panelRef.current;
    if (!el || reduce) return;
    const io = new IntersectionObserver((es) => setActive(es[0].isIntersecting), { threshold: 0.35 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  React.useEffect(() => {
    if (!active || reduce) return;
    let alive = true;
    const timers = [];
    const wait = (ms) => new Promise((r) => timers.push(setTimeout(r, ms)));
    const typeAll = () => new Promise((res) => {
      let i = 0;
      const t = setInterval(() => {
        if (!alive || i >= CHAT_MSG.length) { clearInterval(t); res(); return; }
        i += 1; setTyped(CHAT_MSG.slice(0, i));
      }, 26);
      timers.push(t);
    });
    (async () => {
      while (alive) {
        setTyped(''); setPhase(1);
        await typeAll(); if (!alive) break;
        await wait(450); setPhase(2); setTyped('');
        await wait(650); setPhase(3);
        await wait(1500); setPhase(4);
        await wait(6200); setPhase(5);
        await wait(600);
      }
    })();
    return () => { alive = false; timers.forEach(clearTimeout); };
  }, [active]);

  const vis = (on, delay, dy) => ({
    opacity: on ? 1 : 0,
    transform: on ? 'none' : 'translateY(' + (dy == null ? 10 : dy) + 'px)',
    transition: 'opacity .5s ease ' + (delay || 0) + 's, transform .55s cubic-bezier(.34, 1.3, .64, 1) ' + (delay || 0) + 's',
  });
  const hasText = typed.length > 0;

  return (
    <div ref={panelRef} data-screen-label="Chat demo" className="lp-reveal" style={{
      marginTop: 'var(--space-7)', maxWidth: 680, marginLeft: 'auto', marginRight: 'auto',
      background: 'var(--cam-surface-card)', border: '1px solid var(--cam-border-subtle)',
      borderRadius: 'var(--radius-card)', overflow: 'hidden',
    }}>
      {/* Panel header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)', padding: 'var(--space-4) var(--space-6)', borderBottom: '1px solid var(--cam-border-subtle)' }}>
        <span style={{
          width: 26, height: 26, borderRadius: '50%', background: 'var(--cam-surface-base)',
          border: '1px solid var(--cam-border-subtle)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}><Wordmark height={8} /></span>
        <span style={{ color: 'var(--cam-text-primary)', fontWeight: 'var(--fw-semibold)', fontSize: 'var(--fs-small)', letterSpacing: 'var(--track-text)' }}>Create post</span>
      </div>

      {/* Conversation */}
      <div style={{ padding: 'var(--space-6)', opacity: phase === 5 ? 0 : 1, transition: 'opacity .45s ease' }}>
        <div style={{ textAlign: 'center', color: 'var(--cam-text-inactive)', fontSize: 'var(--fs-small)', letterSpacing: 'var(--track-text)' }}>What post do you want to create?</div>

        {/* The one information-packed input */}
        <div style={{ marginTop: 'var(--space-6)', display: 'flex', alignItems: 'center', gap: 'var(--space-4)' }}>
          <div className="lp-desk" aria-hidden="true" style={{ display: 'flex', alignItems: 'center', gap: 10, flex: 1, minWidth: 0, ...vis(phase >= 2 && phase < 5, 0.3, 0) }}>
            <span style={{ color: 'var(--cam-text-primary)', fontWeight: 'var(--fw-semibold)', fontSize: 'var(--fs-small)', whiteSpace: 'nowrap' }}>An information-packed <span style={{ color: 'var(--cam-accent-lime)' }}>input</span></span>
            <span style={{ flex: 1, height: 1, background: 'var(--cam-border-strong)', minWidth: 24 }} />
            <span style={{
              width: 0, height: 0, borderTop: '4px solid transparent',
              borderBottom: '4px solid transparent', borderLeft: '6px solid var(--cam-border-strong)',
            }} />
          </div>
          <div style={{
            background: 'var(--cam-text-primary)', color: 'var(--cam-surface-base)',
            padding: '0.9em 1.15em', borderRadius: 18, borderBottomRightRadius: 5,
            maxWidth: '36ch', fontSize: 'var(--fs-small)', fontWeight: 'var(--fw-medium)',
            lineHeight: 1.45, letterSpacing: 'var(--track-text)', flex: 'none', marginLeft: 'auto',
            ...vis(phase >= 2 && phase < 5, 0),
          }}>{CHAT_MSG}</div>
        </div>

        {/* Thinking */}
        <div aria-hidden="true" style={{ marginTop: 'var(--space-5)', height: 14, display: 'flex', gap: 5, alignItems: 'center', ...vis(phase === 3, 0, 0) }}>
          {[0, 1, 2].map((i) => <span key={i} className="lp-think" style={{ animationDelay: (i * 0.16) + 's' }} />)}
        </div>

        {/* One input → every format */}
        <div style={{ marginTop: 'var(--space-4)', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 'var(--space-3)' }}>
          {CHAT_FORMATS.map((f, i) => (
            <div key={f.k} style={{
              display: 'flex', alignItems: 'center', gap: 'var(--space-3)',
              background: 'var(--cam-surface-base)', border: '1px solid var(--cam-border-subtle)',
              borderRadius: 'var(--radius-input)', padding: 'var(--space-3) var(--space-4)',
              ...vis(phase >= 4, phase >= 4 ? i * 0.15 : 0, 12),
            }}>
              <FormatGlyph kind={f.k} />
              <span style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
                <span style={{ color: 'var(--cam-text-primary)', fontWeight: 'var(--fw-semibold)', fontSize: 'var(--fs-small)', whiteSpace: 'nowrap' }}>{f.label}</span>
                <span style={{ color: 'var(--cam-text-inactive)', fontSize: '10px', fontWeight: 'var(--fw-semibold)', textTransform: 'uppercase', letterSpacing: 'var(--track-eyebrow)' }}>{f.meta}</span>
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* Composer */}
      <div style={{ padding: '0 var(--space-6) var(--space-5)' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 'var(--space-4)',
          background: 'var(--cam-surface-base)', border: '1px solid var(--cam-border-strong)',
          borderRadius: 14, padding: 'var(--space-4) var(--space-5)',
        }}>
          <span style={{
            flex: 1, minWidth: 0, fontSize: 'var(--fs-small)', lineHeight: 1.4, letterSpacing: 'var(--track-text)',
            color: hasText ? 'var(--cam-text-primary)' : 'var(--cam-text-inactive)',
          }}>{hasText ? typed : CHAT_PLACEHOLDER}{phase === 1 && <span className="lp-caret" />}</span>
          <span aria-hidden="true" style={{
            width: 34, height: 34, borderRadius: '50%', flex: 'none',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            background: hasText ? 'var(--cam-text-primary)' : 'var(--cam-surface-card)',
            border: '1px solid ' + (hasText ? 'var(--cam-text-primary)' : 'var(--cam-border-strong)'),
            transition: 'background .3s ease, border-color .3s ease',
          }}>
            <span style={{
              width: 0, height: 0, marginLeft: 2,
              borderTop: '5px solid transparent', borderBottom: '5px solid transparent',
              borderLeft: '8px solid ' + (hasText ? 'var(--cam-surface-base)' : 'var(--cam-text-inactive)'),
              transition: 'border-color .3s ease',
            }} />
          </span>
        </div>
        <div style={{ marginTop: 'var(--space-4)', textAlign: 'center', color: 'var(--cam-text-inactive)', fontSize: '11px', letterSpacing: 'var(--track-text)' }}>AI-generated. You review and approve before publishing.</div>
      </div>
    </div>
  );
}

/* Geometric person — circle head + shoulder arc */
function PersonGlyph({ size }) {
  const s = size || 40;
  return (
    <svg aria-hidden="true" width={s} height={s} viewBox="0 0 40 40" fill="none" style={{ display: 'block' }}>
      <circle cx="20" cy="13" r="7" stroke="var(--cam-text-secondary)" strokeWidth="1.5" />
      <path d="M7 33 C7 25 12.5 21 20 21 C27.5 21 33 25 33 33" stroke="var(--cam-text-secondary)" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  );
}

/* THE SYSTEM — the loop that keeps working (per sketch): Lead ⇄ Cammus
   Intelligence tied by two marching dotted arcs ("Create more content like
   this." up, "Let's get more leads." back), an olive +1 pulsing off the lead,
   then THE lime handoff arrow into the sales panel with three leads.
   Arc geometry is measured from the real node positions. */
function SystemLoop() {
  const boxRef = React.useRef(null);
  const leadRef = React.useRef(null);
  const camRef = React.useRef(null);
  const [g, setG] = React.useState(null);

  React.useEffect(() => {
    const box = boxRef.current;
    if (!box) return;
    const measure = () => {
      const b = box.getBoundingClientRect();
      const l = leadRef.current && leadRef.current.getBoundingClientRect();
      const c = camRef.current && camRef.current.getBoundingClientRect();
      if (!b.width || !l || !c) return;
      const lx = l.left + l.width / 2 - b.left, lyT = l.top - b.top, lyB = l.bottom - b.top;
      const cx = c.left + c.width / 2 - b.left, cyT = c.top - b.top, cyB = c.bottom - b.top;
      const apex = Math.min(lyT, cyT) - 64;
      const base = Math.max(lyB, cyB) + 58;
      setG({
        w: b.width, h: b.height,
        top: `M ${lx} ${lyT - 12} C ${lx} ${apex} ${cx} ${apex} ${cx} ${cyT - 12}`,
        topTri: `${cx - 4},${cyT - 19} ${cx + 4},${cyT - 19} ${cx},${cyT - 11}`,
        bot: `M ${cx} ${cyB + 12} C ${cx} ${base} ${lx} ${base} ${lx} ${lyB + 13}`,
        botTri: `${lx - 4},${lyB + 20} ${lx + 4},${lyB + 20} ${lx},${lyB + 12}`,
        qTop: { x: (lx + cx) / 2, y: apex - 10 },
        qBot: { x: (lx + cx) / 2, y: base + 10 },
        mid: { x: (lx + cx) / 2, y: (Math.min(lyT, cyT) + Math.max(lyB, cyB)) / 2 },
      });
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(box);
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(measure);
    return () => ro.disconnect();
  }, []);

  const quoteStyle = {
    fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 'var(--fs-small)',
    color: 'var(--cam-text-secondary)', whiteSpace: 'nowrap', letterSpacing: 0,
  };

  /* Typewriter — loops while in view: type → hold → erase → retype. Layout is
     reserved by an invisible copy of the full phrase so the diagram never shifts. */
  function TypeQuote({ text, delay, style }) {
    const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const ref = React.useRef(null);
    const [n, setN] = React.useState(reduce ? text.length : 0);
    React.useEffect(() => {
      if (reduce) return undefined;
      const el = ref.current;
      if (!el) return undefined;
      let timer = null;
      let running = false;
      const type = (c) => {
        setN(c);
        if (c < text.length) timer = setTimeout(() => type(c + 1), 38 + Math.random() * 42);
        else timer = setTimeout(() => erase(c), 2200); /* hold full phrase */
      };
      const erase = (c) => {
        setN(c);
        if (c > 0) timer = setTimeout(() => erase(c - 1), 18);
        else timer = setTimeout(() => type(1), 900); /* pause before retype */
      };
      const io = new IntersectionObserver((entries) => {
        const vis = entries.some((e) => e.isIntersecting);
        if (vis && !running) { running = true; timer = setTimeout(() => type(1), (delay || 0) * 1000); }
        if (!vis && running) { running = false; clearTimeout(timer); }
      }, { threshold: 0.5 });
      io.observe(el);
      return () => { io.disconnect(); clearTimeout(timer); };
    }, []);
    const done = n >= text.length;
    return (
      <span ref={ref} style={{ ...quoteStyle, ...style }}>
        <span style={{ visibility: 'hidden' }} aria-hidden="true">"{text}"</span>
        <span aria-label={'"' + text + '"'} style={{ position: 'absolute', left: 0, top: 0, whiteSpace: 'nowrap' }}>
          "{text.slice(0, n)}{done ? '"' : <span className="lp-caret" />}
        </span>
      </span>
    );
  }
  const eyebrow = {
    color: 'var(--cam-text-inactive)', fontSize: 'var(--fs-eyebrow)', fontWeight: 'var(--fw-semibold)',
    textTransform: 'uppercase', letterSpacing: 'var(--track-eyebrow)', whiteSpace: 'nowrap',
  };

  return (
    <div className="lp-loop lp-group" style={{ marginTop: 'var(--space-6)' }}
      aria-label="Every new lead teaches Cammus Intelligence to create more content, which brings more leads; qualified leads are handed off to sales">

      {/* The feedback loop */}
      <div ref={boxRef} className="lp-loopbox" style={{ position: 'relative', display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '118px 10px 112px' }}>
        <svg aria-hidden="true" viewBox={'0 0 ' + (g ? g.w : 1) + ' ' + (g ? g.h : 1)} preserveAspectRatio="none"
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', display: 'block', pointerEvents: 'none' }}>
          {g && (
            <g>
              <g className="lp-fade" style={{ '--d': '0.5s' }}>
                <path className="lp-dotflow" d={g.top} fill="none" stroke="var(--cam-text-inactive)" strokeWidth="2" strokeLinecap="round" strokeDasharray="0.1 6" />
                <polygon className="lp-fade" style={{ '--d': '0.8s' }} points={g.topTri} fill="var(--cam-text-inactive)" />
              </g>
              <g className="lp-fade" style={{ '--d': '1s' }}>
                <path className="lp-dotflow" d={g.bot} fill="none" stroke="var(--cam-text-inactive)" strokeWidth="2" strokeLinecap="round" strokeDasharray="0.1 6" />
                <polygon className="lp-fade" style={{ '--d': '1.3s' }} points={g.botTri} fill="var(--cam-text-inactive)" />
              </g>
            </g>
          )}
        </svg>
        {g && (
          <TypeQuote text="Create more content like this." delay={0.75}
            style={{ position: 'absolute', left: g.qTop.x, top: g.qTop.y, transform: 'translate(-50%, -100%)' }} />
        )}
        {g && (
          <span className="lp-fade" style={{ ...quoteStyle, '--d': '1.25s', position: 'absolute', left: g.qBot.x, top: g.qBot.y, transform: 'translateX(-50%)' }}>"Let's get more leads."</span>
        )}
        {g && (
          <span className="lp-fade" style={{
            ...eyebrow, '--d': '0.6s', position: 'absolute', left: g.mid.x, top: g.mid.y,
            transform: 'translate(-50%, -50%)', display: 'flex', flexDirection: 'column',
            alignItems: 'center', gap: 2, textAlign: 'center', lineHeight: 1.4,
          }}><span>Feedback</span><span>loop</span></span>
        )}
        <div ref={leadRef} className="lp-pop" style={{ '--d': '0.1s', position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
          <span className="lp-plusone" aria-hidden="true" style={{
            position: 'absolute', top: -8, left: -14, transform: 'translateX(-50%)',
            color: 'var(--cam-accent-olive)', fontWeight: 'var(--fw-bold)', fontSize: '1rem',
          }}>+1</span>
          <PersonGlyph />
          <span style={{ color: 'var(--cam-text-primary)', fontWeight: 'var(--fw-semibold)', fontSize: 'var(--fs-small)', letterSpacing: 'var(--track-text)' }}>Lead</span>
        </div>
        <div ref={camRef} className="lp-pop" style={{ '--d': '0.3s', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-2)' }}>
          <Wordmark height={36} />
          <span style={eyebrow}>Intelligence</span>
        </div>
      </div>

      {/* THE lime signal — handoff to sales */}
      <div>
        <div className="lp-desk" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-3)' }}>
          <span className="lp-fade" style={{ ...eyebrow, '--d': '1.6s' }}>Handoff to sales</span>
          <div style={{ display: 'flex', alignItems: 'center' }} aria-hidden="true">
            <span className="lp-cline-x" style={{ '--d': '1.45s', width: 84, height: 4, borderRadius: 2, background: 'var(--cam-accent-lime)' }} />
            <span className="lp-fade" style={{
              '--d': '1.65s', width: 0, height: 0, marginLeft: -1,
              borderTop: '8px solid transparent', borderBottom: '8px solid transparent',
              borderLeft: '10px solid var(--cam-accent-lime)',
            }} />
          </div>
        </div>
        <div className="lp-mob lp-fade" style={{ '--d': '1.45s', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-3)' }} aria-hidden="true">
          <span style={eyebrow}>Handoff to sales</span>
          <span style={{ width: 4, height: 36, borderRadius: 2, background: 'var(--cam-accent-lime)' }} />
          <span style={{
            width: 0, height: 0, marginTop: -13,
            borderLeft: '8px solid transparent', borderRight: '8px solid transparent',
            borderTop: '10px solid var(--cam-accent-lime)',
          }} />
        </div>
      </div>

      {/* Sales panel */}
      <div>
        <p className="lp-fade" style={{ ...quoteStyle, '--d': '1.8s', whiteSpace: 'normal', margin: '0 0 var(--space-4)', fontSize: 'var(--fs-lead)', lineHeight: 1.4 }}>"The leads that have come in are..."</p>
        <div className="lp-pop" style={{
          '--d': '1.75s',
          background: 'var(--cam-surface-card)', border: '1px solid var(--cam-border-subtle)',
          borderRadius: 'var(--radius-card)', padding: 'var(--space-5)',
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 'var(--space-4)',
        }}>
          {[1, 2, 3].map((n, i) => (
            <div key={n} className="lp-item" style={{ '--d': (1.9 + i * 0.15) + 's', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, textAlign: 'center' }}>
              <PersonGlyph size={26} />
              <span style={{ color: 'var(--cam-text-primary)', fontWeight: 'var(--fw-semibold)', fontSize: 'var(--fs-small)', letterSpacing: 'var(--track-text)' }}>Lead {n}</span>
              <span style={{ color: 'var(--cam-text-inactive)', fontSize: '11px', letterSpacing: 'var(--track-text)' }}>info #1</span>
              <span style={{ color: 'var(--cam-text-inactive)', fontSize: '11px', letterSpacing: 'var(--track-text)' }}>info #2</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function SolutionSection() {
  const boxRef = React.useRef(null);
  const pillRefs = React.useRef([]);
  const markRef = React.useRef(null);
  const [geom, setGeom] = React.useState({ w: 0, h: 0, flows: [] });

  const eyebrowStyle = {
    color: 'var(--cam-text-inactive)', fontSize: 'var(--fs-eyebrow)',
    fontWeight: 'var(--fw-semibold)', textTransform: 'uppercase',
    letterSpacing: 'var(--track-eyebrow)', marginBottom: 'var(--space-4)',
  };
  const inputs = ['Commercial DNA', 'Brand guidelines', 'Brand DNA'];
  const quoteStyle = {
    margin: 0, fontFamily: 'var(--font-serif)', fontStyle: 'italic',
    fontSize: 'var(--fs-lead)', color: 'var(--cam-text-secondary)',
    lineHeight: 1.4, letterSpacing: 0,
  };

  React.useEffect(() => {
    const box = boxRef.current;
    if (!box) return;
    const measure = () => {
      const b = box.getBoundingClientRect();
      const mark = markRef.current;
      const pr = pillRefs.current.map((el) => (el ? el.getBoundingClientRect() : null));
      if (!b.width || !mark || pr.some((r) => !r)) return;
      const m = mark.getBoundingClientRect();
      const cx = m.left + m.width / 2 - b.left;
      const ty = m.top - b.top - 14;              /* flows end just above the wordmark */
      const tips = [cx - 30, cx, cx + 30];        /* three converging entry points */
      const R = 14;                               /* corner radius of the bends */
      const flows = [];
      /* left pill — leaves its right edge, runs, bends down */
      {
        const sx = pr[0].right - b.left + 8, sy = pr[0].top + pr[0].height / 2 - b.top;
        flows.push({ d: `M ${sx} ${sy} H ${tips[0] - R} Q ${tips[0]} ${sy} ${tips[0]} ${sy + R} V ${ty}`, x: tips[0] });
      }
      /* center pill — straight vertical drop */
      {
        const sy = pr[1].bottom - b.top + 8;
        flows.push({ d: `M ${tips[1]} ${sy} V ${ty}`, x: tips[1] });
      }
      /* right pill — leaves its left edge, runs, bends down */
      {
        const sx = pr[2].left - b.left - 8, sy = pr[2].top + pr[2].height / 2 - b.top;
        flows.push({ d: `M ${sx} ${sy} H ${tips[2] + R} Q ${tips[2]} ${sy} ${tips[2]} ${sy + R} V ${ty}`, x: tips[2] });
      }
      setGeom({ w: b.width, h: b.height, flows, ty });
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(box);
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(measure);
    return () => ro.disconnect();
  }, []);

  return (
    <section id="solution" data-screen-label="The Solution" style={{ background: 'var(--cam-surface-section)', borderTop: '1px solid var(--cam-border-subtle)' }}>
      <div style={{ maxWidth: 'var(--page-max)', margin: '0 auto', padding: 'var(--section-pad) var(--page-gutter)' }}>
        <div className="lp-reveal">
          <div style={eyebrowStyle}>The Solution</div>
          <h2 style={{
            margin: 0, fontSize: 'var(--fs-h1)', fontWeight: 'var(--fw-black)',
            letterSpacing: 'var(--track-display)', lineHeight: 'var(--lh-snug)',
            color: 'var(--cam-text-primary)', maxWidth: '24ch',
          }}>Access <a href="https://app.cammusai.com" style={{
            color: 'inherit', textDecoration: 'underline',
            textUnderlineOffset: '0.16em', textDecorationThickness: '3px',
            textDecorationColor: 'var(--cam-border-strong)',
          }}>app.cammusai.com</a></h2>
          <p style={{
            margin: 'var(--space-5) 0 0', fontSize: 'var(--fs-lead)',
            color: 'var(--cam-text-secondary)', letterSpacing: 'var(--track-text)',
            lineHeight: 1.5, maxWidth: '58ch',
          }}>We onboard your company in 5 minutes, and you're ready to post.</p>
        </div>

        {/* Funnel: inputs ⇢ Cammus Intelligence → database */}
        <div ref={boxRef} className="lp-fun lp-group" style={{ marginTop: 'var(--space-9)' }}
          aria-label="Commercial DNA, brand guidelines and brand DNA flow into Cammus Intelligence, which stores your database, ready to produce content">

          {/* Dotted data flows (desktop) — measured, marching toward the wordmark */}
          <svg className="lp-desk" aria-hidden="true" viewBox={'0 0 ' + (geom.w || 1) + ' ' + (geom.h || 1)}
            preserveAspectRatio="none"
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', display: 'block', pointerEvents: 'none' }}>
            {geom.flows.map((f, i) => (
              <g key={i} className="lp-fade" style={{ '--d': (0.4 + i * 0.14) + 's' }}>
                <path className="lp-dotflow" d={f.d} fill="none" stroke={FLOW}
                  strokeWidth="2" strokeLinecap="round" strokeDasharray="0.1 6" />
                <polygon className="lp-fade" style={{ '--d': (0.85 + i * 0.1) + 's' }}
                  points={`${f.x - 4},${geom.ty} ${f.x + 4},${geom.ty} ${f.x},${geom.ty + 7}`} fill={FLOW} />
              </g>
            ))}
          </svg>

          {/* The three brand inputs */}
          <div className="lp-fun-row">
            {inputs.map((label, i) => (
              <span key={label} ref={(el) => { pillRefs.current[i] = el; }}
                className={'lp-pop' + (i !== 1 ? ' lp-fun-side' : '')}
                style={{ '--d': (0.05 + i * 0.12) + 's', display: 'inline-flex' }}>
                <Pill style={{ background: 'var(--cam-surface-section)' }}>{label}</Pill>
              </span>
            ))}
          </div>

          {/* Mobile connector — simple dotted drop */}
          <div className="lp-mob lp-fade" aria-hidden="true" style={{ '--d': '0.4s', flexDirection: 'column', alignItems: 'center', marginTop: 'var(--space-4)' }}>
            <span style={{ width: 0, height: 34, borderLeft: '2px dotted ' + FLOW }} />
            <span style={{
              width: 0, height: 0, borderLeft: '5px solid transparent',
              borderRight: '5px solid transparent', borderTop: '7px solid ' + FLOW,
            }} />
          </div>

          {/* Cammus Intelligence */}
          <div ref={markRef} className="lp-fun-gap lp-pop" style={{
            '--d': '1.05s', display: 'flex', flexDirection: 'column',
            alignItems: 'center', gap: 'var(--space-3)', width: 'fit-content',
            margin: '96px auto 0',
          }}>
            <Wordmark height={46} />
            <span style={{
              color: 'var(--cam-text-auxiliary)', fontSize: 'var(--fs-eyebrow)',
              fontWeight: 'var(--fw-semibold)', textTransform: 'uppercase',
              letterSpacing: 'var(--track-eyebrow)',
            }}>Intelligence</span>
          </div>

          {/* THE lime signal — the arrow */}
          <div aria-hidden="true" style={{ marginTop: 'var(--space-5)', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <span className="lp-cline-y" style={{ '--d': '1.3s', width: 4, height: 42, borderRadius: 2, background: 'var(--cam-accent-lime)' }} />
            <span className="lp-fade" style={{
              '--d': '1.5s', width: 0, height: 0, marginTop: -1,
              borderLeft: '8px solid transparent', borderRight: '8px solid transparent',
              borderTop: '10px solid var(--cam-accent-lime)',
            }} />
          </div>

          {/* The database */}
          <div style={{ marginTop: 'var(--space-5)', display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', columnGap: 'var(--space-6)' }}>
            <span aria-hidden="true" />
            <div className="lp-pop" style={{
              '--d': '1.6s', display: 'flex', alignItems: 'center', gap: 'var(--space-4)',
              background: 'var(--cam-surface-card)', border: '1px solid var(--cam-border-subtle)',
              borderRadius: 'var(--radius-card)', padding: 'var(--space-4) var(--space-6)',
            }}>
              <DbIcon />
              <span style={{ color: 'var(--cam-text-primary)', fontWeight: 'var(--fw-semibold)', fontSize: '1rem', letterSpacing: 'var(--track-text)' }}>We store the database</span>
            </div>
            <div className="lp-item" style={{ '--d': '1.85s', display: 'flex', alignItems: 'center', gap: 'var(--space-3)', justifySelf: 'start' }}>
              <TriRight />
              <span className="lp-fun-ready" style={{ color: 'var(--cam-text-primary)', fontWeight: 'var(--fw-semibold)', fontSize: 'var(--fs-small)', letterSpacing: 'var(--track-text)' }}>Ready to produce content</span>
            </div>
          </div>
        </div>

        {/* Inside the platform — one input, every format */}
        <div className="lp-reveal" style={{ marginTop: 'var(--beat-gap)' }}>
          <div style={eyebrowStyle}>Inside the platform</div>
          <h3 style={{
            margin: 0, fontSize: 'var(--fs-h2)', fontWeight: 'var(--fw-black)',
            letterSpacing: 'var(--track-display)', lineHeight: 'var(--lh-snug)',
            color: 'var(--cam-text-primary)',
          }}>One input. Every format.</h3>
        </div>
        <ChatDemo />

        {/* THE RESULTS — real assets, attached as delivered */}
        <ResultsShowcase />

        {/* THE SYSTEM — post, track, and the loop keeps producing */}
        <div className="lp-reveal" style={{ marginTop: 'var(--beat-gap)' }}>
          <div style={eyebrowStyle}>The System</div>
          <h3 style={{
            margin: 0, fontSize: 'var(--fs-h2)', fontWeight: 'var(--fw-black)',
            letterSpacing: 'var(--track-display)', lineHeight: 'var(--lh-snug)',
            color: 'var(--cam-text-primary)',
          }}>Now, simply post and track performance.</h3>
          <p style={{
            margin: 'var(--space-4) 0 0', fontSize: 'var(--fs-lead)',
            color: 'var(--cam-text-secondary)', letterSpacing: 'var(--track-text)',
            lineHeight: 1.5, maxWidth: '58ch',
          }}>And the system keeps working...</p>
        </div>
        <SystemLoop />
      </div>
    </section>
  );
}
window.SolutionSection = SolutionSection;
