/* eslint-disable */
/* =============================================================
   mobile-nav.jsx — Mobile shell additions (≤ 900px)
   -------------------------------------------------------------
   • <MobileNav/> — hybrid of reference (15-mobile-responsive) and
     the chosen floating-FAB direction:
       – docked tab bar, active tab gets the reference's rounded
         purple highlight + glow
       – glowing spade FAB (→ Spade Labs) raised at the center
       – "المزيد" slides a side DRAWER in from the inline-start
         edge (reference style): account group, full nav list,
         upgrade card (removed with the paid tier).
   • Touch affordances:
       – swipe left/right on the page to move between inner tab
         pills (.tabs-row / .labs-filters / …)
       – tap on a figure/card briefly wakes its hover animation
         (.tap-hover class, consumed by mobile.css)
       – lighter galaxy on small screens.
   ============================================================= */
(function () {
  const { useState, useEffect } = React;

  const DRAWER_ROUTES = ["guide", "centers", "planets", "gates", "charts", "learn", "settings", "support"];

  const gridIcon = (size) => (
    <svg width={size || 21} height={size || 21} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
      <rect x="4" y="4" width="7" height="7" rx="1.8" /><rect x="13" y="4" width="7" height="7" rx="1.8" />
      <rect x="4" y="13" width="7" height="7" rx="1.8" /><rect x="13" y="13" width="7" height="7" rx="1.8" />
    </svg>
  );

  window.MobileNav = function MobileNav({ lang, route, onRoute }) {
    const L = I18N[lang];
    const ar = lang === "ar";
    const admin = !!(window.SpadeAccess && SpadeAccess.isAdmin());
    const [drawer, setDrawer] = useState(false);
    const [closing, setClosing] = useState(false);

    const close = () => {
      setClosing(true);
      setTimeout(() => { setDrawer(false); setClosing(false); }, 260);
    };
    useEffect(() => { if (drawer) close(); }, [route]); // eslint-disable-line

    const go = (r) => onRoute(r);

    const dock = [
      { id: "home", icon: "home", t: L.nav.home },
      { id: "overview", icon: "overview", t: L.nav.overview },
      { id: "compass", icon: "compass", t: ar ? "البوصلة" : "Compass" },
      { id: "gates", icon: "dna", t: L.nav.gates },
      { id: "more", icon: null, t: ar ? "المزيد" : "More" },
    ].filter((x) => x.id === "more" || !window.SpadeAccess || SpadeAccess.canSee(x.id));
    const drawerAccount = [
      { id: "settings#profile", route: "settings", icon: "profile", t: ar ? "حسابي" : "My account" },
      { id: "settings", route: "settings", icon: "settings", t: ar ? "الإعدادات" : "Settings" },
    ];
    const drawerNav = [
      { id: "home", icon: "home", t: L.nav.home },
      { id: "overview", icon: "overview", t: L.nav.overview },
      { id: "guide", icon: "guide", t: L.nav.guide },
      { id: "centers", icon: "centers", t: L.nav.centers },
      { id: "planets", icon: "planets", t: L.nav.planets },
      { id: "gates", icon: "dna", t: L.nav.gates },
      { id: "compare", icon: "compare", t: L.nav.compare },
      { id: "labs", icon: "spade", t: L.nav.labs },
      ...(!window.ChartStore?.remote ? [{ id: "charts", icon: "bookOpen", t: ar ? "خرائطي" : "My charts" }] : []),
      ...(!window.ChartStore?.remote ? [{ id: "support", icon: "support", t: ar ? "الدعم" : "Support" }] : []),
    ].filter((x) => !window.SpadeAccess || SpadeAccess.canSee(x.id));
    const moreActive = drawer || DRAWER_ROUTES.indexOf(route) >= 0;

    const renderDockItem = (x) => {
      const on = x.id === "more" ? moreActive : route === x.id;
      const II = x.icon ? Icon[x.icon] : null;
      return (
        <button key={x.id} className={`mnav-it ${on ? "on" : ""}`} data-galaxy-ui
          onClick={() => (x.id === "more" ? (drawer ? close() : setDrawer(true)) : go(x.id))}>
          <span className="mnav-ic"><Sigil idle={true} size={30}>{II ? <II size={21} /> : gridIcon(21)}</Sigil></span>
          <span className="mnav-t">{x.t}</span>
        </button>
      );
    };

    return (
      <React.Fragment>
        {drawer && <div className={`mdrawer-dim ${closing ? "out" : ""}`} onClick={close}></div>}
        {drawer && (
          <aside className={`mdrawer ${closing ? "out" : ""}`} data-galaxy-ui role="dialog" aria-label={ar ? "القائمة" : "Menu"}>
            <div className="mdrawer-brand">
              <BrandOrb size={44} />
              <div className="mdb-text">
                <strong>{L.brand.title}</strong>
                <span>{L.brand.subtitle}</span>
              </div>
            </div>
            <div className="mdrawer-account">
              {drawerAccount.map((x) => {
                const II = Icon[x.icon];
                return (
                  <button key={x.id} className="mda-row" onClick={() => go(x.route)}>
                    <span className="mda-ic"><II size={18} /></span>
                    <span className="mda-t">{x.t}</span>
                    <span className="mda-chev"><Icon.chevLeft size={15} /></span>
                  </button>
                );
              })}
            </div>
            <nav className="mdrawer-nav">
              {drawerNav.map((x) => {
                const II = Icon[x.icon];
                return (
                  <button key={x.id} className={`mdn-row ${route === x.id ? "on" : ""}`} onClick={() => go(x.id)}>
                    <span className="mdn-t">{x.t}</span>
                    <span className="mdn-ic"><II size={19} /></span>
                  </button>
                );
              })}
            </nav>
            {/* upgrade card removed with the paid tier */}
          </aside>
        )}
        <div className="mnav-wrap" data-galaxy-ui>
          <nav className="mnav">
            {dock.map(renderDockItem)}
          </nav>
        </div>
      </React.Fragment>
    );
  };

  // ── Touch helpers (run once) ────────────────────────────────
  const isMobile = () => window.matchMedia("(max-width: 900px)").matches;

  // 1) lighter galaxy on small screens
  const lighten = () => {
    if (!window.SkyGalaxy || !isMobile()) return;
    try {
      SkyGalaxy.setOption("magLimit", 5.2);
      SkyGalaxy.setOption("twinkle", 0.35);
      SkyGalaxy.setOption("drift", 0.4);
    } catch (e) {}
  };
  if (document.readyState === "complete") lighten();
  else window.addEventListener("load", lighten);

  // 2) tap wakes hover animations (comet, light pass, card lift)
  const TAP_SEL = ".labs-hero-figure, .lab-card, .feature-card, .hero-figure, .fc-figure";
  document.addEventListener("touchstart", (e) => {
    const el = e.target.closest && e.target.closest(TAP_SEL);
    if (!el) return;
    el.classList.add("tap-hover");
    clearTimeout(el.__tapT);
    el.__tapT = setTimeout(() => el.classList.remove("tap-hover"), 3600);
  }, { passive: true });

  // 3) swipe between inner tab pills (RTL-aware)
  let t0 = null;
  document.addEventListener("touchstart", (e) => {
    if (!isMobile() || e.touches.length !== 1) { t0 = null; return; }
    if (e.target.closest("input, textarea, select, .mnav-wrap, .mdrawer, .bodygraph-wrap, svg, canvas")) { t0 = null; return; }
    t0 = { x: e.touches[0].clientX, y: e.touches[0].clientY, t: Date.now() };
  }, { passive: true });
  document.addEventListener("touchend", (e) => {
    if (!t0) return;
    const dx = e.changedTouches[0].clientX - t0.x;
    const dy = e.changedTouches[0].clientY - t0.y;
    const dt = Date.now() - t0.t;
    t0 = null;
    if (dt > 600 || Math.abs(dx) < 64 || Math.abs(dy) > 48) return;
    const active = document.querySelector(".tabs-row .tab-pill.active, .labs-filters .tab-pill.active, .gates-filters .tab-pill.active, .notif-filters .tab-pill.active");
    if (!active) return;
    const pills = Array.from(active.parentElement.querySelectorAll(".tab-pill"));
    const i = pills.indexOf(active);
    const rtl = (document.documentElement.dir || "rtl") === "rtl";
    const fwd = rtl ? dx < 0 : dx > 0;
    const next = pills[i + (fwd ? 1 : -1)];
    if (next) next.click();
  }, { passive: true });
})();
