// Hero — v4 final (orb + starfield, centered, data-driven copy)
const { useEffect, useRef } = React;

function OrbField() {
  const canvasRef = useRef(null);
  const orbRef = useRef(null);
  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    let w, h, stars = [], shooting = [], raf, t0 = performance.now(), lastShoot = performance.now();
    let frameCount = 0;
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    const layerConfigs = [
      { rMin: 0.2, rMax: 0.6, speedY: 1.0,  countPct: 0.55 },
      { rMin: 0.6, rMax: 1.0, speedY: 0.5,  countPct: 0.30 },
      { rMin: 1.0, rMax: 1.5, speedY: 0.25, countPct: 0.15 },
    ];

    const resize = () => {
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      w = canvas.clientWidth; h = canvas.clientHeight;
      canvas.width = w*dpr; canvas.height = h*dpr;
      ctx.setTransform(1,0,0,1,0,0); ctx.scale(dpr, dpr);
    };
    const init = () => {
      stars = [];
      const total = reduced ? 80 : 220;
      const baseVY = h / (12 * 60);
      for (let l = 0; l < layerConfigs.length; l++) {
        const cfg = layerConfigs[l];
        const cnt = Math.round(total * cfg.countPct);
        for (let i = 0; i < cnt; i++) {
          const r = cfg.rMin + Math.random() * (cfg.rMax - cfg.rMin);
          stars.push({
            x: Math.random()*w, y: Math.random()*h,
            r, phase: Math.random() * Math.PI * 2,
            speed: 0.4 + Math.random() * 1.2,
            tinted: Math.random() < 0.06, layer: l,
            vy: baseVY * cfg.speedY, vx: -baseVY * cfg.speedY * 0.35,
            connect: l === 0 && Math.random() < 0.4,
          });
        }
      }
    };
    const onMove = (e) => {
      const r = canvas.getBoundingClientRect();
      const mx = (e.clientX - r.left) / w;
      const my = (e.clientY - r.top) / h;
      if (orbRef.current) {
        orbRef.current.style.setProperty('--orb-tx', `${(mx - 0.5) * 40}px`);
        orbRef.current.style.setProperty('--orb-ty', `${(my - 0.5) * 40}px`);
      }
    };
    const spawnShootingStar = () => {
      const startX = w * (0.6 + Math.random() * 0.4);
      const startY = h * (Math.random() * 0.3);
      const angle = Math.PI * (0.78 + Math.random() * 0.1);
      const speed = 14 + Math.random() * 6;
      shooting.push({ x: startX, y: startY, vx: Math.cos(angle)*speed, vy: Math.sin(angle)*speed, life: 0, maxLife: 60, trail: [] });
    };
    const draw = () => {
      const t = (performance.now() - t0) / 1000;
      frameCount++;
      ctx.clearRect(0,0,w,h);
      // Diagonal glow: from bottom-right → upper-left, intentionally subtle
      const grad = ctx.createLinearGradient(w * 0.8, h, 0, h * 0.12);
      grad.addColorStop(0,   'rgba(247,19,63,0.09)');
      grad.addColorStop(0.5, 'rgba(247,19,63,0.03)');
      grad.addColorStop(1,   'rgba(247,19,63,0)');
      ctx.fillStyle = grad; ctx.fillRect(0,0,w,h);
      stars.forEach(s => {
        s.x += s.vx; s.y += s.vy;
        if (s.y > h + 4) s.y = -4;
        if (s.x < -4)    s.x = w + 4;
        if (s.x > w + 4) s.x = -4;
        const a = 0.15 + (Math.sin(t * s.speed + s.phase) * 0.5 + 0.5) * 0.7;
        ctx.beginPath(); ctx.arc(s.x, s.y, s.r, 0, Math.PI*2);
        ctx.fillStyle = s.tinted ? `rgba(255,120,90,${a*0.8})` : `rgba(245,245,247,${a})`;
        ctx.fill();
      });
      if (frameCount % 2 === 0 && !reduced) {
        const candidates = stars.filter(s => s.connect);
        const maxD2 = 80*80;
        ctx.lineWidth = 0.4;
        for (let i = 0; i < candidates.length; i++) {
          const a = candidates[i];
          for (let j = i+1; j < candidates.length; j++) {
            const b = candidates[j];
            const dx = a.x-b.x, dy = a.y-b.y, d2 = dx*dx+dy*dy;
            if (d2 < maxD2) {
              ctx.strokeStyle = `rgba(245,245,247,${(1-d2/maxD2)*0.10})`;
              ctx.beginPath(); ctx.moveTo(a.x,a.y); ctx.lineTo(b.x,b.y); ctx.stroke();
            }
          }
        }
      }
      const now = performance.now();
      if (!reduced && now - lastShoot > 8000 + Math.random()*7000) { spawnShootingStar(); lastShoot = now; }
      shooting = shooting.filter(s => {
        s.x += s.vx; s.y += s.vy; s.life++;
        s.trail.push({ x: s.x, y: s.y });
        if (s.trail.length > 12) s.trail.shift();
        for (let i = 0; i < s.trail.length; i++) {
          const p = s.trail[i];
          const fade = (i/s.trail.length)*(1-s.life/s.maxLife);
          ctx.beginPath(); ctx.arc(p.x,p.y,1.2,0,Math.PI*2);
          ctx.fillStyle = `rgba(255,130,100,${fade*0.9})`; ctx.fill();
        }
        if (s.life < s.maxLife) {
          ctx.beginPath(); ctx.arc(s.x,s.y,1.6,0,Math.PI*2);
          ctx.fillStyle = `rgba(255,220,200,${1-s.life/s.maxLife})`;
          ctx.shadowColor='#FF8A4F'; ctx.shadowBlur=8; ctx.fill(); ctx.shadowBlur=0;
        }
        return s.life < s.maxLife && s.x > -50 && s.x < w+50 && s.y > -50 && s.y < h+50;
      });
      raf = requestAnimationFrame(draw);
    };
    resize(); init(); draw();
    const onResize = () => { resize(); init(); };
    window.addEventListener('resize', onResize);
    canvas.addEventListener('mousemove', onMove);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', onResize);
      canvas.removeEventListener('mousemove', onMove);
    };
  }, []);

  const orbits = [
    { radius: 232, duration: 16, delay:  0,    hue: 'rgba(247,19,63,0.95)',   size: 6 },
    { radius: 268, duration: 22, delay: -7.5,  hue: 'rgba(255,50,80,0.85)',   size: 5 },
    { radius: 252, duration: 19, delay: -3,    hue: 'rgba(220,0,40,0.85)',    size: 4 },
    { radius: 296, duration: 28, delay: -14,   hue: 'rgba(247,19,63,0.70)',   size: 5 },
  ];

  return (
    <>
      <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }} />
      <div ref={orbRef} className="hero-orb" style={{
        position: 'absolute', top: '50%', left: '50%',
        width: '480px', height: '480px',
        transform: 'translate(calc(-50% + var(--orb-tx, 0px)), calc(-50% + var(--orb-ty, 0px)))',
        transition: 'transform 600ms cubic-bezier(0.22, 1, 0.36, 1)',
        pointerEvents: 'none', zIndex: 1, mixBlendMode: 'screen',
      }}>
        {/* Clean red ring — dark center so headline text reads clearly */}
        <div style={{
          position: 'absolute', inset: 0, borderRadius: '50%',
          background: 'radial-gradient(circle at 50% 50%, transparent 30%, rgba(247,19,63,0.42) 50%, rgba(180,5,35,0.12) 66%, transparent 76%)',
          animation: 'orbBreath 6s ease-in-out infinite', filter: 'blur(8px)',
        }} />
        {/* Subtle outer ambient — stays above orb, not bleeding into button zone */}
        <div style={{
          position: 'absolute', inset: '-20%', borderRadius: '50%',
          background: 'radial-gradient(ellipse at 55% 60%, rgba(247,19,63,0.22), rgba(200,0,30,0.06) 50%, transparent 68%)',
          animation: 'orbBreath 8s ease-in-out infinite reverse', filter: 'blur(32px)',
        }} />
        {/* Orbiting dots — purely red palette */}
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
          {orbits.map((p, i) => (
            <span key={i} style={{
              position: 'absolute', top: '50%', left: '50%',
              width: `${p.size}px`, height: `${p.size}px`,
              marginLeft: `${-p.size/2}px`, marginTop: `${-p.size/2}px`,
              borderRadius: '999px', background: p.hue,
              boxShadow: `0 0 12px ${p.hue}, 0 0 24px ${p.hue}`,
              animation: `orbitMove ${p.duration}s linear infinite`,
              animationDelay: `${p.delay}s`, '--orbit-r': `${p.radius}px`,
            }} />
          ))}
        </div>
      </div>
    </>
  );
}

