/**
 * Sentinel Settings Page JavaScript
 * 
 * JavaScript for the settings page functionality including tab switching,
 * dynamic form controls, and post-submission handling.
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        
        // Tab switching functionality
        const tabs = document.querySelectorAll('.sentinel-tab');
        const tabContents = document.querySelectorAll('.sentinel-tab-content');

        tabs.forEach(tab => {
            tab.addEventListener('click', function(e) {
                e.preventDefault();

                // Remove active class from all tabs
                tabs.forEach(t => t.classList.remove('sentinel-tab-active'));

                // Add active class to clicked tab
                this.classList.add('sentinel-tab-active');

                // Hide all tab contents
                tabContents.forEach(content => {
                    content.style.display = 'none';
                });

                // Show the selected tab content
                const targetTab = this.getAttribute('data-tab');
                const targetContent = document.getElementById(targetTab + '-tab');
                if (targetContent) {
                    targetContent.style.display = 'block';
                }

                // Update hidden tab field for form submission
                const tabField = document.getElementById('sentinel_current_tab');
                if (tabField) {
                    tabField.value = targetTab;
                }
            });
        });

        // Archive retention settings
        const archiveSelect = document.getElementById('archive_retention_type');
        const customDiv = document.getElementById('custom_archive_days');

        if (archiveSelect) {
            archiveSelect.addEventListener('change', function() {
                if (this.value === 'custom') {
                    customDiv.style.display = 'block';
                } else {
                    customDiv.style.display = 'none';
                }
            });
        }

        // Performance & Resource Control settings
        const batchLoggingCheckbox = document.getElementById('batch_logging_enabled');
        const batchSizeRow = document.getElementById('batch_size_row');
        const batchFrequencyRow = document.getElementById('batch_frequency_row');

        if (batchLoggingCheckbox) {
            batchLoggingCheckbox.addEventListener('change', function() {
                if (this.checked) {
                    batchSizeRow.style.display = 'table-row';
                    batchFrequencyRow.style.display = 'table-row';
                } else {
                    batchSizeRow.style.display = 'none';
                    batchFrequencyRow.style.display = 'none';
                }
            });
        }

        const rateLimitingCheckbox = document.getElementById('rate_limiting_enabled');
        const rateLimitMinuteRow = document.getElementById('rate_limit_minute_row');
        const rateLimitHourRow = document.getElementById('rate_limit_hour_row');
        const rateLimitBehaviorRow = document.getElementById('rate_limit_behavior_row');

        if (rateLimitingCheckbox) {
            rateLimitingCheckbox.addEventListener('change', function() {
                if (this.checked) {
                    rateLimitMinuteRow.style.display = 'table-row';
                    rateLimitHourRow.style.display = 'table-row';
                    if (rateLimitBehaviorRow) {
                        rateLimitBehaviorRow.style.display = 'table-row';
                    }
                } else {
                    rateLimitMinuteRow.style.display = 'none';
                    rateLimitHourRow.style.display = 'none';
                    if (rateLimitBehaviorRow) {
                        rateLimitBehaviorRow.style.display = 'none';
                    }
                }
            });
        }

        const memoryMonitoringCheckbox = document.getElementById('memory_monitoring_enabled');
        const memoryThresholdRow = document.getElementById('memory_threshold_row');

        if (memoryMonitoringCheckbox) {
            memoryMonitoringCheckbox.addEventListener('change', function() {
                if (this.checked) {
                    memoryThresholdRow.style.display = 'table-row';
                } else {
                    memoryThresholdRow.style.display = 'none';
                }
            });
        }

        // Handle post-submission redirect if needed
        if (typeof sentinelSettingsData !== 'undefined' && sentinelSettingsData.needsRedirect) {
            setTimeout(function() {
                const currentTab = sentinelSettingsData.currentTab;
                const newUrl = new URL(window.location);
                newUrl.searchParams.set('tab', currentTab);
                newUrl.searchParams.set('settings-updated', 'true');
                newUrl.searchParams.delete('message'); // Remove any existing message param

                // Use replaceState to update URL without refreshing the page
                window.history.replaceState({}, '', newUrl.toString());

                // Update the hidden tab field to match the current state
                const tabField = document.getElementById('sentinel_current_tab');
                if (tabField) {
                    tabField.value = currentTab;
                }

                // Scroll to top to ensure user sees success message
                window.scrollTo(0, 0);
            }, 100);
        }

        // Export button (uses selected options)
        var exportBtn = document.getElementById('sentinel-export-btn');
        if (exportBtn) {
            exportBtn.addEventListener('click', function(e) {
                e.preventDefault();
                var nonce = document.getElementById('sentinel-export-logs-json-nonce').value;
                var dateRange = document.getElementById('export_date_range') ? document.getElementById('export_date_range').value : '30';
                var format = document.getElementById('export_format') ? document.getElementById('export_format').value : 'json';
                var source = getSelectedExportSource();
                var formData = new FormData();
                formData.append('action', 'sentinel_export_logs_json');
                formData.append('nonce', nonce);
                formData.append('date_range', dateRange);
                formData.append('format', format);
                formData.append('export_source', source);
                exportBtn.classList.add('disabled');
                var originalText = exportBtn.textContent;
                exportBtn.textContent = 'Exporting...';
                fetch(ajaxurl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) throw new Error('Network response was not ok');
                    return response.blob();
                })
                .then(blob => {
                    var ext = format === 'csv' ? 'csv' : (format === 'xml' ? 'xml' : 'json');
                    var src = source === 'both' ? 'all' : source;
                    var url = window.URL.createObjectURL(blob);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = 'sentinel-logs-' + src + '-' + dateRange + '-days.' + ext;
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                    exportBtn.classList.remove('disabled');
                    exportBtn.textContent = originalText;
                })
                .catch(error => {
                    alert('Export failed: ' + error.message);
                    exportBtn.classList.remove('disabled');
                    exportBtn.textContent = originalText;
                });
            });
        }

        // Quick Export Last 30 Days button (always main logs, JSON)
        var quickBtn = document.getElementById('sentinel-export-quick-btn');
        if (quickBtn) {
            quickBtn.addEventListener('click', function(e) {
                e.preventDefault();
                var nonce = document.getElementById('sentinel-export-logs-json-nonce').value;
                var formData = new FormData();
                formData.append('action', 'sentinel_export_logs_json');
                formData.append('nonce', nonce);
                formData.append('date_range', '30');
                formData.append('format', 'json');
                formData.append('export_source', 'main');
                quickBtn.classList.add('disabled');
                var originalText = quickBtn.textContent;
                quickBtn.textContent = 'Exporting...';
                fetch(ajaxurl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) throw new Error('Network response was not ok');
                    return response.blob();
                })
                .then(blob => {
                    var url = window.URL.createObjectURL(blob);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = 'sentinel-logs-main-30-days.json';
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                    quickBtn.classList.remove('disabled');
                    quickBtn.textContent = originalText;
                })
                .catch(error => {
                    alert('Export failed: ' + error.message);
                    quickBtn.classList.remove('disabled');
                    quickBtn.textContent = originalText;
                });
            });
        }

        // Sentinel 3-way segmented toggle logic
        var segmentedToggle = document.getElementById('export_source_toggle');
        if (segmentedToggle) {
          var buttons = segmentedToggle.querySelectorAll('.sentinel-segmented-btn');
          var slider = segmentedToggle.querySelector('.slider');
          buttons.forEach(function(btn) {
            btn.addEventListener('click', function() {
              buttons.forEach(function(b) {
                b.classList.remove('active');
                b.setAttribute('aria-pressed', 'false');
              });
              btn.classList.add('active');
              btn.setAttribute('aria-pressed', 'true');
              // Move slider (handled by CSS : the .active + ~ .slider rule)
            });
          });
        }

        // Initialize tab state on page load
        initializeTabState();
    });

    /**
     * Initialize the correct tab state on page load
     */
    function initializeTabState() {
        // Check URL parameters for tab
        const urlParams = new URLSearchParams(window.location.search);
        const urlTab = urlParams.get('tab');
        
        // Check hidden field for tab
        const tabField = document.getElementById('sentinel_current_tab');
        const fieldTab = tabField ? tabField.value : null;
        
        // Determine which tab to show (URL takes precedence)
        const activeTab = urlTab || fieldTab || 'database';
        
        // Update the hidden field
        if (tabField) {
            tabField.value = activeTab;
        }
        
        // Activate the correct tab
        const targetTabLink = document.querySelector('.sentinel-tab[data-tab="' + activeTab + '"]');
        const targetTabContent = document.getElementById(activeTab + '-tab');
        
        if (targetTabLink && targetTabContent) {
            // Remove active class from all tabs
            document.querySelectorAll('.sentinel-tab').forEach(tab => {
                tab.classList.remove('sentinel-tab-active');
            });
            
            // Hide all tab contents
            document.querySelectorAll('.sentinel-tab-content').forEach(content => {
                content.style.display = 'none';
            });
            
            // Activate the target tab
            targetTabLink.classList.add('sentinel-tab-active');
            targetTabContent.style.display = 'block';
        }
    }

    // Update export logic to read the selected export source value
    function getSelectedExportSource() {
      var segmented = document.getElementById('export_source_toggle');
      if (!segmented) return 'main';
      var activeBtn = segmented.querySelector('.sentinel-segmented-btn.active');
      return activeBtn ? activeBtn.getAttribute('data-value') : 'main';
    }

})(jQuery);
