window.Hero = function Hero() {
  const isMobile = useIsMobile();
  const isTablet = useIsTablet();

  const sectionPadding = isMobile ? '64px 24px' : isTablet ? '96px 32px' : '128px 48px 96px';
  const h1Size = isMobile ? 64 : isTablet ? 96 : 144;
  const subSize = isMobile ? 18 : isTablet ? 22 : 24;

  const goTo = (id) => (e) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) {
      const y = el.getBoundingClientRect().top + window.pageYOffset - 80;
      window.scrollTo({ top: y, behavior: 'smooth' });
    }
  };

  const arrow = (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
      <path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );

  return (
    <section style={{ padding: sectionPadding, maxWidth: 1280, margin: '0 auto' }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1.4fr 1fr',
        gap: isMobile ? 48 : 64,
        alignItems: 'center',
      }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 24 }}>Agentic operations</div>
          <h1 style={{
            fontSize: h1Size,
            fontWeight: 800,
            lineHeight: 0.92,
            letterSpacing: '-0.045em',
            color: 'var(--text-primary)',
            margin: '0 0 32px',
          }}>
            Own the next era.
          </h1>
          <p style={{
            fontSize: subSize,
            lineHeight: 1.4,
            color: 'var(--text-secondary)',
            margin: '0 0 40px',
            maxWidth: 540,
          }}>
            stitch_ installs AI agents inside the tools you already use. Production-grade. Yours after six weeks.
          </p>
          <div style={{
            display: 'flex',
            flexDirection: isMobile ? 'column' : 'row',
            gap: 16,
            alignItems: isMobile ? 'stretch' : 'center',
          }}>
            <a href="#contact" onClick={goTo('contact')} className="btn-solid">
              Book a consultation
              {arrow}
            </a>
            <a href="#pillars" onClick={goTo('pillars')} className="cta-arrow" style={{ marginLeft: isMobile ? 0 : 8 }}>
              See how it works
              <span className="arrow">{arrow}</span>
            </a>
          </div>
        </div>
        {!isMobile && <HeroVisual />}
      </div>
      {isMobile && <div style={{ marginTop: 48 }}><HeroVisual /></div>}
    </section>
  );
};

function HeroVisual() {
  const isMobile = useIsMobile();
  const cols = isMobile ? 11 : 14;
  const rows = isMobile ? 11 : 14;
  const total = cols * rows;

  // Cells that form a volatile up-and-to-the-right growth chart
  const growthPath = isMobile
    ? [[0,9],[1,8],[2,9],[3,7],[4,6],[5,8],[6,5],[7,4],[8,6],[9,2],[10,0]]
    : [[0,11],[1,10],[2,11],[3,9],[4,8],[5,10],[6,7],[7,8],[8,5],[9,6],[10,4],[11,5],[12,2],[13,0]];
  const pathLen = growthPath.length;

  const [phase, setPhase] = React.useState('random'); // 'random' | 'growth'
  const [randomActive, setRandomActive] = React.useState(() => {
    const s = new Set();
    for (let i = 0; i < 12; i++) s.add(Math.floor(Math.random() * total));
    return s;
  });
  const [growthCount, setGrowthCount] = React.useState(0);
  const [chartPulse, setChartPulse] = React.useState(false);

  // Once the line finishes drawing, fire a few "live" pulses
  React.useEffect(() => {
    if (phase !== 'growth' || growthCount < pathLen) return;
    const id = setTimeout(() => setChartPulse(true), 250);
    return () => clearTimeout(id);
  }, [phase, growthCount, pathLen]);

  // Phase 1: random pulses for ~6s, then fade out and switch to growth
  React.useEffect(() => {
    if (phase !== 'random') return;
    const tick = () => {
      const next = new Set();
      const count = Math.floor(total * 0.13) + 1;
      for (let i = 0; i < count; i++) next.add(Math.floor(Math.random() * total));
      setRandomActive(next);
    };
    const interval = setInterval(tick, 700);
    const fadeTimeout = setTimeout(() => {
      clearInterval(interval);
      setRandomActive(new Set());
    }, 3000);
    const phaseTimeout = setTimeout(() => setPhase('growth'), 3300);
    return () => { clearInterval(interval); clearTimeout(fadeTimeout); clearTimeout(phaseTimeout); };
  }, [phase, total]);

  // Phase 2: light up the growth path one cell at a time
  React.useEffect(() => {
    if (phase !== 'growth') return;
    if (growthCount >= pathLen) return;
    const id = setTimeout(() => setGrowthCount(c => c + 1), growthCount === 0 ? 50 : 110);
    return () => clearTimeout(id);
  }, [phase, growthCount, pathLen]);

  const growthActive = React.useMemo(
    () => new Set(growthPath.slice(0, growthCount).map(([col, row]) => row * cols + col)),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [growthCount, cols, isMobile]
  );

  const active = phase === 'random' ? randomActive : growthActive;

  return (
    <div style={{
      position: 'relative',
      width: '100%',
      maxWidth: 480,
      marginLeft: 'auto',
    }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: `repeat(${cols}, 1fr)`,
        gap: 4,
      }}>
        {Array.from({ length: total }).map((_, i) => (
          <div key={i} style={{
            aspectRatio: '1',
            background: active.has(i) ? 'var(--accent)' : 'var(--bg-muted)',
            transition: 'background 600ms var(--ease)',
          }} />
        ))}
      </div>
      {phase === 'growth' && (
        <svg
          style={{
            position: 'absolute',
            inset: 0,
            width: '100%',
            height: '100%',
            pointerEvents: 'none',
          }}
          viewBox={`0 0 ${cols} ${rows}`}
          preserveAspectRatio="none"
        >
          <polyline
            className={chartPulse ? 'chart-pulse' : ''}
            pathLength="100"
            points={growthPath.map(([col, row]) => `${col + 0.5},${row + 0.5}`).join(' ')}
            stroke="var(--accent)"
            strokeWidth="2.5"
            strokeLinecap="round"
            strokeLinejoin="round"
            fill="none"
            vectorEffect="non-scaling-stroke"
            style={{
              strokeDasharray: 100,
              strokeDashoffset: 100 - (growthCount / pathLen) * 100,
              transition: 'stroke-dashoffset 110ms linear',
            }}
          />
        </svg>
      )}
    </div>
  );
}
