/* Header — artistic nav with prominent wordmark + underline trail */
function Header({ accentVar }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [active, setActive] = React.useState('');
  const [hover, setHover] = React.useState(null);
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const navRef = React.useRef(null);
  const linkRefs = React.useRef({});
  const [indicator, setIndicator] = React.useState({ left: 0, width: 0, visible: false });
  const nav = window.LB_DATA.nav;

  // Lock scroll when mobile menu is open
  React.useEffect(() => {
    if (mobileOpen) { document.body.style.overflow = 'hidden'; }
    else { document.body.style.overflow = ''; }
    return () => { document.body.style.overflow = ''; };
  }, [mobileOpen]);

  React.useEffect(() => {
    const onScroll = () => {
      setScrolled(window.scrollY > 40);
      let cur = '';
      for (const n of nav) {
        const el = document.getElementById(n.id);
        if (el && el.getBoundingClientRect().top < 160) cur = n.id;
      }
      setActive(cur);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Animated underline indicator
  React.useEffect(() => {
    const id = hover || active;
    const el = linkRefs.current[id];
    const wrap = navRef.current;
    if (el && wrap) {
      const a = el.getBoundingClientRect();
      const b = wrap.getBoundingClientRect();
      setIndicator({ left: a.left - b.left, width: a.width, visible: true });
    } else {
      setIndicator(s => ({ ...s, visible: false }));
    }
  }, [hover, active, scrolled]);

  const go = (e, id) => { e.preventDefault(); const el = document.getElementById(id); if (el) window.scrollTo({ top: el.offsetTop - 72, behavior: 'smooth' }); };

  const onDark = !scrolled;

  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 80,
      transition: 'background 260ms, border-color 260ms, color 260ms, backdrop-filter 260ms',
      background: scrolled ? 'rgba(255,255,255,0.94)' : 'rgba(0,10,24,0.0)',
      backdropFilter: scrolled ? 'blur(14px) saturate(140%)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(14px) saturate(140%)' : 'none',
      borderBottom: scrolled ? '1px solid var(--lb-gray-200)' : '1px solid transparent',
      color: scrolled ? 'var(--lb-navy)' : '#fff',
    }}>
      <div className="shell" style={{ display: 'flex', alignItems: 'center', padding: '16px 32px', gap: 32 }}>
        {/* Wordmark — prominent, single line */}
        <a href="#top" onClick={e=>go(e,'top')} style={{ display:'flex', alignItems:'center', gap:12, textDecoration:'none', color:'inherit', flexShrink: 0 }}>
          <img src={onDark ? 'assets/latent_bio_logo_on_dark.png' : 'assets/latent_bio_logo.png'} alt="" style={{ height: 30, width: 'auto', display:'block' }}/>
          <span style={{
            fontFamily: 'var(--font-display)', fontWeight: 700,
            fontSize: 20, letterSpacing: '-0.005em',
            whiteSpace: 'nowrap', lineHeight: 1,
          }}>
            LatentBio
          </span>
        </a>

        {/* Nav */}
        <nav className="desktop-nav" ref={navRef} style={{
          position: 'relative',
          display: 'flex', gap: 4, marginLeft: 'auto', alignItems: 'center',
          fontFamily: 'var(--font-display)',
        }}>
          {nav.map(n => {
            const isActive = active === n.id;
            return (
              <a
                key={n.id}
                href={`#${n.id}`}
                onClick={e=>go(e, n.id)}
                onMouseEnter={()=>setHover(n.id)}
                onMouseLeave={()=>setHover(null)}
                ref={el => { if (el) linkRefs.current[n.id] = el; }}
                style={{
                  position: 'relative',
                  fontWeight: isActive ? 700 : 500,
                  fontSize: 13,
                  letterSpacing: '0.02em',
                  textDecoration: 'none',
                  color: 'inherit',
                  padding: '10px 14px',
                  whiteSpace: 'nowrap',
                  opacity: isActive || hover === n.id ? 1 : 0.78,
                  transition: 'opacity 160ms, font-weight 160ms',
                }}>
                {n.label}
              </a>
            );
          })}
          {/* Animated indicator */}
          <span aria-hidden style={{
            position: 'absolute',
            bottom: 2,
            left: indicator.left,
            width: indicator.width,
            height: 2,
            background: accentVar,
            borderRadius: 2,
            opacity: indicator.visible ? 1 : 0,
            transform: 'translateY(0)',
            transition: 'left 320ms cubic-bezier(.6,.0,.2,1), width 320ms cubic-bezier(.6,.0,.2,1), opacity 200ms',
            pointerEvents: 'none',
          }}/>
          {/* A subtle dot trail above the indicator */}
          <span aria-hidden style={{
            position:'absolute',
            bottom: 8,
            left: indicator.left + indicator.width / 2 - 2,
            width: 4, height: 4, borderRadius: '50%',
            background: accentVar,
            opacity: indicator.visible ? 0.9 : 0,
            transition: 'left 320ms cubic-bezier(.6,.0,.2,1), opacity 220ms',
            pointerEvents: 'none',
            boxShadow: `0 0 12px ${accentVar}`,
          }}/>
        </nav>

        <button className="btn primary desktop-cta" style={{
          background: accentVar, padding: '11px 18px', fontSize: 12,
          letterSpacing: '0.04em', fontWeight: 600, flexShrink: 0,
          boxShadow: onDark ? '0 4px 24px rgba(54,161,77,0.35)' : '0 2px 10px rgba(54,161,77,0.25)',
        }} onClick={e=>go(e,'contact')}>Request Partnership</button>

        {/* Mobile hamburger — inline display:none so it can never leak to desktop. CSS media query re-enables it on mobile with !important. */}
        <button
          className="mobile-menu-btn"
          aria-label={mobileOpen ? 'Close menu' : 'Open menu'}
          aria-expanded={mobileOpen}
          onClick={() => setMobileOpen(o => !o)}
          style={{ color: 'inherit', display: 'none' }}
        >
          {mobileOpen ? (
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
              <line x1="6" y1="6" x2="18" y2="18"/>
              <line x1="18" y1="6" x2="6" y2="18"/>
            </svg>
          ) : (
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
              <line x1="4" y1="7" x2="20" y2="7"/>
              <line x1="4" y1="12" x2="20" y2="12"/>
              <line x1="4" y1="17" x2="20" y2="17"/>
            </svg>
          )}
        </button>
      </div>

      {/* Mobile overlay — only rendered when open. Since the hamburger is display:none on desktop, mobileOpen can only become true on mobile. Bulletproof against missing CSS. */}
      {mobileOpen && (
        <div className="mobile-nav-overlay open">
          {nav.map(n => (
            <a key={n.id} href={`#${n.id}`} onClick={e => { go(e, n.id); setMobileOpen(false); }}>
              {n.label}
            </a>
          ))}
          <a href="#contact" className="cta-mobile" onClick={e => { go(e,'contact'); setMobileOpen(false); }}>
            Request Partnership
          </a>
        </div>
      )}
    </header>
  );
}
window.Header = Header;
