// Luxury "How it works" — stacking sticky cards with animated icons.
// Each card sticks at the top, then the next slides up over it as you scroll.

const STEPS = [
  {
    n: '01',
    t: '00:00',
    eyebrow: 'Step one · Connect',
    h: <>Connect your <em>storage.</em></>,
    p: 'Connect any major cloud storage — or drag a folder in. We index in place. Your documents never leave your tenant, never train a model, never travel between regions.',
    points: ['One-click connectors to 12 storage backends', 'Index lives in your region', 'Zero document copies — read-only by default'],
    accent: '#1f3a30',
    icon: 'connect',
  },
  {
    n: '02',
    t: '00:08',
    eyebrow: 'Step two · Extract',
    h: <>The first <em>document</em> indexes in 1.2s.</>,
    p: 'Our compliance-tuned AI reads each contract for parties, dates, clauses, signatures, and obligations. Everything is indexed into a domain-specific knowledge base for compliance-aware search. By the time you refill coffee, the first hundred are searchable.',
    points: ['Extracts 47 entity types per document automatically', '1.2s median time to indexed & searchable', 'Compliance-specific confidence grading — flagged below 0.85'],
    accent: '#14110e',
    icon: 'extract',
  },
  {
    n: '03',
    t: '00:42',
    eyebrow: 'Step three · Score',
    h: <>Every vendor, <em>scored.</em></>,
    p: 'Each vendor is scored from twelve weighted factors — coverage, renewals, audits, and more. AI detects risk impact and compliance gaps automatically. Threshold alerts wire to chat, email, or webhook.',
    points: ['0–100 composite score, drillable to each factor', 'AI-driven risk impact detection, live as documents change', 'Routes to chat, email, or any webhook'],
    accent: '#a8854a',
    icon: 'score',
  },
  {
    n: '04',
    t: '01:30',
    eyebrow: 'Step four · Build',
    h: <>The graph <em>builds itself.</em></>,
    p: 'A live knowledge graph links entities to documents, documents to vendors, vendors to regulations. Compliance lineage is mapped automatically. Pull one node — see the full picture. Diff against last quarter.',
    points: ['447 nodes / 1,128 edges in a typical portfolio', 'Time-travel diff against any prior snapshot', 'Exports to JSON, RDF, or visual report'],
    accent: '#5a8470',
    icon: 'graph',
  },
  {
    n: '05',
    t: '04:00',
    eyebrow: 'Step five · Ask',
    h: <>Ask the Compliance Copilot <em>anything.</em></>,
    p: 'Natural-language Q&A grounded in your documents and a compliance-specific knowledge base. Understands gaps, cites source clauses, and refuses when evidence is thin. The afternoon you started — you are done.',
    points: ['Cited answers in 1.4s median', 'Refuses gracefully when sources are thin', 'Saves frequent queries as named reports'],
    accent: '#7d2e3a',
    icon: 'copilot',
  },
];

