const CAP_PAGES = [
  { key: 'manufacturing', label: 'Manufacturing',  num: '01', href: 'manufacturing-v2.html',     desc: 'Own factories + vetted network' },
  { key: 'logistics',     label: 'Logistics',      num: '02', href: 'logistics-v2.html',         desc: 'Factory floor to front door' },
  { key: 'consultancy',   label: 'Consultancy',    num: '03', href: 'consultancy-v2.html',       desc: 'Independent supply-chain advisory' },
  { key: 'ai',            label: 'AI & Technology',num: '04', href: 'ai-and-technology-v2.html', desc: 'The intelligence layer' },
];

function Nav({ linkHome = false, activeCap = null }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [capOpen, setCapOpen] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [mobileCapOpen, setMobileCapOpen] = React.useState(activeCap !== null);
  const closeTimer = React.useRef(null);

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

  React.useEffect(() => {
    document.body.style.overflow = mobileOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [mobileOpen]);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') setMobileOpen(false); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, []);

  const openMenu = () => {
    if (closeTimer.current) { clearTimeout(closeTimer.current); closeTimer.current = null; }
    setCapOpen(true);
  };
  const closeMenuSoon = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => setCapOpen(false), 120);
  };

  const home = linkHome ? 'index.html' : '#';
  const prefix = linkHome ? 'index.html' : '';

  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''} ${mobileOpen ? 'mobile-open' : ''}`}>
      <div className="container nav-inner">
        <a href={home} className="logo">
          <img src={window.__resources?.toroLogo || "assets/toro-logo.png"} alt="Toro" className="logo-img" />
        </a>
        <div className="nav-links">
          <div
            className={`nav-cap ${capOpen ? 'open' : ''}`}
            onMouseEnter={openMenu}
            onMouseLeave={closeMenuSoon}
          >
            <a
              href={`${prefix}#capabilities`}
              className={`nav-cap-trigger ${activeCap ? 'is-active' : ''}`}
              onClick={(e) => {
                // On sub-pages, let the menu handle navigation instead of jumping to anchor
                if (!linkHome && !prefix) return;
              }}
            >
              Capabilities
              <svg className="nav-caret" width="9" height="9" viewBox="0 0 10 10" fill="none" aria-hidden="true">
                <path d="M2.5 3.8L5 6.3l2.5-2.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </a>

            <div className="cap-menu" role="menu" aria-hidden={!capOpen}>
              <div className="cap-menu-inner">
                <div className="cap-menu-head">
                  <span className="kicker"><span className="dot"></span>CAPABILITIES</span>
                  <span className="cap-menu-sub">Four services. One platform.</span>
                </div>
                <div className="cap-menu-grid">
                  {CAP_PAGES.map((c) => (
                    <a
                      key={c.key}
                      href={c.href}
                      className={`cap-menu-item ${activeCap === c.key ? 'active' : ''}`}
                      role="menuitem"
                    >
                      <div className="cap-menu-num">CAP.{c.num}</div>
                      <div className="cap-menu-label">{c.label}</div>
                      <div className="cap-menu-desc">{c.desc}</div>
                      <svg className="cap-menu-arr" width="12" height="12" viewBox="0 0 10 10" fill="none">
                        <path d="M2 5h6m0 0L5.5 2.5M8 5 5.5 7.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                      </svg>
                    </a>
                  ))}
                </div>
                <div className="cap-menu-foot">
                  <a href={`${prefix}#capabilities`} className="link">
                    Overview of all capabilities
                    <svg width="10" height="10" viewBox="0 0 10 10" fill="none"><path d="M2 5h6m0 0L5.5 2.5M8 5 5.5 7.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
                  </a>
                </div>
              </div>
            </div>
          </div>

          <a href="global-locations.html">Locations</a>
          <a href="meet-the-team.html">Team</a>
        </div>
        <a href="contact-us.html" onClick={(e) => { if (window.__setView) { e.preventDefault(); window.__setView('contact'); window.scrollTo({top:0}); } }} className="btn btn-ghost btn-pill nav-cta">
          Talk to an expert
          <svg className="arr" width="11" height="11" viewBox="0 0 10 10" fill="none"><path d="M2 5h6m0 0L5.5 2.5M8 5 5.5 7.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
        </a>
        <button
          type="button"
          className={`nav-burger ${mobileOpen ? 'open' : ''}`}
          aria-label={mobileOpen ? 'Close menu' : 'Open menu'}
          aria-expanded={mobileOpen}
          aria-controls="nav-mobile-panel"
          onClick={() => setMobileOpen(v => !v)}
        >
          <span></span><span></span><span></span>
        </button>
      </div>

      <div
        id="nav-mobile-panel"
        className={`nav-mobile ${mobileOpen ? 'open' : ''}`}
        aria-hidden={!mobileOpen}
      >
        <div className="nav-mobile-inner">
          <div className="nav-mobile-section">
            <button
              type="button"
              className={`nav-mobile-row nav-mobile-cap-toggle ${mobileCapOpen ? 'open' : ''}`}
              onClick={() => setMobileCapOpen(v => !v)}
              aria-expanded={mobileCapOpen}
            >
              <span>Capabilities</span>
              <svg className="nav-mobile-caret" width="12" height="12" viewBox="0 0 10 10" fill="none" aria-hidden="true">
                <path d="M2.5 3.8L5 6.3l2.5-2.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </button>
            <div className={`nav-mobile-cap-list ${mobileCapOpen ? 'open' : ''}`}>
              {CAP_PAGES.map((c) => (
                <a
                  key={c.key}
                  href={c.href}
                  className={`nav-mobile-cap-item ${activeCap === c.key ? 'active' : ''}`}
                >
                  <span className="nav-mobile-cap-num">CAP.{c.num}</span>
                  <span className="nav-mobile-cap-label">{c.label}</span>
                </a>
              ))}
            </div>
          </div>
          <a href="global-locations.html" className="nav-mobile-row">Locations</a>
          <a href="meet-the-team.html" className="nav-mobile-row">Team</a>
          <a
            href="contact-us.html"
            className="nav-mobile-cta"
            onClick={(e) => { if (window.__setView) { e.preventDefault(); window.__setView('contact'); window.scrollTo({top:0}); setMobileOpen(false); } }}
          >
            Talk to an expert
            <svg width="12" height="12" viewBox="0 0 10 10" fill="none"><path d="M2 5h6m0 0L5.5 2.5M8 5 5.5 7.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
          </a>
        </div>
      </div>
      <div
        className={`nav-mobile-scrim ${mobileOpen ? 'open' : ''}`}
        onClick={() => setMobileOpen(false)}
        aria-hidden="true"
      />
    </nav>
  );
}
window.Nav = Nav;
window.CAP_PAGES = CAP_PAGES;
