/* DiagnosticConsole — pure software diagnostic UI. No hardware illustrations.
   A sleek dark console that looks like ALEROQ's app scanning a car live:
   header → 5 live data tiles (counting) → a single red scan-line pass →
   a fault strip → competing quotes + savings. Auto-plays on scroll, replayable,
   3D-tilt on hover, reduced-motion aware. Beauty from type + layout. */
function DiagnosticConsole() {
  const { Reveal, Ic } = window;
  const light = window.useTheme() === 'light';
  const ROOT = React.useRef(null);
  const cardRef = React.useRef(null);

  // phase: 0 streaming · 1 fault · 2 resolved
  const [phase, setPhase] = React.useState(0);
  const [gauges, setGauges] = React.useState({ rpm: 0, coolant: 0, load: 0, throttle: 0, fuel: 0 });
  const [bids, setBids] = React.useState(0);
  const [save, setSave] = React.useState(0);
  const [scanKey, setScanKey] = React.useState(0);
  const startedRef = React.useRef(false);
  const timers = React.useRef([]);
  const rafs = React.useRef([]);

  const TARGET = { rpm: 820, coolant: 92, load: 34, throttle: 12, fuel: 68 };
  const reduce = () => window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  const tiles = [
    { k: 'rpm', label: 'RPM', unit: '' },
    { k: 'coolant', label: 'Coolant', unit: '°C' },
    { k: 'load', label: 'Load', unit: '%' },
    { k: 'throttle', label: 'Throttle', unit: '%' },
    { k: 'fuel', label: 'Fuel', unit: '%' },
  ];
  const bidData = [
    { shop: 'Apache Auto', rating: '4.9', time: '12 min', price: 180, best: false },
    { shop: 'Tempe Motorworks', rating: '4.7', time: '8 min', price: 210, best: false },
    { shop: 'Valley Mechanics', rating: '4.8', time: '20 min', price: 165, best: true },
  ];

  const clearAll = () => {
    timers.current.forEach(clearTimeout); timers.current = [];
    rafs.current.forEach(cancelAnimationFrame); rafs.current = [];
  };
  const after = (ms, fn) => timers.current.push(setTimeout(fn, ms));
  const countTo = (target, dur, setter) => {
    const start = performance.now();
    const tick = (now) => {
      const t = Math.min((now - start) / dur, 1);
      const eased = 1 - Math.pow(1 - t, 3);
      setter(Math.round(target * eased));
      if (t < 1) rafs.current.push(requestAnimationFrame(tick));
    };
    rafs.current.push(requestAnimationFrame(tick));
  };

  const run = React.useCallback(() => {
    clearAll();
    setPhase(0); setBids(0); setSave(0);
    setGauges({ rpm: 0, coolant: 0, load: 0, throttle: 0, fuel: 0 });
    setScanKey((k) => k + 1);
    if (reduce()) { setGauges(TARGET); setBids(3); setSave(255); setPhase(2); return; }
    // streaming: tiles count up + scan pass
    Object.keys(TARGET).forEach((k) => countTo(TARGET[k], 1300, (v) => setGauges((g) => ({ ...g, [k]: v }))));
    // fault strip after the scan pass
    after(1850, () => setPhase(1));
    // resolution: bids + savings
    after(3050, () => {
      setPhase(2);
      after(220, () => setBids(1));
      after(600, () => setBids(2));
      after(980, () => setBids(3));
      after(1260, () => countTo(255, 900, setSave));
    });
  }, []);

  const replay = () => run();

  // auto-play once on scroll into view. Uses a ref guard (NOT state) so firing
  // never changes a dependency / re-runs this effect / cancels the animation.
  React.useEffect(() => {
    const node = ROOT.current; if (!node) return;
    const check = () => {
      if (startedRef.current) return;
      const r = node.getBoundingClientRect();
      if (r.top < (window.innerHeight || 800) * 0.72 && r.bottom > 80) {
        startedRef.current = true;
        cleanup();
        run();
      }
    };
    const io = new IntersectionObserver((entries) => { entries.forEach((e) => { if (e.isIntersecting) check(); }); }, { threshold: 0.18 });
    io.observe(node);
    window.addEventListener('scroll', check, { passive: true });
    const poll = setInterval(check, 400);
    function cleanup() { io.disconnect(); window.removeEventListener('scroll', check); clearInterval(poll); }
    check();
    return () => { cleanup(); clearAll(); };
  }, []);

  // 3D tilt toward cursor (desktop)
  React.useEffect(() => {
    const card = cardRef.current; if (!card) return;
    if (reduce() || (window.matchMedia && window.matchMedia('(hover: none)').matches)) return;
    let raf = 0;
    const move = (e) => {
      const r = card.getBoundingClientRect();
      const px = (e.clientX - (r.left + r.width / 2)) / r.width;
      const py = (e.clientY - (r.top + r.height / 2)) / r.height;
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => { card.style.transform = `perspective(1500px) rotateY(${px * 4.5}deg) rotateX(${-py * 4.5}deg)`; });
    };
    const leave = () => { cancelAnimationFrame(raf); card.style.transform = 'perspective(1500px) rotateY(-3.5deg) rotateX(1.5deg)'; };
    const zone = card.parentElement;
    zone.addEventListener('pointermove', move); zone.addEventListener('pointerleave', leave);
    return () => { zone.removeEventListener('pointermove', move); zone.removeEventListener('pointerleave', leave); cancelAnimationFrame(raf); };
  }, []);

  const statusCol = phase >= 2 ? 'var(--positive)' : 'var(--accent)';

  return (
    <section id="diagnostic" ref={ROOT} style={{ position: 'relative', padding: 'var(--space-section) clamp(20px, 5vw, 48px)' }}>
      <div style={{ maxWidth: 'var(--container)', margin: '0 auto' }}>
        <Reveal style={{ textAlign: 'center', marginBottom: 52 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 18,
            fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 600, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--accent)' }}>
            <Ic name="ScanLine" size={14} color="var(--accent)" /> Live demo
          </span>
          <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)' }}>
            Cryptic code in. Fair price out.
          </h2>
          <p style={{ fontSize: 'var(--fs-lead)', color: 'var(--text-body)', maxWidth: 560, margin: '0 auto' }}>
            Watch ALEROQ read a car in real time, translate the fault into plain English, and turn it into competing quotes.
          </p>
        </Reveal>

        <div style={{ position: 'relative', perspective: 1500 }}>
          <div aria-hidden="true" style={{ position: 'absolute', left: '50%', bottom: -36, width: '74%', height: 170,
            transform: 'translateX(-50%)', pointerEvents: 'none', borderRadius: '50%', filter: 'blur(8px)',
            background: phase >= 2 ? 'radial-gradient(closest-side, rgba(22,214,128,0.30), transparent 72%)'
              : 'radial-gradient(closest-side, rgba(255,46,63,0.26), transparent 72%)', transition: 'background 1s var(--ease-out)' }} />

          <Reveal dir="scale">
            <div ref={cardRef} className="dcx-card" style={{
              position: 'relative', transformStyle: 'preserve-3d',
              transform: 'perspective(1500px) rotateY(-3.5deg) rotateX(1.5deg)', transition: 'transform 0.4s var(--ease-out)',
              background: light ? 'linear-gradient(180deg, #ffffff, #f4f4f9)' : 'linear-gradient(180deg, #141418, #101013)',
              border: `1px solid ${phase >= 2 ? 'rgba(22,214,128,0.4)' : 'var(--border-hover)'}`,
              borderRadius: 'var(--radius-lg)', overflow: 'hidden',
              boxShadow: light ? '0 40px 90px rgba(0,0,0,0.14), inset 0 1px 0 rgba(255,255,255,0.7)' : '0 50px 110px rgba(0,0,0,0.6), inset 0 1px 0 rgba(255,255,255,0.04)' }}>

              {/* header */}
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap',
                padding: '15px 20px', borderBottom: '1px solid var(--line-100)', background: 'var(--inset)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                  <span className={phase < 2 ? 'blink' : ''} style={{ width: 9, height: 9, borderRadius: '50%', background: statusCol, boxShadow: `0 0 10px ${statusCol}` }} />
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--silver-300)' }}>ALEROQ Diagnostic</span>
                </div>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-muted)' }}>2019 Honda Civic</span>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase',
                    color: 'var(--positive-bright)', border: '1px solid rgba(22,214,128,0.4)', borderRadius: 'var(--radius-pill)', padding: '3px 9px' }}>OBD-II Linked</span>
                </div>
              </div>

              <div style={{ padding: 'clamp(18px, 2.4vw, 26px)' }}>
                {/* 5 live data tiles */}
                <div className="dcx-tiles" style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 10 }}>
                  {tiles.map((t) => (
                    <div key={t.k} style={{ padding: '14px 14px 16px', borderRadius: 'var(--radius-md)',
                      background: 'var(--inset)', border: '1px solid var(--line-100)' }}>
                      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: 10 }}>{t.label}</div>
                      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(24px, 3vw, 32px)', color: 'var(--text-strong)', letterSpacing: '-0.02em', lineHeight: 1 }}>
                        {gauges[t.k]}<span style={{ fontSize: 13, color: 'var(--text-muted)', marginLeft: 2, fontWeight: 600 }}>{t.unit}</span>
                      </div>
                    </div>
                  ))}
                </div>

                {/* single red scan pass */}
                <div style={{ position: 'relative', height: 2, margin: '20px 0 4px', borderRadius: 2, background: 'var(--line-100)', overflow: 'hidden' }}>
                  {phase < 1 && !reduce() && (
                    <div key={scanKey} className="dcx-scan" style={{ position: 'absolute', top: 0, bottom: 0, width: '45%',
                      background: 'linear-gradient(90deg, transparent, var(--accent), transparent)', boxShadow: '0 0 14px var(--accent)' }} />
                  )}
                </div>

                {/* fault strip */}
                <div style={{ marginTop: 18, overflow: 'hidden',
                  maxHeight: phase >= 1 ? 120 : 0, opacity: phase >= 1 ? 1 : 0,
                  transition: 'max-height 0.5s var(--ease-out), opacity 0.45s var(--ease-out)' }}>
                  <div className={phase === 1 ? 'dcx-alert' : ''} style={{ display: 'flex', alignItems: 'center', gap: 'clamp(12px, 2vw, 20px)', flexWrap: 'wrap',
                    padding: '14px 18px', borderRadius: 'var(--radius-md)', background: 'rgba(255,46,63,0.06)', border: '1px solid rgba(255,46,63,0.45)' }}>
                    <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 'clamp(18px, 2.4vw, 22px)', color: 'var(--accent)', letterSpacing: '0.04em' }}>P0301</span>
                    <span style={{ color: 'var(--text-faint)', fontSize: 18 }}>&rarr;</span>
                    <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 'clamp(16px, 2.2vw, 20px)', color: 'var(--text-strong)' }}>Cylinder 1 Misfire</span>
                    <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 11px', borderRadius: 'var(--radius-pill)',
                      background: 'rgba(245,166,35,0.12)', border: '1px solid rgba(245,166,35,0.4)', color: '#f5a623',
                      fontFamily: 'var(--font-mono)', fontSize: 10.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase' }}>Moderate</span>
                  </div>
                </div>

                {/* resolution: competing quotes + savings */}
                <div style={{ overflow: 'hidden', maxHeight: phase >= 2 ? 360 : 0, opacity: phase >= 2 ? 1 : 0,
                  transition: 'max-height 0.6s var(--ease-out), opacity 0.5s var(--ease-out)' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 9, margin: '22px 0 14px', fontFamily: 'var(--font-mono)', fontSize: 11,
                    letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--positive-bright)' }}>
                    <span style={{ flex: '0 0 auto' }}>Competing quotes</span>
                    <span style={{ flex: 1, height: 1, background: 'var(--line-100)' }} />
                  </div>
                  <div className="dcx-bids" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
                    {bidData.map((b, i) => (
                      <div key={b.shop} style={{ position: 'relative', padding: '14px 15px', borderRadius: 'var(--radius-md)',
                        background: b.best ? 'var(--green-tint)' : 'var(--inset)',
                        border: `1px solid ${b.best ? 'rgba(22,214,128,0.5)' : 'var(--line-100)'}`,
                        boxShadow: b.best ? 'var(--glow-green-sm, 0 0 22px rgba(22,214,128,0.2))' : 'none',
                        opacity: bids > i ? 1 : 0, transform: bids > i ? 'none' : 'translateX(18px)',
                        transition: 'opacity 0.5s var(--ease-out), transform 0.5s var(--ease-out)' }}>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 8 }}>
                          <span style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--text-strong)' }}>{b.shop}</span>
                          {b.best && <span style={{ fontFamily: 'var(--font-mono)', fontSize: 8.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
                            color: '#04130c', background: 'var(--positive)', padding: '2px 6px', borderRadius: 'var(--radius-pill)' }}>Best value</span>}
                        </div>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)' }}>{b.rating}★ · {b.time}</span>
                          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19, color: b.best ? 'var(--positive-bright)' : 'var(--text-strong)' }}>${b.price}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap',
                    marginTop: 12, padding: '14px 16px', borderRadius: 'var(--radius-md)', background: 'var(--green-tint)', border: '1px solid rgba(22,214,128,0.4)' }}>
                    <span style={{ fontSize: 13.5, color: 'var(--text-body)' }}>
                      Dealership <span style={{ color: 'var(--text-faint)', textDecoration: 'line-through' }}>$420</span> &rarr; ALEROQ <span style={{ color: 'var(--positive-bright)', fontWeight: 600 }}>$165</span>
                    </span>
                    <span style={{ display: 'inline-flex', alignItems: 'baseline', gap: 6, whiteSpace: 'nowrap' }}>
                      <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>you save</span>
                      <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, color: 'var(--positive-bright)', letterSpacing: '-0.02em' }}>${save}</span>
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </Reveal>
        </div>

        {/* controls */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 18, marginTop: 40, flexWrap: 'wrap' }}>
          <button onClick={replay} style={{ display: 'inline-flex', alignItems: 'center', gap: 9, padding: '12px 22px', cursor: 'pointer',
            background: 'transparent', border: '1px solid var(--border-hover)', borderRadius: 'var(--radius-pill)', color: 'var(--text-body)',
            font: 'inherit', fontFamily: 'var(--font-body)', fontWeight: 500, fontSize: 15, transition: 'border-color var(--dur-base), color var(--dur-base)' }}
            onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--accent)'; e.currentTarget.style.color = 'var(--text-strong)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border-hover)'; e.currentTarget.style.color = 'var(--text-body)'; }}>
            <Ic name="RotateCcw" size={16} /> Run scan again
          </button>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, letterSpacing: '0.06em', color: 'var(--text-faint)' }}>This is a demo</span>
        </div>
      </div>
    </section>
  );
}
window.DiagnosticConsole = DiagnosticConsole;
