/* Nav — glass pill row + full-width mega menu (Services, Industries). Cases & About direct. */
function LangToggle({ lang, setLang }) {
  const langs = ['en','pt','es'];
  return (
    <div style={{ display:'flex', alignItems:'center', gap:2, fontFamily:'var(--font-mono)', fontSize:12.5, letterSpacing:'.04em' }}>
      {langs.map((l, i) => (
        <React.Fragment key={l}>
          {i > 0 && <span style={{ color:'var(--text-3)', opacity:.5 }}>|</span>}
          <button onClick={()=>setLang(l)} style={{
            background:'none', border:'none', cursor:'pointer', padding:'4px 6px',
            color: lang===l ? 'var(--text-1)' : 'var(--text-3)', fontWeight: lang===l ? 700 : 400,
            fontFamily:'inherit', fontSize:'inherit', textTransform:'uppercase', transition:'color var(--dur)',
          }}>{l}</button>
        </React.Fragment>
      ))}
    </div>
  );
}

function ThemeToggle({ theme, setTheme }) {
  const [h, setH] = useState(false);
  return (
    <button aria-label="Toggle theme" onClick={()=>setTheme(theme==='dark'?'light':'dark')}
      onMouseEnter={()=>setH(true)} onMouseLeave={()=>setH(false)}
      style={{ display:'grid', placeItems:'center', width:38, height:38, borderRadius:'var(--r-btn)',
        background: h ? 'rgba(155,85,214,.12)' : 'transparent', border:'1px solid var(--border-1)',
        color:'var(--text-1)', cursor:'pointer', transition:'all var(--dur)' }}>
      <Icon name={theme==='dark'?'sun':'moon'} size={18} />
    </button>
  );
}

