/* Motion · site navigation with mega dropdowns.
   Sticky header. Two mega-dropdowns:
     · "Funkcje" — every feature grouped by module (4-column grid)
     · "Cennik" / "Wsparcie" — flat single-column dropdowns
   Plus standard nav links, primary CTA, and a mobile drawer.

   Highlights an item if its slug matches `activeFeature` prop. */

const { useState: useNavState, useEffect: useNavEffect, useRef: useNavRef } = React;

/* Click-outside / Escape close helper. */
function useDismiss(ref, onClose) {
  useNavEffect(() => {
    const onDocClick = (e) => {
      if (ref.current && !ref.current.contains(e.target)) onClose();
    };
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("mousedown", onDocClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDocClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [ref, onClose]);
}

/* Clamp a dropdown into the viewport horizontally: if the natural left:0
   positioning makes it spill off the right edge, shift it left by the
   overflow. Re-runs on resize. */
function useViewportClamp(ref) {
  useNavEffect(() => {
    const el = ref.current;
    if (!el) return;
    const adjust = () => {
      el.style.left = "0";
      const r = el.getBoundingClientRect();
      const margin = 12;
      if (r.right > window.innerWidth - margin) {
        const shift = r.right - (window.innerWidth - margin);
        el.style.left = `-${Math.round(shift)}px`;
      } else if (r.left < margin) {
        el.style.left = `${Math.round(margin - r.left)}px`;
      }
    };
    adjust();
    window.addEventListener("resize", adjust);
    return () => window.removeEventListener("resize", adjust);
  }, [ref]);
}

function MegaTrigger({ label, isOpen, onClick }) {
  return (
    <button
      className={`mpos-nav-trigger${isOpen ? " is-open" : ""}`}
      aria-expanded={isOpen}
      onClick={onClick}
    >
      {label}
      <Icon name="chevronDown" size={14} />
    </button>
  );
}

function FunkcjeMega({ activeFeature, onClose }) {
  const ref = useNavRef(null);
  useViewportClamp(ref);
  return (
    <div ref={ref} className="mpos-mega is-open" role="menu">
      <div className="mpos-mega-grid">
        {FEATURES_BY_MODULE.map((mod) => (
          <div key={mod.id}>
            <p className="mpos-mega-col-title">{mod.name}</p>
            {mod.features.map((f) => (
              <a
                key={f.slug}
                href={featureHref(f.slug)}
                className="mpos-mega-link"
                style={activeFeature === f.slug ? { background: "var(--brand-50)" } : null}
                onClick={onClose}
              >
                <span className="mpos-mega-link-icon">
                  <Icon name={f.icon} size={14} />
                </span>
                <span className="mpos-mega-link-body">
                  <span className="mpos-mega-link-name">
                    {f.name}
                    {!f.built && <span className="mpos-mega-link-soon">wkrótce</span>}
                  </span>
                  <span className="mpos-mega-link-desc">{f.desc}</span>
                </span>
              </a>
            ))}
          </div>
        ))}
      </div>
      <div className="mpos-mega-foot">
        <p className="mpos-mega-foot-text">
          Nie wiesz, od czego zacząć? Pokażemy Ci tylko te funkcje, których naprawdę potrzebujesz.
        </p>
        <a href={url("kontakt.html")} className="mpos-mega-foot-link">
          Umów prezentację <Icon name="arrowRight" size={14} />
        </a>
      </div>
    </div>
  );
}

function ModulyMega({ onClose }) {
  const ref = useNavRef(null);
  useViewportClamp(ref);
  return (
    <div ref={ref} className="mpos-mega mpos-mega-narrow is-open" role="menu">
      <div className="mpos-mega-grid mpos-mega-cols-1">
        {MODULES.map((m) => (
          <a key={m.id} href={m.href} className="mpos-mega-link" onClick={onClose}>
            <span className="mpos-mega-link-icon">
              <Icon name={m.icon} size={14} />
            </span>
            <span className="mpos-mega-link-body">
              <span className="mpos-mega-link-name">{m.name}</span>
              <span className="mpos-mega-link-desc">{m.desc}</span>
            </span>
          </a>
        ))}
      </div>
    </div>
  );
}

function MobilePanel({ open, onClose, activeFeature }) {
  if (!open) return null;
  return (
    <div className={`mpos-mobile-panel${open ? " is-open" : ""}`}>
      <Container>
        {FEATURES_BY_MODULE.map((mod) => (
          <div className="mpos-mobile-section" key={mod.id}>
            <h4>{mod.name}</h4>
            {mod.features.map((f) => (
              <a
                key={f.slug}
                href={featureHref(f.slug)}
                onClick={onClose}
                style={activeFeature === f.slug ? { color: "var(--brand-600)", fontWeight: 600 } : null}
              >
                {f.name}{!f.built ? " · wkrótce" : ""}
              </a>
            ))}
          </div>
        ))}
        <div className="mpos-mobile-section">
          <a href={url("cennik.html")} onClick={onClose}>Cennik</a>
          <a href={url("wsparcie.html")} onClick={onClose}>Wsparcie</a>
          <a href={url("kontakt.html")} onClick={onClose}>Kontakt</a>
        </div>
        <div style={{ paddingTop: 16 }}>
          <Button variant="primary" size="md" href={url("kontakt.html")} as="a" style={{ width: "100%" }}>
            Bezpłatna prezentacja
          </Button>
        </div>
      </Container>
    </div>
  );
}

function Header({ activeFeature }) {
  const [openMenu, setOpenMenu] = useNavState(null); // 'moduly' | 'funkcje' | null
  const [scrolled, setScrolled] = useNavState(false);
  const [mobileOpen, setMobileOpen] = useNavState(false);
  const wrapRef = useNavRef(null);

  useNavEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 4);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useDismiss(wrapRef, () => setOpenMenu(null));

  const toggle = (k) => setOpenMenu((cur) => (cur === k ? null : k));
  const close = () => setOpenMenu(null);

  return (
    <header className={`mpos-header${scrolled ? " is-scrolled" : ""}`}>
      <Container>
        <nav className="mpos-nav" ref={wrapRef}>
          <div className="mpos-nav-left">
            <a href={url("index.html")} aria-label="Motion — strona główna" className="mpos-logo-link">
              <LogoMark size={30} />
              <span className="mpos-logo-word">Motion</span>
            </a>
            <div className="mpos-nav-links">
              <div className="mpos-mega-wrap">
                <MegaTrigger label="Moduły" isOpen={openMenu === "moduly"} onClick={() => toggle("moduly")} />
                {openMenu === "moduly" && <ModulyMega onClose={close} />}
              </div>
              <div className="mpos-mega-wrap">
                <MegaTrigger label="Funkcje" isOpen={openMenu === "funkcje"} onClick={() => toggle("funkcje")} />
                {openMenu === "funkcje" && <FunkcjeMega activeFeature={activeFeature} onClose={close} />}
              </div>
              <a className="mpos-nav-link" href={url("cennik.html")}>Cennik</a>
              <a className="mpos-nav-link" href={url("wsparcie.html")}>Wsparcie</a>
              <a className="mpos-nav-link" href={url("kontakt.html")}>Kontakt</a>
            </div>
          </div>
          <div className="mpos-nav-right">
            <Button variant="primary" size="sm" as="a" href={url("kontakt.html")}>
              Bezpłatna prezentacja
            </Button>
            <button
              className="mpos-mobile-btn"
              aria-label="Otwórz menu"
              onClick={() => setMobileOpen((v) => !v)}
            >
              <Icon name={mobileOpen ? "x" : "menu"} size={20} />
            </button>
          </div>
        </nav>
      </Container>
      <MobilePanel open={mobileOpen} onClose={() => setMobileOpen(false)} activeFeature={activeFeature} />
    </header>
  );
}

Object.assign(window, { Header });
