// Top nav + footer — strict monochrome, brand-typography.

// Main nav order: Products, Services, Sectors, Regions, Company, Partners, Sponsors
// "More" overflow: Contact, Careers, Sustainability
const MAIN_NAV = [
  ["product",        "Products"],
  ["builder",        "Build a Tower"],
  ["services",       "Services"],
  ["sector",         "Sectors"],
  ["about",          "Company"],
  ["partners",       "Partners"],
  ["sponsors",       "Our Sponsorships"],
];
const MORE_NAV = [
  ["contact",        "Contact"],
  ["careers",        "Careers"],
  ["sustainability", "Sustainability"],
];

/*
 * Mega-menu config builder.
 * Returns the dropdown spec for each nav id, or null if no dropdown
 * (in which case the link just navigates directly).
 *
 * Each spec: {
 *   headerLabel, headerTarget, headerSubtitle,
 *   items: [ { code, name, body, page, params?, muted? } ]
 * }
 * - `page` is the page id to navigate to when row is clicked
 * - `params` is the optional second arg passed to onNavigate (e.g. productId)
 */
function getMegaMenuConfig(id) {
  const data = window.SOLO_DATA || {};
  switch (id) {
    case "product":
      return {
        headerLabel: "All products",
        headerSubtitle: "The platform",
        headerTarget: "product",
        items: (data.products || []).map(p => ({
          code: p.callsign,
          name: p.name,
          body: p.tagline,
          page: "product-detail",
          params: p.id,
          muted: p.isLegacy,
          comingSoon: p.comingSoon,
        })),
      };

    case "services":
      return {
        headerLabel: "All services",
        headerSubtitle: "More than hardware",
        headerTarget: "services",
        items: [
          { name: "Contract Manufacturing",   body: "OEM and ODM options for security product design.",                                page: "service-detail", params: { serviceId: "contract-manufacturing" } },
          { name: "Product Design",           body: "You think it, we design it. Full turnkey design service.",                         page: "service-detail", params: { serviceId: "product-design" } },
          { name: "Data Services (SIMs)",     body: "Data and SIM services at source — multi-carrier, private APN, managed.",          page: "service-detail", params: { serviceId: "data-services" } },
          { name: "Network & Infrastructure", body: "All devices, one secure network. Private, mesh, P2P, Starlink, WAN.",            page: "service-detail", params: { serviceId: "network-infrastructure" } },
          { name: "Asset Management",         body: "All devices, one location. Integrations into Ajax, Victron, CRM.",                page: "service-detail", params: { serviceId: "asset-management" } },
          { name: "Transport & Logistics",    body: "You order, we deliver. Own UK + EU transport operation.",                         page: "service-detail", params: { serviceId: "transport-logistics" } },
        ],
      };

    case "sector":
      return {
        headerLabel: "All sectors",
        headerSubtitle: "Where Solo works",
        headerTarget: "sector",
        items: (data.sectors || []).map(s => ({
          code: s.code,
          name: s.name,
          body: s.summary,
          page: "sector",
          params: s.id,
        })),
      };

    case "regions":
      return {
        headerLabel: "All regions",
        headerSubtitle: "Where we operate",
        headerTarget: "regions",
        items: [
          { code: "F-01", name: "United Kingdom",  body: "Bedfordshire · HQ + Factory",        page: "regions" },
          { code: "F-02", name: "Poland",          body: "Wrocław · Factory",                  page: "regions" },
          { code: "F-03", name: "North America",   body: "Wellington, Florida · Factory",      page: "regions" },
          { code: "P-04", name: "European Union",  body: "Partner network",                    page: "regions" },
          { code: "P-05", name: "North America",   body: "Partner network",                    page: "regions" },
        ],
      };

    case "partners":
      return {
        headerLabel: "Partner programme",
        headerSubtitle: "The partner channel",
        headerTarget: "partners",
        // Featured item — rendered with extra emphasis at the top of the panel.
        // Exclusive Regions is the headline because UK + EU operate under a
        // single-customer exclusivity arrangement that distinguishes Solo from
        // standard distribution programmes.
        featuredItem: {
          name: "Exclusive Regions — UK · EU · Switzerland",
          body: "Solo's UK and European regions are held under single-customer regional exclusivity — a programme distinct from the open partner tiers.",
          page: "exclusive-regions",
        },
        // Two-column grouped layout — see MegaMenu rendering branch.
        groups: [
          {
            label: "North American Partners",
            items: [
              { name: "Gold Partners",     body: "Authorised Solo partners across North America.", page: "gold-partners" },
              { name: "Platinum Partners", body: "Top-tier Solo partners across the North American region.", page: "platinum-partners" },
            ],
          },
          {
            label: "Regional coverage",
            items: [
              { name: "All partner regions", body: "UK, EU and North America — including Solo facilities and partner depots.", page: "regions" },
            ],
          },
        ],
        // Footer call-to-action inside the panel
        footerItem: { name: "Become a partner", body: "Apply to the Solo partner programme.", page: "contact" },
      };

    case "sponsors":
      return {
        headerLabel: "All sponsorships",
        headerSubtitle: "Who we back",
        headerTarget: "sponsors",
        items: [
          { code: "S-01", name: "Archie Davies", body: "GB4 Championship driver · Scorpio Motorsport. Backed by Solo since 2024.", page: "sponsor-archie" },
          { code: "S-02", name: "Tommy Lovejoy", body: "8-year-old British karting driver · 2026 Wera Tools British Kart Championship.",  page: "sponsor-tommy" },
        ],
      };

    case "about":
      return {
        headerLabel: "Company overview",
        headerSubtitle: "About Solo",
        headerTarget: "about",
        items: [
          { code: "01", name: "Our Story",         body: "Solo from 2019 to today — built in Britain, exported worldwide.",                page: "our-story"    },
          { code: "02", name: "Meet The Team",     body: "The team running Solo — engineering, commercial, operations.",                   page: "leadership"   },
          { code: "03", name: "Manufacturing",     body: "Bedfordshire, Wrocław and Wellington — three factories, one operating standard.", page: "manufacturing" },
          { code: "04", name: "Press & Media",     body: "Press releases, media kit, brand assets and recent coverage.",                   page: "press"        },
          { code: "05", name: "Investors",         body: "Information for current and prospective Solo investors.",                        page: "investors"    },
          { code: "06", name: "ESG & Compliance",  body: "Modern Slavery, Anti-bribery, environmental and governance statements.",         page: "esg"          },
        ],
      };

    default:
      return null;
  }
}

