// Good Sam two-row navigation
// Row 1 (static): master wordmark + primary mega-menu items + phone + account
// Row 2 (BU-specific): BU mark badge + BU wordmark + secondary links + actions
//
// Hover on any primary item opens its mega-menu. Animation: 180ms fade + 6px Y translate.
// Cross-fading between adjacent menus uses a shared panel so it feels continuous.

const { useState, useRef, useEffect, useCallback } = React;

const ASSET = (file) => `assets/${file}`;

// ---------- helpers ----------
function useDelayedClose(delay = 120) {
  const t = useRef(null);
  const cancel = () => { if (t.current) { clearTimeout(t.current); t.current = null; } };
  const schedule = (fn) => { cancel(); t.current = setTimeout(fn, delay); };
  useEffect(() => cancel, []);
  return { schedule, cancel };
}

// ---------- mega menu panel ----------
function MegaPanel({ item, onMouseEnter, onMouseLeave }) {
  const colCount = item.columns.length;
  return (
    <div
      className="gs-mega"
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
      role="menu"
    >
      <div className="gs-mega-inner">
        <div className={"gs-mega-cols gs-mega-cols--" + colCount}>
          {item.columns.map((col, i) => (
            <div key={i} className="gs-mega-col">
              <div className="gs-mega-eyebrow">{col.title}</div>
              <ul>
                {col.links.map((l, j) => (
                  <li key={j}>
                    <a href={l.href} className="gs-mega-link">
                      {l.logo ? <img className="gs-mega-link-logo" src={ASSET(l.logo)} alt="" /> : null}
                      <span className="gs-mega-link-label">{l.label}</span>
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
          {item.feature ? (
            <div className="gs-mega-feature">
              <div className="gs-mega-feature-eyebrow">{item.feature.eyebrow}</div>
              <div className="gs-mega-feature-title">{item.feature.title}</div>
              <div className="gs-mega-feature-body">{item.feature.body}</div>
              <a href="#" className="gs-mega-feature-cta">
                {item.feature.cta}
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14" /><path d="m12 5 7 7-7 7" /></svg>
              </a>
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );
}

// ---------- secondary BU row ----------
function BURow({ bu, buKey }) {
  // Re-mount the inner row on BU change so links fade in cleanly.
  return (
    <div className="gs-bu-row">
      <div className="gs-bu-inner" key={buKey}>
        <div className="gs-bu-brand">
          {bu.home ? (
            <a href={bu.home} className="gs-bu-brand-link" aria-label={bu.name + " home"}>
              <img className="gs-bu-wordmark" src={ASSET(bu.logo)} alt={bu.name} />
            </a>
          ) : (
            <img className="gs-bu-wordmark" src={ASSET(bu.logo)} alt={bu.name} />
          )}
        </div>
        <nav className="gs-bu-links" aria-label={bu.name + " navigation"}>
          {bu.links.map((l, i) => (
            <a key={i} href={l.href} className="gs-bu-link">{l.label}</a>
          ))}
        </nav>
        <div className="gs-bu-actions">
          {bu.actions.map((a, i) => (
            <a key={i} href={a.href} className={"gs-bu-action" + (a.primary ? " is-primary" : "")}>
              {a.label}
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}

// ---------- mobile drawer ----------
function buildMobileNav(activeBU) {
  // Convert PRIMARY_NAV mega menus into a mobile push-pop tree.
  // Each primary item -> a submenu of "column heads as sections" flattened to a list.
  const items = window.PRIMARY_NAV.map((p) => {
    const flat = [];
    p.columns.forEach((col) => {
      col.links.forEach((l) => {
        flat.push({ label: l.label, href: l.href, has_children: false, icon: l.logo ? ASSET(l.logo) : null });
      });
    });
    if (p.feature) {
      flat.push({ label: p.feature.cta, href: "#", has_children: false, kind: "action" });
    }
    return {
      label: p.label,
      has_children: true,
      submenu: { title: p.label, items: flat },
    };
  });
  // Append BU quick-actions at the top level
  const bu = window.BU_NAVS[activeBU] || window.BU_NAVS.cc;
  items.push({
    label: bu.name,
    has_children: true,
    submenu: {
      title: bu.name,
      homeHref: bu.home,
      items: [
        ...bu.links.map((l) => ({ label: l.label, href: l.href, has_children: false })),
        ...bu.actions.map((a) => ({ label: a.label, href: a.href, has_children: false, kind: "action" })),
      ],
    },
  });
  return { title: "main menu", items };
}

function MobileDrawer({ open, onClose, activeBU }) {
  const [stack, setStack] = useState([]); // array of submenu nodes
  const NAV = React.useMemo(() => buildMobileNav(activeBU), [activeBU]);

  useEffect(() => {
    if (!open) {
      // delay clearing stack until slide-out completes
      const t = setTimeout(() => setStack([]), 220);
      return () => clearTimeout(t);
    }
    // When opening on a BU detail page, jump straight into that BU's submenu
    const buItem = NAV.items.find((it) => it.has_children && it.label === (window.BU_NAVS[activeBU]?.name));
    if (buItem) setStack([buItem.submenu]);
  }, [open, activeBU, NAV]);

  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") {
        if (stack.length > 0) setStack((s) => s.slice(0, -1));
        else onClose();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, stack.length, onClose]);

  const push = (node) => setStack((s) => [...s, node]);
  const pop = () => setStack((s) => s.slice(0, -1));

  const renderRow = (item, idx) => {
    const cls = ["ms-row"];
    if (item.kind === "action") cls.push("ms-row--action");
    else if (!item.has_children) cls.push("ms-row--leaf");
    if (item.has_children) {
      return (
        <button key={idx} className={cls.join(" ")} onClick={() => push(item.submenu)}>
          <span className="ms-row__label">{item.label}</span>
          <svg className="ms-row__chev" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6" /></svg>
        </button>
      );
    }
    const href = item.href || "#";
    return (
      <a key={idx} className={cls.join(" ")} href={href} onClick={onClose}>
        <span className="ms-row__label">{item.label}</span>
      </a>
    );
  };

  const views = [
    { title: NAV.title, items: NAV.items, isRoot: true },
    ...stack.map((n) => ({ ...n, isRoot: false })),
  ];

  return (
    <div className={"ms-root" + (open ? " is-open" : "")}>
      <div className="ms-scrim" onClick={onClose} />
      <div className="ms-drawer" role="dialog" aria-modal="true" aria-label="Main menu">
        <div className="ms-stack">
          {views.map((v, i) => {
            const isActive = i === views.length - 1;
            const isBehind = i < views.length - 1;
            const cls = ["ms-view"];
            if (isActive) cls.push("is-active");
            if (isBehind) cls.push("is-behind");
            const parentTitle = i > 0 ? views[i - 1].title : null;
            return (
              <section key={i} className={cls.join(" ")}>
                {!v.isRoot && (
                  <div className="ms-titlebar">
                    <button className="ms-titlebar__back" onClick={pop}>
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6" /></svg>
                      Back to {parentTitle}
                    </button>
                    {v.homeHref ? (
                      <a className="ms-titlebar__home" href={v.homeHref}>{v.title}</a>
                    ) : (
                      <h2 className="ms-titlebar__title is-static">{v.title}</h2>
                    )}
                  </div>
                )}
                <div className="ms-view__body">
                  <ul className="ms-list">
                    {(v.items || []).map((item, idx) => (
                      <li key={idx}>{renderRow(item, idx)}</li>
                    ))}
                  </ul>
                </div>
              </section>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function MobileHeader({ open, setOpen, activeBU }) {
  return (
    <header className="ms-header" role="banner">
      <a className="ms-header__logo" href="#" aria-label="Good Sam home">
        <img src={ASSET("bu-good-sam.svg")} alt="Good Sam" />
      </a>
      {!open && (
        <div className="ms-utility">
          <a className="ms-header__btn" href="tel:8662057451" aria-label="Call us">
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92Z" /></svg>
          </a>
          <button className="ms-header__btn" aria-label="My account">
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" /><circle cx="12" cy="7" r="4" /></svg>
          </button>
        </div>
      )}
      <button
        className="ms-header__btn"
        aria-label={open ? "Close menu" : "Open menu"}
        aria-expanded={open}
        onClick={() => setOpen(!open)}
      >
        {open ? (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="6" y1="6" x2="18" y2="18" /><line x1="6" y1="18" x2="18" y2="6" /></svg>
        ) : (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="3" y1="6" x2="21" y2="6" /><line x1="3" y1="12" x2="21" y2="12" /><line x1="3" y1="18" x2="21" y2="18" /></svg>
        )}
      </button>
    </header>
  );
}

// ---------- header ----------
function useIsMobile(breakpoint = 880) {
  const [m, setM] = useState(typeof window !== "undefined" ? window.innerWidth <= breakpoint : false);
  useEffect(() => {
    const onR = () => setM(window.innerWidth <= breakpoint);
    window.addEventListener("resize", onR);
    return () => window.removeEventListener("resize", onR);
  }, [breakpoint]);
  return m;
}

function GoodSamHeader({ activeBU = "cc" }) {
  const [open, setOpen] = useState(null); // active primary item id
  const closer = useDelayedClose(140);
  const isMobile = useIsMobile(880);
  const [drawerOpen, setDrawerOpen] = useState(false);
  useEffect(() => { if (!isMobile) setDrawerOpen(false); }, [isMobile]);

  const onItemEnter = (id) => {
    closer.cancel();
    setOpen(id);
  };
  const onItemLeave = () => {
    closer.schedule(() => setOpen(null));
  };

  const onBlurAll = useCallback(() => setOpen(null), []);
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onBlurAll(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onBlurAll]);

  const activeItem = window.PRIMARY_NAV.find((i) => i.id === open);
  const bu = window.BU_NAVS[activeBU] || window.BU_NAVS.cc;

  if (isMobile) {
    return (
      <header className="gs-header gs-header--mobile">
        <MobileHeader open={drawerOpen} setOpen={setDrawerOpen} activeBU={activeBU} />
        <MobileDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)} activeBU={activeBU} />
      </header>
    );
  }

  return (
    <header className="gs-header">
      <div className="gs-row gs-row-primary">
        <div className="gs-row-inner">
          <a href="#" className="gs-master" aria-label="Good Sam home">
            <img src={ASSET("bu-good-sam.svg")} alt="Good Sam" />
          </a>
          <nav className="gs-primary" aria-label="Primary">
            {window.PRIMARY_NAV.map((item) => (
              <div
                key={item.id}
                className={"gs-primary-item" + (open === item.id ? " is-open" : "")}
                onMouseEnter={() => onItemEnter(item.id)}
                onMouseLeave={onItemLeave}
                onFocus={() => onItemEnter(item.id)}
              >
                <button className="gs-primary-trigger" aria-expanded={open === item.id} aria-haspopup="true">
                  {item.label}
                  <svg className="gs-caret" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                    <path d="m6 9 6 6 6-6" />
                  </svg>
                </button>
              </div>
            ))}
          </nav>
          <div className="gs-row-end">
            <a href="tel:8662057451" className="gs-phone">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.86 19.86 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.86 19.86 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z" /></svg>
              866-205-7451
            </a>
            <button className="gs-account" aria-label="Account">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10" /><circle cx="12" cy="10" r="3.2" /><path d="M5.5 19.5a8 8 0 0 1 13 0" /></svg>
            </button>
          </div>
        </div>
        {/* mega menu sits inside primary row so border-bottom stacks correctly */}
        <div
          className={"gs-mega-stage" + (activeItem ? " is-open" : "")}
          aria-hidden={!activeItem}
        >
          {activeItem ? (
            <MegaPanel
              item={activeItem}
              onMouseEnter={closer.cancel}
              onMouseLeave={onItemLeave}
            />
          ) : null}
        </div>
      </div>

      <BURow bu={bu} buKey={activeBU} />
    </header>
  );
}

window.GoodSamHeader = GoodSamHeader;
