// Hero — animated orbital diagram + nav
const { useState, useEffect, useRef, useCallback } = React;

// Global IntersectionObserver reveal — exposed for all sections
function useReveal(rootMargin = '0px 0px -80px 0px') {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal, .reveal-up, .reveal-scale');
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); }
      });
    }, { rootMargin, threshold: 0.05 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []); // run once after full render
}
Object.assign(window, { useReveal });

function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);
  const items = ['Platform', 'Hubs', 'Sectors', 'Insights', 'Company'];
  return (
    <>
      <header style={{
        position: 'sticky', top: 0, zIndex: 50,
        background: scrolled ? 'oklch(98.5% 0.005 85 / 0.88)' : 'transparent',
        backdropFilter: scrolled ? 'saturate(160%) blur(18px)' : 'none',
        WebkitBackdropFilter: scrolled ? 'saturate(160%) blur(18px)' : 'none',
        borderBottom: scrolled ? '1px solid var(--rule)' : '1px solid transparent',
        transition: 'background 260ms ease, border-color 260ms ease, backdrop-filter 260ms ease'
      }}>
        <div className="container" style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          height: 72
        }}>
          <a href="#" style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
            <img src="assets/logo.png" alt="24 Hubs" style={{ width: 32, height: 32, borderRadius: '50%' }} />
            <span style={{ fontFamily: 'var(--serif)', fontSize: 22, letterSpacing: '-0.01em' }}>
              24 Hubs<sup style={{ fontFamily: 'var(--mono)', fontSize: 9, top: '-1em', marginLeft: 2, position: 'relative' }}>™</sup>
            </span>
          </a>

          {/* Desktop nav */}
          <nav className="nav-desktop" style={{ display: 'flex', gap: 32 }}>
            {items.map(i => (
              <a key={i} href={`#${i.toLowerCase()}`} style={{
                fontSize: 14, color: 'var(--ink-soft)', fontWeight: 500,
                transition: 'color 160ms', position: 'relative', paddingBottom: 2
              }}
                onMouseEnter={e => e.currentTarget.style.color = 'var(--ink)'}
                onMouseLeave={e => e.currentTarget.style.color = 'var(--ink-soft)'}
              >{i}</a>
            ))}
          </nav>

          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <a href="https://api.24hubs.com/admin" className="nav-desktop" style={{ fontSize: 14, color: 'var(--ink-soft)', fontWeight: 500, display: 'flex' }}>Sign in</a>
            <a href="#cta" className="btn btn-primary" style={{ padding: '10px 18px', fontSize: 13 }}>
              Book a review <span className="arrow">→</span>
            </a>
            {/* Hamburger */}
            <button
              className={`hamburger${menuOpen ? ' open' : ''}`}
              aria-label={menuOpen ? 'Close menu' : 'Open menu'}
              aria-expanded={menuOpen}
              onClick={() => setMenuOpen(o => !o)}
            >
              <span /><span /><span />
            </button>
          </div>
        </div>
      </header>

      {/* Mobile nav overlay */}
      <nav className={`mobile-nav${menuOpen ? ' open' : ''}`} aria-hidden={!menuOpen}>
        {items.map(i => (
          <a key={i} href={`#${i.toLowerCase()}`} onClick={() => setMenuOpen(false)}>
            {i}
          </a>
        ))}
        <a href="https://api.24hubs.com/admin" onClick={() => setMenuOpen(false)} style={{ marginTop: 8 }}>Sign in</a>
        <a href="#cta" className="btn btn-primary" style={{ marginTop: 20, textAlign: 'center', borderRadius: 999 }}
           onClick={() => setMenuOpen(false)}>
          Book a review →
        </a>
      </nav>
    </>
  );
}

