// Sticky top navigation. Blurred paper bg, hairline border, active accent underline.
// Includes an "Industries" dropdown that links to per-sector landing pages.

function IndustriesDropdown({ dark, currentSlug }) {
  const [open, setOpen] = React.useState(false);
  const wrapRef = React.useRef(null);
  const ctx = (typeof getPageContext === "function") ? getPageContext() : { isIndustryPage: false, linkToIndustry: (s) => `industries/${s}.html` };

  React.useEffect(() => {
    if (!open) return;
    const onDown = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    setTimeout(() => document.addEventListener("mousedown", onDown), 0);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDown);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  const active = !!currentSlug;
  const list = (typeof INDUSTRY_ORDER !== "undefined") ? INDUSTRY_ORDER : [];

  return (
    <div ref={wrapRef} style={{ position: "relative", display: "flex", alignItems: "center" }}>
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        onMouseEnter={() => setOpen(true)}
        aria-haspopup="menu"
        aria-expanded={open}
        style={{
          background: "transparent",
          border: "none",
          cursor: "pointer",
          fontFamily: "var(--font-sans)",
          fontSize: 14,
          lineHeight: 1.45,
          color: dark ? "var(--paper)" : "var(--fg-1)",
          opacity: active || open ? 1 : 0.65,
          padding: 0, paddingBottom: 4,
          display: "inline-flex", alignItems: "center", gap: 6,
          position: "relative",
          transition: "opacity var(--dur-fast) var(--ease-out)",
        }}
      >
        Industries
        <span aria-hidden="true" style={{
          display: "inline-block",
          fontSize: 9,
          transform: open ? "rotate(180deg)" : "rotate(0)",
          transition: "transform var(--dur-fast) var(--ease-out)",
        }}>▼</span>
        {active && (
          <span style={{
            position: "absolute",
            left: 0, right: 0, bottom: -22,
            height: 2,
            background: "var(--site-accent, var(--flame))",
          }} />
        )}
      </button>

      {open && (
        <div
          role="menu"
          onMouseLeave={() => setOpen(false)}
          style={{
            position: "absolute",
            top: "calc(100% + 14px)",
            left: -16,
            minWidth: 380,
            background: dark ? "var(--ink)" : "var(--paper)",
            color: dark ? "var(--paper)" : "var(--fg-1)",
            border: `1px solid ${dark ? "rgba(245,243,238,0.14)" : "var(--border-2)"}`,
            borderRadius: 10,
            boxShadow: dark
              ? "0 24px 48px -16px rgba(0,0,0,0.6)"
              : "0 24px 48px -16px rgba(10,10,10,0.18)",
            padding: 8,
            zIndex: 60,
            animation: "indDropIn 200ms cubic-bezier(0.16,1,0.3,1) both",
          }}>
          <style>{`@keyframes indDropIn { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: translateY(0); } }`}</style>

          <div style={{
            fontFamily: "var(--font-mono)", fontSize: 10,
            letterSpacing: "0.18em",
            color: dark ? "var(--n-400)" : "var(--fg-3)",
            padding: "6px 12px 10px",
            textTransform: "uppercase",
          }}>For your sector</div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 4 }}>
            {list.map((slug) => {
              const ind = INDUSTRIES[slug];
              const isCurrent = slug === currentSlug;
              return (
                <a key={slug} role="menuitem"
                  href={ctx.linkToIndustry(slug)}
                  style={{
                    padding: "10px 12px",
                    borderRadius: 6,
                    textDecoration: "none",
                    color: "inherit",
                    display: "flex", flexDirection: "column", gap: 2,
                    background: isCurrent ? (dark ? "rgba(245,243,238,0.06)" : "var(--bg-2)") : "transparent",
                    transition: "background var(--dur-fast) var(--ease-out)",
                  }}
                  onMouseEnter={(e) => e.currentTarget.style.background = dark ? "rgba(245,243,238,0.06)" : "var(--bg-2)"}
                  onMouseLeave={(e) => e.currentTarget.style.background = isCurrent ? (dark ? "rgba(245,243,238,0.06)" : "var(--bg-2)") : "transparent"}
                >
                  <div style={{
                    display: "flex", alignItems: "baseline", justifyContent: "space-between",
                    gap: 8,
                  }}>
                    <span style={{
                      fontFamily: "var(--font-display)",
                      fontSize: 16, fontWeight: 500,
                      letterSpacing: "-0.01em",
                    }}>{ind.name}</span>
                    <span style={{
                      fontFamily: "var(--font-mono)", fontSize: 10,
                      letterSpacing: "0.14em",
                      color: dark ? "var(--n-400)" : "var(--fg-3)",
                    }}>{ind.code}</span>
                  </div>
                  <span style={{
                    fontFamily: "var(--font-mono)", fontSize: 10,
                    letterSpacing: "0.10em",
                    color: dark ? "var(--n-500)" : "var(--fg-3)",
                    textTransform: "uppercase",
                  }}>{ind.sector}</span>
                </a>
              );
            })}
          </div>

          {/* General / Other — full-width tile at the bottom. No sector page;
              clicking lands on #contact instead. Visual rhythm matches the
              other tiles so it reads as the 9th option, not a footer. */}
          <a
            role="menuitem"
            href={ctx.linkToMain ? ctx.linkToMain("contact") : "#contact"}
            style={{
              marginTop: 6,
              padding: "10px 12px",
              borderTop: `1px solid ${dark ? "rgba(245,243,238,0.10)" : "var(--border-1)"}`,
              borderRadius: 0,
              textDecoration: "none",
              color: "inherit",
              display: "flex", flexDirection: "column", gap: 2,
              transition: "background var(--dur-fast) var(--ease-out)",
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = dark ? "rgba(245,243,238,0.06)" : "var(--bg-2)"}
            onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
          >
            <div style={{
              display: "flex", alignItems: "baseline", justifyContent: "space-between",
              gap: 8,
            }}>
              <span style={{
                fontFamily: "var(--font-display)",
                fontSize: 16, fontWeight: 500,
                letterSpacing: "-0.01em",
              }}>{(typeof INDUSTRY_GENERAL !== "undefined" ? INDUSTRY_GENERAL.name : "Your firm isn't here?")}</span>
              <span style={{
                fontFamily: "var(--font-mono)", fontSize: 10,
                letterSpacing: "0.14em",
                color: dark ? "var(--n-400)" : "var(--fg-3)",
              }}>{(typeof INDUSTRY_GENERAL !== "undefined" ? INDUSTRY_GENERAL.code : "09")}</span>
            </div>
            <div style={{
              display: "flex", alignItems: "center", justifyContent: "space-between",
              gap: 8,
            }}>
              <span style={{
                fontFamily: "var(--font-mono)", fontSize: 10,
                letterSpacing: "0.10em",
                color: dark ? "var(--n-500)" : "var(--fg-3)",
                textTransform: "uppercase",
              }}>OTHER / GENERAL</span>
              <span style={{
                fontFamily: "var(--font-mono)", fontSize: 10,
                letterSpacing: "0.12em",
                color: "var(--site-accent, var(--flame))",
              }}>ASK US →</span>
            </div>
          </a>
        </div>
      )}
    </div>
  );
}