// ===========================================================================
// Animated icons — each plays when its card is the "active" sticky.
// ===========================================================================
const HiwIcon = ({ kind, live }) => {
  const cls = `ccl-hiw-icon ccl-hiw-icon-${kind} ${live ? 'live' : ''}`;
  if (kind === 'connect') {
    return (
      <svg className={cls} viewBox="0 0 240 200" preserveAspectRatio="xMidYMid meet">
        {/* Cloud sources */}
        {[
          { x: 30,  y: 30,  l: 'Cloud' },
          { x: 30,  y: 90,  l: 'SaaS' },
          { x: 30,  y: 150, l: 'Local' },
        ].map((s, i) => (
          <g key={s.l} className="hiw-src" style={{ '--d': `${100 + i * 140}ms` }}>
            <rect x={s.x} y={s.y} width="56" height="34" rx="6"
                  fill="var(--ccl-paper)" stroke="var(--ccl-line)" strokeWidth="1.2"/>
            <text x={s.x + 28} y={s.y + 22} textAnchor="middle"
                  fontFamily="var(--ccl-mono)" fontSize="11" fontWeight="500"
                  letterSpacing="1.2" fill="var(--ccl-ink)">{s.l.toUpperCase()}</text>
          </g>
        ))}
        {/* Wires */}
        <g className="hiw-wires">
          <path d="M86 47 C 130 47, 130 100, 174 100" stroke="#1f3a30" strokeWidth="1.4" fill="none" pathLength="1" className="hiw-wire" style={{ '--d': '600ms' }}/>
          <path d="M86 107 L 174 100" stroke="#1f3a30" strokeWidth="1.4" fill="none" pathLength="1" className="hiw-wire" style={{ '--d': '750ms' }}/>
          <path d="M86 167 C 130 167, 130 100, 174 100" stroke="#1f3a30" strokeWidth="1.4" fill="none" pathLength="1" className="hiw-wire" style={{ '--d': '900ms' }}/>
        </g>
        {/* Hub */}
        <g className="hiw-hub">
          <circle cx="174" cy="100" r="30" fill="none" stroke="#1f3a30" strokeWidth="1" opacity="0.25" className="hiw-hub-halo"/>
          <circle cx="174" cy="100" r="20" fill="#1f3a30"/>
          <text x="174" y="105" textAnchor="middle" fontFamily="var(--ccl-display)" fontWeight="600" fontSize="14" fill="#f1ede3" fontStyle="italic">cc</text>
        </g>
        {/* Pulses traveling inward */}
        {live && (
          <>
            <circle r="3" fill="#5a8470">
              <animateMotion dur="1.8s" begin="1.0s" repeatCount="indefinite" path="M86 47 C 130 47, 130 100, 174 100"/>
            </circle>
            <circle r="3" fill="#5a8470">
              <animateMotion dur="1.8s" begin="1.6s" repeatCount="indefinite" path="M86 107 L 174 100"/>
            </circle>
            <circle r="3" fill="#5a8470">
              <animateMotion dur="1.8s" begin="2.2s" repeatCount="indefinite" path="M86 167 C 130 167, 130 100, 174 100"/>
            </circle>
          </>
        )}
      </svg>
    );
  }
  if (kind === 'extract') {
    return (
      <svg className={cls} viewBox="0 0 240 200" preserveAspectRatio="xMidYMid meet">
        {/* Document */}
        <g className="hiw-doc">
          <rect x="60" y="22" width="120" height="156" rx="8"
                fill="var(--ccl-paper)" stroke="var(--ccl-line)" strokeWidth="1.2"/>
          <text x="120" y="46" textAnchor="middle" fontFamily="var(--ccl-mono)" fontSize="9" letterSpacing="1.4" fill="var(--ccl-mute)">MSA · 0418</text>
          {/* Body lines */}
          {[58, 70, 82, 94, 106, 118, 130, 142, 154].map((y, i) => {
            const w = [104, 96, 88, 100, 84, 96, 70, 92, 76][i];
            const lit = [1, 3, 6].includes(i);
            return (
              <rect key={y} x={68} y={y} width={w} height="3.6" rx="2"
                    className={`hiw-line ${lit ? 'lit' : ''}`}
                    style={{ '--d': `${600 + (lit ? [0,1,2][[1,3,6].indexOf(i)] * 280 : 0)}ms` }}/>
            );
          })}
        </g>
        {/* Scan bar */}
        <rect className="hiw-scan" x="60" y="22" width="120" height="14" rx="2" fill="rgba(31,58,48,0.18)" stroke="rgba(31,58,48,0.5)" strokeWidth="1"/>
        {/* Output chips */}
        <g className="hiw-chips">
          {[
            { y: 50, l: 'PARTY · Harbor', d: '900ms', c: '#1f3a30' },
            { y: 80, l: 'TERM · 36 mo',  d: '1180ms', c: '#1f3a30' },
            { y: 110, l: 'EXPIRES · 09/26', d: '1460ms', c: '#1f3a30' },
          ].map(c => (
            <g key={c.l} className="hiw-chip" style={{ '--d': c.d }}>
              <rect x="186" y={c.y} width="60" height="20" rx="10" fill="var(--ccl-paper)" stroke={c.c} strokeWidth="1"/>
              <text x="216" y={c.y + 14} textAnchor="middle" fontFamily="var(--ccl-mono)" fontSize="8" fontWeight="500" letterSpacing="0.8" fill={c.c}>{c.l}</text>
            </g>
          ))}
        </g>
      </svg>
    );
  }
  if (kind === 'score') {
    const r = 64, c = 2 * Math.PI * r;
    return (
      <svg className={cls} viewBox="0 0 240 200" preserveAspectRatio="xMidYMid meet">
        <g transform="translate(120 100)">
          {/* Tick marks */}
          {Array.from({length: 24}).map((_, i) => {
            const a = (i / 24) * Math.PI * 2 - Math.PI / 2;
            const x1 = Math.cos(a) * 76, y1 = Math.sin(a) * 76;
            const x2 = Math.cos(a) * 82, y2 = Math.sin(a) * 82;
            return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke="var(--ccl-line)" strokeWidth="1"/>;
          })}
          {/* Background ring */}
          <circle r={r} fill="none" stroke="#e6dfcf" strokeWidth="8"/>
          {/* Progress ring — drawn via stroke-dashoffset */}
          <circle r={r} fill="none" stroke="#a8854a" strokeWidth="8"
                  strokeLinecap="round"
                  strokeDasharray={c}
                  strokeDashoffset={c}
                  transform="rotate(-90)"
                  className="hiw-ring"
                  style={{ '--c': c }}/>
          {/* Score */}
          <text textAnchor="middle" y="6" fontFamily="var(--ccl-display)" fontStyle="italic" fontWeight="500" fontSize="44" letterSpacing="-0.04em" fill="var(--ccl-ink)" className="hiw-score-num">86</text>
          <text textAnchor="middle" y="28" fontFamily="var(--ccl-mono)" fontSize="9" letterSpacing="1.4" fill="var(--ccl-mute)">VENDOR SCORE</text>
        </g>
        {/* Factor labels */}
        {[
          { x: 14,  y: 36,  l: 'Coverage' },
          { x: 178, y: 36,  l: 'Renewals' },
          { x: 14,  y: 174, l: 'Audits' },
          { x: 178, y: 174, l: 'Doc gaps' },
        ].map((f, i) => (
          <g key={f.l} className="hiw-factor" style={{ '--d': `${600 + i * 140}ms` }}>
            <text x={f.x} y={f.y} fontFamily="var(--ccl-mono)" fontSize="9" letterSpacing="1.2" fill="var(--ccl-mute)">{f.l.toUpperCase()}</text>
          </g>
        ))}
      </svg>
    );
  }
  if (kind === 'graph') {
    const nodes = [
      { x: 120, y: 100, r: 16, big: true },
      { x: 50,  y: 40, r: 8 },
      { x: 190, y: 40, r: 8 },
      { x: 50,  y: 160, r: 8 },
      { x: 190, y: 160, r: 8 },
      { x: 30,  y: 100, r: 5 },
      { x: 210, y: 100, r: 5 },
      { x: 120, y: 20, r: 5 },
      { x: 120, y: 180, r: 5 },
    ];
    const edges = nodes.slice(1).map(n => ({ x: n.x, y: n.y }));
    return (
      <svg className={cls} viewBox="0 0 240 200" preserveAspectRatio="xMidYMid meet">
        {edges.map((n, i) => (
          <line key={i}
                x1="120" y1="100" x2={n.x} y2={n.y}
                stroke="#c8c0ad" strokeWidth="1.2"
                pathLength="1"
                className="hiw-edge"
                style={{ '--d': `${300 + i * 100}ms` }}/>
        ))}
        {nodes.map((n, i) => (
          <g key={i} className="hiw-node" style={{ '--d': `${500 + i * 90}ms` }}>
            {n.big && (
              <circle cx={n.x} cy={n.y} r={n.r + 10} fill="none" stroke="#5a8470" strokeWidth="1" className="hiw-node-halo"/>
            )}
            <circle cx={n.x} cy={n.y} r={n.r} fill={n.big ? '#5a8470' : '#14110e'}/>
          </g>
        ))}
        {live && (
          <circle r="3" fill="#a8854a">
            <animateMotion dur="4s" repeatCount="indefinite"
              path="M120 100 L50 40 L120 100 L190 40 L120 100 L190 160 L120 100 L50 160 L120 100"/>
          </circle>
        )}
      </svg>
    );
  }
  if (kind === 'copilot') {
    return (
      <svg className={cls} viewBox="0 0 240 200" preserveAspectRatio="xMidYMid meet">
        {/* User bubble */}
        <g className="hiw-bubble hiw-bubble-1" style={{ '--d': '300ms' }}>
          <rect x="76" y="22" width="148" height="36" rx="10" fill="#dcd4be"/>
          <text x="86" y="42" fontFamily="var(--ccl-body)" fontSize="11" fill="var(--ccl-ink)" fontWeight="500">Show overdue audits ↗</text>
          <text x="86" y="54" fontFamily="var(--ccl-mono)" fontSize="8" letterSpacing="1.1" fill="var(--ccl-mute)">YOU</text>
        </g>
        {/* Thinking dots */}
        <g className="hiw-bubble hiw-thinking" style={{ '--d': '900ms' }}>
          <circle cx="22" cy="86" r="3.5" fill="#1f3a30" className="hiw-dot-1"/>
          <circle cx="34" cy="86" r="3.5" fill="#1f3a30" className="hiw-dot-2"/>
          <circle cx="46" cy="86" r="3.5" fill="#1f3a30" className="hiw-dot-3"/>
        </g>
        {/* Answer bubble */}
        <g className="hiw-bubble hiw-bubble-2" style={{ '--d': '1700ms' }}>
          <rect x="16" y="110" width="180" height="72" rx="10" fill="var(--ccl-ink)"/>
          <text x="26" y="130" fontFamily="var(--ccl-mono)" fontSize="8" letterSpacing="1.3" fill="rgba(241,237,227,0.6)">COMPLYCHIP · 1.4S · 7 SOURCES</text>
          <text x="26" y="148" fontFamily="var(--ccl-body)" fontSize="11" fill="#f1ede3" fontWeight="500">3 audits past due:</text>
          <text x="26" y="162" fontFamily="var(--ccl-body)" fontSize="10.5" fill="rgba(241,237,227,0.78)">Harbor · 12d · OSHA</text>
          <text x="26" y="174" fontFamily="var(--ccl-body)" fontSize="10.5" fill="rgba(241,237,227,0.78)">University · 18d · DPA</text>
        </g>
      </svg>
    );
  }
  return null;
};

