/* "The difference" — an invoice teardown.
   ALEROQ audits the SAME repair line by line, exposing the padding a shop hands
   you as one opaque number. The shop's invoice prints in, an audit sweep crosses,
   ALEROQ's fair breakdown reveals, and the gap tallies up. Concrete and on-brand:
   the product's whole thesis is transparency, so we literally show the receipt. */

/* useTally — count 0 -> `to` once `active`, eased. Unlike a bare rAF counter it
   carries a setTimeout fallback that snaps to `to` if rAF is throttled (hidden
   tab / reduced motion), so the RESTING total is always correct, never $0. */
function useTally(to, active, dur = 1100) {
  const [v, setV] = React.useState(0);
  React.useEffect(() => {
    if (!active) { setV(0); return; }
    const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce) { setV(to); return; }
    let raf, start, done = false;
    const fb = setTimeout(() => { if (!done) { done = true; setV(to); } }, dur + 500);
    const tick = (t) => {
      if (start == null) start = t;
      const p = Math.min((t - start) / dur, 1);
      setV(Math.round(to * (1 - Math.pow(1 - p, 3))));
      if (p < 1) { raf = requestAnimationFrame(tick); } else { done = true; }
    };
    raf = requestAnimationFrame(tick);
    return () => { cancelAnimationFrame(raf); clearTimeout(fb); };
  }, [to, active, dur]);
  return v;
}

