// Fixed navigation with native links and a keyboard-accessible mobile menu.
const NAV_LINKS = [
  { name: 'Home', path: '/' },
  { name: 'Work', path: '/work' },
  { name: 'Contact', path: '/contact' },
];

function Navbar({ route, onNavigate }) {
  const [scrolled, setScrolled] = React.useState(() => window.scrollY > 50);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const menuRef = React.useRef(null);
  const openRef = React.useRef(null);

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

  React.useEffect(() => {
    if (!menuOpen) return;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const focusable = () => [...menuRef.current.querySelectorAll('button, a[href]')];
    focusable()[0]?.focus();
    const onKey = (event) => {
      if (event.key === 'Escape') { event.preventDefault(); setMenuOpen(false); }
      if (event.key !== 'Tab') return;
      const items = focusable();
      const first = items[0], last = items[items.length - 1];
      if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
      else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
    };
    const onResize = () => { if (window.innerWidth > 900) setMenuOpen(false); };
    document.addEventListener('keydown', onKey);
    window.addEventListener('resize', onResize);
    return () => {
      document.body.style.overflow = previousOverflow;
      document.removeEventListener('keydown', onKey);
      window.removeEventListener('resize', onResize);
      openRef.current?.focus({ preventScroll: true });
    };
  }, [menuOpen]);

  React.useEffect(() => setMenuOpen(false), [route]);

  const follow = (event, path) => {
    if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
    event.preventDefault(); setMenuOpen(false); onNavigate(path);
  };

  return (
    <>
      <nav className={'zf-nav' + (scrolled ? ' is-scrolled' : '')} aria-label="Primary navigation">
        <div className="zf-nav-inner">
          <a className="zf-nav-logo" href="#/" onClick={e => follow(e, '/')}>
            {window.SITE.name}
          </a>
          <div className="zf-nav-links-desktop">
            {NAV_LINKS.map(link => (
              <a key={link.path} className="zf-nav-link" href={'#' + link.path}
                 aria-current={route === link.path ? 'page' : undefined}
                 onClick={e => follow(e, link.path)}>{link.name}</a>
            ))}
            <a className="zf-nav-whatsapp" href={window.SITE.whatsappUrl} target="_blank" rel="noopener noreferrer">WhatsApp</a>
          </div>
          <button ref={openRef} type="button" className="zf-nav-mobile-btn"
            aria-label="Open menu" aria-expanded={menuOpen} aria-controls="zf-mobile-menu"
            onClick={() => setMenuOpen(true)}>
            <svg aria-hidden="true" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <path d="M4 7h16M4 13h16M4 19h16"/>
            </svg>
          </button>
        </div>
      </nav>
      {menuOpen && (
        <div ref={menuRef} id="zf-mobile-menu" className="zf-mobile-menu" role="dialog" aria-modal="true" aria-label="Navigation menu">
          <button className="zf-mobile-menu-close" aria-label="Close menu" onClick={() => setMenuOpen(false)}>
            <svg aria-hidden="true" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="m6 6 12 12M18 6 6 18"/></svg>
          </button>
          {NAV_LINKS.map(link => (
            <a key={link.path} href={'#' + link.path} data-active={route === link.path}
              aria-current={route === link.path ? 'page' : undefined}
              onClick={e => follow(e, link.path)}>{link.name}</a>
          ))}
          <a href={window.SITE.whatsappUrl} target="_blank" rel="noopener noreferrer" data-active="false" onClick={() => setMenuOpen(false)}>WhatsApp</a>
        </div>
      )}
    </>
  );
}

window.Navbar = Navbar;
