/* Header — sticky nav with three mega menus (Services, Sectors, Locations)
 * plus phone + 'Book a call' CTA. Crossfades between white-on-ink (top of
 * page, over hero) and coloured-on-paper (after scroll). */

const { useState: useStateHdr, useEffect: useEffectHdr, useRef: useRefHdr } = React;

function Header({ activePage = "home", solid = false }) {
  const [scrolled, setScrolled] = useStateHdr(solid);
  const [openMenu, setOpenMenu] = useStateHdr(null);  // 'services' | 'sectors' | 'locations' | 'insights' | null
  const [menuOpen, setMenuOpen] = useStateHdr(false); // mobile drawer
  const closeTimer = useRefHdr(null);

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

  const open = (id) => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    setOpenMenu(id);
  };
  const close = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => setOpenMenu(null), 140);
  };

  useEffectHdr(() => {
    const onKey = (e) => { if (e.key === "Escape") { setOpenMenu(null); setMenuOpen(false); } };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  useEffectHdr(() => {
    const mql = window.matchMedia("(min-width: 1081px)");
    const onChange = (e) => { if (e.matches) setMenuOpen(false); };
    onChange(mql);
    mql.addEventListener("change", onChange);
    return () => mql.removeEventListener("change", onChange);
  }, []);

  const links = [
    { id: "services",  label: "Services",    href: "services.html",  mega: "services", icon: "shield-check" },
    { id: "sectors",   label: "Sectors",     href: "sectors.html",   mega: "sectors",  icon: "scale" },
    { id: "locations", label: "Locations",   href: "#",              mega: "locations", icon: "map-pin" },
    { id: "about",     label: "About",       href: "about.html",     icon: "users" },
    { id: "insights",  label: "Insights",    href: "blog.html",      mega: "insights", icon: "book-open" },
    { id: "contact",   label: "Contact",     href: "contact.html",   icon: "phone" },
  ];

  return (
    <>
      <header
        onMouseLeave={close}
        style={{
          position: "fixed", top: 0, left: 0, right: 0, zIndex: 60,
          background: scrolled ? "var(--ri-paper)" : "transparent",
          borderBottom: scrolled ? "1px solid var(--border)" : "1px solid transparent",
          boxShadow: scrolled ? "0 8px 24px rgba(8,5,38,0.06)" : "none",
          transition: "background 280ms var(--ease-out), border-color 280ms var(--ease-out), box-shadow 240ms var(--ease-out)",
        }}
      >
        <Container style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 76, gap: 24 }}>
          <a
            href="index.html"
            style={{ display: "inline-flex", alignItems: "center", gap: 10,
                     textDecoration: "none", border: 0, flex: "0 0 auto", position: "relative" }}
          >
            <img
              src="assets/logos/logo_black_colour.png"
              alt="Reformed IT"
              style={{ height: 32, display: "block",
                       opacity: scrolled ? 1 : 0,
                       transition: "opacity 240ms var(--ease-out)" }}
            />
            <img
              src="assets/logos/logo_white_colour.png"
              alt=""
              aria-hidden="true"
              style={{ height: 32, display: "block", position: "absolute", top: 0, left: 0,
                       opacity: scrolled ? 0 : 1,
                       transition: "opacity 240ms var(--ease-out)" }}
            />
          </a>

          <nav
            role="navigation"
            aria-label="Primary"
            style={{ display: "flex", gap: 26, alignItems: "center", flex: 1, justifyContent: "center" }}
            className="ri-desktop-nav"
          >
            {links.map((l) => (
              <NavItem
                key={l.id}
                link={l}
                isOpen={openMenu === l.mega}
                isActive={activePage === l.id}
                scrolled={scrolled}
                onEnter={() => l.mega ? open(l.mega) : close()}
                onLeave={close}
              />
            ))}
          </nav>

          <div style={{ display: "flex", gap: 12, alignItems: "center", flex: "0 0 auto" }}>
            <a
              href="tel:01158244824"
              className="ri-phone-link"
              style={{
                fontSize: 14, fontWeight: 600,
                color: scrolled ? "var(--ri-ink)" : "#fff",
                textDecoration: "none", border: 0,
                display: "inline-flex", alignItems: "center", gap: 6,
                transition: "color 200ms var(--ease-out)",
                whiteSpace: "nowrap",
              }}
            >
              <Icon name="phone" size={15} stroke={2} />
              <span className="ri-phone-num">01158 244 824</span>
            </a>
            <Button
              variant="primary"
              size="sm"
              iconRight="arrow-right"
              as="a"
              href="contact.html"
            >
              Book a call
            </Button>
            <button
              aria-label="Menu"
              onClick={() => setMenuOpen((v) => !v)}
              style={{
                display: "none",
                background: "transparent", border: 0, padding: 8, cursor: "pointer",
                color: scrolled ? "var(--fg)" : "#fff",
                transition: "color 200ms var(--ease-out)",
              }}
              className="ri-mobile-toggle"
            >
              <Icon name={menuOpen ? "x" : "menu"} size={22} />
            </button>
          </div>
        </Container>

        <MegaMenu kind="services"  open={openMenu === "services"}  onEnter={() => open("services")}  onLeave={close} />
        <MegaMenu kind="sectors"   open={openMenu === "sectors"}   onEnter={() => open("sectors")}   onLeave={close} />
        <MegaMenu kind="locations" open={openMenu === "locations"} onEnter={() => open("locations")} onLeave={close} />
        <MegaMenu kind="insights"  open={openMenu === "insights"}  onEnter={() => open("insights")}  onLeave={close} />

        {menuOpen && (
          <div style={{
            background: "var(--ri-paper)", borderTop: "1px solid var(--border)",
            padding: "8px 32px 18px",
            maxHeight: "calc(100vh - 76px)", overflowY: "auto",
          }}>
            {links.map((l) => (
              <MobileNavItem
                key={l.id}
                link={l}
                onClose={() => setMenuOpen(false)}
              />
            ))}
            <div style={{ display: "flex", gap: 10, paddingTop: 18 }}>
              <Button variant="primary" iconRight="arrow-right" as="a" href="contact.html" style={{ flex: 1, justifyContent: "center" }}>
                Book a call
              </Button>
            </div>
          </div>
        )}
      </header>

      <style>{`
        @media (max-width: 1080px) {
          .ri-desktop-nav { display: none !important; }
          .ri-mobile-toggle { display: inline-flex !important; }
          .ri-phone-link { display: none !important; }
        }
        @media (max-width: 540px) {
          .ri-phone-num { display: none; }
        }
      `}</style>
    </>
  );
}

