/* Hero — animated cover with culture-media forming motif
   Expects to mount into #hero-root */

const { useEffect, useRef, useState } = React;

function HeroCanvas() {
  const canvasRef = useRef(null);
  const rafRef = useRef(0);
  const startRef = useRef(0);

  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    let 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();
    window.addEventListener('resize', resize);

    // Particles — "colonies" drifting across the petri
    const N = 48;
    const rand = (a,b) => a + Math.random() * (b - a);
    const particles = Array.from({length: N}, (_, i) => ({
      a: rand(0, Math.PI * 2),
      r: rand(60, 300),
      rSpeed: rand(-0.05, 0.05) * 0.3,
      aSpeed: rand(-0.2, 0.2) * 0.15,
      size: rand(1.2, 3.6),
      delay: rand(0, 1.5),
      phase: rand(0, Math.PI * 2),
    }));

    const draw = (t) => {
      if (!startRef.current) startRef.current = t;
      const elapsed = (t - startRef.current) / 1000;

      const r = canvas.getBoundingClientRect();
      const W = r.width, H = r.height;
      const cx = W / 2, cy = H / 2;
      const maxR = Math.min(W, H) * 0.46;

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

      // Intro progress 0..1 over first 2.4s
      const intro = Math.min(1, elapsed / 2.4);
      const ease = 1 - Math.pow(1 - intro, 3);

      // Outer concentric rings — petri suggestion
      ctx.save();
      ctx.translate(cx, cy);

      // Ring field
      for (let i = 0; i < 8; i++) {
        const rr = maxR * (0.35 + i * 0.085) * ease;
        ctx.beginPath();
        ctx.arc(0, 0, rr, 0, Math.PI * 2);
        ctx.strokeStyle = `rgba(23, 20, 15, ${0.04 + i * 0.008})`;
        ctx.lineWidth = 1;
        ctx.stroke();
      }

      // Main dish rim
      ctx.beginPath();
      ctx.arc(0, 0, maxR * ease, 0, Math.PI * 2);
      ctx.strokeStyle = 'rgba(23, 20, 15, 0.18)';
      ctx.lineWidth = 1;
      ctx.stroke();

      // Inner rim
      ctx.beginPath();
      ctx.arc(0, 0, maxR * 0.96 * ease, 0, Math.PI * 2);
      ctx.strokeStyle = 'rgba(23, 20, 15, 0.09)';
      ctx.lineWidth = 1;
      ctx.stroke();

      // Subtle radial fill — like culture media
      const grad = ctx.createRadialGradient(0, 0, 10, 0, 0, maxR);
      grad.addColorStop(0, 'rgba(199, 123, 44, 0.08)');
      grad.addColorStop(0.6, 'rgba(199, 123, 44, 0.02)');
      grad.addColorStop(1, 'rgba(199, 123, 44, 0)');
      ctx.fillStyle = grad;
      ctx.beginPath();
      ctx.arc(0, 0, maxR * 0.95 * ease, 0, Math.PI * 2);
      ctx.fill();

      // Cross-hair ruling (microscopy feel)
      const dash = 4;
      ctx.strokeStyle = 'rgba(23, 20, 15, 0.06)';
      ctx.setLineDash([2, 6]);
      ctx.beginPath();
      ctx.moveTo(-maxR * 0.95 * ease, 0); ctx.lineTo(maxR * 0.95 * ease, 0);
      ctx.moveTo(0, -maxR * 0.95 * ease); ctx.lineTo(0, maxR * 0.95 * ease);
      ctx.stroke();
      ctx.setLineDash([]);

      // Particles / colonies
      particles.forEach(p => {
        const localT = Math.max(0, elapsed - p.delay);
        const appear = Math.min(1, localT / 0.9);
        const a = p.a + p.aSpeed * elapsed;
        const breathe = 1 + Math.sin(elapsed * 0.6 + p.phase) * 0.06;
        const rr = p.r * breathe * ease;
        if (rr > maxR * 0.92) return;
        const x = Math.cos(a) * rr;
        const y = Math.sin(a) * rr;
        ctx.beginPath();
        ctx.arc(x, y, p.size * appear, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(167, 95, 24, ${0.35 * appear})`;
        ctx.fill();
        // Halo
        ctx.beginPath();
        ctx.arc(x, y, p.size * 2.2 * appear, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(199, 123, 44, ${0.08 * appear})`;
        ctx.fill();
      });

      // Sweep line — "scanning" motion
      const sweepA = (elapsed * 0.35) % (Math.PI * 2);
      const grad2 = ctx.createLinearGradient(0, 0, Math.cos(sweepA) * maxR, Math.sin(sweepA) * maxR);
      grad2.addColorStop(0, 'rgba(199, 123, 44, 0)');
      grad2.addColorStop(0.85, 'rgba(199, 123, 44, 0.18)');
      grad2.addColorStop(1, 'rgba(199, 123, 44, 0.35)');
      ctx.strokeStyle = grad2;
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(0, 0);
      ctx.lineTo(Math.cos(sweepA) * maxR * 0.95, Math.sin(sweepA) * maxR * 0.95);
      ctx.stroke();

      ctx.restore();

      rafRef.current = requestAnimationFrame(draw);
    };

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

  return <canvas ref={canvasRef} className="hero-canvas" />;
}

function Hero() {
  const [phase, setPhase] = useState(0);
  useEffect(() => {
    const t1 = setTimeout(() => setPhase(1), 1200);
    const t2 = setTimeout(() => setPhase(2), 2200);
    const t3 = setTimeout(() => setPhase(3), 3000);
    return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); };
  }, []);

  const wordStyle = (i) => ({
    display: 'inline-block',
    transform: phase >= 1 ? 'translateY(0)' : 'translateY(110%)',
    opacity: phase >= 1 ? 1 : 0,
    transition: `transform 900ms cubic-bezier(.2,.8,.2,1) ${i * 90}ms, opacity 900ms ${i * 90}ms`,
  });

  return (
    <section className="hero" id="cover">
      <div className="hero-stage">
        <HeroCanvas />
        <div className="hero-title">
          <span className="eyebrow" style={{
            opacity: phase >= 0 ? 1 : 0,
            transition: 'opacity 700ms',
          }}>Proposal · April 2026 · Confidential</span>

          <h1>
            <span className="split"><span style={wordStyle(0)}>A&nbsp;platform&nbsp;built</span></span><br/>
            <span className="split"><span style={wordStyle(1)}>for&nbsp;the&nbsp;way</span></span><br/>
            <span className="split"><span style={wordStyle(2)}>science&nbsp;buys.</span></span>
          </h1>

          <div className="lockup" style={{
            opacity: phase >= 2 ? 1 : 0,
            transform: phase >= 2 ? 'translateY(0)' : 'translateY(12px)',
            transition: 'opacity 700ms, transform 700ms',
          }}>
            <span>RVS Media</span>
            <span className="x">×</span>
            <span>Formedium Ltd</span>
          </div>
        </div>
      </div>

      <div className="hero-meta" style={{
        opacity: phase >= 3 ? 1 : 0,
        transition: 'opacity 800ms',
      }}>
        <div className="item">
          <span className="k">Prepared for</span>
          <span className="v">Alex Hodge, Formedium</span>
        </div>
        <div className="item">
          <span className="k">Prepared by</span>
          <span className="v">Rajeev Nar, RVS Media</span>
        </div>
        <div className="item">
          <span className="k">Scope</span>
          <span className="v">B2B Platform Rebuild</span>
        </div>
        <div className="item">
          <span className="k">Options</span>
          <span className="v">Magento · Next.js</span>
        </div>
      </div>
    </section>
  );
}

window.Hero = Hero;
