/* Site header for every Kgotla page: the drawn 88px desktop row, plus the
   hamburger, slide-in drawer and scroll-away compact bar that take over below
   1024px. One component so all five page types share one behaviour.
   Loaded before chrome.jsx / parts-hero.jsx, so it keeps its own constants. */

const NAVBRAND = "assets/brand/";
const NAV_LINKS = [
  { label: "Services", href: "Kgotla Services.html" },
  { label: "Impact", href: "Kgotla Coming Soon.html" },
  { label: "Books", href: "Kgotla Books.html" },
  { label: "Insights", href: "Kgotla Coming Soon.html" },
  { label: "About us", href: "Kgotla About.html" },
  { label: "Contact", href: "Kgotla Contact.html" },
];
/* Which nav item is the page we are on — Books also covers the 8 book pages,
   Services covers the boats pages reached from its Locations cards. */
const NAV_FAMILY = { "Kgotla Services.html": ["Kgotla Services.html", "Kgotla Boats.html", "Kgotla Boat - "], "Kgotla Books.html": ["Kgotla Books.html", "Kgotla Book - "] };
function currentPage() {
  try { return decodeURIComponent(location.pathname.split("/").pop() || ""); } catch (e) { return ""; }
}
function isActive(href) {
  const here = currentPage();
  if (!here) return false;
  const family = NAV_FAMILY[href] || [href];
  return family.some((p) => (p.endsWith(" - ") ? here.startsWith(p) : here === p));
}
const NAV_GRADIENT = "linear-gradient(160deg, #0051FF 4%, #009780 96%)";
const NAV_INK = "#0F172B";
const NAV_EASE = "cubic-bezier(.4,0,.2,1)";
const navFont = "var(--font-body)";
const { LogoWhite: NavLogoWhite, LogoColor: NavLogoColor, ButtonPrimaryDark: NavBtnDark, ButtonPrimaryLight: NavBtnLight, ButtonSecondaryDark: NavBtnSecDark } = window.KgotlaDesignSystem_4cd0b1;

function MenuDrawer({ open, onClose, cta, ctaHref }) {
  const [shown, setShown] = React.useState(false);
  const panelRef = React.useRef(null);
  React.useEffect(() => {
    if (!open) { setShown(false); return; }
    const t = setTimeout(() => setShown(true), 20);
    const prevHtml = document.documentElement.style.overflow;
    const prev = document.body.style.overflow;
    document.documentElement.style.overflow = "hidden";
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    const first = panelRef.current && panelRef.current.querySelector("a,button");
    if (first) first.focus({ preventScroll: true });
    return () => { clearTimeout(t); document.documentElement.style.overflow = prevHtml; document.body.style.overflow = prev; window.removeEventListener("keydown", onKey); };
  }, [open, onClose]);
  if (!open) return null;
  const reduced = !!window.REDUCED;
  return ReactDOM.createPortal(
    <div role="dialog" aria-modal="true" aria-label="Menu" style={{ position: "fixed", inset: 0, zIndex: 95, display: "flex", justifyContent: "flex-end" }}>
      <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "rgba(6,10,20,0.55)", backdropFilter: "blur(2px)", opacity: shown ? 1 : 0, transition: reduced ? "none" : `opacity 300ms ${NAV_EASE}` }} />
      <div ref={panelRef} style={{ position: "relative", width: "min(430px, 100%)", height: "100%", boxSizing: "border-box", background: NAV_GRADIENT, padding: "16px var(--kg-pad) 32px", display: "flex", flexDirection: "column", gap: 28, overflowY: "auto", WebkitOverflowScrolling: "touch", boxShadow: "-24px 0 60px rgba(6,10,20,.28)", transform: shown || reduced ? "none" : "translateX(102%)", transition: reduced ? "none" : `transform 360ms ${NAV_EASE}` }}>
        <div style={{ height: 56, display: "flex", alignItems: "center", justifyContent: "space-between", flexShrink: 0 }}>
          <a href="Kgotla Homepage.html" style={{ display: "block" }}><NavLogoWhite height={38} basePath={NAVBRAND} /></a>
          <button type="button" onClick={onClose} aria-label="Close menu" style={{ width: 44, height: 44, marginRight: -8, appearance: "none", border: "none", background: "none", padding: 0, cursor: "pointer", color: "#FFFFFF", display: "flex", alignItems: "center", justifyContent: "flex-end" }}>
            <svg width="20" height="20" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M2 2 L14 14 M14 2 L2 14" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" /></svg>
          </button>
        </div>
        <nav style={{ display: "flex", flexDirection: "column" }}>
          {NAV_LINKS.map((n, i) => (
            <a key={n.label} className="kg-drawerlink" href={n.href} aria-current={isActive(n.href) ? "page" : undefined} style={{ opacity: shown || reduced ? 1 : 0, transform: shown || reduced ? "none" : "translateY(10px)", transition: reduced ? "none" : `opacity 320ms ${NAV_EASE} ${80 + i * 40}ms, transform 320ms ${NAV_EASE} ${80 + i * 40}ms, padding-left 220ms ${NAV_EASE}` }}>{n.label}</a>
          ))}
        </nav>
        <div style={{ marginTop: "auto", display: "flex", flexDirection: "column", gap: 26 }}>
          <NavBtnSecDark as="a" href={ctaHref} style={{ width: "100%", height: 52 }}>{cta}</NavBtnSecDark>
          <div style={{ display: "flex", flexDirection: "column", gap: 6, fontFamily: navFont, fontSize: 14, lineHeight: "22px", color: "rgba(255,255,255,0.86)" }}>
            <a href={(window.KGLINKS || {}).email || "mailto:martijn@kgotla.com"} style={{ color: "#FFFFFF" }}>martijn@kgotla.com</a>
            <a href={(window.KGLINKS || {}).phone || "tel:+85269178389"} style={{ color: "rgba(255,255,255,0.86)" }}>+852 69178389</a>
          </div>
        </div>
      </div>
    </div>, document.body);
}

