/* jshint esversion: 6 */
/* globals ajaxurl, flowdino_ajax, flowdino_data, jQuery */

// Système de confirmation moderne pour les settings
function showFlowDinoConfirm(message, onConfirm, onCancel) {
    var existingConfirms = document.querySelectorAll('.flowdino-confirm-dialog');
    existingConfirms.forEach(function(c) { c.remove(); });

    var overlay = document.createElement('div');
    overlay.className = 'flowdino-confirm-overlay';
    overlay.style.cssText =
        'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);' +
        'z-index:100000;display:flex;align-items:center;justify-content:center;';

    var dialog = document.createElement('div');
    dialog.className = 'flowdino-confirm-dialog';
    dialog.style.cssText =
        'background:white;border-radius:8px;padding:24px;box-shadow:0 8px 40px rgba(0,0,0,0.3);' +
        'max-width:400px;min-width:300px;animation:flowdinoFadeIn 0.3s ease-out;' +
        'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;';

    dialog.innerHTML =
        '<div class="flowdino-confirm-content">' +
        '<div class="flowdino-confirm-icon" style="text-align:center;margin-bottom:16px;font-size:24px;">⚠️</div>' +
        '<div class="flowdino-confirm-message" style="text-align:center;margin-bottom:24px;font-size:16px;line-height:1.4;color:#333;">' + message + '</div>' +
        '<div class="flowdino-confirm-buttons" style="display:flex;gap:12px;justify-content:center;">' +
        '<button class="flowdino-confirm-cancel" style="padding:10px 20px;border:2px solid #ddd;background:white;color:#666;border-radius:6px;cursor:pointer;font-size:14px;font-weight:500;">' +
        flowdino_data.i18n.cancel + '</button>' +
        '<button class="flowdino-confirm-ok" style="padding:10px 20px;border:2px solid #dc3545;background:#dc3545;color:white;border-radius:6px;cursor:pointer;font-size:14px;font-weight:500;">' +
        flowdino_data.i18n.disconnect + '</button>' +
        '</div></div>';

    var cancelBtn = dialog.querySelector('.flowdino-confirm-cancel');
    var okBtn     = dialog.querySelector('.flowdino-confirm-ok');

    cancelBtn.onmouseover = function() { cancelBtn.style.background = '#f5f5f5'; };
    cancelBtn.onmouseout  = function() { cancelBtn.style.background = 'white'; };
    okBtn.onmouseover = function() { okBtn.style.background = '#c82333'; };
    okBtn.onmouseout  = function() { okBtn.style.background = '#dc3545'; };

    var closeDialog = function() {
        overlay.style.animation = 'flowdinoFadeOut 0.3s ease-in';
        setTimeout(function() { overlay.remove(); }, 300);
    };

    cancelBtn.onclick = function() { closeDialog(); if (onCancel) { onCancel(); } };
    okBtn.onclick     = function() { closeDialog(); if (onConfirm) { onConfirm(); } };

    overlay.onclick = function(e) {
        if (e.target === overlay) { closeDialog(); if (onCancel) { onCancel(); } }
    };

    overlay.appendChild(dialog);
    document.body.appendChild(overlay);
    setTimeout(function() { cancelBtn.focus(); }, 100);
    return overlay;
}

function confirmDisconnect(event) {
    event.preventDefault();
    showFlowDinoConfirm(
        flowdino_data.i18n.disconnect_confirm,
        function() {
            var form = event.target.closest('form');
            if (form) {
                var disconnectInput = document.createElement('input');
                disconnectInput.type  = 'hidden';
                disconnectInput.name  = 'disconnect_flowdino';
                disconnectInput.value = '1';
                form.appendChild(disconnectInput);
                form.submit();
            }
        }
    );
}

jQuery(document).ready(function($) {
    $('#test-connection').on('click', function() {
        var button    = $(this);
        var resultDiv = $('#connection-test-result');

        button.prop('disabled', true).text(flowdino_data.i18n.connecting);
        resultDiv.html('');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'flowdino_test_connection',
                nonce: flowdino_ajax.test_nonce
            },
            success: function(response) {
                if (response.success) {
                    resultDiv.html('<div class="notice notice-success"><p><strong>' + flowdino_data.i18n.connection_success + '</strong> ' + response.data.message + '</p></div>');
                    setTimeout(function() { window.location.reload(); }, 2000);
                } else {
                    resultDiv.html('<div class="notice notice-error"><p><strong>' + flowdino_data.i18n.connection_failed + '</strong> ' + response.data.message + '</p></div>');
                }
            },
            error: function() {
                resultDiv.html('<div class="notice notice-error"><p><strong>' + flowdino_data.i18n.error_colon + '</strong> ' + flowdino_data.i18n.unable_test + '</p></div>');
            },
            complete: function() {
                button.prop('disabled', false).text(flowdino_data.i18n.connect_btn);
            }
        });
    });

    // Bouton de reconnexion forcée
    $('#force-reconnect').on('click', function() {
        var button    = $(this);
        var resultDiv = $('#connection-test-result');

        button.prop('disabled', true).text('🔄 Reconnexion...');
        resultDiv.html('<div class="notice notice-info"><p>Tentative de reconnexion forcée...</p></div>');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'flowdino_force_reconnect',
                nonce: flowdino_ajax.force_nonce
            },
            success: function(response) {
                if (response.success) {
                    resultDiv.html('<div class="notice notice-success"><p><strong>✅ Reconnexion réussie!</strong> ' + response.data.message + '</p></div>');
                    setTimeout(function() { window.location.reload(); }, 2000);
                } else {
                    resultDiv.html('<div class="notice notice-error"><p><strong>❌ Reconnexion échouée:</strong> ' + response.data.message + '</p></div>');
                }
            },
            error: function() {
                resultDiv.html('<div class="notice notice-error"><p><strong>Erreur:</strong> Impossible de forcer la reconnexion.</p></div>');
            },
            complete: function() {
                button.prop('disabled', false).text('🔄 Forcer Reconnexion');
            }
        });
    });
});
