"use client";

import { BUILD_ID, isDevBuild } from "./identity";

// A reload triggered by the worker taking control happens at most once per
// page, no matter how many controllerchange events arrive.
let reloadedForNewWorker = false;

/**
 * Register the service worker, and reload once when a new one takes control.
 *
 * This is the layer that actually fixes the PWA cold start. Every other
 * mechanism here reacts to the browser's HTTP cache after the fact; the
 * worker intercepts the start_url navigation itself and decides freshness in
 * code we ship. See public/sw.js.
 *
 * PROGRESSIVE ENHANCEMENT, ON PURPOSE
 *
 * If the browser has no service worker support, no secure context, or
 * registration fails, this returns quietly and everything else -- the version
 * check, _r stamping, entry-point healing, chunk recovery -- keeps working
 * exactly as before. The worker makes those cheaper and more reliable; it is
 * never their precondition.
 *
 * Service workers are supported across the whole browserslist floor
 * (Chrome 80, Firefox 78, Safari 13 -- iOS 11.3+), so in practice this runs
 * everywhere. The guard is for hostile environments, not old ones: private
 * modes and embedded webviews can refuse registration outright.
 */
export function registerServiceWorker(): void {
    if (typeof window === "undefined") return;

    // `next dev` has no stable build id and serves uncacheable assets; a
    // worker here would only get in the way of HMR.
    if (isDevBuild()) return;

    if (!("serviceWorker" in navigator)) return;
    if (!window.isSecureContext) return;

    // Whether a worker was already in charge when this page loaded. This is
    // what separates "a NEW worker replaced the old one, so the page is now
    // running against different rules and should reload" from "the very first
    // worker just installed", where there is nothing to reload for and doing
    // so would give every first-time visitor a pointless flash.
    const hadController = !!navigator.serviceWorker.controller;

    navigator.serviceWorker.addEventListener("controllerchange", () => {
        if (!hadController) return;
        if (reloadedForNewWorker) return;
        reloadedForNewWorker = true;

        // A plain reload is correct here, unlike everywhere else in this
        // folder: the new worker is now in charge of the response, so a
        // same-URL reload cannot be answered from the stale HTTP cache.
        window.location.reload();
    });

    // Registration is deferred to load so it never competes with the first
    // paint for bandwidth.
    const register = () => {
        navigator.serviceWorker
            .register(`/sw.js?v=${BUILD_ID}`, {
                scope: "/",
                // Bypass the HTTP cache when checking for a new worker script.
                // Belt and braces with the ?v= above -- see public/sw.js for
                // why a cached worker script is the worst outcome available.
                updateViaCache: "none",
            })
            .then((reg) => {
                // Ask immediately rather than waiting for the browser's own
                // update heuristics, which can be a day apart.
                reg.update().catch(() => { });
            })
            .catch((err) => {
                console.warn("[sw] registration failed:", err);
            });
    };

    if (document.readyState === "complete") {
        register();
    } else {
        window.addEventListener("load", register, { once: true });
    }
}

/**
 * Emergency: tear down the worker and its caches.
 *
 * Not called anywhere. It exists so that shipping a build which calls it is a
 * one-line change rather than a scramble, if the worker ever turns out to be
 * the problem. See also the kill-switch worker in public/sw.js.
 */
export async function unregisterServiceWorker(): Promise<void> {
    try {
        if (!("serviceWorker" in navigator)) return;

        const regs = await navigator.serviceWorker.getRegistrations();
        await Promise.all(regs.map((r) => r.unregister()));

        if (typeof caches !== "undefined") {
            const names = await caches.keys();
            await Promise.all(names.map((n) => caches.delete(n)));
        }
    } catch (err) {
        console.warn("[sw] unregister failed:", err);
    }
}
