/**
 * Admin Scripts - Bobasoftware Publisher Paywall
 * Extracted from inline <script> blocks for WordPress.org compliance
 */
(function() {
    'use strict';

    // --- Access & Monetization page ---
    (function() {
        var form = document.getElementById("sp-access-monetization-form");
        var tip = document.getElementById("enable_tip_unlock");
        var article = document.getElementById("enable_article_unlock");
        var subscription = document.getElementById("enable_subscription");
        var monthly = document.getElementById("subscription_price_monthly");
        var annual = document.getElementById("subscription_price_annual");
        var defaultTip = document.getElementById("default_tip_amount");
        var minTip = document.getElementById("minimum_tip_amount");
        var articlePrice = document.getElementById("article_unlock_price");
        var minTipRow = document.getElementById("sp-min-tip-row");
        var minTipError = document.getElementById("sp-min-tip-error");
        var saveBtn = document.getElementById("sp-save-access-monetization");
        var resetBtn = document.getElementById("sp-reset-access-monetization-defaults");
        var freeArticleLimit = document.getElementById("free_article_limit");
        var postsDays = document.getElementById("posts_become_paid_after_days");
        var freeAccessOne = form ? form.querySelector('input[name="free_access_model"][value="one_time"]') : null;
        var freeAccessMonth = form ? form.querySelector('input[name="free_access_model"][value="monthly"]') : null;
        var cardSub = form ? form.querySelector(".sp-am-card--subscription") : null;
        var cardTip = form ? form.querySelector(".sp-am-card--tip") : null;
        var cardArticle = form ? form.querySelector(".sp-am-card--article") : null;
        var hasProFields = !!(tip && article && defaultTip && minTip && articlePrice && minTipRow && minTipError && freeArticleLimit && freeAccessOne && freeAccessMonth);
        if (!form || !subscription || !monthly || !annual || !saveBtn || !postsDays) { return; }

        function syncCardCollapse() {
            if (cardSub) { cardSub.classList.toggle("sp-am-card--off", !subscription.checked); }
            if (cardTip && tip) { cardTip.classList.toggle("sp-am-card--off", !tip.checked); }
            if (cardArticle && article) { cardArticle.classList.toggle("sp-am-card--off", !article.checked); }
        }

        function updateDependentFields() {
            monthly.disabled = !subscription.checked;
            annual.disabled = !subscription.checked;
            if (!hasProFields || (typeof spIsPremium !== "undefined" && !spIsPremium)) {
                syncCardCollapse();
                return;
            }
            defaultTip.disabled = !tip.checked;
            minTip.disabled = !tip.checked;
            articlePrice.disabled = !article.checked;
            if (freeAccessOne) { freeAccessOne.disabled = false; }
            if (freeAccessMonth) { freeAccessMonth.disabled = false; }
            if (freeArticleLimit) { freeArticleLimit.disabled = false; }
            syncCardCollapse();
        }

        function getSerializedState() {
            var data = new FormData(form);
            var entries = [];
            data.forEach(function(value, key) {
                entries.push(key + "=" + value);
            });
            entries.sort();
            return entries.join("&");
        }

        var baselineState = getSerializedState();

        function setSaveDirtyState() {
            var current = getSerializedState();
            var dirty = current !== baselineState;
            saveBtn.disabled = !dirty;
            if (saveBtn.disabled) {
                saveBtn.classList.add("sp-save-disabled");
            } else {
                saveBtn.classList.remove("sp-save-disabled");
            }
        }

        function validateTipAmounts() {
            if (!hasProFields || (typeof spIsPremium !== "undefined" && !spIsPremium)) {
                return true;
            }
            var defaultVal = parseFloat(defaultTip.value || "0");
            var minVal = parseFloat(minTip.value || "0");
            var invalid = tip.checked && minVal > defaultVal;

            if (invalid) {
                minTipRow.classList.add("sp-field-error");
                minTipError.classList.add("is-visible");
                minTip.setCustomValidity("Minimum tip cannot be greater than default tip.");
            } else {
                minTipRow.classList.remove("sp-field-error");
                minTipError.classList.remove("is-visible");
                minTip.setCustomValidity("");
            }

            return !invalid;
        }

        function applyRecommendedDefaults() {
            var d = typeof spAccessMonetizationDefaults === "object" && spAccessMonetizationDefaults !== null ? spAccessMonetizationDefaults : null;
            if (!d) { return; }
            subscription.checked = !!parseInt(d.enable_subscription, 10);
            monthly.value = d.subscription_price_monthly;
            annual.value = d.subscription_price_annual;
            if (hasProFields && typeof spIsPremium !== "undefined" && spIsPremium) {
                tip.checked = !!parseInt(d.enable_tip_unlock, 10);
                defaultTip.value = d.default_tip_amount;
                minTip.value = d.minimum_tip_amount;
                article.checked = !!parseInt(d.enable_article_unlock, 10);
                articlePrice.value = d.article_unlock_price;
                if (d.free_access_model === "monthly") {
                    freeAccessMonth.checked = true;
                } else {
                    freeAccessOne.checked = true;
                }
                freeArticleLimit.value = d.free_article_limit;
                if (tip.checked) { article.checked = false; }
                if (article.checked) { tip.checked = false; }
            }
            postsDays.value = d.posts_become_paid_after_days;
            updateDependentFields();
            validateTipAmounts();
            setSaveDirtyState();
        }

        updateDependentFields();
        setSaveDirtyState();
        validateTipAmounts();

        if (resetBtn) {
            resetBtn.addEventListener("click", function() {
                var ok = window.confirm("Reset all Access & Monetization fields to the recommended defaults? Nothing is saved until you click Save settings.");
                if (!ok) { return; }
                applyRecommendedDefaults();
            });
        }

        if (hasProFields) {
            tip.addEventListener("change", function() {
                if (tip.checked) { article.checked = false; }
                updateDependentFields();
                validateTipAmounts();
                setSaveDirtyState();
            });
            article.addEventListener("change", function() {
                if (article.checked) { tip.checked = false; }
                updateDependentFields();
                validateTipAmounts();
                setSaveDirtyState();
            });
            defaultTip.addEventListener("input", function() {
                validateTipAmounts();
                setSaveDirtyState();
            });
            minTip.addEventListener("input", function() {
                validateTipAmounts();
                setSaveDirtyState();
            });
        }

        subscription.addEventListener("change", function() {
            updateDependentFields();
            setSaveDirtyState();
        });

        form.addEventListener("change", function() {
            setSaveDirtyState();
        });
        form.addEventListener("input", function() {
            setSaveDirtyState();
        });

        form.addEventListener("submit", function(e) {
            if (!validateTipAmounts()) {
                e.preventDefault();
                if (minTip) { minTip.focus(); }
            }
        });
    })();

    // --- Settings (Stripe) page ---
    (function(){
        var form = document.getElementById("sp-settings-form");
        var saveBtn = document.getElementById("sp-save-settings");
        var copyBtn = document.getElementById("sp-copy-webhook-url");
        var urlInput = document.getElementById("sp-stripe-webhook-url");
        if (copyBtn && urlInput) {
            copyBtn.addEventListener("click", function() {
                var url = urlInput.value;
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(url).then(function() {
                        var t = copyBtn.textContent;
                        copyBtn.textContent = "Copied!";
                        setTimeout(function(){ copyBtn.textContent = t; }, 1500);
                    });
                } else {
                    urlInput.select();
                    try { document.execCommand("copy"); } catch (e) {}
                }
            });
        }
        if (!form || !saveBtn) { return; }

        var connectStatusEl = document.getElementById("sp-stripe-connect-status");
        var stripeKeyInput = document.getElementById("stripe_api_key");
        var stripeWhInput = document.getElementById("stripe_webhook_secret");

        function updateStripeConnectionStatus() {
            if (!connectStatusEl || !stripeKeyInput || !stripeWhInput) { return; }
            var connected = stripeKeyInput.value.trim() !== "" && stripeWhInput.value.trim() !== "";
            var label = connectStatusEl.querySelector(".sp-stripe-connect-status__label");
            var lc = connectStatusEl.getAttribute("data-label-connected") || "Connected";
            var ln = connectStatusEl.getAttribute("data-label-not") || "Not connected";
            if (connected) {
                connectStatusEl.classList.add("is-connected");
                if (label) { label.textContent = lc; }
            } else {
                connectStatusEl.classList.remove("is-connected");
                if (label) { label.textContent = ln; }
            }
        }

        updateStripeConnectionStatus();

        function getSerializedState() {
            var data = new FormData(form);
            var entries = [];
            data.forEach(function(value, key){ entries.push(key + "=" + value); });
            entries.sort();
            return entries.join("&");
        }

        var baselineState = getSerializedState();

        function setSaveDirtyState() {
            var dirty = getSerializedState() !== baselineState;
            saveBtn.disabled = !dirty;
            if (saveBtn.disabled) {
                saveBtn.classList.add("sp-save-disabled");
            } else {
                saveBtn.classList.remove("sp-save-disabled");
            }
        }

        setSaveDirtyState();

        form.addEventListener("input", function(){
            setSaveDirtyState();
            updateStripeConnectionStatus();
        });
        form.addEventListener("change", function(){
            setSaveDirtyState();
            updateStripeConnectionStatus();
        });

        var secretToggles = document.querySelectorAll(".sp-secret-field__toggle");
        Array.prototype.forEach.call(secretToggles, function(btn){
            btn.addEventListener("click", function(){
                var wrap = btn.closest(".sp-secret-field");
                if (!wrap) { return; }
                var masked = wrap.querySelector(".sp-secret-field__masked");
                var real = wrap.querySelector(".sp-secret-field__real");
                if (!masked || !real) { return; }
                var revealed = real.style.display !== "none";
                if (revealed) {
                    real.style.display = "none";
                    masked.style.display = "";
                    btn.textContent = "Reveal";
                    btn.setAttribute("aria-pressed", "false");
                } else {
                    masked.style.display = "none";
                    real.style.display = "";
                    btn.textContent = "Hide";
                    btn.setAttribute("aria-pressed", "true");
                    real.focus();
                }
            });
        });
    })();

    // --- Setup wizard step 1 ---
    (function(){
        var sub = document.getElementById("sp-ob-enable-subscription");
        var prices = document.getElementById("sp-ob-subscription-fields");
        var form = document.getElementById("sp-onboarding-step1-form");
        if (!form) { return; }
        function syncSub() {
            if (!sub || !prices) { return; }
            var on = sub.checked;
            prices.classList.toggle("sp-onboarding-panel-hidden", !on);
            var ins = prices.querySelectorAll("input");
            for (var i = 0; i < ins.length; i++) { ins[i].disabled = !on; }
        }
        function syncUnlock() {
            var r = form.querySelector('input[name="onboarding_unlock_model"]:checked');
            if (!r) { return; }
            var v = r ? r.value : "tip";
            var tipBox = document.getElementById("sp-ob-tip-fields");
            var artBox = document.getElementById("sp-ob-article-fields");
            if (tipBox) {
                tipBox.classList.toggle("sp-onboarding-panel-hidden", v !== "tip");
                var ti = tipBox.querySelectorAll("input");
                for (var j = 0; j < ti.length; j++) { ti[j].disabled = v !== "tip"; }
            }
            if (artBox) {
                artBox.classList.toggle("sp-onboarding-panel-hidden", v !== "article");
                var ai = artBox.querySelectorAll("input");
                for (var k = 0; k < ai.length; k++) { ai[k].disabled = v !== "article"; }
            }
        }
        if (sub) { sub.addEventListener("change", syncSub); }
        form.addEventListener("change", function(e) {
            if (e.target && e.target.name === "onboarding_unlock_model") { syncUnlock(); }
        });
        syncSub();
        syncUnlock();

        var recBtn = document.getElementById("sp-ob-use-recommended");
        if (recBtn && typeof spOnboardingStep1Recommended === "object" && spOnboardingStep1Recommended) {
            recBtn.addEventListener("click", function() {
                var r = spOnboardingStep1Recommended;
                var mo = document.getElementById("sp-ob-sub-monthly");
                var yr = document.getElementById("sp-ob-sub-annual");
                var dt = document.getElementById("sp-ob-default-tip");
                var mt = document.getElementById("sp-ob-min-tip");
                var ap = document.getElementById("sp-ob-article-price");
                if (sub) { sub.checked = true; }
                if (mo) { mo.value = parseFloat(String(r.subscription_price_monthly)).toFixed(2); }
                if (yr) { yr.value = parseFloat(String(r.subscription_price_annual)).toFixed(2); }
                if (dt && typeof r.default_tip_amount !== "undefined") { dt.value = parseFloat(String(r.default_tip_amount)).toFixed(2); }
                if (mt && typeof r.minimum_tip_amount !== "undefined") { mt.value = parseFloat(String(r.minimum_tip_amount)).toFixed(2); }
                if (ap && typeof r.article_unlock_price !== "undefined") { ap.value = parseFloat(String(r.article_unlock_price)).toFixed(2); }
                syncSub();
                syncUnlock();
            });
        }
    })();

    // --- Setup wizard Stripe step ---
    (function(){
        var form = document.getElementById("sp-onboarding-step3-form");
        var copyBtn = document.getElementById("sp-onboarding-copy-webhook-url");
        var urlInput = document.getElementById("sp-onboarding-stripe-webhook-url");
        if (copyBtn && urlInput) {
            copyBtn.addEventListener("click", function() {
                var url = urlInput.value;
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(url).then(function() {
                        var t = copyBtn.textContent;
                        copyBtn.textContent = "Copied!";
                        setTimeout(function(){ copyBtn.textContent = t; }, 1500);
                    });
                } else {
                    urlInput.select();
                    try { document.execCommand("copy"); } catch (e) {}
                }
            });
        }
        if (!form) { return; }
        var connectStatusEl = document.getElementById("sp-onboarding-stripe-status");
        var stripeKeyInput = document.getElementById("stripe_api_key");
        var stripeWhInput = document.getElementById("stripe_webhook_secret");
        function updateStripeConnectionStatus() {
            if (!connectStatusEl || !stripeKeyInput || !stripeWhInput) { return; }
            var connected = stripeKeyInput.value.trim() !== "" && stripeWhInput.value.trim() !== "";
            var label = connectStatusEl.querySelector(".sp-stripe-connect-status__label");
            var lc = connectStatusEl.getAttribute("data-label-connected") || "Connected";
            var ln = connectStatusEl.getAttribute("data-label-not") || "Not connected";
            if (connected) {
                connectStatusEl.classList.add("is-connected");
                if (label) { label.textContent = lc; }
            } else {
                connectStatusEl.classList.remove("is-connected");
                if (label) { label.textContent = ln; }
            }
        }
        updateStripeConnectionStatus();
        if (stripeKeyInput) { stripeKeyInput.addEventListener("input", updateStripeConnectionStatus); }
        if (stripeWhInput) { stripeWhInput.addEventListener("input", updateStripeConnectionStatus); }

        var secretToggles = form.querySelectorAll(".sp-secret-field__toggle");
        Array.prototype.forEach.call(secretToggles, function(btn){
            btn.addEventListener("click", function(){
                var wrap = btn.closest(".sp-secret-field");
                if (!wrap) { return; }
                var masked = wrap.querySelector(".sp-secret-field__masked");
                var real = wrap.querySelector(".sp-secret-field__real");
                if (!masked || !real) { return; }
                var revealed = real.style.display !== "none";
                if (revealed) {
                    real.style.display = "none";
                    masked.style.display = "";
                    btn.textContent = "Reveal";
                    btn.setAttribute("aria-pressed", "false");
                } else {
                    masked.style.display = "none";
                    real.style.display = "";
                    btn.textContent = "Hide";
                    btn.setAttribute("aria-pressed", "true");
                    real.focus();
                }
            });
        });
    })();

    // --- Setup wizard continue-despite-warning ---
    (function(){
        function getPanelParts(panelId) {
            return {
                root: document.getElementById(panelId),
                initial: document.getElementById(panelId + "-initial"),
                confirm: document.getElementById(panelId + "-confirm")
            };
        }
        document.querySelectorAll(".sp-continue-despite-warning__trigger").forEach(function(link) {
            link.addEventListener("click", function(e) {
                e.preventDefault();
                var panelId = link.getAttribute("data-panel-id");
                if (!panelId) { return; }
                var parts = getPanelParts(panelId);
                if (parts.initial) { parts.initial.classList.add("sp-onboarding-panel-hidden"); }
                if (parts.confirm) { parts.confirm.classList.remove("sp-onboarding-panel-hidden"); }
            });
        });
        document.querySelectorAll(".sp-continue-despite-warning__go-back").forEach(function(btn) {
            btn.addEventListener("click", function() {
                var panelId = btn.getAttribute("data-panel-id");
                if (!panelId) { return; }
                var parts = getPanelParts(panelId);
                if (parts.initial) { parts.initial.classList.remove("sp-onboarding-panel-hidden"); }
                if (parts.confirm) { parts.confirm.classList.add("sp-onboarding-panel-hidden"); }
            });
        });
        document.querySelectorAll(".sp-continue-despite-warning__continue").forEach(function(btn) {
            btn.addEventListener("click", function() {
                var panelId = btn.getAttribute("data-panel-id");
                if (!panelId) { return; }
                var parts = getPanelParts(panelId);
                if (parts.root) { parts.root.classList.add("sp-onboarding-panel-hidden"); }
            });
        });
    })();

})();
