// ── Navigation + Hero ──────────────────────────────────────────────────

function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState('');

  const currentPage = (() => {
    const p = window.location.pathname.split('/').pop();
    if (!p || p === '' || p === 'index.html' || p === 'index') return '';
    return p.replace('.html', '');
  })();
  const isHome = currentPage === '';

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    if (!isHome) return;
    const sections = document.querySelectorAll('section[id]');
    const io = new IntersectionObserver(
      (entries) => entries.forEach(e => { if (e.isIntersecting) setActive(e.target.id); }),
      { threshold: 0.35 }
    );
    sections.forEach(s => io.observe(s));
    return () => io.disconnect();
  }, [isHome]);

  const links = isHome ? [
    ['Research', '#research'],
    ['Publications', '/publications'],
    ['Open Source', '/opensource'],
    ['Blog', '/blog'],
    ['Team', '#team'],
  ] : [
    ['Research', '/#research'],
    ['Publications', '/publications'],
    ['Open Source', '/opensource'],
    ['Blog', '/blog'],
    ['Team', '/#team'],
  ];

  const isActiveLink = (href) => {
    if (isHome && href.startsWith('#')) return active === href.slice(1);
    const pageId = href.replace('/#research','').replace('/#team','').replace('/', '');
    if (!isHome && pageId && !pageId.includes('#')) return currentPage === pageId;
    return false;
  };

  const joinHref = isHome ? '#join' : '/#join';
  const careersHref = isHome ? '#careers' : '/#careers';

  return (
    <header className="fixed top-0 inset-x-0 z-50 transition-all duration-500"
      style={{
        background: scrolled ? 'rgba(5,6,10,0.7)' : 'transparent',
        backdropFilter: scrolled ? 'blur(18px) saturate(140%)' : 'none',
        WebkitBackdropFilter: scrolled ? 'blur(18px) saturate(140%)' : 'none',
        borderBottom: scrolled ? '1px solid rgba(255,255,255,0.07)' : '1px solid transparent',
      }}>
      <nav className="max-w-shell mx-auto px-6 lg:px-8 h-[72px] flex items-center justify-between">
        <Wordmark />
        <div className="hidden md:flex items-center gap-8">
          {links.map(([label, href]) => {
            const active_ = isActiveLink(href);
            return (
              <a key={label} href={href}
                className="text-[14px] transition-colors duration-300 relative group"
                style={{ color: active_ ? 'var(--accent-from)' : '' }}>
                <span className={active_ ? 'text-soft' : 'text-muted hover:text-soft'}>{label}</span>
                <span className={`absolute -bottom-1.5 left-0 h-px bg-gradient-to-r from-ebl to-evi transition-all duration-300 ${active_ ? 'w-full' : 'w-0 group-hover:w-full'}`}></span>
              </a>
            );
          })}
        </div>
        <div className="hidden md:flex items-center gap-3">
          <a href={careersHref} className="text-[14px] text-muted hover:text-soft transition-colors duration-300">Careers</a>
          <a href={joinHref} className="btn-primary rounded-full px-5 py-2.5 text-[14px]">Join the Mission</a>
        </div>
        <button className="md:hidden text-soft p-2" onClick={() => setOpen(!open)} aria-label="Menu">
          <svg width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d={open ? 'M6 6l12 12M18 6L6 18' : 'M4 8h16M4 16h16'} /></svg>
        </button>
      </nav>
      {open && (
        <div className="md:hidden glass border-t-0 px-6 py-5 flex flex-col gap-4">
          {[...links, ['Careers', careersHref]].map(([label, href]) => (
            <a key={label} href={href} onClick={() => setOpen(false)} className="text-muted hover:text-soft text-[15px]">{label}</a>
          ))}
          <a href={joinHref} onClick={() => setOpen(false)} className="btn-primary rounded-full px-5 py-3 text-[14px] text-center mt-1">Join the Mission</a>
        </div>
      )}
    </header>
  );
}

function Eyebrow({ children, num }) {
  return (
    <div className="flex items-center gap-3 font-mono text-[12px] tracking-[0.22em] uppercase text-ebl">
      {num && <span className="text-faint">{num}</span>}
      <span className="h-px w-7 bg-gradient-to-r from-ebl to-transparent"></span>
      <span>{children}</span>
    </div>
  );
}

// Venue wordmarks — research credibility
const VENUES = ['NeurIPS', 'ICML', 'ICLR', 'Nature', 'Science', 'ACL', 'CVPR', 'AAAI'];

function VenueStrip({ label = 'Published & presented at' }) {
  return (
    <div className="w-full">
      <div className="font-mono text-[11px] tracking-[0.24em] uppercase text-faint mb-5">{label}</div>
      <div className="marquee-mask overflow-hidden">
        <div className="marquee-track items-center gap-12">
          {[...VENUES, ...VENUES].map((v, i) => (
            <span key={i} className="font-display text-[1.15rem] font-medium text-muted/80 whitespace-nowrap tracking-tight" style={{ opacity: 0.5 }}>{v}</span>
          ))}
        </div>
      </div>
    </div>
  );
}

