function Hero() {
  const heroRef = useRef(null);
  const bgALayerRef = useRef(null);
  const bgBLayerRef = useRef(null);
  const phiRef = useRef(null);

  const isMobile = window.innerWidth <= 820;

  useEffect(() => {
    // Mobile: kill GPU-composited parallax entirely — it causes rendering artifacts on iOS
    if (isMobile) {
      if (bgBLayerRef.current) bgBLayerRef.current.style.opacity = '0';
      // Remove will-change so layers don't get promoted to separate compositor tiles
      if (bgALayerRef.current) bgALayerRef.current.style.willChange = 'auto';
      return; // no mouse/scroll handlers needed on mobile
    }

    const state = { mx: 50, my: 50, p: 0 };

    const updateTransforms = () => {
      const { p, mx, my } = state;
      const bgZoom = 1 + Math.max(0, p) * 0.18;
      const bgShift = p * 40;
      if (bgALayerRef.current) {
        bgALayerRef.current.style.transform = `scale(${bgZoom}) translate3d(${(mx-50)*-0.2}px,${bgShift+(my-50)*-0.15}px,0)`;
      }
      if (bgBLayerRef.current) {
        bgBLayerRef.current.style.transform = `scale(${bgZoom}) translate3d(${(mx-50)*-0.12}px,${bgShift+(my-50)*-0.1}px,0)`;
      }
      if (phiRef.current) {
        phiRef.current.style.transform = `translate3d(0,${p*-180}px,0) rotate(${p*-6}deg)`;
      }
    };

    const onMouse = (e) => {
      const r = heroRef.current?.getBoundingClientRect();
      state.mx = (e.clientX / window.innerWidth) * 100;
      state.my = (e.clientY / window.innerHeight) * 100;
      if (r && bgBLayerRef.current) {
        const px = e.clientX - r.left;
        const py = e.clientY - r.top;
        const mask = `radial-gradient(circle 280px at ${px}px ${py}px,black 0%,black 60%,transparent 100%)`;
        bgBLayerRef.current.style.maskImage = mask;
        bgBLayerRef.current.style.webkitMaskImage = mask;
      }
      updateTransforms();
    };

    let raf = 0;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = 0;
        const el = heroRef.current;
        if (!el) return;
        const r = el.getBoundingClientRect();
        const vh = window.innerHeight;
        state.p = Math.max(0, Math.min(1, (vh - r.top) / (2 * vh)));
        updateTransforms();
      });
    };

    onScroll();
    window.addEventListener('mousemove', onMouse);
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('mousemove', onMouse);
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <header
      id="top"
      ref={heroRef}
      className="hero-section"
      style={{
        position: 'relative',
        minHeight: '100vh',
        clipPath: 'inset(0)',
        isolation: 'isolate',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
      }}
    >
      {/* === BG LAYER A === */}
      <div
        ref={bgALayerRef}
        className="hero-bg-a"
        style={{
          position: 'absolute', inset: '-6%', zIndex: -3,
          transformOrigin: '50% 50%',
          willChange: 'transform',
        }}
      >
        <HeroBg src="images/hero-bg-a.webp" srcMobile="images/hero-bg-a-mobile.webp" seed={0} />
      </div>

      {/* === BG LAYER B — revealed by mouse on desktop only === */}
      <div
        ref={bgBLayerRef}
        style={{
          position: 'absolute', inset: '-6%', zIndex: -2,
          transformOrigin: '50% 50%',
          willChange: 'transform',
        }}
      >
        <HeroBg src="images/hero-bg-b.webp" srcMobile="images/hero-bg-b-mobile.webp" seed={1} />
      </div>

      {/* Scrim — rgba, compatible with all Safari versions */}
      <div aria-hidden className="hero-scrim" style={{
        position: 'absolute', inset: 0, zIndex: -1, pointerEvents: 'none',
        background: `
          radial-gradient(110% 80% at 50% 50%, transparent 0%, rgba(246,241,232,0.55) 75%),
          linear-gradient(180deg,
            rgba(246,241,232,0.55) 0%,
            transparent 25%,
            transparent 55%,
            rgba(246,241,232,0.88) 100%)
        `,
      }} />

      {/* Floating PHI glyph — desktop only */}
      <div ref={phiRef} aria-hidden className="hero-phi" style={{
        position: 'absolute', top: '8%', right: '-4%',
        fontFamily: 'var(--serif)', fontStyle: 'italic',
        fontSize: 'clamp(260px, 38vw, 540px)',
        color: 'rgba(30,25,18,0.06)',
        lineHeight: 0.8,
        willChange: 'transform', pointerEvents: 'none', userSelect: 'none', zIndex: 0,
      }}>Φ</div>

      {/* === CONTENT === */}
      <div className="container" style={{ position: 'relative', zIndex: 3 }}>
        <Reveal className="hero-tagline">
          <div className="mono" style={{ marginBottom: 40, display: 'flex', gap: 14, alignItems: 'center' }}>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--accent)' }} />
            Direção estratégica para produtos físicos · Método PHI
          </div>
        </Reveal>

        <MaskLines
          tag="h1"
          className="serif"
          delay={60}
          style={{
            fontSize: 'clamp(48px, 9vw, 132px)',
            lineHeight: 0.94,
            letterSpacing: '-0.035em',
            marginBottom: 48,
            position: 'relative', zIndex: 2,
            maxWidth: 'clamp(300px, 62%, 860px)',
          }}
          lines={[
            <>Seu produto não</>,
            <>vende mal por <em className="italic">estética.</em></>,
            <>Vende mal por <em className="italic">falta</em></>,
            <>de <em className="italic">direção.</em></>,
          ]}
        />

        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 80, alignItems: 'end', marginTop: 40 }} className="hero-grid">
          <Reveal delay={300} className="hero-desc">
            <p style={{ fontSize: 19, lineHeight: 1.5, color: 'var(--fg-dim)', maxWidth: 560, letterSpacing: '-0.005em' }}>
              Eu não entrego layouts bonitos. Eu entrego decisões —
              baseadas em concorrência, cliente e voz de mercado.
              O design vem depois, como <span style={{ color: 'var(--fg)' }} className="italic serif">consequência</span>.
            </p>
          </Reveal>
          <Reveal delay={380}>
            <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', justifyContent: 'flex-end' }} className="hero-ctas">
              <CTA onClick={() => window.__openContactModal()}>
                Diagnosticar meu produto
              </CTA>
              <CTA variant="ghost" onClick={() => document.getElementById('metodo')?.scrollIntoView({ behavior: 'smooth' })}>
                Ver o Método PHI
              </CTA>
            </div>
          </Reveal>
        </div>
      </div>

      {/* Bottom fade */}
      <div aria-hidden className="hero-bottom-fade" style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        height: 280, pointerEvents: 'none', zIndex: 2,
        background: 'linear-gradient(to bottom, transparent 0%, rgba(246,241,232,1) 85%)',
      }} />

      <style>{`
        .hero-section { padding-top: 140px; padding-bottom: 80px; }

        @media (max-width: 820px) {
          /* Zona de imagem fixa no topo, conteúdo flui abaixo num fundo sólido */
          .hero-section {
            padding-top: 64vh !important;
            padding-bottom: 60px !important;
            justify-content: flex-start !important;
          }
          /*
           * Imagem 768×1400 (proporção 0.549).
           * Com height:70vh o container fica mais "paisagem" que a imagem
           * (390÷591=0.66 > 0.549), então object-fit:cover escala pela LARGURA:
           * escala=390÷768=0.508 → altura renderizada=711px > 591px (container).
           * objectPosition:50% 0% mostra o TOPO da imagem (onde está o rosto),
           * cortando os 120px inferiores (pés/fundo).
           * Sem esse constraint a layer cobre a hero inteira e escala pela ALTURA,
           * mapeando o rosto (~60% da imagem) para ~72vh — exatamente onde começa o texto.
           */
          .hero-bg-a {
            top: 0 !important;
            left: 0 !important;
            right: 0 !important;
            bottom: auto !important;
            height: 70vh !important;
          }
          .hero-grid { grid-template-columns: 1fr !important; gap: 12px !important; margin-top: 0 !important; }
          .hero-ctas { justify-content: flex-start !important; }
          .hero-section h1 { max-width: 100% !important; font-size: clamp(38px,10vw,80px) !important; margin-bottom: 12px !important; }
          .hero-tagline .mono { margin-bottom: 12px !important; }
          .hero-desc p { font-size: 15px !important; }
          /* Bottom fade do desktop interfere no mobile — ocultar */
          .hero-bottom-fade { display: none !important; }
          /* Rosto visível até 54vh, degradê suave 54→66vh, sólido aos 68vh, texto em 70vh */
          .hero-scrim {
            background: linear-gradient(
              180deg,
              rgba(246,241,232,0.00) 0px,
              rgba(246,241,232,0.00) 54vh,
              rgba(246,241,232,0.20) 62vh,
              rgba(246,241,232,1.00) 68vh,
              rgba(246,241,232,1.00) 100%
            ) !important;
          }
          .hero-phi { display: none !important; }
        }

        @media (max-width: 480px) {
          .hero-section { padding-bottom: 36px !important; }
          .hero-ctas { flex-direction: column !important; width: 100%; }
          .hero-ctas > * { width: 100% !important; justify-content: center !important; }
        }
      `}</style>
    </header>
  );
}

