// Hero — evolved: kinetic headline + convergent particle canvas + live counters

function ParticleCanvas({ active }) {
  const cvRef = useRef(null);
  useEffect(() => {
    if (!active) return;
    const cv = cvRef.current;
    if (!cv) return;
    const ctx = cv.getContext('2d');
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    let W, H;
    const resize = () => {
      const r = cv.getBoundingClientRect();
      W = r.width; H = r.height;
      cv.width = W * dpr; cv.height = H * dpr;
      ctx.scale(dpr, dpr);
    };
    resize();
    window.addEventListener('resize', resize);

    const COUNT = 110;
    const particles = Array.from({ length: COUNT }, () => {
      const angle = Math.random() * Math.PI * 2;
      const dist = 520 + Math.random() * 680;
      return {
        sx: Math.cos(angle) * dist,
        sy: Math.sin(angle) * dist * 0.55,
        x: 0, y: 0,
        phase: Math.random() * Math.PI * 2,
        speed: 0.5 + Math.random() * 0.6,
        size: 0.6 + Math.random() * 1.6,
        hue: Math.random() < 0.55 ? 0 : (Math.random() < 0.5 ? 1 : 2),
      };
    });

    let start = performance.now();
    let raf;
    const tick = () => {
      const t = (performance.now() - start) / 1000;
      // Three-stage animation:
      // 0 – 1s: fly in, starting far out
      // 1 – 2.5s: settle into orbital band
      // 2.5s+:   gentle idle drift
      const cx = W / 2;
      const cy = H / 2;
      ctx.clearRect(0, 0, W, H);

      // soft central glow — doubled radius
      const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, 440);
      const accent = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim() || '#00B4FF';
      g.addColorStop(0, accent + '22');
      g.addColorStop(1, 'transparent');
      ctx.fillStyle = g;
      ctx.fillRect(cx - 520, cy - 520, 1040, 1040);

      particles.forEach(p => {
        const settle = Math.min(1, t / 1.8);
        const ease = 1 - Math.pow(1 - settle, 3);
        // target position: orbital band — doubled radius
        const orbitR = 340 + Math.sin(p.phase) * 80;
        const ox = cx + Math.cos(p.phase + t * p.speed * 0.35) * orbitR;
        const oy = cy + Math.sin(p.phase + t * p.speed * 0.35) * (orbitR * 0.42);
        p.x = (cx + p.sx) * (1 - ease) + ox * ease;
        p.y = (cy + p.sy) * (1 - ease) + oy * ease;

        const col = p.hue === 0 ? accent : (p.hue === 1 ? '#7C3AED' : '#00E5A0');
        ctx.fillStyle = col;
        ctx.globalAlpha = 0.35 + Math.sin(t + p.phase) * 0.2;
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
        ctx.fill();
        // glow
        ctx.globalAlpha = 0.12;
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.size * 3, 0, Math.PI * 2);
        ctx.fill();
      });
      ctx.globalAlpha = 1;

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

  return <canvas ref={cvRef} style={{ width:'100%', height:'100%', display:'block' }} />;
}

function HeroSection() {
  const [mounted, setMounted] = useState(false);
  useEffect(() => { setMounted(true); }, []);

  const STATS = [
    { value: '+72%', label: 'ROAS Lift' },
    { value: '+47%', label: 'CTR Increase' },
    { value: '14×', label: 'Conversion' },
    { value: '1/10', label: 'Production Cost' },
  ];

  const [statsRef, statsVis] = useReveal();

  return (
    <section id="hero" style={{
      position:'relative', minHeight:'100vh', background:'var(--bg)',
      display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
      overflow:'hidden', paddingTop:120, paddingBottom:60,
    }}>
      <Aurora />

      {/* Particle canvas behind text */}
      <div style={{ position:'absolute', inset:0, pointerEvents:'none' }}>
        {mounted && <ParticleCanvas active={mounted} />}
      </div>

      {/* Decorative corner ticks */}
      <div style={{ position:'absolute', top:100, left:40, fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'0.18em', color:'var(--muted)', textTransform:'uppercase' }} className="hero-deco">
        <div>[01]</div>
        <div style={{ marginTop:6, width:1, height:48, background:'linear-gradient(to bottom, var(--muted), transparent)' }}/>
      </div>
      <div style={{ position:'absolute', top:100, right:40, fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'0.18em', color:'var(--muted)', textAlign:'right', textTransform:'uppercase' }} className="hero-deco">
        <div>SYSTEM · ONLINE</div>
        <div style={{ marginTop:8, display:'inline-flex', alignItems:'center', gap:6 }}>
          <span style={{ width:6, height:6, borderRadius:'50%', background:'#00E5A0', boxShadow:'0 0 8px #00E5A0', animation:'pulseDot 2s ease-in-out infinite' }}/>
          <span>Lagos · GMT+1</span>
        </div>
      </div>

      {/* Main copy */}
      <div style={{ position:'relative', zIndex:2, textAlign:'center', padding:'0 24px', maxWidth:980 }}>
        <div style={{
          display:'inline-flex', alignItems:'center', gap:10,
          padding:'6px 14px', borderRadius:99,
          background:'rgba(0,229,160,0.1)', border:'1px solid rgba(0,229,160,0.3)',
          fontSize:11, fontWeight:600, letterSpacing:'0.12em', textTransform:'uppercase',
          color:'#00E5A0', fontFamily:'var(--font-body)',
          marginBottom: 28,
          opacity: mounted ? 1 : 0, transform: mounted ? 'translateY(0)' : 'translateY(-10px)',
          transition:'opacity .6s ease .1s, transform .6s ease .1s',
        }}>
          <span style={{ width:7, height:7, borderRadius:'50%', background:'#00E5A0', boxShadow:'0 0 8px #00E5A0', animation:'pulseDot 2s ease-in-out infinite' }}/>
          Available · Booking Q2
        </div>

        <h1 className="display" style={{
          fontSize:'clamp(44px, 6.2vw, 92px)',
          lineHeight:1.02,
          letterSpacing:'-0.035em',
          color:'var(--text)',
          marginBottom:20,
        }}>
          <span style={{
            display:'inline-block',
            opacity: mounted ? 1 : 0,
            transform: mounted ? 'translateY(0)' : 'translateY(20px)',
            transition:'opacity .8s ease .35s, transform .8s ease .35s',
          }}>I build AI systems</span>
          <br/>
          <span style={{
            display:'inline-block',
            opacity: mounted ? 1 : 0,
            transform: mounted ? 'translateY(0)' : 'translateY(20px)',
            transition:'opacity .8s ease .55s, transform .8s ease .55s',
          }}>
            that work{' '}
            <span className="glow-text" style={{ fontStyle:'italic', fontWeight: 800 }}>while you sleep.</span>
          </span>
        </h1>

        <p style={{
          fontSize:13, color:'var(--muted-strong)',
          letterSpacing:'0.22em', textTransform:'uppercase', fontWeight:500,
          fontFamily:'var(--font-mono)',
          opacity: mounted ? 1 : 0, transition:'opacity .8s ease 0.8s',
          marginTop: 4,
        }}>
          Automation &nbsp;·&nbsp; AI Video &nbsp;·&nbsp; Full-Stack
        </p>

        <div style={{
          display:'flex', flexWrap:'wrap', gap:14, justifyContent:'center', marginTop:36,
          opacity: mounted ? 1 : 0, transform: mounted ? 'translateY(0)' : 'translateY(10px)',
          transition:'opacity .6s ease 1s, transform .6s ease 1s',
        }}>
          <a href="#contact" className="btn-primary">
            Start a Project
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M1 7h12m0 0L7 1m6 6L7 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </a>
          <a href="#work" className="btn-ghost">See the Work</a>
        </div>
      </div>

      {/* Stats strip */}
      <div ref={statsRef} style={{
        position:'relative', zIndex:2, marginTop:80, width:'100%', maxWidth:820,
        padding:'0 24px',
        opacity: statsVis ? 1 : 0, transform: statsVis ? 'translateY(0)' : 'translateY(20px)',
        transition:'opacity .8s ease, transform .8s ease',
      }}>
        <div style={{
          display:'grid', gridTemplateColumns:'repeat(4, 1fr)',
          borderTop:'1px solid var(--border)', borderBottom:'1px solid var(--border)',
        }} className="hero-stats">
          {STATS.map((s, i) => {
            const v = useCountUp(s.value, { active: statsVis, duration: 1400 + i*150 });
            return (
              <div key={s.label} style={{
                textAlign:'center', padding:'22px 10px',
                borderRight: i < STATS.length - 1 ? '1px solid var(--border)' : 'none',
              }}>
                <div className="mono" style={{
                  fontSize:'clamp(22px, 2.4vw, 32px)', fontWeight:600,
                  color:'var(--accent)',
                  textShadow:'0 0 calc(20px * var(--glow)) rgba(var(--accent-rgb),0.45)',
                  lineHeight:1,
                }}>{v}</div>
                <div style={{ fontSize:10.5, color:'var(--muted)', marginTop:8, fontWeight:500, letterSpacing:'0.12em', textTransform:'uppercase' }}>
                  {s.label}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Scroll hint */}
      <div style={{
        position:'absolute', bottom:24, left:'50%', transform:'translateX(-50%)',
        display:'flex', flexDirection:'column', alignItems:'center', gap:8,
        opacity: mounted ? 0.8 : 0, transition:'opacity 1s ease 1.6s',
      }}>
        <span style={{ fontSize:10, color:'var(--muted)', letterSpacing:'0.2em', textTransform:'uppercase', fontFamily:'var(--font-mono)' }}>Scroll</span>
        <div style={{ width:1, height:36, background:'linear-gradient(to bottom, rgba(var(--accent-rgb),0.6), transparent)' }}/>
      </div>

      <style>{`
        @media (max-width:768px){
          .hero-deco{ display:none; }
          .hero-stats{ grid-template-columns: repeat(2, 1fr) !important; }
          .hero-stats > div:nth-child(2){ border-right:none !important; }
          .hero-stats > div:nth-child(1),
          .hero-stats > div:nth-child(2){ border-bottom:1px solid var(--border); }
        }
      `}</style>
    </section>
  );
}

window.HeroSection = HeroSection;
