/* ==========================================================================
   PSLNav.jsx  —  @role
   Shared top navigation. Sticky overlay nav (transparent over dark hero, solidifies to light on scroll). Links + active state driven by PSL_NAV_LINKS; props: theme ("light"|"dark"), active (page id), overlay (bool). Used by every page.
   ========================================================================== */
/* PSLNav.jsx — single canonical top nav used across every PSL page.
   Self-contained styles so it renders identically regardless of which
   stylesheet a page loads. Exposed as window.PSLNav for use anywhere.

   Usage:
     <PSLNav theme="light" active="home" />     // home, method, insights, diagnostic
     <PSLNav theme="dark"  active="teams" />    // teams, individuals (dark hero pages)

   active values: "home" | "method" | "teams" | "individuals" | "diagnostic" | ""
   theme:        "light" | "dark"
*/

const PSL_NAV_STYLE_ID = "__psl-nav-style";
function ensurePSLNavStyles() {
  if (typeof document === "undefined") return;
  if (document.getElementById(PSL_NAV_STYLE_ID)) return;
  const s = document.createElement("style");
  s.id = PSL_NAV_STYLE_ID;
  s.textContent = `
    .psl-nav {
      position: sticky; top: 0; z-index: 60;
      width: 100%;
      font-family: "Mona Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
      transition: background 240ms ease, border-color 240ms ease, box-shadow 240ms ease;
    }
    .psl-nav-inner {
      max-width: 1200px;
      margin: 0 auto;
      padding: 0 32px;
      height: 54px;
      display: flex; align-items: center; justify-content: space-between;
      gap: 24px;
      position: relative;
    }
    .psl-nav-logo {
      display: inline-flex; align-items: center;
      flex-shrink: 0;
      text-decoration: none;
    }
    .psl-nav-logo img { height: 34px; width: auto; display: block; }

    /* ---- Links ---- */
    .psl-nav-links {
      display: flex; align-items: center; gap: 15px;
    }
    .psl-nav-link {
      position: relative;
      font-size: 11px; font-weight: 500;
      text-decoration: none;
      padding: 4px 0;
      transition: color 200ms ease;
    }
    .psl-nav-link::after {
      content: "";
      position: absolute; left: 0; right: 0; bottom: -6px;
      height: 2px;
      transform: scaleX(0);
      transform-origin: left;
      transition: transform 240ms ease, background 240ms ease;
      border-radius: 1px;
    }
    .psl-nav-link.is-active::after { transform: scaleX(1); }
    .psl-nav-link:hover::after     { transform: scaleX(1); }

    /* ---- CTA ---- */
    .psl-nav-cta {
      display: inline-flex; align-items: center; gap: 6px;
      padding: 4px 10px;
      border-radius: 6px;
      font-size: 11px; font-weight: 600;
      text-decoration: none;
      letter-spacing: 0.005em;
      transition: background 200ms ease, transform 200ms ease, box-shadow 200ms ease;
    }
    .psl-nav-cta:hover { transform: translateY(-1px); }

    /* Active CTA — used on the Diagnostic page itself so the user sees they're "here" */
    .psl-nav-cta.is-active {
      background: #2EE0B0 !important;
      color: #0B3F35 !important;
      box-shadow: 0 0 0 3px rgba(46,224,176,0.22), 0 6px 16px rgba(46,224,176,0.20);
    }
    .psl-nav-cta.is-active:hover {
      background: #1FC79A !important;
      transform: translateY(-1px);
    }

    /* ---- Mobile toggle ---- */
    .psl-nav-toggle {
      display: none;
      width: 40px; height: 40px;
      padding: 0;
      background: transparent;
      border: 1px solid transparent;
      border-radius: 8px;
      cursor: pointer;
      flex-direction: column; align-items: center; justify-content: center; gap: 5px;
    }
    .psl-nav-toggle span {
      display: block; width: 20px; height: 2px;
      border-radius: 2px;
      transition: transform 200ms ease, opacity 200ms ease;
    }
    .psl-nav[data-open="true"] .psl-nav-toggle span:nth-child(1) { transform: translateY(7px) rotate(45deg); }
    .psl-nav[data-open="true"] .psl-nav-toggle span:nth-child(2) { opacity: 0; }
    .psl-nav[data-open="true"] .psl-nav-toggle span:nth-child(3) { transform: translateY(-7px) rotate(-45deg); }

    /* ---- Mobile panel ---- */
    .psl-nav-mobile {
      display: none;
      position: absolute; top: 100%; left: 0; right: 0;
      padding: 12px 32px 20px;
      flex-direction: column; gap: 4px;
    }
    .psl-nav[data-open="true"] .psl-nav-mobile { display: flex; }
    .psl-nav-mobile a {
      font-size: 16px; font-weight: 500;
      padding: 14px 4px;
      text-decoration: none;
      border-bottom: 1px solid currentColor;
    }
    .psl-nav-mobile a.psl-nav-cta {
      margin-top: 12px;
      border-bottom: none;
      justify-content: center;
    }

    /* ===== LIGHT theme ===== */
    .psl-nav--light {
      background: rgba(255,255,255,0.92);
      backdrop-filter: saturate(160%) blur(12px);
      -webkit-backdrop-filter: saturate(160%) blur(12px);
      border-bottom: 1px solid rgba(13,0,66,0.06);
    }
    .psl-nav--light.is-scrolled {
      background: rgba(255,255,255,0.96);
      border-bottom-color: rgba(13,0,66,0.09);
      box-shadow: 0 4px 18px rgba(13,0,66,0.05);
    }
    .psl-nav--light .psl-nav-link        { color: #0D0042; }
    .psl-nav--light .psl-nav-link::after  { background: #1F4DD8; }
    .psl-nav--light .psl-nav-link:hover   { color: #1F4DD8; }
    .psl-nav--light .psl-nav-link.is-active { color: #1F4DD8; }
    .psl-nav--light .psl-nav-cta         { background: #1F4DD8; color: #fff; }
    .psl-nav--light .psl-nav-cta:hover   { background: #1A3FB8; box-shadow: 0 6px 16px rgba(31,77,216,0.28); }
    .psl-nav--light .psl-nav-toggle span { background: #0D0042; }
    .psl-nav--light .psl-nav-mobile      { background: rgba(255,255,255,0.98); border-top: 1px solid rgba(13,0,66,0.08); }
    .psl-nav--light .psl-nav-mobile a    { color: #0D0042; border-color: rgba(13,0,66,0.08); }

    /* ===== DARK theme ===== */
    .psl-nav--dark {
      background: #0D0042;
      border-bottom: 1px solid rgba(255,255,255,0.08);
    }
    .psl-nav--dark.is-scrolled {
      background: rgba(13,0,66,0.92);
      backdrop-filter: saturate(160%) blur(14px);
      -webkit-backdrop-filter: saturate(160%) blur(14px);
      border-bottom-color: rgba(255,255,255,0.14);
      box-shadow: 0 4px 22px rgba(0,0,0,0.32);
    }
    .psl-nav--dark .psl-nav-link        { color: rgba(255,255,255,0.86); }
    .psl-nav--dark .psl-nav-link::after  { background: #7FE7C8; }
    .psl-nav--dark .psl-nav-link:hover   { color: #fff; }
    .psl-nav--dark .psl-nav-link.is-active { color: #fff; }
    .psl-nav--dark .psl-nav-cta         { background: #1F4DD8; color: #fff; }
    .psl-nav--dark .psl-nav-cta:hover   { background: #2A5BEF; box-shadow: 0 6px 16px rgba(31,77,216,0.34); }
    .psl-nav--dark .psl-nav-toggle span { background: #fff; }
    .psl-nav--dark .psl-nav-mobile      { background: rgba(13,0,66,0.97); border-top: 1px solid rgba(255,255,255,0.10); }
    .psl-nav--dark .psl-nav-mobile a    { color: rgba(255,255,255,0.92); border-color: rgba(255,255,255,0.10); }

    /* ===== OVERLAY mode =====
       Used on the home page so the looping video hero fills the top of
       the page from y=0. At rest the nav is transparent with white text;
       on scroll it transitions to the chosen theme (light = white solid,
       dark = navy solid). */
    .psl-nav--overlay {
      position: absolute; top: 0; left: 0; right: 0;
      background: transparent !important;
      border-bottom: 1px solid transparent !important;
      box-shadow: none !important;
      backdrop-filter: none !important;
    }
    /* Top scrim so the white logo + links stay legible over any hero (light
       or dark photo), not just dark ones. Fades out once solid on scroll. */
    .psl-nav--overlay::before {
      content: ""; position: absolute; inset: 0; pointer-events: none;
      background: linear-gradient(180deg, rgba(0,0,0,0.38) 0%, rgba(0,0,0,0.14) 55%, rgba(0,0,0,0) 100%);
      transition: opacity 0.3s ease;
    }
    .psl-nav--overlay.is-scrolled::before { opacity: 0; }
    .psl-nav--overlay .psl-nav-inner { position: relative; z-index: 1; }
    .psl-nav--overlay .psl-nav-link        { color: rgba(255,255,255,0.86); }
    .psl-nav--overlay .psl-nav-link::after  { background: #7FE7C8; }
    .psl-nav--overlay .psl-nav-link:hover   { color: #fff; }
    .psl-nav--overlay .psl-nav-link.is-active { color: #fff; }
    .psl-nav--overlay .psl-nav-toggle span { background: #fff; }
    /* Hide the dark-on-white logo while overlaying the video; show its
       negative counterpart instead. Each variant is rendered into the
       DOM and swapped via display so we don't need to invert filters. */
    .psl-nav-logo-light { display: inline-flex; }
    .psl-nav-logo-dark  { display: none; }
    .psl-nav--overlay .psl-nav-logo-light { display: none; }
    .psl-nav--overlay .psl-nav-logo-dark  { display: inline-flex; }

    /* Once the user scrolls past the hero band, lock to the top of the
       viewport and reveal the solid theme treatment. */
    .psl-nav--overlay.is-scrolled {
      position: fixed;
      background: rgba(255,255,255,0.96) !important;
      backdrop-filter: saturate(160%) blur(12px) !important;
      border-bottom: 1px solid rgba(13,0,66,0.09) !important;
      box-shadow: 0 4px 18px rgba(13,0,66,0.05) !important;
    }
    .psl-nav--overlay.is-scrolled .psl-nav-link        { color: #0D0042; }
    .psl-nav--overlay.is-scrolled .psl-nav-link:hover   { color: #1F4DD8; }
    .psl-nav--overlay.is-scrolled .psl-nav-link.is-active { color: #1F4DD8; }
    .psl-nav--overlay.is-scrolled .psl-nav-toggle span { background: #0D0042; }
    .psl-nav--overlay.is-scrolled .psl-nav-logo-light { display: inline-flex; }
    .psl-nav--overlay.is-scrolled .psl-nav-logo-dark  { display: none; }
    .psl-nav--overlay.is-scrolled .psl-nav-mobile {
      background: rgba(255,255,255,0.98);
      border-top: 1px solid rgba(13,0,66,0.08);
    }
    .psl-nav--overlay.is-scrolled .psl-nav-mobile a {
      color: #0D0042; border-color: rgba(13,0,66,0.08);
    }

    /* ---- Responsive ---- */
    @media (max-width: 880px) {
      .psl-nav-inner { padding: 0 20px; height: 56px; }
      .psl-nav-logo img { height: 30px; }
      .psl-nav-links     { display: none; }
      .psl-nav-toggle    { display: inline-flex; }
    }
    /* Container-query versions so the nav adapts inside artboards
       (page containers: pslpage / psli / pslmethod / pslinsights / pslteams) */
    @container pslpage (max-width: 880px) {
      .psl-nav-inner { padding: 0 20px; height: 68px; }
      .psl-nav-logo img { height: 32px; }
      .psl-nav-links     { display: none; }
      .psl-nav-toggle    { display: inline-flex; }
    }
    @container psli (max-width: 880px) {
      .psl-nav-inner { padding: 0 20px; height: 68px; }
      .psl-nav-logo img { height: 32px; }
      .psl-nav-links     { display: none; }
      .psl-nav-toggle    { display: inline-flex; }
    }
    @container pslmethod (max-width: 880px) {
      .psl-nav-inner { padding: 0 20px; height: 68px; }
      .psl-nav-logo img { height: 32px; }
      .psl-nav-links     { display: none; }
      .psl-nav-toggle    { display: inline-flex; }
    }
    @container pslinsights (max-width: 880px) {
      .psl-nav-inner { padding: 0 20px; height: 68px; }
      .psl-nav-logo img { height: 32px; }
      .psl-nav-links     { display: none; }
      .psl-nav-toggle    { display: inline-flex; }
    }
    @container pslteams (max-width: 880px) {
      .psl-nav-inner { padding: 0 20px; height: 68px; }
      .psl-nav-logo img { height: 32px; }
      .psl-nav-links     { display: none; }
      .psl-nav-toggle    { display: inline-flex; }
    }

    /* ---- Defensive: ensure CTA always renders inside scoped containers ---- */
    .psl-i .psl-nav,
    .psl-method .psl-nav { z-index: 60; }
    .psl-i .psl-nav-links,
    .psl-method .psl-nav-links,
    .psl-i .psl-nav-cta,
    .psl-method .psl-nav-cta { display: inline-flex !important; }
    @media (max-width: 880px) {
      .psl-i .psl-nav-links,
      .psl-method .psl-nav-links { display: none !important; }
      .psl-i .psl-nav-cta,
      .psl-method .psl-nav-cta { display: none !important; }
    }
    /* Container-query overrides for the !important defensive rules above */
    @container psli (max-width: 880px) {
      .psl-i .psl-nav-links { display: none !important; }
      .psl-i .psl-nav-cta { display: none !important; }
    }
    @container pslmethod (max-width: 880px) {
      .psl-method .psl-nav-links { display: none !important; }
      .psl-method .psl-nav-cta { display: none !important; }
    }
    @container pslteams (max-width: 880px) {
      .psl-teams .psl-nav-links { display: none !important; }
      .psl-teams .psl-nav-cta { display: none !important; }
    }
  `;
  document.head.appendChild(s);
}

