function NavLink({ label, active, onClick, mobile = false }) {
  const [hovered, setHovered] = React.useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        border: 'none', background: 'none', cursor: 'pointer',
        padding: mobile ? '18px 4px' : '4px 0',
        width: mobile ? '100%' : undefined,
        textAlign: mobile ? 'left' : undefined,
        fontFamily: 'var(--font-primary)', fontSize: '11px',
        fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase',
        color: (active || hovered) ? 'var(--color-terracota)' : 'var(--color-text)',
        borderBottom: active ? '1px solid var(--color-terracota)' : '1px solid transparent',
        transition: 'color 150ms ease, border-color 150ms ease',
      }}
    >
      {label}
    </button>
  );
}

function InstagramLink({ mobile = false }) {
  const [hovered, setHovered] = React.useState(false);
  return (
    <a
      href="https://www.instagram.com/calmaeta.coffee"
      target="_blank"
      rel="noreferrer"
      aria-label="Instagram"
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        display: 'flex', alignItems: 'center',
        color: hovered ? 'var(--color-terracota)' : 'var(--color-text-muted)',
        transition: 'color 150ms ease',
        padding: mobile ? '18px 4px' : '4px 0',
      }}
    >
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
        <rect x="2" y="2" width="20" height="20" rx="5" ry="5" />
        <circle cx="12" cy="12" r="4" />
        <circle cx="17.5" cy="6.5" r="0.5" fill="currentColor" stroke="none" />
      </svg>
    </a>
  );
}

function LangToggle({ lang, setLang, mobile = false, onSelect }) {
  const opt = (code, label) => (
    <button
      onClick={() => { setLang(code); if (onSelect) onSelect(); }}
      style={{
        border: 'none', background: 'none', cursor: 'pointer', padding: mobile ? '4px' : 0,
        fontFamily: 'var(--font-primary)', fontSize: mobile ? '11px' : '10px',
        fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase',
        color: lang === code ? 'var(--color-terracota)' : 'var(--color-text-muted)',
        transition: 'color 150ms ease',
      }}
    >
      {label}
    </button>
  );
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: '8px',
      padding: mobile ? '16px 4px' : 0,
      marginBottom: mobile ? '8px' : 0,
      borderBottom: mobile ? '1px solid var(--color-border)' : 'none',
    }}>
      {opt('es', 'ES')}
      <span style={{ color: 'var(--color-text-muted)', fontSize: '10px' }}>·</span>
      {opt('en', 'EN')}
    </div>
  );
}

function Nav({ activeSection, onNavigate }) {
  const { useLang } = window;
  const { t, lang, setLang } = useLang();
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);

  React.useEffect(() => {
    const handler = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', handler);
    return () => window.removeEventListener('scroll', handler);
  }, []);

  React.useEffect(() => {
    if (!menuOpen) return;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') setMenuOpen(false); };
    document.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = '';
      document.removeEventListener('keydown', onKey);
    };
  }, [menuOpen]);

  const go = (section) => { onNavigate(section); setMenuOpen(false); };

  const links = [
    { label: t.nav.menu, section: 'carta' },
    { label: t.nav.historia, section: 'nosotros' },
    { label: t.nav.espacio, section: 'espacio' },
    { label: t.nav.contacto, section: 'contacto' },
  ];

  return (
    <nav className="calmaeta-nav" style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
      height: '72px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      background: scrolled ? 'rgba(248,247,242,0.95)' : 'transparent',
      backdropFilter: scrolled ? 'blur(10px)' : 'none',
      borderBottom: scrolled ? '1px solid var(--color-border)' : '1px solid transparent',
      transition: 'background 300ms ease, border-color 300ms ease',
    }}>
      <button onClick={() => go('home')} style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 0 }}>
        <img src="assets/logos/logo-principal.svg" style={{ height: 'clamp(48px, 9vw, 68px)', width: 'auto' }} alt="Calmaeta" />
      </button>

      <div className="calmaeta-nav-links">
        {links.map(({ label, section }) => (
          <NavLink key={section} label={label} active={activeSection === section} onClick={() => go(section)} />
        ))}
        <LangToggle lang={lang} setLang={setLang} />
        <InstagramLink />
      </div>

      <button
        className={menuOpen ? 'calmaeta-nav-toggle calmaeta-nav-toggle-open' : 'calmaeta-nav-toggle'}
        onClick={() => setMenuOpen((o) => !o)}
        aria-expanded={menuOpen}
        aria-controls="calmaeta-mobile-menu"
        aria-label={menuOpen ? t.nav.closeMenu : t.nav.openMenu}
      >
        <span /><span /><span />
      </button>

      {menuOpen && (
        <React.Fragment>
          <div className="calmaeta-nav-backdrop" onClick={() => setMenuOpen(false)} />
          <div id="calmaeta-mobile-menu" className="calmaeta-nav-mobile-menu">
            <LangToggle lang={lang} setLang={setLang} mobile={true} onSelect={() => setMenuOpen(false)} />
            {links.map(({ label, section }) => (
              <NavLink key={section} label={label} active={activeSection === section} onClick={() => go(section)} mobile={true} />
            ))}
            <InstagramLink mobile={true} />
          </div>
        </React.Fragment>
      )}
    </nav>
  );
}

Object.assign(window, { Nav });