/* Compact bar that arrives once the page has scrolled and steps out of the way
   while the reader is moving down. Phones and tablets only. */
function StickyBar({ onOpen }) {
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    let last = window.scrollY, raf = 0;
    const paint = () => {
      raf = 0;
      const y = window.scrollY;
      if (y < 260) setVisible(false);
      else if (y < last - 4) setVisible(true);
      else if (y > last + 8) setVisible(false);
      last = y;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(paint); };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => { window.removeEventListener("scroll", onScroll); if (raf) cancelAnimationFrame(raf); };
  }, []);
  return ReactDOM.createPortal(
    <div className="kg-stickybar" aria-hidden={!visible} style={{ position: "fixed", top: 0, left: 0, right: 0, zIndex: 70, height: 62, boxSizing: "border-box", padding: "0 var(--kg-pad)", background: "rgba(255,255,255,0.94)", backdropFilter: "blur(12px)", borderBottom: "1px solid rgba(15,23,43,0.09)", display: "flex", alignItems: "center", justifyContent: "space-between", transform: visible ? "none" : "translateY(-102%)", transition: window.REDUCED ? "none" : `transform 320ms ${NAV_EASE}`, pointerEvents: visible ? "auto" : "none" }}>
      <a href="Kgotla Homepage.html" style={{ display: "block" }}><NavLogoColor height={32} basePath={NAVBRAND} /></a>
      <button type="button" className="kg-burger" onClick={onOpen} aria-label="Open menu" tabIndex={visible ? 0 : -1} style={{ color: NAV_INK }}><span /><span /></button>
    </div>, document.body);
}

/* Reading progress — a hairline at the very top on phones and tablets. */
function ScrollProgress() {
  const ref = React.useRef(null);
  React.useEffect(() => {
    let raf = 0;
    const paint = () => {
      raf = 0;
      const h = document.documentElement.scrollHeight - window.innerHeight;
      const p = h > 40 ? Math.max(0, Math.min(1, window.scrollY / h)) : 0;
      if (ref.current) ref.current.style.transform = `scaleX(${p.toFixed(4)})`;
    };
    const on = () => { if (!raf) raf = requestAnimationFrame(paint); };
    paint();
    window.addEventListener("scroll", on, { passive: true });
    window.addEventListener("resize", on);
    const t = setInterval(paint, 900);
    return () => { clearInterval(t); window.removeEventListener("scroll", on); window.removeEventListener("resize", on); if (raf) cancelAnimationFrame(raf); };
  }, []);
  return ReactDOM.createPortal(<div className="kg-progress" aria-hidden="true"><i ref={ref} /></div>, document.body);
}

/* tone="dark" over photography and gradient, "light" on white pages. */
function SiteHeader({ tone = "dark", cta = "Get started", ctaHref, style }) {
  const [open, setOpen] = React.useState(false);
  const narrow = window.useNarrow ? window.useNarrow() : false;
  const dark = tone === "dark";
  const Logo = dark ? NavLogoWhite : NavLogoColor;
  const Cta = dark ? NavBtnDark : NavBtnLight;
  const href = ctaHref || (window.KGLINKS || {}).contact || "Kgotla Contact.html";
  const close = React.useCallback(() => setOpen(false), []);
  return (
    <header className="kg-header" style={{ height: 88, boxSizing: "border-box", padding: "24px 0", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 24, ...style }}>
      <a href="Kgotla Homepage.html" aria-label="Kgotla — home" style={{ display: "block", flexShrink: 0 }}><Logo height={46.38} basePath={NAVBRAND} /></a>
      <nav className="kg-navlinks" aria-label="Main" style={{ display: "flex", gap: 40, alignItems: "flex-start" }}>
        {NAV_LINKS.map((n) => {
          const on = isActive(n.href);
          return (
            <a key={n.label} className={(dark ? "kg-navlink" : "kg-inklink") + (on ? " kg-navlink-on" : "")} href={n.href} aria-current={on ? "page" : undefined} style={{ fontFamily: navFont, fontWeight: 500, fontSize: 14, lineHeight: "20px", color: dark ? "#FFFFFF" : NAV_INK, whiteSpace: "nowrap" }}>{n.label}</a>
          );
        })}
      </nav>
      <div className="kg-navcta" style={{ flexShrink: 0 }}><Cta as="a" href={href} style={{ height: 48, padding: "0 28px" }}>{cta}</Cta></div>
      <button type="button" className="kg-burger" onClick={() => setOpen(true)} aria-label="Open menu" aria-expanded={open} style={{ color: dark ? "#FFFFFF" : NAV_INK }}><span /><span /></button>
      {narrow && <StickyBar onOpen={() => setOpen(true)} />}
      {narrow && <ScrollProgress />}
      <MenuDrawer open={open} onClose={close} cta={cta} ctaHref={href} />
    </header>
  );
}

Object.assign(window, { SiteHeader, MenuDrawer, NAV_LINKS, isActive });
