/* global React, IconChevDown, IconArrowRight, IconMenu, IconX */
const { useState: useNavState, useEffect: useNavEffect, useRef: useNavRef } = React;

const NAV_STRUCTURE = [
  {
    label: "AORBIT",
    headline: "The Autonomous Enterprise Intelligence Suite.",
    sub: "Private AI infrastructure that evolves.",
    items: [
      { label: "Overview", route: "/aorbit", sub: "How AORBIT maps to your stack" },
      { label: "01 Foundation", route: "/aorbit/foundation", sub: "Private AI infrastructure" },
      { label: "02 Intelligence", route: "/aorbit/intelligence", sub: "Multi-LLM orchestration · AIOps" },
      { label: "03 Frontier", route: "/aorbit/frontier", sub: "Agents · Treasury · Payments" },
      { label: "Architecture", route: "/aorbit/architecture", sub: "5-layer reference architecture" },
    ],
  },
  {
    label: "Services",
    headline: "Specialists, training, and R&D for enterprise AI.",
    sub: "Build with us, or train your team to build.",
    items: [
      { label: "Resource Augmentation", route: "/services/augmentation", sub: "Embedded specialists in your team" },
      { label: "Corporate Training", route: "/services/training", sub: "Architecture-first AI training" },
      { label: "Applied Research", route: "/services/research", sub: "R&D for your roadmap" },
    ],
  },
  {
    label: "Industries",
    headline: "Architecture for regulated industries.",
    sub: "Where data sovereignty is non-negotiable.",
    items: [
      { label: "Banking & Finance", route: "/industries/banking", sub: "Tier-1 production deployments" },
      { label: "Digital Assets", route: "/industries/digital-assets", sub: "Agentic finance, AgentPay rails" },
      { label: "Government", route: "/industries/government", sub: "Sovereign AI for the public sector" },
    ],
  },
  {
    label: "Why Doblier",
    headline: "Why architecture matters more than AI tools.",
    sub: "The named gap between AI capability and enterprise readiness.",
    items: [
      { label: "The Architecture Gap", route: "/why-doblier/architecture-gap", sub: "Flagship whitepaper" },
      { label: "Data Sovereignty", route: "/why-doblier/data-sovereignty", sub: "Build where the data lives" },
      { label: "Case Studies", route: "/why-doblier/case-studies", sub: "Production track record" },
      { label: "Security & Trust", route: "/why-doblier/security", sub: "Compliance & documentation" },
    ],
  },
  {
    label: "Resources",
    headline: "Thought leadership and research on enterprise AI architecture.",
    sub: "Long-form thinking from the team building the back.",
    items: [
      { label: "Blog / Insights", route: "/resources/blog", sub: "Field notes from production" },
      { label: "Whitepapers", route: "/resources/whitepapers", sub: "Architecture briefs and research" },
    ],
  },
  {
    label: "Company",
    headline: "Founded 2019. California HQ. Global operations.",
    sub: "An architecture firm that ships production AI.",
    items: [
      { label: "About Doblier", route: "/company/about", sub: "Who we are and why" },
      { label: "Careers", route: "/company/careers", sub: "Build the back" },
    ],
  },
];