function NavItem({ link, isOpen, isActive, scrolled, onEnter, onLeave }) {
  const hasMega = !!link.mega;
  const restColor = scrolled ? "var(--fg)" : "rgba(255,255,255,0.92)";
  const hoverColor = "var(--ri-pink)";
  const showPink = isOpen || isActive;
  return (
    <div
      onMouseEnter={onEnter}
      onMouseLeave={onLeave}
      style={{ position: "relative" }}
    >
      <a
        href={link.href || "#"}
        onClick={(e) => smartNav(e, link.href)}
        style={{
          color: showPink ? hoverColor : restColor,
          fontSize: 14, fontWeight: 500, textDecoration: "none", border: 0,
          display: "inline-flex", alignItems: "center", gap: 4,
          padding: "6px 0",
          transition: "color 200ms var(--ease-out)",
          whiteSpace: "nowrap",
        }}
      >
        {link.label}
        {hasMega && (
          <span style={{
            display: "inline-flex",
            transform: isOpen ? "rotate(180deg)" : "rotate(0)",
            transition: "transform 200ms var(--ease-out)",
            lineHeight: 0,
          }}>
            <Icon name="chevron-down" size={14} stroke={2.2} />
          </span>
        )}
      </a>
    </div>
  );
}

function smartNav(e, href) {
  if (!href || href === "#") { e.preventDefault(); return; }
  if (href.startsWith("#")) {
    e.preventDefault();
    const id = href.slice(1);
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
    return;
  }
  const hashIdx = href.indexOf("#");
  if (hashIdx > 0) {
    const page = href.slice(0, hashIdx);
    const anchor = href.slice(hashIdx + 1);
    const currentFile = location.pathname.split("/").pop() || "index.html";
    if (currentFile === page || (page === "index.html" && currentFile === "")) {
      e.preventDefault();
      const el = document.getElementById(anchor);
      if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
    }
  }
}

