/* ========================================================
   Navigation with mega-menu + mobile drawer
   ======================================================== */
const { useState, useEffect, useRef } = React;

// Global menu model — shared across every page
const MENU = {
  Services: {
    columns: [
      {
        label: "AI ENGINEERING", icon: "agents",
        items: [
          ["AI Agents", "services-agents.html", "Multi-step reasoning"],
          ["RAG & Knowledge", "services-rag.html", "Grounded retrieval"],
          ["Voice AI", "services-voice.html", "Sub-second telephony"],
          ["Workflow Automation", "services-flow.html", "Agentic pipelines"],
        ],
      },
      {
        label: "PRODUCT & STRATEGY", icon: "stack",
        items: [
          ["Full-Stack AI Products", "services-stack.html", "End-to-end builds"],
          ["AI Consulting", "services-consult.html", "Fractional CTO"],
          ["Architecture Reviews", "services-consult.html#reviews", "Audit + roadmap"],
          ["Fractional CTO", "services-consult.html#cto", "10–20 hrs/wk"],
        ],
      },
      {
        label: "DELIVERY MODELS", icon: "flow",
        items: [
          ["Discovery Sprints", "services.html#sprints", "2 weeks, fixed cost"],
          ["Retainer Teams", "services.html#retainer", "Dedicated squads"],
          ["Staff Augmentation", "services.html#staff", "Senior-only"],
          ["Build-Operate-Transfer", "services.html#bot", "India delivery"],
        ],
      },
    ],
    feature: {
      tag: "FEATURED WORK",
      title: "Meridian Claims · Insurance",
      body: "Five agents replaced a 40-person triage team.",
      metric: "92% auto-resolution",
      href: "case-meridian.html",
    },
  },
  Technology: {
    columns: [
      {
        label: "FOUNDATION MODELS", icon: "consult",
        items: [
          ["Claude", "technology.html#claude", "Anthropic"],
          ["OpenAI", "technology.html#openai", "GPT + Realtime"],
          ["Gemini", "technology.html#gemini", "Google"],
          ["Open source", "technology.html#oss", "Llama, Mistral"],
        ],
      },
      {
        label: "ORCHESTRATION", icon: "agents",
        items: [
          ["LangGraph", "technology.html#langgraph", ""],
          ["LangChain", "technology.html#langchain", ""],
          ["Temporal", "technology.html#temporal", ""],
          ["n8n", "technology.html#n8n", ""],
        ],
      },
      {
        label: "DATA & INFRA", icon: "rag",
        items: [
          ["Pinecone · pgvector", "technology.html#vectors", ""],
          ["LlamaIndex", "technology.html#llamaindex", ""],
          ["Postgres · Redis", "technology.html#data", ""],
          ["AWS · GCP · Fly", "technology.html#infra", ""],
        ],
      },
    ],
  },
  Industries: {
    columns: [
      {
        label: "SECTORS WE SERVE", icon: "stack",
        items: [
          ["Hospitality", "industry-hospitality.html", "Voice + reservations"],
          ["Fintech", "industry-fintech.html", "Research + compliance"],
          ["Insurance", "industry-insurance.html", "Claims triage"],
          ["Real Estate", "industry-realestate.html", "Lead qualification"],
        ],
      },
      {
        label: "", icon: "flow",
        items: [
          ["MSP", "industry-msp.html", "Ticket automation"],
          ["Construction", "industry-construction.html", "Bid + estimation"],
          ["Healthcare", "industry-healthcare.html", "Intake + scheduling"],
          ["Legal", "industry-legal.html", "Document review"],
        ],
      },
    ],
  },
  Company: {
    columns: [
      {
        label: "ABOUT US", icon: "consult",
        items: [
          ["About Mindlytic", "about.html", "Team, story, values"],
          ["Leadership", "about.html#leadership", ""],
          ["Locations", "about.html#locations", "NJ + Surat"],
          ["Press", "about.html#press", ""],
        ],
      },
      {
        label: "RESOURCES", icon: "rag",
        items: [
          ["Clients", "clients.html", "Logo wall + quotes"],
          ["Portfolio", "portfolio.html", "All case studies"],
          ["Careers", "careers.html", "9 open roles"],
          ["Journal", "journal.html", "Writing + talks"],
        ],
      },
    ],
  },
};

