import Swal from "./_global-sweetalert2.js";
import { neo__ } from "./_global--translation.js";
import { pricingUrl } from "./_global-pricing-url.js";
import { reloadPage } from "./_global-reload-page.js";
import { jsVar } from "./_global--enqueue-loader.js";



while (!window.wp?.updates?.updatePluginError) { await new Promise((resolve) => requestAnimationFrame(resolve)); }
const originalUpdatePluginError = window.wp.updates.updatePluginError;
window.wp.updates.updatePluginError = function (resp) {
    if (resp?.plugin?.startsWith("neo-") && resp?.errorMessage?.toLowerCase().includes("payment required")) {
        (async () => {
            const firstResult = await Swal.fire({
                title: neo__("License Required", "Lizenz erforderlich"),
                html: neo__("The neoPro license is missing or expired. To install updates, please purchase and enter a valid license.", "Die neoPro-Lizenz fehlt oder ist abgelaufen. Um Updates zu installieren, kaufe bitte eine gültige Lizenz und gib sie ein."),
                icon: "error",
                confirmButtonText: neo__("Buy now", "Jetzt kaufen"),
                showCancelButton: true,
                cancelButtonText: neo__("Cancel", "Abbrechen"),
            });
            if (firstResult.isConfirmed) { reloadPage(pricingUrl()); return; }
            if (firstResult.dismiss === Swal.DismissReason.cancel) {
                const secondResult = await Swal.fire({
                    title: neo__("20% Discount", "20% Rabatt"),
                    html: neo__(
                        `As a loyal neoWP user, you get 20% off with the following coupon code today:<br><strong><code>${jsVar("neoPluginUpdateExitCouponCode")}</code></strong>`,
                        `Als treuer neoWP-Nutzer erhältst du heute 20% Rabatt mit dem folgenden Coupon-Code:<br><strong><code>${jsVar("neoPluginUpdateExitCouponCode")}</code></strong>`,
                    ),
                    icon: "info",
                    confirmButtonText: neo__("Redeem discount", "Rabatt einlösen"),
                    showCancelButton: true,
                    cancelButtonText: neo__("Skip", "Verzichten"),
                });
                if (secondResult.isConfirmed) { window.open(jsVar("neoPluginUpdateExitCouponUrl"), "_blank"); }
            }
        })();
    }
    return originalUpdatePluginError(resp);
};
