import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { registerSW } from "virtual:pwa-register";

// Guard: never run a service worker inside Lovable's preview iframe or on preview hosts.
const isInIframe = (() => {
  try {
    return window.self !== window.top;
  } catch {
    return true;
  }
})();

const isPreviewHost =
  window.location.hostname.includes("id-preview--") ||
  window.location.hostname.includes("lovableproject.com") ||
  window.location.hostname.includes("lovable.app");

if (isPreviewHost || isInIframe) {
  // Unregister any previously installed SWs so the preview never serves stale assets.
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker.getRegistrations().then((regs) => {
      regs.forEach((r) => r.unregister());
    });
  }
} else {
  registerSW({ immediate: true });
  // Register the dedicated push service worker (separate from workbox).
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker.register("/sw-push.js").catch((e) => console.warn("push SW failed", e));
  }
}

createRoot(document.getElementById("root")!).render(<App />);