// Orbital hub visual — concentric rings with rotating nodes connecting to legacy system tiles
function HeroVisual() {
  const ref = useRef(null);
  const [t, setT] = useState(0);
  useEffect(() => {
    let raf;
    const start = performance.now();
    const tick = () => {
      setT((performance.now() - start) / 1000);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const cx = 280, cy = 280;
  const rings = [80, 130, 190, 250];
  const nodes = [
    { ring: 0, count: 4, speed: 0.18, phase: 0, size: 8 },
    { ring: 1, count: 6, speed: -0.12, phase: 0.3, size: 6 },
    { ring: 2, count: 8, speed: 0.08, phase: 0.6, size: 5 },
    { ring: 3, count: 12, speed: -0.05, phase: 0.9, size: 4 },
  ];

  // Legacy system labels positioned around the orbit
  const legacyTags = [
    { x: 36, y: 80, label: 'SAP' },
    { x: 470, y: 60, label: 'ORACLE' },
    { x: 510, y: 220, label: 'Salesforce' },
    { x: 480, y: 420, label: 'Workday' },
    { x: 60, y: 440, label: 'Mainframe' },
    { x: 18, y: 240, label: 'AS/400' },
  ];

  return (
    <div ref={ref} style={{
      position: 'relative',
      width: '100%',
      aspectRatio: '1 / 1',
      maxWidth: 560,
      margin: '0 auto'
    }}>
      <svg viewBox="0 0 560 560" width="100%" height="100%" style={{ overflow: 'visible' }}>
        <defs>
          <radialGradient id="coreGlow" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="oklch(72% 0.13 252)" stopOpacity="0.5" />
            <stop offset="60%" stopColor="oklch(72% 0.13 252)" stopOpacity="0.05" />
            <stop offset="100%" stopColor="oklch(72% 0.13 252)" stopOpacity="0" />
          </radialGradient>
          <linearGradient id="ringStroke" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="oklch(55% 0.18 255)" stopOpacity="0.8" />
            <stop offset="100%" stopColor="oklch(72% 0.13 252)" stopOpacity="0.3" />
          </linearGradient>
        </defs>

        {/* glow */}
        <circle cx={cx} cy={cy} r={170} fill="url(#coreGlow)" />

        {/* concentric rings */}
        {rings.map((r, i) => (
          <circle key={i} cx={cx} cy={cy} r={r}
            fill="none"
            stroke={i === 0 ? 'url(#ringStroke)' : 'oklch(80% 0.04 250)'}
            strokeWidth={i === 0 ? 1.4 : 0.8}
            strokeDasharray={i === 3 ? '2 4' : 'none'}
            opacity={i === 0 ? 1 : 0.55}
          />
        ))}

        {/* connector spokes between core node and outer tags */}
        {legacyTags.map((tag, i) => {
          const angle = Math.atan2(tag.y + 20 - cy, tag.x + 30 - cx);
          const x1 = cx + Math.cos(angle) * 80;
          const y1 = cy + Math.sin(angle) * 80;
          const x2 = cx + Math.cos(angle) * 250;
          const y2 = cy + Math.sin(angle) * 250;
          return (
            <line key={i} x1={x1} y1={y1} x2={x2} y2={y2}
              stroke="oklch(55% 0.18 255)"
              strokeWidth="0.8"
              strokeOpacity="0.35"
              strokeDasharray="3 4"
            />
          );
        })}

        {/* orbiting nodes */}
        {nodes.flatMap((n, ni) =>
          Array.from({ length: n.count }, (_, i) => {
            const a = (i / n.count) * Math.PI * 2 + n.phase + t * n.speed;
            const x = cx + Math.cos(a) * rings[n.ring];
            const y = cy + Math.sin(a) * rings[n.ring];
            const isAccent = (ni + i) % 5 === 0;
            return (
              <g key={`${ni}-${i}`}>
                <circle cx={x} cy={y} r={n.size + 2} fill="oklch(98% 0.005 85)" />
                <circle cx={x} cy={y} r={n.size}
                  fill={isAccent ? 'oklch(55% 0.18 255)' : 'oklch(22% 0.08 260)'}
                />
              </g>
            );
          })
        )}

        {/* core */}
        <circle cx={cx} cy={cy} r={42} fill="oklch(18% 0.02 255)" />
        <circle cx={cx} cy={cy} r={42} fill="none" stroke="oklch(55% 0.18 255)" strokeWidth="1.5" />
        <text x={cx} y={cy + 6} textAnchor="middle"
          fontFamily="var(--serif)" fontSize="22" fill="oklch(98% 0.005 85)">
          24
        </text>
      </svg>

      {/* legacy tags */}
      {legacyTags.map((tag, i) => (
        <div key={i} style={{
          position: 'absolute',
          left: `${(tag.x / 560) * 100}%`,
          top: `${(tag.y / 560) * 100}%`,
          transform: 'translate(-50%, -50%)',
          fontFamily: 'var(--mono)',
          fontSize: 10,
          letterSpacing: '0.1em',
          textTransform: 'uppercase',
          padding: '6px 10px',
          background: 'var(--paper)',
          border: '1px solid var(--rule)',
          borderRadius: 999,
          color: 'var(--ink-soft)',
          whiteSpace: 'nowrap',
          boxShadow: '0 1px 0 rgba(0,0,0,0.02)'
        }}>{tag.label}</div>
      ))}

      {/* status chip */}
      <div style={{
        position: 'absolute',
        bottom: -8, left: '50%',
        transform: 'translateX(-50%)',
        background: 'oklch(100% 0 0 / 0.85)',
        backdropFilter: 'blur(12px)',
        WebkitBackdropFilter: 'blur(12px)',
        border: '1px solid var(--rule)',
        borderRadius: 999,
        padding: '9px 16px',
        display: 'flex', alignItems: 'center', gap: 8,
        fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.08em',
        textTransform: 'uppercase', color: 'var(--ink-soft)',
        whiteSpace: 'nowrap',
        boxShadow: '0 2px 12px rgba(0,0,0,0.06)'
      }}>
        <span className="live-dot" />
        24 hubs · live · uk → west africa
      </div>
    </div>
  );
}

function Hero({ headline, sub }) {
  return (
    <section id="top" style={{ paddingTop: 32, paddingBottom: 0, position: 'relative', overflow: 'hidden' }}>
      {/* Mesh gradient background */}
      <div className="hero-mesh" aria-hidden="true" />
      {/* Subtle dot grid */}
      <div className="dot-pattern" style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        opacity: 0.35, zIndex: 0
      }} aria-hidden="true" />

      <div className="container hero-layout" style={{
        display: 'grid',
        gridTemplateColumns: 'minmax(0, 1.1fr) minmax(0, 1fr)',
        gap: 64,
        alignItems: 'center',
        paddingTop: 48,
        paddingBottom: 96,
        position: 'relative', zIndex: 1
      }}>
        <div>
          <div className="reveal-up in" style={{ marginBottom: 36 }}>
            <span className="section-badge">
              <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--blue-600)', display: 'inline-block' }} />
              001 — Unified digital infrastructure
            </span>
          </div>
          <h1 className="display reveal-up in" style={{
            fontSize: 'clamp(44px, 6vw, 88px)',
            margin: 0,
            marginBottom: 28
          }}>
            {headline}
          </h1>
          <p className="reveal-up in delay-1" style={{
            fontSize: 18,
            lineHeight: 1.58,
            color: 'var(--ink-soft)',
            maxWidth: 520,
            margin: 0,
            marginBottom: 36
          }}>{sub}</p>
          <div className="reveal-up in delay-2" style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <a href="#cta" className="btn btn-primary">
              Schedule an architecture review <span className="arrow">→</span>
            </a>
            <a href="#hubs" className="btn btn-ghost">
              Explore our ecosystem
            </a>
          </div>

          {/* Stats */}
          <div className="hero-stats reveal-up in delay-3" style={{
            marginTop: 56,
            display: 'grid',
            gridTemplateColumns: 'repeat(3, 1fr)',
            gap: 24,
            paddingTop: 28,
            borderTop: '1px solid var(--rule)'
          }}>
            {[
              { k: '14 yrs', v: 'Operating across UK & West Africa' },
              { k: '4.2M', v: 'Active enterprise endpoints' },
              { k: '99.98%', v: 'Platform availability, 2025' },
            ].map((s, i) => (
              <div key={s.k} style={{ paddingRight: i < 2 ? 16 : 0, borderRight: i < 2 ? '1px solid var(--rule-soft)' : 'none' }}>
                <div style={{
                  fontFamily: 'var(--serif)', fontSize: 'clamp(22px, 3vw, 32px)',
                  lineHeight: 1, letterSpacing: '-0.02em', color: 'var(--ink)'
                }}>{s.k}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-mute)', marginTop: 6, lineHeight: 1.4 }}>{s.v}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="hero-visual-wrap">
          <HeroVisual />
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, Hero, HeroVisual });
