// Pinned horizontal-scroll PRODUCT section (acceler8-style)
// Five capability slides, each with its own intuitive animated visual.
// Slide becomes "live" when active — animations key off that class.

const CAPS = [
  {
    n: '01',
    name: 'Intake',
    eyebrow: 'Document intake · Auto-extraction',
    h: <>Drop a contract.<br/>Watch every <em>field populate.</em></>,
    body: 'Upload PDFs, connect cloud storage, or hit the API. Our compliance AI parses entities, dates, parties, and clauses — then indexes them into a structured knowledge base. You move on.',
    feats: [
      'Reads NDAs, MSAs, SOWs, certificates, and audits out of the box',
      'Extracts 47 entity types with compliance-tuned reasoning',
      '1.2 second median time to indexed and searchable',
    ],
  },
  {
    n: '02',
    name: 'Risk',
    eyebrow: 'Vendor risk · Composite scoring',
    h: <>Know which vendors<br/>are <em>a problem</em> first.</>,
    body: 'Every vendor scored 0–100 across twelve weighted factors — compliance gaps, missing documents, contract value, and renewal posture. Risk impact updates live as documents process.',
    feats: [
      'Composite scoring across 12 weighted factors',
      'AI-driven risk impact detection per vendor',
      'Threshold alerts route to chat, email, or webhook',
    ],
  },
  {
    n: '03',
    name: 'Compliance Copilot',
    eyebrow: 'Compliance Copilot · grounded answers over your corpus',
    h: <>Ask your compliance<br/>data <em>anything.</em></>,
    body: 'Natural-language Q&A grounded in your own documents and a compliance-specific knowledge base. Cites source clauses, understands gaps, and refuses when evidence is thin. No hallucinations.',
    feats: [
      'Cited answers in 1.4s median',
      'Refuses gracefully when sources are thin',
      'Saves frequent queries as named reports',
    ],
  },
  {
    n: '04',
    name: 'Workflows',
    eyebrow: 'Workflows · AI-native pipelines',
    h: <>Compliance that<br/><em>runs itself.</em></>,
    body: 'Purpose-built workflows handle intake, gap detection, risk scoring, vendor enrichment, reminders, and graph rebuilds. Pipelines that solve for compliance gaps — not generic automation retrofitted.',
    feats: [
      '60+ purpose-built nodes for compliance workflows',
      'AI detects compliance gaps and triggers remediation',
      'Full audit trail with replay & rollback',
    ],
  },
  {
    n: '05',
    name: 'Graph',
    eyebrow: 'Knowledge graph · Live connections',
    h: <>See how<br/><em>everything</em> connects.</>,
    body: 'A live knowledge graph linking entities, documents, vendors, and regulations. One vendor failing an audit shows you every contract and jurisdiction it touches — automatically.',
    feats: [
      '447 nodes, 1,128 edges in a typical mid-market portfolio',
      'Click any node — see contracts, controls, history',
      'Diff over time — what changed since last audit',
    ],
  },
];

// ===========================================================================
// VISUAL 1 · INTAKE — scan beam + field highlight + JSON typewriter
// ===========================================================================
const VisIntake = ({ live }) => {
  const lits = [1, 4, 6, 8, 10];
  const tags = ['Party', 'Date', 'Term', 'Confidentiality', 'Signature'];
  return (
    <div className={`ccl-vis ccl-vis-intake ${live ? 'live' : ''}`}>
      <div className="ccl-vis-intake-doc">
        <div className="ccl-vis-mono">NDA-0418.PDF · 6 PAGES</div>
        <div className="ccl-vis-doc-title">NON-DISCLOSURE AGREEMENT</div>
        <div className="ccl-vis-doc-lines">
          {[100, 92, 70, 96, 80, 88, 94, 70, 90, 84, 76, 90, 72, 88].map((w, i) => {
            const litI = lits.indexOf(i);
            const lit = litI > -1;
            return (
              <div
                key={i}
                className={`ccl-vis-doc-line ${lit ? 'lit' : ''}`}
                style={{ '--w': `${w}%`, '--d': `${600 + (lit ? litI * 220 : 0)}ms` }}
              >
                {lit && <span className="ccl-vis-doc-tag">{tags[litI]}</span>}
              </div>
            );
          })}
        </div>
        <div className="ccl-vis-scan"/>
      </div>
      <div className="ccl-vis-intake-out">
        <div className="ccl-vis-out-eb">EXTRACTED · AI</div>
        <pre className="ccl-vis-json">{`{
  "entity":     "Harbor Industrial",
  "type":       "NDA",
  "expires":    "2026-09-12",
  "parties":    [2],
  "risk":       "low",
  "confidence": 0.97
}`}</pre>
        <div className="ccl-vis-out-status">
          <span className="ccl-vis-out-dot"/>INDEXED · 1.2s
        </div>
      </div>
    </div>
  );
};