const PSL_NAV_LINKS = [
  { id: "method",      label: "Method",      href: "method.html" },
  { id: "teams",       label: "Teams",       href: "teams.html" },
  { id: "individuals", label: "Individuals", href: "individuals.html" },
  { id: "insights",    label: "Insights",    href: "insights.html" },
];

const PSLNav = ({ theme = "light", active = "", overlay = false }) => {
  if (typeof window !== "undefined") ensurePSLNavStyles();
  const [open, setOpen] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);
  const sentinelRef = React.useRef(null);

  React.useEffect(() => {
    // Scroll detection strategy:
    // 1. Window scroll covers the normal case (page opened on its own).
    // 2. IntersectionObserver on a sentinel at the very top covers cases
    //    where the page is rendered inside a transformed/scrollable
    //    ancestor (e.g. a DesignCanvas artboard in focus mode) — the
    //    window scrollY stays at 0 there, so the listener alone fails.
    const onScroll = () => {
      if (window.scrollY > 8) setScrolled(true);
    };
    window.addEventListener("scroll", onScroll, { passive: true });

    let io;
    if (sentinelRef.current && "IntersectionObserver" in window) {
      io = new IntersectionObserver(
        ([entry]) => setScrolled(!entry.isIntersecting),
        { threshold: 0, rootMargin: "0px" }
      );
      io.observe(sentinelRef.current);
    } else {
      // Fall back to the listener alone — initialise once.
      onScroll();
    }

    return () => {
      window.removeEventListener("scroll", onScroll);
      if (io) io.disconnect();
    };
  }, []);

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

  const isDark = theme === "dark";
  const logoSrc = isDark
    ? "assets/logos/PSL-Logo-Negative.png"
    : "assets/logos/PSL-Logo-Header.svg";

  const navClass =
    "psl-nav psl-nav--" + theme + (scrolled ? " is-scrolled" : "") + (overlay ? " psl-nav--overlay" : "");

  return (
    <React.Fragment>
      {/* Sentinel — sits at the very top of the document. The nav's
          IntersectionObserver flips `scrolled` true the moment this
          element leaves the viewport. Works even when scroll happens
          on a parent container, not the window. */}
      <span
        ref={sentinelRef}
        aria-hidden="true"
        style={{
          position: "absolute",
          top: 0, left: 0,
          width: 1, height: 1,
          pointerEvents: "none",
          opacity: 0
        }}
      />
      <nav
      className={navClass}
      data-open={open ? "true" : "false"}
      data-screen-label="Nav"
      aria-label="Primary"
    >
      <div className="psl-nav-inner">
        <a href="index.html" className="psl-nav-logo" aria-label="Performance Systems Lab — home">
          {overlay ? (
            <React.Fragment>
              {/* Dark-theme (white) logo, shown when nav is transparent
                  over the hero video; CSS swaps to the light logo on scroll. */}
              <img className="psl-nav-logo-dark"  src="assets/logos/PSL-Logo-Negative.png" alt="Performance Systems Lab" />
              <img className="psl-nav-logo-light" src="assets/logos/PSL-Logo-Header.svg"   alt="Performance Systems Lab" />
            </React.Fragment>
          ) : (
            <img src={logoSrc} alt="Performance Systems Lab" />
          )}
        </a>

        <div className="psl-nav-links">
          {PSL_NAV_LINKS.map((l) => (
            <a
              key={l.id}
              href={l.href}
              className={"psl-nav-link" + (l.id === active ? " is-active" : "")}
              aria-current={l.id === active ? "page" : undefined}
            >
              {l.label}
            </a>
          ))}
          <a
            href="diagnostic.html"
            className={"psl-nav-cta" + (active === "diagnostic" ? " is-active" : "")}
            aria-current={active === "diagnostic" ? "page" : undefined}
          >
            Diagnostic
          </a>
        </div>

        <button
          type="button"
          className="psl-nav-toggle"
          aria-label={open ? "Close menu" : "Open menu"}
          aria-expanded={open}
          onClick={() => setOpen((o) => !o)}
        >
          <span></span>
          <span></span>
          <span></span>
        </button>

        <div className="psl-nav-mobile">
          {PSL_NAV_LINKS.map((l) => (
            <a
              key={l.id}
              href={l.href}
              className={l.id === active ? "is-active" : ""}
              onClick={() => setOpen(false)}
            >
              {l.label}
            </a>
          ))}
          <a
            href="diagnostic.html"
            className="psl-nav-cta"
            onClick={() => setOpen(false)}
          >
            Diagnostic
          </a>
        </div>
      </div>
    </nav>
    </React.Fragment>
  );
};

Object.assign(window, { PSLNav });
