/**
 * BotFend Anti-Bot Firewall - Dashboard Scripts
 * @version 5.0.0 - Cleaned and optimized collapsible sections
 */
(function($) {
    'use strict';
    
    // Only initialize on the dashboard page
    if (!$('.botfend-dashboard-wrap').length) {
        return;
    }
    
    // ============================================
    // CONFIRMATION DIALOGS
    // ============================================
    $('.botfend-dashboard-wrap').on('click', '.botfend-confirm-action', function(e) {
        var confirmMsg = $(this).data('confirm');
        if (confirmMsg && !confirm(confirmMsg)) {
            e.preventDefault();
            return false;
        }
    });

    /**
     * BotFend Anti-Bot Firewall Dashboard - Collapsible Sections
     */
    jQuery(document).ready(function($) {
        // Target all main card headers across the dashboard
        var headers = $('.botfend-card-header, .botfend-protection-header');

        headers.each(function() {
            var $header = $(this);
            var $card = $header.parent();
            
            // Create a unique ID for local storage based on the header text
            var titleText = $header.text().trim().replace(/[^a-z0-9]/gi, '-').toLowerCase();
            if (!titleText) return; // Skip if no title
            var storageKey = 'botfend_toggle_' + titleText;

            // Apply flexbox to align the new arrow to the right safely
            $header.css({
                'display': 'flex',
                'align-items': 'center',
                'cursor': 'pointer',
                'user-select': 'none'
            });

            // Ensure the h2/h3 takes up the remaining space
            $header.find('h2, h3').css({
                'margin': '0',
                'margin-left': '8px',
                'flex-grow': '1'
            });

            // Append the toggle arrow
            $header.append('<span class="dashicons dashicons-arrow-up-alt2 botfend-section-toggle" style="margin-left: auto; color: #a7aaad; transition: transform 0.2s ease;"></span>');

            // Find the content body (everything in the card except the header)
            var $body = $card.children().not($header);

            // Check local storage for previous state
            if (localStorage.getItem(storageKey) === 'collapsed') {
                $body.hide();
                $header.find('.botfend-section-toggle').removeClass('dashicons-arrow-up-alt2').addClass('dashicons-arrow-down-alt2');
            }

            // Click event to toggle
            $header.on('click', function() {
                var $icon = $(this).find('.botfend-section-toggle');

                $body.slideToggle(250, function() {
                    if ($body.is(':visible')) {
                        $icon.removeClass('dashicons-arrow-down-alt2').addClass('dashicons-arrow-up-alt2');
                        localStorage.setItem(storageKey, 'expanded');
                    } else {
                        $icon.removeClass('dashicons-arrow-up-alt2').addClass('dashicons-arrow-down-alt2');
                        localStorage.setItem(storageKey, 'collapsed');
                    }
                });
            });
        });
    });

    // ============================================
    // DASHBOARD REFRESH
    // ============================================
    $('.botfend-dashboard-wrap').on('click', '.botfend-refresh-dashboard', function() {
        var $btn = $(this);
        var originalHtml = $btn.html();
        
        $btn.prop('disabled', true).html(
            '<span class="dashicons dashicons-update dashicons-update-spin"></span> ' + 
            botfendDashboard.refreshingText
        );
        
        $.ajax({
            url: botfendDashboard.ajax_url,
            type: 'POST',
            data: {
                action: 'botfend_refresh_dashboard',
                nonce: botfendDashboard.refreshNonce
            },
            success: function(response) {
                if (response.success) {
                    showToast(botfendDashboard.refreshSuccess, 'success');
                    setTimeout(function() { location.reload(); }, 500);
                } else {
                    $btn.prop('disabled', false).html(originalHtml);
                    showToast(response.data.message || botfendDashboard.refreshFailed, 'error');
                }
            },
            error: function() {
                $btn.prop('disabled', false).html(originalHtml);
                showToast(botfendDashboard.errorOccurred, 'error');
            }
        });
    });
    
    // ============================================
    // REFRESH THREAT FEEDS
    // ============================================
    $('.botfend-dashboard-wrap').on('click', '#botfend-refresh-threat-feeds', function(e) {
        e.preventDefault();
        
        var $btn = $(this);
        var $status = $('#botfend-threat-feed-status');
        var originalHtml = $btn.html();
        
        if (!botfendDashboard.threatFeedsNonce) {
            showToast('Security token missing. Please refresh the page.', 'error');
            return;
        }
        
        $btn.prop('disabled', true).html(
            '<span class="dashicons dashicons-update dashicons-update-spin"></span> ' + 
            botfendDashboard.updatingFeedsText
        );
        $status.html('<span style="color: #0073aa;">' + botfendDashboard.pleaseWaitText + '</span>');
        
        $.ajax({
            url: botfendDashboard.ajax_url,
            type: 'POST',
            data: {
                action: 'botfend_force_update_threat_feeds',
                nonce: botfendDashboard.threatFeedsNonce
            },
            timeout: 65000,
            success: function(response) {
                $btn.prop('disabled', false).html(originalHtml);
                
                if (response.success) {
                    $status.html('<span style="color: #46b450;">✓ ' + response.data.message + '</span>');
                    if (response.data.last_update) {
                        $('#botfend-threat-last-sync').text(response.data.last_update);
                    }
                    setTimeout(function() { location.reload(); }, 1500);
                } else {
                    var errorMsg = response.data?.message || botfendDashboard.unknownErrorText;
                    $status.html('<span style="color: #dc3232;">✗ ' + errorMsg + '</span>');
                }
            },
            error: function(xhr, status) {
                $btn.prop('disabled', false).html(originalHtml);
                var errorMessage = status === 'timeout' ? 
                    botfendDashboard.requestTimeoutText : 
                    botfendDashboard.serverTimeoutText;
                $status.html('<span style="color: #dc3232;">✗ ' + errorMessage + '</span>');
            }
        });
    });

    // ============================================
    // UPDATE TOR NODES
    // ============================================
    $('.botfend-dashboard-wrap').on('click', '.botfend-update-tor-nodes', function(e) {
        e.preventDefault();
        
        var $btn = $(this);
        var originalHtml = $btn.html();
        
        if (!botfendDashboard.torNodesNonce) {
            showToast('Security token missing. Please refresh the page.', 'error');
            return;
        }
        
        $btn.prop('disabled', true).html(
            '<span class="dashicons dashicons-update dashicons-update-spin"></span> ' + 
            botfendDashboard.updatingTorText
        );
        
        $.ajax({
            url: botfendDashboard.ajax_url,
            type: 'POST',
            data: {
                action: 'botfend_update_tor_nodes',
                nonce: botfendDashboard.torNodesNonce
            },
            success: function(response) {
                if (response.success) {
                    showToast(response.data.message, 'success');
                    setTimeout(function() { location.reload(); }, 1500);
                } else {
                    $btn.prop('disabled', false).html(originalHtml);
                    showToast(response.data.message || 'Update failed', 'error');
                }
            },
            error: function() {
                $btn.prop('disabled', false).html(originalHtml);
                showToast('Connection error', 'error');
            }
        });
    });
    
    // ============================================
    // TOAST NOTIFICATION
    // ============================================
    function showToast(message, type) {
        var $toast = $('#botfend-dashboard-toast');
        
        if (!$toast.length) {
            $toast = $('<div id="botfend-dashboard-toast" class="botfend-toast"></div>').appendTo('body');
        }
        
        $toast.removeClass('success error warning').addClass(type);
        $toast.html('<span class="dashicons"></span><span class="toast-message">' + message + '</span>');
        $toast.addClass('show');
        
        setTimeout(function() {
            $toast.removeClass('show');
        }, 3000);
    }
    
    // ============================================
    // TOOLTIP INITIALIZATION
    // ============================================
    function initTooltips() {
        $('.botfend-dashboard-wrap .botfend-tooltip').each(function() {
            var $el = $(this);
            var title = $el.attr('title');
            
            if (!title) return;
            
            $el.data('tooltip', title).removeAttr('title');
            
            $el.on('mouseenter', function() {
                var $tooltip = $('<div class="botfend-tooltip-box">' + $el.data('tooltip') + '</div>');
                $('body').append($tooltip);
                
                var offset = $el.offset();
                $tooltip.css({
                    top: offset.top - $tooltip.outerHeight() - 8,
                    left: offset.left + ($el.outerWidth() / 2) - ($tooltip.outerWidth() / 2)
                });
                
                setTimeout(function() { $tooltip.addClass('visible'); }, 10);
                $el.data('tooltip-instance', $tooltip);
            });
            
            $el.on('mouseleave', function() {
                var $tooltip = $el.data('tooltip-instance');
                if ($tooltip) {
                    $tooltip.remove();
                    $el.removeData('tooltip-instance');
                }
            });
        });
    }
    
    // ============================================
    // ADD DYNAMIC STYLES
    // ============================================
    function addDynamicStyles() {
        var styles = {
            'botfend-spin-style-dash': 
                '.dashicons-update-spin{animation:dashicons-spin 1s infinite linear;display:inline-block}' +
                '@keyframes dashicons-spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}',
            
            'botfend-toast-style':
                '.botfend-toast{position:fixed;bottom:24px;right:24px;padding:12px 20px;border-radius:8px;color:#fff;font-size:14px;font-weight:500;display:flex;align-items:center;gap:10px;box-shadow:0 4px 12px rgba(0,0,0,0.15);transform:translateX(400px);transition:transform 0.3s ease;z-index:10000}' +
                '.botfend-toast.show{transform:translateX(0)}' +
                '.botfend-toast.success{background:#46b450}' +
                '.botfend-toast.error{background:#dc3232}' +
                '.botfend-toast.warning{background:#ffb900}' +
                '.botfend-toast .dashicons{font-size:18px;width:18px;height:18px}' +
                '.botfend-toast.success .dashicons:before{content:"\\f147"}' +
                '.botfend-toast.error .dashicons:before{content:"\\f158"}' +
                '.botfend-toast.warning .dashicons:before{content:"\\f534"}',
            
            'botfend-tooltip-style':
                '.botfend-tooltip-box{position:absolute;background:#1d2327;color:#fff;padding:6px 12px;border-radius:4px;font-size:12px;white-space:nowrap;z-index:10001;opacity:0;transition:opacity 0.15s ease;pointer-events:none}' +
                '.botfend-tooltip-box.visible{opacity:1}' +
                '.botfend-tooltip-box:after{content:"";position:absolute;top:100%;left:50%;margin-left:-5px;border-width:5px;border-style:solid;border-color:#1d2327 transparent transparent transparent}'
        };
        
        $.each(styles, function(id, css) {
            if (!$('#' + id).length) {
                $('head').append('<style id="' + id + '">' + css + '</style>');
            }
        });
    }
    
    // ============================================
    // INITIALIZE
    // ============================================
    function initialize() {
        addDynamicStyles();
        initTooltips();
    }
    
    initialize();
    
    // ============================================
    // EXPOSE PUBLIC FUNCTIONS
    // ============================================
    window.botfendDashboard = window.botfendDashboard || {};
    window.botfendDashboard.showToast = showToast;
    window.botfendDashboard.refresh = function() {
        $('.botfend-dashboard-wrap .botfend-refresh-dashboard').trigger('click');
    };
    
})(jQuery);