// ===========================================================================
// VISUAL 2 · RISK — distribution + animated vendor bars
// ===========================================================================
const VisRisk = ({ live }) => {
  const vendors = [
    { n: 'BuildRight Co.', s: 91, t: '#5a8470', tag: 'Healthy' },
    { n: 'Anchor Materials', s: 86, t: '#5a8470', tag: 'Healthy' },
    { n: 'Clearwater Logistics', s: 78, t: '#a8854a', tag: 'Watch' },
    { n: 'Meridian Tech', s: 69, t: '#a8854a', tag: 'Watch' },
    { n: 'Northgate Holdings', s: 54, t: '#7d2e3a', tag: 'Action' },
    { n: 'Summit Partners', s: 42, t: '#7d2e3a', tag: 'Action' },
  ];
  const dist = [8, 14, 26, 30, 18, 6];
  return (
    <div className={`ccl-vis ccl-vis-risk ${live ? 'live' : ''}`}>
      <div className="ccl-vis-risk-head">
        <span>200 Vendors · sorted by risk</span>
        <span>Q2 2026</span>
      </div>
      <div className="ccl-vis-risk-dist">
        {dist.map((h, i) => (
          <span
            key={i}
            className="ccl-vis-risk-bar"
            style={{ '--h': `${h * 1.8}px`, '--d': `${i * 80}ms` }}
          />
        ))}
      </div>
      <div className="ccl-vis-risk-rows">
        {vendors.map((v, i) => (
          <div
            key={v.n}
            className="ccl-vis-risk-row"
            style={{ '--d': `${300 + i * 120}ms`, '--t': v.t }}
          >
            <span className="ccl-vis-risk-name">{v.n}</span>
            <span className="ccl-vis-risk-track">
              <span className="ccl-vis-risk-fill" style={{ '--w': `${v.s}%` }}/>
            </span>
            <span className="ccl-vis-risk-tag" style={{ color: v.t, borderColor: v.t + '50' }}>
              {v.tag}
            </span>
            <span className="ccl-vis-risk-score" style={{ color: v.t }}>{v.s}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// ===========================================================================
// VISUAL 3 · COPILOT — Q types → thinking → cited answer reveals
// ===========================================================================
const VisCopilot = ({ live }) => {
  const rows = [
    { g: 'Missing OSHA cert', e: 'Harbor Industrial', t: '#7d2e3a', l: 'High', src: 'audit-log#412' },
    { g: 'Expired DPA', e: 'University Campus', t: '#7d2e3a', l: 'High', src: 'contracts#88' },
    { g: 'Workers Comp expires 9d', e: 'Riverside Medical', t: '#a8854a', l: 'Med', src: 'docs#1204' },
  ];
  return (
    <div className={`ccl-vis ccl-vis-copilot ${live ? 'live' : ''}`}>
      <div className="ccl-vis-cp-q">
        <div className="ccl-vis-out-eb">You</div>
        <div className="ccl-vis-cp-qtext">
          <span>What are the top compliance gaps across all entities?</span>
        </div>
      </div>
      <div className="ccl-vis-cp-think">
        <span/><span/><span/>
        <em>ComplyChip is reading 287 documents…</em>
      </div>
      <div className="ccl-vis-cp-a">
        <div className="ccl-vis-cp-ahead">
          <span>ComplyChip · 1.4s</span>
          <span>23 sources cited</span>
        </div>
        <div className="ccl-vis-cp-aintro">
          Three gaps stand out — two critical, one watchpoint:
        </div>
        {rows.map((r, i) => (
          <div
            key={r.g}
            className="ccl-vis-cp-row"
            style={{ '--d': `${2900 + i * 180}ms` }}
          >
            <span>
              <strong>{r.g}</strong>
              <em>{r.e}</em>
            </span>
            <span className="ccl-vis-cp-src">{r.src}</span>
            <span
              className="ccl-vis-cp-tag"
              style={{ color: r.t, borderColor: r.t + '50' }}
            >{r.l}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// ===========================================================================
// VISUAL 4 · WORKFLOWS — pipeline with traveling data dots
// ===========================================================================
const VisWorkflow = ({ live }) => {
  const nodes = [
    { x: 195, y: 30, l: 'Ingest', s: 'PDF · Cloud · API', i: 0 },
    { x: 65, y: 140, l: 'Extract', s: 'AI parser', i: 1 },
    { x: 325, y: 140, l: 'Score', s: 'Composite', i: 2, hot: true },
    { x: 65, y: 240, l: 'Notify', s: 'Chat · Email', i: 3 },
    { x: 325, y: 240, l: 'Graph', s: 'Vector index', i: 4 },
  ];
  return (
    <div className={`ccl-vis ccl-vis-flow ${live ? 'live' : ''}`}>
      <div className="ccl-vis-flow-head">
        <span>Pipeline · Workflow engine</span>
        <span className="ccl-vis-flow-status"><i/>RUNNING · 28 events/min</span>
      </div>
      <svg viewBox="0 0 480 312" className="ccl-vis-flow-svg" preserveAspectRatio="xMidYMid meet">
        <defs>
          <marker id="arF" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto">
            <path d="M0 0L8 4L0 8z" fill="#56503f"/>
          </marker>
          <path id="pA" d="M225 80 L110 140"/>
          <path id="pB" d="M285 80 L370 140"/>
          <path id="pC" d="M110 190 L110 240"/>
          <path id="pD" d="M370 190 L370 240"/>
        </defs>

        {/* Edges */}
        <path d="M225 80 L110 140" stroke="#c8c0ad" strokeWidth="1.4" fill="none" markerEnd="url(#arF)"/>
        <path d="M285 80 L370 140" stroke="#c8c0ad" strokeWidth="1.4" fill="none" markerEnd="url(#arF)"/>
        <path d="M110 190 L110 240" stroke="#c8c0ad" strokeWidth="1.4" fill="none" markerEnd="url(#arF)"/>
        <path d="M370 190 L370 240" stroke="#c8c0ad" strokeWidth="1.4" fill="none" markerEnd="url(#arF)"/>

        {/* Traveling data dots — continuous flow */}
        <circle r="4" fill="#1f3a30">
          <animateMotion dur="2.4s" repeatCount="indefinite"><mpath href="#pA"/></animateMotion>
        </circle>
        <circle r="4" fill="#1f3a30">
          <animateMotion dur="2.4s" begin="0.7s" repeatCount="indefinite"><mpath href="#pB"/></animateMotion>
        </circle>
        <circle r="3.4" fill="#a8854a">
          <animateMotion dur="2.1s" begin="0.4s" repeatCount="indefinite"><mpath href="#pC"/></animateMotion>
        </circle>
        <circle r="3.4" fill="#a8854a">
          <animateMotion dur="2.1s" begin="1.1s" repeatCount="indefinite"><mpath href="#pD"/></animateMotion>
        </circle>

        {/* Nodes */}
        {nodes.map(n => (
          <g key={n.i} className="ccl-vis-flow-node" style={{ '--d': `${300 + n.i * 180}ms` }}>
            <rect x={n.x} y={n.y} width="90" height="48" rx="8"
                  fill="var(--ccl-paper)" stroke="var(--ccl-line)" strokeWidth="1.2"/>
            <text x={n.x + 45} y={n.y + 22} textAnchor="middle" fontSize="13"
                  fill="var(--ccl-ink)" fontFamily="var(--ccl-body)" fontWeight="500">{n.l}</text>
            <text x={n.x + 45} y={n.y + 38} textAnchor="middle" fontSize="9.5"
                  fill="var(--ccl-mute)" fontFamily="var(--ccl-mono)" letterSpacing="0.1em">{n.s.toUpperCase()}</text>
            {n.hot && (
              <circle cx={n.x + 82} cy={n.y + 10} r="4" fill="#a8854a">
                <animate attributeName="opacity" values="1;.3;1" dur="1.4s" repeatCount="indefinite"/>
              </circle>
            )}
          </g>
        ))}
      </svg>
    </div>
  );
};

// ===========================================================================
// VISUAL 5 · GRAPH — edges draw, nodes appear, central halo pulses
// ===========================================================================
const VisGraph = ({ live }) => {
  const nodes = [
    { x: 250, y: 165, r: 28, c: '#1f3a30', l: 'Harbor Industrial', big: true },
    { x: 100, y: 70, r: 14, c: '#14110e', l: 'NDA-0418' },
    { x: 400, y: 70, r: 14, c: '#5a8470', l: 'OSHA cert' },
    { x: 70, y: 260, r: 14, c: '#7d2e3a', l: 'Audit Q2' },
    { x: 430, y: 260, r: 14, c: '#a8854a', l: 'BuildRight' },
    { x: 180, y: 30, r: 8, c: '#c5bca5' },
    { x: 325, y: 30, r: 8, c: '#c5bca5' },
    { x: 35, y: 160, r: 8, c: '#c5bca5' },
    { x: 465, y: 160, r: 8, c: '#c5bca5' },
  ];
  return (
    <div className={`ccl-vis ccl-vis-graph ${live ? 'live' : ''}`}>
      <div className="ccl-vis-flow-head">
        <span>447 nodes · 1,128 edges</span>
        <span>Centered: Harbor</span>
      </div>
      <svg viewBox="0 0 500 310" className="ccl-vis-graph-svg" preserveAspectRatio="xMidYMid meet">
        {nodes.slice(1).map((n, i) => (
          <line
            key={`l${i}`}
            className="ccl-vis-graph-edge"
            x1={250} y1={165} x2={n.x} y2={n.y}
            stroke="#c5bca5" strokeWidth="1.2"
            strokeDasharray="300" strokeDashoffset="300"
            style={{ '--d': `${300 + i * 100}ms` }}
          />
        ))}
        {nodes.map((n, i) => (
          <g key={i} className="ccl-vis-graph-node" style={{ '--d': `${500 + i * 110}ms` }}>
            {n.big && (
              <>
                <circle cx={n.x} cy={n.y} r={n.r + 18} fill="none" stroke={n.c} strokeWidth="1" className="ccl-vis-graph-halo"/>
                <circle cx={n.x} cy={n.y} r={n.r + 8} fill="none" stroke={n.c} strokeWidth="1" opacity="0.4"/>
              </>
            )}
            <circle cx={n.x} cy={n.y} r={n.r} fill={n.c}/>
            {n.l && (
              <text x={n.x} y={n.y + n.r + 16} fontSize="11" textAnchor="middle"
                    fill="#2a261f" fontFamily="var(--ccl-body)" fontWeight="500">{n.l}</text>
            )}
          </g>
        ))}
        {/* Live activity ping — travels along one edge */}
        <circle r="3" fill="#1f3a30" className="ccl-vis-graph-ping">
          <animateMotion dur="3s" repeatCount="indefinite" path="M250 165 L100 70 L250 165 L400 70 L250 165 L70 260 L250 165 L430 260 L250 165"/>
        </circle>
      </svg>
    </div>
  );
};

const __visuals = [VisIntake, VisRisk, VisCopilot, VisWorkflow, VisGraph];

// ===========================================================================
// PINNED HORIZONTAL-SCROLL SECTION
// ===========================================================================
const LCapabilities = () => {
  const wrapRef = React.useRef(null);
  const trackRef = React.useRef(null);
  const [active, setActive] = React.useState(0);

  React.useEffect(() => {
    let raf = 0;
    const update = () => {
      raf = 0;
      const el = wrapRef.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const vh = window.innerHeight;
      const total = rect.height - vh;
      if (total <= 0) return;
      const t = Math.max(0, Math.min(1, -rect.top / total));
      if (trackRef.current) {
        const tx = -t * (CAPS.length - 1) * 100;
        trackRef.current.style.transform = `translate3d(${tx.toFixed(3)}vw, 0, 0)`;
      }
      const idx = Math.min(CAPS.length - 1, Math.max(0, Math.round(t * (CAPS.length - 1))));
      setActive(idx);
    };
    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);
    };
  }, []);

  const jumpTo = (i) => {
    const el = wrapRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const top = window.scrollY + rect.top;
    const total = el.offsetHeight - window.innerHeight;
    const targetY = top + total * (i / (CAPS.length - 1));
    window.scrollTo({ top: targetY + 8, behavior: 'smooth' });
  };

  return (
    <section
      ref={wrapRef}
      className="ccl-cap-pin"
      id="product"
      style={{ height: `${CAPS.length * 100}vh` }}
    >
      <div className="ccl-cap-pin-sticky">
        <div className="ccl-cap-pin-head">
          <div className="ccl-cap-pin-head-left">
            <div className="ccl-eyebrow">
              <span className="ccl-eyebrow-num">★</span>
              The product · Five moments
            </div>
            <h2 className="ccl-cap-pin-title">
              Real product,<br/><em>not promises.</em>
            </h2>
          </div>
          <div className="ccl-cap-pin-pips" role="tablist">
            <div
              className="ccl-cap-pin-pips-rail"
              style={{ width: `${((active) / (CAPS.length - 1)) * 100}%` }}
            />
            {CAPS.map((c, i) => (
              <button
                key={c.n}
                className={`ccl-cap-pin-pip ${i === active ? 'on' : ''} ${i < active ? 'past' : ''}`}
                onClick={() => jumpTo(i)}
                aria-label={`Go to ${c.name}`}
              >
                <span className="ccl-cap-pin-pip-num">{c.n}</span>
                <span className="ccl-cap-pin-pip-name">{c.name}</span>
              </button>
            ))}
          </div>
        </div>
        <div className="ccl-cap-pin-viewport">
          <div ref={trackRef} className="ccl-cap-pin-track">
            {CAPS.map((cap, i) => {
              const Visual = __visuals[i];
              return (
                <div key={cap.n} className={`ccl-cap-pin-slide ${i === active ? 'is-active' : ''}`}>
                  <div className="ccl-cap-pin-slide-inner">
                    <div className="ccl-cap-pin-text">
                      <div className="ccl-eyebrow">{cap.eyebrow}</div>
                      <h3>{cap.h}</h3>
                      <p>{cap.body}</p>
                      <div className="ccl-cap-feats">
                        {cap.feats.map(f => (
                          <div key={f} className="ccl-cap-feat">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
                              <path d="M5 12l5 5L20 7" strokeLinecap="round" strokeLinejoin="round"/>
                            </svg>
                            <span>{f}</span>
                          </div>
                        ))}
                      </div>
                      <a href="#" className="ccl-link">
                        See {cap.name.toLowerCase()} in detail <LIcon name="arrR" size={13}/>
                      </a>
                    </div>
                    <div className="ccl-cap-pin-canvas">
                      <Visual live={i === active}/>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
          <div className="ccl-cap-pin-hint">
            <span className="ccl-cap-pin-hint-num">{String(active + 1).padStart(2, '0')} <em>/ {String(CAPS.length).padStart(2, '0')}</em></span>
            <span className="ccl-cap-pin-hint-tip">scroll →</span>
          </div>
        </div>
      </div>
    </section>
  );
};

window.LCapabilities = LCapabilities;
