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

if (!window.location.hash) {
  window.location.hash = "#/";
}

// PWA: Service Worker registrieren (nur in Production, sonst stört's HMR).
if ("serviceWorker" in navigator && import.meta.env.PROD) {
  window.addEventListener("load", () => {
    navigator.serviceWorker
      .register("/sw.js")
      .catch((err) => console.warn("[Tapecast] SW registration failed:", err));
  });
}

// beforeinstallprompt abfangen, damit Settings einen "App installieren"-Button anbieten kann.
// Wir speichern das Event auf window, App-Code greift drauf zu.
declare global {
  interface Window {
    __tapecastInstallPrompt?: BeforeInstallPromptEvent | null;
  }
  interface BeforeInstallPromptEvent extends Event {
    prompt: () => Promise<void>;
    userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;
  }
}

window.addEventListener("beforeinstallprompt", (e) => {
  e.preventDefault();
  window.__tapecastInstallPrompt = e as BeforeInstallPromptEvent;
  window.dispatchEvent(new CustomEvent("tapecast:installable"));
});

window.addEventListener("appinstalled", () => {
  window.__tapecastInstallPrompt = null;
  window.dispatchEvent(new CustomEvent("tapecast:installed"));
});

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