function TdnMoney({ v, color, strike }) {
  return (
    <span style={{ position: 'relative', display: 'inline-block', fontFamily: 'var(--font-mono)', fontWeight: 700,
      fontSize: 18, color, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em', whiteSpace: 'nowrap' }}>
      ${v.toLocaleString()}
      {strike && (
        <span style={{ position: 'absolute', left: -2, right: -2, top: '52%', height: 2, background: 'var(--red-400)',
          transformOrigin: 'left', animation: 'tdnStrike .45s var(--ease-out) both', boxShadow: '0 0 8px rgba(255,79,92,0.65)' }} />
      )}
    </span>
  );
}

function PriceReveal() {
  const { Badge } = window.RevvoDesignSystem_a89086;
  const { Reveal, Ic } = window;

  const cardRef = React.useRef(null);
  const [phase, setPhase] = React.useState(0); // 0 idle · 1 invoice printed · 2 audited
  const [runId, setRunId] = React.useState(0);

  // One transmission service, audited. Padding lives in the diagnostic fee,
  // inflated labor HOURS (rate is honest), and junk "shop supplies" — parts are
  // left untouched, which keeps the teardown credible.
  const rows = [
    { key: 'diag',  label: 'Diagnostic fee',        shopNote: 'Standard shop charge',      shop: 150, mine: 0,   mineNote: 'Read free on-device',     tag: 'Removed' },
    { key: 'labor', label: 'Labor',                 shopNote: '3.5 hrs billed @ $145',     shop: 510, mine: 290, mineNote: '2.0 hrs · book time',     tag: 'Corrected' },
    { key: 'parts', label: 'Parts & fluid',         shopNote: 'OEM filter + ATF',          shop: 450, mine: 450, mineNote: 'Same parts · fair retail', tag: 'Fair' },
    { key: 'fees',  label: 'Shop supplies & fees',  shopNote: '\u201CMisc / environmental\u201D', shop: 90,  mine: 0,   mineNote: 'No junk fees',            tag: 'Removed' },
  ];
  const SHOP_TOTAL = 1200, GAP = 460, PCT = 38;

  const reduce = () => window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  const run = React.useCallback(() => {
    setPhase(1);
    if (reduce()) { setPhase(2); return; }
    setTimeout(() => setPhase(2), rows.length * 130 + 480);
  }, [rows.length]);

  React.useEffect(() => {
    const node = cardRef.current; if (!node) return;
    let fired = false;
    const trigger = () => { if (fired) return; fired = true; run(); };
    const check = () => { const r = node.getBoundingClientRect(); if (r.top < (window.innerHeight || 800) * 0.72 && r.bottom > 0) trigger(); };
    check();
    window.addEventListener('scroll', check, { passive: true });
    const poll = setInterval(() => { if (fired) { clearInterval(poll); return; } check(); }, 500);
    return () => { window.removeEventListener('scroll', check); clearInterval(poll); };
  }, [run, runId]);

  const replay = () => { setPhase(0); setTimeout(() => { setRunId((n) => n + 1); run(); }, 30); };

  const shopIn = phase >= 1, auditIn = phase >= 2;
  const gapCount = useTally(GAP, auditIn, 1100);
  const myShown = SHOP_TOTAL - gapCount;

  const rev = (on, i) => ({
    opacity: on ? 1 : 0,
    transform: on ? 'none' : 'translateY(10px)',
    transition: `opacity .5s var(--ease-out) ${i * 110}ms, transform .5s var(--ease-out) ${i * 110}ms`,
  });

  const css = `
    .tdn-grid { display:grid; grid-template-columns:1fr 1fr; }
    @media (max-width: 820px){
      .tdn-grid { grid-template-columns:1fr; }
      .tdn-seam { display:none !important; }
      .tdn-shop { border-bottom:1px solid var(--line-200); }
    }
    @keyframes tdnStrike { from { transform:scaleX(0); } to { transform:scaleX(1); } }
  `;

  const colHead = (icon, label, col, border) => (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 18, padding: '5px 11px',
      borderRadius: 'var(--radius-pill)', border: `1px solid ${border}`, color: col,
      fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase' }}>
      <Ic name={icon} size={13} color={col} /> {label}
    </div>
  );

  return (
    <section style={{ position: 'relative', padding: 'var(--space-section) clamp(20px, 5vw, 48px)' }}>
      <style dangerouslySetInnerHTML={{ __html: css }} />
      <div style={{ maxWidth: 'var(--container-narrow)', margin: '0 auto' }}>
        <Reveal style={{ textAlign: 'center', marginBottom: 44 }}>
          <Badge variant="neutral" style={{ marginBottom: 20 }}>The difference</Badge>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--fs-display-2)',
            letterSpacing: 'var(--ls-snug)', color: 'var(--text-strong)', margin: '0 0 14px', lineHeight: 'var(--lh-snug)' }}>
            Same repair. The padding has nowhere to hide.
          </h2>
          <p style={{ fontSize: 'var(--fs-lead)', color: 'var(--text-body)', maxWidth: 560, margin: '0 auto' }}>
            A shop hands you one number. ALEROQ audits the identical job line by line &mdash; so every charge has to earn its place.
          </p>
        </Reveal>

        <Reveal dir="scale">
          <div ref={cardRef} style={{ position: 'relative', borderRadius: 'var(--radius-lg)', overflow: 'hidden',
            border: '1px solid var(--border)', background: 'var(--surface)', boxShadow: '0 40px 90px rgba(0,0,0,0.5)' }}>
            {/* narrative arc hairline: fault (red) -> resolved (green) */}
            <div style={{ height: 3, background: 'linear-gradient(90deg, var(--red-500), var(--green-500))', opacity: 0.9 }} />
            {/* faint circuit substrate */}
            <div style={{ position: 'absolute', inset: 0, backgroundImage: window.ALEROQ_CIRCUIT, backgroundSize: '320px',
              opacity: 0.04, pointerEvents: 'none' }} />

            {/* job header */}
            <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              gap: 16, flexWrap: 'wrap', padding: '15px clamp(18px,3vw,28px)', borderBottom: '1px solid var(--line-100)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <Ic name="ScrollText" size={17} color="var(--silver-400)" />
                <div>
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-strong)' }}>Transmission fluid &amp; filter service</div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--text-muted)', letterSpacing: '0.04em', marginTop: 2 }}>2014 Honda Accord &middot; RO #4417</div>
                </div>
              </div>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--text-faint)', letterSpacing: '0.06em' }}>Phoenix, AZ</span>
            </div>

            {/* two invoices */}
            <div className="tdn-grid" style={{ position: 'relative' }}>
              {/* center seam */}
              <div className="tdn-seam" style={{ position: 'absolute', top: 0, bottom: 0, left: '50%', width: 1,
                background: 'linear-gradient(180deg, transparent, var(--line-200) 12%, var(--line-200) 88%, transparent)', transform: 'translateX(-0.5px)' }} />
              {/* audit sweep (one-shot) */}
              {auditIn && !reduce() && (
                <div style={{ position: 'absolute', top: 0, bottom: 0, width: '30%', left: 0, pointerEvents: 'none',
                  animation: 'dcxScan 1.4s var(--ease-out) both',
                  background: 'linear-gradient(90deg, transparent, rgba(22,214,128,0.16), transparent)' }} />
              )}

              {/* SHOP side */}
              <div className="tdn-shop" style={{ position: 'relative', padding: '22px clamp(18px,3vw,28px)',
                background: 'linear-gradient(180deg, rgba(229,25,42,0.06), rgba(229,25,42,0) 62%)' }}>
                {colHead('Receipt', 'The shop\u2019s invoice', 'var(--red-300)', 'rgba(255,79,92,0.4)')}
                <div style={{ display: 'grid', gap: 0 }}>
                  {rows.map((r, i) => (
                    <div key={r.key} style={{ ...rev(shopIn, i), display: 'flex', alignItems: 'flex-start',
                      justifyContent: 'space-between', gap: 14, padding: '12px 0', borderBottom: '1px solid var(--line-100)' }}>
                      <div>
                        <div style={{ fontSize: 14.5, color: 'var(--text-body)', fontWeight: 500 }}>{r.label}</div>
                        <div style={{ fontSize: 12, color: 'var(--text-faint)', marginTop: 3 }}>{r.shopNote}</div>
                      </div>
                      <TdnMoney v={r.shop} color="var(--text-strong)" strike={auditIn && r.mine < r.shop} />
                    </div>
                  ))}
                </div>
                <div style={{ ...rev(shopIn, rows.length), display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginTop: 16 }}>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Total billed</span>
                  <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 34, color: 'var(--text-strong)', letterSpacing: '-0.02em' }}>$1,200</span>
                </div>
                <div style={{ ...rev(shopIn, rows.length + 1), fontSize: 12, color: 'var(--text-faint)', marginTop: 8 }}>One number. No breakdown.</div>
              </div>

              {/* ALEROQ side */}
              <div style={{ position: 'relative', padding: '22px clamp(18px,3vw,28px)',
                background: 'linear-gradient(180deg, rgba(22,214,128,0.06), rgba(22,214,128,0) 62%)' }}>
                {colHead('ShieldCheck', 'What ALEROQ found', 'var(--positive-bright)', 'rgba(22,214,128,0.4)')}
                <div style={{ display: 'grid', gap: 0 }}>
                  {rows.map((r, i) => {
                    const saved = r.shop - r.mine;
                    return (
                      <div key={r.key} style={{ ...rev(auditIn, i), display: 'flex', alignItems: 'flex-start',
                        justifyContent: 'space-between', gap: 14, padding: '12px 0', borderBottom: '1px solid var(--line-100)' }}>
                        <div>
                          <div style={{ fontSize: 14.5, color: 'var(--text-strong)', fontWeight: 500 }}>{r.label}</div>
                          <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 3, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                            <Ic name={saved > 0 ? 'Check' : 'Minus'} size={12} color={saved > 0 ? 'var(--positive-bright)' : 'var(--text-faint)'} />
                            {r.mineNote}
                          </div>
                        </div>
                        <div style={{ textAlign: 'right' }}>
                          <TdnMoney v={r.mine} color={saved > 0 ? 'var(--positive-bright)' : 'var(--text-strong)'} />
                          <div style={{ marginTop: 5, fontFamily: 'var(--font-mono)', fontSize: 10.5, fontWeight: 700,
                            letterSpacing: '0.06em', color: saved > 0 ? 'var(--positive-bright)' : 'var(--text-faint)' }}>
                            {saved > 0 ? `\u2212$${saved} \u00B7 ${r.tag}` : 'Fair'}
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
                <div style={{ ...rev(auditIn, rows.length), display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginTop: 16 }}>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>You pay</span>
                  <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 34, color: 'var(--positive-bright)',
                    letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums', textShadow: '0 0 22px rgba(22,214,128,0.35)' }}>${myShown.toLocaleString()}</span>
                </div>
                <div style={{ ...rev(auditIn, rows.length + 1), fontSize: 12, color: 'var(--text-muted)', marginTop: 8 }}>Every line, explained.</div>
              </div>
            </div>

            {/* gap footer */}
            <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              gap: 20, flexWrap: 'wrap', padding: '16px clamp(18px,3vw,28px)', borderTop: '1px solid var(--line-200)',
              background: 'linear-gradient(90deg, rgba(229,25,42,0.05), rgba(22,214,128,0.07))' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 9, padding: '10px 16px', borderRadius: 'var(--radius-pill)',
                  background: 'var(--inset)', border: '1px solid rgba(22,214,128,0.45)', boxShadow: 'var(--glow-green-sm)' }}>
                  <Ic name="TrendingDown" size={17} color="var(--positive-bright)" />
                  <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, color: 'var(--positive-bright)', fontVariantNumeric: 'tabular-nums' }}>${gapCount}</span>
                  <span style={{ fontSize: 13, color: 'var(--text-body)' }}>saved &middot; {PCT}% less</span>
                </div>
                <span style={{ fontSize: 13.5, color: 'var(--text-muted)', maxWidth: 320 }}>Same parts, same warranty &mdash; the gap was information, not quality.</span>
              </div>
              <button onClick={replay} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '9px 15px',
                cursor: 'pointer', background: 'transparent', border: '1px solid var(--border)', borderRadius: 'var(--radius-pill)',
                color: 'var(--text-muted)', font: 'inherit', fontFamily: 'var(--font-mono)', fontSize: 12 }}>
                <Ic name="RotateCcw" size={13} /> Replay audit
              </button>
            </div>
          </div>
        </Reveal>

        <Reveal delay={120}>
          <p style={{ textAlign: 'center', margin: '24px auto 0', fontSize: 13, color: 'var(--text-faint)', maxWidth: 560 }}>
            Figures are illustrative. Your actual breakdown depends on the vehicle, parts, and a mechanic&rsquo;s inspection.
          </p>
        </Reveal>
      </div>
    </section>
  );
}
window.PriceReveal = PriceReveal;
