/* ============================================================
   Top navigation — unified across the whole site.
   - Sliding glass pill behind the active tab
   - Language switcher (DropdownMenu) right of the tabs
   - "Contact sales" primary CTA
   - Socials no longer live here — they're in the footer.
   ============================================================ */

/* Pages in subfolders (services/, legal/) need "../" on shared nav links. */
const NAV_PREFIX = /\/(services|legal|technologies|blog|apps)\/[^/]*$/.test(window.location.pathname) ? "../" : "";

const NAV_ITEMS = [
{ key: "apps", label: "Apps", href: NAV_PREFIX + "apps.html" },
{ key: "tech", label: "Technologies", href: NAV_PREFIX + "technologies.html" },
{ key: "about", label: "About", href: NAV_PREFIX + "about.html" },
{ key: "process", label: "Process", href: NAV_PREFIX + "process.html" },
{ key: "pricing", label: "Pricing", href: NAV_PREFIX + "pricing.html" },
{ key: "blog", label: "News Hub", href: NAV_PREFIX + "blog.html" },
{ key: "contact", label: "Contact", href: NAV_PREFIX + "contact.html" }];


const LANGUAGES = [
{ code: "en", flag: "🇬🇧", label: "English", local: "English" },
{ code: "ar", flag: "🇸🇦", label: "Arabic", local: "العربية" },
{ code: "tr", flag: "🇹🇷", label: "Turkish", local: "Türkçe" },
{ code: "et", flag: "🇪🇪", label: "Estonian", local: "Eesti" },
{ code: "ru", flag: "🇷🇺", label: "Russian", local: "Русский" },
{ code: "hi", flag: "🇮🇳", label: "Hindi", local: "हिन्दी" },
{ code: "es", flag: "🇪🇸", label: "Spanish", local: "Español" },
{ code: "fr", flag: "🇫🇷", label: "French", local: "Français" }];


const LANGUAGES_SOON = [
{ code: "de", flag: "🇩🇪", label: "German", local: "Deutsch" },
{ code: "zh", flag: "🇨🇳", label: "Chinese", local: "中文" },
{ code: "ja", flag: "🇯🇵", label: "Japanese", local: "日本語" },
{ code: "pt", flag: "🇵🇹", label: "Portuguese", local: "Português" },
{ code: "ur", flag: "🇵🇰", label: "Urdu", local: "اردو" }];


function NavTabs({ items, currentKey, scrolled }) {
  const listRef = React.useRef(null);
  const linkRefs = React.useRef({});
  const [hoverKey, setHoverKey] = React.useState(null);
  const [indicator, setIndicator] = React.useState(null);
  const [tick, setTick] = React.useState(0);

  const focusKey = hoverKey || currentKey;

  const measure = React.useCallback((key) => {
    const list = listRef.current;
    const el = linkRefs.current[key];
    if (!list || !el) return null;
    const listR = list.getBoundingClientRect();
    const elR = el.getBoundingClientRect();
    return { left: elR.left - listR.left, width: elR.width };
  }, []);

  React.useLayoutEffect(() => {
    const pos = focusKey ? measure(focusKey) : null;
    setIndicator(pos);
  }, [focusKey, measure, tick, scrolled, items.length]);

  React.useEffect(() => {
    const onResize = () => setTick((n) => n + 1);
    window.addEventListener("resize", onResize);
    if (document.fonts && document.fonts.ready) {
      document.fonts.ready.then(() => setTick((n) => n + 1));
    }
    return () => window.removeEventListener("resize", onResize);
  }, []);

  return (
    <div
      ref={listRef}
      className="nav__tabs"
      role="navigation"
      onMouseLeave={() => setHoverKey(null)}>
      
      <span
        className={`nav__tabs-pill ${indicator ? "is-visible" : ""}`}
        style={indicator ? { left: `${indicator.left}px`, width: `${indicator.width}px` } : null}
        aria-hidden="true">
      </span>
      {items.map((it) => {
        const isFocus = focusKey === it.key;
        const isCurrent = currentKey === it.key;
        return (
          <a
            key={it.key}
            ref={(el) => {linkRefs.current[it.key] = el;}}
            href={it.href}
            className={`nav__tab ${isFocus ? "is-focus" : ""} ${isCurrent ? "is-current" : ""}`}
            aria-current={isCurrent ? "page" : undefined}
            onMouseEnter={() => setHoverKey(it.key)}
            onFocus={() => setHoverKey(it.key)}
            onBlur={() => setHoverKey(null)}>
            
            {it.label}
          </a>);

      })}
    </div>);

}

