// Navbar.jsx
//
// Fully responsive site header: desktop mega-menu for the 15 real product
// modules (SPEC-07 Section 0/2), a mobile hamburger drawer, a "Login" link
// to the deployed product, and a global "Request a Demo" CTA. Route slugs
// match the ones the Footer and EarlyAccessGate.jsx use - see that file's
// REAL_MODULES.
//
// Loaded as a classic (non-module) Babel-transformed script - see
// index.html's header comment. React 19 ships no UMD global, so
// `window.React` here is the bridge index.html's ESM import sets up; hooks
// are called as `React.useState` etc. (fully qualified, not destructured at
// top level) because sibling classic scripts share one global lexical
// scope - a repeated top-level `const useState = ...` across files is a
// SyntaxError there, not a harmless shadow.

// Single source of truth for the "Login" link's target - every page loads
// this same Navbar.jsx, so changing this one constant updates the link
// everywhere at once. Update when the deployed product's real domain changes.
const PRODUCT_APP_URL = "https://trans.upmarx.ai";

const PRODUCT_LINKS = [
  { slug: "fleet-dispatch", label: "Fleet & Dispatch" },
  { slug: "sales-orders", label: "Sales Orders" },
  { slug: "purchase-grn", label: "Purchase Orders & GRN" },
  { slug: "inventory", label: "Inventory Management" },
  { slug: "warehouses", label: "Multi-Warehouse Management" },
  { slug: "production-workflow", label: "Production & WIP Workflow Engine" },
  { slug: "business-rules", label: "Business Rules Engine" },
  { slug: "analytics-dashboards", label: "Analytics & Dashboards" },
  { slug: "ai-assistant", label: "AI Business Assistant" },
  { slug: "customer-portal", label: "Customer Portal" },
  { slug: "customers", label: "Customer Management" },
  { slug: "vendors", label: "Vendor Management" },
  { slug: "brokers", label: "Broker Management" },
  { slug: "roles-permissions", label: "Roles & Permissions" },
  { slug: "localization", label: "Localization & Multi-Language" },
];

const SOLUTION_LINKS = [
  { slug: "manufacturing", label: "Manufacturing SMEs" },
  { slug: "processing", label: "Processing & Converting" },
  { slug: "distribution", label: "Distribution & Logistics" },
];

const COMPARE_LINKS = [
  { slug: "skelbiz-vs-tally-zoho-odoo", label: "Full Comparison" },
  { slug: "vs-tally-prime", label: "vs Tally Prime" },
  { slug: "vs-zoho", label: "vs Zoho" },
  { slug: "vs-odoo", label: "vs Odoo" },
];

const SIMPLE_LINKS = [
  { path: "/pricing", label: "Pricing" },
  { path: "/security", label: "Security & Trust" },
];

function ChevronIcon({ open }) {
  return (
    <svg
      className={`h-3.5 w-3.5 transition-transform ${open ? "rotate-180" : ""}`}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.5"
    >
      <path d="M6 9l6 6 6-6" />
    </svg>
  );
}

function MenuIcon() {
  return (
    <svg className="h-6 w-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path strokeLinecap="round" d="M4 7h16M4 12h16M4 17h16" />
    </svg>
  );
}

function CloseIcon() {
  return (
    <svg className="h-6 w-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path strokeLinecap="round" d="M6 6l12 12M18 6L6 18" />
    </svg>
  );
}

function DesktopDropdown({ label, isOpen, onToggle, onClose, children }) {
  const ref = React.useRef(null);
  // Closing because a real nav link was clicked (page is about to unload for
  // a full reload - this site has no client-side routing) skips the fade/
  // translate transition entirely, instead of animating it. Full-page
  // navigation means the outgoing page can sit visible for a while longer
  // while the new page's CDN scripts (Tailwind, Babel, React) load, so an
  // animated close left a mid-transition dropdown frame hanging/flickering
  // during that gap - reported as "submenu opening with fluctuation and
  // disappearing" when clicking Pricing right after opening Product/Solutions.
  // Closing by clicking elsewhere on the same page still animates normally.
  const [instantClose, setInstantClose] = React.useState(false);

  React.useEffect(() => {
    if (isOpen) setInstantClose(false);
  }, [isOpen]);

  React.useEffect(() => {
    if (!isOpen) return;
    const onClickAway = (e) => {
      if (ref.current && !ref.current.contains(e.target)) {
        setInstantClose(!!e.target.closest("a[href]"));
        onClose();
      }
    };
    document.addEventListener("mousedown", onClickAway);
    return () => document.removeEventListener("mousedown", onClickAway);
  }, [isOpen, onClose]);

  return (
    <div className="relative" ref={ref}>
      <button
        type="button"
        onClick={onToggle}
        className="flex items-center gap-1 text-sm font-medium text-slate-600 transition hover:text-brand-navy"
      >
        {label}
        <ChevronIcon open={isOpen} />
      </button>
      {/* Left-anchored (not centered under the trigger) - a centered dropdown
          wider than the space to either side of its trigger clips off-screen
          at in-between widths (confirmed at 1024px: a centered 720px panel
          ran off the left edge entirely). Each menu's own content div caps
          its width against the viewport (max-w-[90vw]) rather than this
          shell, since a fixed-width child ignores a max-width set only on
          its positioned ancestor. */}
      <div
        className={`absolute left-0 top-full z-40 mt-3 ${instantClose ? "" : "transition duration-150"} ${
          isOpen ? "pointer-events-auto translate-y-0 opacity-100" : "pointer-events-none -translate-y-2 opacity-0"
        }`}
      >
        {children}
      </div>
    </div>
  );
}

