(function () {
    "use strict";

    var FIXED_PRICING_ORDER = ["69616", "69617", "69618", "69619", "69622", "69623"];
    var PLAN_DEFS = {
        "69616": { label: "Single Site", licenses: "1", shortLabel: "Single site license" },
        "69617": { label: "3 Sites", licenses: "3", shortLabel: "3 site license" },
        "69618": { label: "5 Sites", licenses: "5", shortLabel: "5 site license" },
        "69619": { label: "10 Sites", licenses: "10", shortLabel: "10 site license" },
        "69622": { label: "20 Sites", licenses: "20", shortLabel: "20 site license" },
        "69623": { label: "Unlimited Sites", licenses: "unlimited", shortLabel: "Unlimited 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 || 32243)) + "/plan/" + encodeURIComponent(String(planId || 52911)) + "/");
        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 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.tiaurPricing && window.tiaurPricing.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 getCheckout(payload) {
        if (checkout) { return checkout; }
        if (!payload || !checkoutScriptLoaded || !window.FS || !window.FS.Checkout) { return null; }
        checkout = new window.FS.Checkout({
            product_id: Number(payload.product_id || 32243),
            plan_id: Number(payload.plan_id || 52911),
            currency: String(payload.currency || (window.tiaurPricing && window.tiaurPricing.currency) || "gbp").toLowerCase(),
            billing_cycle: "annual"
        });
        return checkout;
    }

    function openCheckout(plan) {
        var payload = pricingPayload || { product_id: 32243, plan_id: 52911, currency: (window.tiaurPricing && window.tiaurPricing.currency) || "gbp" };
        loadCheckoutScript(function (loaded) {
            var fsCheckout = loaded ? getCheckout(payload) : null;
            if (!fsCheckout) {
                window.location.href = plan.checkout;
                return;
            }
            var params = {
                pricing_id: Number(plan.pricing_id),
                billing_cycle: "annual",
                currency: String(plan.currency || payload.currency || "gbp").toLowerCase()
            };
            if (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.tiaurPricing && window.tiaurPricing.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) { 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"));

        // Never mark the current plan by pricing ID. Freemius can keep an old
        // pricing_id when the license limit was manually changed, which can
        // incorrectly mark two cards as active. The active card is based only
        // on the current license count, using the closest lower matching plan.
        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.tiaurPricing && window.tiaurPricing.button) || "UPGRADE NOW";
        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="tiaur-pricing-price-premium tiaur-pricing-error-inline">' + escapeHtml((window.tiaurPricing && window.tiaurPricing.priceUnavailableText) || "Prices could not be downloaded. Secure checkout will show the current price.") + '</div>';
        } else if (plan.priceLoading) {
            priceHtml = '<div class="tiaur-pricing-price-premium tiaur-pricing-price-premium--loading"><span class="tiaur-pricing-spinner" aria-hidden="true"></span><span>' + escapeHtml((window.tiaurPricing && window.tiaurPricing.loadingPricesText) || "Loading prices...") + '</span></div>';
        } else if (hasDiscount) {
            priceHtml =
                '<div class="tiaur-pricing-price-old">Regular price: <del>' + escapeHtml(money(plan.raw_price, plan.currency, false)) + '</del></div>' +
                '<div class="tiaur-pricing-price-premium tiaur-pricing-price-premium--sale"><strong>' + escapeHtml(money(plan.sale_price, plan.currency, false)) + '</strong><span>first year</span></div>' +
                '<div class="tiaur-pricing-discount-badge"><strong>' + escapeHtml(discountLabel(plan.coupon, plan.currency)) + ' first-year discount applied.</strong> Renews at ' + escapeHtml(money(plan.raw_price, plan.currency, false)) + '/year.</div>';
        } else {
            priceHtml = '<div class="tiaur-pricing-price-premium"><strong>' + escapeHtml(money(plan.raw_price, plan.currency, true)) + '</strong><span>' + escapeHtml((window.tiaurPricing && window.tiaurPricing.perYear) || "/ year") + '</span></div>';
        }

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

        var buttonHtml;
        if (isActive) {
            buttonHtml = '<button class="tiaur-upgrade-card-button tiaur-upgrade-card-button--active" type="button" disabled>' + escapeHtml(buttonText) + '</button>';
        } else if (isLowerPlan) {
            buttonHtml = '<button class="tiaur-upgrade-card-button tiaur-upgrade-card-button--disabled" type="button" disabled>' + escapeHtml(buttonText) + '</button>';
        } else {
            buttonHtml = '<a class="tiaur-upgrade-card-button" href="' + escapeHtml(plan.checkout) + '">' + escapeHtml(buttonText) + '</a>';
        }

        card.innerHTML =
            '<div class="tiaur-pricing-shine"></div>' +
            '<div class="tiaur-pricing-card-head"><span class="tiaur-plan-pro-badge">PRO</span><span class="tiaur-plan-cycle">ANNUAL</span></div>' +
            '<h3>' + escapeHtml(plan.label) + '</h3>' +
            priceHtml +
            '<span class="tiaur-plan-license-pill">' + escapeHtml(plan.shortLabel) + '</span>' +
            '<div class="tiaur-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(".tiaur-upgrade-card-button");
            if (btn) {
                btn.addEventListener("click", function (event) {
                    event.preventDefault();
                    openCheckout(plan);
                });
            }
        }

        return card;
    }

    function fallbackPlans() {
        pricingPayload = { product_id: 32243, plan_id: 52911, currency: (window.tiaurPricing && window.tiaurPricing.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(32243, 52911, pricingId, null, pricingPayload.currency)
            };
        });
    }

    function showError(container) {
        var message = container.getAttribute("data-error") || (window.tiaurPricing && window.tiaurPricing.priceUnavailableText) || "Prices could not be downloaded. Secure checkout will show the current price.";
        var cards = container.querySelectorAll(".tiaur-pricing-card-premium");
        if (!cards.length) {
            renderPlans(container, fallbackPlans());
            return;
        }
        cards.forEach(function (card) {
            var price = card.querySelector(".tiaur-pricing-price-premium");
            if (price) {
                price.className = "tiaur-pricing-price-premium tiaur-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: 32243, plan_id: 52911, currency: (window.tiaurPricing && window.tiaurPricing.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.tiaurPricing && window.tiaurPricing.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.tiaurPricing || !window.tiaurPricing.ajaxUrl) {
            showError(container);
            return;
        }
        var formData = new FormData();
        formData.append("action", window.tiaurPricing.action || "tiaur_get_freemius_pricing");
        formData.append("nonce", container.getAttribute("data-nonce") || "");

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

    function loadPricing(container) {
        if (window.tiaurPricing && window.tiaurPricing.cachedPricingPayload && window.tiaurPricing.cachedPricingPayload.pricing) {
            renderPayloadOrFallback(container, window.tiaurPricing.cachedPricingPayload);
            return;
        }
        // Do not call adminplugins.com directly from the browser. Some security
        // plugins can return 401 for cross-site REST calls even when the endpoint
        // is intentionally public. Use the local admin-ajax proxy instead.
        loadViaAjax(container);
    }

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