(function () {
    'use strict';

    function handleDisconnect(e) {
        e.preventDefault();
        const btn = e.currentTarget;

        if (confirm(seekmakeSettings.confirmMsg)) {
            btn.style.pointerEvents = 'none';
            btn.style.opacity = '0.7';
            const originalText = btn.innerHTML;
            btn.innerHTML = '<span class="dashicons dashicons-update-alt" style="margin-top: 3px; animation: rotation 1s infinite linear;"></span> ' + seekmakeSettings.disconnectingMsg;

            const formData = new FormData();
            formData.append('action', 'seekmake_disconnect_account');
            formData.append('seekmake_nonce', seekmakeSettings.nonce);

            fetch(seekmakeSettings.ajaxUrl, {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.cookie.split(";").forEach(function (c) {
                            document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/");
                        });

                        window.location.href = seekmakeSettings.redirectUrl + Date.now();
                    } else {
                        alert(seekmakeSettings.failMsg);
                        btn.style.pointerEvents = 'auto';
                        btn.style.opacity = '1';
                        btn.innerHTML = originalText;
                    }
                })
                .catch(error => {
                    alert(seekmakeSettings.errorMsg);
                    btn.style.pointerEvents = 'auto';
                    btn.style.opacity = '1';
                    btn.innerHTML = originalText;
                });
        }
    }

    const settingsBtn = document.getElementById('seekmake-settings-disconnect');
    if (settingsBtn) {
        settingsBtn.addEventListener('click', handleDisconnect);
    }

    const dashboardBtn = document.getElementById('seekmake-dashboard-disconnect');
    if (dashboardBtn) {
        dashboardBtn.addEventListener('click', handleDisconnect);
    }

})();