// Tries to load a static image (with mobile variant); falls back to animated placeholder
function HeroBg({ src, srcMobile, seed }) {
  const [err, setErr] = useState(false);
  if (err) return <HeroMediaCanvas seed={seed} />;
  return (
    <picture style={{ width: '100%', height: '100%', display: 'block' }}>
      {srcMobile && <source media="(max-width: 768px)" srcSet={srcMobile} type="image/webp" />}
      <img
        src={src}
        alt=""
        onError={() => setErr(true)}
        style={{
          width: '100%', height: '100%',
          objectFit: 'cover',
          objectPosition: '50% 0%',
        }}
      />
    </picture>
  );
}

// Animated placeholder — smooth blobs, no tiling artifacts
function HeroMediaCanvas({ seed = 0 }) {
  const bgRef = useRef(null);
  useEffect(() => {
    let raf;
    const start = performance.now();
    const tick = (now) => {
      const t = (now - start) / 1000;
      const s1 = 50 + Math.sin(t * 0.12 + seed) * 10;
      const s2 = 42 + Math.cos(t * 0.10 + seed) * 10;
      const s3 = 68 + Math.sin(t * 0.08 + seed + 1) * 12;
      const s4 = 60 + Math.cos(t * 0.11 + seed + 2) * 10;

      const bg = seed === 0
        ? `radial-gradient(ellipse 60% 55% at ${s1}% ${s2}%, rgba(209,178,138,0.65), transparent 55%),
           radial-gradient(ellipse 55% 50% at ${s3}% ${s4}%, rgba(184,148,100,0.55), transparent 55%),
           radial-gradient(ellipse 80% 55% at 50% 115%, rgba(140,110,68,0.5), transparent 65%),
           linear-gradient(180deg, rgb(237,228,212), rgb(210,195,170))`
        : `radial-gradient(ellipse 65% 55% at ${100-s1}% ${100-s2}%, rgba(72,85,107,0.75), transparent 55%),
           radial-gradient(ellipse 55% 55% at ${100-s3}% ${s4}%, rgba(51,63,82,0.65), transparent 55%),
           radial-gradient(ellipse 80% 65% at 40% 115%, rgba(38,47,62,1), transparent 60%),
           linear-gradient(180deg, rgb(56,67,88), rgb(36,45,58))`;

      if (bgRef.current) bgRef.current.style.background = bg;
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <div style={{ position: 'absolute', inset: 0 }}>
      <div ref={bgRef} style={{ position: 'absolute', inset: 0 }} />
    </div>
  );
}

window.Hero = Hero;
