/* Hero — full-bleed car scene. Opens anxious (red "fault" state) and resolves to
   a calm green "diagnosed · you saved" exhale. Replayable. Headline animates in
   word by word; the resolution line shifts red -> green when the scan clears. */
function Hero() {
  const { Button, Badge } = window.RevvoDesignSystem_a89086;
  const { Ic, Parallax } = window;
  const light = window.useTheme() === 'light';
  const headerRef = React.useRef(null);
  const carRef = React.useRef(null);
  const hudRef = React.useRef(null);

  // Mouse-driven 3D parallax: car drifts one way, HUD the other, for depth.
  React.useEffect(() => {
    const header = headerRef.current;
    if (!header) return;
    if (window.matchMedia && (window.matchMedia('(hover: none)').matches || window.matchMedia('(prefers-reduced-motion: reduce)').matches)) return;
    let raf = 0;
    const onMove = (e) => {
      const r = header.getBoundingClientRect();
      const mx = (e.clientX - r.left) / r.width - 0.5;
      const my = (e.clientY - r.top) / r.height - 0.5;
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        if (carRef.current) carRef.current.style.transform = `scale(1.06) translate(${(-mx * 22).toFixed(1)}px, ${(-my * 14).toFixed(1)}px)`;
        if (hudRef.current) hudRef.current.style.transform = `translate(${(mx * 26).toFixed(1)}px, ${(my * 18).toFixed(1)}px)`;
      });
    };
    const reset = () => {
      if (carRef.current) carRef.current.style.transform = 'scale(1.06)';
      if (hudRef.current) hudRef.current.style.transform = 'none';
    };
    header.addEventListener('pointermove', onMove);
    header.addEventListener('pointerleave', reset);
    return () => { header.removeEventListener('pointermove', onMove); header.removeEventListener('pointerleave', reset); cancelAnimationFrame(raf); };
  }, []);

  const [phase, setPhase] = React.useState('fault'); // fault -> scanning -> resolved
  const [runId, setRunId] = React.useState(0);
  const timers = React.useRef([]);
  React.useEffect(() => {
    timers.current.forEach(clearTimeout);
    timers.current = [];
    setPhase('fault');
    if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      setPhase('resolved'); return;
    }
    timers.current.push(setTimeout(() => setPhase('scanning'), 1500));
    timers.current.push(setTimeout(() => setPhase('resolved'), 3200));
    return () => timers.current.forEach(clearTimeout);
  }, [runId]);
  const resolved = phase === 'resolved';
  const scanning = phase === 'scanning';
  const savings = window.useCountUp(427, resolved, 1300);
  const replay = () => setRunId((n) => n + 1);

  const line1 = ['Your', 'car', 'knows', 'what\u2019s', 'wrong.'];
  const line2 = ['Now', 'so', 'do', 'you.'];
  const word = (w, color) => (
    <span key={w} style={{ display: 'inline-block', marginRight: '0.28em', color }}>{w}</span>
  );

  // HUD chips reflect the arc: red warnings -> green all-clear.
  const hud = resolved ? [
    { label: 'Diagnosed', top: '21%', right: '7%', speed: 0.5, delay: '0s', good: true },
    { label: 'Best quote $312', top: '40%', right: '19%', speed: 0.34, delay: '0.8s', good: true },
    { label: 'You save $427', top: '62%', right: '8%', speed: 0.42, delay: '0.4s', good: true },
    { label: 'All systems clear', top: '75%', right: '23%', speed: 0.28, delay: '1.2s', good: true },
  ] : [
    { label: 'LIVE OBD-II', top: '21%', right: '7%', speed: 0.5, delay: '0s', dot: true },
    { label: 'P0301 · Misfire', top: '40%', right: '19%', speed: 0.34, delay: '0.8s', warn: true },
    { label: 'Coolant 94°C', top: '62%', right: '8%', speed: 0.42, delay: '0.4s' },
    { label: 'Scanning…', top: '75%', right: '23%', speed: 0.28, delay: '1.2s', dot: scanning },
  ];

  const glow = resolved
    ? 'radial-gradient(closest-side, rgba(22,214,128,0.30), rgba(22,214,128,0.06) 58%, transparent 78%)'
    : 'radial-gradient(closest-side, rgba(255,46,63,0.24), rgba(255,46,63,0.05) 55%, transparent 76%)';

  return (
    <header ref={headerRef} style={{
      position: 'relative', minHeight: '100vh', display: 'flex', alignItems: 'center',
      padding: '120px clamp(20px, 5vw, 64px) 110px', overflow: 'hidden', boxSizing: 'border-box',
    }}>
      {/* car image, gentle scroll parallax (mouse 3D applied to inner layer) */}
      <Parallax speed={0.1} style={{ position: 'absolute', inset: 0, zIndex: 0 }}>
        <div ref={carRef} style={{
          position: 'absolute', top: '-9%', left: '-6%', width: '112%', height: '120%',
          backgroundImage: 'url("hero-car.png")', backgroundSize: 'cover', backgroundPosition: 'center right',
          transform: 'scale(1.06)', willChange: 'transform',
          filter: resolved ? 'hue-rotate(118deg) saturate(1.18) brightness(1.04)' : 'none',
          transition: 'filter 1.7s var(--ease-in-out)',
        }} />
      </Parallax>
      {/* left->right legibility wash so the headline stays crisp — tinted to the
          active theme so the hero reads light in light mode, dark in dark mode */}
      <div style={{
        position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none',
        background: light
          ? 'linear-gradient(90deg, #f3f3f7 0%, rgba(243,243,247,0.9) 26%, rgba(243,243,247,0.5) 52%, rgba(243,243,247,0) 78%)'
          : 'linear-gradient(90deg, #0B0B0D 0%, rgba(11,11,13,0.82) 28%, rgba(11,11,13,0.34) 56%, rgba(11,11,13,0) 80%)',
      }} />
      <div style={{
        position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none',
        background: light
          ? 'linear-gradient(180deg, rgba(243,243,247,0.7) 0%, transparent 22%, transparent 56%, #f3f3f7 100%)'
          : 'linear-gradient(180deg, rgba(11,11,13,0.55) 0%, transparent 24%, transparent 68%, #0B0B0D 100%)',
      }} />
      {/* arc glow: red fault -> green resolved */}
      <div className="hero-glow" style={{
        position: 'absolute', top: '46%', left: '62%', width: 'min(900px, 80vw)', height: '640px',
        transform: 'translate(-50%, -50%)', pointerEvents: 'none', zIndex: 1,
        background: glow, mixBlendMode: 'screen', transition: 'background 1.6s var(--ease-in-out)',
      }} />

      {/* floating HUD chips */}
      <div ref={hudRef} className="hud-hide" style={{ position: 'absolute', inset: 0, zIndex: 2, pointerEvents: 'none', willChange: 'transform', transition: 'transform 0.2s var(--ease-out)' }}>
        {hud.map((h, i) => {
          const col = h.good ? 'var(--positive-bright)' : h.warn ? 'var(--red-300)' : 'var(--text-body)';
          const bd = h.good ? 'rgba(22,214,128,0.42)' : h.warn ? 'rgba(255,46,63,0.42)' : 'var(--border)';
          return (
            <Parallax key={i} speed={h.speed} style={{ position: 'absolute', top: h.top, right: h.right }}>
              <span key={resolved ? 'r' : 'f'} className="hud-chip" style={{
                display: 'inline-flex', alignItems: 'center', gap: 8, padding: '8px 13px',
                borderRadius: 'var(--radius-pill)', background: light ? 'rgba(255,255,255,0.72)' : 'rgba(14,14,18,0.5)',
                backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)',
                border: `1px solid ${bd}`, fontFamily: 'var(--font-mono)', fontSize: 12,
                letterSpacing: '0.04em', color: col, whiteSpace: 'nowrap',
                boxShadow: light ? '0 8px 28px rgba(0,0,0,0.14)' : '0 8px 28px rgba(0,0,0,0.45)', animation: `hudFloat 8s var(--ease-in-out) ${h.delay} infinite`,
              }}>
                {h.good
                  ? <Ic name="Check" size={13} color="var(--positive-bright)" />
                  : (h.dot || h.warn) && <span className="blink" style={{
                      width: 7, height: 7, borderRadius: '50%', background: h.warn ? 'var(--accent)' : 'var(--silver-300)',
                      boxShadow: `0 0 8px ${h.warn ? 'var(--accent)' : 'transparent'}`,
                    }} />}
                {h.label}
              </span>
            </Parallax>
          );
        })}
      </div>

      {/* content */}
      <div style={{ position: 'relative', zIndex: 3, maxWidth: 'var(--container)', margin: '0 auto', width: '100%' }}>
        <div style={{ maxWidth: 680 }}>
          <div style={{ marginBottom: 26, minHeight: 30 }}>
            {resolved
              ? <Badge key="r" variant="solid" dot style={{ background: 'var(--positive)', color: '#04130c', whiteSpace: 'nowrap' }}>Diagnosed · You saved ${savings}</Badge>
              : <Badge key="f" variant="accent" dot>{scanning ? 'Scanning your car…' : 'Fault detected'}</Badge>}
          </div>
          <h1 style={{
            fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(44px, 6.4vw, 82px)',
            lineHeight: 1.03, letterSpacing: 'var(--ls-tight)', margin: '0 0 26px',
          }}>
            {line1.map((w, i) => word(w, i === line1.length - 1 ? 'var(--accent)' : 'var(--text-strong)'))}<br />
            {line2.map((w) => word(w, resolved ? 'var(--positive-bright)' : 'var(--text-strong)'))}
          </h1>
          <p style={{
            fontFamily: 'var(--font-body)', fontSize: 'var(--fs-lead)', lineHeight: 1.6,
            color: 'var(--text-body)', maxWidth: 500, margin: '0 0 38px', textWrap: 'pretty',
          }}>
            ALEROQ reads your car&rsquo;s diagnostics, explains every issue in plain English,
            and makes mechanics compete &mdash; so you never overpay again.
          </p>
          <div style={{ display: 'flex', gap: 18, flexWrap: 'wrap', alignItems: 'center' }}>
            <div style={{ display: 'inline-flex' }}>
              <window.Magnetic strength={0.22}>
                <Button variant="positive" size="lg" className="pulse-glow" onClick={() => window.aleroqScrollTo('waitlist')}>
                  Join the Waitlist
                </Button>
              </window.Magnetic>
            </div>
            <div style={{ display: 'inline-flex' }}>
              <window.Magnetic strength={0.18}>
                <Button variant="ghost" size="lg" onClick={replay}>
                  <Ic name="RotateCcw" size={16} /> Replay the scan
                </Button>
              </window.Magnetic>
            </div>
          </div>
          <div style={{
            marginTop: 22, display: 'flex', alignItems: 'center', gap: 9,
            fontFamily: 'var(--font-mono)', fontSize: 12.5, letterSpacing: '0.02em', color: 'var(--text-muted)',
          }}>
            <Ic name="PlugZap" size={14} color="var(--silver-300)" />
            Works with most cars built after 1996 &middot; no credit card to join
          </div>
        </div>
      </div>

      <div className="scroll-cue" style={{
        position: 'absolute', bottom: 30, left: '50%', transform: 'translateX(-50%)', zIndex: 3,
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7,
        color: 'var(--text-muted)', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em',
      }}>
        <span>SCROLL</span>
        <Ic name="ChevronDown" size={18} />
      </div>
    </header>
  );
}

window.Hero = Hero;