function Nav({ t, lang, setLang, theme, setTheme, active, heroDark = true }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);      // mobile drawer
  const [mega, setMega] = useState(null);        // 'services' | 'industries' | null
  const closeTimer = useRef(null);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll(); window.addEventListener('scroll', onScroll, { passive:true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const openMega = (k) => { clearTimeout(closeTimer.current); setMega(k); };
  const scheduleClose = () => { clearTimeout(closeTimer.current); closeTimer.current = setTimeout(()=>setMega(null), 90); };

  const P = window.PAGES;
  const N = t.nav;
  // solid surface whenever scrolled OR a mega panel is open (so the full-width bar reads clearly)
  const solid = scrolled || !!mega;
  const topWhite = !solid && heroDark;
  const topVars = topWhite ? { '--text-1':'#fff', '--text-2':'rgba(255,255,255,.8)', '--text-3':'rgba(255,255,255,.62)', '--border-1':'rgba(255,255,255,.2)', '--border-2':'rgba(255,255,255,.3)' } : {};
  const logoVariant = topWhite ? 'paper' : (theme==='light' ? 'gradient' : 'paper');

  const megaItems = mega==='services' ? N.servicesItems : mega==='industries' ? N.industriesItems : [];

  return (
    <React.Fragment>
      <header onMouseLeave={scheduleClose} style={{ position:'fixed', top:0, left:0, right:0, zIndex:100,
        transition:'background var(--dur) var(--ease-out), border-color var(--dur), box-shadow var(--dur)',
        background: solid ? 'var(--nav-bg)' : 'rgba(255,255,255,0.10)',
        backdropFilter: 'blur(16px) saturate(1.6)', WebkitBackdropFilter: 'blur(16px) saturate(1.6)',
        boxShadow: solid ? '0 8px 30px rgba(10,4,24,.28)' : 'none',
        borderBottom:`1px solid ${solid ? 'var(--border-1)' : 'rgba(255,255,255,.08)'}`, ...topVars }}>
        <Container style={{ display:'flex', alignItems:'center', justifyContent:'space-between', height:72 }}>
          <Logo size={30} variant={logoVariant} href={P.home} />
          <nav style={{ display:'flex', alignItems:'center', gap:28 }} className="bne-navlinks">
            <MegaTrigger label={N.services} open={mega==='services'} active={active==='services'} onOpen={()=>openMega('services')} />
            <MegaTrigger label={N.industries} open={mega==='industries'} active={active==='industries'} onOpen={()=>openMega('industries')} />
            <NavLink href={P.cases} label={N.cases} active={active==='cases'} onHover={scheduleClose} />
            <NavLink href={P.about} label={N.about} active={active==='about'} onHover={scheduleClose} />
          </nav>
          <div style={{ display:'flex', alignItems:'center', gap:14 }} className="bne-navactions">
            <LangDropdown lang={lang} setLang={setLang} />
            <ThemeToggle theme={theme} setTheme={setTheme} />
            <Button variant="accent" href={P.contact} style={{ padding:'11px 18px', fontSize:14.5 }}>{N.cta}</Button>
          </div>
          <button className="bne-burger" aria-label="Menu" onClick={()=>setOpen(true)}
            style={{ display:'none', placeItems:'center', width:40, height:40, borderRadius:'var(--r-btn)',
              background:'transparent', border:'1px solid var(--border-1)', color:'var(--text-1)', cursor:'pointer' }}>
            <Icon name="menu" size={20} />
          </button>
        </Container>

        {/* Full-width mega bar — seamlessly attached below the pill row */}
        {mega && (
          <div onMouseEnter={()=>openMega(mega)} style={{ borderTop:'1px solid var(--border-1)', animation:'bneMegaIn .2s var(--ease-out)' }}>
            <Container style={{ paddingTop:26, paddingBottom:30 }}>
              <div className="t-eyebrow" style={{ marginBottom:18 }}>{mega==='services' ? N.services : N.industries}</div>
              <div className="bne-mega-grid" style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:6 }}>
                {megaItems.map(it => <MegaItem key={it.label} it={it} />)}
              </div>
            </Container>
          </div>
        )}
      </header>

      {/* Mobile drawer with accordions */}
      <div style={{ position:'fixed', inset:0, zIndex:200, pointerEvents: open?'auto':'none' }}>
        <div onClick={()=>setOpen(false)} style={{ position:'absolute', inset:0, background:'rgba(10,5,20,.5)',
          opacity: open?1:0, transition:'opacity var(--dur)' }}></div>
        <div style={{ position:'absolute', top:0, right:0, bottom:0, width:'min(88vw,360px)', background:'#2A0F4F',
          color:'#fff', padding:'24px', transform: open?'translateX(0)':'translateX(100%)',
          transition:'transform .3s var(--ease-out)', boxShadow:'var(--shadow-lg)', display:'flex', flexDirection:'column', gap:18, overflowY:'auto' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <Mark size={28} variant="paper" />
            <button aria-label="Close" onClick={()=>setOpen(false)} style={{ background:'none', border:'none', color:'#fff', cursor:'pointer' }}><Icon name="x" size={22}/></button>
          </div>
          <nav style={{ display:'flex', flexDirection:'column', gap:2 }}>
            <MobileAccordion label={N.services} items={N.servicesItems} onNav={()=>setOpen(false)} />
            <MobileAccordion label={N.industries} items={N.industriesItems} onNav={()=>setOpen(false)} />
            <a href={P.cases} onClick={()=>setOpen(false)} style={mobileLink(active==='cases')}>{N.cases}</a>
            <a href={P.about} onClick={()=>setOpen(false)} style={mobileLink(active==='about')}>{N.about}</a>
          </nav>
          <div style={{ display:'flex', alignItems:'center', gap:16, marginTop:'auto', paddingTop:12 }}>
            <LangDropdown lang={lang} setLang={setLang} up={true} />
            <ThemeToggle theme={theme} setTheme={setTheme} />
          </div>
          <Button variant="accent" href={P.contact} onClick={()=>setOpen(false)} style={{ justifyContent:'center' }}>{N.cta}</Button>
        </div>
      </div>
    </React.Fragment>
  );
}

function mobileLink(active) {
  return { color: active ? 'var(--purple-light)' : '#fff', textDecoration:'none',
    fontFamily:'var(--font-display)', fontWeight:700, fontSize:23, padding:'13px 0', letterSpacing:'-.01em',
    borderBottom:'1px solid rgba(255,255,255,.1)' };
}

function MegaTrigger({ label, open, active, onOpen }) {
  return (
    <button onMouseEnter={onOpen} onFocus={onOpen} aria-expanded={open} style={{
      display:'inline-flex', alignItems:'center', gap:5, background:'none', border:'none', cursor:'pointer',
      color:(open||active)?'var(--accent)':'var(--text-2)', fontFamily:'var(--font-body)', fontSize:15, fontWeight:500,
      padding:0, transition:'color var(--dur)' }}>
      {label} <Icon name="chevron" size={14} style={{ transform: open?'rotate(180deg)':'none', transition:'transform var(--dur)', opacity:.8 }}/>
    </button>
  );
}

function MegaItem({ it }) {
  const [h, setH] = useState(false);
  return (
    <a href={it.href} onMouseEnter={()=>setH(true)} onMouseLeave={()=>setH(false)} style={{
      display:'flex', alignItems:'center', gap:13, padding:'13px 14px', borderRadius:10, textDecoration:'none',
      background: h ? 'rgba(123,47,190,.12)' : 'transparent', transition:'background var(--dur)' }}>
      <span style={{ display:'grid', placeItems:'center', flexShrink:0, width:38, height:38, borderRadius:10,
        background:'rgba(123,47,190,.14)', color:'var(--accent)' }}><Icon name={it.icon} size={19}/></span>
      <span style={{ fontFamily:'var(--font-display)', fontWeight:700, fontSize:15.5,
        color: h ? 'var(--accent)' : 'var(--text-1)', transition:'color var(--dur)' }}>{it.label}</span>
    </a>
  );
}

function MobileAccordion({ label, items, onNav }) {
  const [exp, setExp] = useState(false);
  return (
    <div style={{ borderBottom:'1px solid rgba(255,255,255,.1)' }}>
      <button onClick={()=>setExp(e=>!e)} style={{ width:'100%', display:'flex', alignItems:'center', justifyContent:'space-between',
        background:'none', border:'none', cursor:'pointer', color:'#fff', padding:'13px 0',
        fontFamily:'var(--font-display)', fontWeight:700, fontSize:23, letterSpacing:'-.01em' }}>
        {label} <Icon name="chevron" size={20} style={{ transform: exp?'rotate(180deg)':'none', transition:'transform var(--dur)' }}/>
      </button>
      <div style={{ overflow:'hidden', maxHeight: exp ? items.length*46+8 : 0, transition:'max-height .3s var(--ease-out)' }}>
        <div style={{ display:'flex', flexDirection:'column', paddingBottom:8 }}>
          {items.map(it => (
            <a key={it.label} href={it.href} onClick={onNav} style={{ display:'flex', alignItems:'center', gap:11,
              color:'rgba(255,255,255,.8)', textDecoration:'none', fontFamily:'var(--font-body)', fontWeight:600, fontSize:16, padding:'9px 0 9px 6px' }}>
              <Icon name={it.icon} size={17} style={{ color:'var(--purple-light)' }}/>{it.label}
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}

function NavLink({ href, label, active, onHover }) {
  const [h, setH] = useState(false);
  return (
    <a href={href} onMouseEnter={()=>{ setH(true); onHover && onHover(); }} onMouseLeave={()=>setH(false)} style={{
      color: active ? 'var(--accent)' : (h ? 'var(--text-1)' : 'var(--text-2)'), textDecoration:'none', fontFamily:'var(--font-body)',
      fontSize:15, fontWeight:500, transition:'color var(--dur)', position:'relative', paddingBottom:3 }}>
      {label}
      {active && <span style={{ position:'absolute', left:0, right:0, bottom:-1, height:2, borderRadius:2, background:'var(--accent)' }}></span>}
    </a>
  );
}

Object.assign(window, { Nav, LangToggle, ThemeToggle });