function Navbar() {
  // Real per-path navigation now (see index.html's header comment) - every
  // link is a full page load, so the active path only needs to be read
  // once at mount, not tracked via a router prop/listener.
  const route = window.location.pathname;
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [mobileProductOpen, setMobileProductOpen] = React.useState(false);
  const [mobileSolutionOpen, setMobileSolutionOpen] = React.useState(false);
  const [mobileCompareOpen, setMobileCompareOpen] = React.useState(false);
  const [desktopMenu, setDesktopMenu] = React.useState(null); // "product" | "solutions" | "compare" | null

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

  const isActive = (path) => route === path || route.startsWith(path + "/");

  return (
    <header className="sticky top-0 z-50 border-b border-slate-200 bg-surface-card/95 backdrop-blur">
      <div className="mx-auto flex h-16 max-w-7xl items-center justify-between px-6">
        <a href="/" className="flex items-center">
          <img
            src="/src/assets/skelbiz-lockup.png"
            alt="SkelBiz - Manufacturing Operations Automation Platform"
            className="h-7 w-auto"
          />
        </a>

        {/* Desktop nav */}
        <nav className="hidden items-center gap-8 xl:flex">
          <DesktopDropdown
            label="Product"
            isOpen={desktopMenu === "product"}
            onToggle={() => setDesktopMenu((m) => (m === "product" ? null : "product"))}
            onClose={() => setDesktopMenu(null)}
          >
            <div className="grid w-[720px] max-w-[90vw] grid-cols-3 gap-1 rounded-card border border-slate-200 bg-surface-card p-3 shadow-premium">
              {PRODUCT_LINKS.map((link) => (
                <a
                  key={link.slug}
                  href={`/product/${link.slug}/`}
                  className={`rounded-lg px-3 py-2.5 text-sm font-medium transition hover:bg-surface ${
                    isActive(`/product/${link.slug}`) ? "text-emerald-700" : "text-slate-600 hover:text-brand-navy"
                  }`}
                >
                  {link.label}
                </a>
              ))}
            </div>
          </DesktopDropdown>

          <DesktopDropdown
            label="Solutions"
            isOpen={desktopMenu === "solutions"}
            onToggle={() => setDesktopMenu((m) => (m === "solutions" ? null : "solutions"))}
            onClose={() => setDesktopMenu(null)}
          >
            <div className="w-64 rounded-card border border-slate-200 bg-surface-card p-3 shadow-premium">
              {SOLUTION_LINKS.map((link) => (
                <a
                  key={link.slug}
                  href={`/solutions/${link.slug}/`}
                  className="block rounded-lg px-3 py-2.5 text-sm font-medium text-slate-600 transition hover:bg-surface hover:text-brand-navy"
                >
                  {link.label}
                </a>
              ))}
            </div>
          </DesktopDropdown>

          <DesktopDropdown
            label="Compare"
            isOpen={desktopMenu === "compare"}
            onToggle={() => setDesktopMenu((m) => (m === "compare" ? null : "compare"))}
            onClose={() => setDesktopMenu(null)}
          >
            <div className="w-64 rounded-card border border-slate-200 bg-surface-card p-3 shadow-premium">
              {COMPARE_LINKS.map((link) => (
                <a
                  key={link.slug}
                  href={`/${link.slug}/`}
                  className="block rounded-lg px-3 py-2.5 text-sm font-medium text-slate-600 transition hover:bg-surface hover:text-brand-navy"
                >
                  {link.label}
                </a>
              ))}
            </div>
          </DesktopDropdown>

          {SIMPLE_LINKS.map((link) => (
            <a
              key={link.path}
              href={`${link.path}/`}
              className={`text-sm font-medium transition hover:text-brand-navy ${
                isActive(link.path) ? "text-emerald-700" : "text-slate-600"
              }`}
            >
              {link.label}
            </a>
          ))}

          <a href="/resources/" className="text-sm font-medium text-slate-600 transition hover:text-brand-navy">
            Resources
          </a>
          <a href="/about/" className="text-sm font-medium text-slate-600 transition hover:text-brand-navy">
            Company
          </a>
        </nav>

        <div className="hidden items-center gap-3 xl:flex">
          <a
            href={PRODUCT_APP_URL}
            className="rounded-card border-2 border-emerald-600 px-5 py-2 text-sm font-semibold text-emerald-700 transition hover:bg-emerald-50"
          >
            Login
          </a>
          <a
            href="/request-demo/"
            className="rounded-card bg-emerald-600 px-5 py-2.5 text-sm font-semibold text-white shadow-card transition hover:bg-emerald-700"
          >
            Request a Demo
          </a>
        </div>

        {/* Mobile controls */}
        <div className="flex items-center gap-3 xl:hidden">
          <a
            href="/request-demo/"
            className="rounded-card bg-emerald-600 px-3.5 py-2 text-xs font-semibold text-white shadow-card transition hover:bg-emerald-700"
          >
            Request a Demo
          </a>
          <button
            type="button"
            aria-label={mobileOpen ? "Close menu" : "Open menu"}
            onClick={() => setMobileOpen((o) => !o)}
            className="flex h-10 w-10 items-center justify-center rounded-lg border border-slate-200 text-brand-navy"
          >
            {mobileOpen ? <CloseIcon /> : <MenuIcon />}
          </button>
        </div>
      </div>

      {/* Mobile drawer */}
      <div
        className={`overflow-hidden border-t border-slate-200 bg-surface-card transition-[max-height] duration-300 xl:hidden ${
          mobileOpen ? "max-h-[32rem] overflow-y-auto" : "max-h-0"
        }`}
      >
        <div className="space-y-1 px-6 py-4">
          <a
            href={PRODUCT_APP_URL}
            className="mb-2 flex w-full items-center justify-center rounded-card border-2 border-emerald-600 px-4 py-2.5 text-sm font-semibold text-emerald-700 transition hover:bg-emerald-50"
          >
            Login
          </a>
          <button
            type="button"
            onClick={() => setMobileProductOpen((o) => !o)}
            className="flex w-full items-center justify-between py-2.5 text-sm font-semibold text-brand-navy"
          >
            Product
            <ChevronIcon open={mobileProductOpen} />
          </button>
          {mobileProductOpen && (
            <div className="grid grid-cols-1 gap-0.5 pb-2 pl-3">
              {PRODUCT_LINKS.map((link) => (
                <a
                  key={link.slug}
                  href={`/product/${link.slug}/`}
                  className="rounded-lg px-2 py-2 text-sm text-slate-600 hover:bg-surface hover:text-brand-navy"
                >
                  {link.label}
                </a>
              ))}
            </div>
          )}

          <button
            type="button"
            onClick={() => setMobileSolutionOpen((o) => !o)}
            className="flex w-full items-center justify-between py-2.5 text-sm font-semibold text-brand-navy"
          >
            Solutions
            <ChevronIcon open={mobileSolutionOpen} />
          </button>
          {mobileSolutionOpen && (
            <div className="grid grid-cols-1 gap-0.5 pb-2 pl-3">
              {SOLUTION_LINKS.map((link) => (
                <a
                  key={link.slug}
                  href={`/solutions/${link.slug}/`}
                  className="rounded-lg px-2 py-2 text-sm text-slate-600 hover:bg-surface hover:text-brand-navy"
                >
                  {link.label}
                </a>
              ))}
            </div>
          )}

          <button
            type="button"
            onClick={() => setMobileCompareOpen((o) => !o)}
            className="flex w-full items-center justify-between py-2.5 text-sm font-semibold text-brand-navy"
          >
            Compare
            <ChevronIcon open={mobileCompareOpen} />
          </button>
          {mobileCompareOpen && (
            <div className="grid grid-cols-1 gap-0.5 pb-2 pl-3">
              {COMPARE_LINKS.map((link) => (
                <a
                  key={link.slug}
                  href={`/${link.slug}/`}
                  className="rounded-lg px-2 py-2 text-sm text-slate-600 hover:bg-surface hover:text-brand-navy"
                >
                  {link.label}
                </a>
              ))}
            </div>
          )}

          {SIMPLE_LINKS.map((link) => (
            <a
              key={link.path}
              href={`${link.path}/`}
              className="block py-2.5 text-sm font-semibold text-brand-navy"
            >
              {link.label}
            </a>
          ))}
          <a href="/resources/" className="block py-2.5 text-sm font-semibold text-brand-navy">
            Resources
          </a>
          <a href="/about/" className="block py-2.5 text-sm font-semibold text-brand-navy">
            Company
          </a>
        </div>
      </div>
    </header>
  );
}
