// Hero.jsx — neon/dark rework
// Filtration-chamber animation: particles rise through 5 horizontal stages.
// "Contaminants" (tinted, jittery) get caught at each stage line; clean
// molecules (cyan, smooth) pass through. By the top, only clean ones remain.
function Hero({ variant }) {
  const canvasRef = React.useRef(null);

  React.useEffect(() => {
    const canvas = canvasRef.current; if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const dpr = Math.min(window.devicePixelRatio || 1, 2);

    const resize = () => {
      const r = canvas.getBoundingClientRect();
      canvas.width  = r.width  * dpr;
      canvas.height = r.height * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    const ro = new ResizeObserver(resize); ro.observe(canvas);

    // 5 filtration stages as y-fractions (top→bottom order of how water
    // moves UP through them). Stage 5 is lowest (inlet), stage 0 near the top.
    const STAGES = [0.18, 0.34, 0.50, 0.66, 0.82];

    const rand = (a, b) => a + Math.random() * (b - a);

    // particle factory
    const spawn = () => {
      const clean = Math.random() > 0.42;
      return {
        x: rand(0.08, 0.92),          // fractional x
        y: 1.05,                      // start below frame
        vy: rand(0.0016, 0.0032),     // rise speed (frac/ms)
        wobble: rand(0.8, 2.2),       // horizontal jitter amplitude (px)
        phase: rand(0, Math.PI * 2),
        r: clean ? rand(1.4, 2.6) : rand(2.2, 3.6),
        clean,
        life: 1,
        caught: false,
        caughtAt: 0,
        stageIdx: 0,                  // how many stages it's passed
      };
    };

    const particles = Array.from({ length: 80 }, () => {
      const p = spawn();
      p.y = rand(0.2, 1.1);            // prefill
      return p;
    });

    // ripples (when a contaminant is caught)
    const ripples = [];

    let raf; let last = performance.now();

    const draw = (t) => {
      const dt = Math.min(t - last, 40); last = t;
      const W = canvas.width / dpr, H = canvas.height / dpr;

      ctx.clearRect(0, 0, W, H);

      // --- stage lines (filtration membranes) ---
      STAGES.forEach((sy, i) => {
        const y = sy * H;
        // faint line
        const g = ctx.createLinearGradient(0, y, W, y);
        g.addColorStop(0,   'rgba(0,229,255,0)');
        g.addColorStop(0.5, 'rgba(0,229,255,0.35)');
        g.addColorStop(1,   'rgba(0,229,255,0)');
        ctx.strokeStyle = g;
        ctx.lineWidth = 1;
        ctx.setLineDash([4, 6]);
        ctx.beginPath(); ctx.moveTo(10, y); ctx.lineTo(W - 10, y); ctx.stroke();
        ctx.setLineDash([]);

        // stage label
        ctx.fillStyle = 'rgba(0,229,255,0.45)';
        ctx.font = '9px "IBM Plex Mono", monospace';
        ctx.fillText(`0${STAGES.length - i}`, 8, y - 4);
      });

      // --- ripples (caught contaminants) ---
      for (let i = ripples.length - 1; i >= 0; i--) {
        const r = ripples[i];
        r.age += dt;
        const p = r.age / r.ttl;
        if (p >= 1) { ripples.splice(i, 1); continue; }
        ctx.strokeStyle = `rgba(255,70,90,${0.5 * (1 - p)})`;
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.arc(r.x, r.y, 2 + p * 16, 0, Math.PI * 2);
        ctx.stroke();
      }

      // --- particles ---
      particles.forEach((p, idx) => {
        if (p.caught) {
          // fade out at the stage line
          p.caughtAt += dt;
          const k = p.caughtAt / 600;
          if (k >= 1) { particles[idx] = spawn(); return; }
          const px = p.x * W + Math.sin(p.phase + t * 0.008) * p.wobble;
          const py = p.capturedY;
          ctx.fillStyle = `rgba(255,70,90,${0.8 * (1 - k)})`;
          ctx.beginPath();
          ctx.arc(px, py, p.r * (1 + k * 0.6), 0, Math.PI * 2);
          ctx.fill();
          return;
        }

        const prevY = p.y;
        p.y -= p.vy * dt;
        p.phase += dt * 0.003;

        // check if it crossed a stage line this frame
        for (let s = 0; s < STAGES.length; s++) {
          const sy = STAGES[s];
          if (prevY > sy && p.y <= sy && p.stageIdx === STAGES.length - 1 - s) {
            p.stageIdx++;
            // contaminant gets caught at stage 1 or 2 (bottom-most membranes)
            if (!p.clean && p.stageIdx >= 1 + (p.r > 3 ? 0 : 1)) {
              p.caught = true;
              p.capturedY = sy * H;
              ripples.push({
                x: p.x * W + Math.sin(p.phase + t * 0.008) * p.wobble,
                y: sy * H, age: 0, ttl: 900,
              });
            }
          }
        }

        if (p.y < -0.05) { particles[idx] = spawn(); return; }

        const px = p.x * W + Math.sin(p.phase + t * 0.008) * p.wobble;
        const py = p.y * H;

        // trail
        const tg = ctx.createLinearGradient(px, py, px, py + 18);
        if (p.clean) {
          tg.addColorStop(0, 'rgba(0,229,255,0.6)');
          tg.addColorStop(1, 'rgba(0,229,255,0)');
        } else {
          tg.addColorStop(0, 'rgba(255,70,90,0.6)');
          tg.addColorStop(1, 'rgba(255,70,90,0)');
        }
        ctx.strokeStyle = tg;
        ctx.lineWidth = p.r * 0.8;
        ctx.lineCap = 'round';
        ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px, py + 14); ctx.stroke();

        // molecule
        ctx.fillStyle = p.clean ? '#00E5FF' : '#FF465A';
        ctx.shadowColor = p.clean ? 'rgba(0,229,255,0.9)' : 'rgba(255,70,90,0.8)';
        ctx.shadowBlur = p.clean ? 10 : 5;
        ctx.beginPath(); ctx.arc(px, py, p.r, 0, Math.PI * 2); ctx.fill();
        ctx.shadowBlur = 0;
      });

      raf = requestAnimationFrame(draw);
    };
    raf = requestAnimationFrame(draw);
    return () => { cancelAnimationFrame(raf); ro.disconnect(); };
  }, []);

  return (
    <section className="hero" data-screen-label="01 Hero">
      <div className="wrap">
        <div className="hero-grid">
          <div className="hero-copy">
            <div className="eyebrow">SYS.01 — Hydration Protocol</div>
            <h1 className="hero-title">
              Water,<br/>
              <span className="outline">engineered</span><br/>
              to <span className="glow">clarity.</span>
            </h1>
            <p className="hero-sub">
              Filtration systems, cartridge subscriptions, and spring delivery —
              built for households that take what's in the glass seriously.
              Certified, tested quarterly, transparent.
            </p>
            <div className="hero-cta-row">
              <a href="#" className="btn btn-primary">
                Find your system
                <svg className="btn-arrow" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
                  <path d="M5 12h14M13 5l7 7-7 7" />
                </svg>
              </a>
              <a href="#" className="btn btn-ghost">Book water test ↗</a>
            </div>
            <div className="hero-badges">
              <span className="badge"><span className="bd-num">99.9%</span> contaminant reduction</span>
            </div>
          </div>

          <div className="hero-visual" aria-hidden="true">
            <span className="corner tl" /><span className="corner tr" />
            <span className="corner bl" /><span className="corner br" />

            <div className="tag">
              <span className="mono">AQUO · SYS-03 · UNDER-SINK</span>
              <span className="mono live">LIVE</span>
            </div>

            <div className="water-wrap">
              <canvas ref={canvasRef} style={{ width: '100%', height: '100%', display: 'block' }} />
            </div>

            <div className="spec">
              <div className="spec-item"><div className="k">Flow</div><div className="v">0.8</div></div>
              <div className="spec-item"><div className="k">Life</div><div className="v">12mo</div></div>
              <div className="spec-item"><div className="k">Stages</div><div className="v">05</div></div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.Hero = Hero;
