"use client";

import * as Sentry from "@sentry/browser";
import { checkForUpdate, forceReloadOntoCurrentBuild } from "./version-check";
import { isReloadScheduled } from "./reload";

// One recovery attempt per window. A second chunk failure straight after an
// attempt means the reload did not help, and retrying every time would trap
// the user in a reload loop.
const COOLDOWN_MS = 60 * 1000;
const COOLDOWN_KEY = "chunk-recovery-last-attempt";

// Held in memory AS WELL AS sessionStorage, and the module variable is what
// actually matters for a burst.
//
// sessionStorage writes throw or no-op in Safari Private Browsing, with site
// data blocked, and in some PWA/WebView containers. When that happened the
// cooldown silently stopped existing: every failing chunk raised its own
// Sentry event and its own recovery attempt, so one page with a dozen failing
// chunks produced a dozen of each -- on exactly the installed-PWA clients
// this code exists to help. The in-memory copy needs no permission and covers
// the whole page lifetime, which is the window a burst happens in.
let lastAttemptAt = 0;

// Set once the page is going away. Every pending subresource is aborted at
// that moment, and each aborted <script> fires an error event indistinguishable
// from a 404. Reporting those turns one recovery reload into a burst of
// "chunk failed" events describing nothing but our own teardown.
let shuttingDown = false;

function isChunkAssetUrl(url?: string | null): boolean {
    if (!url) return false;
    return /\/_next\/static\/.*\.(js|css|mjs)(\?.*)?$/i.test(url);
}

function canAttempt(): boolean {
    // In-memory is authoritative when set: it cannot be blocked, and within a
    // single page load it is what stops a burst.
    if (lastAttemptAt && Date.now() - lastAttemptAt <= COOLDOWN_MS) return false;

    // Storage extends the same cooldown across a reload, when available.
    try {
        const last = sessionStorage.getItem(COOLDOWN_KEY);
        if (!last) return true;
        return Date.now() - Number(last) > COOLDOWN_MS;
    } catch {
        return true;
    }
}

function markAttempt(): void {
    lastAttemptAt = Date.now();
    try {
        sessionStorage.setItem(COOLDOWN_KEY, String(Date.now()));
    } catch { }
}

async function recover(reason: string): Promise<void> {
    // These two separate a real failure from our own teardown. Checked before
    // the cooldown so an abort burst cannot even consume the budget.
    if (shuttingDown || isReloadScheduled()) return;
    if (!canAttempt()) return;
    markAttempt();

    console.warn("[chunk-errors] broken chunk:", reason);

    try {
        Sentry.captureMessage(`Chunk recovery triggered: ${reason}`, "warning");
    } catch { }

    // A newer build being deployed is the common cause, and checkForUpdate()
    // handles that case end to end -- it reloads and reports true so we stand
    // down.
    if (await checkForUpdate()) return;

    // Nothing newer is deployed, so this was not staleness: a transient
    // network failure, or a document served from a cache that still names an
    // asset no longer present. Either way the fix is the same -- get onto a
    // freshly fetched document.
    if (await forceReloadOntoCurrentBuild()) return;

    // Budget spent. Reloading again is what the budget exists to prevent, so
    // stop and leave a trail rather than looping the tab.
    console.error(
        "[chunk-errors] giving up: retries exhausted and chunks still failing. " +
        "Cause is below this app -- network, or an asset missing from the deploy."
    );
    try {
        Sentry.captureMessage(`Chunk recovery exhausted: ${reason}`, "error");
    } catch { }
}

// Installs process-wide listeners, so calling it twice would double every
// event: one real chunk failure would run recover() twice, and only the
// cooldown would (silently) paper over it. Cheap to make idempotent, and it
// removes a whole class of "why is this reported twice" confusion.
let installed = false;

export function initChunkErrorGuard(): void {
    if (typeof window === "undefined") return;
    if (installed) return;
    installed = true;

    // pagehide covers bfcache, tab close and navigation, and unlike
    // beforeunload it is reliable on iOS Safari -- the platform this recovery
    // path most often runs on.
    window.addEventListener("pagehide", () => { shuttingDown = true; });

    // Resource-level load failures (a 404 for a script/link tag). These do not
    // bubble, so the listener must be on the capture phase.
    //
    // This is also the listener that carries old Safari: `unhandledrejection`
    // below does not exist before Safari 15.4, and webpack loads chunks via
    // script tags, so this path is what makes recovery work there at all.
    window.addEventListener(
        "error",
        (event) => {
            const target = event.target as HTMLScriptElement | HTMLLinkElement | null;
            if (!target || !("tagName" in target)) return;

            if (target.tagName === "LINK") {
                // Ignore prefetch/preload/modulepreload. Next speculatively
                // prefetches other routes' chunks and those fail or get
                // cancelled constantly for reasons unrelated to this page.
                // Only a stylesheet is actually critical.
                const rel = ((target as HTMLLinkElement).rel || "").toLowerCase();
                if (rel !== "stylesheet") return;
            } else if (target.tagName !== "SCRIPT") {
                return;
            }

            const src =
                (target as HTMLScriptElement).src ||
                (target as HTMLLinkElement).href ||
                "";

            if (isChunkAssetUrl(src)) recover(`resource-error:${src}`);
        },
        true
    );

    // Webpack's promise-based loader rejects with ChunkLoadError when a chunk
    // request fails outright. Absent on Safari < 15.4; the capture listener
    // above covers that case.
    window.addEventListener("unhandledrejection", (event: PromiseRejectionEvent) => {
        const reason = event.reason as { name?: string; message?: string } | undefined;
        const name = reason?.name || "";
        const message = reason?.message || String(event.reason || "");

        if (
            name === "ChunkLoadError" ||
            /loading chunk/i.test(message) ||
            /loading css chunk/i.test(message)
        ) {
            recover(`chunk-load-error:${message}`);
        }
    });
}
