import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";

type DeferredInstallPromptEvent = Event & {
  prompt: () => Promise<void>;
  userChoice: Promise<{ outcome: "accepted" | "dismissed"; platform: string }>;
};

declare global {
  interface Window {
    __deferredInstallPrompt?: DeferredInstallPromptEvent;
  }
}

window.addEventListener("beforeinstallprompt", (event) => {
  const installEvent = event as DeferredInstallPromptEvent;
  installEvent.preventDefault();
  window.__deferredInstallPrompt = installEvent;
  window.dispatchEvent(new Event("lovable-install-prompt-ready"));
});

window.addEventListener("appinstalled", () => {
  window.__deferredInstallPrompt = undefined;
  window.dispatchEvent(new Event("lovable-app-installed"));
});

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

// Remove the static HTML splash once React has mounted.
function removeInitialLoader() {
  const el = document.getElementById("initial-loader");
  if (!el) return;
  el.classList.add("hide");
  setTimeout(() => el.remove(), 300);
}
if (document.readyState === "complete") {
  requestAnimationFrame(removeInitialLoader);
} else {
  window.addEventListener("load", () => requestAnimationFrame(removeInitialLoader), { once: true });
}

// Single guarded SW registration (no-op in dev/preview/iframe; auto-cleans broken installs)
import { registerAppSW } from "@/lib/registerSW";
void registerAppSW();

// Detect post-deploy ChunkLoadError / failed dynamic imports → show refresh overlay
import { installChunkRecovery } from "@/lib/chunkRecovery";
installChunkRecovery();

