/**
 * WRO Settings Page JavaScript - Fixed and Optimized Version
 * Syntax errors fixed, logic improved, code cleaned up
 */

jQuery(document).ready(function($) {
    'use strict';
    
    // Debug mode check
    const isDebugMode = (typeof kdsamrefData !== 'undefined' && kdsamrefData.debug) || 
                       (typeof wp !== 'undefined' && wp.debug) || 
                       (typeof console !== 'undefined' && console.log && window.location.search.includes('debug=true'));
    
    // Debug logging function
    function debugLog(message, data = null) {
        if (isDebugMode) {
            if (data !== null) {
                console.log(message, data);
            } else {
                console.log(message);
            }
        }
    }
    
    // Ensure kdsamrefData exists for settings page
    if (typeof kdsamrefData === 'undefined') {
        console.error('kdsamrefData is not defined. Please check if the script is loaded correctly.');
        return;
    }
    
    // === TAB SWITCHING FUNCTIONALITY ===
    $('.kdsamref-tab-btn').on('click', function() {
        const tabId = $(this).data('tab');
        
        // Remove active class from all tabs and hide all content
        $('.kdsamref-tab-btn').removeClass('active');
        $('.kdsamref-tab-content').hide();
        
        // Add active class to clicked tab and show corresponding content
        $(this).addClass('active');
        $('#tab-' + tabId).show();
        
        // Store active tab in session storage for persistence
        sessionStorage.setItem('kdsamref-active-tab', tabId);
    });
    
    // Restore active tab on page load
    const activeTab = sessionStorage.getItem('kdsamref-active-tab') || 'general';
    
    // Ensure the first tab is active by default
    if (!$('.kdsamref-tab-btn.active').length) {
        $('.kdsamref-tab-btn:first').addClass('active');
        $('.kdsamref-tab-content:first').show();
    }
    
    $('.kdsamref-tab-btn[data-tab="' + activeTab + '"]').click();
    
    // Suppress service worker preload warnings
    const originalConsoleWarn = console.warn;
    console.warn = function(...args) {
        if (args[0] && typeof args[0] === 'string' && 
            (args[0].includes('service worker') || args[0].includes('preloadResponse'))) {
            return; // Suppress service worker warnings
        }
        originalConsoleWarn.apply(console, args);
    };
    
    // Better notification system - defined early for compatibility mode
    function showNotification(message, type = 'info', duration = 5000) {
        const typeClasses = {
            'success': 'notice-success',
            'error': 'notice-error', 
            'warning': 'notice-warning',
            'info': 'notice-info'
        };
        
        const notification = $('<div class="notice ' + (typeClasses[type] || 'notice-info') + ' is-dismissible"><p>' + message + '</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss</span></button></div>');
        
        $('.kdsamref-settings-header').after(notification);
        
        // Auto remove
        setTimeout(() => {
            notification.fadeOut(300, function() { $(this).remove(); });
        }, duration);
        
        // Manual dismiss
        notification.find('.notice-dismiss').on('click', function() {
            notification.fadeOut(300, function() { $(this).remove(); });
        });
    }
    
    // === COMPATIBILITY MODE FUNCTIONALITY ===
    $('#kdsamref_compatibility_mode').on('change', function() {
        const selectedMode = $(this).val();
        
        // Hide all mode descriptions first
        $('.kdsamref-mode-desc').hide();
        
        // Show the description for selected mode with animation
        const $selectedDesc = $(`[data-mode="${selectedMode}"]`);
        if ($selectedDesc.length) {
            $selectedDesc.fadeIn(300);
        }
        
        // Show save reminder with mode-specific color
        const modeLabels = {
            'auto': kdsamrefSettings?.strings?.automaticDetection || 'Automatic Detection',
            'orderable': kdsamrefSettings?.strings?.orderableMode || 'Orderable Mode (complete)',
            'woocommerce': kdsamrefSettings?.strings?.woocommerceMode || 'WooCommerce Mode (standard)'
        };
        
        const modeLabel = modeLabels[selectedMode] || selectedMode;
        showNotification((kdsamrefSettings?.strings?.selectedMode || 'Selected mode: ') + modeLabel + (kdsamrefSettings?.strings?.dontForgetToSave || '. Don\'t forget to save!'), 'info', 4000);
    });
    
    // Initialize mode descriptions on page load
    const initialMode = $('#kdsamref_compatibility_mode').val();
    if (initialMode) {
        $('.kdsamref-mode-desc').hide();
        $(`[data-mode="${initialMode}"]`).show();
    }
    
    // === RANGE SLIDERS ===
    $('#default_font_size').on('input', function() {
        $('#font_size_display').text($(this).val() + '%');
    });
    
    $('#notification_volume').on('input', function() {
        $('#volume_display').text(Math.round($(this).val() * 100) + '%');
    });
    
    $('#completed_orders_opacity').on('input', function() {
        $('#opacity_display').text(Math.round($(this).val() * 100) + '%');
    });
    

    

    

    

    
    // Enhanced settings sync function
    function syncSettingsWithDashboard() {
        const ajaxUrl = kdsamrefData.ajaxUrl || ajaxurl;
        const nonce = kdsamrefData.nonce || '';
        
        if (!ajaxUrl || !nonce) {
            console.warn('Missing ajaxUrl or nonce for sync');
            return;
        }
        
        $.post(ajaxUrl, {
            action: 'kdsamref_get_settings',
            nonce: nonce
        })
        .done(function(response) {
            if (response.success && response.data) {
                debugLog('🔧 Dashboard-Settings sync completed:', response.data);
                

                if (response.data.custom_statuses) {
                    kdsamrefData.customStatuses = response.data.custom_statuses;
                }
                if (response.data.statusLabels) {
                    kdsamrefData.statusLabels = response.data.statusLabels;
                }
                if (response.data.statusColors) {
                    kdsamrefData.statusColors = response.data.statusColors;
                }
                
                showNotification('Paramètres synchronisés avec le dashboard', 'success');
                
                // Notify other tabs about the changes
                notifyOtherTabs(response.data);
            }
        })
        .fail(function(xhr, status, error) {
            console.warn('Failed to sync settings with dashboard:', error);
        });
    }
    
    // Add sync button functionality
    $(document).on('click', '#sync-with-dashboard', function() {
        syncSettingsWithDashboard();
    });
    
    // Auto-sync after form submission
    $('form.kdsamref-settings-form').on('submit', function() {
        setTimeout(function() {
            syncSettingsWithDashboard();
        }, 1000); // Wait 1 second for settings to be saved
    });
    

    
    function renderCustomStatuses(statuses) {
        // Update custom status display
        Object.keys(statuses).forEach(slug => {
            const status = statuses[slug];
            if (status && status.color) {
                updateStatusColor(slug, status.color);
            }
        });
    }
    
    // === LICENSE MANAGEMENT ===
    function handleLicenseAction(action, buttonSelector, data = {}) {
        const $btn = $(buttonSelector);
        const originalText = $btn.html();
        
        // Check if kdsamrefSettings exists
        if (typeof kdsamrefSettings === 'undefined' || !kdsamrefSettings.nonces || !kdsamrefSettings.nonces.license) {
            showNotification('Erreur: Configuration de licence manquante', 'error');
            return;
        }
        
        $btn.prop('disabled', true);
        
        const ajaxData = {
            action: action,
            nonce: kdsamrefSettings.nonces.license,
            ...data
        };
        
        $.post(ajaxurl, ajaxData)
            .done(function(response) {
                if (response.success) {
                    $btn.removeClass('button-secondary button-link-delete').addClass('button-primary');
                    showNotification(response.data.message || 'Opération réussie', 'success');
                    setTimeout(() => location.reload(), 2000);
                } else {
                    $btn.removeClass('button-secondary').addClass('button-link-delete');
                    showNotification('Erreur: ' + (response.data.message || 'Opération échouée'), 'error');
                }
            })
            .fail(function(xhr, status, error) {
                $btn.removeClass('button-secondary').addClass('button-link-delete');
                const errorMsg = xhr.responseJSON?.data?.message || 'Erreur de connexion';
                showNotification(errorMsg, 'error');
                console.error('License action failed:', error);
            })
            .always(function() {
                setTimeout(() => {
                    $btn.prop('disabled', false).html(originalText).removeClass('button-primary button-link-delete').addClass('button-secondary');
                }, 3000);
            });
    }
    
    // License management event handlers
    $('#kdsamref-refresh-license-info').on('click', function() {
        const $btn = $(this);
        $btn.find('.dashicons').addClass('dashicons-update-spin');
        $btn.html('<span class="dashicons dashicons-update dashicons-update-spin"></span> Actualisation...');
        handleLicenseAction('kdsamref_refresh_license_info', '#kdsamref-refresh-license-info');
    });
    
    $('#kdsamref-revalidate-license').on('click', function() {
        const licenseKey = $('input[readonly]').val();
        if (!licenseKey) {
            showNotification('Aucune licence trouvée à revalider', 'warning');
            return;
        }
        handleLicenseAction('kdsamref_validate_license', '#kdsamref-revalidate-license', { license_key: licenseKey });
    });
    
    $('#kdsamref-remove-license').on('click', function() {
        if (!confirm('Êtes-vous sûr de vouloir supprimer la licence ? Vous passerez en version gratuite.')) {
            return;
        }
        handleLicenseAction('kdsamref_remove_license', '#kdsamref-remove-license');
    });
    
    $('#kdsamref-add-license').on('click', function() {
        const licenseKey = $('#kdsamref_license_key').val().trim();
        if (!licenseKey) {
            showNotification('Veuillez entrer une clé de licence.', 'warning');
            $('#kdsamref_license_key').focus();
            return;
        }
        handleLicenseAction('kdsamref_validate_license', '#kdsamref-add-license', { license_key: licenseKey });
    });
    
    $('#kdsamref-change-license').on('click', function() {
        const newLicenseKey = prompt('Entrez la nouvelle clé de licence:');
        if (!newLicenseKey || !newLicenseKey.trim()) {
            return;
        }
        handleLicenseAction('kdsamref_validate_license', '#kdsamref-change-license', { license_key: newLicenseKey.trim() });
    });
    

    
    // === SETTINGS EXPORT/IMPORT ===
    $('#kdsamref-export-settings').on('click', function() {
        try {
            const $btn = $(this);
            const originalText = $btn.text();
            
            $btn.prop('disabled', true).text('Export...');
            
            // Get current form data
            const $form = $('form.kdsamref-settings-form');
            if (!$form.length) {
                throw new Error('Formulaire de paramètres non trouvé');
            }
            
            const formData = new FormData($form[0]);
            const settings = {};
            
            // Convert form data to object
            for (let [key, value] of formData.entries()) {
                if (key.startsWith('kdsamref_settings[')) {
                    const settingKey = key.replace('kdsamref_settings[', '').replace(']', '');
                    settings[settingKey] = value;
                }
            }
            
            // Add checkboxes that might not be in formData
            $('input[type="checkbox"][name^="kdsamref_settings"]').each(function() {
                const $checkbox = $(this);
                const name = $checkbox.attr('name');
                if (name) {
                    const settingKey = name.replace('kdsamref_settings[', '').replace(']', '');
                    settings[settingKey] = $checkbox.is(':checked') ? '1' : '0';
                }
            });
            
            // Create export object
            const exportData = {
                version: '1.0',
                plugin: 'kds-report-for-orderable',
                exported_at: new Date().toISOString(),
                settings: settings
            };
            
            // Create and download file
            const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = 'kdsamref-settings-' + new Date().toISOString().split('T')[0] + '.json';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
            
            $btn.prop('disabled', false).text(originalText);
            showNotification('Paramètres exportés avec succès !', 'success');
            
        } catch (error) {
            console.error('Export error:', error);
            showNotification('Erreur lors de l\'export: ' + error.message, 'error');
            $(this).prop('disabled', false).text('Exporter');
        }
    });
    
    $('#kdsamref-import-settings-btn').on('click', function() {
        try {
            const fileInput = $('#kdsamref-import-settings')[0];
            if (!fileInput || !fileInput.files || !fileInput.files[0]) {
                showNotification('Veuillez sélectionner un fichier à importer.', 'warning');
                return;
            }
            
            const file = fileInput.files[0];
            if (!file.name.endsWith('.json')) {
                showNotification('Veuillez sélectionner un fichier JSON valide.', 'error');
                return;
            }
            
            const $btn = $(this);
            const originalText = $btn.text();
            
            $btn.prop('disabled', true).text('Import...');
            
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const importData = JSON.parse(e.target.result);
                    
                    // Validate import data
                    if (!importData.settings || typeof importData.settings !== 'object') {
                        throw new Error('Format de fichier invalide');
                    }
                    
                    // Apply settings to form
                    Object.keys(importData.settings).forEach(key => {
                        const value = importData.settings[key];
                        const $input = $('[name="kdsamref_settings[' + key + ']"]');
                        
                        if ($input.length) {
                            if ($input.attr('type') === 'checkbox') {
                                $input.prop('checked', value === '1' || value === true);
                            } else {
                                $input.val(value);
                                
                                // Update range displays
                                updateRangeDisplay(key, value);
                                
                                // Handle compatibility mode change
                                if (key === 'compatibility_mode') {
                                    $('.kdsamref-mode-desc').hide();
                                    $(`[data-mode="${value}"]`).show();
                                }
                            }
                        }
                    });
                    
                    $btn.prop('disabled', false).text(originalText);
                    showNotification('Paramètres importés avec succès ! N\'oubliez pas de les enregistrer.', 'success');
                    
                } catch (error) {
                    $btn.prop('disabled', false).text(originalText);
                    showNotification('Erreur lors de l\'import: ' + error.message, 'error');
                    console.error('Import error:', error);
                }
            };
            
            reader.onerror = function() {
                $btn.prop('disabled', false).text(originalText);
                showNotification('Erreur lors de la lecture du fichier.', 'error');
            };
            
            reader.readAsText(file);
            
        } catch (error) {
            console.error('Import setup error:', error);
            showNotification('Erreur lors de l\'import: ' + error.message, 'error');
        }
    });
    
    function updateRangeDisplay(key, value) {
        if (key === 'default_font_size') {
            $('#font_size_display').text(value + '%');
        } else if (key === 'notification_volume') {
            $('#volume_display').text(Math.round(value * 100) + '%');
        } else if (key === 'completed_orders_opacity') {
            $('#opacity_display').text(Math.round(value * 100) + '%');
        }
    }
    
    // Reset settings to defaults
    $('#kdsamref-reset-settings').on('click', function() {
        if (!confirm('Êtes-vous sûr de vouloir réinitialiser tous les paramètres ?')) {
            return;
        }
        
        // Default values
        const defaults = {
            'max_orders_limit': 100,
            'default_font_size': 100,
            'auto_refresh_interval': 15,
            'enable_notifications': true,
            'notification_sound': true,
            'disable_refresh_notifications': false,
            'notification_volume': 0.3,
            'show_completed_orders': true,
            'completed_orders_opacity': 0.8,

            'compact_mode': false,
            'show_order_numbers': true,
            'show_customer_names': true,
            'show_product_options': true,
            'show_tips': true,
            'show_fees': true,
            'delivery_badge_color': '#4ade80', // Pastel yeşil
            'pickup_badge_color': '#a78bfa', // Pastel mor
            'dine_in_badge_color': '#60a5fa', // Pastel mavi
            'compatibility_mode': 'auto'
        };
        
        // Apply defaults
        Object.keys(defaults).forEach(key => {
            const value = defaults[key];
            const $input = $('[name="kdsamref_settings[' + key + ']"]');
            
            if ($input.length) {
                if ($input.attr('type') === 'checkbox') {
                    $input.prop('checked', value);
                } else {
                    $input.val(value);
                    updateRangeDisplay(key, value);
                    
                    // Handle compatibility mode reset
                    if (key === 'compatibility_mode') {
                        $('.kdsamref-mode-desc').hide();
                        $(`[data-mode="${value}"]`).show();
                    }
                }
            }
        });
        
        showNotification('Paramètres réinitialisés aux valeurs par défaut ! N\'oubliez pas de les enregistrer.', 'success');
    });
    
    // === WORKFLOW STEP MANAGEMENT FUNCTIONS ===
    function addCustomStatus() {
        const slugInput = document.getElementById('custom_status_slug');
        const labelInput = document.getElementById('custom_status_label');
        const colorInput = document.getElementById('custom_status_color');

        if (!slugInput || !labelInput || !colorInput) {
            console.error('Custom status form elements not found');
            return;
        }

        const slug = slugInput.value.trim();
        const label = labelInput.value.trim();
        const color = colorInput.value;

        if (!slug || !label) {
            alert('Le slug et le nom d\'affichage sont requis pour ajouter un statut personnalisé.');
            return;
        }

        const container = document.getElementById('kdsamref-custom-statuses-container');
        if (!container) {
            console.error('Custom statuses container not found');
            return;
        }

        const newItem = document.createElement('div');
        newItem.className = 'kdsamref-custom-status-item';
        newItem.setAttribute('data-slug', slug);

        newItem.innerHTML = `
            <div class="kdsamref-status-color" style="background-color: ${color}"></div>
            <div class="kdsamref-status-info">
                <input type="text" name="kdsamref_settings[custom_statuses][${slug}][label]" value="${label}" placeholder="Nom du statut" />
                <span class="kdsamref-status-slug">${slug}</span>
            </div>
            <input type="color" name="kdsamref_settings[custom_statuses][${slug}][color]" value="${color}" />
            <button type="button" class="kdsamref-status-remove-btn" onclick="removeCustomStatus('${slug}')">&times;</button>
        `;

        // Remove any existing "no custom statuses" message
        const noStatusMessage = container.querySelector('.kdsamref-no-custom-statuses');
        if (noStatusMessage) {
            noStatusMessage.remove();
        }
        
        container.appendChild(newItem);

        // Clear inputs
        slugInput.value = '';
        labelInput.value = '';
        colorInput.value = '#007cba';
        
        showNotification('Statut personnalisé ajouté: ' + label, 'success');
    }

    function removeCustomStatus(slug) {
        if (!confirm('Supprimer ce statut personnalisé ?')) {
            return;
        }
        
        const container = document.getElementById('kdsamref-custom-statuses-container');
        if (!container) {
            console.error('Custom statuses container not found');
            return;
        }
        
        const item = container.querySelector(`.kdsamref-custom-status-item[data-slug="${slug}"]`);
        if (item) {
            item.remove();
            showNotification('Statut supprimé', 'success');
            
            // Check if no custom statuses left and show message
            const remainingItems = container.querySelectorAll('.kdsamref-custom-status-item');
            if (remainingItems.length === 0) {
                container.innerHTML = '<p class="kdsamref-no-custom-statuses">Aucun statut personnalisé défini. Ajoutez-en un ci-dessus.</p>';
            }
        }
    }

    function updateStatusColor(slug, newColor) {
        const item = document.querySelector(`.kdsamref-custom-status-item[data-slug="${slug}"]`);
        if (item) {
            const colorDisplay = item.querySelector('.kdsamref-status-color');
            if (colorDisplay) {
                colorDisplay.style.backgroundColor = newColor;
            }
        }
    }






    
    // Color input change handler
    $(document).on('change', 'input[type="color"]', function() {
        const item = $(this).closest('.kdsamref-custom-status-item');
        if (item.length) {
            const slug = item.attr('data-slug');
            const newColor = $(this).val();
            if (slug) {
                updateStatusColor(slug, newColor);
            }
        }
    });
    
    /**
     * Notify dashboard and other tabs about settings changes
     */
    function notifyOtherTabs(settingsData) {
        try {
            if (typeof BroadcastChannel !== 'undefined') {
                const channel = new BroadcastChannel('kdsamref-settings-updates');
                channel.postMessage({
                    type: 'settings-changed',
                    timestamp: Date.now(),
                    workflowSteps: settingsData.workflow_steps || [],
                    customStatuses: settingsData.custom_statuses || {},
                    statusLabels: settingsData.statusLabels || {},
                    statusColors: settingsData.statusColors || {}
                });
                debugLog('📡 Settings changes broadcasted to other tabs');
                
                // Close channel after use
                setTimeout(() => channel.close(), 1000);
            }
        } catch (error) {
            console.warn('Could not broadcast settings changes:', error);
        }
    }
    
    // Make functions globally available for template compatibility
    window.addCustomStatus = addCustomStatus;
    window.removeCustomStatus = removeCustomStatus;
    window.updateStatusColor = updateStatusColor;
    
    // Apply default colors to color inputs if they're empty or have old values
    function applyDefaultColors() {
        const defaultColors = {
            'delivery_badge_color': '#4ade80',
            'pickup_badge_color': '#a78bfa', 
            'dine_in_badge_color': '#60a5fa'
        };
        
        Object.keys(defaultColors).forEach(key => {
            const $input = $(`[name="kdsamref_settings[${key}]"]`);
            if ($input.length) {
                const currentValue = $input.val();
                // If the value is empty or is one of the old default colors, apply new default
                if (!currentValue || 
                    currentValue === '#28a745' || 
                    currentValue === '#007cba' || 
                    currentValue === '#6f42c1') {
                    $input.val(defaultColors[key]);
                }
            }
        });
    }
    
    // Apply default colors on page load
    applyDefaultColors();
    
    // Notify other tabs when settings are saved
    $('form[name="kdsamref-settings-form"]').on('submit', function() {
        // Settings form submitted, notifying other tabs
        
        // Notify other tabs about settings change
        if (typeof BroadcastChannel !== 'undefined') {
            const channel = new BroadcastChannel('kdsamref-settings-updates');
            channel.postMessage({
                type: 'settings-changed',
                timestamp: Date.now()
            });
            setTimeout(() => channel.close(), 1000);
        }
    });

});
