/* =========================================================================
 *  CTWCAD — Mobile bootstrap
 *  ──────────────────────────
 *  Mounts the bottom tab bar in its own React root, and injects a mobile
 *  "folders" rail toggle into the file browser bar without modifying the
 *  desktop components. Communicates with the main app via the existing
 *  ctwcad:* CustomEvent bus.
 * =======================================================================*/

(function () {
  // ---- 1) Bottom tab bar (mounted at body level) ----
  const tabRoot = document.createElement("div");
  tabRoot.id = "ct-mobile-tabbar-root";
  document.body.appendChild(tabRoot);

  function MobileShell() {
    // Track whether the app shell (.ct-app) is mounted. The sign-in card
    // and the desktop-app connect flow render outside the shell — we hide
    // the tab bar entirely on those screens.
    const [hasApp, setHasApp] = React.useState(() => !!document.querySelector(".ct-app"));
    const [route, setRoute] = React.useState(() => {
      const el = document.querySelector(".ct-app");
      return el?.getAttribute("data-route") || "dashboard";
    });

    React.useEffect(() => {
      // Listen for the App's route-changed event instead of polling the
      // DOM via a body-subtree MutationObserver. The previous observer
      // fired on every framer-motion tick and ground the tab to a halt
      // when the file browser mounted (each fire ran a querySelector
      // that's O(N) over the document).
      const apply = (detail) => {
        if (!detail) return;
        if (typeof detail.route === "string") setRoute(detail.route);
        if (typeof detail.hasApp === "boolean") setHasApp(detail.hasApp);
      };
      // Pick up the initial state — the App may have dispatched before
      // we mounted, in which case its event has already fired.
      const el = document.querySelector(".ct-app");
      if (el) apply({ route: el.getAttribute("data-route") || "dashboard", hasApp: true });
      const onRouteChanged = (e) => apply(e.detail);
      window.addEventListener("ctwcad:route-changed", onRouteChanged);
      return () => window.removeEventListener("ctwcad:route-changed", onRouteChanged);
    }, []);

    if (!hasApp) return null;

    const onNavigate = (r) => {
      // Fire a synthetic event the main app listens for. Easier than direct setState.
      window.dispatchEvent(new CustomEvent("ctwcad:mobile-nav", { detail: { route: r } }));
    };

    return <MobileTabBar route={route} onNavigate={onNavigate} />;
  }

  ReactDOM.createRoot(tabRoot).render(<MobileShell/>);

  // ---- 2) Wire the mobile-nav event back into the main app ----
  // The App exposes window.CTWCAD_NAV(path) once the path-based router
  // mounts. We call it directly instead of synthesizing clicks on the
  // desktop top-nav (which the previous implementation did).
  const PATH_FOR = {
    dashboard: "/",
    files:     "/files",
    trash:     "/trash",
    settings:  "/settings",
    admin:     "/admin",
  };
  window.addEventListener("ctwcad:mobile-nav", (e) => {
    const route = e.detail?.route;
    const path = route && PATH_FOR[route];
    if (!path) return;
    if (typeof window.CTWCAD_NAV === "function") {
      window.CTWCAD_NAV(path);
    } else {
      // Router not mounted yet — fall back to a hard navigation.
      window.location.assign(path);
    }
  });

  // ---- 3) Tap outside the rail closes it ----
  // (The rail toggle itself is now rendered inline by FileBrowserView,
  //  not injected here. The previous injection used a second body-subtree
  //  MutationObserver that was firing on every framer-motion tick.)
  document.addEventListener("click", (e) => {
    if (document.documentElement.getAttribute("data-rail-open") !== "1") return;
    const rail = document.querySelector(".ct-browser-rail");
    const toggle = document.querySelector(".ct-mobile-rail-btn");
    if (rail && (rail.contains(e.target) || toggle?.contains(e.target))) return;
    document.documentElement.setAttribute("data-rail-open", "0");
  }, true);
})();
