(function () {
    "use strict";

    var FIXED_PRICING_ORDER = ["76766", "76767", "76768", "76769", "76770", "80169"];
    var PLAN_DEFS = {
        "76766": { label: "Single Site", licenses: "1", shortLabel: "Single site license" },
        "76767": { label: "3 Sites", licenses: "3", shortLabel: "3 site license" },
        "76768": { label: "5 Sites", licenses: "5", shortLabel: "5 site license" },
        "76769": { label: "10 Sites", licenses: "10", shortLabel: "10 site license" },
        "76770": { label: "20 Sites", licenses: "20", shortLabel: "20 site license" },
        "80169": { label: "50 Sites", licenses: "50", shortLabel: "50 site license" }
    };

    var pricingPayload = null;
    var checkout = null;
    var checkoutScriptLoaded = false;
    var checkoutScriptLoading = false;
    var checkoutCallbacks = [];

    function escapeHtml(value) {
        return String(value === undefined || value === null ? "" : value)
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    function symbol(currency) {
        currency = String(currency || "gbp").toLowerCase();
        if (currency === "eur") { return "€"; }
        if (currency === "usd") { return "$"; }
        return "£";
    }

    function money(value, currency, includeYear) {
        var num = Number(value);
        if (!isFinite(num)) { return ""; }
        var formatted = num % 1 === 0 ? num.toFixed(0) : num.toFixed(2);
        return symbol(currency) + formatted + (includeYear ? "/year" : "");
    }

    function normaliseDiscountType(type) {
        type = String(type || "").toLowerCase();
        if (type === "percentage" || type === "percent" || type === "%") { return "percentage"; }
        if (type === "money" || type === "fixed" || type === "amount" || type === "currency") { return "fixed"; }
        return type;
    }

    function couponIsActive(coupon) {
        if (!coupon) { return false; }
        var value = coupon.is_active;
        if (value === undefined || value === null) { value = coupon.active; }
        if (value === true) { return true; }
        if (value === false) { return false; }
        value = String(value || "").toLowerCase().trim();
        return value === "1" || value === "true" || value === "yes" || value === "on" || value === "active" || value === "enabled";
    }

    function couponDiscountValue(coupon) {
        if (!coupon) { return NaN; }
        var keys = ["discount", "discount_amount", "amount", "coupon_discount"];
        for (var i = 0; i < keys.length; i++) {
            if (coupon[keys[i]] !== undefined && coupon[keys[i]] !== null && coupon[keys[i]] !== "") {
                return Number(coupon[keys[i]]);
            }
        }
        return NaN;
    }

    function couponDiscountType(coupon) {
        if (!coupon) { return ""; }
        return normaliseDiscountType(coupon.discount_type || coupon.type || coupon.discount_kind || "");
    }

    function hasRealDiscount(coupon) {
        if (!couponIsActive(coupon)) { return false; }
        var discount = couponDiscountValue(coupon);
        if (!isFinite(discount) || discount <= 0) { return false; }
        var type = couponDiscountType(coupon);
        return type === "percentage" || type === "fixed";
    }

    function discountedPrice(price, coupon) {
        var num = Number(price);
        if (!isFinite(num) || !hasRealDiscount(coupon)) { return null; }
        var discount = couponDiscountValue(coupon);
        var type = couponDiscountType(coupon);
        if (type === "percentage") {
            return Math.max(0, num - (num * discount / 100));
        }
        return Math.max(0, num - discount);
    }

    function discountLabel(coupon, currency) {
        if (!hasRealDiscount(coupon)) { return ""; }
        if (couponDiscountType(coupon) === "percentage") {
            var discount = couponDiscountValue(coupon);
            return (discount % 1 === 0 ? discount.toFixed(0) : discount.toFixed(2)) + "%";
        }
        return money(couponDiscountValue(coupon), currency, false);
    }

    function checkoutUrl(productId, planId, pricingId, coupon, currency) {
        var url = new URL("https://checkout.freemius.com/product/" + encodeURIComponent(String(productId || 34725)) + "/plan/" + encodeURIComponent(String(planId || 57101)) + "/");
        url.searchParams.set("pricing_id", String(pricingId || ""));
        url.searchParams.set("billing_cycle", "annual");
        url.searchParams.set("currency", String(currency || "gbp").toLowerCase());
        if (hasRealDiscount(coupon) && coupon.code) {
            url.searchParams.set("coupon", String(coupon.code));
            url.searchParams.set("coupon_code", String(coupon.code));
            url.searchParams.set("hide_coupon", "1");
        }
        return url.toString();
    }

    function checkoutUrlWithoutCoupon(url) {
        try {
            var cleanUrl = new URL(String(url || ""), window.location.href);
            cleanUrl.searchParams.delete("coupon");
            cleanUrl.searchParams.delete("coupon_code");
            cleanUrl.searchParams.delete("hide_coupon");
            return cleanUrl.toString();
        } catch (error) {
            return String(url || "");
        }
    }

    function loadCheckoutScript(done) {
        if (window.FS && window.FS.Checkout) {
            checkoutScriptLoaded = true;
            done(true);
            return;
        }
        checkoutCallbacks.push(done);
        if (checkoutScriptLoading) { return; }
        checkoutScriptLoading = true;
        var script = document.createElement("script");
        script.src = (window.tmsmtpPricing && window.tmsmtpPricing.checkoutScriptUrl) || "https://checkout.freemius.com/js/v1/";
        script.async = true;
        script.onload = function () {
            checkoutScriptLoaded = true;
            checkoutScriptLoading = false;
            var callbacks = checkoutCallbacks.slice();
            checkoutCallbacks = [];
            callbacks.forEach(function (callback) { callback(!!(window.FS && window.FS.Checkout)); });
        };
        script.onerror = function () {
            checkoutScriptLoading = false;
            var callbacks = checkoutCallbacks.slice();
            checkoutCallbacks = [];
            callbacks.forEach(function (callback) { callback(false); });
        };
        document.head.appendChild(script);
    }

    function createCheckout(payload) {
        if (!payload || !checkoutScriptLoaded || !window.FS || !window.FS.Checkout) { return null; }
        return new window.FS.Checkout({
            product_id: Number(payload.product_id || 34725),
            plan_id: Number(payload.plan_id || 57101),
            currency: String(payload.currency || (window.tmsmtpPricing && window.tmsmtpPricing.currency) || "gbp").toLowerCase(),
            billing_cycle: "annual"
        });
    }

    function getCheckout(payload) {
        if (checkout) { return checkout; }
        checkout = createCheckout(payload);
        return checkout;
    }

    function openCheckout(plan, applyAutomaticCoupon) {
        var payload = pricingPayload || { product_id: 34725, plan_id: 57101, currency: (window.tmsmtpPricing && window.tmsmtpPricing.currency) || "gbp" };
        var useAutomaticCoupon = applyAutomaticCoupon !== false;
        loadCheckoutScript(function (loaded) {
            var fsCheckout = loaded ? (useAutomaticCoupon ? getCheckout(payload) : createCheckout(payload)) : null;
            if (!fsCheckout) {
                window.location.href = useAutomaticCoupon ? plan.checkout : checkoutUrlWithoutCoupon(plan.checkout);
                return;
            }
            var params = {
                pricing_id: Number(plan.pricing_id),
                billing_cycle: "annual",
                currency: String(plan.currency || payload.currency || "gbp").toLowerCase()
            };
            if (useAutomaticCoupon && hasRealDiscount(plan.coupon) && plan.coupon.code) {
                params.coupon = String(plan.coupon.code);
                params.coupon_code = String(plan.coupon.code);
                params.hide_coupon = true;
            }
            fsCheckout.open(params);
        });
    }

    function planFromRestItem(pricingId, item, payload) {
        var def = PLAN_DEFS[String(pricingId)] || {};
        var currency = String((item && item.currency) || payload.currency || (window.tmsmtpPricing && window.tmsmtpPricing.currency) || "gbp").toLowerCase();
        var rawPrice = item && item.annual_price;
        if (rawPrice === undefined || rawPrice === null || rawPrice === "" || !isFinite(Number(rawPrice))) {
            return null;
        }
        var coupon = hasRealDiscount(payload.coupon) ? payload.coupon : null;
        var sale = discountedPrice(rawPrice, coupon);
        var realPricingId = String((item && item.id) || pricingId);
        return {
            label: def.label || "Pro License",
            licenses: def.licenses || String((item && item.licenses) || ""),
            shortLabel: def.shortLabel || "Pro license",
            pricing_id: realPricingId,
            raw_price: Number(rawPrice),
            sale_price: sale,
            currency: currency,
            coupon: coupon,
            checkout: checkoutUrl(payload.product_id, payload.plan_id, realPricingId, coupon, currency)
        };
    }

    function buildPlansFromRest(payload) {
        if (!payload || !payload.pricing || typeof payload.pricing !== "object") {
            return [];
        }
        pricingPayload = payload;
        var plans = [];
        FIXED_PRICING_ORDER.forEach(function (pricingId) {
            var item = payload.pricing[pricingId];
            var plan = item ? planFromRestItem(pricingId, item, payload) : null;
            if (!plan) {
                var def = PLAN_DEFS[pricingId] || {};
                var currency = String(payload.currency || (window.tmsmtpPricing && window.tmsmtpPricing.currency) || "gbp").toLowerCase();
                plan = {
                    label: def.label || "Pro License",
                    licenses: def.licenses || "",
                    shortLabel: def.shortLabel || "Pro license",
                    pricing_id: pricingId,
                    raw_price: null,
                    sale_price: null,
                    currency: currency,
                    coupon: null,
                    priceUnavailable: true,
                    checkout: checkoutUrl(payload.product_id, payload.plan_id, pricingId, null, currency)
                };
            }
            plans.push(plan);
        });
        return plans;
    }

    function normalizeLicenseValue(value) {
        value = String(value === undefined || value === null ? "" : value).toLowerCase().trim();
        if (!value) { return null; }
        if (value === "unlimited") { return Infinity; }
        var number = parseInt(value, 10);
        return isFinite(number) && number > 0 ? number : null;
    }

    function resolveActivePlan(container, plans) {
        var currentLicenses = normalizeLicenseValue(container.getAttribute("data-current-licenses"));

        if (currentLicenses === null) {
            return null;
        }

        var selected = null;
        plans.forEach(function (plan) {
            var planLicenses = normalizeLicenseValue(plan.licenses);
            if (currentLicenses === Infinity) {
                if (planLicenses === Infinity) {
                    selected = plan;
                }
                return;
            }
            if (planLicenses !== null && planLicenses !== Infinity && planLicenses <= currentLicenses) {
                if (!selected || planLicenses > normalizeLicenseValue(selected.licenses)) {
                    selected = plan;
                }
            }
        });

        return selected;
    }

    function isLowerThanCurrent(container, plan, activePlan) {
        if (!activePlan || String(activePlan.pricing_id) === String(plan.pricing_id)) {
            return false;
        }

        var currentLicenses = normalizeLicenseValue(container.getAttribute("data-current-licenses"));
        var planLicenses = normalizeLicenseValue(plan.licenses);

        if (currentLicenses === null || planLicenses === null) {
            return false;
        }

        if (currentLicenses === Infinity) {
            return planLicenses !== Infinity;
        }

        return planLicenses !== Infinity && planLicenses < currentLicenses;
    }

    function createCard(container, plan, activePlan) {
        var isActive = activePlan && String(activePlan.pricing_id) === String(plan.pricing_id);
        var isLowerPlan = isLowerThanCurrent(container, plan, activePlan);
        var normalButtonText = container.getAttribute("data-button") || (window.tmsmtpPricing && window.tmsmtpPricing.button) || "UPGRADE NOW";
        var manualCouponText = (window.tmsmtpPricing && window.tmsmtpPricing.manualCouponText) || "Have a different coupon code?";
        var buttonText = isActive ? "ACTIVE" : normalButtonText;
        var hasDiscount = plan.sale_price !== null && plan.sale_price < plan.raw_price && hasRealDiscount(plan.coupon);
        var priceHtml = "";

        if (plan.priceUnavailable) {
            priceHtml = '<div class="tmsmtp-pricing-price-premium tmsmtp-pricing-error-inline">' + escapeHtml((window.tmsmtpPricing && window.tmsmtpPricing.priceUnavailableText) || "Prices could not be downloaded. Secure checkout will show the current price.") + '</div>';
        } else if (plan.priceLoading) {
            priceHtml = '<div class="tmsmtp-pricing-price-premium tmsmtp-pricing-price-premium--loading"><span class="tmsmtp-pricing-spinner" aria-hidden="true"></span><span>' + escapeHtml((window.tmsmtpPricing && window.tmsmtpPricing.loadingPricesText) || "Loading prices...") + '</span></div>';
        } else if (hasDiscount) {
            priceHtml =
                '<div class="tmsmtp-pricing-price-old">Regular price: <del>' + escapeHtml(money(plan.raw_price, plan.currency, false)) + '</del></div>' +
                '<div class="tmsmtp-pricing-price-premium tmsmtp-pricing-price-premium--sale"><strong>' + escapeHtml(money(plan.sale_price, plan.currency, false)) + '</strong><span>first year</span></div>' +
                '<div class="tmsmtp-pricing-discount-badge"><strong>' + escapeHtml(discountLabel(plan.coupon, plan.currency)) + ' discount applied.</strong></div>';
        } else {
            priceHtml = '<div class="tmsmtp-pricing-price-premium"><strong>' + escapeHtml(money(plan.raw_price, plan.currency, false)) + '</strong><span>' + escapeHtml((window.tmsmtpPricing && window.tmsmtpPricing.perYear) || "/ year") + '</span></div>';
        }

        var card = document.createElement("div");
        card.className = "tmsmtp-pricing-card-premium" + (isActive ? " tmsmtp-pricing-card-premium--active" : "");
        card.setAttribute("data-tmsmtp-pricing-id", plan.pricing_id);

        var disabledCouponHtml = '<span class="tmsmtp-manual-coupon-link tmsmtp-manual-coupon-link--disabled" aria-disabled="true">' + escapeHtml(manualCouponText) + '</span>';
        var buttonHtml;
        if (isActive) {
            buttonHtml = '<button class="tmsmtp-upgrade-card-button tmsmtp-upgrade-card-button--active" type="button" disabled>' + escapeHtml(buttonText) + '</button>' + disabledCouponHtml;
        } else if (isLowerPlan) {
            buttonHtml = '<button class="tmsmtp-upgrade-card-button tmsmtp-upgrade-card-button--disabled" type="button" disabled>' + escapeHtml(buttonText) + '</button>' + disabledCouponHtml;
        } else {
            buttonHtml =
                '<a class="tmsmtp-upgrade-card-button" href="' + escapeHtml(plan.checkout) + '">' + escapeHtml(buttonText) + '</a>' +
                '<a class="tmsmtp-manual-coupon-link" href="' + escapeHtml(checkoutUrlWithoutCoupon(plan.checkout)) + '">' + escapeHtml(manualCouponText) + '</a>';
        }

        card.innerHTML =
            '<div class="tmsmtp-pricing-shine"></div>' +
            '<div class="tmsmtp-pricing-card-head"><span class="tmsmtp-plan-pro-badge">PRO</span><span class="tmsmtp-plan-cycle">ANNUAL</span></div>' +
            '<h3>' + escapeHtml(plan.label) + '</h3>' +
            priceHtml +
            '<span class="tmsmtp-plan-license-pill">' + escapeHtml(plan.shortLabel) + '</span>' +
            '<div class="tmsmtp-plan-includes"><span>All Pro features</span><span>Updates and support</span><span>License managed by Freemius</span></div>' +
            buttonHtml;

        if (!isActive && !isLowerPlan) {
            var btn = card.querySelector(".tmsmtp-upgrade-card-button");
            var manualCouponLink = card.querySelector(".tmsmtp-manual-coupon-link");
            if (btn) {
                btn.addEventListener("click", function (event) {
                    event.preventDefault();
                    openCheckout(plan, true);
                });
            }
            if (manualCouponLink) {
                manualCouponLink.addEventListener("click", function (event) {
                    event.preventDefault();
                    openCheckout(plan, false);
                });
            }
        }

        return card;
    }

    function bindExistingCheckoutButtons(container) {
        var cards = container.querySelectorAll(".tmsmtp-pricing-card-premium");
        cards.forEach(function (card) {
            var button = card.querySelector("a.tmsmtp-upgrade-card-button");
            var manualCouponLink = card.querySelector("a.tmsmtp-manual-coupon-link");
            if (!button) { return; }

            var plan = {
                pricing_id: String(card.getAttribute("data-tmsmtp-pricing-id") || ""),
                licenses: String(card.getAttribute("data-tmsmtp-licenses") || ""),
                currency: (window.tmsmtpPricing && window.tmsmtpPricing.currency) || "gbp",
                coupon: null,
                checkout: button.getAttribute("href") || ""
            };

            button.addEventListener("click", function (event) {
                event.preventDefault();
                openCheckout(plan, true);
            });
            if (manualCouponLink) {
                manualCouponLink.addEventListener("click", function (event) {
                    event.preventDefault();
                    openCheckout(plan, false);
                });
            }
        });
    }

    function fallbackPlans() {
        pricingPayload = { product_id: 34725, plan_id: 57101, currency: (window.tmsmtpPricing && window.tmsmtpPricing.currency) || "gbp", coupon: null };
        return FIXED_PRICING_ORDER.map(function (pricingId) {
            var def = PLAN_DEFS[pricingId];
            return {
                label: def.label,
                licenses: def.licenses,
                shortLabel: def.shortLabel,
                pricing_id: pricingId,
                raw_price: null,
                sale_price: null,
                currency: pricingPayload.currency,
                coupon: null,
                priceUnavailable: true,
                checkout: checkoutUrl(34725, 57101, pricingId, null, pricingPayload.currency)
            };
        });
    }

    function showError(container) {
        var message = container.getAttribute("data-error") || (window.tmsmtpPricing && window.tmsmtpPricing.priceUnavailableText) || "Prices could not be downloaded. Secure checkout will show the current price.";
        var cards = container.querySelectorAll(".tmsmtp-pricing-card-premium");
        if (!cards.length) {
            renderPlans(container, fallbackPlans());
            return;
        }
        cards.forEach(function (card) {
            var price = card.querySelector(".tmsmtp-pricing-price-premium");
            if (price) {
                price.className = "tmsmtp-pricing-price-premium tmsmtp-pricing-error-inline";
                price.textContent = message;
            }
        });
    }

    function renderPlans(container, plans) {
        if (!plans || !plans.length) {
            showError(container);
            return;
        }
        var activePlan = resolveActivePlan(container, plans);
        container.innerHTML = "";
        plans.forEach(function (plan) {
            container.appendChild(createCard(container, plan, activePlan));
        });
    }

    function plansFromFallback(payload) {
        if (!payload || !payload.success || !payload.data || !Array.isArray(payload.data.plans)) {
            return [];
        }
        pricingPayload = { product_id: 34725, plan_id: 57101, currency: (window.tmsmtpPricing && window.tmsmtpPricing.currency) || "gbp", coupon: null };
        return payload.data.plans.map(function (plan) {
            var price = parseFloat(String(plan.price || "").replace(/[^0-9.]/g, ""));
            return {
                label: plan.label,
                licenses: plan.licenses,
                shortLabel: plan.licenses === "unlimited" ? "Unlimited site license" : (plan.licenses === "1" ? "Single site license" : plan.licenses + " site license"),
                pricing_id: String(plan.pricing_id || ""),
                raw_price: isFinite(price) && price > 0 ? price : null,
                sale_price: null,
                priceUnavailable: !(isFinite(price) && price > 0),
                currency: (window.tmsmtpPricing && window.tmsmtpPricing.currency) || "gbp",
                coupon: null,
                checkout: plan.checkout
            };
        });
    }

    function renderPayloadOrFallback(container, payload) {
        var plans = [];
        if (payload && payload.pricing && typeof payload.pricing === "object") {
            plans = buildPlansFromRest(payload);
        } else if (payload && payload.success && payload.data && payload.data.pricingPayload) {
            plans = buildPlansFromRest(payload.data.pricingPayload);
        }
        if (!plans.length) {
            plans = plansFromFallback(payload);
        }
        renderPlans(container, plans.length ? plans : fallbackPlans());
    }

    function loadViaAjax(container) {
        if (!window.tmsmtpPricing || !window.tmsmtpPricing.ajaxUrl) {
            showError(container);
            return;
        }
        var formData = new FormData();
        formData.append("action", window.tmsmtpPricing.action || "tmsmtp_get_freemius_pricing");
        formData.append("nonce", container.getAttribute("data-nonce") || "");
        if (window.tmsmtpPricing && window.tmsmtpPricing.noCache) { formData.append("no_cache", "1"); }

        fetch(window.tmsmtpPricing.ajaxUrl, {
            method: "POST",
            credentials: "same-origin",
            body: formData
        })
            .then(function (response) { return response.json(); })
            .then(function (payload) {
                if (window.tmsmtpPricing && window.tmsmtpPricing.pricingEnabled) {
                    renderPayloadOrFallback(container, payload);
                }
            })
            .catch(function () {
                if (window.tmsmtpPricing && window.tmsmtpPricing.pricingEnabled) {
                    showError(container);
                }
            });
    }

    function consentFormHtml(enabled, compact) {
        var config = window.tmsmtpPricing || {};
        var action = enabled ? "disable" : "enable";
        var label = enabled ? (config.disablePricesText || "DISABLE CURRENT PRICES") : (compact ? (config.showPriceText || "SHOW CURRENT PRICE") : (config.enablePricesText || "ENABLE CURRENT PRICES"));
        var formClass = compact ? "tmsmtp-price-consent-inline" : "tmsmtp-pricing-consent-form";
        var buttonClass = compact ? "tmsmtp-price-consent-button" : "tmsmtp-upgrade-secondary tmsmtp-upgrade-secondary--bright";
        return '<form class="' + formClass + '" method="post">' +
            '<input type="hidden" name="tmsmtp_pricing_consent_nonce" value="' + escapeHtml(config.consentNonce || "") + '">' +
            '<input type="hidden" name="tmsmtp_pricing_consent_action" value="' + action + '">' +
            '<button class="' + buttonClass + '" type="submit">' + escapeHtml(label) + '</button>' +
            '</form>';
    }

    function replacePriceDisplay(card, className, content) {
        var nodes = card.querySelectorAll(".tmsmtp-pricing-price-old, .tmsmtp-pricing-price-premium, .tmsmtp-pricing-discount-badge");
        nodes.forEach(function (node) { node.remove(); });
        var price = document.createElement("div");
        price.className = className;
        price.innerHTML = content;
        var heading = card.querySelector("h3");
        if (heading) {
            heading.insertAdjacentElement("afterend", price);
        }
    }

    function showLoadingPrices(container) {
        container.querySelectorAll(".tmsmtp-pricing-card-premium").forEach(function (card) {
            replacePriceDisplay(
                card,
                "tmsmtp-pricing-price-premium tmsmtp-pricing-price-premium--loading",
                '<span class="tmsmtp-pricing-spinner" aria-hidden="true"></span><span>' + escapeHtml((window.tmsmtpPricing && window.tmsmtpPricing.loadingPricesText) || "Loading prices...") + '</span>'
            );
        });
    }

    function showConsentPrices(container) {
        container.querySelectorAll(".tmsmtp-pricing-card-premium").forEach(function (card) {
            replacePriceDisplay(
                card,
                "tmsmtp-pricing-price-premium tmsmtp-pricing-price-premium--consent",
                consentFormHtml(false, true)
            );
        });
    }

    function updateConsentForm(form, enabled) {
        var compact = form.classList.contains("tmsmtp-price-consent-inline");
        var actionInput = form.querySelector('input[name="tmsmtp_pricing_consent_action"]');
        var nonceInput = form.querySelector('input[name="tmsmtp_pricing_consent_nonce"]');
        var button = form.querySelector("button");
        var config = window.tmsmtpPricing || {};
        if (actionInput) { actionInput.value = enabled ? "disable" : "enable"; }
        if (nonceInput) { nonceInput.value = config.consentNonce || ""; }
        if (button) {
            button.textContent = enabled ? (config.disablePricesText || "DISABLE CURRENT PRICES") : (compact ? (config.showPriceText || "SHOW CURRENT PRICE") : (config.enablePricesText || "ENABLE CURRENT PRICES"));
        }
    }

    function updateConsentUi(container, enabled, pricingNonce) {
        var config = window.tmsmtpPricing || {};
        config.pricingEnabled = enabled;
        window.tmsmtpPricing = config;
        container.setAttribute("data-nonce", enabled ? String(pricingNonce || "") : "");

        var panelTitle = document.querySelector(".tmsmtp-pricing-consent-panel h2");
        if (panelTitle) {
            panelTitle.textContent = enabled ? (config.pricesEnabledTitle || "Current prices are enabled") : (config.pricesDisabledTitle || "Choose whether to display current prices");
        }

        document.querySelectorAll(".tmsmtp-pricing-consent-form, .tmsmtp-price-consent-inline").forEach(function (form) {
            updateConsentForm(form, enabled);
        });

        if (enabled) {
            showLoadingPrices(container);
            loadViaAjax(container);
        } else {
            pricingPayload = null;
            checkout = null;
            showConsentPrices(container);
        }
    }

    function submitConsentForm(form, container) {
        if (!window.tmsmtpPricing || form.classList.contains("tmsmtp-consent-is-loading")) {
            return;
        }

        var consentAction = form.querySelector('input[name="tmsmtp_pricing_consent_action"]');
        var nonce = form.querySelector('input[name="tmsmtp_pricing_consent_nonce"]');
        if (!consentAction || !nonce) { return; }

        var buttons = Array.prototype.slice.call(document.querySelectorAll(".tmsmtp-pricing-consent-form button, .tmsmtp-price-consent-inline button"));
        buttons.forEach(function (button) { button.disabled = true; });
        form.classList.add("tmsmtp-consent-is-loading");

        var requestBody = new URLSearchParams();
        requestBody.append("tmsmtp_pricing_consent_nonce", nonce.value || window.tmsmtpPricing.consentNonce || "");
        requestBody.append("tmsmtp_pricing_consent_action", consentAction.value || "");
        requestBody.append("tmsmtp_pricing_consent_ajax", "1");

        fetch(window.location.pathname + window.location.search, {
            method: "POST",
            credentials: "same-origin",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                "X-Requested-With": "XMLHttpRequest"
            },
            body: requestBody.toString()
        })
            .then(function (response) { return response.json(); })
            .then(function (payload) {
                if (!payload || !payload.success || !payload.data) {
                    throw new Error("pricing-consent-failed");
                }
                window.tmsmtpPricing.consentNonce = payload.data.consentNonce || window.tmsmtpPricing.consentNonce;
                updateConsentUi(container, !!payload.data.enabled, payload.data.pricingNonce || "");
            })
            .catch(function () {
                form.classList.remove("tmsmtp-consent-is-loading");
            })
            .then(function () {
                buttons.forEach(function (button) { button.disabled = false; });
                if (form.isConnected) { form.classList.remove("tmsmtp-consent-is-loading"); }
            });
    }

    function loadPricing(container) {
        var forceRefresh = !!(window.tmsmtpPricing && window.tmsmtpPricing.noCache);
        if (window.tmsmtpPricing && window.tmsmtpPricing.cachedPricingPayload && window.tmsmtpPricing.cachedPricingPayload.pricing) {
            renderPayloadOrFallback(container, window.tmsmtpPricing.cachedPricingPayload);
            if (!forceRefresh) { return; }
        }
        if (!forceRefresh && window.tmsmtpPricing && window.tmsmtpPricing.pricingCacheFresh) {
            renderPayloadOrFallback(container, null);
            return;
        }
        loadViaAjax(container);
    }

    document.addEventListener("DOMContentLoaded", function () {
        var container = document.getElementById("tmsmtp-dynamic-pricing");
        if (!container) { return; }

        document.addEventListener("submit", function (event) {
            var form = event.target;
            if (!form || !form.matches || !form.matches(".tmsmtp-pricing-consent-form, .tmsmtp-price-consent-inline")) {
                return;
            }
            event.preventDefault();
            submitConsentForm(form, container);
        });

        bindExistingCheckoutButtons(container);
        if (window.tmsmtpPricing && window.tmsmtpPricing.pricingEnabled) {
            loadPricing(container);
        }
    });
}());
