(function () {
    var RSPData = window.newssyncAutoImportData || window.RSPAutoImportData || {};
    var RSPAdmin = window.newssyncAdminData || window.RSPAdminData || {};
    var ajaxurl = typeof window.ajaxurl !== 'undefined' ? window.ajaxurl : (RSPData.ajax_url || '');

    const IMPORTING_TEXT      = RSPData.importing_text || 'Importing...';
    const ERROR_IMPORT_TEXT   = RSPData.error_import_text || 'Error during import';
    const TIMEOUT_MSG_TEXT    = RSPData.timeout_msg_text || 'Import timed out or error — check posts for results.';
    const FORCE_LABEL         = RSPData.force_label || 'Force Import Now';
    const NONCE               = RSPData.nonce || '';
    const CLEAR_CACHE_NONCE   = RSPData.clear_cache_nonce || '';
    const CLEARING_TEXT       = RSPData.clearing_text || 'Clearing cache...';
    const CACHE_CLEARED_TEXT  = RSPData.cache_cleared_text || 'Cache cleared';

    var confirmText = (RSPAdmin && RSPAdmin.i18n && RSPAdmin.i18n.confirm) || 'Are you sure you want to clear the cache?';

    document.addEventListener("DOMContentLoaded", function () {
        const select = document.querySelector("select[name='newssync_save_as_posts']");
        const forceButton = document.getElementById("rsp-force-import-btn");
        const clearBtn = document.querySelector(".rsp-clear-cache-btn");
        const statusEl = document.getElementById("rsp-import-status");

        function updateForceButton() {
            if (select && forceButton) {
                forceButton.style.display = (select.value === "1") ? "inline-block" : "none";
            }
        }

        updateForceButton();
        if (select) select.addEventListener("change", updateForceButton);

        if (forceButton) {
            forceButton.addEventListener("click", function (e) {
                e.preventDefault();
                const btn = this;
                btn.disabled = true;
                btn.textContent = IMPORTING_TEXT;
                if (statusEl) statusEl.innerHTML = "";

                const controller = new AbortController();
                const timeoutId = setTimeout(function () { controller.abort(); }, 120000);

                fetch(ajaxurl, {
                    method: "POST",
                    credentials: "same-origin",
                    signal: controller.signal,
                    body: new URLSearchParams({
                        "action": "newssync_force_import",
                        "_ajax_nonce": NONCE
                    })
                })
                .then(function (r) {
                    clearTimeout(timeoutId);
                    return r.json();
                })
                .then(function (data) {
                    if (statusEl) {
                        if (data && data.success) {
                            statusEl.innerHTML = "<span style=\"color:green;\">✓ " + (data.data && data.data.message ? data.data.message : 'Import started') + "</span>";
                        } else {
                            statusEl.innerHTML = "<span style=\"color:red;\">" + ERROR_IMPORT_TEXT + "</span>";
                        }
                    }
                })
                .catch(function () {
                    if (statusEl) statusEl.innerHTML = "<span style=\"color:orange;\">" + TIMEOUT_MSG_TEXT + "</span>";
                })
                .finally(function () {
                    btn.disabled = false;
                    btn.textContent = FORCE_LABEL;
                });
            });
        }

        // Clear cache: if button is inside a form, only confirm (allow form submit).
        // If the button is standalone, perform AJAX fallback.
        if (clearBtn) {
            clearBtn.addEventListener('click', function (e) {
                var inForm = !!this.closest('form');

                if (!confirm(confirmText)) {
                    e.preventDefault();
                    return;
                }

                if (inForm) {
                    // allow the form to submit normally to admin-post.php
                    return;
                }

                // No form found — fallback to AJAX
                e.preventDefault();
                var btn = this;
                var original = btn.textContent;
                btn.disabled = true;
                btn.textContent = CLEARING_TEXT;

                var endpoint = (RSPAdmin && RSPAdmin.admin_post_url) ? RSPAdmin.admin_post_url : (RSPData.ajax_url || ajaxurl);
                var body = new URLSearchParams();
                body.append('action', 'newssync_clear_cache');

                if (typeof CLEAR_CACHE_NONCE !== 'undefined' && CLEAR_CACHE_NONCE) {
                    body.append('_wpnonce', CLEAR_CACHE_NONCE);
                } else if (RSPData && RSPData.nonce) {
                    body.append('_ajax_nonce', RSPData.nonce);
                }

                fetch(endpoint, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: body
                })
                .then(function (r) {
                    var ct = r.headers.get('content-type') || '';
                    if (ct.indexOf('application/json') !== -1) {
                        return r.json();
                    }
                    return r.text().then(function (t) { return { fallback_text: t }; });
                })
                .then(function (data) {
                    if (data && data.success) {
                        btn.textContent = CACHE_CLEARED_TEXT;
                        setTimeout(function () { btn.textContent = original; }, 1600);
                    } else if (data && data.fallback_text) {
                        console.log('newssync_clear_cache response:', data.fallback_text);
                        btn.textContent = original;
                    } else {
                        btn.textContent = original;
                    }
                })
                .catch(function (err) {
                    console.error('Clear cache failed:', err);
                    btn.textContent = original;
                })
                .finally(function () {
                    btn.disabled = false;
                });
            });
        }
    });
})();