// Page IDs that should mark a main-nav item as active when the user is on
// a sub-route (e.g. product-detail belongs under the Products nav item).
const NAV_ID_ALIASES = {
  product:  ["product-detail"],
  about:    ["our-story", "leadership", "manufacturing", "press", "investors", "esg"],
  // Regions sits under Partners because the regions ARE partner-agreement
  // territories (with UK + EU specifically under single-customer exclusivity).
  partners: ["exclusive-regions", "gold-partners", "platinum-partners", "regions"],
  sponsors: ["sponsor-archie", "sponsor-tommy"],
};

function TopNav({ page, onNavigate }) {
  // Mobile menu state — full-screen slide-in for phones/tablets
  const [mobileOpen, setMobileOpen] = useState(false);

  // Close mobile menu whenever navigation happens
  const wrapNav = (target, arg) => {
    setMobileOpen(false);
    onNavigate(target, arg);
  };

  // Lock body scroll while mobile menu is open
  useEffect(() => {
    if (mobileOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [mobileOpen]);

  // Single "currently-open" identifier — only one dropdown at a time.
  const [openId, setOpenId] = useState(null);
  const navRootRef = useRef(null);
  // Tiny close delay lets the cursor cross the gap between trigger and panel
  const closeTimerRef = useRef(null);

  // Outside-click close — closes any dropdown if click falls outside the nav root
  useEffect(() => {
    if (!openId) return;
    const handler = (e) => {
      if (navRootRef.current && !navRootRef.current.contains(e.target)) setOpenId(null);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [openId]);

  const open = (id) => {
    if (closeTimerRef.current) clearTimeout(closeTimerRef.current);
    setOpenId(id);
  };
  const scheduleClose = () => {
    if (closeTimerRef.current) clearTimeout(closeTimerRef.current);
    closeTimerRef.current = setTimeout(() => setOpenId(null), 140);
  };
  const toggle = (id) => setOpenId((cur) => (cur === id ? null : id));

  // Whether a given main-nav id should be marked as the active page
  const isActive = (id) => {
    if (page === id) return true;
    const aliases = NAV_ID_ALIASES[id];
    if (aliases && aliases.includes(page)) return true;
    return false;
  };

  // Highlight "More" when current page is one of its children
  const moreActive = MORE_NAV.some(([id]) => id === page);

  return (
    <>
    <header style={{
      position: "sticky", top: 0, zIndex: 60,
      background: "var(--nav-bg)",
      borderBottom: "1px solid var(--line)",
      backdropFilter: "blur(14px)",
      WebkitBackdropFilter: "blur(14px)",
    }}>
      <div ref={navRootRef} style={{
        maxWidth: 1480, margin: "0 auto",
        padding: "18px 28px",
        display: "flex", alignItems: "center", gap: 24,
      }}>
        <div onClick={() => onNavigate("home")} style={{ cursor: "pointer" }}>
          <SoloLogo size={26} />
        </div>
        <nav style={{ display: "flex", gap: 22, marginLeft: 24, flex: 1, alignItems: "center" }}>
          {MAIN_NAV.map(([id, lbl]) => {
            const config = getMegaMenuConfig(id);
            if (config) {
              return (
                <MegaMenu
                  key={id}
                  id={id}
                  label={lbl}
                  active={isActive(id)}
                  open={openId === id}
                  onOpen={() => open(id)}
                  onClose={scheduleClose}
                  onToggle={() => toggle(id)}
                  onNavigate={onNavigate}
                  config={config}
                  closeAll={() => setOpenId(null)}
                />
              );
            }
            // No dropdown — direct nav link
            return <NavLink key={id} id={id} active={isActive(id)} onClick={() => onNavigate(id)}>{lbl}</NavLink>;
          })}

          {/* "More" overflow — small simple dropdown */}
          <div
            onMouseEnter={() => open("__more__")}
            onMouseLeave={scheduleClose}
            style={{ position: "relative" }}
          >
            <button
              onClick={() => toggle("__more__")}
              style={{
                background: "none", border: "none", cursor: "pointer",
                fontFamily: "var(--font-body)",
                fontSize: 12, fontWeight: 500,
                letterSpacing: "0.18em",
                textTransform: "uppercase",
                color: (openId === "__more__" || moreActive) ? "var(--fg)" : "var(--fg-dim)",
                padding: "6px 0",
                borderBottom: (openId === "__more__" || moreActive) ? "1.5px solid var(--fg)" : "1.5px solid transparent",
                display: "inline-flex", alignItems: "center", gap: 6,
                whiteSpace: "nowrap",
              }}>
              More
              <span style={{
                fontSize: 9,
                transform: openId === "__more__" ? "rotate(180deg)" : "rotate(0deg)",
                transition: "transform 160ms",
              }}>▾</span>
            </button>
            {openId === "__more__" && (
              <div
                onMouseEnter={() => open("__more__")}
                onMouseLeave={scheduleClose}
                style={{
                  position: "absolute",
                  top: "calc(100% + 14px)",
                  left: -16,
                  minWidth: 220,
                  background: "var(--bg)",
                  border: "1px solid var(--line-strong)",
                  padding: "8px 0",
                  boxShadow: "0 24px 60px rgba(0,0,0,0.14)",
                  zIndex: 70,
                }}>
                {MORE_NAV.map(([id, lbl]) => (
                  <button
                    key={id}
                    onClick={() => { setOpenId(null); onNavigate(id); }}
                    style={{
                      display: "block", width: "100%", textAlign: "left",
                      background: "transparent", border: "none", cursor: "pointer",
                      fontFamily: "var(--font-body)",
                      fontSize: 12, fontWeight: 500,
                      letterSpacing: "0.18em",
                      textTransform: "uppercase",
                      color: page === id ? "var(--fg)" : "var(--fg-soft)",
                      padding: "12px 20px",
                      transition: "background 140ms",
                    }}
                    onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface)"}
                    onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
                  >{lbl}</button>
                ))}
              </div>
            )}
          </div>
        </nav>
        {/* Primary CTA group. Support ticket raising now lives inside the
            reseller portal only (see reseller-portal-dashboard.jsx) — no
            public entry point here any more.
            className used by responsive CSS to hide on mobile. */}
        <div className="solo-nav-primary-cta" style={{ display: "flex", gap: 10, alignItems: "center" }}>
          <Button primary small onClick={() => onNavigate("contact", { subject: "Request a demo" })}>
            Request a demo
          </Button>
        </div>

        {/* Far-right utility slot — reseller login. Separated by a thin
            vertical divider so it reads as a secondary utility action,
            not part of the primary CTA group.
            className used by responsive CSS to hide on mobile. */}
        <div className="solo-nav-utility" style={{
          display: "flex", alignItems: "center", gap: 16,
          paddingLeft: 16, marginLeft: 4,
          borderLeft: "1px solid var(--line)",
          alignSelf: "stretch",
        }}>
          <button
            onClick={() => onNavigate("reseller-login")}
            style={{
              background: "none", border: "none", padding: "10px 0",
              cursor: "pointer",
              fontFamily: "var(--font-body)",
              fontSize: 12, fontWeight: 500,
              letterSpacing: "0.18em", textTransform: "uppercase",
              color: "var(--fg-dim)",
              whiteSpace: "nowrap",
              display: "inline-flex", alignItems: "center", gap: 8,
              transition: "color 140ms",
            }}
            onMouseEnter={(e) => e.currentTarget.style.color = "var(--fg)"}
            onMouseLeave={(e) => e.currentTarget.style.color = "var(--fg-dim)"}
          >
            <LockIcon />
            <span>Reseller login</span>
          </button>
        </div>

        {/* ───────── Mobile hamburger ─────────
            Only visible below 900px. Toggles the full-screen mobile menu.
            Uses a class name so the responsive CSS in index.html can
            show/hide it without React re-rendering on every viewport change. */}
        <button
          className="solo-mobile-menu-toggle"
          onClick={() => setMobileOpen(true)}
          aria-label="Open menu"
          style={{
            display: "none", // shown by responsive CSS below 900px
            background: "none",
            border: "1px solid var(--line-strong)",
            padding: "10px 12px",
            cursor: "pointer",
            color: "var(--fg)",
            marginLeft: "auto",
          }}
        >
          <svg width="20" height="14" viewBox="0 0 20 14" fill="none">
            <path d="M0 1h20M0 7h20M0 13h20" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square"/>
          </svg>
        </button>
      </div>

    </header>
    {/* ───────── Mobile menu drawer ─────────
        Rendered OUTSIDE the <header> element. Two reasons:
          1. The header has `backdrop-filter: blur(...)` which creates a
             new containing block for `position: fixed` descendants —
             a fixed child would size against the 72px header, not the
             viewport. Sibling placement avoids that trap.
          2. A global CSS rule `header nav { display: none }` at <900px
             hides the desktop nav; the drawer contains its own <nav>
             which would inherit that hide if it lived inside <header>. */}
    {mobileOpen && (
      <MobileMenu
        page={page}
        onNavigate={wrapNav}
        onClose={() => setMobileOpen(false)}
      />
    )}
    </>
  );
}

/* ═══════════════════════════════════════════════════
   MOBILE MENU
   Full-screen slide-in menu for phones/tablets (<900px).
   Every nav item is a tappable row. Includes primary CTAs
   at the top and expandable product/sector sub-lists.
   ═══════════════════════════════════════════════════ */
function MobileMenu({ page, onNavigate, onClose }) {
  const [expanded, setExpanded] = useState(null); // which sub-list is open
  const data = window.SOLO_DATA || {};
  const products = data.products || [];
  const sectors  = data.sectors  || [];

  const toggle = (key) => setExpanded((cur) => (cur === key ? null : key));

  return (
    <div
      role="dialog"
      aria-modal="true"
      style={{
        position: "fixed",
        top: 0, left: 0, right: 0, bottom: 0,
        background: "var(--bg)",
        zIndex: 100,
        overflowY: "auto",
        WebkitOverflowScrolling: "touch",
        display: "flex", flexDirection: "column",
      }}
    >
      {/* Header row inside the menu — logo + close button */}
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "18px 20px",
        borderBottom: "1px solid var(--line)",
      }}>
        <div onClick={() => onNavigate("home")} style={{ cursor: "pointer" }}>
          <SoloLogo size={24} />
        </div>
        <button
          onClick={onClose}
          aria-label="Close menu"
          style={{
            background: "none",
            border: "1px solid var(--line-strong)",
            padding: "10px 12px",
            cursor: "pointer",
            color: "var(--fg)",
            fontFamily: "var(--font-body)",
            fontSize: 11,
            letterSpacing: "0.2em",
            textTransform: "uppercase",
            fontWeight: 500,
          }}
        >Close ✕</button>
      </div>

      {/* Primary CTAs — always visible at the top */}
      <div style={{
        padding: "20px 20px 12px",
        display: "flex", flexDirection: "column", gap: 10,
      }}>
        <button
          onClick={() => onNavigate("contact", { subject: "Request a demo" })}
          style={mobileCTAStyle(true)}
        >Request a demo →</button>
      </div>

      <div style={{ height: 1, background: "var(--line)", margin: "12px 20px" }} />

      {/* Main nav items */}
      <nav style={{ padding: "8px 0" }}>
        {/* Products — expandable */}
        <MobileNavGroup
          label="Products"
          isActive={page === "product" || page === "product-detail"}
          isOpen={expanded === "product"}
          onToggle={() => toggle("product")}
          onNavigate={() => onNavigate("product")}
        >
          {products.map(p => (
            <MobileSubItem
              key={p.id}
              muted={p.isLegacy}
              comingSoon={p.comingSoon}
              onClick={p.comingSoon ? undefined : () => onNavigate("product-detail", p.id)}
            >{p.name}</MobileSubItem>
          ))}
        </MobileNavGroup>

        <MobileNavLink
          label="Build a Tower"
          active={page === "builder"}
          onClick={() => onNavigate("builder")}
        />

        <MobileNavLink
          label="Services"
          active={page === "services"}
          onClick={() => onNavigate("services")}
        />

        {/* Sectors — expandable */}
        <MobileNavGroup
          label="Sectors"
          isActive={page === "sector"}
          isOpen={expanded === "sector"}
          onToggle={() => toggle("sector")}
          onNavigate={() => onNavigate("sector")}
        >
          {sectors.map(s => (
            <MobileSubItem
              key={s.id}
              onClick={() => onNavigate("sector", s.id)}
            >{s.name}</MobileSubItem>
          ))}
        </MobileNavGroup>

        <MobileNavLink
          label="Company"
          active={page === "about"}
          onClick={() => onNavigate("about")}
        />
        <MobileNavLink
          label="Partners"
          active={page === "partners"}
          onClick={() => onNavigate("partners")}
        />
        <MobileNavLink
          label="Sponsorships"
          active={page === "sponsors"}
          onClick={() => onNavigate("sponsors")}
        />

        <div style={{ height: 1, background: "var(--line)", margin: "12px 20px" }} />

        <MobileNavLink
          label="Contact"
          active={page === "contact"}
          onClick={() => onNavigate("contact")}
        />
        <MobileNavLink
          label="Careers"
          active={page === "careers"}
          onClick={() => onNavigate("careers")}
        />
        <MobileNavLink
          label="Sustainability"
          active={page === "sustainability"}
          onClick={() => onNavigate("sustainability")}
        />
        <MobileNavLink
          label="Deployments"
          active={page === "cases"}
          onClick={() => onNavigate("cases")}
        />

        <div style={{ height: 1, background: "var(--line)", margin: "12px 20px" }} />

        <MobileNavLink
          label="Reseller login"
          active={page === "reseller-login"}
          onClick={() => onNavigate("reseller-login")}
          muted
        />
      </nav>

      {/* Footer inside the drawer — contact + copyright */}
      <div style={{
        marginTop: "auto",
        padding: "24px 20px 32px",
        borderTop: "1px solid var(--line)",
        fontFamily: "var(--font-body)",
        fontSize: 12,
        color: "var(--fg-dim)",
        letterSpacing: "0.1em",
        textTransform: "uppercase",
      }}>
        <div>contactus@solosecure.group</div>
        <div style={{ marginTop: 8 }}>© {new Date().getUTCFullYear()} Solo Secure Group</div>
      </div>
    </div>
  );
}

function mobileCTAStyle(primary) {
  return {
    display: "block", width: "100%",
    padding: "16px 18px",
    border: primary ? "1px solid var(--fg)" : "1px solid var(--line-strong)",
    background: primary ? "var(--fg)" : "transparent",
    color: primary ? "var(--invert-fg)" : "var(--fg)",
    fontFamily: "var(--font-body)",
    fontSize: 13, fontWeight: 500,
    letterSpacing: "0.18em",
    textTransform: "uppercase",
    cursor: "pointer",
    textAlign: "left",
  };
}

function MobileNavLink({ label, active, onClick, muted }) {
  return (
    <button
      onClick={onClick}
      style={{
        display: "block", width: "100%", textAlign: "left",
        background: "transparent", border: "none", cursor: "pointer",
        padding: "18px 20px",
        fontFamily: "var(--font-body)",
        fontSize: 15, fontWeight: 500,
        letterSpacing: "0.14em",
        textTransform: "uppercase",
        color: muted ? "var(--fg-dim)" : (active ? "var(--fg)" : "var(--fg-soft)"),
        borderLeft: active ? "3px solid var(--fg)" : "3px solid transparent",
      }}
    >{label}</button>
  );
}

function MobileNavGroup({ label, isActive, isOpen, onToggle, onNavigate, children }) {
  return (
    <div>
      <div style={{
        display: "flex", alignItems: "stretch",
        borderLeft: isActive ? "3px solid var(--fg)" : "3px solid transparent",
      }}>
        <button
          onClick={onNavigate}
          style={{
            flex: 1, textAlign: "left",
            background: "transparent", border: "none", cursor: "pointer",
            padding: "18px 20px",
            fontFamily: "var(--font-body)",
            fontSize: 15, fontWeight: 500,
            letterSpacing: "0.14em",
            textTransform: "uppercase",
            color: isActive ? "var(--fg)" : "var(--fg-soft)",
          }}
        >{label}</button>
        <button
          onClick={onToggle}
          aria-label={isOpen ? `Collapse ${label}` : `Expand ${label}`}
          style={{
            background: "transparent", border: "none", cursor: "pointer",
            padding: "0 20px",
            color: "var(--fg-soft)",
            fontSize: 14,
            fontFamily: "var(--font-body)",
          }}
        >{isOpen ? "−" : "+"}</button>
      </div>
      {isOpen && (
        <div style={{
          background: "var(--surface)",
          padding: "8px 0",
          borderTop: "1px solid var(--line)",
          borderBottom: "1px solid var(--line)",
        }}>
          {children}
        </div>
      )}
    </div>
  );
}

function MobileSubItem({ muted, comingSoon, onClick, children }) {
  return (
    <button
      onClick={onClick}
      disabled={comingSoon}
      style={{
        display: "flex", alignItems: "center", gap: 8, width: "100%", textAlign: "left",
        background: "transparent", border: "none",
        cursor: comingSoon ? "default" : "pointer",
        padding: "13px 20px 13px 40px",
        fontFamily: "var(--font-body)",
        fontSize: 13, fontWeight: 400,
        letterSpacing: "0.06em",
        color: muted ? "var(--fg-dim)" : "var(--fg-soft)",
      }}
    >
      {children}
      {comingSoon && (
        <span style={{
          fontFamily: "var(--font-body)", fontSize: 9, fontWeight: 500,
          letterSpacing: "0.14em", textTransform: "uppercase",
          color: "var(--fg-dim)", border: "1px solid var(--line-strong)",
          padding: "2px 7px", whiteSpace: "nowrap",
        }}>Coming Soon</span>
      )}
    </button>
  );
}

function NavLink({ id, active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      background: "none", border: "none", cursor: "pointer",
      fontFamily: "var(--font-body)",
      fontSize: 12, fontWeight: 500,
      letterSpacing: "0.18em",
      textTransform: "uppercase",
      color: active ? "var(--fg)" : "var(--fg-dim)",
      padding: "6px 0",
      borderBottom: active ? "1.5px solid var(--fg)" : "1.5px solid transparent",
      transition: "color 140ms, border-color 140ms",
      whiteSpace: "nowrap",
    }}>{children}</button>
  );
}

