/* Blueprint → Build — pinned, layered, GPU-light intro hero.
   Performance model: ONE progress value (0→1) derived from the tall
   section's scroll position, smoothed with a rAF lerp. The loop writes
   a single CSS custom property (--p) on the stage; every layer derives
   its opacity / transform from --p in CSS. No React re-renders during
   scroll, no video seeking, no animated filters or layout properties.
   Mobile: no pinning/scrub — the finished-building frame is shown. */

function BlueprintHero({ onNav }) {
  const wrapRef = React.useRef(null);
  const stageRef = React.useRef(null);
  const canvasRef = React.useRef(null);

  React.useEffect(() => {
    const wrap = wrapRef.current;
    const stage = stageRef.current;
    const canvas = canvasRef.current;
    if (!wrap || !stage || !canvas) return;

    const clamp = (x, a, b) => (x < a ? a : x > b ? b : x);
    const isMobile = window.matchMedia('(max-width: 820px)').matches;

    // ---- Frame sequence: preload all stills, draw the nearest one on a
    // canvas. No video seeking → buttery scroll-scrub. ----
    // First few frames render nearly pure black — skip them so the hero opens
    // on a recognisable Colosseum blueprint instead of an empty void.
    const START = 5;
    const END = 71;
    const N = END - START + 1;
    const SIZE = 1024;
    canvas.width = SIZE;
    canvas.height = SIZE;
    const ctx = canvas.getContext('2d');
    const imgs = new Array(N);
    let loaded = 0;
    let lastDrawn = -1;

    const drawFrame = (idx) => {
      idx = clamp(Math.round(idx), 0, N - 1);
      if (idx === lastDrawn) return;
      const im = imgs[idx];
      if (im && im.complete && im.naturalWidth) {
        ctx.drawImage(im, 0, 0, SIZE, SIZE);
        lastDrawn = idx;
      }
    };

    for (let i = 0; i < N; i++) {
      const im = new Image();
      im.decoding = 'async';
      im.src = 'frames/roman-' + String(i + START).padStart(2, '0') + '.webp';
      im.onload = () => {
        loaded++;
        // Draw the very first frame as soon as it arrives.
        if (i === 0 && lastDrawn === -1) drawFrame(0);
      };
      imgs[i] = im;
    }

    // Mobile: shorter scroll distance feels right on touch; everything else identical.
    if (isMobile) {
      stage.dataset.mobile = '1';
    }

    const phaseCenters = [0.10, 0.38, 0.64, 0.90];
    let lastPhase = -1;

    const writePhase = (p) => {
      let idx = 0, best = 2;
      for (let i = 0; i < phaseCenters.length; i++) {
        const d = Math.abs(p - phaseCenters[i]);
        if (d < best) { best = d; idx = i; }
      }
      if (idx !== lastPhase) { lastPhase = idx; stage.dataset.phase = String(idx); }
    };

    const measure = () => {
      const rect = wrap.getBoundingClientRect();
      const total = wrap.offsetHeight - window.innerHeight;
      return total > 0 ? clamp(-rect.top / total, 0, 1) : 0;
    };

    let target = 0, current = 0, raf = 0;

    // Single smoothing loop: lerp current → target, write --p, draw frame.
    const tick = () => {
      current += (target - current) * 0.14;
      const settled = Math.abs(target - current) < 0.0004;
      if (settled) current = target;
      stage.style.setProperty('--p', current.toFixed(4));
      writePhase(current);
      drawFrame(current * (N - 1));
      if (settled) { raf = 0; return; }
      raf = requestAnimationFrame(tick);
    };

    // Scroll handler is intentionally trivial: read target, kick the loop.
    const onScroll = () => {
      target = measure();
      if (!raf) raf = requestAnimationFrame(tick);
    };

    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll, { passive: true });

    current = target = measure();
    stage.style.setProperty('--p', current.toFixed(4));
    writePhase(current);
    drawFrame(current * (N - 1));

    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  const phases = ['Planung', 'Rohbau', 'Ausbau', 'Fertigstellung'];

  return (
    <section className="bp-hero" ref={wrapRef} id="intro" data-screen-label="Blueprint Hero">
      <div className="bp-stage" ref={stageRef}>
        {/* Scroll-scrubbed hero — nearest still frame drawn to canvas via --p */}
        <div className="bp-frames" aria-hidden="true">
          <canvas ref={canvasRef} className="bp-video"></canvas>
        </div>

        {/* Static legibility layers */}
        <div className="bp-scrim" aria-hidden="true"></div>
        <div className="bp-vignette" aria-hidden="true"></div>

        {/* Catch frames — three punchy claims that scrub through before the final title */}
        <div className="bp-catches" aria-hidden="true">
          <div className="bp-catch" data-i="0">
            <em className="bp-catch-num">01 — Prinzip</em>
            <span className="bp-catch-line">Erst denken.<br/><i>Dann bauen.</i></span>
          </div>
          <div className="bp-catch" data-i="1">
            <em className="bp-catch-num">02 — Anspruch</em>
            <span className="bp-catch-line">Handwerk<br/>mit <i>Haltung.</i></span>
          </div>
          <div className="bp-catch" data-i="2">
            <em className="bp-catch-num">03 — Methode</em>
            <span className="bp-catch-line">Detail. Disziplin.<br/><i>Dauer.</i></span>
          </div>
        </div>

        {/* Phase labels */}
        <div className="bp-phases" aria-hidden="true">
          {phases.map((k, i) => (
            <span key={k} className="bp-phase" data-i={i}><em className="dot"></em>{k}</span>
          ))}
        </div>

        {/* Content overlay */}
        <div className="bp-content">
          <div className="bp-eyebrow"><span className="ln"></span>Bau · Sanierung · Ausbau</div>
          <h1 className="bp-title"><span className="ln1">Vom Bauplan</span><span className="ln2">zur <em>Realität.</em></span></h1>
          <p className="bp-sub">Ottoman Pro realisiert hochwertige Bauprojekte mit Präzision, Erfahrung und klarer Planung.</p>
          <div className="bp-actions">
            <a className="btn btn-primary" onClick={() => onNav('contact')}><span className="dot"></span>Projekt anfragen</a>
            <a className="btn btn-ghost" onClick={() => onNav('services')}>Leistungen ansehen</a>
          </div>
        </div>

        {/* Scroll hint + progress rail */}
        <div className="bp-hint"><span>Scrollen</span><span className="bp-hint-track"></span></div>
        <div className="bp-rail" aria-hidden="true"><span></span></div>
      </div>
    </section>
  );
}