const MEGA_CONTENT = {
  services: {
    columns: [
      {
        eyebrow: "Managed IT Services",
        items: [
          { icon: "monitor",        title: "Workstation management", blurb: "Patching, replacement, recovery", href: "service-detail.html" },
          { icon: "server",         title: "Servers & networking",   blurb: "On-prem, hybrid, cloud",           href: "service-detail.html" },
          { icon: "message-square", title: "Helpdesk",               blurb: "A human, fast — Mon–Fri 8am–5.30pm", href: "service-detail.html" },
          { icon: "cloud",          title: "Microsoft 365 & Cloud",  blurb: "Migrations & governance",          href: "service-detail.html" },
        ],
      },
      {
        eyebrow: "Cybersecurity services",
        items: [
          { icon: "shield-check",   title: "Threat protection",      blurb: "EDR, MFA, mailbox",                href: "service-detail.html" },
          { icon: "fingerprint",    title: "Identity & access",      blurb: "SSO, MFA, conditional access",     href: "service-detail.html" },
          { icon: "scan-eye",       title: "Posture audits",         blurb: "Tenant scan, gap analysis",        href: "service-detail.html" },
          { icon: "triangle-alert", title: "Incident response",      blurb: "Hour-zero containment",            href: "service-detail.html" },
        ],
      },
      {
        eyebrow: "Compliance & strategy",
        items: [
          { icon: "award",          title: "Cyber Essentials Plus",  blurb: "Certified since 2019",             href: "service-detail.html" },
          { icon: "clipboard-check",title: "ISO 27001 prep",         blurb: "Controls & evidence library",      href: "service-detail.html" },
          { icon: "scale",          title: "Regulated work",         blurb: "FCA / SRA-aligned",                href: "service-detail.html" },
          { icon: "trending-up",    title: "IT strategy & roadmap",  blurb: "Quarterly reviews",                href: "service-detail.html" },
        ],
      },
    ],
    feature: {
      eyebrow: "Featured",
      title: "Co-managed IT, plainly explained.",
      blurb: "What changes when we slot in alongside your internal team — and what you keep in-house.",
      cta: "Read the guide",
      href: "blog-post.html",
    },
  },
  sectors: {
    columns: [
      {
        eyebrow: "Regulated work",
        items: [
          { icon: "scale",        title: "Solicitors",        blurb: "SRA-aligned, mailbox-first",      href: "sector-solicitors.html" },
          { icon: "calculator",   title: "Accountants",       blurb: "AML data, ICAEW & ACCA",          href: "sector-accountants.html" },
        ],
      },
      {
        eyebrow: "Property & manufacturing",
        items: [
          { icon: "home",         title: "Property services", blurb: "Estate agents, surveyors, developers", href: "sector-property.html" },
          { icon: "factory",      title: "Manufacturers",     blurb: "OT-aware, uptime-first",          href: "sector-manufacturers.html" },
        ],
      },
      {
        eyebrow: "Not in this list?",
        items: [
          { icon: "users",        title: "Other regulated industries", blurb: "Recruitment, finance, legal-adjacent", href: "contact.html" },
          { icon: "message-circle", title: "Talk to us",        blurb: "10-min call · we'll be straight", href: "contact.html" },
        ],
      },
    ],
    feature: {
      eyebrow: "Why sector matters",
      title: "We work in four sectors.",
      blurb: "Sector specialism means the engineer knows your software stack, regulator, and the way your team actually works on a Tuesday.",
      cta: "How we choose",
      href: "about.html",
    },
  },
  locations: {
    columns: [
      {
        eyebrow: "On-site, fully inclusive",
        items: [
          { icon: "map-pin",      title: "IT Support Nottingham", blurb: "HQ · 10 Farrington Way, Eastwood, NG16 3BF", href: "location-nottingham.html" },
          { icon: "map-pin",      title: "IT Support Derby",      blurb: "By appointment · DE1",          href: "location-derby.html" },
        ],
      },
      {
        eyebrow: "Inclusive remote",
        items: [
          { icon: "map-pin",      title: "IT Support London",     blurb: "Remote with on-site visits",     href: "location-london.html" },
          { icon: "globe",        title: "Elsewhere in the UK",   blurb: "By exception — talk to us",     href: "contact.html" },
        ],
      },
      {
        eyebrow: "Direct lines",
        items: [
          { icon: "phone",        title: "01158 244 824",         blurb: "Mon–Fri · 8am–5.30pm",             href: "tel:01158244824" },
          { icon: "mail",         title: "hello@reformed-it.co.uk", blurb: "New enquiries · reply within the hour", href: "mailto:hello@reformed-it.co.uk" },
        ],
      },
    ],
    feature: {
      eyebrow: "Coverage map",
      title: "90 minutes by car.",
      blurb: "On-site visits anywhere in the East Midlands inside 90 minutes. Remote support, anywhere in the UK.",
      cta: "Book a call",
      href: "contact.html",
    },
  },
  insights: {
    columns: [
      {
        eyebrow: "Guides",
        items: [
          { icon: "book-marked", title: "Cybersecurity for legal firms",      blurb: "10-min read", href: "blog-post.html" },
          { icon: "book-marked", title: "M365 migration, plainly",            blurb: "12-min read", href: "blog-post.html" },
          { icon: "book-marked", title: "MFA without the friction",           blurb: "6-min read",  href: "blog-post.html" },
        ],
      },
      {
        eyebrow: "Case studies",
        items: [
          { icon: "file-text", title: "Acme Legal · 65 people",     blurb: "On-prem → M365 in 11 weeks", href: "blog-post.html" },
          { icon: "file-text", title: "Bridge Capital · 32 people", blurb: "ISO 27001 in 9 months",      href: "blog-post.html" },
          { icon: "file-text", title: "Howell Build · 110 people",  blurb: "Co-managed · 110 people",    href: "blog-post.html" },
        ],
      },
      {
        eyebrow: "For clients",
        items: [
          { icon: "life-buoy",   title: "Open a ticket",  blurb: "support@reformed-it.co.uk", href: "contact.html" },
          { icon: "activity",    title: "Status page",    blurb: "Live system health",         href: "#" },
          { icon: "user",        title: "Client portal",  blurb: "Sign in →",                  href: "#" },
        ],
      },
    ],
    feature: {
      eyebrow: "This week",
      title: "Q3 service review.",
      blurb: "412 tickets resolved · 2.1 h average response · 99.1% SLA met. The numbers, plainly.",
      cta: "See the figures",
      href: "blog-post.html",
    },
  },
};