/* ──────────── Lock icon ────────────
 * Padlock — used on the Reseller login link in the far-right nav slot.
 * Stroke uses currentColor so it picks up the link's text colour. */
function LockIcon() {
  return (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
      stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"
      aria-hidden="true">
      {/* Shackle */}
      <path d="M8 10 V7 a4 4 0 0 1 8 0 V10" />
      {/* Body */}
      <rect x="5" y="10" width="14" height="11" rx="1" />
    </svg>
  );
}

/* ──────────── Generic mega-menu ────────────
 * Opens on hover and on click. Hover-aware (small close delay so the
 * cursor can travel into the dropdown without it collapsing).
 * Config: see getMegaMenuConfig() above.
 */
function MegaMenu({ id, label, active, open, onOpen, onClose, onToggle, onNavigate, config, closeAll }) {
  // Sector pages are fully built (see SectorPage in pages.jsx, routed via
  // page === "sector" + sectorId in app.jsx) — mega-menu rows link
  // straight to them like every other section. Items only stay inactive
  // when the item itself is a not-yet-released product (comingSoon).
  const isInactiveItem = (item) => !!item.comingSoon;
  const handleItemClick = (item) => {
    if (isInactiveItem(item)) return;
    closeAll();
    onNavigate(item.page, item.params);
  };
  const handleHeaderClick = () => {
    closeAll();
    onNavigate(config.headerTarget);
  };

  return (
    <div
      style={{ position: "relative" }}
      onMouseEnter={onOpen}
      onMouseLeave={onClose}
    >
      <button
        onClick={onToggle}
        style={{
          background: "none", border: "none", cursor: "pointer",
          fontFamily: "var(--font-body)",
          fontSize: 12, fontWeight: 500,
          letterSpacing: "0.18em",
          textTransform: "uppercase",
          color: (open || active) ? "var(--fg)" : "var(--fg-dim)",
          padding: "6px 0",
          borderBottom: (open || active) ? "1.5px solid var(--fg)" : "1.5px solid transparent",
          transition: "color 140ms, border-color 140ms",
          display: "inline-flex", alignItems: "center", gap: 6,
          whiteSpace: "nowrap",
        }}>
        {label}
        <span style={{
          fontSize: 9,
          transform: open ? "rotate(180deg)" : "rotate(0deg)",
          transition: "transform 160ms",
        }}>▾</span>
      </button>

      {open && (
        <div
          onMouseEnter={onOpen}
          onMouseLeave={onClose}
          style={{
            position: "absolute",
            top: "calc(100% + 14px)",
            left: -20,
            // Grouped configs render two columns of items, so widen the panel.
            width: config.groups ? 760 : 460,
            background: "var(--bg)",
            border: "1px solid var(--line-strong)",
            boxShadow: "0 24px 60px rgba(0,0,0,0.14)",
            zIndex: 70,
            padding: 0,
            maxHeight: "calc(100vh - 120px)",
            overflowY: "auto",
          }}
        >
          {/* Header — clickable link to the section's index page. */}
          <button
            onClick={handleHeaderClick}
            style={{
              display: "flex", width: "100%", alignItems: "center", justifyContent: "space-between",
              background: "transparent", border: "none",
              cursor: "pointer",
              padding: "20px 24px 16px",
              borderBottom: "1px solid var(--line)",
              textAlign: "left",
              transition: "background 140ms",
            }}
            onMouseEnter={(e) => { e.currentTarget.style.background = "var(--surface)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; }}
          >
            <div>
              <div style={{
                fontFamily: "var(--font-body)", fontSize: 10,
                letterSpacing: "0.22em", textTransform: "uppercase",
                color: "var(--fg-dim)", fontWeight: 500, marginBottom: 4,
              }}>{config.headerSubtitle}</div>
              <div style={{
                fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 700,
                letterSpacing: "0.01em", textTransform: "uppercase", color: "var(--fg)",
              }}>{config.headerLabel} →</div>
            </div>
          </button>

          {/* Featured highlight — sits above groups when present. */}
          {config.featuredItem && (
            <button
              onClick={() => handleItemClick(config.featuredItem)}
              style={{
                display: "block",
                width: "100%",
                textAlign: "left",
                background: "var(--fg)",
                color: "var(--bg)",
                border: "none",
                cursor: "pointer",
                padding: "22px 24px 24px",
                transition: "background 140ms",
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = "var(--grey700)"}
              onMouseLeave={(e) => e.currentTarget.style.background = "var(--fg)"}
            >
              <div style={{
                fontFamily: "var(--font-body)", fontSize: 10,
                letterSpacing: "0.22em", textTransform: "uppercase",
                color: "rgba(255,255,255,0.6)", marginBottom: 8,
                fontWeight: 500,
              }}>Featured · By invitation</div>
              <div style={{
                display: "flex", justifyContent: "space-between", alignItems: "baseline",
                gap: 16, marginBottom: 6,
              }}>
                <span style={{
                  fontFamily: "var(--font-display)", fontWeight: 700,
                  fontSize: 17, letterSpacing: "0.005em",
                  textTransform: "uppercase", color: "var(--bg)",
                }}>{config.featuredItem.name}</span>
                <span style={{
                  fontFamily: "var(--font-body)", fontSize: 14,
                  color: "var(--bg)",
                }}>→</span>
              </div>
              {config.featuredItem.body && (
                <div style={{
                  fontFamily: "var(--font-body)", fontSize: 12,
                  lineHeight: 1.45, color: "rgba(255,255,255,0.75)",
                  marginTop: 4,
                }}>{config.featuredItem.body}</div>
              )}
            </button>
          )}

          {/* Body — either flat items or grouped two-column */}
          {config.groups ? (
            <>
              <div style={{
                display: "grid",
                gridTemplateColumns: "1fr 1fr",
              }}>
                {config.groups.map((g, gi) => (
                  <div key={`${id}-group-${gi}`} style={{
                    borderRight: gi === 0 ? "1px solid var(--line)" : "none",
                  }}>
                    {/* Group label */}
                    <div style={{
                      fontFamily: "var(--font-body)", fontSize: 10,
                      letterSpacing: "0.22em", textTransform: "uppercase",
                      color: "var(--fg-dim)", fontWeight: 500,
                      padding: "18px 24px 12px",
                      borderBottom: "1px solid var(--line)",
                    }}>{g.label}</div>
                    {g.items.map((item, ii) => (
                      <MegaMenuRow
                        key={`${id}-${gi}-${ii}`}
                        item={item}
                        first={ii === 0}
                        inactive={isInactiveItem(item)}
                        onClick={() => handleItemClick(item)}
                      />
                    ))}
                  </div>
                ))}
              </div>
              {config.footerItem && (
                <MegaMenuRow
                  item={config.footerItem}
                  first={false}
                  emphasized
                  inactive={isInactiveItem(config.footerItem)}
                  onClick={() => handleItemClick(config.footerItem)}
                />
              )}
            </>
          ) : (
            config.items.map((item, i) => (
              <MegaMenuRow
                key={`${id}-${i}`}
                item={item}
                first={i === 0}
                inactive={isInactiveItem(item)}
                onClick={() => handleItemClick(item)}
              />
            ))
          )}
        </div>
      )}
    </div>
  );
}

// Single mega-menu row — code, name, optional body, arrow.
// `inactive` renders the row as read-only: no hover, no arrow, no pointer,
// no click behaviour. Used for sector cards while sector detail pages are
// still being built out.
function MegaMenuRow({ item, first, emphasized, inactive, onClick }) {
  return (
    <button
      onClick={inactive ? undefined : onClick}
      disabled={inactive}
      style={{
        display: "grid",
        gridTemplateColumns: "1fr auto",
        gap: 16,
        alignItems: "center",
        width: "100%",
        textAlign: "left",
        background: emphasized ? "var(--surface)" : "transparent",
        border: "none",
        borderTop: first ? "none" : "1px solid var(--line)",
        cursor: inactive ? "default" : "pointer",
        padding: "16px 24px",
        transition: "background 140ms",
      }}
      onMouseEnter={(e) => { if (!inactive) e.currentTarget.style.background = "var(--surface)"; }}
      onMouseLeave={(e) => { if (!inactive) e.currentTarget.style.background = emphasized ? "var(--surface)" : "transparent"; }}
    >
      <span>
        <span style={{
          display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap",
          marginBottom: item.body ? 4 : 0,
        }}>
          <span style={{
            fontFamily: "var(--font-display)", fontSize: 15, fontWeight: 700,
            letterSpacing: "0.005em", textTransform: "uppercase",
            color: item.muted ? "var(--fg-soft)" : "var(--fg)",
          }}>{item.name}</span>
          {item.comingSoon && (
            <span style={{
              fontFamily: "var(--font-body)", fontSize: 9, fontWeight: 500,
              letterSpacing: "0.14em", textTransform: "uppercase",
              color: "var(--fg-dim)", border: "1px solid var(--line-strong)",
              padding: "2px 7px", whiteSpace: "nowrap",
            }}>Coming Soon</span>
          )}
        </span>
        {item.body && (
          <span style={{
            display: "block",
            fontFamily: "var(--font-body)", fontSize: 12,
            lineHeight: 1.4, color: "var(--fg-soft)",
          }}>{item.body}</span>
        )}
      </span>
      {!inactive && (
        <span style={{
          fontFamily: "var(--font-body)", fontSize: 14,
          color: "var(--fg)",
        }}>→</span>
      )}
    </button>
  );
}

function Footer({ onNavigate }) {
  return (
    <footer style={{ background: "var(--black)", color: "var(--invert-fg)" }}>
      <div style={{ maxWidth: 1480, margin: "0 auto", padding: "100px 36px 32px" }}>
        {/* Hero footer brand line */}
        <div style={{ borderBottom: "1px solid rgba(255,255,255,0.10)", paddingBottom: 60, marginBottom: 60 }}>
          <div style={{
            fontFamily: "var(--font-display)",
            fontWeight: 700,
            fontSize: "clamp(40px, 6vw, 96px)",
            lineHeight: 0.96,
            letterSpacing: "-0.005em",
            textTransform: "uppercase",
            color: "var(--invert-fg)",
            maxWidth: 1100,
          }}>
            Secure beyond limits.
          </div>
          <div style={{
            marginTop: 28, fontFamily: "var(--font-body)",
            fontSize: 16, lineHeight: 1.55,
            color: "rgba(255,255,255,0.65)",
            maxWidth: 560,
          }}>
            UK-engineered mobile CCTV towers and rapidly-deployable security platforms.
            Designed, built and supported in Britain since 2019.
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr 1fr", gap: 40, paddingBottom: 56 }}>
          <div>
            <SoloLogo size={28} variant="white" />
            <div style={{ display: "flex", gap: 8, marginTop: 28, flexWrap: "wrap" }}>
              {["ISO 9001", "ISO 27001", "UKCA", "CE", "Constructionline"].map((c) => (
                <span key={c} style={{
                  fontFamily: "var(--font-body)",
                  fontSize: 10, fontWeight: 500,
                  letterSpacing: "0.16em",
                  padding: "5px 9px",
                  border: "1px solid rgba(255,255,255,0.22)",
                  color: "rgba(255,255,255,0.85)",
                  textTransform: "uppercase",
                }}>{c}</span>
              ))}
            </div>
          </div>
          <FootCol title="Products & Services" items={[
            ["product",  "All products"],
            ["services", "Services"],
            ["sector",   "Sectors"],
            ["cases",    "Deployments"],
          ]} onNavigate={onNavigate} />
          <FootCol title="Partners & Regions" items={[
            ["partners",          "Partner programme"],
            ["exclusive-regions", "Exclusive Regions"],
            // Gold + Platinum tiers hidden from the footer until the tier
            // rosters have real partners to feature — empty tier pages
            // read worse than a smaller partner section. Re-add when ready.
            // ["gold-partners",     "Gold Partners"],
            // ["platinum-partners", "Platinum Partners"],
            ["regions",           "All regions"],
          ]} onNavigate={onNavigate} />
          <FootCol title="Company" items={[
            ["about",          "About Solo"],
            ["sponsors",       "Our Sponsorships"],
            ["careers",        "Careers"],
            ["sustainability", "Sustainability"],
          ]} onNavigate={onNavigate} />
          <FootCol title="Get in touch" items={[
            ["contact", "Contact"],
            ["contact", "Reseller programme"],
            ["contact", "Support 24/7"],
            ["contact", "contactus@solosecure.group"],
          ]} onNavigate={onNavigate} />
          <FootCol title="Legal" items={[
            ["privacy",        "Privacy"],
            ["terms",          "Terms"],
            ["warranty",       "Warranty"],
            ["modern-slavery", "Modern Slavery"],
            ["cookie-policy",  "Cookie policy"],
          ]} onNavigate={onNavigate} />
        </div>

        {/* TECHNOLOGY PARTNERS — Victron + Ajax wordmarks.
            Sits in the footer so it appears on every page. White-only PNGs
            so they read cleanly against the black footer background.
            Heading centered above a centered logo row, matching the
            Accreditations block's layout directly below it. */}
        <div style={{
          textAlign: "center",
          // Bumped vertical padding to give the now-larger Ajax stacked
          // lockup (~110px tall) proper breathing room top and bottom.
          paddingTop: 44, paddingBottom: 44,
          borderTop: "1px solid rgba(255,255,255,0.10)",
          borderBottom: "1px solid rgba(255,255,255,0.10)",
          marginBottom: 24,
        }}>
          <div style={{
            fontFamily: "var(--font-body)", fontSize: 11,
            letterSpacing: "0.22em", textTransform: "uppercase",
            color: "rgba(255,255,255,0.55)", fontWeight: 500,
            marginBottom: 28,
          }}>Our technology partners</div>

          <div style={{
            display: "flex", alignItems: "center", justifyContent: "center",
            gap: 48, flexWrap: "wrap",
          }}>
            <img
              src="assets/partner-victron-white.png"
              alt="Victron Energy"
              style={{
                height: 32, width: "auto",
                opacity: 0.85,
                display: "block",
              }}
            />
            <img
              src="assets/partner-ajax-white.png"
              alt="Ajax Ready"
              style={{
                // Ajax stacked lockup ("AJAX" over "<READY>") — large
                // enough that the AJAX cap-height clearly dominates the
                // Victron wordmark next to it.
                height: 110, width: "auto",
                opacity: 0.85,
                display: "block",
              }}
            />
            <img
              src="assets/partner-teltonika-white.png"
              alt="Teltonika"
              style={{
                // Teltonika is a plain single-line wordmark like Victron
                // (no stacked tagline like Ajax) — matched to the same
                // rendered height so the two horizontal marks sit at a
                // comparable cap-height.
                height: 32, width: "auto",
                opacity: 0.85,
                display: "block",
              }}
            />
          </div>
        </div>

        {/* ACCREDITATIONS — certification badge wall, sitewide footer.
            Sits between Technology Partners and the Registered Entities
            disclosure so it appears on every page, matching the same
            label + wrapped-row layout used by the Technology Partners
            block above it. Badge PNGs already ship with their own solid
            black backgrounds, so they sit flush against the footer with
            no visible box/seam. */}
        <div style={{
          paddingBottom: 44,
          borderBottom: "1px solid rgba(255,255,255,0.10)",
          marginBottom: 24,
        }}>
          <div style={{ textAlign: "center", marginBottom: 28 }}>
            <div style={{
              fontFamily: "var(--font-display)", fontWeight: 700,
              fontSize: 15, letterSpacing: "0.04em", textTransform: "uppercase",
              color: "#fff", marginBottom: 10,
            }}>Accreditations</div>
            <div style={{
              fontFamily: "var(--font-body)", fontSize: 11,
              letterSpacing: "0.24em", textTransform: "uppercase",
              color: "rgba(255,255,255,0.55)", fontWeight: 500,
            }}>
              Certified for quality, safety &amp; performance
            </div>
          </div>
          <div style={{
            display: "flex", flexWrap: "wrap",
            alignItems: "center", justifyContent: "center",
            gap: "32px 44px",
          }}>
            {[
              { name: "Cyber Essentials",                            logo: "assets/accred-cyber-essentials.png",  height: 56 },
              { name: "Citation ISO Certification — ISO 27001",      logo: "assets/accred-iso-27001.png",         height: 56 },
              { name: "Citation ISO Certification — ISO 9001:2015",  logo: "assets/accred-iso-9001.png",          height: 50 },
              { name: "Constructionline Associate Member",           logo: "assets/accred-constructionline.png",  height: 56 },
              { name: "UKCA & CE Marking",                           logo: "assets/accred-ukca-ce.png",           height: 38 },
            ].map((a) => (
              <img
                key={a.name}
                src={a.logo}
                alt={a.name}
                style={{ height: a.height, width: "auto", display: "block", opacity: 0.92 }}
              />
            ))}
          </div>
        </div>

        {/* ── Companies Act 2006 disclosure ──
            UK limited companies operating a website MUST publish the
            registered name, number, place of registration and registered
            office. We list the three group entities here — one line each,
            small type, so it's compliant without dominating the footer. */}
        <div style={{
          paddingTop: 24, paddingBottom: 20,
          borderTop: "1px solid rgba(255,255,255,0.10)",
          fontFamily: "var(--font-body)", fontSize: 11,
          lineHeight: 1.65,
          color: "rgba(255,255,255,0.55)",
        }}>
          <div style={{
            fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase",
            color: "rgba(255,255,255,0.4)", marginBottom: 10, fontWeight: 500,
          }}>Registered entities</div>

          <div style={{ marginBottom: 4 }}>
            <b style={{ color: "rgba(255,255,255,0.85)" }}>Solo Secure Group Limited</b>
            {" "}· Company no. 16206860 · Registered in England and Wales · Unit 3 Eldon Way Industrial Estate, Biggleswade, Bedfordshire SG18 8NH.
          </div>
          <div style={{ marginBottom: 4 }}>
            <b style={{ color: "rgba(255,255,255,0.85)" }}>Site Secure Services Limited</b>
            {" "}· Company no. 11519748 · Registered in England and Wales · Unit 3 Eldon Way Industrial Estate, Biggleswade, Bedfordshire SG18 8NH.
          </div>
          <div>
            <b style={{ color: "rgba(255,255,255,0.85)" }}>Solo Secure Technologies USA, Inc.</b>
            {" "}· Company no. P26000029423 · Registered in the United States of America · 12070 SW Tom Mackie Blvd., Suite 105, Port St. Lucie, FL 34953.
          </div>
        </div>

        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          paddingTop: 24, borderTop: "1px solid rgba(255,255,255,0.10)",
          fontFamily: "var(--font-body)", fontSize: 11,
          letterSpacing: "0.14em", color: "rgba(255,255,255,0.5)",
          textTransform: "uppercase",
        }}>
          <span>© {new Date().getUTCFullYear()} Solo Secure Group of Companies</span>
          {/* Cookie preferences — opens the consent modal so users can
              change their mind later without hunting through legal pages. */}
          <span
            onClick={() => window.SOLO_COOKIES?.open()}
            style={{
              cursor: "pointer",
              transition: "color 140ms",
            }}
            onMouseEnter={(e) => e.currentTarget.style.color = "rgba(255,255,255,0.9)"}
            onMouseLeave={(e) => e.currentTarget.style.color = ""}
          >Cookie preferences</span>
          <span>Designed and engineered in the UK</span>
          <span><LiveClock /></span>
        </div>
      </div>
    </footer>
  );
}

function FootCol({ title, items, onNavigate }) {
  return (
    <div>
      <div style={{
        fontFamily: "var(--font-body)", fontSize: 11,
        letterSpacing: "0.22em", textTransform: "uppercase",
        color: "rgba(255,255,255,0.55)", marginBottom: 20,
      }}>{title}</div>
      {items.map(([target, label], i) => (
        <div key={i} onClick={() => onNavigate(target)} style={{
          fontFamily: "var(--font-body)", fontSize: 14,
          padding: "6px 0", cursor: "pointer",
          color: "rgba(255,255,255,0.85)",
        }}>{label}</div>
      ))}
    </div>
  );
}

Object.assign(window, { TopNav, Footer });