function Nav({ route, navigate }) {
  const [openIdx, setOpenIdx] = useNavState(null);
  const [scrolled, setScrolled] = useNavState(false);
  const [mobileOpen, setMobileOpen] = useNavState(false);
  const navRef = useNavRef(null);
  const closeTimer = useNavRef(null);

  // Sticky-nav scroll state: background opacity bumps to ~95%, logo shrinks slightly.
  // CTA button stays full size. (Chunk 2 § Nav dev note.)
  useNavEffect(() => {
    const onScroll = () => {
      setOpenIdx(null);
      setScrolled(window.scrollY > 12);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Mobile drawer: lock body scroll while open + close on Escape.
  // Mirrors the gated-download modal pattern.
  useNavEffect(() => {
    if (!mobileOpen) return;
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") setMobileOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKey);
    };
  }, [mobileOpen]);

  // Auto-close the drawer whenever the route changes (hash-based routing
  // re-renders Nav with a new `route` prop on every navigate()).
  useNavEffect(() => { setMobileOpen(false); }, [route]);

  const onOpen = (i) => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    setOpenIdx(i);
  };
  const onLeave = () => {
    closeTimer.current = setTimeout(() => setOpenIdx(null), 120);
  };

  const isActive = (label) => {
    const map = {
      AORBIT: "/aorbit",
      Services: "/services",
      Industries: "/industries",
      "Why Doblier": "/why-doblier",
      Resources: "/resources",
      Company: "/company",
    };
    return route.startsWith(map[label] || "___");
  };

  return (
    <React.Fragment>
    <nav className={`nav ${scrolled ? "scrolled" : ""}`} ref={navRef} onMouseLeave={onLeave}>
      <div className="nav-inner">
        <a className="nav-logo" onClick={(e) => { e.preventDefault(); navigate("/"); }} href="#/">
          <img src="site/assets/doblier_horizontal.svg" alt="DOBLIER" />
        </a>

        <div className="nav-items">
          {NAV_STRUCTURE.map((section, i) => (
            <button
              key={section.label}
              className={`nav-item ${isActive(section.label) ? "active" : ""} ${openIdx === i ? "open" : ""}`}
              onMouseEnter={() => onOpen(i)}
              onClick={() => {
                if (section.items[0]) navigate(section.items[0].route);
              }}
            >
              {section.label}
              <IconChevDown size={10} stroke={2} className="chev" />
            </button>
          ))}
        </div>

        <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
          <button className="btn btn-primary nav-cta" onClick={() => navigate("/talk-to-an-architect")}>
            Talk to an architect
            <IconArrowRight size={14} className="arrow" />
          </button>
          <button
            className="nav-burger"
            aria-label={mobileOpen ? "Close menu" : "Open menu"}
            aria-expanded={mobileOpen}
            aria-controls="mobile-drawer"
            onClick={() => setMobileOpen((v) => !v)}
          >
            {mobileOpen ? <IconX size={22} stroke={1.6} /> : <IconMenu size={22} stroke={1.6} />}
          </button>
        </div>
      </div>

      {openIdx !== null && (
        <div className="mega" onMouseEnter={() => onOpen(openIdx)} onMouseLeave={onLeave}>
          <div className="mega-inner">
            <div className="mega-headline">
              <span className="mono">// {NAV_STRUCTURE[openIdx].label.toUpperCase()}</span>
              {NAV_STRUCTURE[openIdx].headline}
              <div style={{ fontSize: 14, color: "var(--text-mute)", marginTop: 12, fontWeight: 400 }}>
                {NAV_STRUCTURE[openIdx].sub}
              </div>
            </div>
            <div className="mega-grid">
              {NAV_STRUCTURE[openIdx].items.map((item) => (
                <a
                  key={item.route}
                  className="mega-link"
                  href={`#${item.route}`}
                  onClick={(e) => { e.preventDefault(); navigate(item.route); setOpenIdx(null); }}
                >
                  {item.label}
                  <span className="sub">{item.sub}</span>
                </a>
              ))}
            </div>
          </div>
        </div>
      )}
    </nav>

      {mobileOpen && (
        <div
          className="nav-drawer"
          id="mobile-drawer"
          onClick={(e) => { if (e.target === e.currentTarget) setMobileOpen(false); }}
        >
          <div className="nav-drawer-inner">
            {NAV_STRUCTURE.map((section) => (
              <div key={section.label} className="nav-drawer-group">
                <div className="nav-drawer-label mono">// {section.label.toUpperCase()}</div>
                {section.items.map((item) => (
                  <a
                    key={item.route}
                    className="nav-drawer-link"
                    href={`#${item.route}`}
                    onClick={(e) => { e.preventDefault(); navigate(item.route); }}
                  >
                    {item.label}
                    <span className="sub">{item.sub}</span>
                  </a>
                ))}
              </div>
            ))}
            <button
              className="btn btn-primary nav-drawer-cta"
              onClick={() => navigate("/talk-to-an-architect")}
            >
              Talk to an architect
              <IconArrowRight size={14} className="arrow" />
            </button>
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

/* Footer follows Chunk 2 spec exactly:
   Col1 = logo + tagline + founding line.
   Col2 AORBIT · Col3 Company · Col4 Resources · Col5 Contact.
   Bottom bar: copyright + Privacy/Terms/Cookies + social icons (LinkedIn / X / GitHub).
*/
function Footer({ navigate }) {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-grid">
          <div>
            <img src="site/assets/doblier_stacked.svg" alt="DOBLIER" className="footer-logo" />
            <div className="footer-tag">// Enterprise AI Infrastructure</div>
            <p style={{ color: "var(--text-dim)", maxWidth: 320, lineHeight: 1.6, marginTop: 16, fontSize: 14 }}>
              Private AI infrastructure that absorbs change. Built where your data lives. Deployed in production.
            </p>
            <div style={{ marginTop: 24, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-mute)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
              Founded 2019 · California, USA
            </div>
            <address style={{ marginTop: 16, fontStyle: "normal", color: "var(--text-dim)", fontSize: 13, lineHeight: 1.55 }}>
              1750 Prairie City Rd #130<br />
              Folsom, CA 95630<br />
              United States
            </address>
          </div>

          <div>
            <h5>AORBIT™</h5>
            <ul>
              <li onClick={() => navigate("/aorbit")}>Overview</li>
              <li onClick={() => navigate("/aorbit/foundation")}>01 Foundation</li>
              <li onClick={() => navigate("/aorbit/intelligence")}>02 Intelligence</li>
              <li onClick={() => navigate("/aorbit/frontier")}>03 Frontier</li>
              <li onClick={() => navigate("/aorbit/architecture")}>Architecture</li>
            </ul>
          </div>

          <div>
            <h5>Company</h5>
            <ul>
              <li onClick={() => navigate("/services/augmentation")}>Services</li>
              <li onClick={() => navigate("/industries/banking")}>Industries</li>
              <li onClick={() => navigate("/why-doblier/architecture-gap")}>Why Doblier</li>
              <li onClick={() => navigate("/company/about")}>About</li>
              <li onClick={() => navigate("/company/careers")}>Careers</li>
            </ul>
          </div>

          <div>
            <h5>Resources</h5>
            <ul>
              <li onClick={() => navigate("/resources/blog")}>Blog</li>
              <li onClick={() => navigate("/resources/whitepapers")}>Whitepapers</li>
              <li onClick={() => navigate("/why-doblier/case-studies")}>Case Studies</li>
              <li onClick={() => navigate("/why-doblier/security")}>Security & Trust</li>
            </ul>
          </div>

          <div>
            <h5>Contact</h5>
            <ul>
              <li onClick={() => navigate("/talk-to-an-architect")}>Talk to an architect</li>
              <li onClick={() => navigate("/aorbit")}>See AORBIT in action</li>
              <li>
                <a href="mailto:hello@doblier.io" style={{ color: "inherit", textDecoration: "none" }}>hello@doblier.io</a>
              </li>
              <li>
                <a href="tel:+16282293590" style={{ color: "inherit", textDecoration: "none" }}>+1 628 229 3590</a>
              </li>
            </ul>
          </div>
        </div>

        <div className="footer-base">
          <div className="footer-legal">
            <div className="footer-copy">
              © 2026 Doblier Inc. All rights reserved.
              <span className="footer-tm">DOBLIER™, AORBIT™, and The Architecture Gap™ are trademarks of Doblier Inc.</span>
            </div>
            <div className="footer-legal-links">
              <a className="legal" href="#/privacy" onClick={(e) => { e.preventDefault(); navigate("/privacy"); }}>Privacy Policy</a>
              <span className="sep">·</span>
              <a className="legal" href="#/terms" onClick={(e) => { e.preventDefault(); navigate("/terms"); }}>Terms of Use</a>
              <span className="sep">·</span>
              <a className="legal" href="#/cookies" onClick={(e) => { e.preventDefault(); navigate("/cookies"); }}>Cookie Policy</a>
              <span className="sep">·</span>
              <a className="legal" onClick={(e) => { e.preventDefault(); window.reopenCookieSettings && window.reopenCookieSettings(); }}>Cookie Settings</a>
              <span className="sep">·</span>
              <a className="legal" href="#/privacy" onClick={(e) => { e.preventDefault(); navigate("/privacy"); setTimeout(() => { const el = document.getElementById("ccpa-opt-out"); if (el) window.scrollTo({ top: el.offsetTop - 88, behavior: "smooth" }); }, 80); }}>Do Not Sell or Share My Personal Information</a>
              <span className="sep">·</span>
              <a className="legal" href="#/accessibility" onClick={(e) => { e.preventDefault(); navigate("/accessibility"); }}>Accessibility</a>
            </div>
          </div>
          <div className="social-row" aria-label="Social">
            <a href="https://www.linkedin.com/company/doblier" target="_blank" rel="noopener noreferrer" className="social" aria-label="LinkedIn">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
                <rect x="3" y="3" width="18" height="18" rx="2" />
                <path d="M8 10v7" />
                <circle cx="8" cy="7" r="0.6" fill="currentColor" />
                <path d="M12 17v-4a2 2 0 0 1 4 0v4" />
                <path d="M12 10v7" />
              </svg>
            </a>
            <a href="https://x.com/doblier_io" target="_blank" rel="noopener noreferrer" className="social" aria-label="X (Twitter)">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="square">
                <path d="M4 4 L20 20 M20 4 L4 20" />
              </svg>
            </a>
            <a href="https://github.com/Doblier/" target="_blank" rel="noopener noreferrer" className="social" aria-label="GitHub">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
                <path d="M12 3a9 9 0 0 0-2.85 17.54c.45.09.61-.2.61-.43v-1.5c-2.5.55-3.03-1.07-3.03-1.07-.41-1.04-1-1.32-1-1.32-.82-.56.06-.55.06-.55.91.06 1.39.93 1.39.93.81 1.39 2.12.99 2.64.75.08-.58.32-.99.57-1.22-2-.23-4.1-1-4.1-4.45 0-.98.35-1.79.93-2.42-.09-.23-.4-1.15.09-2.4 0 0 .76-.24 2.49.93a8.6 8.6 0 0 1 4.54 0c1.73-1.17 2.49-.93 2.49-.93.49 1.25.18 2.17.09 2.4.58.63.93 1.44.93 2.42 0 3.46-2.11 4.22-4.11 4.44.33.28.61.83.61 1.68v2.5c0 .24.16.53.62.43A9 9 0 0 0 12 3Z" />
              </svg>
            </a>
            <a href="https://www.instagram.com/doblier.io" target="_blank" rel="noopener noreferrer" className="social" aria-label="Instagram">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
                <rect x="3" y="3" width="18" height="18" rx="5" />
                <circle cx="12" cy="12" r="4" />
                <circle cx="17.3" cy="6.7" r="0.7" fill="currentColor" stroke="none" />
              </svg>
            </a>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Nav, Footer, NAV_STRUCTURE });