function LanguageSwitcher() {
  const [lang, setLang] = React.useState(() => {
    if (typeof window === "undefined") return "en";
    try {return localStorage.getItem("innoveev:lang") || "en";} catch {return "en";}
  });

  // Apply lang/dir to root on mount + whenever lang changes.
  React.useEffect(() => {
    document.documentElement.setAttribute("lang", lang);
    document.documentElement.setAttribute("dir", lang === "ar" ? "rtl" : "ltr");
  }, [lang]);

  const select = (code) => {
    if (code === lang) return;
    try {localStorage.setItem("innoveev:lang", code);} catch {}
    // For pages with translations (blog/post) keep the URL param in sync.
    const url = new URL(window.location.href);
    url.searchParams.set("lang", code);
    window.history.replaceState(null, "", url.toString());
    // Hard reload so translated pages pick up the new language. Other pages
    // just flip dir/lang — visually nearly instant.
    window.location.reload();
  };

  const current = LANGUAGES.find((l) => l.code === lang) || LANGUAGES[0];

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <button
          type="button"
          className="lang-switcher"
          aria-label="Change language"
          data-cursor="Language">
          
          <span className="lang-switcher__flag" aria-hidden="true">{current.flag}</span>
          <span className="lang-switcher__code">{current.code.toUpperCase()}</span>
          <svg width="10" height="10" viewBox="0 0 14 14" fill="none" aria-hidden="true">
            <path d="M3 5.5 L7 9.5 L11 5.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" sideOffset={12}>
        <DropdownMenuLabel>Language</DropdownMenuLabel>
        <DropdownMenuGroup>
          {LANGUAGES.map((l) =>
          <DropdownMenuItem
            key={l.code}
            onSelect={() => select(l.code)}
            className={l.code === lang ? "is-selected" : ""}>
            
              <span className="dropdown-menu__flag" aria-hidden="true">{l.flag}</span>
              <span>{l.label}</span>
              <span className="dropdown-menu__shortcut">{l.local}</span>
            </DropdownMenuItem>
          )}
        </DropdownMenuGroup>
        <DropdownMenuSeparator />
        <DropdownMenuLabel>More coming soon</DropdownMenuLabel>
        <DropdownMenuGroup>
          {LANGUAGES_SOON.map((l) =>
          <DropdownMenuItem key={l.code} disabled>
              <span className="dropdown-menu__flag" aria-hidden="true">{l.flag}</span>
              <span>{l.label}</span>
              <span className="dropdown-menu__shortcut">{l.local}</span>
            </DropdownMenuItem>
          )}
        </DropdownMenuGroup>
      </DropdownMenuContent>
    </DropdownMenu>);

}

function MobileMenu({ items, currentKey, open, onClose }) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => {if (e.key === "Escape") onClose();};
    window.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = prev;
    };
  }, [open, onClose]);

  return (
    <div className={`nav-mobile ${open ? "is-open" : ""}`} aria-hidden={!open}>
      <button type="button" className="nav-mobile__backdrop" aria-label="Close menu" tabIndex={open ? 0 : -1} onClick={onClose}></button>
      <div className="nav-mobile__sheet" role="dialog" aria-modal="true" aria-label="Menu">
        <nav className="nav-mobile__links">
          {items.map((it, i) =>
          <a
            key={it.key}
            href={it.href}
            className={`nav-mobile__link ${currentKey === it.key ? "is-current" : ""}`}
            style={{ "--i": i }}
            tabIndex={open ? 0 : -1}
            onClick={onClose}>
            
              {it.label}
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M6 3l5 5-5 5" /></svg>
            </a>
          )}
        </nav>
        <a href={NAV_PREFIX + "contact.html"} className="btn btn--primary nav-mobile__cta" tabIndex={open ? 0 : -1} onClick={onClose}>
          Talk to us <Arrow />
        </a>
      </div>
    </div>);

}

function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const currentKey = React.useMemo(() => {
    if (typeof window === "undefined") return null;
    const path = window.location.pathname.toLowerCase();
    if (path.endsWith("/blog.html") || path.endsWith("blog.html")) return "blog";
    if (path.endsWith("/post.html") || path.endsWith("post.html")) return "blog";
    if (path.endsWith("/apps.html") || path.endsWith("apps.html")) return "apps";
    if (path.endsWith("/app.html") || path.endsWith("app.html")) return "apps";
    if (path.endsWith("/technologies.html") || path.endsWith("/technology.html")) return "tech";
    if (path.endsWith("/about.html") || path.endsWith("about.html")) return "about";
    if (path.endsWith("/pricing.html") || path.endsWith("pricing.html")) return "pricing";
    if (path.endsWith("/process.html") || path.endsWith("process.html")) return "process";
    if (path.endsWith("/contact.html") || path.endsWith("contact.html")) return "contact";
    return null;
  }, []);

  return (
    <nav className={`nav ${scrolled ? "nav--scrolled" : ""} ${menuOpen ? "nav--menu-open" : ""}`} style={{ borderWidth: "0px" }}>
      <div className="container nav__row">
        <a href={NAV_PREFIX + "index.html"} aria-label="Innoveev home"><Brand /></a>
        <NavTabs items={NAV_ITEMS} currentKey={currentKey} scrolled={scrolled} />
        <div className="nav__cta">
          <LanguageSwitcher />
          <a href={NAV_PREFIX + "contact.html"} className="btn btn--primary btn--small nav__cta-btn">
            Talk to us <Arrow />
          </a>
          <button
            type="button"
            className={`nav-burger ${menuOpen ? "is-open" : ""}`}
            aria-label={menuOpen ? "Close menu" : "Open menu"}
            aria-expanded={menuOpen}
            onClick={() => setMenuOpen((v) => !v)}>
            
            <span></span>
            <span></span>
          </button>
        </div>
      </div>
      <MobileMenu items={NAV_ITEMS} currentKey={currentKey} open={menuOpen} onClose={() => setMenuOpen(false)} />
    </nav>);

}

window.Nav = Nav;