// nav.jsx — top nav + language switcher (works on landing + jur-help)

const Nav = ({ lang, setLang, t, page = "landing" }) => {
  const [open, setOpen] = React.useState(false);
  const isCyr = lang === "ru";
  const logoSrc = isCyr ? "assets/icons/logo-sborka-word-cyrillic.svg" : "assets/icons/logo-sborka-word-latin.svg";

  // page-aware link targets:
  //   on landing  → in-page anchor smooth-scroll
  //   on jur-help → "jur" link is current page (no nav); others go to index.html#anchor
  const links = [
    { id: "media", label: t.nav.media, isMedia: true },
    { id: "courses", label: t.nav.courses, isCourses: true },
    { id: "jur", label: t.nav.jur, isJur: true },
    { id: "events", label: t.nav.events, isEvents: true },
    { id: "about", label: t.nav.about, isAbout: true },
  ];

  const isActiveLink = (link) => {
    if (page === "landing") return false;
    if (page === "article") return !!link.isMedia;
    if (page === "media") return !!link.isMedia;
    if (page === "courses") return !!link.isCourses;
    if (page === "jur") return !!link.isJur;
    if (page === "events") return !!link.isEvents;
    if (page === "about") return !!link.isAbout;
    return false;
  };

  const langs = ["ru", "en", "ca", "es"];

  React.useEffect(() => {
    setOpen(false);
  }, [lang, page]);

  React.useEffect(() => {
    if (typeof window === "undefined") return undefined;

    const syncViewport = () => {
      if (window.innerWidth > 900) setOpen(false);
    };

    const onKey = (e) => {
      if (e.key === "Escape") setOpen(false);
    };

    window.addEventListener("resize", syncViewport);
    window.addEventListener("keydown", onKey);
    syncViewport();

    return () => {
      window.removeEventListener("resize", syncViewport);
      window.removeEventListener("keydown", onKey);
    };
  }, []);

  React.useEffect(() => {
    if (typeof window === "undefined") return undefined;
    const isMobile = window.innerWidth <= 900;
    const body = document.body;
    const html = document.documentElement;

    if (!isMobile) {
      body.classList.remove("sb-menu-open");
      html.classList.remove("sb-menu-open");
      return undefined;
    }

    const prev = document.body.style.overflow;
    document.body.style.overflow = open ? "hidden" : "";
    body.classList.toggle("sb-menu-open", open);
    html.classList.toggle("sb-menu-open", open);
    return () => {
      document.body.style.overflow = prev;
      body.classList.remove("sb-menu-open");
      html.classList.remove("sb-menu-open");
    };
  }, [open]);

  const closeMenu = () => setOpen(false);

  const onClick = (e, link) => {
    closeMenu();
    if (link.isJur) {
      e.preventDefault();
      if (page === "jur") { window.scrollTo({ top: 0, behavior: "smooth" }); }
      else { window.location.href = "jur-help.html"; }
      return;
    }
    if (link.isCourses) {
      e.preventDefault();
      if (page === "courses") { window.scrollTo({ top: 0, behavior: "smooth" }); }
      else { window.location.href = "courses.html"; }
      return;
    }
    if (link.isMedia) {
      e.preventDefault();
      // already here? scroll to top. otherwise navigate.
      if (page === "media") {
        window.scrollTo({ top: 0, behavior: "smooth" });
      } else {
        window.location.href = "media.html";
      }
      return;
    }
    if (link.isEvents) {
      e.preventDefault();
      if (page === "events") { window.scrollTo({ top: 0, behavior: "smooth" }); }
      else { window.location.href = "events.html"; }
      return;
    }
    if (link.isAbout) {
      e.preventDefault();
      if (page === "about") { window.scrollTo({ top: 0, behavior: "smooth" }); }
      else { window.location.href = "about.html"; }
      return;
    }
    if (page === "landing") {
      e.preventDefault();
      const el = document.getElementById(link.id);
      if (el) {
        const navEl = document.querySelector(".nav");
        const navOffset = navEl ? navEl.getBoundingClientRect().height : 72;
        const top = el.getBoundingClientRect().top + window.scrollY - navOffset;
        window.scrollTo({ top, behavior: "smooth" });
      }
    } else {
      // off-landing: navigate to landing anchor
      e.preventDefault();
      window.location.href = "index.html#" + link.id;
    }
  };

  const onBrand = (e) => {
    closeMenu();
    if (page === "landing") {
      e.preventDefault();
      window.scrollTo({ top: 0, behavior: "smooth" });
    } else {
      e.preventDefault();
      window.location.href = "index.html";
    }
  };

  const onLang = (code) => {
    setLang(code);
    closeMenu();
  };

  return (
    <nav className={`nav${open ? " mobile-open" : ""}`} data-screen-label="00 nav" style={{ borderWidth: "0px" }}>
      <a className="brand" href="index.html" onClick={onBrand} style={{ lineHeight: "0", borderWidth: "0px" }}>
        <img src={logoSrc} alt="sbor/ka" />
      </a>
      <div className="links" style={{ lineHeight: "0" }}>
        {links.map((l) => (
          <a
            key={l.id}
            className={isActiveLink(l) ? "active" : ""}
            href={l.isJur ? "jur-help.html" : l.isMedia ? "media.html" : l.isCourses ? "courses.html" : l.isEvents ? "events.html" : l.isAbout ? "about.html" : `#${l.id}`}
            onClick={(e) => onClick(e, l)}
          >
            {l.label}
          </a>
        ))}
      </div>
      <div className="end">
        <div className="lang">
          {langs.map((code) => (
            <button key={code} className={lang === code ? "on" : ""} onClick={() => onLang(code)}>{code}</button>
          ))}
        </div>
      </div>
      <button
        type="button"
        className="nav-toggle"
        aria-label={open ? "close menu" : "open menu"}
        aria-expanded={open ? "true" : "false"}
        onClick={() => setOpen((v) => !v)}
      >
        <span className="nav-toggle-bars" aria-hidden="true">
          <span></span>
          <span></span>
          <span></span>
        </span>
      </button>
      <div className="nav-panel" aria-hidden={open ? "false" : "true"}>
        <div className="nav-panel-main">
          {links.map((l) => (
            <a
              key={`mobile-${l.id}`}
              className={`nav-panel-link${isActiveLink(l) ? " active" : ""}`}
              href={l.isJur ? "jur-help.html" : l.isMedia ? "media.html" : l.isCourses ? "courses.html" : l.isEvents ? "events.html" : l.isAbout ? "about.html" : `#${l.id}`}
              onClick={(e) => onClick(e, l)}
            >
              <span>{l.label}</span>
              <span className="arr">→</span>
            </a>
          ))}
        </div>
        <div className="nav-panel-lang">
          {langs.map((code) => (
            <button key={`mobile-lang-${code}`} className={lang === code ? "on" : ""} onClick={() => onLang(code)}>
              {code}
            </button>
          ))}
        </div>
      </div>
      <button type="button" className="nav-backdrop" aria-label="close menu" onClick={closeMenu}></button>
    </nav>
  );
};

window.Nav = Nav;