// ===========================================================================
// Stacking sticky cards section
// ===========================================================================
const LHowItWorks = () => {
  const sectionRef = React.useRef(null);
  const [active, setActive] = React.useState(0);

  React.useEffect(() => {
    let raf = 0;
    const update = () => {
      raf = 0;
      const cards = sectionRef.current?.querySelectorAll('.ccl-hiw-card');
      if (!cards || !cards.length) return;
      const vh = window.innerHeight;
      // The card whose top is closest to (but past) 30% of the viewport is "active"
      let best = 0;
      let bestDist = Infinity;
      cards.forEach((c, i) => {
        const r = c.getBoundingClientRect();
        const dist = Math.abs(r.top - vh * 0.30);
        if (r.top < vh * 0.55 && dist < bestDist) {
          bestDist = dist;
          best = i;
        }
      });
      setActive(best);
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    update();
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <section className="ccl-section ccl-hiw" id="how" ref={sectionRef}>
      <div className="ccl-wrap">
        <div className="ccl-section-head">
          <div className="ccl-eyebrow"><span className="ccl-eyebrow-num">→</span>How it works</div>
          <h2 className="ccl-h2" style={{ marginTop: 24 }}>
            From folder of PDFs<br/>to <em>indexed portfolio,</em> in one afternoon.
          </h2>
          <p className="ccl-lede">
            No migration team. No six-week implementation. Connect storage, point at your folders, watch the graph build itself.
          </p>
        </div>

        <div className="ccl-hiw-grid">
          {/* Left rail — index */}
          <aside className="ccl-hiw-rail" aria-hidden="true">
            <div className="ccl-hiw-rail-inner">
              <div className="ccl-hiw-rail-eb">PROGRESS</div>
              {STEPS.map((s, i) => (
                <button
                  key={s.n}
                  className={`ccl-hiw-rail-row ${i === active ? 'on' : ''} ${i < active ? 'past' : ''}`}
                  onClick={() => {
                    const cards = sectionRef.current?.querySelectorAll('.ccl-hiw-card');
                    const el = cards?.[i];
                    if (el) {
                      const r = el.getBoundingClientRect();
                      window.scrollTo({ top: window.scrollY + r.top - 60, behavior: 'smooth' });
                    }
                  }}
                >
                  <span className="ccl-hiw-rail-n">{s.n}</span>
                  <span className="ccl-hiw-rail-name">{s.eyebrow.split(' · ')[1]}</span>
                  <span className="ccl-hiw-rail-t">{s.t}</span>
                </button>
              ))}
              <div className="ccl-hiw-rail-track">
                <div
                  className="ccl-hiw-rail-fill"
                  style={{ height: `${(active / Math.max(1, STEPS.length - 1)) * 100}%` }}
                />
              </div>
            </div>
          </aside>

          {/* Stacking cards */}
          <div className="ccl-hiw-stack">
            {STEPS.map((s, i) => (
              <article
                key={s.n}
                className={`ccl-hiw-card ${i === active ? 'is-active' : ''}`}
                style={{
                  '--i': i,
                  '--accent': s.accent,
                  zIndex: i + 1,
                  top: `${80 + i * 12}px`,
                }}
              >
                <div className="ccl-hiw-card-inner">
                  <div className="ccl-hiw-card-meta">
                    <span className="ccl-hiw-card-n">{s.n}</span>
                    <span className="ccl-hiw-card-time">T+{s.t}</span>
                  </div>

                  <div className="ccl-hiw-card-body">
                    <div className="ccl-hiw-card-text">
                      <div className="ccl-eyebrow">{s.eyebrow}</div>
                      <h3 className="ccl-hiw-card-h">{s.h}</h3>
                      <p className="ccl-hiw-card-p">{s.p}</p>
                      <ul className="ccl-hiw-card-list">
                        {s.points.map(pt => (
                          <li key={pt}>
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                              <path d="M5 12l5 5L20 7" strokeLinecap="round" strokeLinejoin="round"/>
                            </svg>
                            <span>{pt}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                    <div className="ccl-hiw-card-vis">
                      <HiwIcon kind={s.icon} live={i === active}/>
                    </div>
                  </div>
                </div>
              </article>
            ))}
            {/* Spacer so the last card has runout */}
            <div className="ccl-hiw-spacer" aria-hidden="true"/>
          </div>
        </div>
      </div>
    </section>
  );
};

window.LHowItWorks = LHowItWorks;