function MegaMenu({ kind, open, onEnter, onLeave }) {
  const data = MEGA_CONTENT[kind];
  if (!data) return null;
  return (
    <div
      onMouseEnter={onEnter}
      onMouseLeave={onLeave}
      aria-hidden={!open}
      style={{
        position: "absolute", left: 0, right: 0, top: "100%",
        background: "var(--ri-paper)",
        borderTop: "1px solid var(--border)",
        borderBottom: "1px solid var(--border)",
        boxShadow: "0 24px 48px rgba(8,5,38,0.08)",
        opacity: open ? 1 : 0,
        transform: open ? "translateY(0)" : "translateY(-8px)",
        pointerEvents: open ? "auto" : "none",
        transition: "opacity 200ms var(--ease-out), transform 240ms var(--ease-out)",
      }}
    >
      <Container style={{ padding: "36px 32px 40px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.1fr 1.1fr 1.1fr 1fr", gap: 32 }}>
          {data.columns.map((col) => (
            <div key={col.eyebrow}>
              <div style={{
                fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase",
                fontWeight: 600, color: "var(--ri-pink)", marginBottom: 18,
              }}>{col.eyebrow}</div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0,
                           display: "flex", flexDirection: "column", gap: 6 }}>
                {col.items.map((it) => <MegaItem key={it.title} {...it} />)}
              </ul>
            </div>
          ))}
          <FeatureCard {...data.feature} />
        </div>
        <div style={{
          marginTop: 28, height: 6, borderRadius: 4,
          background: "var(--grad-brand)", opacity: 0.9,
        }}></div>
      </Container>
    </div>
  );
}