function NavHamburgerIcon({ open }) {
  return (
    <span className={"nav-hamburger-icon" + (open ? " is-open" : "")} aria-hidden="true">
      <span /><span /><span />
    </span>
  );
}

function MobileNavMenu({ open, onClose, dark, active, links, ctx, onLinkClick }) {
  const [indOpen, setIndOpen] = React.useState(false);
  const list = (typeof INDUSTRY_ORDER !== "undefined") ? INDUSTRY_ORDER : [];

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  React.useEffect(() => {
    if (!open) setIndOpen(false);
  }, [open]);

  if (!open) return null;

  const items = [
    ...links.slice(0, 2).map((l) => ({ type: "link", ...l })),
    { type: "industries", id: "industries", label: "Industries" },
    ...links.slice(2).map((l) => ({ type: "link", ...l })),
  ];

  const industries = (typeof INDUSTRIES !== "undefined") ? INDUSTRIES : {};

  const panel = (
    <div
      className={"nav-mobile-overlay" + (dark ? " is-dark" : "")}
      role="dialog"
      aria-modal="true"
      aria-label="Site navigation"
      style={{
        position: "fixed",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        zIndex: 100001,
        background: dark ? "var(--ink)" : "var(--paper)",
        color: dark ? "var(--paper)" : "var(--fg-1)",
        overflowY: "auto",
        WebkitOverflowScrolling: "touch",
        touchAction: "pan-y",
      }}
    >
      <div className="nav-mobile-overlay-inner">
        <p className="nav-mobile-eyebrow">// NAVIGATION</p>

        <nav className="nav-mobile-list">
          {items.map((item, i) => {
            if (item.type === "industries") {
              return (
                <div key={item.id} className="nav-mobile-group">
                  <button
                    type="button"
                    className={"nav-mobile-item" + (indOpen ? " is-open" : "")}
                    aria-expanded={indOpen}
                    onClick={() => setIndOpen((v) => !v)}
                  >
                    <span className="nav-mobile-num">{String(i + 1).padStart(2, "0")}</span>
                    <span className="nav-mobile-label">{item.label}</span>
                    <span className="nav-mobile-chevron" aria-hidden="true">+</span>
                  </button>
                  {indOpen && (
                    <div className="nav-mobile-sublist">
                      {list.map((slug) => {
                        const ind = industries[slug];
                        if (!ind) return null;
                        const isCurrent = slug === ctx.slug;
                        return (
                          <a
                            key={slug}
                            href={ctx.linkToIndustry(slug)}
                            className={"nav-mobile-subitem" + (isCurrent ? " is-active" : "")}
                            onClick={onClose}
                          >
                            <span>{ind.name}</span>
                            <span className="nav-mobile-subcode">{ind.code}</span>
                          </a>
                        );
                      })}
                      <a
                        href={ctx.linkToMain ? ctx.linkToMain("contact") : "#contact"}
                        className="nav-mobile-subitem nav-mobile-subitem-accent"
                        onClick={onClose}
                      >
                        <span>{(typeof INDUSTRY_GENERAL !== "undefined" ? INDUSTRY_GENERAL.name : "Your firm isn't here?")}</span>
                        <span className="nav-mobile-subcode">ASK →</span>
                      </a>
                    </div>
                  )}
                </div>
              );
            }

            const l = item;
            return (
              <a
                key={l.id}
                href={l.href || ctx.linkToMain(l.id)}
                className={"nav-mobile-item" + (active === l.id ? " is-active" : "")}
                onClick={(e) => onLinkClick(e, l)}
              >
                <span className="nav-mobile-num">{String(i + 1).padStart(2, "0")}</span>
                <span className="nav-mobile-label">{l.label}</span>
              </a>
            );
          })}
        </nav>

        <div className="nav-mobile-foot">
          <a
            href={ctx.linkToMain("contact")}
            className="nav-mobile-cta"
            onClick={(e) => onLinkClick(e, { id: "contact" })}
            style={{
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
              gap: 8,
              width: "100%",
              padding: "12px 20px",
              borderRadius: 6,
              fontFamily: "var(--font-sans)",
              fontSize: 14,
              fontWeight: 500,
              textDecoration: "none",
              background: dark ? "transparent" : "var(--ink)",
              color: dark ? "var(--paper)" : "var(--paper)",
              border: dark ? "1px solid rgba(245,243,238,0.28)" : "1px solid transparent",
            }}
          >
            Start a project <ArrowGlyph />
          </a>
        </div>
      </div>
    </div>
  );

  return panel;
}

