/* IMMERSIVE cinematic hero — Dexpress
   Truly different now: Canvas-driven motion blur on the photo, animated rain/streaks
   along motion vectors, depth-of-field bokeh from passing lights, dynamic colour
   grade that shifts with time-of-day cycle, and a true "speed line" effect
   that makes the truck feel like it's moving at 100 km/h. */

function CinematicHighwayHero({ eyebrow, title, sub, primary, secondary, kicker, photo = 'assets/truck-highway-1.jpg' }) {
  const canvasRef = React.useRef(null);
  const photoRef = React.useRef(null);
  const [t, setT] = React.useState(0);
  const [loaded, setLoaded] = React.useState(false);

  React.useEffect(() => {
    let raf; const start = performance.now();
    const loop = (now) => { setT((now - start) / 1000); raf = requestAnimationFrame(loop); };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  // Canvas particle system: speed lines + bokeh + rain streaks
  React.useEffect(() => {
    const c = canvasRef.current;
    if (!c) return;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    const resize = () => {
      c.width = c.clientWidth * dpr;
      c.height = c.clientHeight * dpr;
    };
    resize();
    window.addEventListener('resize', resize);
    const ctx = c.getContext('2d');

    // particles — moderate density, calmer speeds (still constant motion)
    const speedLines = Array.from({length: 110}, () => ({
      x: Math.random(), y: Math.random(),
      len: 0.04 + Math.random() * 0.28,
      v: 0.5 + Math.random() * 1.6,
      a: 0.12 + Math.random() * 0.5,
    }));
    const bokeh = Array.from({length: 18}, () => ({
      x: Math.random(), y: 0.25 + Math.random() * 0.6,
      r: 8 + Math.random() * 32,
      v: 0.05 + Math.random() * 0.20,
      hue: Math.random() < 0.6 ? 'warm' : (Math.random() < 0.5 ? 'red' : 'blue'),
      a: 0.2 + Math.random() * 0.4,
    }));

    let raf;
    const draw = () => {
      const w = c.width, h = c.height;
      ctx.clearRect(0, 0, w, h);

      // Speed lines (horizontal motion blur streaks)
      ctx.lineCap = 'round';
      for (const p of speedLines) {
        p.x -= p.v * 0.012;
        if (p.x < -0.3) p.x = 1 + Math.random() * 0.2;
        const grad = ctx.createLinearGradient((p.x + p.len) * w, p.y * h, p.x * w, p.y * h);
        grad.addColorStop(0, `rgba(245,242,236,${p.a})`);
        grad.addColorStop(1, 'rgba(245,242,236,0)');
        ctx.strokeStyle = grad;
        ctx.lineWidth = 0.8 * dpr;
        ctx.beginPath();
        ctx.moveTo(p.x * w, p.y * h);
        ctx.lineTo((p.x + p.len) * w, p.y * h);
        ctx.stroke();
      }

      // Bokeh — soft glowing orbs drifting (out-of-focus oncoming lights)
      for (const b of bokeh) {
        b.x -= b.v * 0.008;
        if (b.x < -0.2) { b.x = 1.1 + Math.random() * 0.3; b.y = 0.3 + Math.random() * 0.5; }
        const r = b.r * dpr;
        const cx = b.x * w, cy = b.y * h;
        const grad = ctx.createRadialGradient(cx, cy, 0, cx, cy, r);
        const color = b.hue === 'red' ? '255,80,90' : b.hue === 'blue' ? '120,160,255' : '255,230,180';
        grad.addColorStop(0, `rgba(${color},${b.a})`);
        grad.addColorStop(0.4, `rgba(${color},${b.a * 0.4})`);
        grad.addColorStop(1, `rgba(${color},0)`);
        ctx.fillStyle = grad;
        ctx.beginPath();
        ctx.arc(cx, cy, r, 0, Math.PI * 2);
        ctx.fill();
      }

      raf = requestAnimationFrame(draw);
    };
    draw();
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', resize); };
  }, []);

  // TRULY continuous forward zoom — two layers offset by half a cycle.
  // Cycle tuned slower for a calmer dolly while particles still carry motion.
  const cycle = 14;                                          // seconds per zoom — calmer pace
  const phaseA = (t % cycle) / cycle;                        // 0 → 1 (layer A)
  const phaseB = ((t + cycle / 2) % cycle) / cycle;          // 0 → 1 (layer B, offset)
  const zoomA = 1.0 + phaseA * 0.18;                         // 1.0 → 1.18
  const zoomB = 1.0 + phaseB * 0.18;
  // Sine² crossfade — A peaks when B snaps, vice versa
  const opA = Math.sin(phaseA * Math.PI) ** 2;
  const opB = Math.sin(phaseB * Math.PI) ** 2;
  const sum = opA + opB || 1;
  const aOpacity = opA / sum;
  const bOpacity = opB / sum;

  // Live HUD
  const speed = 98 + Math.round(4 * Math.sin(t * 0.6));

  // Camera-jostle: tiny irregular vertical bob (chase-vehicle on imperfect pavement)
  // Sub-pixel amplitude, multi-frequency — reads as "alive" not "shaking"
  const jostleY = Math.sin(t * 7.3) * 0.6 + Math.sin(t * 11.7) * 0.4 + Math.sin(t * 3.1) * 0.3;
  const jostleX = Math.sin(t * 5.2) * 0.4 + Math.sin(t * 13.1) * 0.2;

  // Heat shimmer phase — oscillates the road-level distortion band
  const heatPhase = Math.sin(t * 2.4) * 0.5 + Math.sin(t * 3.7) * 0.5;

  // Time-of-day color shift
  const phase = (t * 0.02) % 1;
  const warmth = 0.4 + 0.4 * Math.sin(phase * Math.PI * 2);

  return (
    <section className="hero-cinema" style={{position:'relative', height:'100vh', minHeight: 720, overflow:'hidden', background:'#000',
      transform: `translate(${jostleX}px, ${jostleY}px)`, willChange:'transform'}}>

      {/* === DOLLY LAYER A — background blur + sharp foreground === */}
      <div style={{position:'absolute', inset:0, opacity: aOpacity}}>
        <img src={photo} alt="" onLoad={() => setLoaded(true)} style={{
          position:'absolute', inset:'-4%', width:'108%', height:'108%', objectFit:'cover',
          transform: `scale(${zoomA * 1.05})`, transformOrigin: 'center 60%',
          filter: `contrast(1.15) saturate(0.7) brightness(0.42) blur(6px) hue-rotate(${-8 + warmth * 16}deg)`,
          willChange: 'transform',
        }}/>
        <img ref={photoRef} src={photo} alt="" style={{
          position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover',
          transform: `scale(${zoomA})`, transformOrigin: 'center 60%',
          filter: `contrast(1.18) saturate(0.78) brightness(0.6) hue-rotate(${-4 + warmth * 8}deg)`,
          willChange: 'transform',
          maskImage: 'radial-gradient(ellipse 60% 70% at 55% 60%, #000 50%, transparent 100%)',
          WebkitMaskImage: 'radial-gradient(ellipse 60% 70% at 55% 60%, #000 50%, transparent 100%)',
        }}/>
      </div>

      {/* === DOLLY LAYER B — same, half-cycle offset, fades in as A fades out === */}
      <div style={{position:'absolute', inset:0, opacity: bOpacity}}>
        <img src={photo} alt="" style={{
          position:'absolute', inset:'-4%', width:'108%', height:'108%', objectFit:'cover',
          transform: `scale(${zoomB * 1.05})`, transformOrigin: 'center 60%',
          filter: `contrast(1.15) saturate(0.7) brightness(0.42) blur(6px) hue-rotate(${-8 + warmth * 16}deg)`,
          willChange: 'transform',
        }}/>
        <img src={photo} alt="" style={{
          position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover',
          transform: `scale(${zoomB})`, transformOrigin: 'center 60%',
          filter: `contrast(1.18) saturate(0.78) brightness(0.6) hue-rotate(${-4 + warmth * 8}deg)`,
          willChange: 'transform',
          maskImage: 'radial-gradient(ellipse 60% 70% at 55% 60%, #000 50%, transparent 100%)',
          WebkitMaskImage: 'radial-gradient(ellipse 60% 70% at 55% 60%, #000 50%, transparent 100%)',
        }}/>
      </div>

      {/* === Layer 3: Canvas particle system (speed lines, bokeh) === */}
      <canvas ref={canvasRef} style={{
        position:'absolute', inset:0, width:'100%', height:'100%',
        zIndex: 2, pointerEvents:'none',
        mixBlendMode:'screen',
      }}/>

      {/* === Road-level dust haze — warm particles drifting along the bottom third,
              suggests dust kicked up around the wheels without animating them === */}
      <div style={{position:'absolute', left:0, right:0, bottom:'18%', height:'30%', zIndex:2, pointerEvents:'none', overflow:'hidden', mixBlendMode:'screen', opacity:0.55}}>
        {[0,1,2,3,4,5,6,7].map(i => {
          const seed = i * 1.7;
          const x = ((t * (0.04 + i * 0.012) + seed) % 1.4) * 100 - 20;
          const y = 20 + 60 * ((Math.sin(t * 0.3 + seed) + 1) / 2);
          const sz = 180 + (i % 3) * 90;
          return (
            <div key={i} style={{
              position:'absolute', left:`${x}%`, top:`${y}%`,
              width: sz, height: sz, marginLeft: -sz/2, marginTop: -sz/2,
              background:'radial-gradient(circle, rgba(220,200,160,0.35) 0%, rgba(180,160,130,0.12) 35%, transparent 70%)',
              filter:'blur(8px)',
            }}/>
          );
        })}
      </div>

      {/* === Heat-shimmer band at road level — slight vertical squeeze of
              a thin slice, oscillating, sells "hot asphalt" without warping the truck === */}
      <div style={{position:'absolute', left:0, right:0, bottom:'14%', height: 32, zIndex:2, pointerEvents:'none',
        background:'linear-gradient(180deg, transparent, rgba(255,200,140,0.06), transparent)',
        transform: `scaleY(${1 + heatPhase * 0.06}) translateY(${heatPhase * 1.5}px)`,
        filter:'blur(0.6px)',
        mixBlendMode:'screen',
      }}></div>

      {/* === Layer 4: Anamorphic letterbox === */}
      <div style={{position:'absolute', top:0, left:0, right:0, height:48, background:'linear-gradient(180deg, #000 0%, transparent 100%)', zIndex:3, pointerEvents:'none'}}></div>
      <div style={{position:'absolute', bottom:0, left:0, right:0, height:160, background:'linear-gradient(0deg, #000 0%, rgba(0,0,0,0.6) 50%, transparent 100%)', zIndex:3, pointerEvents:'none'}}></div>

      {/* === Layer 5: Cinematic colour grade === */}
      <div style={{position:'absolute', inset:0, zIndex:3, pointerEvents:'none', mixBlendMode:'multiply',
        background: `linear-gradient(180deg, rgba(20,30,55,0.5) 0%, rgba(40,30,40,0.2) 40%, rgba(80,25,28,0.4) 100%)`}}></div>
      <div style={{position:'absolute', inset:0, zIndex:3, pointerEvents:'none', mixBlendMode:'screen',
        background: `radial-gradient(ellipse at 80% 30%, rgba(120,160,255,0.10) 0%, transparent 45%), radial-gradient(ellipse at 30% 90%, rgba(217,39,46,0.18) 0%, transparent 50%)`}}></div>

      {/* === Layer 6: Lens flare from approaching headlight === */}
      <div style={{position:'absolute',
        left: `${20 + 60 * ((t * 0.05) % 1)}%`,
        top: `${48 + 6 * Math.sin(t * 0.3)}%`,
        width: 300, height: 300,
        marginLeft: -150, marginTop: -150,
        background: 'radial-gradient(circle, rgba(255,247,217,0.45) 0%, rgba(255,247,217,0.1) 25%, transparent 60%)',
        zIndex: 3, pointerEvents:'none', mixBlendMode:'screen',
        opacity: 0.4 + 0.3 * Math.sin(t * 0.4),
        filter: 'blur(2px)',
      }}></div>

      {/* === Layer 7: Chromatic aberration band (subtle) === */}
      <div style={{position:'absolute', inset:0, zIndex:3, pointerEvents:'none',
        background:'linear-gradient(90deg, rgba(255,0,40,0.04) 0%, transparent 4%, transparent 96%, rgba(0,180,255,0.04) 100%)'}}></div>

      {/* === Layer 8: Film grain === */}
      <div className="grain" style={{zIndex:3, opacity:0.10}}></div>

      {/* === Layer 9: Vertical edge vignette === */}
      <div style={{position:'absolute', inset:0, zIndex:3, pointerEvents:'none',
        background:'radial-gradient(ellipse 90% 100% at 50% 50%, transparent 40%, rgba(0,0,0,0.55) 100%)'}}></div>

      {/* === Top HUD === */}
      <div className="wrap hero-top-hud" style={{position:'relative', zIndex:5, paddingTop:108}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap:12}}>
          <span className="pill" style={{background:'rgba(0,0,0,0.6)', backdropFilter:'blur(10px)', WebkitBackdropFilter:'blur(10px)', border:'1px solid rgba(217,39,46,0.4)'}}>
            <span className="dot live"></span>{kicker || 'DISPATCH LIVE · 24/7'}
          </span>
          <span className="mono hero-coords" style={{color:'rgba(217,39,46,0.85)', letterSpacing:'0.18em', display:'flex', alignItems:'center', gap:8}}>
            <span style={{width:8, height:8, borderRadius:'50%', background:'var(--red)', boxShadow:'0 0 12px var(--red)', animation:'livepulse 1.4s infinite'}}></span>
            REC ● {String(Math.floor(t/60)).padStart(2,'0')}:{String(Math.floor(t)%60).padStart(2,'0')}.{String(Math.floor(t*100)%100).padStart(2,'0')}
          </span>
        </div>
      </div>

      {/* === Main copy === */}
      <div className="wrap hero-copy" style={{position:'absolute', left:0, right:0, bottom: 150, zIndex: 5}}>
        <div className="eyebrow" style={{marginBottom:24, color:'rgba(245,242,236,0.75)'}}>{eyebrow}</div>
        <h1 className="h-display h1" style={{margin:0, maxWidth:'14ch', textShadow:'0 6px 50px rgba(0,0,0,0.8), 0 2px 12px rgba(0,0,0,0.6)'}}>{title}</h1>
        <p className="lede" style={{marginTop:24, maxWidth:'56ch', color:'rgba(245,242,236,0.95)', textShadow:'0 2px 24px rgba(0,0,0,0.8)'}}>{sub}</p>
        <div style={{display:'flex', gap:14, marginTop:36, flexWrap:'wrap'}}>
          {primary}
          {secondary}
        </div>
      </div>

      {/* === Bottom HUD with telemetry === */}
      <div className="hero-bottom-hud" style={{position:'absolute', left:0, right:0, bottom:0, zIndex:5, borderTop:'1px solid rgba(245,242,236,0.15)', background:'linear-gradient(180deg, transparent, rgba(0,0,0,0.85))'}}>
        <div className="wrap hero-hud-grid" style={{display:'grid', gridTemplateColumns:'repeat(5, 1fr)', gap:0, padding:'18px 0'}}>
          <HudCell k="LANE" v="ON-401 W" />
          <HudCell k="SPEED" v={`${speed} KM/H`} live />
          <HudCell k="HEADING" v="265° W" />
          <HudCell k="ETA" v="03h 42m" />
          <HudCell k="UNIT" v="DEXP-047" accent />
        </div>
      </div>

      {/* Speedometer-style ring on right */}
      <div className="hero-speedo" style={{position:'absolute', right: 36, top:'50%', marginTop: -60, width:120, height:120, zIndex:5, pointerEvents:'none'}}>
        <svg viewBox="0 0 120 120" width="120" height="120">
          <circle cx="60" cy="60" r="52" fill="none" stroke="rgba(245,242,236,0.1)" strokeWidth="1"/>
          <circle cx="60" cy="60" r="52" fill="none" stroke="var(--red)" strokeWidth="2"
            strokeDasharray={`${(speed/120) * 326} 326`} strokeLinecap="round"
            transform="rotate(-90 60 60)" style={{filter:'drop-shadow(0 0 6px rgba(217,39,46,0.6))'}}/>
          <text x="60" y="58" fill="#F5F2EC" fontSize="22" fontFamily="Archivo, sans-serif" fontWeight="800" textAnchor="middle">{speed}</text>
          <text x="60" y="76" fill="rgba(245,242,236,0.6)" fontSize="9" fontFamily="JetBrains Mono, monospace" letterSpacing="2" textAnchor="middle">KM/H</text>
        </svg>
      </div>

      {/* Brand seal lines */}
      <div className="hero-seal" style={{position:'absolute', left:0, top:'50%', width:60, height:1, background:'var(--red)', zIndex:5, opacity:0.8, boxShadow:'0 0 8px var(--red)'}}></div>
    </section>
  );
}

function HudCell({ k, v, accent, live }) {
  return (
    <div style={{padding:'0 24px', borderRight:'1px solid rgba(245,242,236,0.12)'}}>
      <div className="mono" style={{color:'rgba(245,242,236,0.5)', fontSize:10, letterSpacing:'0.2em', display:'flex', alignItems:'center', gap:6}}>
        {live && <span style={{width:5, height:5, borderRadius:'50%', background:'#4ade80', boxShadow:'0 0 6px #4ade80'}}></span>}
        {k}
      </div>
      <div className="mono" style={{color: accent ? 'var(--red)' : 'var(--ink)', fontSize:14, marginTop:4, letterSpacing:'0.08em'}}>{v}</div>
    </div>
  );
}

window.CinematicHighwayHero = CinematicHighwayHero;