function Hero() {
  const { isMobile } = useBreakpoint();

  return (
    <section data-screen-label="01 Hero" style={{
      position: 'relative', minHeight: '100vh', width: '100%', overflow: 'hidden',
      display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center',
    }}>
      <OrbField />

      {/* Navbar */}
      <div style={{
        position: 'absolute', top: isMobile ? '20px' : '32px',
        left: isMobile ? '20px' : '32px',
        right: isMobile ? '20px' : '32px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        zIndex: 10,
      }}>
        <Wordmark size={20} />
        <span style={{
          fontFamily: 'var(--font-mono)', fontSize: isMobile ? '10px' : '11px',
          color: 'var(--text-secondary)', letterSpacing: '0.05em',
        }}>powered by galandr.com</span>
      </div>

      {/* Content */}
      <div style={{
        position: 'relative', zIndex: 5,
        maxWidth: '1440px', width: '100%', margin: '0 auto',
        padding: isMobile ? '64px 20px 90px' : '0 32px',
        display: 'flex', flexDirection: 'column',
        gap: isMobile ? '24px' : '40px',
        textAlign: 'center', alignItems: 'center',
      }}>
        {/* Pill badge */}
        <Reveal y={12}>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: '8px',
            padding: isMobile ? '5px 10px' : '6px 14px', borderRadius: '999px',
            background: 'rgba(247,19,63,0.12)',
            border: '1px solid rgba(247,19,63,0.30)',
            fontFamily: 'var(--font-mono)', fontSize: isMobile ? '10px' : '11px',
            color: '#FFB48E', letterSpacing: '0.1em', textTransform: 'uppercase',
          }}>
            <span style={{
              width: '6px', height: '6px', borderRadius: '999px',
              background: 'var(--accent)',
              animation: 'recBlink 1.4s ease-in-out infinite',
            }} />
            Data → kreativa → výkon
          </span>
        </Reveal>

        <h1 style={{
          fontFamily: 'var(--font-display)', fontWeight: 700,
          fontSize: isMobile ? 'clamp(36px, 10vw, 52px)' : 'clamp(38px, 4.4vw, 80px)',
          lineHeight: isMobile ? 1.08 : 0.95, letterSpacing: '-0.035em',
          color: 'var(--text-primary)', margin: 0, textWrap: 'balance',
          maxWidth: isMobile ? '16ch' : '18ch',
        }}>
          <span style={{ display: 'block' }}>
            <SplitText text="Kreativy pro Meta Ads" baseDelay={200} perWord={50} y={36} />
          </span>
          <span style={{ display: 'block' }}>
            <SplitText text="bez grafika, focení" baseDelay={380} perWord={50} y={36} />
          </span>
          <span style={{ display: 'block', color: 'var(--text-tertiary)' }}>
            <SplitText text="a trápení s AI." baseDelay={560} perWord={50} y={36} />
          </span>
        </h1>

        <Reveal delay={900} y={16}>
          <p style={{
            fontFamily: 'var(--font-body)',
            fontSize: isMobile ? '16px' : '20px',
            lineHeight: 1.55,
            color: 'var(--text-secondary)',
            maxWidth: isMobile ? '34ch' : '50ch',
            margin: '0 auto',
          }}>
            AI vám generuje nepoužitelné výstupy? Grafik nestíhá a produkční studio je mimo rozpočet? Dodáme vám pravidelně nové reklamní kreativy pro Meta Ads – připravené na testování a postavené na datech z vašich kampaní.
          </p>
        </Reveal>

        <Reveal delay={1100} y={16}>
          <div style={{
            display: 'flex',
            flexDirection: isMobile ? 'column' : 'row',
            gap: isMobile ? '10px' : '12px',
            alignItems: 'center',
            justifyContent: 'center',
          }}>
            <CTA size={isMobile ? 'md' : 'lg'}>Chci kreativy na test</CTA>
            <CTA size={isMobile ? 'md' : 'lg'} variant="secondary">Jak to děláme</CTA>
          </div>
          <span style={{
            fontFamily: 'var(--font-mono)',
            fontSize: isMobile ? '11px' : '12px',
            color: 'var(--text-tertiary)',
            letterSpacing: '0.05em', display: 'block',
            marginTop: '18px', textAlign: 'center',
          }}>Aktuálně přijímáme <CountUp to={5} suffix="" /> klientů / měsíc.</span>
        </Reveal>
      </div>

      <ScrollIndicator />
    </section>
  );
}

window.Hero = Hero;