// Scientific instrument readout — sits under the hero copy
function StatConsole() {
  const stats = [
    ['Researchers', '40+', 'across 9 disciplines'],
    ['Publications', '120', 'peer-reviewed'],
    ['Citations', '8.4k', 'and counting'],
    ['Research areas', '06', 'active programs'],
  ];
  const [time, setTime] = useState('');
  useEffect(() => {
    const fmt = () => {
      const d = new Date();
      const p = n => String(n).padStart(2, '0');
      return `${d.getUTCFullYear()}-${p(d.getUTCMonth()+1)}-${p(d.getUTCDate())} · ${p(d.getUTCHours())}:${p(d.getUTCMinutes())}:${p(d.getUTCSeconds())} UTC`;
    };
    setTime(fmt());
    const id = setInterval(() => setTime(fmt()), 1000);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="glass rounded-2xl overflow-hidden mt-12 relative ticked">
      <div className="flex items-center justify-between px-5 py-3 border-b" style={{ borderColor: 'rgba(255,255,255,0.07)' }}>
        <div className="flex items-center gap-2.5">
          <span className="w-1.5 h-1.5 rounded-full bg-ebl live-dot inline-block"></span>
          <span className="font-mono text-[11px] tracking-[0.18em] uppercase text-faint">Lab Index — Live</span>
        </div>
        <span className="font-mono text-[11px] text-faint hidden sm:block">{time}</span>
      </div>
      <div className="grid grid-cols-2 sm:grid-cols-4">
        {stats.map(([label, val, sub], i) => (
          <div key={label} className="p-5 sm:p-6 relative"
            style={{ borderRight: i < 3 ? '1px solid rgba(255,255,255,0.06)' : 'none', borderBottom: i < 2 ? '1px solid rgba(255,255,255,0.06)' : 'none' }}>
            <div className="font-mono text-[10px] tracking-[0.16em] uppercase text-faint">{label}</div>
            <div className="font-display text-[clamp(1.7rem,2.4vw,2.1rem)] text-soft leading-none mt-2.5 tabular-nums"><CountUp value={val} /></div>
            <div className="text-[12px] text-muted mt-2">{sub}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function Hero() {
  const coreRef = useRef(null);
  const badgeText = useScramble('Interpretability benchmark suite v2 is live');
  useEffect(() => {
    const onScroll = () => {
      if (!coreRef.current) return;
      const y = window.scrollY;
      coreRef.current.style.transform = `translateY(${y * 0.14}px)`;
      coreRef.current.style.opacity = Math.max(0, 1 - y / 760);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <section id="top" className="relative min-h-screen flex flex-col justify-center pt-32 pb-16 overflow-hidden">
      {/* layered backdrop */}
      <div className="absolute inset-0 grid-bg pointer-events-none"></div>
      <div className="aurora" style={{ top: '-160px', left: '8%', width: 620, height: 460, background: 'radial-gradient(circle, rgba(91,134,255,0.26), transparent 68%)', animation: 'drift-a 16s ease-in-out infinite' }}></div>
      <div className="aurora" style={{ top: '40px', right: '2%', width: 560, height: 520, background: 'radial-gradient(circle, rgba(164,118,255,0.20), transparent 68%)', animation: 'drift-b 19s ease-in-out infinite' }}></div>
      {/* vignette */}
      <div className="absolute inset-0 pointer-events-none" style={{ background: 'radial-gradient(ellipse 120% 80% at 50% 30%, transparent 50%, rgba(5,6,10,0.7) 100%)' }}></div>

      <div className="relative max-w-shell mx-auto px-6 lg:px-8 w-full grid lg:grid-cols-[1.08fr_0.92fr] gap-x-12 gap-y-16 items-center">
        <div>
          <div className="reveal in inline-flex items-center gap-2.5 glass rounded-full pl-2 pr-4 py-1.5 mb-8">
            <span className="font-mono text-[10px] tracking-[0.12em] text-ebl bg-ebl/10 rounded-full px-2.5 py-1">2026</span>
            <span className="text-[13px] text-muted">{badgeText}</span>
            <ArrowRight size={13} />
          </div>

          <h1 className="reveal in font-display font-semibold tracking-[-0.025em] leading-[1.02] text-[clamp(2.7rem,5.6vw,4.7rem)]" style={{ textWrap: 'balance' }}>
            Where Disciplines<br />Converge on{' '}
            <span className="grad-text">Intelligence</span>
          </h1>

          <p className="reveal in mt-8 text-[clamp(1.08rem,1.4vw,1.26rem)] text-muted leading-relaxed max-w-[35rem]">
            CIRA Labs is an interdisciplinary research institute studying how intelligence
            works — in minds and in machines — and how to build artificial systems we can
            understand, trust, and direct. We bring computer science, cognitive science,
            and the domain sciences into a single program of inquiry.
          </p>

          <div className="reveal in mt-9 flex flex-wrap items-center gap-4">
            <a href="#research" className="btn-primary rounded-full px-7 py-3.5 text-[15px] inline-flex items-center gap-2">
              Explore Research <ArrowRight size={16} />
            </a>
            <a href="#join" className="btn-ghost rounded-full px-7 py-3.5 text-[15px] inline-flex items-center gap-2">
              Join the Mission
            </a>
          </div>

          <div className="reveal in"><StatConsole /></div>
        </div>

        {/* core visual — visible on all sizes, scaled on mobile */}
        <div ref={coreRef} className="reveal in relative flex justify-center will-change-transform order-first lg:order-none">
          <HeroCore />
        </div>
      </div>

      {/* credibility strip */}
      <div className="reveal in relative max-w-shell mx-auto px-6 lg:px-8 w-full mt-16 lg:mt-24">
        <VenueStrip />
      </div>
    </section>
  );
}

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