/**
 * Mamba Cache - Tab-specific JavaScript
 * 
 * This file contains JavaScript for all admin tabs.
 * Dynamic data is passed via wp_localize_script() as MambaTabs object.
 */
(function($) {
    'use strict';

    // Wait for DOM ready
    $(document).ready(function() {
        // Determine which tab we're on - use localized data first, DOM fallback
        var currentTab = (typeof MambaTabs !== 'undefined' && MambaTabs.currentTab) 
            ? MambaTabs.currentTab 
            : ($('[data-tab]').data('tab') || '');
        
        // Initialize tab-specific functionality
        switch(currentTab) {
            case 'logs':
                initLogsTab();
                break;
            case 'cdn':
                initCdnTab();
                break;
            case 'db':
                initDbTab();
                break;
            case 'caching':
                initCachingTab();
                break;
            case 'overhead':
                initOverheadTab();
                break;
            case 'media':
                initMediaTab();
                break;
        }
    });

    /**
     * Logs Tab
     */
    function initLogsTab() {
        if (typeof MambaTabs === 'undefined' || !MambaTabs.logs) return;
        
        var currentOffset = 0;
        var currentLimit = 100;
        var nonce = MambaTabs.logs.nonce;
        
        // Load logs on page load
        loadLogs();
        
        // Refresh logs
        $('#mamba-refresh-logs').on('click', function() {
            currentOffset = 0;
            loadLogs();
        });
        
        // Filter change
        $('#mamba-log-date, #mamba-log-level-filter').on('change', function() {
            currentOffset = 0;
            loadLogs();
        });
        
        // Load more
        $('#mamba-load-more').on('click', function() {
            currentOffset += currentLimit;
            loadLogs(true);
        });
        
        // Save settings (button click)
        $('#mamba-save-log-settings').on('click', function() {
            saveLogSettings($(this));
        });
        
        // Auto-save on toggle change
        $('#mamba_enable_logging, #mamba_debug_mode').on('change', function() {
            saveLogSettings($('#mamba-save-log-settings'));
        });
        
        // Auto-save on select change
        $('#mamba_log_level, #mamba_log_retention').on('change', function() {
            saveLogSettings($('#mamba-save-log-settings'));
        });
        
        function saveLogSettings($btn) {
            $btn.prop('disabled', true).find('.dashicons').addClass('spin');
            
            $.post(ajaxurl, {
                action: 'mamba_save_log_settings',
                nonce: nonce,
                debug_mode: $('#mamba_debug_mode').is(':checked') ? '1' : '0',
                logging_enabled: $('#mamba_enable_logging').is(':checked') ? '1' : '0',
                log_level: $('#mamba_log_level').val(),
                retention_days: $('#mamba_log_retention').val()
            }, function(response) {
                $btn.prop('disabled', false).find('.dashicons').removeClass('spin');
                if (response.success) {
                    showNotice(MambaTabs.logs.i18n.settingsSaved || 'Settings saved successfully', 'success');
                } else {
                    showNotice(response.data.message || MambaTabs.logs.i18n.errorSaving || 'Error saving settings', 'error');
                }
            }).fail(function() {
                $btn.prop('disabled', false).find('.dashicons').removeClass('spin');
                showNotice(MambaTabs.logs.i18n.errorSaving || 'Error saving settings', 'error');
            });
        }
        
        // Export logs
        $('#mamba-export-logs').on('click', function() {
            var $btn = $(this);
            $btn.prop('disabled', true);
            
            $.post(ajaxurl, {
                action: 'mamba_export_logs',
                nonce: nonce,
                days: $('#mamba-export-days').val()
            }, function(response) {
                $btn.prop('disabled', false);
                if (response.success) {
                    var blob = new Blob([response.data.content], {type: 'application/json'});
                    var url = URL.createObjectURL(blob);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = response.data.filename;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                    showNotice(MambaTabs.logs.i18n.exportSuccess || 'Logs exported successfully', 'success');
                } else {
                    showNotice(response.data.message || MambaTabs.logs.i18n.exportError || 'Error exporting logs', 'error');
                }
            });
        });
        
        // Clear logs
        $('#mamba-clear-logs').on('click', function() {
            if (!confirm(MambaTabs.logs.i18n.confirmClear || 'Are you sure you want to delete all log files? This cannot be undone.')) {
                return;
            }
            
            var $btn = $(this);
            $btn.prop('disabled', true);
            
            $.post(ajaxurl, {
                action: 'mamba_clear_logs',
                nonce: nonce
            }, function(response) {
                $btn.prop('disabled', false);
                if (response.success) {
                    showNotice(response.data.message, 'success');
                    loadLogs();
                } else {
                    showNotice(response.data.message || MambaTabs.logs.i18n.clearError || 'Error clearing logs', 'error');
                }
            });
        });
        
        function loadLogs(append) {
            var $viewer = $('#mamba-log-viewer');
            
            if (!append) {
                $viewer.html('<div class="mamba-log-loading"><span class="dashicons dashicons-update spin"></span> ' + (MambaTabs.logs.i18n.loading || 'Loading logs...') + '</div>');
            }
            
            $.post(ajaxurl, {
                action: 'mamba_get_logs',
                nonce: nonce,
                date: $('#mamba-log-date').val(),
                level: $('#mamba-log-level-filter').val(),
                limit: currentLimit,
                offset: currentOffset
            }, function(response) {
                if (response.success) {
                    renderLogs(response.data, append);
                } else {
                    $viewer.html('<div class="mamba-log-empty">' + (MambaTabs.logs.i18n.errorLoading || 'Error loading logs') + '</div>');
                }
            });
        }
        
        function renderLogs(data, append) {
            var $viewer = $('#mamba-log-viewer');
            var $pagination = $('#mamba-log-pagination');
            var $count = $('#mamba-log-count');
            
            if (!data.entries.length && !append) {
                $viewer.html('<div class="mamba-log-empty"><span class="dashicons dashicons-info"></span> ' + (MambaTabs.logs.i18n.noEntries || 'No log entries found') + '</div>');
                $pagination.hide();
                return;
            }
            
            var html = '';
            data.entries.forEach(function(entry) {
                var levelClass = (entry.level || 'info').toLowerCase();
                html += '<div class="mamba-log-entry level-' + levelClass + '">';
                html += '<span class="mamba-log-timestamp">' + escapeHtml(entry.timestamp || '') + '</span>';
                html += '<span class="mamba-log-level ' + levelClass + '">' + escapeHtml(entry.level || 'INFO') + '</span>';
                html += '<span class="mamba-log-message">' + escapeHtml(entry.message || '') + '</span>';
                
                if (entry.context && Object.keys(entry.context).length) {
                    html += '<div class="mamba-log-context">' + escapeHtml(JSON.stringify(entry.context)) + '</div>';
                }
                
                html += '</div>';
            });
            
            if (append) {
                $viewer.append(html);
            } else {
                $viewer.html(html);
            }
            
            var showing = currentOffset + data.entries.length;
            $count.text(showing + ' of ' + data.total + ' entries');
            
            if (data.has_more) {
                $pagination.show();
                $('#mamba-load-more').show();
            } else {
                $('#mamba-load-more').hide();
                if (data.total > 0) {
                    $pagination.show();
                }
            }
        }
    }

    /**
     * CDN Tab
     */
    function initCdnTab() {
        if (typeof MambaTabs === 'undefined' || !MambaTabs.cdn) return;
        
        var nonce = MambaTabs.cdn.nonce;
        var i18n = MambaTabs.cdn.i18n || {};
        
        // Show/hide provider-specific settings
        $('#mamba_cdn_provider').on('change', function() {
            var provider = $(this).val();
            $('.mamba-form-section[id$="-settings"]').hide();
            if (provider !== 'disabled') {
                $('#' + provider + '-settings').show();
            }
            
            if (provider === 'cloudflare') {
                $('#apply-recommended-settings').closest('.mamba-optimization-item').show();
            } else {
                $('#apply-recommended-settings').closest('.mamba-optimization-item').hide();
            }
        });
        
        // Initial state
        var currentProvider = $('#mamba_cdn_provider').val();
        if (currentProvider !== 'cloudflare') {
            $('#apply-recommended-settings').closest('.mamba-optimization-item').hide();
        }
        
        // Test connection
        $('#test-connection').on('click', function() {
            var button = $(this);
            var result = $('#connection-result');
            
            button.prop('disabled', true).text(i18n.testing || 'Testing...');
            result.html('');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'mamba_cdn_test_connection',
                    nonce: nonce
                },
                success: function(response) {
                    if (response.success) {
                        result.html('<div class="notice notice-success"><p>' + response.data + '</p></div>');
                    } else {
                        result.html('<div class="notice notice-error"><p>' + response.data + '</p></div>');
                    }
                },
                error: function() {
                    result.html('<div class="notice notice-error"><p>' + (i18n.requestFailed || 'Request failed') + '</p></div>');
                },
                complete: function() {
                    button.prop('disabled', false).text(i18n.testConnection || 'Test Connection');
                }
            });
        });
        
        // Test purge
        $('#test-purge-url, #test-purge-tag').on('click', function() {
            var button = $(this);
            var result = $('#purge-result');
            var type = button.attr('id') === 'test-purge-tag' ? 'tag' : 'url';
            
            button.prop('disabled', true).text(i18n.testing || 'Testing...');
            result.html('');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'mamba_cdn_test_purge',
                    type: type,
                    nonce: nonce
                },
                success: function(response) {
                    if (response.success) {
                        result.html('<div class="notice notice-success"><p>' + response.data + '</p></div>');
                    } else {
                        result.html('<div class="notice notice-error"><p>' + response.data + '</p></div>');
                    }
                },
                error: function() {
                    result.html('<div class="notice notice-error"><p>' + (i18n.requestFailed || 'Request failed') + '</p></div>');
                },
                complete: function() {
                    var btnText = button.attr('id') === 'test-purge-tag' ? (i18n.testTagPurge || 'Test Tag Purge') : (i18n.testUrlPurge || 'Test URL Purge');
                    button.prop('disabled', false).text(btnText);
                }
            });
        });
        
        // Apply recommended settings
        $('#apply-recommended-settings').on('click', function() {
            if (!confirm(i18n.confirmApply || 'This will apply recommended Cloudflare settings. Continue?')) {
                return;
            }
            
            var button = $(this);
            var result = $('#settings-result');
            
            button.prop('disabled', true).text(i18n.applying || 'Applying...');
            result.html('');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'mamba_cdn_apply_recommended_settings',
                    nonce: nonce
                },
                success: function(response) {
                    if (response.success) {
                        result.html('<div class="notice notice-success"><p>' + response.data + '</p></div>');
                    } else {
                        result.html('<div class="notice notice-error"><p>' + response.data + '</p></div>');
                    }
                },
                error: function() {
                    result.html('<div class="notice notice-error"><p>' + (i18n.requestFailed || 'Request failed') + '</p></div>');
                },
                complete: function() {
                    button.prop('disabled', false).text(i18n.applySettings || 'Apply Settings');
                }
            });
        });
    }

    /**
     * Database Tab
     */
    function initDbTab() {
        // Ensure MambaDB is available (fallback if localization failed)
        if (typeof MambaDB === 'undefined') {
            if (typeof MambaTabs !== 'undefined' && MambaTabs.db) {
                window.MambaDB = {
                    ajaxurl: MambaTabs.db.ajaxurl || ajaxurl,
                    nonce: MambaTabs.db.nonce
                };
            } else {
                return;
            }
        }
        
        // Toggle switch functionality
        $('.mamba-toggle-switch input[type="checkbox"]').on('change', function() {
            var checkbox = $(this);
            var taskCard = checkbox.closest('.mamba-task-card');
            var scheduleSelect = taskCard.find('.mamba-select');
            var statusBadge = taskCard.find('.mamba-status-badge');
            
            if (checkbox.is(':checked')) {
                scheduleSelect.prop('disabled', false);
                statusBadge.removeClass('mamba-status-warning').addClass('mamba-status-success').text('Scheduled');
            } else {
                scheduleSelect.prop('disabled', true);
                statusBadge.removeClass('mamba-status-success').addClass('mamba-status-warning').text('Disabled');
            }
        });
        
        // Initialize schedule dropdowns on page load
        $('.mamba-toggle-switch input[type="checkbox"]').each(function() {
            var checkbox = $(this);
            var taskCard = checkbox.closest('.mamba-task-card');
            var scheduleSelect = taskCard.find('.mamba-select');
            
            if (!checkbox.is(':checked')) {
                scheduleSelect.prop('disabled', true);
            }
        });
        
        // Settings toggle
        $('.mamba-settings-toggle').on('click', function() {
            var button = $(this);
            var taskId = button.data('task');
            var settingsRow = $('#settings-' + taskId);
            var icon = button.find('.dashicons');
            
            if (settingsRow.is(':visible')) {
                settingsRow.hide();
                icon.removeClass('dashicons-arrow-up-alt2').addClass('dashicons-admin-generic');
                button.text('Settings');
            } else {
                settingsRow.show();
                icon.removeClass('dashicons-admin-generic').addClass('dashicons-arrow-up-alt2');
                button.text('Hide Settings');
            }
        });
        
        // Manual run task
        $('.mamba-run-task').on('click', function() {
            var button = $(this);
            var taskId = button.data('task');
            var nonce = button.data('nonce');
            var statusEl = $('#status-' + taskId);
            
            if (button.prop('disabled')) return;
            
            button.prop('disabled', true);
            statusEl.removeClass('success error').addClass('loading').text('Running...');
            
            $.ajax({
                url: MambaDB.ajaxurl,
                type: 'POST',
                data: {
                    action: 'mamba_db_run_task',
                    task_id: taskId,
                    nonce: nonce
                },
                timeout: 60000,
                success: function(response) {
                    if (response.success) {
                        statusEl.removeClass('loading').addClass('success').text(response.data.message);
                        refreshCounts();
                        setTimeout(function() {
                            statusEl.removeClass('success').text('');
                        }, 3000);
                    } else {
                        var errorMsg = response.data ? (typeof response.data === 'string' ? response.data : response.data.message || 'Task failed') : 'Task failed';
                        statusEl.removeClass('loading').addClass('error').text(errorMsg);
                        setTimeout(function() {
                            statusEl.removeClass('error').text('');
                        }, 5000);
                    }
                },
                error: function(xhr, status) {
                    var errorMsg = 'Network error';
                    if (status === 'timeout') {
                        errorMsg = 'Request timed out';
                    } else if (xhr.status === 403) {
                        errorMsg = 'Permission denied';
                    } else if (xhr.status === 500) {
                        errorMsg = 'Server error';
                    }
                    statusEl.removeClass('loading').addClass('error').text(errorMsg);
                    setTimeout(function() {
                        statusEl.removeClass('error').text('');
                    }, 5000);
                },
                complete: function() {
                    button.prop('disabled', false);
                }
            });
        });
        
        // Refresh counts
        $('#refresh-counts').on('click', function() {
            refreshCounts();
        });
        
        function refreshCounts() {
            var button = $('#refresh-counts');
            var originalHtml = button.html();
            
            button.prop('disabled', true);
            button.html('<span class="dashicons dashicons-update spin"></span> Refreshing...');
            
            $.ajax({
                url: MambaDB.ajaxurl,
                type: 'POST',
                data: {
                    action: 'mamba_db_get_counts',
                    nonce: MambaDB.nonce || $('#refresh-counts').data('nonce')
                },
                timeout: 30000
            })
            .done(function(response) {
                if (response.success && response.data) {
                    Object.keys(response.data).forEach(function(taskId) {
                        var count = response.data[taskId];
                        var $countEl = $('.mamba-current[data-task="'+taskId+'"]');
                        if ($countEl.length) {
                            $countEl.text((typeof count === 'number') ? count.toLocaleString() : count);
                            $countEl.css('color', '#10b981');
                            setTimeout(function() {
                                $countEl.css('color', '');
                            }, 1000);
                        }
                    });
                    updateOverviewStats();
                }
            })
            .always(function() {
                button.prop('disabled', false);
                button.html(originalHtml);
            });
        }
        
        function updateOverviewStats() {
            $.ajax({
                url: MambaDB.ajaxurl,
                type: 'POST',
                data: {
                    action: 'mamba_db_get_overview',
                    nonce: MambaDB.nonce || $('#refresh-counts').data('nonce')
                },
                timeout: 30000
            })
            .done(function(response) {
                if (response.success && response.data && response.data.html) {
                    $('.mamba-execution-stats').html(response.data.html);
                }
            });
        }
    }

    /**
     * Caching Tab
     */
    function initCachingTab() {
        // Initialize WooCommerce enhanced select (Select2) for warmup selects
        if ($.fn.select2 && $('#mamba_warmup_selected_categories').length) {
            $('#mamba_warmup_selected_categories, #mamba_warmup_selected_products').each(function() {
                var $select = $(this);
                if (!$select.prop('disabled')) {
                    $select.select2({
                        placeholder: $select.data('placeholder') || 'Select...',
                        allowClear: true,
                        width: '100%'
                    });
                }
            });
        }
        
        // Toggle schedule time field based on schedule enabled checkbox
        $('#mamba_warmup_schedule_enabled').on('change', function() {
            var $row = $('#schedule-time-row');
            var $input = $('#mamba_warmup_schedule_time');
            if ($(this).is(':checked')) {
                $row.css('opacity', '1');
                $input.prop('disabled', false);
            } else {
                $row.css('opacity', '0.6');
                $input.prop('disabled', true);
            }
        });
        
        // Toggle selective warmup fields based on selective mode checkbox
        $('#mamba_warmup_selective_mode').on('change', function() {
            var isEnabled = $(this).is(':checked');
            var $catRow = $('#selective-categories-row');
            var $prodRow = $('#selective-products-row');
            var $catSelect = $('#mamba_warmup_selected_categories');
            var $prodSelect = $('#mamba_warmup_selected_products');
            
            if (isEnabled) {
                $catRow.css('opacity', '1');
                $prodRow.css('opacity', '1');
                $catSelect.prop('disabled', false);
                $prodSelect.prop('disabled', false);
                if ($.fn.select2) {
                    $catSelect.select2({
                        placeholder: $catSelect.data('placeholder') || 'Select categories...',
                        allowClear: true,
                        width: '100%'
                    });
                    $prodSelect.select2({
                        placeholder: $prodSelect.data('placeholder') || 'Select products...',
                        allowClear: true,
                        width: '100%'
                    });
                }
            } else {
                $catRow.css('opacity', '0.6');
                $prodRow.css('opacity', '0.6');
                if ($.fn.select2) {
                    if ($catSelect.hasClass('select2-hidden-accessible')) {
                        $catSelect.select2('destroy');
                    }
                    if ($prodSelect.hasClass('select2-hidden-accessible')) {
                        $prodSelect.select2('destroy');
                    }
                }
                $catSelect.prop('disabled', true);
                $prodSelect.prop('disabled', true);
            }
        });
        
        // Preload concurrency slider
        var $slider = $('#mamba_preload_concurrency');
        var $value = $('#preload-concurrency-value');
        
        if ($slider.length && $value.length) {
            $slider.on('input', function() {
                $value.text($(this).val());
            });
        }
        
        // Cache exclusion patterns
        $('#add-exclusion').on('click', function() {
            var pattern = $('#new-exclusion-pattern').val().trim();
            if (!pattern) return;
            
            var $list = $('#exclusion-list');
            var html = '<div class="mamba-exclusion-item">';
            html += '<code>' + escapeHtml(pattern) + '</code>';
            html += '<button type="button" class="remove-exclusion button-link"><span class="dashicons dashicons-no-alt"></span></button>';
            html += '<input type="hidden" name="mamba_cache_exclusions[]" value="' + escapeHtml(pattern) + '">';
            html += '</div>';
            
            $list.append(html);
            $('#new-exclusion-pattern').val('');
        });
        
        $(document).on('click', '.remove-exclusion', function() {
            $(this).closest('.mamba-exclusion-item').remove();
        });
    }

    /**
     * Overhead/Performance Tab
     */
    function initOverheadTab() {
        // Minify mode toggle - sync disabled state with checkbox
        var $cb = $('#mamba_enable_html_minify');
        var $item = $('#mamba_minify_mode_item');
        var $select = $('select[name="mamba_html_minify_mode"]');
        
        if ($cb.length && $item.length && $select.length) {
            function syncMinifyMode() {
                if ($cb.is(':checked')) {
                    $item.removeClass('mamba-disabled');
                    $select.prop('disabled', false);
                } else {
                    $item.addClass('mamba-disabled');
                    $select.prop('disabled', true);
                }
            }
            $cb.on('change', syncMinifyMode);
            syncMinifyMode();
        }
        
        // Domain management for DNS prefetch
        $('#add-domain').on('click', function() {
            var domain = $('#new-domain').val().trim();
            if (!domain) return;
            
            var $list = $('#domain-list');
            var html = '<div class="mamba-domain-item">';
            html += '<code>' + escapeHtml(domain) + '</code>';
            html += '<button type="button" class="remove-domain button-link"><span class="dashicons dashicons-no-alt"></span></button>';
            html += '<input type="hidden" name="mamba_custom_prefetch_domains[]" value="' + escapeHtml(domain) + '">';
            html += '</div>';
            
            $list.append(html);
            $('#new-domain').val('');
        });
        
        $(document).on('click', '.remove-domain', function() {
            $(this).closest('.mamba-domain-item').remove();
        });
    }

    /**
     * Media Tab
     */
    function initMediaTab() {
        if (typeof MambaTabs === 'undefined' || !MambaTabs.media) return;
        
        var nonce = MambaTabs.media.nonce;
        var i18n = MambaTabs.media.i18n || {};
        
        // Bulk conversion
        $('#start-bulk-conversion').on('click', function() {
            var $btn = $(this);
            var $progress = $('#conversion-progress');
            var $status = $('#conversion-status');
            
            $btn.prop('disabled', true);
            $progress.show();
            $status.text(i18n.starting || 'Starting conversion...');
            
            processBulkConversion(0);
        });
        
        function processBulkConversion(offset) {
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'mamba_bulk_convert',
                    nonce: nonce,
                    offset: offset
                },
                success: function(response) {
                    if (response.success) {
                        var data = response.data;
                        $('#conversion-progress-bar').css('width', data.progress + '%');
                        $('#conversion-status').text(data.message);
                        
                        if (data.complete) {
                            $('#start-bulk-conversion').prop('disabled', false);
                        } else {
                            processBulkConversion(data.next_offset);
                        }
                    } else {
                        $('#conversion-status').text(response.data.message || i18n.error || 'Error');
                        $('#start-bulk-conversion').prop('disabled', false);
                    }
                },
                error: function() {
                    $('#conversion-status').text(i18n.networkError || 'Network error');
                    $('#start-bulk-conversion').prop('disabled', false);
                }
            });
        }
    }

    /**
     * Utility Functions
     */
    function escapeHtml(text) {
        var div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    /**
     * Initialize copy-to-clipboard buttons
     * Used by admin notices for Nginx snippets
     */
    function initCopyButtons() {
        $('[data-mamba-copy]').each(function() {
            var $btn = $(this);
            var targetId = $btn.data('mamba-copy');
            var $code = $('#' + targetId);
            
            if (!$code.length) return;
            
            $btn.on('click', function() {
                var range = document.createRange();
                range.selectNodeContents($code[0]);
                var selection = window.getSelection();
                selection.removeAllRanges();
                selection.addRange(range);
                
                try {
                    document.execCommand('copy');
                    var $copyText = $btn.find('.copy-text');
                    var $copiedText = $btn.find('.copied-text');
                    $copyText.hide();
                    $copiedText.show();
                    
                    setTimeout(function() {
                        $copyText.show();
                        $copiedText.hide();
                    }, 2000);
                } catch(e) {
                    console.log('Copy failed:', e);
                }
            });
        });
    }
    
    // Initialize copy buttons on DOM ready
    $(document).ready(function() {
        initCopyButtons();
    });
    
    function showNotice(message, type) {
        var $notice = $('<div class="mamba-toast mamba-toast-' + type + '">' + escapeHtml(message) + '</div>');
        $('body').append($notice);
        setTimeout(function() { $notice.addClass('show'); }, 10);
        setTimeout(function() { 
            $notice.removeClass('show'); 
            setTimeout(function() { $notice.remove(); }, 300); 
        }, 3000);
    }

})(jQuery);
