let bundleStaleNotified = false;

export function checkBundleVersion(response) {
    const serverVersion = response.headers.get("X-Bundle-Version");
    const clientVersion = window.__BUNDLE_VERSION__;
    if (!serverVersion || !clientVersion || serverVersion === clientVersion) {
        return;
    }

    if (bundleStaleNotified) {
        return;
    }
    bundleStaleNotified = true;

    const bar = document.createElement("div");
    bar.setAttribute("role", "status");
    bar.style.cssText = [
        "position:fixed",
        "top:0",
        "left:0",
        "right:0",
        "z-index:99999",
        "padding:12px 16px",
        "background:#141620",
        "color:#fff",
        "text-align:center",
        "font:14px system-ui,sans-serif",
        "box-shadow:0 2px 8px rgba(0,0,0,0.2)",
    ].join(";");

    const message = document.createElement("span");
    message.textContent = "A new version of National CD Rateline is available.";

    const button = document.createElement("button");
    button.type = "button";
    button.textContent = "Refresh";
    button.style.cssText = "margin-left:12px;padding:4px 12px;cursor:pointer;border:0;border-radius:4px;background:#fff;color:#141620;font:inherit";

    button.addEventListener("click", () => {
        window.location.reload();
    });

    bar.append(message, button);
    document.body.prepend(bar);
}

export async function apiFetch(url, options) {
    const response = await fetch(url, options);
    checkBundleVersion(response);
    return response;
}