function MegaItem({ icon, title, blurb, href = "#" }) {
  const [hover, setHover] = React.useState(false);
  return (
    <li>
      <a
        href={href}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        style={{
          display: "flex", alignItems: "flex-start", gap: 12,
          padding: "10px 12px", margin: "0 -12px",
          borderRadius: 10,
          background: hover ? "rgba(242,43,105,0.06)" : "transparent",
          textDecoration: "none", border: 0, color: "var(--fg)",
          transition: "background 120ms var(--ease-out)",
        }}
      >
        <span style={{
          width: 34, height: 34, borderRadius: 10,
          background: hover ? "rgba(242,43,105,0.12)" : "var(--bg-subtle)",
          color: hover ? "var(--ri-pink)" : "var(--ri-ink)",
          display: "flex", alignItems: "center", justifyContent: "center",
          flex: "0 0 auto", transition: "background 120ms, color 120ms",
        }}>
          <Icon name={icon} size={17} stroke={2} />
        </span>
        <span style={{ display: "flex", flexDirection: "column", gap: 2, minWidth: 0 }}>
          <span style={{ fontSize: 13.5, fontWeight: 600, color: hover ? "var(--ri-pink)" : "var(--fg)",
                         transition: "color 120ms" }}>{title}</span>
          <span style={{ fontSize: 12, color: "var(--fg-muted)", lineHeight: 1.4 }}>{blurb}</span>
        </span>
      </a>
    </li>
  );
}

function FeatureCard({ eyebrow, title, blurb, cta, href = "#" }) {
  const [hover, setHover] = React.useState(false);
  return (
    <a
      href={href}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: "block", textDecoration: "none", border: 0,
        background: "var(--ri-ink)", color: "#fff",
        borderRadius: 16, padding: 22,
        position: "relative", overflow: "hidden",
        transition: "transform 200ms var(--ease-out)",
        transform: hover ? "translateY(-2px)" : "translateY(0)",
      }}
    >
      <div aria-hidden="true" style={{
        position: "absolute", left: 0, right: 0, top: 0, height: 3,
        background: "var(--grad-brand)",
      }}></div>
      <div style={{
        fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase",
        fontWeight: 600, color: "var(--ri-pink)", marginBottom: 14,
      }}>{eyebrow}</div>
      <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-0.01em",
                    lineHeight: 1.2, marginBottom: 10, textWrap: "balance" }}>
        {title}
      </div>
      <p style={{ fontSize: 12.5, lineHeight: 1.5, margin: "0 0 18px",
                  color: "rgba(245,245,247,0.7)" }}>{blurb}</p>
      <span style={{
        fontSize: 12, fontWeight: 600, color: "var(--ri-pink)",
        display: "inline-flex", alignItems: "center", gap: 6,
      }}>
        {cta} <Icon name="arrow-right" size={14} stroke={2.2} />
      </span>
    </a>
  );
}

