(function () {
    "use strict";

    var freemiusCheckoutHandler = null;
    var freemiusCheckoutScriptPromise = null;

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

    function getString(key, fallback) {
        if (window.tiamrPricing && window.tiamrPricing.strings && window.tiamrPricing.strings[key]) {
            return window.tiamrPricing.strings[key];
        }

        return fallback;
    }

    function loadFreemiusCheckoutScript() {
        if (window.FS && window.FS.Checkout) {
            return Promise.resolve();
        }

        if (freemiusCheckoutScriptPromise) {
            return freemiusCheckoutScriptPromise;
        }

        freemiusCheckoutScriptPromise = new Promise(function (resolve, reject) {
            var script = document.querySelector('script[data-tiamr-freemius-checkout="1"]');

            function finish() {
                if (window.FS && window.FS.Checkout) {
                    resolve();
                    return;
                }

                reject(new Error("Freemius checkout is not available."));
            }

            if (!script) {
                script = document.createElement("script");
                script.src = "https://checkout.freemius.com/js/v1/";
                script.async = true;
                script.setAttribute("data-tiamr-freemius-checkout", "1");
                document.head.appendChild(script);
            }

            script.addEventListener("load", finish, { once: true });
            script.addEventListener("error", function () {
                reject(new Error("Freemius checkout could not be loaded."));
            }, { once: true });
        });

        return freemiusCheckoutScriptPromise;
    }

    function getCheckoutHandler() {
        if (freemiusCheckoutHandler) {
            return freemiusCheckoutHandler;
        }

        if (!window.FS || !window.FS.Checkout) {
            return null;
        }

        freemiusCheckoutHandler = new window.FS.Checkout({
            product_id: 32028,
            plan_id: 52536,
            public_key: "pk_5571f63bb4256d51416cc00cd2c25"
        });

        return freemiusCheckoutHandler;
    }

    function normalizeCouponCode(code) {
        code = String(code || "").trim();

        if (!code) {
            return "";
        }

        if (code.toLowerCase() === "firstyear50") {
            return "FirstYear50";
        }

        return code;
    }

    function parseCheckoutOptions(link) {
        var href = link.getAttribute("href") || "";
        var plan = link.__tiamrPlan || {};
        var parsed;

        try {
            parsed = new URL(href, window.location.href);
        } catch (error) {
            parsed = null;
        }

        var pricingId = String(plan.pricing_id || (parsed ? parsed.searchParams.get("pricing_id") : "") || "");
        var licenses = String(plan.licenses || "");
        var coupon = normalizeCouponCode(plan.coupon_code || (parsed ? (parsed.searchParams.get("coupon") || parsed.searchParams.get("coupon_code")) : ""));
        var licenseKey = parsed ? String(parsed.searchParams.get("license_key") || "") : "";
        var currency = String((parsed ? parsed.searchParams.get("currency") : "") || "gbp").toLowerCase();
        var billingCycle = String((parsed ? parsed.searchParams.get("billing_cycle") : "") || "annual").toLowerCase();

        var options = {
            plan_id: 52536,
            billing_cycle: billingCycle,
            currency: currency
        };

        if (pricingId) {
            options.pricing_id = pricingId;
        }

        if (licenses) {
            options.licenses = licenses === "unlimited" ? "unlimited" : parseInt(licenses, 10);
        }

        if (coupon) {
            options.coupon = coupon;
            options.coupon_code = coupon;
            options.hide_coupon = true;
        }

        if (licenseKey) {
            options.license_key = licenseKey;
        }

        return options;
    }

    function openOverlayCheckout(event) {
        var link = event.currentTarget;
        var href = link.getAttribute("href") || "";

        if (!href) {
            return;
        }

        event.preventDefault();

        loadFreemiusCheckoutScript()
            .then(function () {
                var handler = getCheckoutHandler();

                if (!handler || typeof handler.open !== "function") {
                    window.location.href = href;
                    return;
                }

                var options = parseCheckoutOptions(link);
                var opened = handler.open(options);

                if (opened && typeof opened.catch === "function") {
                    opened.catch(function () {
                        window.location.href = href;
                    });
                }
            })
            .catch(function () {
                window.location.href = href;
            });
    }

    function getLicenseRank(licenses) {
        licenses = String(licenses || "").toLowerCase();

        if (licenses === "unlimited") {
            return 999999;
        }

        var value = parseInt(licenses, 10);

        if (!value || value < 1) {
            return 0;
        }

        if (value >= 20) {
            return 20;
        }

        if (value >= 10) {
            return 10;
        }

        if (value >= 5) {
            return 5;
        }

        if (value >= 3) {
            return 3;
        }

        return 1;
    }

    function getPriceHtml(plan) {
        var status = String(plan.price_status || "");
        var hasPrice = !!String(plan.price || "");
        var hasDiscount = hasPrice && !!plan.has_discount;
        var priceTerm = plan.term || (hasDiscount ? "first year" : (window.tiamrPricing && window.tiamrPricing.perYear ? window.tiamrPricing.perYear : "/ year"));
        var hasDiscountClass = hasDiscount ? " amr-pricing-price-premium--sale" : "";

        if (status === "loading") {
            return '<div class="amr-pricing-price-premium amr-pricing-price-premium--loading">' +
                '<span class="amr-pricing-inline-status">' +
                    '<span class="amr-pricing-spinner amr-pricing-spinner--small" aria-hidden="true"></span>' +
                    '<strong>' + escapeHtml(getString("loadingPrices", "Loading prices...")) + '</strong>' +
                '</span>' +
            '</div>';
        }

        if (status === "error") {
            return '<div class="amr-pricing-price-unavailable amr-pricing-price-unavailable--error">' +
                escapeHtml(getString("pricesUnavailable", "Unable to load prices. Secure checkout will show the current price.")) +
            '</div>';
        }

        if (hasPrice) {
            return '<div class="amr-pricing-price-premium' + hasDiscountClass + '">' +
                '<strong>' + escapeHtml(plan.price) + '</strong>' +
                '<span>' + escapeHtml(priceTerm) + '</span>' +
            '</div>';
        }

        return '<div class="amr-pricing-price-unavailable">' +
            escapeHtml(getString("checkoutPrice", "Price shown at secure checkout")) +
        '</div>';
    }

    function createCard(plan) {
        var container = document.getElementById("amr-dynamic-pricing");
        var proActive = container && container.getAttribute("data-pro-active") === "1";
        var currentLicenses = proActive && container ? String(container.getAttribute("data-current-licenses") || "") : "";
        var planLicenses = String(plan.licenses || "");
        var currentRank = getLicenseRank(currentLicenses);
        var planRank = getLicenseRank(planLicenses);
        var isActive = proActive && currentRank > 0 && planRank > 0 && currentRank === planRank;
        var isLowerPlan = proActive && currentRank > 0 && planRank > 0 && planRank < currentRank;
        var buttonText = isActive ? "ACTIVE" : ((container && container.getAttribute("data-button")) || (window.tiamrPricing && window.tiamrPricing.button ? window.tiamrPricing.button : "UPGRADE NOW"));
        var hasPrice = !!String(plan.price || "");
        var hasDiscount = hasPrice && !!plan.has_discount;
        var discountNote = plan.discount_note || "";

        var card = document.createElement("div");
        card.className = "amr-pricing-card-premium" + (isActive ? " amr-pricing-card-premium--active" : "") + (isLowerPlan ? " amr-pricing-card-premium--disabled" : "") + (plan.price_status === "loading" ? " amr-pricing-card-premium--loading" : "");

        card.innerHTML =
            '<div class="amr-pricing-shine"></div>' +
            '<div class="amr-pricing-card-head">' +
                '<span class="amr-plan-pro-badge">PRO</span>' +
                '<span class="amr-plan-cycle">ANNUAL</span>' +
            '</div>' +
            '<h3>' + escapeHtml(plan.label) + '</h3>' +
            (hasDiscount && plan.regular_price
                ? '<div class="amr-pricing-price-old">Regular price: <del>' + escapeHtml(plan.regular_price) + '</del></div>'
                : '') +
            getPriceHtml(plan) +
            (hasDiscount && discountNote
                ? '<div class="amr-pricing-discount-badge"><strong>' + escapeHtml(discountNote) + '</strong></div>'
                : '') +
            '<span class="amr-plan-license-pill">' + escapeHtml(plan.license_label || plan.label + " license") + '</span>' +
            '<div class="amr-plan-includes">' +
                '<span>All Pro features</span>' +
                '<span>Updates and support</span>' +
                '<span>License managed by Freemius</span>' +
            '</div>' +
            (isActive
                ? '<button class="amr-upgrade-card-button amr-upgrade-card-button--active" type="button" disabled>' + escapeHtml(buttonText) + '</button>'
                : (isLowerPlan
                    ? '<button class="amr-upgrade-card-button amr-upgrade-card-button--disabled" type="button" disabled>' + escapeHtml(buttonText) + '</button>'
                    : '<a class="amr-upgrade-card-button" href="' + escapeHtml(plan.checkout) + '">' + escapeHtml(buttonText) + '</a>'));

        if (!isActive && !isLowerPlan) {
            var button = card.querySelector(".amr-upgrade-card-button");

            if (button) {
                button.__tiamrPlan = plan;
                button.addEventListener("click", openOverlayCheckout);
            }
        }

        return card;
    }

    function attachCheckoutHandlers(container) {
        Array.prototype.forEach.call(container.querySelectorAll("a.amr-upgrade-card-button"), function (button) {
            if (button.__tiamrPricingBound) {
                return;
            }

            button.__tiamrPricingBound = true;
            button.addEventListener("click", openOverlayCheckout);
        });
    }

    function markExistingCardsAsError(container) {
        var cards = container.querySelectorAll(".amr-pricing-card-premium");

        if (!cards.length) {
            return false;
        }

        Array.prototype.forEach.call(cards, function (card) {
            var oldPrice = card.querySelector(".amr-pricing-price-old");
            var discount = card.querySelector(".amr-pricing-discount-badge");
            var price = card.querySelector(".amr-pricing-price-premium, .amr-pricing-price-unavailable");

            if (oldPrice && oldPrice.parentNode) {
                oldPrice.parentNode.removeChild(oldPrice);
            }

            if (discount && discount.parentNode) {
                discount.parentNode.removeChild(discount);
            }

            if (price) {
                price.outerHTML = getPriceHtml({ price_status: "error" });
            }

            card.classList.remove("amr-pricing-card-premium--loading");
        });

        attachCheckoutHandlers(container);

        return true;
    }

    function showError(container) {
        if (markExistingCardsAsError(container)) {
            return;
        }

        var message = container.getAttribute("data-error") || getString("pricesUnavailable", "Unable to load prices. Secure checkout will show the current price.");
        container.innerHTML = '<div class="amr-pricing-error">' + escapeHtml(message) + '</div>';
    }

    function loadPricing(container) {
        attachCheckoutHandlers(container);

        if (container.getAttribute("data-prices-loaded") === "1") {
            return;
        }

        if (!window.tiamrPricing || !window.tiamrPricing.ajaxUrl) {
            showError(container);
            return;
        }

        var formData = new FormData();
        formData.append("action", window.tiamrPricing.action || "tiamr_get_freemius_pricing");
        formData.append("nonce", container.getAttribute("data-nonce") || "");

        try {
            var currentUrl = new URL(window.location.href);
            if (currentUrl.searchParams.get("no_cache") === "1") {
                formData.append("no_cache", "1");
            }
        } catch (error) {}

        fetch(window.tiamrPricing.ajaxUrl, {
            method: "POST",
            credentials: "same-origin",
            body: formData
        })
            .then(function (response) {
                return response.json();
            })
            .then(function (payload) {
                if (!payload || !payload.success || !payload.data || !Array.isArray(payload.data.plans) || !payload.data.plans.length) {
                    showError(container);
                    return;
                }

                if (payload.data.proActive) {
                    container.setAttribute("data-pro-active", "1");
                } else {
                    container.setAttribute("data-pro-active", "0");
                    container.setAttribute("data-current-licenses", "");
                }

                var pricesLoaded = payload.data.pricesLoaded !== false;
                container.setAttribute("data-prices-loaded", pricesLoaded ? "1" : "0");

                container.innerHTML = "";
                payload.data.plans.forEach(function (plan) {
                    if (!pricesLoaded && !plan.price) {
                        plan.price_status = "error";
                    }

                    container.appendChild(createCard(plan));
                });
            })
            .catch(function () {
                showError(container);
            });
    }

    document.addEventListener("DOMContentLoaded", function () {
        var container = document.getElementById("amr-dynamic-pricing");

        if (container) {
            loadPricing(container);
        }
    });
}());
