import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { SUPABASE_URL } from "@/lib/supabase-env";

// Loud console line so it's obvious which backend (Cloud Test vs Live) the build is talking to.
// eslint-disable-next-line no-console
console.info(`[env] Booting → ${SUPABASE_URL}`);

const isNative =
  typeof (window as any).Capacitor !== "undefined" &&
  (window as any).Capacitor.isNativePlatform?.() === true;

// Service workers block Capacitor's native plugin bridge injection.
// Unregister them when running inside a native APK.
if (isNative && "serviceWorker" in navigator) {
  navigator.serviceWorker.getRegistrations().then((registrations) => {
    registrations.forEach((r) => r.unregister());
  });
}

// Register the PWA service worker via vite-plugin-pwa's official virtual
// module on web only. This gives the app a deterministic updater handle —
// `PWAUpdatePrompt` consumes the same module to drive its banner.
if (!isNative) {
  // Dynamic import keeps the virtual module out of native builds.
  import("virtual:pwa-register")
    .then(({ registerSW }) => {
      registerSW({
        immediate: true,
        onRegisteredSW(_swUrl, registration) {
          // Periodically prompt the SW to check for a new build.
          if (!registration) return;
          setInterval(() => {
            registration.update().catch(() => {
              /* ignore */
            });
          }, 60_000);
        },
      });
    })
    .catch(() => {
      /* PWA module unavailable — fall back to native browser caching */
    });
}

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