import { createRoot } from "react-dom/client";
import { registerSW } from "virtual:pwa-register";
import App from "./App.tsx";
import { isHostedAppHostname } from "./lib/environment.ts";
import "./index.css";
import { applyEarlyAuthLandingTheme } from "./lib/authLandingTheme";
import { cleanupLegacyVapidPushServiceWorkers } from "./lib/onesignalWeb";
import {
  clearAppBrowserCache,
  installEarlyCacheRecoveryHandlers,
} from "./lib/appBrowserCache";

applyEarlyAuthLandingTheme();
installEarlyCacheRecoveryHandlers();

// In iframe previews we disable Service Workers to avoid stale cached builds.
const isInIframe = (() => {
  try {
    return window.self !== window.top;
  } catch {
    return true;
  }
})();

// Bypass SW on hosted OTAP/custom domains to prevent stale cache and auth redirect issues.
const isHostedEnvironment = (() => {
  try {
    return isHostedAppHostname();
  } catch {
    return false;
  }
})();

const mountApp = () => {
  void cleanupLegacyVapidPushServiceWorkers();
  createRoot(document.getElementById("root")!).render(<App />);
};

// Also bypass cache when viewing history/versions
const isViewingHistory = (() => {
  try {
    const url = new URL(window.location.href);
    return url.searchParams.has("version") || url.searchParams.has("edit");
  } catch {
    return false;
  }
})();

const shouldBypassSWCache = isInIframe || isHostedEnvironment || isViewingHistory;

// In iframe/hosted environments, mount immediately. SW/cache cleanup max 1× per sessie
if (shouldBypassSWCache) {
  const cleanupKey = "__novione_hosted_sw_cleanup_done__";
  let alreadyCleaned = false;
  try {
    alreadyCleaned = sessionStorage.getItem(cleanupKey) === "1";
  } catch {
    alreadyCleaned = false;
  }

  if (!alreadyCleaned) {
    try {
      sessionStorage.setItem(cleanupKey, "1");
    } catch {
      // ignore
    }
    void clearAppBrowserCache();
  }

  mountApp();
} else {
  if (import.meta.env.PROD) {
    // Force immediate update when new version is available
    const updateSW: ((reloadPage?: boolean) => Promise<void>) | undefined = registerSW({
      immediate: true,
      onNeedRefresh() {
        // Activate the waiting service worker and reload into the latest version
        updateSW?.(true);
      },
      onOfflineReady() {
        console.log("App ready to work offline");
      },
    });
  }

  mountApp();
}
