// SPA router for RBI. Loaded last; renders the right view based on URL.
// Hosts in-app navigation via window.RBI_NAV(view), which calls history.pushState
// so the URL stays clean (and back/forward work).
//
// UPDATED: added "login" view + RBI_SIGNOUT helper that redirects to login.html.

(function () {
  const { useState: useRouterState, useEffect: useRouterEffect } = React;

  const VIEW_FILES = {
    "landing": "landing.html",
    "login": "login.html",
    "home": "index.html",
    "creditscore": "business-credit.html",
    "cashflow": "RBI Cash Flow.html",
    "insights": "rbi_industry_insights.html",
    "privacy": "privacy.html",
  };
  const VIEW_TITLES = {
    "landing": "Revenued Business Intelligence — Landing",
    "login": "Revenued Business Intelligence — Login",
    "home": "Revenued Business Intelligence — Home",
    "creditscore": "Revenued BI — Business Credit",
    "cashflow": "Revenued BI — Cash flow",
    "insights": "Revenued BI — Industry insights",
    "privacy": "Revenued BI — Privacy policy",
  };

  function hasSessionToken() {
    try {
      if (window.RBI_API && window.RBI_API.getToken) return !!window.RBI_API.getToken();
      return !!localStorage.getItem("id_token");
    } catch (e) {
      return false;
    }
  }

  function viewFromPath() {
    const path = decodeURIComponent(location.pathname).toLowerCase();
    if (path.includes("landing")) return "landing";
    if (path.indexOf("cash flow") !== -1 || path.indexOf("cashflow") !== -1) return "cashflow";
    if (path.indexOf("industry") !== -1 || path.indexOf("insights") !== -1) return "insights";
    if (path.indexOf("business-credit") !== -1 || path.indexOf("creditscore") !== -1) return "creditscore";
    // if (path.indexOf("privacy") !== -1) return "privacy";
    return hasSessionToken() ? "home" : "landing";
  }

  // Report a named RUM view so Datadog groups sessions by screen instead of by
  // raw file path (this app mixes real page loads with pushState navigation).
  function trackView(view) {
    if (window.RBI_MONITOR) window.RBI_MONITOR.trackView(view);
  }

  function navigate(view) {
    // Full-page redirects below get a fresh RUM view on load, so only the
    // in-app (pushState) navigations need an explicit startView.

    // "login" is a full page — redirect to login.html.
    if (view === "login") {
      const base = location.pathname.replace(/[^/]*$/, "");
      location.href = base + "login.html";
      return;
    }
    if (view === "landing") {
      const base = location.pathname.replace(/[^/]*$/, "");
      location.href = base + "landing.html";
      return;
    }
    if (view === "privacy") {
      const base = location.pathname.replace(/[^/]*$/, "");
      location.href = base + "privacy.html";
      return;
    }

    if (!VIEW_FILES[view]) return;
    const file = VIEW_FILES[view];
    const base = location.pathname.replace(/[^/]*$/, "");
    const newPath = base + file;
    history.pushState({ view: view }, "", newPath);
    trackView(view);
    document.title = VIEW_TITLES[view];
    window.dispatchEvent(new CustomEvent("rbi:nav", { detail: { view: view } }));
    window.scrollTo(0, 0);
  }

  window.RBI_NAV = navigate;

  // Convenience helper used by the topbar "Sign out" button.
  // Calls POST /v1/bi/signOut (Bearer), then clears local session and returns
  // to the landing page. Local cleanup always runs even if the API fails.
  window.RBI_SIGNOUT = async function () {
    if (window.RBI_MONITOR) {
      window.RBI_MONITOR.trackAction("sign_out");
    }
    sessionStorage.removeItem("rbi_authed");
    if (window.RBI_API && window.RBI_API.signOut) {
      try {
        await window.RBI_API.signOut();
      } catch (e) {
        // signOut already clears local state; this is a last-resort fallback.
        if (window.RBI_API.clearToken) window.RBI_API.clearToken();
      }
    } else if (window.RBI_API && window.RBI_API.clearToken) {
      window.RBI_API.clearToken();
    } else {
      try { localStorage.removeItem("id_token"); } catch (e) { /* ignore */ }
    }
    navigate("landing");
    window.scrollTo(0, 0);
  };

  function appsReadyFor(view) {
    if (view === "cashflow") return typeof window.CFApp === "function";
    if (view === "insights") return typeof window.InsApp === "function";
    if (view === "privacy") return typeof window.PrivacyApp === "function";
    if (view === "landing") return typeof window.LandingApp === "function";
    if (view === "creditscore") return typeof window.HomeApp === "function";
    return typeof window.OverviewApp === "function";
  }

  function RouterBoot() {
    return (
      <div className="rbi-app" style={{ padding: "48px 24px", textAlign: "center", color: "var(--fg-2, #445)" }}>
        Loading…
      </div>
    );
  }

  function Router() {
    const [view, setView] = useRouterState(viewFromPath);
    const [ready, setReady] = useRouterState(function () { return appsReadyFor(viewFromPath()); });

    // Babel loads page apps async — wait until the active view's component exists
    // so we never render <undefined /> (blank screen after login / first nav).
    useRouterEffect(function () {
      if (appsReadyFor(view)) {
        setReady(true);
        return;
      }
      setReady(false);
      var tries = 0;
      var t = setInterval(function () {
        tries += 1;
        if (appsReadyFor(view) || tries > 200) {
          setReady(appsReadyFor(view));
          clearInterval(t);
        }
      }, 50);
      return function () { clearInterval(t); };
    }, [view]);

    // First view of this page load.
    useRouterEffect(function () { trackView(viewFromPath()); }, []);

    useRouterEffect(function () {
      // No session token on a protected view → landing + login popup.
      if (!hasSessionToken()) {
        if (window.RBI_API && window.RBI_API.goToLoginPopup) {
          window.RBI_API.goToLoginPopup("missing_token");
        } else {
          try { sessionStorage.setItem("rbi_open_login", "1"); } catch (e) { /* ignore */ }
          navigate("landing");
        }
      }

      function onNav(e) { setView(e.detail.view); }
      function onPop() { setView(viewFromPath()); document.title = VIEW_TITLES[viewFromPath()]; trackView(viewFromPath()); }
      window.addEventListener("rbi:nav", onNav);
      window.addEventListener("popstate", onPop);
      return function () {
        window.removeEventListener("rbi:nav", onNav);
        window.removeEventListener("popstate", onPop);
      };
    }, []);

    if (!ready || !appsReadyFor(view)) return <RouterBoot />;

    if (view === "landing") return React.createElement(window.LandingApp);
    if (view === "cashflow") return React.createElement(window.CFApp);
    if (view === "insights") return React.createElement(window.InsApp);
    if (view === "privacy") return React.createElement(window.PrivacyApp);
    if (view === "creditscore") return React.createElement(window.HomeApp);

    return React.createElement(window.OverviewApp);
  }

  const rbiRoot = ReactDOM.createRoot(document.getElementById("root"));
  rbiRoot.render(<Router />);
})();