// Header nav for Layer 1 static pages.
// Hrefs MUST be real paths so static pages outside the SPA work as crawlable
// HTML. Lane labels translate per current language; lane hrefs preserve the
// current language so users stay in their chosen language as they navigate
// across lanes/destinations. The lang button opens a chooser; selecting a
// language navigates to the language-specific URL of the current page.

const NAV_LANES = [
  { id: "plan", label: { en: "Plan", es: "Planificar", fr: "Planifier", pt: "Planejar", de: "Planen", zh: "规划", ar: "خطّط", hi: "योजना" } },
  { id: "book", label: { en: "Book", es: "Reservar", fr: "Réserver", pt: "Reservar", de: "Buchen", zh: "预订", ar: "احجز", hi: "बुक करें" } },
  { id: "pack", label: { en: "Pack", es: "Empacar", fr: "Préparer", pt: "Arrumar", de: "Packen", zh: "打包", ar: "احزم", hi: "सामान बांधें" } },
  { id: "visas-docs", label: { en: "Visas & Docs", es: "Visas y Docs", fr: "Visas & Papiers", pt: "Vistos e Docs", de: "Visa & Dokumente", zh: "签证与文件", ar: "تأشيرات ووثائق", hi: "वीज़ा व दस्तावेज़" } },
  { id: "on-the-ground", label: { en: "On the Ground", es: "Sobre el Terreno", fr: "Sur Place", pt: "No Local", de: "Vor Ort", zh: "实地", ar: "على الأرض", hi: "ज़मीन पर" } },
  { id: "budget", label: { en: "Budget", es: "Presupuesto", fr: "Budget", pt: "Orçamento", de: "Budget", zh: "预算", ar: "الميزانية", hi: "बजट" } },
];

const LANG_OPTIONS = [
  { code: "en", short: "EN", name: "English" },
  { code: "es", short: "ES", name: "Español" },
  { code: "fr", short: "FR", name: "Français" },
  { code: "pt", short: "PT", name: "Português" },
  { code: "de", short: "DE", name: "Deutsch" },
  { code: "zh", short: "中文", name: "中文" },
  { code: "ar", short: "AR", name: "العربية" },
  { code: "hi", short: "HI", name: "हिन्दी" },
];

const NON_EN_LANGS = LANG_OPTIONS.map((o) => o.code).filter((c) => c !== "en");

const SIGN_IN_LABEL = {
  en: "Sign In", es: "Entrar", fr: "Connexion", pt: "Entrar",
  de: "Anmelden", zh: "登录", ar: "تسجيل الدخول", hi: "साइन इन",
};

// Parse path like /plan/, /plan/es/, /europe/ar/, / etc.
function parseLayer1Path(path) {
  const segs = path.split("/").filter(Boolean);
  const lane = segs[0] || "";
  const maybeLang = segs[1] || "";
  const lang = NON_EN_LANGS.includes(maybeLang) ? maybeLang : "en";
  return { lane, lang, basePath: lane ? `/${lane}/` : "/" };
}

function urlForLang(basePath, langCode) {
  if (basePath === "/" || langCode === "en") return basePath;
  return `${basePath}${langCode}/`;
}

const Nav = () => {
  const path = typeof window !== "undefined" ? window.location.pathname : "/";
  const { lane, lang, basePath } = parseLayer1Path(path);
  const [menuOpen, setMenuOpen] = useState(false);
  const wrapRef = useRef(null);

  useEffect(() => {
    if (!menuOpen) return;
    const onDoc = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setMenuOpen(false);
    };
    const onKey = (e) => { if (e.key === "Escape") setMenuOpen(false); };
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDoc);
      document.removeEventListener("keydown", onKey);
    };
  }, [menuOpen]);

  const current = LANG_OPTIONS.find((o) => o.code === lang) || LANG_OPTIONS[0];
  const isActive = (laneId) => lane === laneId;

  return (
    <nav className="nav">
      <a href="/" className="logo" aria-label="HowTo: Travel Edition — home">
        <span className="howto">HowTo:</span>
        <span className="edition">Travel Edition</span>
      </a>
      <ul>
        {NAV_LANES.map((l) => {
          const href = urlForLang(`/${l.id}/`, lang);
          const label = l.label[lang] || l.label.en;
          return (
            <li key={l.id}>
              <a href={href} className={isActive(l.id) ? "active" : undefined} aria-current={isActive(l.id) ? "page" : undefined}>{label}</a>
            </li>
          );
        })}
      </ul>
      <div className="right">
        <div className="lang-wrap" ref={wrapRef} style={{ position: "relative" }}>
          <button
            className="lang"
            onClick={() => setMenuOpen((v) => !v)}
            aria-haspopup="listbox"
            aria-expanded={menuOpen}
            aria-label="Choose language"
          >
            <Icon name="globe" size={16} /> {current.short} <Icon name="chevron" size={12} />
          </button>
          {menuOpen && (
            <ul
              className="lang-menu"
              role="listbox"
              style={{
                position: "absolute", top: "calc(100% + 6px)", right: 0,
                background: "#fff", color: "#111", listStyle: "none",
                margin: 0, padding: "6px 0", border: "1px solid rgba(0,0,0,0.08)",
                borderRadius: 6, boxShadow: "0 8px 28px rgba(0,0,0,0.14)",
                minWidth: 170, zIndex: 1000,
                fontFamily: "DM Sans, system-ui, sans-serif", fontSize: 14,
              }}
            >
              {LANG_OPTIONS.map((opt) => {
                const targetHref = urlForLang(basePath, opt.code);
                const active = opt.code === lang;
                return (
                  <li key={opt.code} role="option" aria-selected={active}>
                    <a
                      href={targetHref}
                      style={{
                        display: "block", padding: "8px 14px", color: "inherit",
                        textDecoration: "none", fontWeight: active ? 600 : 400,
                        background: active ? "rgba(0,0,0,0.04)" : "transparent",
                        direction: opt.code === "ar" ? "rtl" : "ltr",
                      }}
                    >
                      {opt.name}
                    </a>
                  </li>
                );
              })}
            </ul>
          )}
        </div>
        <a href="/sign-in" className="sign-in">{SIGN_IN_LABEL[lang] || SIGN_IN_LABEL.en}</a>
      </div>
    </nav>
  );
};

// Back-compat export — code that referenced the old NAV_LANES shape gets the
// English-href list. New code reads NAV_LANES directly.
const NAV_LANES_LEGACY = NAV_LANES.map((l) => ({ label: l.label.en, href: `/${l.id}/` }));
Object.assign(window, { Nav, NAV_LANES: NAV_LANES_LEGACY, parseLayer1Path, urlForLang, LANG_OPTIONS });