function MobileNavItem({ link, onClose }) {
  const [open, setOpen] = React.useState(false);
  const mega = link.mega ? MEGA_CONTENT[link.mega] : null;

  if (!mega) {
    return (
      <a
        href={link.href || "#"}
        onClick={(e) => { smartNav(e, link.href); onClose(); }}
        style={{
          display: "flex", alignItems: "center", gap: 14,
          padding: "16px 0", color: "var(--fg)",
          textDecoration: "none", border: 0, borderBottom: "1px solid var(--border)",
          fontSize: 16, fontWeight: 500,
        }}
      >
        <span style={{
          width: 36, height: 36, borderRadius: 10,
          background: "var(--bg-subtle)", color: "var(--ri-ink)",
          display: "flex", alignItems: "center", justifyContent: "center",
          flex: "0 0 auto",
        }}>
          <Icon name={link.icon || "circle"} size={18} stroke={2} />
        </span>
        {link.label}
      </a>
    );
  }

  return (
    <div style={{ borderBottom: "1px solid var(--border)" }}>
      <button
        onClick={() => setOpen((v) => !v)}
        aria-expanded={open}
        style={{
          width: "100%", padding: "16px 0", background: "transparent", border: 0,
          display: "flex", justifyContent: "space-between", alignItems: "center",
          color: open ? "var(--ri-pink)" : "var(--fg)",
          fontSize: 16, fontWeight: 500, cursor: "pointer",
          fontFamily: "inherit", textAlign: "left",
          transition: "color 160ms var(--ease-out)",
        }}
      >
        <span style={{ display: "inline-flex", alignItems: "center", gap: 14 }}>
          <span style={{
            width: 36, height: 36, borderRadius: 10,
            background: open ? "rgba(242,43,105,0.12)" : "var(--bg-subtle)",
            color: open ? "var(--ri-pink)" : "var(--ri-ink)",
            display: "flex", alignItems: "center", justifyContent: "center",
            flex: "0 0 auto",
            transition: "background 160ms var(--ease-out), color 160ms var(--ease-out)",
          }}>
            <Icon name={link.icon || "circle"} size={18} stroke={2} />
          </span>
          {link.label}
        </span>
        <span style={{
          display: "inline-flex", lineHeight: 0,
          transform: open ? "rotate(180deg)" : "rotate(0)",
          transition: "transform 200ms var(--ease-out)",
        }}>
          <Icon name="chevron-down" size={18} stroke={2.2} />
        </span>
      </button>

      {open && (
        <div style={{ padding: "4px 0 18px" }}>
          {mega.columns.map((col) => (
            <div key={col.eyebrow} style={{ marginBottom: 18 }}>
              <div style={{
                fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase",
                fontWeight: 600, color: "var(--ri-pink)",
                margin: "8px 0 10px",
              }}>{col.eyebrow}</div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0,
                           display: "flex", flexDirection: "column", gap: 2 }}>
                {col.items.map((it) => (
                  <li key={it.title}>
                    <a
                      href={it.href || "#"}
                      onClick={() => onClose()}
                      style={{
                        display: "flex", alignItems: "center", gap: 12,
                        padding: "10px 0", textDecoration: "none",
                        border: 0, color: "var(--fg)",
                      }}
                    >
                      <span style={{
                        width: 32, height: 32, borderRadius: 8,
                        background: "var(--bg-subtle)", color: "var(--ri-ink)",
                        display: "flex", alignItems: "center", justifyContent: "center",
                        flex: "0 0 auto",
                      }}>
                        <Icon name={it.icon} size={16} stroke={2} />
                      </span>
                      <span style={{ display: "flex", flexDirection: "column", gap: 1 }}>
                        <span style={{ fontSize: 14, fontWeight: 600 }}>{it.title}</span>
                        <span style={{ fontSize: 11.5, color: "var(--fg-muted)", lineHeight: 1.4 }}>{it.blurb}</span>
                      </span>
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Header });