function Nav({ active, onNavigate, dark }) {
  const [mobileOpen, setMobileOpen] = React.useState(false);

  React.useEffect(() => {
    const reset = () => {
      setMobileOpen(false);
      document.documentElement.classList.remove("nav-menu-open");
      if (typeof window.__clearNavLock === "function") window.__clearNavLock();
    };
    window.addEventListener("pageshow", reset);
    return () => window.removeEventListener("pageshow", reset);
  }, []);

  React.useEffect(() => {
    const root = document.documentElement;
    root.classList.toggle("nav-menu-open", mobileOpen);
    const pt = document.querySelector(".om-pt");
    if (pt && mobileOpen) pt.style.visibility = "hidden";
    if (!mobileOpen && typeof window.__clearNavLock === "function") window.__clearNavLock();
    return () => {
      root.classList.remove("nav-menu-open");
      if (typeof window.__clearNavLock === "function") window.__clearNavLock();
    };
  }, [mobileOpen]);
  const ctx = (typeof getPageContext === "function") ? getPageContext() : {
    isIndustryPage: false,
    linkToMain: (id) => `#${id}`,
    linkToRoot: () => "#top",
  };

  const links = [
    { id: "about",       label: "About Us", href: ctx.isIndustryPage ? "about.html" : "about.html" },
    { id: "services",    label: "Services" },
    { id: "careers",     label: "Careers", href: "careers.html" },
    { id: "contact",     label: "Contact" },
  ];

  const bg = dark
    ? "rgba(10, 10, 10, 0.78)"
    : "rgba(245, 243, 238, 0.78)";

  // On industry pages, clicking a section link should navigate to the main page.
  // On the main page, scroll-spy via onNavigate handles smooth scroll.
  // Exception: links with an explicit `href` (e.g. About → about.html) are real
  // page navigations — let the browser follow them.
  const handleClick = (e, link) => {
    if (link.href) return; // real navigation
    if (ctx.isSubPage) return; // let href do its job (industry / about)
    e.preventDefault();
    onNavigate && onNavigate(link.id);
  };

  const handleLogoClick = (e) => {
    if (ctx.isSubPage) return; // let href navigate to index.html
    e.preventDefault();
    onNavigate && onNavigate("top");
  };

  const closeMobile = React.useCallback(() => setMobileOpen(false), []);

  const handleMobileLink = (e, link) => {
    e.preventDefault();
    closeMobile();
    requestAnimationFrame(() => {
      if (link.href) {
        window.location.href = link.href;
        return;
      }
      if (ctx.isSubPage) {
        window.location.href = ctx.linkToMain(link.id);
        return;
      }
      onNavigate && onNavigate(link.id);
    });
  };

  return (
    <>
    <header
      className={mobileOpen ? "nav-header-menu-open" : ""}
      style={{
      position: "sticky",
      top: 0,
      zIndex: mobileOpen ? 100002 : 50,
      background: bg,
      backdropFilter: "blur(14px)",
      WebkitBackdropFilter: "blur(14px)",
      borderBottom: "1px solid var(--border-1)",
    }}>
      <div className="container" style={{
        display: "flex",
        alignItems: "center",
        gap: 32,
        height: 84,
      }}>
        <a href={ctx.linkToRoot()} onClick={handleLogoClick}
          style={{ display: "inline-flex", alignItems: "center", gap: 10, textDecoration: "none" }}>
          <img
            src="assets/logo.png"
            alt="Promefy Solutions"
            style={{
              height: 54,
              width: "auto",
              userSelect: "none",
              filter: dark ? "invert(1)" : "none",
            }}/>
        </a>

        <nav style={{ display: "flex", gap: 28, marginLeft: 16, alignItems: "center" }} className="hide-sm">
          {links.slice(0, 2).map(l => (
            <a key={l.id} href={l.href || ctx.linkToMain(l.id)}
              onClick={(e) => handleClick(e, l)}
              style={{
                fontFamily: "var(--font-sans)",
                fontSize: 14,
                color: dark ? "var(--paper)" : "var(--fg-1)",
                textDecoration: "none",
                opacity: active === l.id ? 1 : 0.65,
                position: "relative",
                paddingBottom: 4,
                transition: "opacity var(--dur-fast) var(--ease-out)",
              }}
              onMouseEnter={(e) => e.currentTarget.style.opacity = 1}
              onMouseLeave={(e) => e.currentTarget.style.opacity = active === l.id ? 1 : 0.65}
            >
              {l.label}
              {active === l.id && (
                <span style={{
                  position: "absolute",
                  left: 0, right: 0, bottom: -22,
                  height: 2,
                  background: "var(--site-accent, var(--flame))",
                }} />
              )}
            </a>
          ))}

          {/* Industries dropdown between Services and Careers */}
          <IndustriesDropdown dark={dark} currentSlug={ctx.slug || null} />

          {links.slice(2).map(l => (
            <a key={l.id} href={l.href || ctx.linkToMain(l.id)}
              onClick={(e) => handleClick(e, l)}
              style={{
                fontFamily: "var(--font-sans)",
                fontSize: 14,
                color: dark ? "var(--paper)" : "var(--fg-1)",
                textDecoration: "none",
                opacity: active === l.id ? 1 : 0.65,
                position: "relative",
                paddingBottom: 4,
                transition: "opacity var(--dur-fast) var(--ease-out)",
              }}
              onMouseEnter={(e) => e.currentTarget.style.opacity = 1}
              onMouseLeave={(e) => e.currentTarget.style.opacity = active === l.id ? 1 : 0.65}
            >
              {l.label}
              {active === l.id && (
                <span style={{
                  position: "absolute",
                  left: 0, right: 0, bottom: -22,
                  height: 2,
                  background: "var(--site-accent, var(--flame))",
                }} />
              )}
            </a>
          ))}
        </nav>

        <button
          type="button"
          className={"show-sm-only nav-hamburger" + (mobileOpen ? " is-open" : "") + (dark ? " is-dark" : "")}
          aria-label={mobileOpen ? "Close menu" : "Open menu"}
          aria-expanded={mobileOpen}
          onClick={() => setMobileOpen((v) => !v)}
        >
          <NavHamburgerIcon open={mobileOpen} />
        </button>

        <div className="hide-sm" style={{
          marginLeft: "auto",
          display: "flex",
          alignItems: "center",
          gap: 18,
        }}>
          <span style={{
            fontFamily: "var(--font-mono)",
            fontSize: 11,
            letterSpacing: "0.12em",
            color: dark ? "var(--n-400)" : "var(--fg-3)",
            display: "flex",
            alignItems: "center",
            gap: 8,
          }}>
            <span style={{
              width: 6, height: 6, borderRadius: "50%",
              background: "var(--status-ok)",
              boxShadow: "0 0 0 3px rgba(31,138,91,0.18)",
              animation: "blink 2s ease-in-out infinite",
            }} />
            ACCEPTING Q3 INTAKE
          </span>
          <Button variant="primary"
            href={ctx.linkToMain("contact")}
            onClick={(e) => handleClick(e, { id: "contact" })}>
            Start a project <ArrowGlyph />
          </Button>
        </div>
      </div>
    </header>

    <MobileNavMenu
      open={mobileOpen}
      onClose={closeMobile}
      dark={dark}
      active={active}
      links={links}
      ctx={ctx}
      onLinkClick={handleMobileLink}
    />
    </>
  );
}

Object.assign(window, { Nav, IndustriesDropdown });
