import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { registerSW } from "virtual:pwa-register";
import App from "./App";
import { useStore } from "./stores/useStore";
import "./index.css";

// Auto-reload when a new service worker is available
const updateSW = registerSW({
  onNeedRefresh() {
    const hasActiveTransfers = useStore
      .getState()
      .transfers.some((t) => t.status === "transferring" || t.status === "pending");
    if (hasActiveTransfers) {
      // Defer update — check again every 30s
      const interval = setInterval(() => {
        const still = useStore
          .getState()
          .transfers.some((t) => t.status === "transferring" || t.status === "pending");
        if (!still) {
          clearInterval(interval);
          updateSW(true);
        }
      }, 30_000);
    } else {
      updateSW(true);
    }
  },
  onOfflineReady() {},
});

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