// Mobile navigation: hamburger + slide-in drawer with collapsible sections.
// Renders a portal-style drawer when the hamburger is tapped.
// Uses the existing MENU data shape from hero.jsx (window.MENU is not exported,
// so we re-source it via the rendered nav-link hrefs as labels — instead, we
// rebuild a minimal menu inline keyed off the same labels).

const MobileNav = () => {
  const [open, setOpen] = React.useState(false);
  const [isMobile, setIsMobile] = React.useState(false);

  React.useEffect(() => {
    const check = () => setIsMobile(window.matchMedia('(max-width: 1024px)').matches);
    check();
    window.addEventListener('resize', check);
    return () => window.removeEventListener('resize', check);
  }, []);

  // Lock body scroll when drawer is open.
  React.useEffect(() => {
    if (open) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = prev; };
    }
  }, [open]);

  // Close drawer on Escape.
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  // Inject hamburger button into the nav-cta (mobile only).
  // The Nav is rendered by a different React root that may mount slightly
  // after us, so poll until .nav-cta exists, then keep a MutationObserver
  // running to re-inject if React re-renders the nav.
  React.useEffect(() => {
    let btn = null;
    const onClick = () => setOpen(true);
    const inject = () => {
      const cta = document.querySelector('.nav .nav-cta');
      if (!cta) return false;
      if (cta.querySelector('.qtg-hamburger')) return true;
      btn = document.createElement('button');
      btn.className = 'qtg-hamburger';
      btn.setAttribute('aria-label', 'Open menu');
      btn.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><line x1="4" y1="7" x2="20" y2="7"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="17" x2="20" y2="17"/></svg>';
      btn.addEventListener('click', onClick);
      cta.appendChild(btn);
      return true;
    };
    if (!inject()) {
      const t = setInterval(() => { if (inject()) clearInterval(t); }, 100);
      setTimeout(() => clearInterval(t), 4000);
    }
    // Re-inject on nav re-render (React replacing the subtree drops our button).
    const obs = new MutationObserver(() => {
      if (!document.querySelector('.nav .nav-cta .qtg-hamburger')) inject();
    });
    obs.observe(document.documentElement, { childList: true, subtree: true });
    return () => { obs.disconnect(); if (btn) btn.removeEventListener('click', onClick); };
  }, []);

  // Inline mobile menu data — mirrors the desktop sitemap.
  const sections = [
    { label: 'Platforms', href: 'platforms.html', items: [
      { k: 'YourPropFirm', d: 'Prop Firm Launch & Management', href: 'yourpropfirm.html' },
      { k: 'Broker Infrastructure', d: 'Tech Infrastructure for Brokers', href: 'broker-infrastructure.html' },
      { k: 'QuantSentry', d: 'Risk Monitoring & Surveillance', href: 'quantsentry.html' },
      { k: 'QuantCX', d: 'Customer Experience Tools', href: 'quantcx.html' },
      { k: 'PropTradeGroup', d: 'White-Label Prop Firm', href: 'proptradegroup.html' },
      { k: 'TradoPay', d: 'Payments & Payout Infrastructure', href: 'tradopay.html' },
    ]},
    { label: 'Components', href: 'components.html', groups: [
      { label: 'Operations & Risk', items: [
        { k: 'Prop CRM', href: 'prop-crm.html' },
        { k: 'Broker CRM', href: 'broker-crm.html' },
        { k: 'Risk & Rules Engine', href: 'risk-rules-engine.html' },
      ]},
      { label: 'Commercial', items: [
        { k: 'Checkout System', href: 'checkout-system.html' },
        { k: 'Payments & Payouts', href: 'payments-payouts.html' },
        { k: 'Affiliate & IB Management', href: 'affiliate-ib-management.html' },
        { k: 'Loyalty Program', href: 'loyalty-program.html' },
      ]},
      { label: 'Trader Experience', items: [
        { k: 'Trader Dashboard', href: 'trader-dashboard.html' },
        { k: 'Trading Journal', href: 'trading-journal.html' },
        { k: 'Trading Competitions', href: 'trading-competitions.html' },
        { k: 'Copy Trading', href: 'copy-trading.html' },
        { k: 'Algo Trading Tools', href: 'algo-trading-tools.html' },
      ]},
      { label: 'Data & Intelligence', items: [
        { k: 'Business Intelligence', href: 'business-intelligence.html' },
        { k: 'Reports & Analytics', href: 'reports-analytics.html' },
        { k: 'AI Agents', href: 'ai-agents.html' },
      ]},
    ]},
    { label: 'Industries', href: 'industries.html', items: [
      { k: 'Proprietary Trading Firms', href: 'industries/prop-trading-firms.html' },
      { k: 'Brokers', href: 'industries/brokers.html' },
      { k: 'Fintech & Trading Platforms', href: 'industries/fintech-platforms.html' },
      { k: 'Trading Academies & Communities', href: 'industries/academies-communities.html' },
      { k: 'Professional Trading Teams', href: 'industries/professional-teams.html' },
      { k: 'Funds & Asset Managers', href: 'industries/funds-asset-managers.html' },
      { k: 'Liquidity Providers', href: 'industries/liquidity-providers.html' },
    ]},
    { label: 'Services', href: 'services.html', items: [
      { k: 'Dedicated Tech Teams', href: 'dedicated-tech-teams.html' },
      { k: 'Customer Support Service', href: 'customer-support-service.html' },
      { k: 'Technical Support', href: 'technical-support.html' },
      { k: 'Custom Trading Technology', href: 'custom-trading-technology.html' },
    ]},
    { label: 'News & Insights', href: 'insights.html', items: [
      { k: 'Company News', href: 'insights.html#company' },
      { k: 'Industry Insights', href: 'insights.html#industry' },
      { k: 'Product Updates', href: 'insights.html#product' },
      { k: 'Event Recaps', href: 'insights.html#event' },
    ]},
    { label: 'Company', href: 'company.html', items: [
      { k: 'About QTG', href: 'company.html' },
      { k: 'Integrated Partners', href: 'partners.html' },
      { k: 'Expos & Events', href: 'events.html' },
      { k: 'Contact', href: 'contact.html' },
    ]},
  ];

  if (!isMobile) return null;

  return (
    <div className={`qtg-mobile-drawer ${open ? 'is-open' : ''}`} role="dialog" aria-modal="true" aria-hidden={!open}>
      <div className="qmd-head">
        <a className="brand" href="index.html" onClick={() => setOpen(false)}>
          <img src={(window.QTG_BASE || '') + 'assets/qtg-lockup-white.png'} alt="QTG" style={{ height: 26, display: 'block' }} />
        </a>
        <button className="qmd-close" aria-label="Close menu" onClick={() => setOpen(false)}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
            <line x1="6" y1="6" x2="18" y2="18"/>
            <line x1="6" y1="18" x2="18" y2="6"/>
          </svg>
        </button>
      </div>
      <div className="qmd-body">
        {sections.map((sec, i) => (
          <details key={i} name="qmd-section">
            <summary>
              <span>{sec.label}</span>
              <svg className="qmd-caret" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
                <path d="M3 6 L8 11 L13 6"/>
              </svg>
            </summary>
            <div className="qmd-sub">
              <a className="qmd-overview" href={sec.href} onClick={() => setOpen(false)}>
                <span>{sec.label} Overview</span>
                <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M3 8 H12 M9 5 L12 8 L9 11"/></svg>
              </a>
              {sec.groups ? sec.groups.map((g, gi) => (
                <div key={gi} className="qmd-group">
                  <div className="qmd-group-label">{g.label}</div>
                  {g.items.map((it, j) => (
                    <a key={j} href={it.href} onClick={() => setOpen(false)}>
                      <span className="qmd-k"><span className="qmd-dot" />{it.k}</span>
                      {it.d && <span className="d">{it.d}</span>}
                    </a>
                  ))}
                </div>
              )) : sec.items.map((it, j) => (
                <a key={j} href={it.href} onClick={() => setOpen(false)}>
                  <span className="qmd-k"><span className="qmd-dot" />{it.k}</span>
                  {it.d && <span className="d">{it.d}</span>}
                </a>
              ))}
            </div>
          </details>
        ))}
        <div className="qmd-foot">
          <a className="btn btn-primary" href="contact.html" onClick={() => setOpen(false)}>Contact QTG</a>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { MobileNav });

// Self-mount into a dedicated root so individual page apps don't each need to
// render <MobileNav/>. Guarded against double-mount.
(function mountMobileNav() {
  if (window.__qtgMobileNavMounted) return;
  if (!(window.React && window.ReactDOM && window.ReactDOM.createRoot)) return;
  window.__qtgMobileNavMounted = true;
  let host = document.getElementById('qtg-mobile-nav-root');
  if (!host) {
    host = document.createElement('div');
    host.id = 'qtg-mobile-nav-root';
    document.body.appendChild(host);
  }
  ReactDOM.createRoot(host).render(React.createElement(MobileNav));
})();
