// LiveDemo.jsx — auto-cycling before/after of the actual Plumb panel
// Now supports scroll-pinned scrubbing: wrap in a .pin-track parent and
// the scene index follows scroll progress.
const PlumbLiveDemo = ({ autoplay = true, speed = 1, scrub = false } = {}) => {
  const { useState, useEffect, useRef } = React;
  const SCENES = [
    {
      id: 0,
      label: 'Tuesday 09:14 — initial draft',
      part: 'MNT-0042-bracket · rev 3',
      cost: 26.10,
      lead: '12–17',
      delta: null,
      flags: 4,
      alert: null,
      caption: 'baseline. four open flags.',
    },
    {
      id: 1,
      label: 'Tuesday 09:22 — wall thinned to 2.4mm',
      part: 'MNT-0042-bracket · rev 3 · edit',
      cost: 23.10,
      lead: '12–17',
      delta: -3.00,
      flags: 5,
      alert: {
        title: 'wall under 3mm',
        body: 'Aluminum 6061. Mesa Fab will not run that.',
        cite: 'rule dfm-al-001 · same as MNT-0042 rev 3',
      },
      caption: 'cheaper on paper. shop will reject it.',
    },
    {
      id: 2,
      label: 'Tuesday 09:24 — wall set to 3.2mm',
      part: 'MNT-0042-bracket · rev 4',
      cost: 24.80,
      lead: '9–14',
      delta: -1.30,
      flags: 2,
      alert: null,
      caption: 'true from drawing to delivery.',
    },
  ];

  const [i, setI] = useState(0);
  const [paused, setPaused] = useState(false);
  const trackRef = useRef(null);

  // Auto-cycle (only when not in scrub mode)
  useEffect(() => {
    if (scrub || paused || !autoplay) return;
    const base = i === 1 ? 4200 : 3400;
    const t = setTimeout(() => setI((n) => (n + 1) % SCENES.length), base / Math.max(0.3, speed));
    return () => clearTimeout(t);
  }, [i, paused, autoplay, speed, scrub]);

  // Scrub mode: track parent .pin-track scroll progress and map to scene index
  useEffect(() => {
    if (!scrub) return;
    const track = trackRef.current && trackRef.current.closest('.pin-track');
    if (!track) return;
    let raf = null;
    const tick = () => {
      const vh = window.innerHeight || 800;
      const r = track.getBoundingClientRect();
      const total = Math.max(1, r.height - vh);
      const scrolled = Math.max(0, Math.min(total, -r.top));
      const p = scrolled / total; // 0..1 across the track
      // Distribute across scenes: first 25% = scene 0, mid 50% = scene 1, last 25% = scene 2.
      // Scene 1 (the alert moment) gets the most dwell time.
      let idx;
      if (p < 0.22) idx = 0;
      else if (p < 0.78) idx = 1;
      else idx = 2;
      setI(idx);
      track.style.setProperty('--scrub', p.toFixed(4));
      raf = null;
    };
    const onScroll = () => { if (raf == null) raf = requestAnimationFrame(tick); };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll, { passive: true });
    tick();
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, [scrub]);

  const s = SCENES[i];

  return (
    <div className={scrub ? 'pin-track demo-pin-track' : 'demo-static-wrap'}>
      <section
        id="demo"
        className={`section demo reveal-fx ${scrub ? 'demo-pinned' : ''}`}
        data-screen-label="live-demo"
      >
      <div className="page" ref={trackRef}>
        <p className="eyebrow">03 · what it looks like</p>
        <h2 className="section-h" style={{ maxWidth: '20ch' }}>
          Eight seconds. Same desk. Same file.
        </h2>
        <p className="lead" style={{ marginTop: 24, marginBottom: 56 }}>
          {scrub
            ? 'Scroll through one Tuesday morning. The engineer thins a wall to save cost, Plumb names the rule, the precedent fix, and the named human who would have caught it.'
            : 'Watch one Tuesday morning. The engineer thins a wall to save cost, Plumb names the rule, the precedent fix, and the named human who would have caught it.'}
        </p>

        <div
          className="demo-frame"
          onClick={scrub ? undefined : () => setPaused((p) => !p)}
          role={scrub ? undefined : 'button'}
          aria-label={scrub ? undefined : (paused ? 'Resume demo' : 'Pause demo')}
        >
          {/* Window chrome */}
          <div className="demo-chrome">
            <div className="dc-dots">
              <span /><span /><span />
            </div>
            <div className="dc-title readout">{s.part}</div>
            <div className="dc-status">
              <span className={`dc-dot ${s.flags > 0 ? 'on' : ''}`} />
              <span className="readout">{s.flags} flag{s.flags === 1 ? '' : 's'}</span>
            </div>
          </div>

          {/* CAD panel + Cost panel */}
          <div className="demo-body">
            <div className="cad-pane">
              {/* Drafting corners */}
              <span className="cad-corner tl">{s.label}</span>
              <span className="cad-corner tr">doc 001 · sheet 1 of 1</span>
              <span className="cad-corner bl">Aluminum 6061 · CNC 3-axis · Mesa Fab</span>
              <span className="cad-corner br">plumb · 2026</span>

              <div className="cad-cross-h" />
              <div className="cad-cross-v" />

              {/* Bracket sketch */}
              <svg viewBox="0 0 320 220" className="bracket" xmlns="http://www.w3.org/2000/svg">
                {/* Body */}
                <rect x="40" y="60" width="240" height="110" stroke="rgba(26,26,26,0.55)" strokeWidth="1.2" fill="rgba(26,26,26,0.02)"/>
                {/* Rib — animates thickness based on scene */}
                <rect
                  x={i === 1 ? 76 : 70} y="60"
                  width={i === 1 ? 8 : i === 2 ? 18 : 14} height="110"
                  stroke="rgba(26,26,26,0.4)" strokeWidth="0.8"
                  fill="rgba(26,26,26,0.06)"
                  style={{ transition: 'all 600ms cubic-bezier(0.4,0,0.2,1)' }}
                />
                {/* Pocket */}
                <rect x="120" y="80" width="80" height="70" stroke="rgba(26,26,26,0.4)" strokeWidth="0.8" strokeDasharray="4 2" fill="none"/>
                {/* Bolt holes */}
                <circle cx="60" cy="85" r="7" stroke="rgba(26,26,26,0.45)" strokeWidth="0.8" fill="rgba(232,226,213,1)"/>
                <circle cx="60" cy="145" r="7" stroke="rgba(26,26,26,0.45)" strokeWidth="0.8" fill="rgba(232,226,213,1)"/>
                <circle cx="260" cy="85" r="7" stroke="rgba(26,26,26,0.45)" strokeWidth="0.8" fill="rgba(232,226,213,1)"/>
                <circle cx="260" cy="145" r="7" stroke="rgba(26,26,26,0.45)" strokeWidth="0.8" fill="rgba(232,226,213,1)"/>
                {/* Dimension */}
                <line x1="40" y1="190" x2="280" y2="190" stroke="rgba(26,26,26,0.3)" strokeWidth="0.6"/>
                <line x1="40" y1="186" x2="40" y2="194" stroke="rgba(26,26,26,0.3)" strokeWidth="0.6"/>
                <line x1="280" y1="186" x2="280" y2="194" stroke="rgba(26,26,26,0.3)" strokeWidth="0.6"/>
                <text x="160" y="204" textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="9" fill="rgba(26,26,26,0.5)">180.00 mm</text>

                {/* Flag overlay on rib when alert */}
                {i === 1 && (
                  <g style={{ transition: 'opacity 300ms' }}>
                    <rect x="74" y="58" width="12" height="114" stroke="#B83A2D" strokeWidth="1" strokeDasharray="3 2" fill="rgba(184,58,45,0.08)"/>
                    <line x1="80" y1="58" x2="80" y2="40" stroke="#B83A2D" strokeWidth="0.8"/>
                    <text x="80" y="36" textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="9" fill="#B83A2D">⚠ 2.4 mm</text>
                  </g>
                )}
                {i === 2 && (
                  <g>
                    <line x1="79" y1="58" x2="79" y2="40" stroke="#1B3A5C" strokeWidth="0.8"/>
                    <text x="79" y="36" textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="9" fill="#1B3A5C">3.2 mm ✓</text>
                  </g>
                )}
              </svg>

              {/* Caption strip */}
              <div className="cad-caption">
                <span className="readout">{s.caption}</span>
              </div>
            </div>

            {/* Cost panel — right rail */}
            <div className="cost-rail">
              <div className="cr-head">
                <span className="readout cr-eyebrow">cost · live</span>
                <span className="readout cr-shop">Mesa Fab · qty 500</span>
              </div>
              <div className="cr-big">
                <span className="cr-currency">$</span>
                <span className="cr-num readout" key={s.cost}>{s.cost.toFixed(2)}</span>
                <span className="cr-unit">/ unit</span>
              </div>
              <div className="cr-delta">
                {s.delta !== null ? (
                  <span className={`readout cr-d ${s.delta < 0 ? 'down' : 'up'}`}>
                    {s.delta < 0 ? '−' : '+'}${Math.abs(s.delta).toFixed(2)} since rev 3
                  </span>
                ) : (
                  <span className="readout cr-d muted">baseline</span>
                )}
              </div>

              <div className="cr-row">
                <span className="cr-k">lead time</span>
                <span className="cr-v readout">{s.lead} days</span>
              </div>
              <div className="cr-row">
                <span className="cr-k">flags</span>
                <span className={`cr-v readout ${s.flags > 2 ? 'r' : ''}`}>{s.flags} open</span>
              </div>

              {/* Alert card */}
              <div className={`cr-alert ${s.alert ? 'show' : ''}`}>
                {s.alert && (
                  <>
                    <div className="cra-head">
                      <span className="ps-tag-r">flag</span>
                      <span className="readout cra-conf">high confidence</span>
                    </div>
                    <div className="cra-title">{s.alert.title}</div>
                    <div className="cra-body">{s.alert.body}</div>
                    <div className="cra-cite readout">{s.alert.cite}</div>
                  </>
                )}
              </div>

              <div className="cr-foot readout">
                {paused ? 'paused · click to resume' : `updated ${(i+1) * 8}s ago`}
              </div>
            </div>
          </div>

          {/* Scene progress */}
          <div className="demo-progress">
            {SCENES.map((sc, idx) => (
              <button
                key={sc.id}
                className={`dp ${idx === i ? 'on' : ''}`}
                onClick={(e) => { e.stopPropagation(); setI(idx); setPaused(true); }}
                aria-label={`Scene ${idx+1}`}
              >
                <span className="dp-num readout">0{idx+1}</span>
                <span className="dp-bar"><span className={`dp-fill ${idx === i && !paused ? 'run' : ''}`} key={`${i}-${paused}`} /></span>
              </button>
            ))}
          </div>
        </div>
      </div>

      <style>{`
        .demo-pin-track {
          position: relative;
          /* 280vh of scroll for the 3 scenes — first 22% scene 0, mid 56% scene 1, last 22% scene 2 */
          height: 280vh;
        }
        .demo-pinned {
          position: sticky;
          top: 0;
          height: 100vh;
          display: flex;
          align-items: center;
          padding: 0 !important;
          overflow: hidden;
        }
        .demo-pinned > .page {
          width: 100%;
          max-height: 100vh;
          overflow: hidden;
          padding-top: 32px;
          padding-bottom: 32px;
        }
        .demo-pinned .section-h { font-size: clamp(28px, 3.4vw, 44px); margin-top: 8px; }
        .demo-pinned .lead { margin-top: 14px !important; margin-bottom: 28px !important; max-width: 64ch; }
        .demo-pinned .demo-frame { margin-top: 16px; }
        .demo-pinned .demo-body { min-height: 380px; }
        .demo-pinned .cad-pane { min-height: 360px; padding: 22px 26px 76px; }
        @media (max-width: 900px) {
          .demo-pin-track { height: auto; }
          .demo-pinned { position: relative; height: auto; padding: 96px 0 !important; display: block; }
          .demo-pinned > .page { max-height: none; }
        }

        .demo-frame {
          margin-top: 64px;
          background: var(--color-surface-white);
          border: 1px solid var(--border-default);
          border-radius: 4px;
          overflow: hidden;
          box-shadow: var(--shadow-1);
          transition: box-shadow 200ms var(--ease-standard);
          cursor: default;
        }
        .demo-frame:hover { box-shadow: var(--shadow-2); }

        .demo-chrome {
          display: flex; align-items: center; justify-content: space-between;
          padding: 10px 14px;
          background: #f4f0e8;
          border-bottom: 1px solid var(--border-default);
        }
        .dc-dots { display: flex; gap: 6px; }
        .dc-dots span {
          width: 10px; height: 10px; border-radius: 50%;
          background: rgba(26,26,26,0.18);
        }
        .dc-title {
          font-size: 11px; color: rgba(26,26,26,0.6);
          letter-spacing: 0.04em;
        }
        .dc-status { display: flex; align-items: center; gap: 8px; font-size: 11px; color: rgba(26,26,26,0.55); }
        .dc-dot { width: 6px; height: 6px; border-radius: 50%; background: rgba(26,26,26,0.2); transition: background-color 200ms; }
        .dc-dot.on { background: var(--color-redline); animation: pulseDot 1.6s infinite; }
        @keyframes pulseDot { 0%,100% { opacity: 1; } 50% { opacity: 0.45; } }

        .demo-body {
          display: grid;
          grid-template-columns: 1fr;
          min-height: 460px;
        }
        @media (min-width: 900px) {
          .demo-body { grid-template-columns: 1fr 320px; }
        }

        .cad-pane {
          position: relative;
          background: var(--bg-primary);
          padding: 28px 32px 88px;
          min-height: 420px;
          border-bottom: 1px solid var(--border-default);
        }
        @media (min-width: 900px) {
          .cad-pane { border-bottom: 0; border-right: 1px solid var(--border-default); }
        }
        .cad-corner {
          position: absolute;
          font-family: var(--font-mono);
          font-size: 9px;
          color: rgba(26,26,26,0.42);
          letter-spacing: 0.06em;
        }
        .cad-corner.tl { top: 12px; left: 16px; }
        .cad-corner.tr { top: 12px; right: 16px; }
        .cad-corner.bl { bottom: 64px; left: 16px; }
        .cad-corner.br { bottom: 64px; right: 16px; }
        .cad-cross-h { position: absolute; left: 0; right: 0; top: 50%; height: 1px; background: rgba(26,26,26,0.05); }
        .cad-cross-v { position: absolute; top: 0; bottom: 0; left: 50%; width: 1px; background: rgba(26,26,26,0.05); }
        .bracket {
          display: block;
          width: 100%;
          max-width: 460px;
          height: auto;
          margin: 32px auto 16px;
          position: relative;
          z-index: 1;
        }
        .cad-caption {
          position: absolute;
          left: 16px; right: 16px; bottom: 18px;
          font-size: 11px; color: rgba(26,26,26,0.62);
          padding-top: 10px;
          border-top: 1px solid rgba(26,26,26,0.1);
          letter-spacing: 0.02em;
          font-style: italic;
        }

        .cost-rail {
          padding: 24px 24px 64px;
          background: #f9f5ec;
          display: flex; flex-direction: column; gap: 14px;
        }
        .cr-head { display: flex; justify-content: space-between; }
        .cr-eyebrow {
          font-size: 9px; letter-spacing: 0.14em;
          color: rgba(26,26,26,0.45); text-transform: uppercase;
        }
        .cr-shop { font-size: 10px; color: rgba(26,26,26,0.5); letter-spacing: 0.06em; }
        .cr-big {
          display: flex; align-items: baseline; gap: 4px;
          padding: 10px 0 4px;
          border-bottom: 1px solid rgba(26,26,26,0.1);
        }
        .cr-currency {
          font-family: var(--font-mono);
          font-size: 18px; color: var(--color-prussian); margin-right: 2px;
        }
        .cr-num {
          font-family: var(--font-mono);
          font-size: 38px;
          font-weight: 500;
          color: var(--color-graphite);
          letter-spacing: -0.02em;
          line-height: 1;
          animation: numPulse 400ms var(--ease-standard);
        }
        @keyframes numPulse {
          0% { opacity: 0.3; transform: translateY(-2px); }
          100% { opacity: 1; transform: none; }
        }
        .cr-unit {
          font-family: var(--font-mono);
          font-size: 11px; color: rgba(26,26,26,0.45);
          margin-left: 6px;
        }
        .cr-delta { padding-bottom: 4px; }
        .cr-d {
          font-size: 11px; padding: 3px 8px;
          background: rgba(26,26,26,0.05); border-radius: 2px;
          color: rgba(26,26,26,0.6);
        }
        .cr-d.down { color: var(--color-prussian); background: rgba(27,58,92,0.07); }
        .cr-d.up { color: var(--color-redline); background: rgba(184,58,45,0.07); }
        .cr-d.muted { color: rgba(26,26,26,0.5); }
        .cr-row {
          display: flex; justify-content: space-between;
          padding: 8px 0;
          border-bottom: 1px solid rgba(26,26,26,0.08);
        }
        .cr-k { font-family: var(--font-mono); font-size: 11px; color: rgba(26,26,26,0.55); letter-spacing: 0.04em; }
        .cr-v { font-size: 12px; font-weight: 500; }
        .cr-v.r { color: var(--color-redline); }

        .cr-alert {
          background: rgba(184,58,45,0.06);
          border: 1px solid rgba(184,58,45,0.2);
          border-radius: 2px;
          padding: 12px;
          margin-top: 4px;
          opacity: 0;
          max-height: 0;
          overflow: hidden;
          transition: opacity 250ms var(--ease-standard), max-height 350ms var(--ease-standard), padding 250ms var(--ease-standard);
        }
        .cr-alert.show {
          opacity: 1; max-height: 220px; padding: 12px;
        }
        .cra-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
        .cra-conf { font-size: 9px; color: rgba(26,26,26,0.5); letter-spacing: 0.08em; }
        .cra-title { font-size: 13px; font-weight: 500; margin-bottom: 4px; }
        .cra-body { font-size: 12px; color: rgba(26,26,26,0.7); margin-bottom: 8px; line-height: 1.5; }
        .cra-cite { font-size: 9px; color: rgba(26,26,26,0.5); letter-spacing: 0.04em; }

        .cr-foot {
          font-size: 9px; color: rgba(26,26,26,0.4); letter-spacing: 0.06em;
          margin-top: auto;
        }

        .demo-progress {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 0;
          background: #f4f0e8;
          border-top: 1px solid var(--border-default);
        }
        .dp {
          appearance: none;
          background: transparent;
          border: 0;
          border-right: 1px solid rgba(26,26,26,0.08);
          padding: 12px 16px;
          text-align: left;
          cursor: default;
          display: flex; flex-direction: column; gap: 6px;
          opacity: 0.55;
          transition: opacity 200ms var(--ease-standard), background-color 200ms var(--ease-standard);
        }
        .dp:last-child { border-right: 0; }
        .dp:hover { background: rgba(26,26,26,0.03); opacity: 0.9; }
        .dp.on { opacity: 1; }
        .dp-num {
          font-size: 9px; letter-spacing: 0.14em;
          color: rgba(26,26,26,0.5);
        }
        .dp-bar {
          display: block; height: 1px;
          background: rgba(26,26,26,0.12);
          position: relative;
          overflow: hidden;
        }
        .dp-fill {
          position: absolute; inset: 0;
          background: var(--color-graphite);
          transform: scaleX(0);
          transform-origin: left;
        }
        .dp.on .dp-fill { transform: scaleX(1); transition: transform 200ms; }
        .dp.on .dp-fill.run {
          animation: dpRun 3.4s linear forwards;
        }
        @keyframes dpRun {
          from { transform: scaleX(0); }
          to { transform: scaleX(1); }
        }
      `}</style>
      </section>
    </div>
  );
};

window.PlumbLiveDemo = PlumbLiveDemo;