function Wordmark({ big }) {
  return (
    <a href="index.html" className="wordmark" aria-label="Mindlytic AI home">
      <svg width={big ? 30 : 26} height={big ? 30 : 26} viewBox="0 0 26 26" fill="none" aria-hidden>
        <rect x="0.75" y="0.75" width="24.5" height="24.5" rx="6.5" stroke="currentColor" strokeOpacity="0.35"/>
        <path d="M6.5 18V8l3.5 5 3-3.5 3 3.5L19.5 8v10" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
        <circle cx="13" cy="9.5" r="1.4" fill="var(--accent)"/>
      </svg>
      <span className="wm-text">
        Mindlytic<span className="wm-ai">/ai</span>
      </span>
      <style>{`
        .wordmark { display: inline-flex; align-items: center; gap: 10px; color: var(--text); }
        .wm-text { font-size: 15.5px; font-weight: 600; letter-spacing: -0.015em; }
        .wm-ai { color: var(--text-3); font-family: var(--font-mono); font-weight: 500; font-size: 13px; margin-left: 2px; }
      `}</style>
    </a>
  );
}

function MegaPanel({ menu, onLeave }) {
  return (
    <div className="mega" onMouseLeave={onLeave}>
      <div className="container mega-inner">
        <div className="mega-cols" style={{gridTemplateColumns: `repeat(${menu.columns.length}, 1fr) ${menu.feature ? "1.1fr" : ""}`}}>
          {menu.columns.map((col, ci) => (
            <div className="mega-col" key={ci}>
              {col.label && <div className="mega-col-label mono">{col.label}</div>}
              <ul>
                {col.items.map(([name, href, desc]) => (
                  <li key={name}>
                    <a href={href}>
                      <span className="mega-item-name">{name}</span>
                      {desc && <span className="mega-item-desc">{desc}</span>}
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
          {menu.feature && (
            <a className="mega-feature" href={menu.feature.href}>
              <div className="mono mega-feat-tag">{menu.feature.tag}</div>
              <div className="mega-feat-title">{menu.feature.title}</div>
              <div className="mega-feat-body">{menu.feature.body}</div>
              <div className="mega-feat-metric">
                <span>{menu.feature.metric}</span>
                <I.Arrow size={14}/>
              </div>
            </a>
          )}
        </div>
      </div>
      <style>{`
        .mega {
          position: absolute; left: 0; right: 0; top: 100%;
          background: color-mix(in oklab, var(--bg-soft) 96%, transparent);
          backdrop-filter: blur(14px) saturate(140%);
          border-top: 1px solid var(--border);
          border-bottom: 1px solid var(--border);
          padding: 40px 0;
          animation: megaIn .2s ease-out;
        }
        @keyframes megaIn { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }
        .mega-cols { display: grid; gap: 48px; }
        .mega-col-label { font-size: 10px; color: var(--text-4); margin-bottom: 16px; letter-spacing: 0.14em; }
        .mega-col ul { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 4px; }
        .mega-col a {
          display: block; padding: 10px 12px; margin: 0 -12px;
          border-radius: 8px;
          transition: background-color .15s, color .15s;
        }
        .mega-col a:hover { background: var(--surface); }
        .mega-item-name { display: block; font-size: 14.5px; font-weight: 500; color: var(--text); letter-spacing: -0.01em; }
        .mega-item-desc { display: block; font-size: 12px; color: var(--text-4); margin-top: 2px; }
        .mega-col a:hover .mega-item-name { color: var(--accent); }
        .mega-feature {
          position: relative;
          display: flex; flex-direction: column;
          padding: 24px;
          border: 1px solid var(--border-2);
          border-radius: 12px;
          background: linear-gradient(180deg, var(--surface), var(--bg-soft));
          overflow: hidden;
          transition: border-color .2s;
        }
        .mega-feature:hover { border-color: var(--accent-line); }
        .mega-feature::before {
          content: ""; position: absolute; inset: 0;
          background: radial-gradient(ellipse 80% 60% at 100% 0%, var(--accent-soft), transparent 60%);
          pointer-events: none;
        }
        .mega-feat-tag { font-size: 10px; color: var(--accent); margin-bottom: 10px; }
        .mega-feat-title { font-size: 18px; font-weight: 600; letter-spacing: -0.02em; margin-bottom: 8px; }
        .mega-feat-body { font-size: 13.5px; color: var(--text-3); line-height: 1.5; flex: 1; }
        .mega-feat-metric {
          display: flex; align-items: center; justify-content: space-between;
          margin-top: 16px; padding-top: 14px;
          border-top: 1px solid var(--border);
          font-family: var(--font-mono); font-size: 11.5px; color: var(--accent);
          letter-spacing: 0.06em;
        }
      `}</style>
    </div>
  );
}

function Nav({ onOpenMenu, current }) {
  const [scrolled, setScrolled] = useState(false);
  const [openKey, setOpenKey] = useState(null);
  const hoverTimer = useRef(null);

  useEffect(() => {
    const f = () => setScrolled(window.scrollY > 8);
    f();
    window.addEventListener("scroll", f, { passive: true });
    return () => window.removeEventListener("scroll", f);
  }, []);

  const onEnter = (k) => {
    clearTimeout(hoverTimer.current);
    setOpenKey(k);
  };
  const onLeaveDelay = () => {
    hoverTimer.current = setTimeout(() => setOpenKey(null), 120);
  };

  // Direct links
  const direct = [
    ["Portfolio", "portfolio.html"],
    ["Clients", "clients.html"],
    ["Careers", "careers.html"],
  ];

  return (
    <header className={"nav " + (scrolled ? "nav--scrolled" : "") + (openKey ? " nav--open" : "")} role="banner"
      onMouseLeave={onLeaveDelay}>
      <div className="nav-inner container">
        <Wordmark />
        <nav className="nav-links" aria-label="Primary">
          {Object.keys(MENU).map((k) => (
            <button
              key={k}
              className={"nav-link nav-link--menu " + (openKey === k ? "active " : "") + (current === k ? "current" : "")}
              onMouseEnter={() => onEnter(k)}
              onFocus={() => onEnter(k)}
            >
              {k}
              <svg width="10" height="10" viewBox="0 0 10 10" fill="none" aria-hidden>
                <path d="M2 4l3 3 3-3" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
              </svg>
            </button>
          ))}
          {direct.map(([l, h]) => (
            <a key={l} href={h} className={"nav-link " + (current === l ? "current" : "")} onMouseEnter={() => setOpenKey(null)}>
              {l}
            </a>
          ))}
        </nav>
        <div className="nav-right">
          <a href="contact.html" className="btn btn-primary btn-sm nav-cta">
            Contact us
          </a>
          <button className="nav-menu-btn" onClick={onOpenMenu} aria-label="Open menu">
            <I.Menu/>
          </button>
        </div>
      </div>
      {openKey && <MegaPanel menu={MENU[openKey]} onLeave={onLeaveDelay}/>}
      <style>{`
        .nav {
          position: sticky; top: 0; z-index: 50;
          transition: background-color .3s, border-color .3s, backdrop-filter .3s;
          border-bottom: 1px solid transparent;
        }
        .nav-inner { height: 68px; display: flex; align-items: center; justify-content: space-between; gap: 24px; }
        .nav--scrolled, .nav--open {
          background: color-mix(in oklab, var(--bg) 72%, transparent);
          backdrop-filter: blur(12px) saturate(140%);
          -webkit-backdrop-filter: blur(12px) saturate(140%);
          border-bottom-color: var(--border);
        }
        .nav-links { display: flex; gap: 6px; align-items: center; }
        .nav-link {
          font-family: inherit;
          display: inline-flex; align-items: center; gap: 5px;
          font-size: 14px; color: var(--text-3);
          padding: 8px 12px;
          border-radius: 8px;
          transition: color .2s, background-color .2s;
          background: transparent;
        }
        .nav-link:hover, .nav-link.active, .nav-link.current { color: var(--text); }
        .nav-link.active, .nav-link.current { background: var(--surface); }
        .nav-link svg { opacity: 0.5; transition: transform .2s; }
        .nav-link.active svg { transform: rotate(180deg); }
        .nav-right { display: flex; align-items: center; gap: 12px; }
        .nav-menu-btn { display: none; color: var(--text); padding: 8px; border-radius: 8px; }
        .nav-menu-btn:hover { background: var(--surface-2); }
        @media (max-width: 1080px) {
          .nav-links { display: none; }
          .nav-menu-btn { display: inline-flex; }
          .nav-cta { display: none; }
        }
      `}</style>
    </header>
  );
}

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

  const groups = Object.entries(MENU);

  return (
    <div className={"mobile-menu " + (open ? "open" : "")} aria-hidden={!open}>
      <div className="mm-head container">
        <Wordmark/>
        <button className="mm-close" onClick={onClose} aria-label="Close menu"><I.Close/></button>
      </div>
      <nav className="mm-body container" aria-label="Mobile">
        {groups.map(([k, v], gi) => (
          <details key={k} className="mm-group">
            <summary>
              <span>{k}</span>
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M3 5l4 4 4-4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
              </svg>
            </summary>
            <div className="mm-group-body">
              {v.columns.flatMap(c => c.items).map(([name, href]) => (
                <a key={name} href={href} onClick={onClose} className="mm-sub">{name}</a>
              ))}
            </div>
          </details>
        ))}
        <a href="portfolio.html" onClick={onClose} className="mm-link">Portfolio</a>
        <a href="clients.html" onClick={onClose} className="mm-link">Clients</a>
        <a href="careers.html" onClick={onClose} className="mm-link">Careers</a>
      </nav>
      <div className="mm-foot container">
        <a href="contact.html" onClick={onClose} className="btn btn-primary" style={{width:"100%", justifyContent:"center"}}>
          Contact us <I.Arrow/>
        </a>
      </div>
      <style>{`
        .mobile-menu {
          position: fixed; inset: 0; z-index: 100;
          background: var(--bg);
          transform: translateY(-100%);
          transition: transform .35s cubic-bezier(.7,0,.2,1);
          display: flex; flex-direction: column;
          visibility: hidden; pointer-events: none;
          overflow-y: auto;
        }
        .mobile-menu.open { transform: none; visibility: visible; pointer-events: auto; }
        .mm-head { display: flex; align-items: center; justify-content: space-between; height: 68px; position: sticky; top: 0; background: var(--bg); z-index: 2; }
        .mm-close { color: var(--text); padding: 8px; }
        .mm-body { flex: 1; padding-top: 16px; display: flex; flex-direction: column; gap: 0; padding-bottom: 40px; }
        .mm-group { border-bottom: 1px solid var(--border); }
        .mm-group summary {
          display: flex; align-items: center; justify-content: space-between;
          padding: 20px 0; list-style: none; cursor: pointer;
          font-size: 22px; font-weight: 500; letter-spacing: -0.02em;
        }
        .mm-group summary::-webkit-details-marker { display: none; }
        .mm-group[open] summary svg { transform: rotate(180deg); }
        .mm-group-body { display: flex; flex-direction: column; padding: 0 0 16px; gap: 2px; }
        .mm-sub {
          padding: 10px 0;
          font-size: 15px; color: var(--text-3);
        }
        .mm-sub:hover { color: var(--accent); }
        .mm-link {
          display: flex; padding: 20px 0;
          border-bottom: 1px solid var(--border);
          font-size: 22px; font-weight: 500; color: var(--text);
          letter-spacing: -0.02em;
        }
        .mm-foot { padding: 24px 0 40px; position: sticky; bottom: 0; background: var(--bg); border-top: 1px solid var(--border); }
      `}</style>
    </div>
  );
}

Object.assign(window, { Nav, MobileMenu, Wordmark, MENU });
