/**
 * KDS & Report for Orderable - Admin Dashboard JavaScript
 * Optimized with Enhanced Workflow Integration
 */

(function($) {
    'use strict';

    // Ensure kdsamrefData exists (for dashboard)
    if (typeof kdsamrefData === 'undefined') {
        console.warn('kdsamrefData is not defined. Initializing with default values.');
        window.kdsamrefData = {
            ajaxUrl: ajaxurl || '/wp-admin/admin-ajax.php',
            pluginUrl: '',
            nonce: '',
            settings: {},
            currentWpDate: new Date().toISOString().split('T')[0],
            yesterdayWpDate: new Date(Date.now() - 24*60*60*1000).toISOString().split('T')[0],
            tomorrowWpDate: new Date(Date.now() + 24*60*60*1000).toISOString().split('T')[0],
            wpTimezoneOffset: new Date().getTimezoneOffset() / -60
        };
    }

    // Global variables
    let isUserInteracting = false;
    let autoRefreshTimer;
    let currentFilter = 'all';
    let currentSearchTerm = '';
    let orders = [];
    let lastUpdateTime = null;
    let currentDateFilter = 'today';
    let lastOrderCount = 0;
    let notificationPermission = false;
    let audioContext = null;
    let settingsCheckTimer;
    let lastNotificationTime = 0; // throttle desktop + sound notifications
    let pendingNewOrders = 0; // badge count

    // Global variables for date filtering
    let dateFilterType = 'created'; // 'created' or 'delivery'
    let isDeliveryMode = false;
    
    // 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);
            }
        }
    }

    /**
     * Initialize when document is ready
     */
    $(document).ready(function() {
        // Clean initialization
        initDashboard();
    });

    /**
     * Initialize dashboard
     */
    function initDashboard() {
        // Debug: Log custom statuses data
        debugLog('🔧 Dashboard initialization - Custom statuses data:', {
            kdsamrefCustomStatuses: typeof kdsamrefCustomStatuses !== 'undefined' ? kdsamrefCustomStatuses : 'undefined',
            kdsamrefData: kdsamrefData,
            kdsamrefDataCustomStatuses: kdsamrefData && kdsamrefData.customStatuses ? kdsamrefData.customStatuses : 'undefined'
        });
        
        // Apply dashboard settings first
        applyDashboardSettings();
        
        // Apply custom colors (without recursion)
        applyCustomColorsOnly();
        
        // Set completed status text for CSS
        setCompletedStatusText();
        
        // Initialize workflow system
        initializeWorkflowSystem();
        
        // Initialize layout mode from localStorage
        initializeLayoutMode();
        
        // Load initial orders
        loadOrdersByDate('today');
        
        // Bind all events
        bindEvents();
        
        // Start auto-refresh if enabled
        startAutoRefresh();
        
        // Show license warnings if needed
        showLicenseWarnings();
        
        // Update last update time
        updateLastUpdateTime();
        
        // Listen for settings changes
        listenForSettingsChanges();
        
        // Initialize notifications
        initNotificationSystem();

        // Initialize date mode switch functionality
        initializeDateModeSwitch();


        

        
        // Initialize header toggle functionality
        initializeHeaderToggle();
        
        // Initialize fullscreen functionality
        initializeFullscreenMode();
        
        // Restore fullscreen state on page load
        restoreFullscreenState();
    }

    /**
     * Initialize workflow system integration
     */
    function initializeWorkflowSystem() {
        // Load current workflow settings immediately
        loadWorkflowSettings();
        
        // Setup cross-tab communication for settings changes
        setupCrossTabCommunication();
    }

    /**
     * Load workflow settings from server
     */
    function loadWorkflowSettings() {
        const ajaxUrl = kdsamrefData.ajaxUrl || ajaxurl;
        const nonce = kdsamrefData.nonce || '';
        
        if (!ajaxUrl || !nonce) {
            console.warn('Missing ajaxUrl or nonce for workflow settings');
            return;
        }
        
        $.post(ajaxUrl, {
            action: 'kdsamref_get_settings',
            nonce: nonce
        })
        .done(function(response) {
            if (response.success && response.data) {
                // Update kdsamrefData with fresh settings
                updateWorkflowData(response.data);
                
                // Re-render workflow-dependent UI elements
                renderStatusFilters();
                renderOrders();
            }
        })
        .fail(function() {
            // Silent fail for settings loading
        });
    }

    /**
     * Update workflow data with new settings
     */
    function updateWorkflowData(newSettings) {
        let hasChanges = false;
        
        // Check and update workflow steps
        if (newSettings.workflow_steps && 
            JSON.stringify(kdsamrefData.workflowSteps) !== JSON.stringify(newSettings.workflow_steps)) {
            kdsamrefData.workflowSteps = newSettings.workflow_steps;
            hasChanges = true;
        }
        
        // Check and update status labels
        if (newSettings.statusLabels && 
            JSON.stringify(kdsamrefData.statusLabels) !== JSON.stringify(newSettings.statusLabels)) {
            kdsamrefData.statusLabels = newSettings.statusLabels;
            hasChanges = true;
        }
        
        // Check and update status colors
        if (newSettings.statusColors && 
            JSON.stringify(kdsamrefData.statusColors) !== JSON.stringify(newSettings.statusColors)) {
            kdsamrefData.statusColors = newSettings.statusColors;
            hasChanges = true;
        }
        
        // Check and update custom statuses
        if (newSettings.custom_statuses && 
            JSON.stringify(kdsamrefData.customStatuses) !== JSON.stringify(newSettings.custom_statuses)) {
            kdsamrefData.customStatuses = newSettings.custom_statuses;
            hasChanges = true;
        }
        
        // Workflow data updated if changes detected
        
        return hasChanges;
    }

    /**
     * Setup cross-tab communication for settings changes
     */
    function setupCrossTabCommunication() {
        if (typeof BroadcastChannel !== 'undefined') {
            const channel = new BroadcastChannel('kdsamref-settings-updates');
            
            channel.addEventListener('message', function(event) {
                if (event.data.type === 'settings-changed') {
                    // Update local data
                    kdsamrefData.workflowSteps = event.data.workflowSteps || kdsamrefData.workflowSteps;
                    kdsamrefData.customStatuses = event.data.customStatuses || kdsamrefData.customStatuses;
                    kdsamrefData.statusLabels = event.data.statusLabels || kdsamrefData.statusLabels;
                    kdsamrefData.statusColors = event.data.statusColors || kdsamrefData.statusColors;
                    
                    // Re-render components that depend on workflow settings
                    renderStatusFilters();
                    renderOrders();
                    
                    showSuccessMessage('✨ Workflow settings updated');
                }
            });
        }
    }

    /**
     * Listen for settings changes and refresh dashboard
     */
    function listenForSettingsChanges() {
        // Check for settings changes every 30 seconds
        settingsCheckTimer = setInterval(() => {
            checkForSettingsChanges();
        }, 30000);
        
        // Also check immediately on page load
        setTimeout(() => {
            checkForSettingsChanges();
        }, 500);
    }

    /**
     * Check for settings changes
     */
    function checkForSettingsChanges() {
        $.post(kdsamrefData.ajaxUrl, {
            action: 'kdsamref_get_settings',
            nonce: kdsamrefData.nonce
        })
        .done(function(response) {
            if (response.success && response.data) {
                const hasChanges = updateWorkflowData(response.data);
                
                if (hasChanges) {
                    // Re-render status filters and orders
                    renderStatusFilters();
                    renderOrders();
                }
            }
        })
        .fail(function() {
            // Silent fail for settings check
        });
    }

    /**
     * Apply custom status colors to the dashboard
     */
    function applyCustomStatusColors() {
        // Remove existing custom status styles
        $('#kdsamref-custom-status-styles').remove();
        
        const statusColors = kdsamrefData.statusColors || {};
        const customStatuses = kdsamrefData.customStatuses || {};
        
        let customStyles = '';
        
        // Add styles for custom status colors
        Object.keys(statusColors).forEach(status => {
            const color = statusColors[status];
            customStyles += `
                .kdsamref-status-badge.status-${status} {
                    background-color: ${color} !important;
                    border-color: ${color} !important;
                }
                .kdsamref-order-card[data-status="${status}"] {
                    border-color: ${color} !important;
                }
                .kdsamref-status-btn[data-filter="${status}"] {
                    border-color: ${color} !important;
                }
                .kdsamref-status-btn[data-filter="${status}"].active {
                    background-color: ${color} !important;
                    color: white !important;
                }
            `;
        });
        
        // Add styles for custom statuses from settings
        Object.keys(customStatuses).forEach(status => {
            const statusData = customStatuses[status];
            if (statusData.color) {
                customStyles += `
                    .kdsamref-status-badge.status-${status} {
                        background-color: ${statusData.color} !important;
                        border-color: ${statusData.color} !important;
                    }
                    .kdsamref-order-card[data-status="${status}"] {
                        border-color: ${statusData.color} !important;
                    }
                    .kdsamref-status-btn[data-filter="${status}"] {
                        border-color: ${statusData.color} !important;
                    }
                    .kdsamref-status-btn[data-filter="${status}"].active {
                        background-color: ${statusData.color} !important;
                        color: white !important;
                    }
                `;
            }
        });
        
        if (customStyles) {
            $('<style>', {
                id: 'kdsamref-custom-status-styles',
                text: customStyles
            }).appendTo('head');
        }
    }

    /**
     * Initialize notification and sound system
     */
    function initNotificationSystem() {
        debugLog('🔔 Initializing notification system...');
        
        // Check settings
        const notificationsEnabled = kdsamrefData.settings?.enable_notifications == 1;
        const soundEnabled = kdsamrefData.settings?.notification_sound == 1;
        
        debugLog('Settings:', { notificationsEnabled, soundEnabled });
        
        // Detect iPad
        const isIPad = /iPad|Macintosh/.test(navigator.userAgent) && 'ontouchend' in document;
        
        // Setup audio context activation
        setupAudioContextActivation();
        
        // Request notification permission if enabled
        if (notificationsEnabled && 'Notification' in window) {
            requestNotificationPermission();
        } else {
            notificationPermission = false;
            debugLog('🔕 Browser notifications disabled in settings or not supported');
        }
        
        // iPad-specific setup
        if (isIPad) {
            debugLog('📱 iPad detected - Enhanced notification system enabled');
        }
        
        // Update button visual state
        const $btn = $('#kdsamref-notifications-btn');
        if ($btn.length) {
            if (notificationsEnabled && Notification.permission === 'granted') {
                if (kdsamrefData.settings?.notification_sound == 1) {
                    $btn.addClass('enabled');
                } else {
                    $btn.removeClass('enabled');
                }
                $btn.attr('title', kdsamrefData.settings?.notification_sound == 1 ? 'Notifications enabled (Sound on)' : 'Notifications enabled (Sound off)');
            } else if (notificationsEnabled && Notification.permission === 'default') {
                $btn.removeClass('enabled');
                $btn.attr('title', 'Click to enable notifications');
            } else {
                $btn.removeClass('enabled');
                $btn.attr('title', 'Notifications disabled in settings');
            }
            // Initialize badge to 0 and hidden
            updateNotificationBadge(0);
        }

        debugLog('✅ Notification system initialized');
    }

    // Update notification badge count on the bell button
    function updateNotificationBadge(count) {
        try {
            const badge = document.getElementById('kdsamref-notification-badge');
            if (!badge) return;
            if (count && count > 0) {
                badge.textContent = String(count);
                badge.style.display = 'inline-block';
            } else {
                badge.textContent = '0';
                badge.style.display = 'none';
            }
        } catch (e) {
            // no-op
        }
    }

    /**
     * Setup audio context activation on user interaction
     */
    function setupAudioContextActivation() {
        const events = ['click', 'touchstart', 'keydown'];
        let activated = false;
        
        const activateAudio = async () => {
            if (activated) return;
            activated = true;
            
            try {
                await initializeAudioContext();
                debugLog('🔊 Audio context activated by user interaction');
                
                // Remove event listeners
                events.forEach(event => {
                    document.removeEventListener(event, activateAudio);
                });
                
            } catch (error) {
                console.warn('Could not activate audio context:', error);
            }
        };
        
        // Listen for any user interaction
        events.forEach(event => {
            document.addEventListener(event, activateAudio, { once: true });
        });
    }
    
    /**
     * Initialize audio context properly
     */
    function initializeAudioContext() {
        return new Promise((resolve, reject) => {
            try {
                if (!audioContext) {
                    audioContext = new (window.AudioContext || window.webkitAudioContext)();
                }
                
                // Resume if suspended (Safari requirement)
                if (audioContext.state === 'suspended') {
                    audioContext.resume().then(() => {
                        debugLog('🔊 Audio context resumed');
                        resolve();
                    }).catch(reject);
                } else {
                    debugLog('🔊 Audio context ready');
                    resolve();
                }
            } catch (error) {
                console.warn('Audio context not supported:', error);
                reject(error);
            }
        });
    }
    
    /**
     * Request notification permission
     */
    function requestNotificationPermission() {
        if (Notification.permission === 'granted') {
            notificationPermission = true;
            debugLog('✅ Notification permission already granted');
            return;
        }
        
        if (Notification.permission === 'denied') {
            notificationPermission = false;
            debugLog('❌ Notification permission denied');
            showNotificationHelp();
            return;
        }
        
        // Request permission
        Notification.requestPermission().then(function (permission) {
            notificationPermission = (permission === 'granted');
            
            if (notificationPermission) {
                showSuccessMessage('🔔 Notifications enabled!');
                debugLog('✅ Notification permission granted');
            } else {
                debugLog('❌ Notification permission denied by user');
                showNotificationHelp();
            }
        }).catch(error => {
            console.warn('Error requesting notification permission:', error);
        });
    }
    
    /**
     * Show notification help message
     */
    function showNotificationHelp() {
        const helpMsg = 'To enable notifications: Click the lock icon in your browser address bar and allow notifications for this site.';
        showSuccessMessage('🔔 ' + helpMsg);
    }

    /**
     * Play notification sound
     */
    function playNotificationSound() {
        // Check if sound is enabled
        const soundEnabled = kdsamrefData.settings?.notification_sound == 1;
        if (!soundEnabled) {
            debugLog('🔇 Notification sound disabled in settings');
            return;
        }
        
        const volume = parseFloat(kdsamrefData.settings?.notification_volume || 0.3);
        debugLog('🔊 Playing notification sound, volume:', volume);
        
        // Try Web Audio API first
        if (audioContext && audioContext.state === 'running') {
            playWebAudioSound(volume);
        } else {
            // Try to initialize audio context
            initializeAudioContext().then(() => {
                if (audioContext && audioContext.state === 'running') {
                    playWebAudioSound(volume);
                } else {
                    playFallbackSound(volume);
                }
            }).catch(() => {
                playFallbackSound(volume);
            });
        }
    }
    
    /**
     * Play sound using Web Audio API
     */
    function playWebAudioSound(volume) {
        try {
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            // Create a pleasant notification sound (two-tone)
            oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
            oscillator.frequency.setValueAtTime(600, audioContext.currentTime + 0.15);
            oscillator.frequency.setValueAtTime(800, audioContext.currentTime + 0.3);
            
            // Volume envelope
            gainNode.gain.setValueAtTime(0, audioContext.currentTime);
            gainNode.gain.linearRampToValueAtTime(volume, audioContext.currentTime + 0.05);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.6);
            
            // Sine wave for pleasant sound
            oscillator.type = 'sine';
            
            // Play the sound
            oscillator.start(audioContext.currentTime);
            oscillator.stop(audioContext.currentTime + 0.6);
            
            debugLog('✅ Notification sound played via Web Audio API');
            
        } catch (error) {
            console.warn('Web Audio API error:', error);
            playFallbackSound(volume);
        }
    }
    
    /**
     * Fallback sound using HTML5 Audio
     */
    function playFallbackSound(volume) {
        try {
            // Use the actual notification.mp3 file if available
            const audio = new Audio(kdsamrefData.pluginUrl + 'assets/sounds/notification.mp3');
            audio.volume = Math.min(1.0, Math.max(0.1, volume));
            
            audio.play().then(() => {
                debugLog('✅ Notification sound played via HTML5 Audio');
            }).catch(() => {
                // Final fallback with data URL
                playDataUrlSound(volume);
            });
            
        } catch (error) {
            console.warn('HTML5 Audio failed:', error);
            playDataUrlSound(volume);
        }
    }
    
    /**
     * Final fallback with data URL
     */
    function playDataUrlSound(volume) {
        try {
            const audio = new Audio();
            audio.volume = Math.min(1.0, Math.max(0.1, volume));
            audio.src = 'data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBSuBzvLZiTYIG2m98OScTgwOUarm7blmGgU7k9n1unEiBC13yO/eizEIHWq+8+OWT';
            
            audio.play().then(() => {
                debugLog('✅ Fallback sound played');
            }).catch((error) => {
                console.warn('All audio methods failed:', error);
            });
            
        } catch (error) {
            console.warn('Final fallback sound failed:', error);
        }
    }

    /**
     * Show browser notification for new orders
     */
    function showNewOrderNotification(newOrdersCount) {
        const notificationsEnabled = kdsamrefData.settings?.enable_notifications == 1;
        const isIPad = /iPad|Macintosh/.test(navigator.userAgent) && 'ontouchend' in document;
        
        debugLog('🔔 Showing notification:', {
            enabled: notificationsEnabled,
            permission: notificationPermission,
            count: newOrdersCount,
            isIPad: isIPad
        });
        
        if (!notificationsEnabled) {
            debugLog('🔕 Browser notifications disabled in settings');
            return;
        }
        
        // Throttle desktop notifications as well
        const now = Date.now();
        const THROTTLE_MS = 3000;
        if ((now - lastNotificationTime) <= THROTTLE_MS) {
            debugLog('⏳ Notification throttled');
            return;
        }
        lastNotificationTime = now;

        try {
            const title = `🍽️ ${kdsamrefData.strings?.js?.newOrdersTitle || 'New Orders!'}`;
            const body = `${newOrdersCount} ${kdsamrefData.strings?.js?.newOrdersBody || 'new order(s) received'}`;
            const icon = kdsamrefData.pluginUrl + 'assets/images/kds_for_orderable_logo.png';
            
            // Try browser notification if permission granted
            if (notificationPermission && 'Notification' in window) {
                const notification = new Notification(title, {
                    body: body,
                    icon: icon,
                    badge: icon,
                    tag: 'new-order-' + Date.now(), // Unique tag to show multiple notifications
                    requireInteraction: false, // Don't require interaction
                    silent: true // Silence system sound; we handle sound ourselves
                });
                
                // Auto-close after 8 seconds
                setTimeout(() => {
                    try {
                        notification.close();
                    } catch (e) {
                        // Notification might already be closed
                    }
                }, 8000);
                
                // Click handler
                notification.onclick = function() {
                    window.focus();
                    try {
                        notification.close();
                    } catch (e) {
                        // Ignore errors
                    }
                    
                    // Scroll to orders
                    const ordersContainer = document.getElementById('kdsamref-orders-container');
                    if (ordersContainer) {
                        ordersContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }
                };
                
                debugLog('✅ Browser notification displayed');
            } else {
                debugLog('⚠️ Browser notification permission not granted');
            }
            
            // Always show visual notification for iPad or as fallback
            if (isIPad || !notificationPermission) {
                showIPadNotification(newOrdersCount);
            }
            
        } catch (error) {
            console.warn('Browser notification error:', error);
            // Always fallback to visual notification
            showIPadNotification(newOrdersCount);
        }
    }
    
    /**
     * Show enhanced visual notification for iPad
     */
    function showIPadNotification(newOrdersCount) {
        const $notification = $(`
            <div class="kdsamref-ipad-notification">
                <div class="kdsamref-notification-content">
                    <span class="kdsamref-notification-icon">🍽️</span>
                    <div>
                        <div class="kdsamref-notification-title">${kdsamrefData.strings?.js?.newOrdersTitle || 'New Orders!'}</div>
                        <div class="kdsamref-notification-message">
                            ${newOrdersCount} ${kdsamrefData.strings?.js?.newOrdersBody || 'new order(s) received'}
                        </div>
                    </div>
                </div>
            </div>
        `);
        
        // Add animation CSS if not exists
        if (!$('#ipad-notification-animation').length) {
            $('<style>', {
                id: 'ipad-notification-animation',
                text: `
                    @keyframes slideInRight {
                        from { transform: translateX(100%); opacity: 0; }
                        to { transform: translateX(0); opacity: 1; }
                    }
                `
            }).appendTo('head');
        }
        
        $('body').append($notification);
        
        // Auto remove after 4 seconds
        setTimeout(() => {
            $notification.fadeOut(300, () => $notification.remove());
        }, 4000);
    }

    /**
     * Check for new orders and trigger notifications
     */
    function checkForNewOrders(currentOrders) {
        const currentOrderCount = currentOrders.length;
        const currentOrderIds = currentOrders.map(order => order.id);
        
        debugLog('🔍 Checking for new orders:', {
            currentCount: currentOrderCount,
            lastCount: lastOrderCount,
            preventNotifications: window.preventNotifications,
            currentDateFilter: currentDateFilter
        });
        
        // Don't trigger notifications during switch changes or other operations
        if (window.preventNotifications) {
            debugLog('🙅 Notifications prevented');
            lastOrderCount = currentOrderCount;
            window.lastOrderIds = currentOrderIds;
            return;
        }
        
        // Initialize on first run
        if (typeof lastOrderCount === 'undefined' || !window.lastOrderIds) {
            debugLog('🎆 First run - initializing order tracking');
            lastOrderCount = currentOrderCount;
            window.lastOrderIds = currentOrderIds;
            return;
        }
        
        // Skip notification on initial load with orders (page refresh)
        if (lastOrderCount === 0 && currentOrderCount > 0) {
            debugLog('🔄 Initial load with orders - no notification');
            lastOrderCount = currentOrderCount;
            window.lastOrderIds = currentOrderIds;
            return;
        }
        
        // Check for truly new orders by comparing IDs
        const previousOrderIds = window.lastOrderIds || [];
        const newOrderIds = currentOrderIds.filter(id => !previousOrderIds.includes(id));
        
        debugLog('🔍 Order comparison:', {
            previousIds: previousOrderIds.slice(0, 3) + (previousOrderIds.length > 3 ? '...' : ''),
            currentIds: currentOrderIds.slice(0, 3) + (currentOrderIds.length > 3 ? '...' : ''),
            newIds: newOrderIds
        });
        
        // Trigger notifications only for truly new orders
        if (newOrderIds.length > 0) {
            const newOrdersCount = newOrderIds.length;
            debugLog('✨ New orders detected:', newOrdersCount);

            // Throttle to avoid spam: min 3s gap between sound/desktop notifications
            const now = Date.now();
            const THROTTLE_MS = 3000;
            const canNotify = (now - lastNotificationTime) > THROTTLE_MS;

            // Update badge count
            pendingNewOrders += newOrdersCount;
            updateNotificationBadge(pendingNewOrders);

            if (canNotify) {
                lastNotificationTime = now;
                playNotificationSound();
                showNewOrderNotification(pendingNewOrders);
                showSuccessMessage(`🎆 ${pendingNewOrders} new order${pendingNewOrders > 1 ? 's' : ''} received!`);
                // Reset badge counter after notifying
                pendingNewOrders = 0;
                updateNotificationBadge(0);
            }

            // Flash header for visual attention
            flashHeader();
        }
        
        // Always update tracking variables
        lastOrderCount = currentOrderCount;
        window.lastOrderIds = currentOrderIds;
    }

    /**
     * Flash header to get attention for new orders
     */
    function flashHeader() {
        const $header = $('.kdsamref-header');
        $header.addClass('new-order-flash');
        
        if (!$('#new-order-flash-style').length) {
            $('<style>', {
                id: 'new-order-flash-style',
                text: `
                    .new-order-flash {
                        animation: orderFlash 2s ease-in-out 3;
                        background: linear-gradient(90deg, #10b981, #34d399, #10b981) !important;
                        background-size: 200% 100% !important;
                    }
                    @keyframes orderFlash {
                        0%, 100% { background-position: 0% 50%; }
                        50% { background-position: 100% 50%; }
                    }
                `
            }).appendTo('head');
        }
        
        setTimeout(() => {
            $header.removeClass('new-order-flash');
        }, 6000);
    }

    /**
     * Show license warnings for free users
     */
    function showLicenseWarnings() {
        const hasValidLicense = (kdsamrefData.license && (
            kdsamrefData.license.is_premium || 
            kdsamrefData.license.valid || 
            kdsamrefData.license.realtime_enabled
        )) || kdsamrefData.realTimeEnabled || false;
        
        if (!hasValidLicense) {
            const $refreshBtn = $('#kdsamref-refresh-btn');
            $refreshBtn.attr('title', 'Free version: Manual refresh only. Activate your license for automatic refresh.');
        }
    }

    /**
     * Apply dashboard settings from admin panel - Optimized to prevent style injection loops
     */
    function applyDashboardSettings() {
        const settings = kdsamrefData.settings || {};
        
        // Remove existing dashboard style tags to prevent duplication
        $('#kdsamref-dashboard-settings-style').remove();
        $('#kdsamref-font-size-style').remove();
        
        let combinedStyles = '';
        
        // Apply default font size if no saved value
        if (!localStorage.getItem('kdsamref-font-size') && settings.defaultFontSize) {
            const size = settings.defaultFontSize;
            if (size !== 100) {
                combinedStyles += `
                    .kdsamref-dashboard, .kdsamref-dashboard * {
                        font-size: ${size}% !important;
                    }
                `;
            }
            $('#kdsamref-font-decrease').prop('disabled', size <= 80);
            $('#kdsamref-font-increase').prop('disabled', size >= 140);
        }
        
        // Apply completed orders opacity
        if (settings.completedOrdersOpacity !== undefined) {
            combinedStyles += `
                .kdsamref-order-card.completed {
                    opacity: ${settings.completedOrdersOpacity} !important;
                }
            `;
        }
        
        // Apply compact mode
        if (settings.compactMode) {
            combinedStyles += `
                .kdsamref-order-card {
                    padding: 12px !important;
                    margin-bottom: 8px !important;
                }
                .kdsamref-order-card .kdsamref-order-header {
                    margin-bottom: 8px !important;
                }
                .kdsamref-order-card .kdsamref-order-items {
                    margin-bottom: 8px !important;
                }
                .kdsamref-order-card .kdsamref-order-footer {
                    margin-top: 8px !important;
                }
                .kdsamref-order-card .kdsamref-order-meta {
                    font-size: 0.85em !important;
                }
                .kdsamref-order-card .kdsamref-order-number {
                    font-size: 0.9em !important;
                }
                .kdsamref-order-card .kdsamref-customer-name {
                    font-size: 0.9em !important;
                }
                .kdsamref-order-card .kdsamref-order-total {
                    font-size: 0.9em !important;
                }
                .kdsamref-orders-container {
                    gap: 8px !important;
                }
            `;
        }
        
        // Apply show completed orders setting
        if (settings.showCompletedOrders === false) {
            combinedStyles += `
                .kdsamref-order-card.completed {
                    display: none !important;
                }
            `;
        }

        // Add all styles in a single tag if there are any
        if (combinedStyles) {
            $('<style>', {
                id: 'kdsamref-dashboard-settings-style',
                text: combinedStyles
            }).appendTo('head');
        }

        // Apply custom colors and status colors (only once, no recursion)
        applyCustomColorsOnly();
        applyCustomStatusColors();
    }

    /**
     * Bind all event handlers
     */
    function bindEvents() {
        // User interaction tracking
        $(document).on('mousedown touchstart keydown', trackUserInteraction);
        $(document).on('mouseup touchend keyup', function() {
            setTimeout(() => isUserInteracting = false, 200);
        });

        // Status filter buttons - Enhanced for workflow
        $(document).on('click', '.kdsamref-status-btn', function() {
            $('.kdsamref-status-btn').removeClass('active');
            $(this).addClass('active');
            currentFilter = $(this).data('filter');
            filterOrders();
        });

        // Search functionality
        $('.kdsamref-search-btn').on('click', function() {
            const $container = $('#kdsamref-search-container');
            const $input = $('#kdsamref-search');
            
            if ($container.is(':visible')) {
                $container.hide();
                $input.val('');
                currentSearchTerm = '';
                filterOrders();
            } else {
                $container.show();
                $input.focus();
            }
        });

        $('#kdsamref-search').on('input', debounce(function() {
            const searchValue = $(this).val() || '';
            currentSearchTerm = searchValue.toLowerCase();
            filterOrders();
        }, 300));

        // Manual refresh button
        $('#kdsamref-refresh-btn').on('click', function() {
            const $btn = $(this);
            if ($btn.hasClass('loading')) return; // Prevent multiple clicks
            
            $btn.addClass('loading');
            
            // Show notification instead of scrolling
            showSuccessMessage('🔄 ' + (kdsamrefData.strings?.js?.refreshStarted || 'Refresh started...'));
            
            loadOrdersByDate(currentDateFilter);
            
            // Remove loading after 2 seconds or when orders are loaded
            setTimeout(() => {
                $btn.removeClass('loading');
            }, 2000);
        });
        
        // Notifications button
        $('#kdsamref-notifications-btn').on('click', function() {
            if ('Notification' in window) {
                if (Notification.permission === 'default') {
                    Notification.requestPermission().then(function (permission) {
                        notificationPermission = (permission === 'granted');
                        if (notificationPermission) {
                        const soundWas = kdsamrefData.settings?.notification_sound == 1;
                        $('#kdsamref-notifications-btn').addClass('enabled');
                        $('#kdsamref-notifications-btn').attr('title', soundWas ? 'Notifications enabled (Sound on)' : 'Notifications enabled (Sound off)');
                            // Test sound
                        if (soundWas) {
                            playNotificationSound();
                        }
                        } else {
                            showError('Notifications refusées');
                            $('#kdsamref-notifications-btn').removeClass('enabled');
                            $('#kdsamref-notifications-btn').attr('title', 'Notifications blocked in browser');
                        }
                    });
                } else if (Notification.permission === 'granted') {
                // Toggle sound on/off quickly from button
                // Ensure settings object exists
                if (!kdsamrefData.settings) {
                    kdsamrefData.settings = {};
                }
                const currentSound = kdsamrefData.settings.notification_sound == 1;
                kdsamrefData.settings.notification_sound = currentSound ? 0 : 1;
                const soundOn = kdsamrefData.settings.notification_sound == 1;
                const label = soundOn ? 'Sound on 🔔' : 'Sound off 🔕';
                showSuccessMessage(label);
                if (soundOn) {
                    $('#kdsamref-notifications-btn').addClass('enabled');
                } else {
                    $('#kdsamref-notifications-btn').removeClass('enabled');
                }
                $('#kdsamref-notifications-btn').attr('title', soundOn ? 'Notifications enabled (Sound on)' : 'Notifications enabled (Sound off)');
                    // Test sound
                if (soundOn) {
                    playNotificationSound();
                }
                } else {
                    showError('Notifications bloquées dans votre navigateur');
                    $('#kdsamref-notifications-btn').removeClass('enabled');
                    $('#kdsamref-notifications-btn').attr('title', 'Notifications blocked in browser');
                }
            } else {
                showError('Votre navigateur ne supporte pas les notifications');
            }
        });
        
        // Font size controls
        $('#kdsamref-font-decrease').on('click', function() {
            changeFontSize(-1);
        });
        
        $('#kdsamref-font-increase').on('click', function() {
            changeFontSize(1);
        });

        // Order actions (delegated events) - Enhanced for workflow
        $(document).on('click', '.kdsamref-action-btn[data-action]', handleOrderAction);

        // Modal close - Enhanced with better event handling
        $(document).on('click', '.kdsamref-modal-close', function(e) {
            e.preventDefault();
            e.stopPropagation();
            closeModal();
        });
        
        // Click outside modal to close
        $(document).on('click', '.kdsamref-modal', function(e) {
            if (e.target === this) {
                closeModal();
            }
        });

        // ESC key to close modal or search
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape') {
                if ($('#kdsamref-order-modal').is(':visible')) {
                    closeModal();
                } else if ($('#kdsamref-search-container').is(':visible')) {
                    $('#kdsamref-search-container').hide();
                    $('#kdsamref-search').val('');
                    currentSearchTerm = '';
                    filterOrders();
                } else if ($('.kdsamref-dashboard').hasClass('fullscreen-mode')) {
                    exitFullscreen();
                }
            }
        });
        
        // Dashboard fullscreen button
        $('#kdsamref-dashboard-fullscreen-btn').on('click', function() {
            const dashboard = $('.kdsamref-dashboard');
            if (dashboard.hasClass('fullscreen-mode') || document.fullscreenElement) {
                exitFullscreen();
            } else {
                enterFullscreen();
            }
        });
        
        // Masonry layout toggle button
        $('#kdsamref-masonry-toggle-btn').on('click', function() {
            // Check if Pro feature is available
            if ($(this).hasClass('kdsamref-pro-feature') && !kdsamrefData.proActive) {
                // Redirect to Pro Features page
                window.location.href = 'admin.php?page=kdsamref-pro-features';
                return;
            }
            
            const $btn = $(this);
            const $container = $('#kdsamref-orders-container');
            
            if ($container.hasClass('masonry-layout')) {
                // Switch to grid layout
                $container.removeClass('masonry-layout');
                $btn.removeClass('active');
                localStorage.setItem('kdsamref_layout_mode', 'grid');
                // Let CSS handle the grid layout
                restoreGridLayout();
            } else {
                // Switch to masonry layout
                $container.addClass('masonry-layout');
                $btn.addClass('active');
                localStorage.setItem('kdsamref_layout_mode', 'masonry');
                // Apply masonry layout
                applyMasonryLayout();
            }
        });
        
        // Listen for fullscreen change events
        document.addEventListener('fullscreenchange', handleFullscreenChange);
        document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
        document.addEventListener('mozfullscreenchange', handleFullscreenChange);
        document.addEventListener('MSFullscreenChange', handleFullscreenChange);
        
        // Add back/settings shortcut if not present
        if (!document.getElementById('kdsamref-back-btn')) {
            const $controls = $('.kdsamref-controls');
            if ($controls.length) {
                const backUrl = (kdsamrefData && kdsamrefData.ajaxUrl) ? kdsamrefData.ajaxUrl.replace('admin-ajax.php', 'admin.php?page=restaurant-orders-settings') : 'admin.php?page=restaurant-orders-settings';
                const $backBtn = $(`
                    <a id="kdsamref-back-btn" class="kdsamref-font-btn" href="${backUrl}" title="Settings">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 18l-6-6 6-6"/></svg>
                    </a>
                `);
                $controls.prepend($backBtn);
            }
        }



        // Handle date filter button clicks
        $(document).on('click', '.kdsamref-date-btn', function() {
            const dateFilter = $(this).data('date');
            const buttonText = $(this).text();
            
            // Prevent notifications during date filter changes
            window.preventNotifications = true;
            
            // Update current date filter
            currentDateFilter = dateFilter;
            
            // Update active button
            $('.kdsamref-date-btn').removeClass('active');
            $(this).addClass('active');
            
            // Load orders for selected date
            loadOrdersByDate(dateFilter);
            
            // Re-enable notifications after a short delay
            setTimeout(() => {
                window.preventNotifications = false;
            }, 1000);
        });
        
        // Handle window resize for masonry layout
        $(window).on('resize', debounce(function() {
            const $container = $('#kdsamref-orders-container');
            if ($container.hasClass('masonry-layout')) {
                applyMasonryLayout();
            }
        }, 250));

        // Stock Management Button
        $('#kdsamref-stock-management-btn').on('click', function() {
            // Check if Pro feature is available
            if ($(this).hasClass('kdsamref-pro-feature') && !kdsamrefData.proActive) {
                // Redirect to Pro Features page
                window.location.href = 'admin.php?page=kdsamref-pro-features';
                return;
            }
            
            openStockModal();
        });

        // Stock Modal Close
        $(document).on('click', '#kdsamref-stock-modal .kdsamref-modal-close', function() {
            closeStockModal();
        });

        // Stock Modal Backdrop Close
        $(document).on('click', '#kdsamref-stock-modal', function(e) {
            if (e.target === this) {
                closeStockModal();
            }
        });

        // Stock Search Functionality
        $('#kdsamref-stock-search').on('input', debounce(function() {
            const searchTerm = $(this).val().toLowerCase();
            filterStockItems(searchTerm);
            updateSearchClearButton();
        }, 300));

        // Stock Search Clear Button
        $('#kdsamref-stock-search-clear').on('click', function() {
            $('#kdsamref-stock-search').val('');
            filterStockItems('');
            updateSearchClearButton();
        });

        // Stock Filter Buttons
        $(document).on('click', '.kdsamref-stock-filter-btn', function() {
            const filter = $(this).data('filter');
            $('.kdsamref-stock-filter-btn').removeClass('active');
            $(this).addClass('active');
            filterStockByStatus(filter);
        });

        // Stock Quantity Input Changes
        $(document).on('input', '.kdsamref-stock-quantity-input', function() {
            checkStockChanges($(this).closest('.kdsamref-stock-item'));
        });

        // Stock Status Select Changes
        $(document).on('change', '.kdsamref-stock-status-select', function() {
            checkStockChanges($(this).closest('.kdsamref-stock-item'));
        });

        // Stock Save Button
        $(document).on('click', '.kdsamref-stock-save-btn', function() {
            const $btn = $(this);
            const $item = $btn.closest('.kdsamref-stock-item');
            const productId = $item.data('product-id');
            const newQuantity = parseInt($item.find('.kdsamref-stock-quantity-input').val()) || 0;
            const newStatus = $item.find('.kdsamref-stock-status-select').val();
            
            saveStockQuantity(productId, newQuantity, $item, newStatus);
        });

        // Stock Reset Button
        $(document).on('click', '.kdsamref-stock-reset-btn', function() {
            const $item = $(this).closest('.kdsamref-stock-item');
            const originalQuantity = $item.data('original-quantity');
            const originalStatus = $item.data('original-status');
            $item.find('.kdsamref-stock-quantity-input').val(originalQuantity);
            $item.find('.kdsamref-stock-status-select').val(originalStatus);
            $item.find('.kdsamref-stock-save-btn').prop('disabled', true);
        });

        // ESC key to close modals
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape') {
                if ($('#kdsamref-order-modal').is(':visible')) {
                    closeModal();
                } else if ($('#kdsamref-stock-modal').is(':visible')) {
                    closeStockModal();
                } else if ($('.kdsamref-dashboard').hasClass('fullscreen-mode')) {
                    exitFullscreen();
                }
            }
        });
    }

    /**
     * Track user interactions
     */
    function trackUserInteraction() {
        isUserInteracting = true;
    }

    // Stock Management Variables
    let stockItems = [];
    let currentStockFilter = 'all';
    let currentStockSearch = '';

    /**
     * Open Stock Management Modal
     */
    function openStockModal() {
        const $modal = $('#kdsamref-stock-modal');
        $modal.removeAttr('aria-hidden').addClass('modal-active');
        $('body').addClass('modal-open');
        
        // Load stock data
        loadStockData();
    }

    /**
     * Close Stock Management Modal
     */
    function closeStockModal() {
        const $modal = $('#kdsamref-stock-modal');
        $modal.attr('aria-hidden', 'true').removeClass('modal-active');
        $('body').removeClass('modal-open');
        
        // Clear search
        $('#kdsamref-stock-search').val('');
        currentStockSearch = '';
        updateSearchClearButton();
    }

    /**
     * Load Stock Data
     */
    function loadStockData() {
        const $container = $('#kdsamref-stock-container');
        const $loading = $('#kdsamref-stock-loading');
        const $noItems = $('#kdsamref-no-stock-items');
        
        $container.hide();
        $noItems.hide();
        $loading.show();

        // Real AJAX call to get stock items
        $.ajax({
            url: kdsamrefData.ajaxUrl,
            type: 'POST',
            data: {
                action: 'kdsamref_get_stock_items',
                nonce: kdsamrefData.nonce
            },
            success: function(response) {
                if (response.success && response.data.stock_items) {
                    stockItems = response.data.stock_items;
                    renderStockItems();
                    updateStockCounts();
                } else {
                    console.error('Failed to load stock items:', response.data?.message || 'Unknown error');
                    showStockErrorMessage('Failed to load stock items');
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error:', error);
                showStockErrorMessage('Network error while loading stock items');
            },
            complete: function() {
                $loading.hide();
                $container.show();
            }
        });
    }

    /**
     * Render Stock Items
     */
    function renderStockItems() {
        const $container = $('#kdsamref-stock-container');
        $container.empty();

        if (stockItems.length === 0) {
            $('#kdsamref-no-stock-items').show();
            return;
        }

        stockItems.forEach(item => {
            const $item = createStockItemElement(item);
            $container.append($item);
        });
    }

    /**
     * Create Stock Item Element
     */
    function createStockItemElement(item) {
        const statusClass = item.status === 'in-stock' ? 'in-stock' : 
                           item.status === 'low-stock' ? 'low-stock' : 'out-of-stock';
        
        const statusText = item.status === 'in-stock' ? 'In Stock' : 
                          item.status === 'low-stock' ? 'Low Stock' : 'Out of Stock';

        const stockStatusOptions = `
            <option value="instock" ${item.stock_status === 'instock' ? 'selected' : ''}>In Stock</option>
            <option value="outofstock" ${item.stock_status === 'outofstock' ? 'selected' : ''}>Out of Stock</option>
            <option value="onbackorder" ${item.stock_status === 'onbackorder' ? 'selected' : ''}>On Backorder</option>
        `;

        return $(`
            <div class="kdsamref-stock-item" data-product-id="${item.id}" data-original-quantity="${item.quantity}" data-original-status="${item.stock_status}">
                <div class="kdsamref-stock-item-header">
                    <div>
                        <h3 class="kdsamref-stock-item-title">${item.name}</h3>
                        <div class="kdsamref-stock-item-sku">
                            ${item.sku}
                            ${item.parent_category ? `<span class="kdsamref-stock-parent-category">${item.parent_category}</span>` : item.category ? `<span class="kdsamref-stock-parent-category">${item.category}</span>` : ''}
                        </div>
                        ${!item.manage_stock ? '<div class="kdsamref-stock-note" style="font-size: 11px; color: #6c757d; margin-top: 4px;">Stock management will be enabled when updated</div>' : ''}
                    </div>
                    <div class="kdsamref-stock-item-status ${statusClass}">${statusText}</div>
                </div>
                <div class="kdsamref-stock-item-content">
                    <div class="kdsamref-stock-item-price">${item.price}</div>
                    <div class="kdsamref-stock-item-quantity">
                        <span class="kdsamref-stock-quantity-label">Quantity:</span>
                        <input type="number" class="kdsamref-stock-quantity-input" value="${item.quantity}" min="0">
                    </div>
                </div>
                <div class="kdsamref-stock-item-status-control">
                    <span class="kdsamref-stock-status-label">Stock Status:</span>
                    <select class="kdsamref-stock-status-select">
                        ${stockStatusOptions}
                    </select>
                </div>
                <div class="kdsamref-stock-item-actions">
                    <button class="kdsamref-stock-save-btn" disabled>Save</button>
                    <button class="kdsamref-stock-reset-btn">Reset</button>
                </div>
            </div>
        `);
    }

    /**
     * Filter Stock Items by Search Term
     */
    function filterStockItems(searchTerm) {
        currentStockSearch = searchTerm;
        applyStockFilters();
    }

    /**
     * Filter Stock Items by Status
     */
    function filterStockByStatus(filter) {
        currentStockFilter = filter;
        applyStockFilters();
    }

    /**
     * Apply Stock Filters
     */
    function applyStockFilters() {
        const $container = $('#kdsamref-stock-container');
        const $noItems = $('#kdsamref-no-stock-items');
        
        let filteredItems = stockItems;

        // Apply search filter
        if (currentStockSearch) {
            filteredItems = filteredItems.filter(item => 
                item.name.toLowerCase().includes(currentStockSearch) ||
                item.sku.toLowerCase().includes(currentStockSearch) ||
                item.category.toLowerCase().includes(currentStockSearch)
            );
        }

        // Apply status filter
        if (currentStockFilter !== 'all') {
            filteredItems = filteredItems.filter(item => item.status === currentStockFilter);
        }

        // Render filtered items
        $container.empty();
        
        if (filteredItems.length === 0) {
            $noItems.show();
        } else {
            $noItems.hide();
            filteredItems.forEach(item => {
                const $item = createStockItemElement(item);
                $container.append($item);
            });
        }
    }

    /**
     * Update Stock Counts
     */
    function updateStockCounts() {
        const counts = {
            all: stockItems.length,
            'in-stock': stockItems.filter(item => item.status === 'in-stock').length,
            'low-stock': stockItems.filter(item => item.status === 'low-stock').length,
            'out-of-stock': stockItems.filter(item => item.status === 'out-of-stock').length
        };

        $('#stock-count-all').text(counts.all);
        $('#stock-count-in-stock').text(counts['in-stock']);
        $('#stock-count-low-stock').text(counts['low-stock']);
        $('#stock-count-out-of-stock').text(counts['out-of-stock']);
    }

    /**
     * Update Search Clear Button
     */
    function updateSearchClearButton() {
        const $clearBtn = $('#kdsamref-stock-search-clear');
        const searchValue = $('#kdsamref-stock-search').val();
        
        if (searchValue) {
            $clearBtn.show();
        } else {
            $clearBtn.hide();
        }
    }

    /**
     * Check Stock Changes
     */
    function checkStockChanges($item) {
        const originalQuantity = $item.data('original-quantity');
        const originalStatus = $item.data('original-status');
        const currentQuantity = parseInt($item.find('.kdsamref-stock-quantity-input').val()) || 0;
        const currentStatus = $item.find('.kdsamref-stock-status-select').val();
        
        // Enable/disable save button based on changes
        const $saveBtn = $item.find('.kdsamref-stock-save-btn');
        if (currentQuantity !== originalQuantity || currentStatus !== originalStatus) {
            $saveBtn.prop('disabled', false);
        } else {
            $saveBtn.prop('disabled', true);
        }
    }

    /**
     * Save Stock Quantity
     */
    function saveStockQuantity(productId, newQuantity, $item, newStatus) {
        const $btn = $item.find('.kdsamref-stock-save-btn');
        const originalText = $btn.text();
        
        $btn.prop('disabled', true).text('Saving...');

        // Real AJAX call to update stock quantity
        $.ajax({
            url: kdsamrefData.ajaxUrl,
            type: 'POST',
            data: {
                action: 'kdsamref_update_stock_quantity',
                product_id: productId,
                quantity: newQuantity,
                stock_status: newStatus,
                nonce: kdsamrefData.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Update local data
                    const item = stockItems.find(item => item.id === productId);
                    if (item) {
                        item.quantity = response.data.new_quantity;
                        item.status = response.data.new_status;
                        item.stock_status = response.data.stock_status;
                        item.manage_stock = response.data.manage_stock;
                        
                        // Update the item element
                        const $status = $item.find('.kdsamref-stock-item-status');
                        const statusClass = item.status === 'in-stock' ? 'in-stock' : 
                                           item.status === 'low-stock' ? 'low-stock' : 'out-of-stock';
                        const statusText = item.status === 'in-stock' ? 'In Stock' : 
                                          item.status === 'low-stock' ? 'Low Stock' : 'Out of Stock';
                        
                        $status.removeClass('in-stock low-stock out-of-stock').addClass(statusClass).text(statusText);
                        $item.data('original-quantity', response.data.new_quantity);
                        $item.data('original-status', response.data.stock_status);
                        
                        // Update status select
                        $item.find('.kdsamref-stock-status-select').val(response.data.stock_status);
                        
                        // Update or remove the stock management note
                        const $note = $item.find('.kdsamref-stock-note');
                        if (response.data.manage_stock) {
                            $note.remove();
                        } else if ($note.length === 0) {
                            $item.find('.kdsamref-stock-item-title').after('<div class="kdsamref-stock-note" style="font-size: 11px; color: #6c757d; margin-top: 4px;">Stock management will be enabled when updated</div>');
                        }
                    }

                    $btn.prop('disabled', true).text(originalText);
                    
                    // Show success message
                    showStockSuccessMessage(response.data.message);
                    
                    // Update counts
                    updateStockCounts();
                } else {
                    $btn.prop('disabled', false).text(originalText);
                    showStockErrorMessage(response.data?.message || 'Failed to update stock quantity');
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error:', error);
                $btn.prop('disabled', false).text(originalText);
                showStockErrorMessage('Network error while updating stock quantity');
            }
        });
    }

    /**
     * Show Stock Success Message
     */
    function showStockSuccessMessage(message) {
        const $message = $(`
            <div class="kdsamref-stock-success-message" style="
                position: fixed;
                top: 20px;
                right: 20px;
                background: #d4edda;
                color: #155724;
                padding: 12px 20px;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                z-index: 999999;
                animation: slideInRight 0.3s ease;
            ">
                ${message}
            </div>
        `);
        
        $('body').append($message);
        
        setTimeout(() => {
            $message.fadeOut(300, () => $message.remove());
        }, 3000);
    }

    /**
     * Show Stock Error Message
     */
    function showStockErrorMessage(message) {
        const $message = $(`
            <div class="kdsamref-stock-error-message" style="
                position: fixed;
                top: 20px;
                right: 20px;
                background: #f8d7da;
                color: #721c24;
                padding: 12px 20px;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                z-index: 999999;
                animation: slideInRight 0.3s ease;
            ">
                ${message}
            </div>
        `);
        
        $('body').append($message);
        
        setTimeout(() => {
            $message.fadeOut(300, () => $message.remove());
        }, 5000);
    }
    
    /**
     * Change font size with limits
     */
    function changeFontSize(delta) {
        const currentSize = parseInt(localStorage.getItem('kdsamref-font-size') || '100');
        const newSize = Math.max(80, Math.min(140, currentSize + delta * 5));
        
        localStorage.setItem('kdsamref-font-size', newSize);
        
        $('#kdsamref-font-size-style').remove();
        
        if (newSize !== 100) {
            const styleContent = `
                .kdsamref-dashboard, .kdsamref-dashboard * {
                    font-size: ${newSize}% !important;
                }
            `;
            $('<style>', {id: 'kdsamref-font-size-style', text: styleContent}).appendTo('head');
        }
        
        $('#kdsamref-font-decrease').prop('disabled', newSize <= 80);
        $('#kdsamref-font-increase').prop('disabled', newSize >= 140);
        
        showSuccessMessage(`Font size: ${newSize}%`);
    }

    /**
     * Test date calculations
     */
    function testDateCalculations() {
        debugLog('🧪 Testing date calculations...');
        
        const wpDates = calculateWpDates();
        const now = new Date();
        

        
        return wpDates;
    }

    /**
     * Check for Orderable orders in database
     */
    function checkOrderableOrders() {
        const wpDates = calculateWpDates();
        
        // Check for orders with Orderable date fields
        const checkData = {
            action: 'kdsamref_get_orders_by_date_range',
            nonce: kdsamrefData.nonce,
            start_date: wpDates.yesterday,
            end_date: wpDates.tomorrow,
            limit: 50,
            date_filter_type: 'created'
        };
        
        $.post(kdsamrefData.ajaxUrl || ajaxurl, checkData)
            .done(function(response) {
                if (response.success) {
                    const orders = response.data.orders || [];
                    
                    // Group orders by date
                    const ordersByDate = {};
                    orders.forEach(order => {
                        const orderDate = order.date_created.split('T')[0];
                        if (!ordersByDate[orderDate]) {
                            ordersByDate[orderDate] = [];
                        }
                        ordersByDate[orderDate].push(order);
                    });
                    
                }
            })
            .fail(function(xhr, status, error) {
                // Silent fail
            });
    }

    /**
     * Test date filtering functionality
     */
    function testDateFiltering() {
        debugLog('🧪 Testing Date Filtering...');
        
        // Test dynamic date calculation
        const wpDates = calculateWpDates();
        debugLog('✅ Dynamic date calculation:', wpDates);
        
        // Test each date filter
        const testDates = isDeliveryMode ? ['today', 'yesterday', 'tomorrow'] : ['today', 'yesterday'];
        
        testDates.forEach((dateFilter, index) => {
            setTimeout(() => {
                debugLog(`🧪 Testing ${dateFilter} filter...`);
                
                // Simulate the AJAX call data
                const testData = {
                    action: 'kdsamref_get_orders_by_date_range',
                    nonce: kdsamrefData.nonce,
                    start_date: wpDates[dateFilter],
                    end_date: wpDates[dateFilter],
                    limit: 10,
                    date_filter_type: 'created'
                };
                
                debugLog(`📅 Test data for ${dateFilter}:`, testData);
                
                // Make actual AJAX call to test
                $.post(kdsamrefData.ajaxUrl || ajaxurl, testData)
                    .done(function(response) {
                        debugLog(`✅ ${dateFilter} filter result:`, {
                            success: response.success,
                            orderCount: response.data?.orders?.length || 0,
                            dateRange: response.data?.date_range,
                            compatibilityMode: response.data?.compatibility_mode
                        });
                    })
                    .fail(function(xhr, status, error) {
                        debugLog(`❌ ${dateFilter} filter failed:`, {xhr, status, error});
                    });
            }, index * 1000); // Test each filter with 1 second delay
        });
    }

    /**
     * Debug function to check date calculations
     */
    function debugDateCalculations() {
        const wpDates = calculateWpDates();
        return wpDates;
    }

    /**
     * Calculate WordPress timezone dates dynamically
     */
    function calculateWpDates() {
        // Use WordPress dates from server (more reliable)
        const wpDates = {
            today: kdsamrefData.currentWpDate || new Date().toISOString().split('T')[0],
            yesterday: kdsamrefData.yesterdayWpDate || new Date(Date.now() - 24*60*60*1000).toISOString().split('T')[0],
            tomorrow: kdsamrefData.tomorrowWpDate || calculateTomorrowDate(), // Include tomorrow for delivery mode
            wpTimezone: kdsamrefData.wpTimezone || 'UTC',
            wpTimezoneOffset: kdsamrefData.wpTimezoneOffset || 0,
            currentWpTime: kdsamrefData.debugCurrentTime
        };
        
        // Fallback tomorrow date calculation
        if (!wpDates.tomorrow) {
            wpDates.tomorrow = calculateTomorrowDate();
        }
        
        return wpDates;
    }

    /**
     * Load orders by date range
     */
    function loadOrdersByDate(dateFilter) {
        currentDateFilter = dateFilter;
        
        // Prevent notifications during manual date filter changes
        window.preventNotifications = true;
        
        showLoading();
        
        // Calculate dates dynamically in WordPress timezone
        const wpDates = calculateWpDates();
        let startDate, endDate;
        
        if (dateFilter === 'today') {
            startDate = endDate = wpDates.today;
        } else if (dateFilter === 'yesterday') {
            startDate = endDate = wpDates.yesterday;
        } else if (dateFilter === 'tomorrow') {
            startDate = endDate = wpDates.tomorrow;
            
            // Validate tomorrow date
            if (!wpDates.tomorrow) {
                showError('Error: Tomorrow date is not available');
                hideLoading();
                return;
            }
        } else {
            startDate = endDate = wpDates.today;
        }
        
        // Prepare AJAX data
        const data = {
            action: 'kdsamref_get_orders_by_date_range',
            nonce: kdsamrefData.nonce,
            start_date: startDate,
            end_date: endDate,
            limit: kdsamrefData.settings?.maxOrdersLimit || 100,
            date_filter_type: dateFilterType // Send the current date filter type
        };
        
        // Debug: Log the data being sent
        
        $.post(kdsamrefData.ajaxUrl || ajaxurl, data)
            .done(function(response) {
                if (response.success) {
                    // Store current filter before rendering
                    const previousFilter = currentFilter;
                    
                    orders = (response.data.orders || []);
                    renderOrders();
                    
                    // Restore the previous filter after rendering
                    if (previousFilter) {
                        currentFilter = previousFilter;
                        // Ensure the correct filter button is active
                        $('.kdsamref-status-btn').removeClass('active');
                        const $activeBtn = $(`.kdsamref-status-btn[data-filter="${currentFilter}"]`);
                        if ($activeBtn.length) {
                            $activeBtn.addClass('active');
                        } else {
                            // Fallback to 'all' if previous filter doesn't exist
                            const $allBtn = $('.kdsamref-status-btn[data-filter="all"]');
                            if ($allBtn.length) {
                                $allBtn.addClass('active');
                                currentFilter = 'all';
                            }
                        }
                    }
                    
                    updateStatistics();
                    hideLoading();
                    
                    // Remove loading from refresh button (only if not auto-refresh)
                    if (!window.isAutoRefresh) {
                        $('#kdsamref-refresh-btn').removeClass('loading');
                    }
                    
                    // Show success notification only if enabled
                    if (!kdsamrefData.settings?.disable_refresh_notifications) {
                        showSuccessMessage('✅ ' + (kdsamrefData.strings?.js?.refreshCompleted || 'Refresh completed!'));
                    }
                    
                    // Re-enable notifications after a short delay
                    setTimeout(() => {
                        window.preventNotifications = false;
                    }, 1000);
                } else {
                    console.error('❌ AJAX Error:', response);
                    showError('Error loading orders: ' + (response.data || 'Unknown error'));
                    hideLoading();
                    
                    // Remove loading from refresh button (only if not auto-refresh)
                    if (!window.isAutoRefresh) {
                        $('#kdsamref-refresh-btn').removeClass('loading');
                    }
                    
                    // Re-enable notifications on error
                    window.preventNotifications = false;
                }
            })
            .fail(function(xhr, status, error) {
                console.error('❌ AJAX Failed:', {status, error});
                showError('Error loading orders: ' + error);
                hideLoading();
                
                // Remove loading from refresh button (only if not auto-refresh)
                if (!window.isAutoRefresh) {
                    $('#kdsamref-refresh-btn').removeClass('loading');
                }
                
                // Re-enable notifications on error
                window.preventNotifications = false;
            });
    }

    /**
     * Render orders in the grid with enhanced workflow support
     */
    function renderOrders() {
        const $container = $('#kdsamref-orders-container');
        const $noOrders = $('#kdsamref-no-orders');
        
        const compatibilityMode = kdsamrefData.compatibilityMode || 'auto';
        
        // Filter forbidden statuses
        let forbidden = [];
        if (compatibilityMode === 'woocommerce') {
            forbidden = ['checkout-draft', 'wc-checkout-draft'];
        } else {
            forbidden = ['checkout-draft', 'wc-checkout-draft'];
        }

        let filteredOrders = orders.filter(order => {
            const statusOk = !forbidden.includes(order.status);
            return statusOk;
        });
        
        // Apply license order limit
        if (kdsamrefData.license && kdsamrefData.license.order_limit > 0) {
            if (filteredOrders.length > kdsamrefData.license.order_limit) {
                showLimitWarning(filteredOrders.length, kdsamrefData.license.order_limit);
                filteredOrders = filteredOrders.slice(0, kdsamrefData.license.order_limit);
            }
        }

        // Check for new orders and send notifications
        checkForNewOrders(filteredOrders);

        // Clear container and show appropriate content
        $container.empty();
        
        if (filteredOrders.length === 0) {
            $container.hide();
            $noOrders.show();
            
            // Zero out statistics if no orders
            $('#count-all').text('0');
            Object.keys(kdsamrefData.statusLabels || {}).forEach(status => {
                $(`#count-${status}`).text('0');
            });
            return;
        }

        $noOrders.hide();
        $container.show();

        filteredOrders.forEach(order => {
            const $orderCard = createOrderCard(order);
            $container.append($orderCard);
        });

        // Update statistics AFTER all orders are rendered
        updateStatistics();
        
        // Render custom status filters with workflow integration (only once)
        renderStatusFilters();

        // Filter which orders are visible - preserve current filter selection
        filterOrders();
        
        // Update card borders based on status colors
        updateOrderCardBorders();
        
        // Apply masonry layout if enabled with optimized timing
        if ($container.hasClass('masonry-layout')) {
            // Use requestAnimationFrame for smoother layout updates
            requestAnimationFrame(() => {
                applyMasonryLayout();
            });
        }
    }

    /**
     * Show order limit warning for free users
     */
    function showLimitWarning(totalOrders, limit) {
        $('.kdsamref-limit-warning').remove();
        
        const message = `⚠️ Free version: Displaying ${limit} orders out of ${totalOrders} available (today + yesterday).`;
        
        const $warning = $(`
            <div class="kdsamref-limit-warning">
                <span class="kdsamref-warning-icon">⚠️</span>
                <span class="kdsamref-warning-message">${message}</span>
                <div class="kdsamref-warning-actions">
                    <a href="${kdsamrefData.ajaxUrl.replace('admin-ajax.php', 'admin.php?page=restaurant-orders-settings')}" class="kdsamref-warning-link">
                       Activate Premium →
                    </a>
                    <button onclick="$(this).closest('.kdsamref-limit-warning').fadeOut();" class="kdsamref-warning-dismiss" title="Hide">×</button>
                </div>
            </div>
        `);
        
        $('#kdsamref-orders-container').before($warning);
    }

    /**
     * Get delivery type information with enhanced compatibility
     */
    function getDeliveryType(type, orderableService = null, compatibilityMode = null) {
        if (!compatibilityMode) {
            compatibilityMode = kdsamrefData.compatibilityMode || kdsamrefData.orderableMode || 'auto';
        }
        

        
        // Enhanced Orderable service type mapping
        if (orderableService && compatibilityMode === 'orderable') {
            const serviceLower = orderableService.toLowerCase();
            
            if (serviceLower.includes('delivery') || serviceLower.includes('livraison')) {
                return {
                    class: 'delivery',
                    label: kdsamrefData.strings?.deliveryTypes?.livraison || 'Livraison'
                };
            } else if (serviceLower.includes('pickup') || serviceLower.includes('emporter') || serviceLower.includes('takeaway')) {
                return {
                    class: 'pickup',
                    label: kdsamrefData.strings?.deliveryTypes?.emporter || 'À Emporter'
                };
            } else if (serviceLower.includes('dine') || serviceLower.includes('surplace') || serviceLower.includes('table')) {
                return {
                    class: 'dine-in',
                    label: kdsamrefData.strings?.deliveryTypes?.surplace || 'Sur Place'
                };
            }
        }
        
        // WooCommerce mode delivery types
        if (compatibilityMode === 'woocommerce') {
            const woocommerceTypes = {
                'numerique': {
                    class: 'numerique',
                    label: kdsamrefData.strings.deliveryTypes.numerique || 'Numérique'
                },
                'point-vente': {
                    class: 'point-vente',
                    label: kdsamrefData.strings.deliveryTypes['point-vente'] || 'Point de Vente'
                },
                'livraison': {
                    class: 'delivery',
                    label: kdsamrefData.strings?.deliveryTypes?.livraison || 'Livraison'
                },
                'delivery': {
                    class: 'delivery',
                    label: kdsamrefData.strings?.deliveryTypes?.livraison || 'Livraison'
                },
                'retrait': {
                    class: 'pickup',
                    label: kdsamrefData.strings.deliveryTypes.retrait || 'Retrait'
                },
                'pickup': {
                    class: 'pickup',
                    label: kdsamrefData.strings.deliveryTypes.retrait || 'Retrait'
                }
            };
            
            return woocommerceTypes[type] || woocommerceTypes['point-vente'];
        }
        
        // Fallback to original Orderable type mapping
        const orderableTypes = {
            'emporter': {
                class: 'pickup',
                label: kdsamrefData.strings?.deliveryTypes?.emporter || 'À Emporter'
            },
            'livraison': {
                class: 'delivery',
                label: kdsamrefData.strings?.deliveryTypes?.livraison || 'Livraison'
            },
            'surplace': {
                class: 'dine-in',
                label: kdsamrefData.strings?.deliveryTypes?.surplace || 'Sur Place'
            },
            'pickup': {
                class: 'pickup',
                label: kdsamrefData.strings?.deliveryTypes?.emporter || 'À Emporter'
            },
            'delivery': {
                class: 'delivery',
                label: kdsamrefData.strings?.deliveryTypes?.livraison || 'Livraison'
            },
            'takeaway': {
                class: 'pickup',
                label: kdsamrefData.strings?.deliveryTypes?.emporter || 'À Emporter'
            },
            'dinein': {
                class: 'dine-in',
                label: kdsamrefData.strings?.deliveryTypes?.surplace || 'Sur Place'
            }
        };
        
        return orderableTypes[type] || orderableTypes['emporter'];
    }

    /**
     * Create order card HTML with enhanced workflow support
     */
    function createOrderCard(order) {
        const compatibilityMode = kdsamrefData.compatibilityMode || 'auto';
        const deliveryType = getDeliveryType(order.delivery.type, order.delivery.orderable_service, compatibilityMode);
        const statusBadge = getStatusBadge(order.status);
        const timeAgo = getTimeAgo(order.date_created);
        const isCompleted = order.status === 'completed';

        // Enhanced info rendering
        const orderableInfo = renderOrderableInfo(order);
        const scheduledInfo = renderScheduledInfo(order);
        const tipInfo = renderTipInfo(order);

        // Apply status color to card border if color exists
        const cardBorderClass = statusBadge.color ? 'kdsamref-custom-border' : '';
        const cardCustomStyle = statusBadge.color ? `--custom-color: ${statusBadge.color};` : '';

        // Settings-based visibility
        const showOrderNumbers = (kdsamrefData.settings?.show_order_numbers ?? 1) == 1;
        const showCustomerNames = (kdsamrefData.settings?.show_customer_names ?? 1) == 1;
        const orderNumberHtml = showOrderNumbers ? `<h3 class="kdsamref-order-number">#${order.number}</h3>` : '';
        const customerNameHtml = showCustomerNames ? `<div class="kdsamref-customer-name">${order.customer.name}</div>` : '';

        const $card = $(`
            <div class="kdsamref-order-card ${deliveryType.class} ${isCompleted ? 'completed' : ''}" 
                 data-order-id="${order.id}" 
                 data-timestamp="${order.date_created}"
                 data-status="${order.status}"
                 data-delivery="${order.delivery.type}"
                 data-compatibility-mode="${compatibilityMode}"
                 ${cardCustomStyle ? `style="${cardCustomStyle}"` : ''}>
                
                <!-- Order Content -->
                <div class="kdsamref-order-content">
                    <div class="kdsamref-order-header">
                        <div class="kdsamref-order-left">
                            ${orderNumberHtml}
                            <p class="kdsamref-order-time">${formatTime(order.date_created)} - ${timeAgo}</p>
                            ${order.delivery.table_number ? `<p class="kdsamref-order-table">${kdsamrefData.strings?.labels?.table || 'Table'} ${order.delivery.table_number}</p>` : ''}
                            ${scheduledInfo}
                        </div>
                        <div class="kdsamref-order-right">
                            <div class="kdsamref-status-badge status-${order.status} ${statusBadge.class}" ${statusBadge.color ? `style="--custom-color: ${statusBadge.color};"` : ''}>
                                ${statusBadge.label}
                            </div>
                            <div class="kdsamref-delivery-badge ${deliveryType.class}">
                                ${deliveryType.label}
                            </div>
                        </div>
                    </div>

                    ${customerNameHtml}

                    ${orderableInfo}

                    <div class="kdsamref-order-items">
                        ${renderOrderItems(order.items, order.currency_symbol || '€')}
                    </div>

                    <div class="kdsamref-order-total">
                        <span class="kdsamref-total-label">${kdsamrefData.strings?.labels?.total || 'Total:'}</span>
                        <span class="kdsamref-total-amount">${order.total_formatted || (order.total + (order.currency_symbol || '€'))}</span>
                        ${tipInfo}
                    </div>

                    <div class="kdsamref-action-buttons">
                        ${renderActionButtons(order)}
                    </div>
                </div>
            </div>
        `);

        return $card;
    }

    /**
     * Get status badge information with enhanced workflow support
     */
    function getStatusBadge(status) {
        const statusColors = kdsamrefData.statusColors || {};
        const statusLabels = kdsamrefData.statusLabels || {};
        const customStatuses = kdsamrefData.customStatuses || {};
        
        // Priority 1: Custom statuses from settings (highest priority)
        if (customStatuses[status]) {
            return {
                class: 'custom-status',
                label: customStatuses[status].label || status,
                color: customStatuses[status].color || '#007cba'
            };
        }
        
        // Priority 2: Workflow statuses with WooCommerce labels
        if (statusLabels[status] || statusColors[status]) {
            return {
                class: 'processing',
                label: statusLabels[status] || status,
                color: statusColors[status] || '#007cba'
            };
        }
        
        // Priority 3: Fallback to status slug
        return {
            class: 'processing',
            label: status,
            color: '#007cba'
        };
    }

    /**
     * Render status filter buttons with enhanced workflow support
     */
    function renderStatusFilters() {
        debugLog('🔧 renderStatusFilters called');
        
        const statusLabels = kdsamrefData.statusLabels || {};
        const statusColors = kdsamrefData.statusColors || {};
        const customStatuses = kdsamrefData.customStatuses || {};
        let workflowSteps = kdsamrefData.workflowSteps || ['processing', 'completed'];

        // Normalize workflow steps (remove wc- prefix if present) and align synonyms
        function normalizeStatusSlug(slug) {
            if (!slug) return slug;
            const map = {
                'preparation': 'preparing',
                'ready': 'ready-pickup',
                'pret': 'ready-pickup',
                'pret-pour-livre': 'ready-pickup',
                'pret_pour_livre': 'ready-pickup'
            };
            return map[slug] || slug;
        }
        workflowSteps = workflowSteps
            .map(s => (typeof s === 'string' && s.indexOf('wc-') === 0) ? s.substring(3) : s)
            .map(s => normalizeStatusSlug(s));
        
        // Build filters STRICTLY from workflow only
        const allStatuses = new Set();
        
        // Fallback to default workflow if no workflow is defined
        if (!workflowSteps || workflowSteps.length === 0) {
            workflowSteps = ['processing', 'completed'];
            debugLog('⚠️ No workflow defined, using default: processing → completed');
        }
        
        // Include only workflow steps
        workflowSteps.forEach(step => allStatuses.add(step));
        
        // Sort statuses strictly according to workflow order
        const availableStatuses = Array.from(allStatuses).sort((a, b) => {
            const aIndex = workflowSteps.indexOf(a);
            const bIndex = workflowSteps.indexOf(b);
            
            // If both are in workflow, sort by workflow order
            if (aIndex !== -1 && bIndex !== -1) {
                return aIndex - bIndex;
            }
            
            // If only one is in workflow, prioritize workflow statuses
            if (aIndex !== -1 && bIndex === -1) {
                return -1;
            }
            if (aIndex === -1 && bIndex !== -1) {
                return 1;
            }
            
            // If neither is in workflow, keep as is
            return 0;
        });
        
        debugLog('🔧 Workflow steps:', workflowSteps);
        debugLog('🔧 Available statuses for filters (sorted):', availableStatuses);
        
        const $filtersContainer = $('.kdsamref-status-filters');
        $filtersContainer.empty();
        
        // Calculate statistics using the same logic as updateStatistics
        const stats = {
            all: $('.kdsamref-order-card').length
        };
        
        // Initialize stats for all available statuses
        availableStatuses.forEach(status => {
            stats[status] = 0;
        });
        
        // Count orders by status using DOM elements
        $('.kdsamref-order-card').each(function() {
            const status = $(this).data('status');
            
            if (stats.hasOwnProperty(status)) {
                stats[status]++;
            }
        });
        
        // Add "All" filter first
        $filtersContainer.append(`
            <button class="kdsamref-status-btn active" data-filter="all">
                <div class="kdsamref-status-content">
                    <span class="status-label">${kdsamrefData.strings?.js?.all || 'All'}</span>
                    <span class="status-count" id="count-all">${stats.all}</span>
                </div>
            </button>
        `);
        
        // Add status filters based on sorted available statuses
        availableStatuses.forEach(status => {
            const count = stats[status] || 0;
            let label = status;
            let color = '#007cba';
            
            // Priority 1: Use custom settings label/color if available
            if (customStatuses[status]) {
                label = customStatuses[status].label || status;
                color = customStatuses[status].color || '#007cba';
            } else if (typeof kdsamrefCustomStatuses !== 'undefined' && kdsamrefCustomStatuses[status]) {
                // Priority 2: Custom statuses from kdsamrefCustomStatuses
                label = kdsamrefCustomStatuses[status].label || status;
                color = kdsamrefCustomStatuses[status].color || '#007cba';
            } else {
                // Priority 3: Default labels based on status
                switch (status) {
                    case 'processing':
                        label = 'Processing';
                        color = '#3b82f6';
                        break;
                    case 'cooking':
                        label = 'Cooking';
                        color = '#f59e0b';
                        break;
                    case 'ready-pickup':
                        label = 'Ready';
                        color = '#10b981';
                        break;
                    case 'completed':
                        label = 'Completed';
                        color = '#6b7280';
                        break;
                    case 'cancelled':
                        label = 'Cancelled';
                        color = '#ef4444';
                        break;
                    case 'refunded':
                        label = 'Refunded';
                        color = '#06b6d4';
                        break;
                    case 'failed':
                        label = 'Failed';
                        color = '#dc2626';
                        break;
                    default:
                        color = '#007cba';
                }
            }
            
            // Only show statuses that are in the workflow
            const isInWorkflow = workflowSteps.includes(status);
            const workflowIndicator = isInWorkflow ? ' <span class="workflow-indicator" title="In workflow"></span>' : '';
            
            // Only show the button if it's in workflow
            if (isInWorkflow) {
                $filtersContainer.append(`
                    <button class="kdsamref-status-btn ${isInWorkflow ? 'workflow-status' : ''}" data-filter="${status}" style="--custom-color: ${color};">
                        <div class="kdsamref-status-content">
                            <span class="status-label">${label}${workflowIndicator}</span>
                            <span class="status-count" id="count-${status}">${count}</span>
                        </div>
                    </button>
                `);
            }
        });
        
        // Re-bind click events for the new buttons
        $('.kdsamref-status-btn').off('click').on('click', function() {
            const filter = $(this).data('filter');
            $('.kdsamref-status-btn').removeClass('active');
            $(this).addClass('active');
            currentFilter = filter;
            filterOrders();
        });
        
        // Restore previously selected filter button visually
        if (currentFilter) {
            const $btn = $filtersContainer.find(`.kdsamref-status-btn[data-filter="${currentFilter}"]`);
            if ($btn.length) {
                $('.kdsamref-status-btn').removeClass('active');
                $btn.addClass('active');
            } else {
                // If the current filter doesn't exist in the rendered buttons, fallback to 'all'
                // BUT don't call filterOrders() to prevent automatic switching
                const $allBtn = $filtersContainer.find(`.kdsamref-status-btn[data-filter="all"]`);
                if ($allBtn.length) {
                    $('.kdsamref-status-btn').removeClass('active');
                    $allBtn.addClass('active');
                    currentFilter = 'all';
                    // Don't call filterOrders() here to prevent automatic switching
                }
            }
        }
        
        // Apply custom status colors after rendering (only if needed)
        if (Object.keys(kdsamrefData.statusColors || {}).length > 0 || Object.keys(kdsamrefData.customStatuses || {}).length > 0) {
            applyCustomStatusColors();
        }
    }

    /**
     * Set completed status text for CSS custom property
     */
    function setCompletedStatusText() {
        // Get completed status label from kdsamrefData or use default
        const completedStatusText = kdsamrefData.statusLabels?.completed || 
                                  kdsamrefData.strings?.js?.completed || 
                                  'Completed';
        
        // Set CSS custom property
        document.documentElement.style.setProperty('--completed-status-text', `"${completedStatusText}"`);
    }

    /**
     * Apply custom colors to dashboard - Optimized to prevent style injection loops
     */
    function applyCustomColors() {
        // Remove existing custom color styles to prevent duplication
        $('#kdsamref-custom-colors-style').remove();
        
        const borderColorPrimary = kdsamrefData.settings?.borderColorPrimary || '#dee2e6';
        const borderColorSecondary = kdsamrefData.settings?.borderColorSecondary || '#e9ecef';
        const cardBackgroundColor = kdsamrefData.settings?.cardBackgroundColor || '#ffffff';
        
        // Get delivery type colors from settings
        const deliveryBadgeColor = kdsamrefData.settings?.deliveryBadgeColor || '#4ade80';
        const pickupBadgeColor = kdsamrefData.settings?.pickupBadgeColor || '#a78bfa';
        const dineInBadgeColor = kdsamrefData.settings?.dineInBadgeColor || '#60a5fa';
        
        const styleContent = `
            .kdsamref-order-card {
                background-color: ${cardBackgroundColor} !important;
                border-color: ${borderColorPrimary} !important;
            }
            .kdsamref-status-filters .kdsamref-status-btn {
                border-color: ${borderColorSecondary} !important;
            }
            .kdsamref-order-card .kdsamref-status-badge {
                border-color: ${borderColorPrimary} !important;
            }
            
            /* Delivery type badge colors - High specificity to override CSS */
            .kdsamref-orders-container .kdsamref-order-card .kdsamref-delivery-badge.delivery {
                background: ${deliveryBadgeColor} !important;
                background-color: ${deliveryBadgeColor} !important;
            }
            .kdsamref-orders-container .kdsamref-order-card .kdsamref-delivery-badge.pickup {
                background: ${pickupBadgeColor} !important;
                background-color: ${pickupBadgeColor} !important;
            }
            .kdsamref-orders-container .kdsamref-order-card .kdsamref-delivery-badge.dine-in {
                background: ${dineInBadgeColor} !important;
                background-color: ${dineInBadgeColor} !important;
            }
        `;
        
        // Add single style tag with unique ID
        $('<style>', {
            id: 'kdsamref-custom-colors-style',
            text: styleContent
        }).appendTo('head');
        
        // Update order card borders only
        updateOrderCardBorders();
    }

    /**
     * Apply custom colors only (without calling other functions to prevent loops)
     */
    function applyCustomColorsOnly() {
        // Remove existing custom color styles to prevent duplication
        $('#kdsamref-custom-colors-style').remove();
        
        const borderColorPrimary = kdsamrefData.settings?.borderColorPrimary || '#dee2e6';
        const borderColorSecondary = kdsamrefData.settings?.borderColorSecondary || '#e9ecef';
        const cardBackgroundColor = kdsamrefData.settings?.cardBackgroundColor || '#ffffff';
        
        // Get delivery type colors from settings
        const deliveryBadgeColor = kdsamrefData.settings?.deliveryBadgeColor || '#4ade80';
        const pickupBadgeColor = kdsamrefData.settings?.pickupBadgeColor || '#a78bfa';
        const dineInBadgeColor = kdsamrefData.settings?.dineInBadgeColor || '#60a5fa';
        
        const styleContent = `
            .kdsamref-order-card {
                background-color: ${cardBackgroundColor} !important;
                border-color: ${borderColorPrimary} !important;
            }
            .kdsamref-status-filters .kdsamref-status-btn {
                border-color: ${borderColorSecondary} !important;
            }
            .kdsamref-order-card .kdsamref-status-badge {
                border-color: ${borderColorPrimary} !important;
            }
            
            /* Delivery type badge colors - High specificity to override CSS */
            .kdsamref-orders-container .kdsamref-order-card .kdsamref-delivery-badge.delivery {
                background: ${deliveryBadgeColor} !important;
                background-color: ${deliveryBadgeColor} !important;
            }
            .kdsamref-orders-container .kdsamref-order-card .kdsamref-delivery-badge.pickup {
                background: ${pickupBadgeColor} !important;
                background-color: ${pickupBadgeColor} !important;
            }
            .kdsamref-orders-container .kdsamref-order-card .kdsamref-delivery-badge.dine-in {
                background: ${dineInBadgeColor} !important;
                background-color: ${dineInBadgeColor} !important;
            }
        `;
        
        // Add single style tag with unique ID
        $('<style>', {
            id: 'kdsamref-custom-colors-style',
            text: styleContent
        }).appendTo('head');
        
        // Update order card borders only
        updateOrderCardBorders();
    }
    
    /**
     * Update order card borders based on current status colors
     */
    function updateOrderCardBorders() {
        const statusColors = kdsamrefData.statusColors || {};
        const customStatuses = kdsamrefData.customStatuses || {};
        
        $('.kdsamref-order-card').each(function() {
            const $card = $(this);
            const status = $card.data('status');
            let color = null;
            
            // Check custom statuses first (highest priority)
            if (customStatuses[status] && customStatuses[status].color) {
                color = customStatuses[status].color;
            }
            // Check workflow statuses
            else if (statusColors[status]) {
                color = statusColors[status];
            }
            
            if (color) {
                $card.css('border-color', color);
            }
        });
    }

    /**
     * Render item options/variations
     */
    function renderItemOptions(item) {
        if (!item.meta || item.meta.length === 0) {
            return '';
        }
        
        const options = item.meta
            .filter(meta => {
                const technicalKeys = [
                    '_qty', '_tax_class', '_product_id', '_variation_id',
                    '_wallee_unique_line_item_id', '_wallee_coupon_discount_line_item_discounts',
                    '_wallee_', '_wc_', '_woocommerce_', '_orderable_'
                ];
                
                const isTechnical = technicalKeys.some(techKey => 
                    meta.key === techKey || meta.key.startsWith(techKey)
                );
                
                return !isTechnical && meta.display_value && meta.display_value.trim() !== '';
            })
            .map(meta => `<span class="kdsamref-item-option"><strong>${meta.display_key}:</strong> ${meta.display_value}</span>`)
            .join('');
        
        return options ? `<div class="kdsamref-item-options">${options}</div>` : '';
    }

    /**
     * Render order items with enhanced data
     */
    function renderOrderItems(items, currencySymbol = '€') {
        return items.map(item => `
            <div class="kdsamref-order-item">
                <div class="kdsamref-item-left">
                    <span class="kdsamref-item-qty">x${item.quantity}</span>
                    <div class="kdsamref-item-details">
                        <span class="kdsamref-item-name">${item.name}</span>
                        ${renderItemOptions(item)}
                    </div>
                </div>
                <span class="kdsamref-item-price">${item.price_formatted || (item.price + currencySymbol)}</span>
            </div>
        `).join('');
    }

    /**
     * Render Orderable information
     */
    function renderOrderableInfo(order) {
        const info = [];
        
        if (order.delivery.location) {
            info.push(`<div class="kdsamref-orderable-location">${order.delivery.location}</div>`);
        }
        
        if (order.special_instructions) {
            info.push(`<div class="kdsamref-special-instructions">${order.special_instructions}</div>`);
        }
        
        if (info.length > 0) {
            return `<div class="kdsamref-orderable-info">${info.join('')}</div>`;
        }
        
        return '';
    }

    /**
     * Render scheduled time information
     */
    function renderScheduledInfo(order) {
        if (order.delivery.formatted_schedule) {
            const timeUntil = order.delivery.time_until_scheduled;
            return `<p class="kdsamref-scheduled-time">${order.delivery.formatted_schedule}${timeUntil ? ` (${timeUntil})` : ''}</p>`;
        }
        return '';
    }

    /**
     * Render tip information
     */
    function renderTipInfo(order) {
        if (order.has_tip && order.tip_info) {
            return `<div class="kdsamref-tip-info">${kdsamrefData.strings?.labels?.tip || 'Tip:'}: ${order.tip_info.formatted}</div>`;
        }
        return '';
    }

    /**
     * Render action buttons with dynamic custom status colors and icons
     */
    function renderActionButtons(order) {
        const statusLabels = kdsamrefData.statusLabels || {};
        const customStatuses = kdsamrefData.customStatuses || {};
        const workflowSteps = kdsamrefData.workflowSteps || ['processing', 'completed'];
        // Normalize steps by removing wc- prefix only (respect exact custom slugs like pret-pour-livre)
        const normalizedSteps = workflowSteps.map(s => (typeof s === 'string' && s.indexOf('wc-') === 0) ? s.substring(3) : s);
        
        // Debug logging
        debugLog('🔧 renderActionButtons debug:', {
            order: order,
            statusLabels: statusLabels,
            customStatuses: customStatuses,
            kdsamrefCustomStatuses: typeof kdsamrefCustomStatuses !== 'undefined' ? kdsamrefCustomStatuses : 'undefined',
            kdsamrefData: kdsamrefData,
            workflowSteps: workflowSteps
        });
        
        // Get current and next status in the workflow
        let currentIndex = normalizedSteps.indexOf(order.status);
        if (currentIndex === -1) {
            // If current status not part of workflow, treat as before first step
            currentIndex = -1;
        }
        const nextStatus = normalizedSteps[currentIndex + 1];
        
        debugLog('🔧 Status workflow:', {
            currentStatus: order.status,
            currentIndex: currentIndex,
            nextStatus: nextStatus
        });
        
        // If no next status or completed, show details
        if (!nextStatus || order.status === 'completed') {
            return `<button class="kdsamref-action-btn completed" data-action="details" data-order-id="${order.id}">Détails</button>`;
        }
        
        // Get custom status data for next status
        let nextLabel = nextStatus;
        let nextColor = null;
        let nextIcon = null;
        
        // First check kdsamrefCustomStatuses (primary source)
        if (typeof kdsamrefCustomStatuses !== 'undefined' && nextStatus && kdsamrefCustomStatuses[nextStatus]) {
            const customStatus = kdsamrefCustomStatuses[nextStatus];
            nextLabel = customStatus.label || nextStatus;
            nextColor = customStatus.color;
            nextIcon = customStatus.icon;
            debugLog('🔧 Found custom status in kdsamrefCustomStatuses:', { nextStatus, customStatus });
        } 
        // Then check kdsamrefData.customStatuses (backup source)
        else if (kdsamrefData && kdsamrefData.customStatuses && nextStatus && kdsamrefData.customStatuses[nextStatus]) {
            const customStatus = kdsamrefData.customStatuses[nextStatus];
            nextLabel = customStatus.label || nextStatus;
            nextColor = customStatus.color;
            nextIcon = customStatus.icon;
            debugLog('🔧 Found custom status in kdsamrefData.customStatuses:', { nextStatus, customStatus });
        }
        // Then check customStatuses (legacy source)
        else if (nextStatus && customStatuses && customStatuses[nextStatus]) {
            const customStatus = customStatuses[nextStatus];
            nextLabel = customStatus.label || nextStatus;
            nextColor = customStatus.color;
            nextIcon = customStatus.icon;
            debugLog('🔧 Found custom status in customStatuses:', { nextStatus, data: customStatuses[nextStatus] });
        }
        // Finally check statusLabels (fallback)
        else if (nextStatus && statusLabels && statusLabels[nextStatus]) {
            nextLabel = statusLabels[nextStatus];
            debugLog('🔧 Found in statusLabels:', { nextStatus, label: statusLabels[nextStatus] });
        }
        
        debugLog('🔧 Final button data:', { nextLabel, nextColor, nextIcon });
        
        // Create next status button (colored)
        let nextButtonStyles = '';
        let nextIconHtml = '';
        let unicodeIcon = '';

        if (nextColor) {
            nextButtonStyles = `background: ${nextColor} !important; border-color: ${nextColor} !important; color: #ffffff !important;`;
        }

        // Determine icon (custom or unicode)
        if (nextIcon) {
            // Custom status icon (FontAwesome, Dashicons, WooCommerce)
            let iconFamily = 'fontawesome'; // default
            
            // Try to get icon family from different sources
            if (typeof kdsamrefCustomStatuses !== 'undefined' && kdsamrefCustomStatuses[nextStatus]) {
                iconFamily = kdsamrefCustomStatuses[nextStatus].icon_family || 'fontawesome';
            } else if (kdsamrefData && kdsamrefData.customStatuses && kdsamrefData.customStatuses[nextStatus]) {
                iconFamily = kdsamrefData.customStatuses[nextStatus].icon_family || 'fontawesome';
            } else if (customStatuses && customStatuses[nextStatus]) {
                iconFamily = customStatuses[nextStatus].icon_family || 'fontawesome';
            }
            
            let iconClass = '';
            switch (iconFamily) {
                case 'dashicons':
                    iconClass = `dashicons ${nextIcon}`;
                    break;
                case 'woocommerce':
                    iconClass = `wooicon ${nextIcon}`;
                    break;
                default:
                    iconClass = `fa ${nextIcon}`;
                    break;
            }
                            nextIconHtml = `<i class="${iconClass} kdsamref-next-icon"></i>`;
        } else {
            // Unicode fallback for default statuses
            switch (nextStatus) {
                case 'processing':
                    unicodeIcon = '⏰'; break;
                case 'cooking':
                    unicodeIcon = '🔥'; break;
                case 'ready':
                    unicodeIcon = '✅'; break;
                case 'completed':
                    unicodeIcon = '🏁'; break;
                case 'cancelled':
                    unicodeIcon = '❌'; break;
                case 'refunded':
                    unicodeIcon = '💰'; break;
                case 'failed':
                    unicodeIcon = '💥'; break;
                default:
                    unicodeIcon = '●';
            }
                            nextIconHtml = `<span class="kdsamref-action-icon">${unicodeIcon}</span>`;
        }

        // Create only the next status button
        return `
            <button class="kdsamref-action-btn next-status" data-action="next-status" data-order-id="${order.id}" data-next-status="${nextStatus}" style="${nextButtonStyles}">
                ${nextIconHtml}${nextLabel} <span class="kdsamref-action-arrow">→</span>
            </button>
        `;
    }
    
    /**
     * Adjust color brightness for gradient effect
     */
    function adjustColor(color, amount) {
        const hex = color.replace('#', '');
        const r = Math.max(0, Math.min(255, parseInt(hex.substr(0, 2), 16) + amount));
        const g = Math.max(0, Math.min(255, parseInt(hex.substr(2, 2), 16) + amount));
        const b = Math.max(0, Math.min(255, parseInt(hex.substr(4, 2), 16) + amount));
        return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
    }

    /**
     * Handle order actions with enhanced workflow support
     */
    function handleOrderAction(e) {
        e.preventDefault();
        
        const $btn = $(this);
        const action = $btn.data('action');
        const orderId = $btn.data('order-id');
        const nextStatus = $btn.data('next-status');
        
        if (!orderId || !action) return;

        switch (action) {
            case 'next-status':
                if (nextStatus) {
                    updateOrderStatus(orderId, nextStatus);
                }
                break;
            case 'mark-ready':
                updateOrderStatus(orderId, 'ready-pickup');
                break;
            case 'complete':
                updateOrderStatus(orderId, 'completed');
                break;
            case 'details':
                showOrderDetails(orderId);
                break;
        }
    }

    /**
     * Update order status with enhanced workflow support
     */
    function updateOrderStatus(orderId, newStatus) {
        const $btn = $(`.kdsamref-order-card[data-order-id="${orderId}"] .kdsamref-action-btn`);
        const originalText = $btn.text();
        
        debugLog('🔧 updateOrderStatus called:', { 
            orderId, newStatus, ajaxUrl: kdsamrefData.ajaxUrl, workflowSteps: kdsamrefData.workflowSteps 
        });
        
        $btn.prop('disabled', true).text('⏳ Updating...');

        const data = {
            action: 'kdsamref_update_order_status',
            nonce: kdsamrefData.nonce,
            order_id: orderId,
            new_status: newStatus
        };

        $.post(kdsamrefData.ajaxUrl, data)
            .done(function(response) {
                if (response.success) {
                    const updatedOrder = (response.data && response.data.order) ? response.data.order : null;
                    showSuccessMessage(kdsamrefData.strings?.js?.orderUpdated || 'Order updated!');

                    // Optimistically update UI to avoid one-step lag
                    if (updatedOrder && typeof updatedOrder === 'object') {
                        try {
                            // Update in-memory list
                            const idx = orders.findIndex(o => String(o.id) === String(updatedOrder.id));
                            if (idx !== -1) {
                                orders[idx] = updatedOrder;
                            } else {
                                orders.unshift(updatedOrder);
                            }
                            // Re-render quickly to reflect new state
                            renderOrders();
                        } catch (e) {
                            // Fallback to full reload if anything goes wrong
                            loadOrdersByDate(currentDateFilter);
                        }
                    } else {
                        // No order payload returned: do a full reload
                        loadOrdersByDate(currentDateFilter);
                    }

                    // Background reconcile after a short delay to avoid race conditions
                    setTimeout(() => {
                        loadOrdersByDate(currentDateFilter);
                    }, 400);
                } else {
                    showError(response.data?.message || (kdsamrefData.strings?.js?.updateError || 'Error during update'));
                    $btn.prop('disabled', false).text(originalText);
                }
            })
            .fail(function(xhr, status, error) {
                showError(kdsamrefData.strings?.js?.connectionError || 'Connection error');
                $btn.prop('disabled', false).text(originalText);
            });
    }

    /**
     * Filter orders based on current filters with enhanced workflow support
     */
    function filterOrders() {
        const $cards = $('.kdsamref-order-card');
        let workflowSteps = (kdsamrefData.workflowSteps || []).map(s => (typeof s === 'string' && s.indexOf('wc-') === 0) ? s.substring(3) : s);
        
        // Fallback to default workflow if no workflow is defined
        if (!workflowSteps || workflowSteps.length === 0) {
            workflowSteps = ['processing', 'completed'];
            debugLog('⚠️ No workflow defined in filterOrders, using default: processing → completed');
        }
        
        let visibleAll = 0;

        // Get all available statuses including custom ones
        const allStatuses = new Set();
        $cards.each(function() {
            const status = $(this).data('status');
            if (status) {
                allStatuses.add(status);
            }
        });

        debugLog('🔧 Available statuses for filtering:', Array.from(allStatuses));
        debugLog('🔧 Current filter:', currentFilter);

        $cards.each(function() {
            const $card = $(this);
            const status = $card.data('status');
            const orderNumber = $card.find('.kdsamref-order-number').text();
            const customerName = $card.find('.kdsamref-customer-name').text();

            let showCard = true;

            // Enhanced status filter using all available statuses
            if (currentFilter !== 'all') {
                // Show only if card status is in workflow and matches currentFilter
                if (!workflowSteps.includes(status) || currentFilter !== status) {
                    showCard = false;
                }
            }

            // Search filter
            if (showCard && currentSearchTerm) {
                const searchTerm = currentSearchTerm.toLowerCase();
                if (!orderNumber.toLowerCase().includes(searchTerm) && 
                    !customerName.toLowerCase().includes(searchTerm)) {
                    showCard = false;
                }
            }

            if (showCard) {
                $card.show();
                visibleAll++;
            } else {
                $card.hide();
            }
        });

        // Show/hide no orders message
        if (visibleAll === 0) {
            $('#kdsamref-no-orders').show();
        } else {
            $('#kdsamref-no-orders').hide();
        }

        // Ensure the correct filter button is active
        $('.kdsamref-status-btn').removeClass('active');
        const $activeBtn = $(`.kdsamref-status-btn[data-filter="${currentFilter}"]`);
        if ($activeBtn.length) {
            $activeBtn.addClass('active');
        } else {
            // Fallback to 'all' if current filter doesn't exist
            const $allBtn = $('.kdsamref-status-btn[data-filter="all"]');
            if ($allBtn.length) {
                $allBtn.addClass('active');
                currentFilter = 'all';
            }
        }
        
        // Update statistics after filtering
        updateStatistics();
    }

    /**
     * Update statistics with enhanced workflow support
     */
    function updateStatistics() {
        // Get all available statuses from actual orders
        const allStatuses = new Set();
        $('.kdsamref-order-card').each(function() {
            const status = $(this).data('status');
            if (status) {
                allStatuses.add(status);
            }
        });
        
        const availableStatuses = Array.from(allStatuses);
        
        // Calculate statistics using DOM elements for consistency
        const stats = {
            all: $('.kdsamref-order-card').length
        };

        // Initialize stats for all available statuses
        availableStatuses.forEach(status => {
            stats[status] = 0;
        });

        // Count orders by status using DOM elements
        $('.kdsamref-order-card').each(function() {
            const status = $(this).data('status');
            
            if (stats.hasOwnProperty(status)) {
                stats[status]++;
            }
        });

        // Update display with animation
        $('#count-all').fadeOut(100, function() {
            $(this).text(stats.all || '0').fadeIn(100);
        });
        
        // Get workflow steps with fallback
        let workflowSteps = (kdsamrefData.workflowSteps || []).map(s => (typeof s === 'string' && s.indexOf('wc-') === 0) ? s.substring(3) : s);
        
        // Fallback to default workflow if no workflow is defined
        if (!workflowSteps || workflowSteps.length === 0) {
            workflowSteps = ['processing', 'completed'];
            debugLog('⚠️ No workflow defined in updateStatistics, using default: processing → completed');
        }
        
        // Update counts only for workflow statuses
        availableStatuses.forEach(status => {
            // Only update counts for statuses that are in workflow
            if (workflowSteps.includes(status)) {
                const $countElement = $(`#count-${status}`);
                if ($countElement.length) {
                    $countElement.fadeOut(100, function() {
                        $(this).text(stats[status] || '0').fadeIn(100);
                    });
                }
            }
        });
        
        // Reset counts for workflow statuses that are no longer available
        workflowSteps.forEach(status => {
            const $countElement = $(`#count-${status}`);
            if ($countElement.length) {
                const count = stats[status] || 0;
                $countElement.fadeOut(100, function() {
                    $(this).text(count).fadeIn(100);
                });
            }
        });
        
        debugLog('📊 Statistics updated:', stats);
    }

    /**
     * Start auto-refresh timer with enhanced license checking
     */
    function startAutoRefresh() {
        const hasValidLicense = (kdsamrefData.license && (
            kdsamrefData.license.is_premium || 
            kdsamrefData.license.valid || 
            kdsamrefData.license.realtime_enabled
        )) || kdsamrefData.realTimeEnabled || false;
        
        let interval = 0;
        if (kdsamrefData.settings && kdsamrefData.settings.auto_refresh_interval) {
            interval = parseInt(kdsamrefData.settings.auto_refresh_interval);
        } else if (kdsamrefData.settings && kdsamrefData.settings.autoRefreshInterval) {
            interval = parseInt(kdsamrefData.settings.autoRefreshInterval);
        } else if (kdsamrefData.autoRefresh) {
            interval = parseInt(kdsamrefData.autoRefresh);
        }
        
        if (hasValidLicense && interval > 0) {
            if (autoRefreshTimer) {
                clearInterval(autoRefreshTimer);
            }
            
            if (interval < 5) interval = 5;
            if (interval > 300) interval = 300;
            
            const intervalMs = interval * 1000;
            
    
            
            autoRefreshTimer = setInterval(() => {
                if (!isUserInteracting) {
                    // Prevent notifications during auto-refresh
                    window.preventNotifications = true;
                    window.isAutoRefresh = true;
                    
                    // Add loading to refresh button during auto-refresh
                    $('#kdsamref-refresh-btn').addClass('loading');
                    
                    // Show auto-refresh notification only if not disabled
                    if (!kdsamrefData.settings?.disable_refresh_notifications) {
                        showSuccessMessage('🔄 ' + (kdsamrefData.strings?.js?.autoRefresh || 'Auto-refresh...'));
                    }
                    
                    loadOrdersByDate(currentDateFilter);
                    
                    // Re-enable notifications after auto-refresh
                    setTimeout(() => {
                        window.preventNotifications = false;
                        window.isAutoRefresh = false;
                        // Remove loading class from refresh button after auto-refresh
                        $('#kdsamref-refresh-btn').removeClass('loading');
                    }, 2000);
                }
            }, intervalMs);
            
            // Show auto-refresh started notification only if not disabled
            if (!kdsamrefData.settings?.disable_refresh_notifications) {
                showSuccessMessage(`✅ Auto-refresh activé: ${interval}s`);
            }
            
        } else {
            showAutoRefreshTeaser();
        }
    }

    /**
     * Show auto-refresh premium teaser
     */
    function showAutoRefreshTeaser() { 
        return; 
    }

    /**
     * Utility functions for date/time formatting
     */
    function formatTime(dateString) {
        const date = new Date(dateString);
        return date.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
    }

    function formatDateTime(dateString) {
        const date = new Date(dateString);
        return date.toLocaleString('fr-FR');
    }

    function getTimeAgo(dateString) {
        const now = new Date();
        const orderDate = new Date(dateString);
        
        const diffMs = now - orderDate;
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMs / 3600000);
        const diffDays = Math.floor(diffMs / 86400000);

        if (diffMins < 1) {
            return kdsamrefData.strings?.js?.justNow || 'Just now';
        } else if (diffMins < 60) {
            return `${diffMins} ${kdsamrefData.strings?.js?.minAgo || 'min ago'}`;
        } else if (diffHours < 24) {
            return `${diffHours}${kdsamrefData.strings?.js?.hAgo || 'h ago'}`;
        } else {
            return `${diffDays} ${kdsamrefData.strings?.js?.daysAgo || 'days ago'}`;
        }
    }

    function updateLastUpdateTime() {
        lastUpdateTime = new Date();
    }

    function showLoading() {
        // Don't show loading spinner, use notification instead
        // $('#kdsamref-loading').show();
    }

    function hideLoading() {
        // Don't hide loading spinner, use notification instead
        // $('#kdsamref-loading').hide();
    }
    
    // Overlay loader removed; notifications provide feedback

    function showError(message) {
        alert(message);
    }

    function showSuccessMessage(message) {
        const $notification = $(`
            <div style="
                position: fixed;
                top: 20px;
                right: 20px;
                background: #111827;
                color: #ffffff;
                padding: 16px 24px;
                border-radius: 12px;
                box-shadow: 0 8px 25px rgba(0, 0, 0, 0.25);
                z-index: 9999999;
                font-size: 14px;
                font-weight: 500;
                opacity: 0;
                transform: translateX(100%);
                transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
                border: 1px solid rgba(255, 255, 255, 0.1);
            ">
                ${message}
            </div>
        `);
        
        // Check if dashboard is in fullscreen mode
        const dashboard = $('.kdsamref-dashboard');
        const isFullscreen = dashboard.hasClass('fullscreen-mode');
        
        // Adjust position for fullscreen mode
        if (isFullscreen) {
            $notification.css({
                'position': 'absolute',
                'top': '20px',
                'right': '20px',
                'z-index': '9999999'
            });
            dashboard.append($notification);
        } else {
            $('body').append($notification);
        }
        
        setTimeout(() => {
            $notification.css({ opacity: 1, transform: 'translateX(0)' });
        }, 10);
        
        setTimeout(() => {
            $notification.css({ opacity: 0, transform: 'translateX(100%)' });
            setTimeout(() => $notification.remove(), 400);
        }, 2500);
    }

    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func.apply(this, args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    /**
     * Show order details modal with enhanced data and optimized performance
     */
    function showOrderDetails(orderId) {
        const order = orders.find(o => o.id == orderId);
        
        if (!order) {
            showError(kdsamrefData.strings?.js?.orderNotFound || 'Order not found');
            return;
        }

        // Show modal content directly - let CSS handle fullscreen visibility
        showModalContent(order);
    }
    
    function showModalContent(order) {
        // Pre-generate modal content for better performance
        const modalContent = generateOrderDetailsContent(order);

        // Set modal content immediately
        $('#kdsamref-order-modal .kdsamref-modal-body').html(modalContent);
        
        // Set modal state and add active class
        $('#kdsamref-order-modal').attr('aria-hidden', 'false').addClass('modal-active');
        
        // Disable body scroll
        $('body').addClass('modal-open');
        
        // Show modal with optimized animation (faster)
        $('#kdsamref-order-modal').fadeIn(150, function() {
            // Focus on close button for accessibility
            $('#kdsamref-order-modal .kdsamref-modal-close').focus();
        });
    }

    /**
     * Generate order details content for better performance
     */
    function generateOrderDetailsContent(order) {
        return `
            <div class="order-details">
                <div class="detail-section">
                    <h3>${kdsamrefData.strings?.js?.orderInformation || 'Order Information'}</h3>
                    <p><strong>${kdsamrefData.strings?.js?.number || 'Number'}:</strong> ${order.number}</p>
                    <p><strong>${kdsamrefData.strings?.js?.date || 'Date'}:</strong> ${formatDateTime(order.date_created)}</p>
                    <p><strong>${kdsamrefData.strings?.js?.status || 'Status'}:</strong> ${order.status_name || getStatusBadge(order.status).label}</p>
                    <p><strong>${kdsamrefData.strings?.js?.type || 'Type'}:</strong> ${getDeliveryType(order.delivery.type, order.delivery.orderable_service).label}</p>
                    ${order.delivery.formatted_schedule ? `<p><strong>${kdsamrefData.strings?.js?.scheduled || 'Scheduled'}:</strong> ${order.delivery.formatted_schedule}</p>` : ''}
                </div>

                <div class="detail-section">
                    <h3>${kdsamrefData.strings?.js?.customer || 'Customer'}</h3>
                    <p><strong>${kdsamrefData.strings?.js?.name || 'Name'}:</strong> ${order.customer.name}</p>
                    <p><strong>${kdsamrefData.strings?.js?.phone || 'Phone'}:</strong> ${order.customer.phone || 'N/A'}</p>
                    <p><strong>${kdsamrefData.strings?.js?.email || 'Email'}:</strong> ${order.customer.email || 'N/A'}</p>
                </div>

                ${renderOrderableDetailsSection(order)}

                ${order.delivery.address ? `
                    <div class="detail-section">
                        <h3>${kdsamrefData.strings?.js?.deliveryAddress || 'Delivery Address'}</h3>
                        <p>${order.delivery.address}</p>
                    </div>
                ` : ''}

                <div class="detail-section">
                    <h3>${kdsamrefData.strings?.js?.orderedItems || 'Ordered Items'}</h3>
                    <div class="items-list">
                        ${order.items.map(item => `
                            <div class="item-detail">
                                <div class="item-info">
                                    <span class="item-name">${item.name}</span>
                                    ${renderItemOptions(item)}
                                </div>
                                <span class="item-qty">x${item.quantity}</span>
                                <span class="item-price">${item.price_formatted || (item.price + (order.currency_symbol || '€'))}</span>
                            </div>
                        `).join('')}
                    </div>
                </div>

                <div class="detail-section">
                    <h3>Total: <strong>${order.total_formatted || (order.total + (order.currency_symbol || '€'))}</strong></h3>
                    ${renderTotalBreakdown(order)}
                    ${renderFeesBreakdown(order)}
                </div>

                ${renderPaymentSection(order)}
            </div>
        `;
    }

    /**
     * Render Orderable details section for modal
     */
    function renderOrderableDetailsSection(order) {
        const details = [];
        
        if (order.delivery.location) {
            details.push(`<p><strong>${kdsamrefData.strings?.js?.location || 'Location'}:</strong> ${order.delivery.location}</p>`);
        }
        
        if (order.delivery.table_number) {
            details.push(`<p><strong>${kdsamrefData.strings?.labels?.table || 'Table'}:</strong> ${order.delivery.table_number}</p>`);
        }
        
        if (order.special_instructions) {
            details.push(`<p><strong>${kdsamrefData.strings?.js?.specialInstructions || 'Special Instructions'}:</strong> ${order.special_instructions}</p>`);
        }
        
        if (details.length > 0) {
            return `<div class="detail-section">
                <h3>${kdsamrefData.strings?.js?.orderableDetails || 'Orderable Details'}</h3>
                ${details.join('')}
            </div>`;
        }
        
        return '';
    }

    /**
     * Render total breakdown for modal
     */
    function renderTotalBreakdown(order) {
        if (!order.total_with_breakdown) {
            return '';
        }
        
        const breakdown = order.total_with_breakdown;
        
        return `<div class="total-breakdown">
            <div class="breakdown-item">
                <span>Sous-total:</span>
                <span>${breakdown.subtotal_formatted || (breakdown.subtotal + (order.currency_symbol || '€'))}</span>
            </div>
            <div class="breakdown-item">
                <span>TVA:</span>
                <span>${breakdown.tax_total_formatted || (breakdown.tax_total + (order.currency_symbol || '€'))}</span>
            </div>
            ${breakdown.fees_total > 0 ? `
            <div class="breakdown-item">
                <span>Frais:</span>
                <span>${breakdown.fees_total_formatted || (breakdown.fees_total + (order.currency_symbol || '€'))}</span>
            </div>
            ` : ''}
        </div>`;
    }

    /**
     * Render fees breakdown for modal
     */
    function renderFeesBreakdown(order) {
        if (!order.fees || order.fees.length === 0) {
            return '';
        }
        
        const feesHtml = order.fees.map(fee => 
            `<div class="fee-item">
                <span>${fee.name}</span>
                <span>${fee.formatted}</span>
            </div>`
        ).join('');
        
        return `<div class="fees-breakdown">
            <h4>Frais & Charges:</h4>
            ${feesHtml}
        </div>`;
    }

    /**
     * Render payment information section for modal
     */
    function renderPaymentSection(order) {
        const paymentDetails = [];
        
        // Payment method
        if (order.payment_method_title || order.payment_method) {
            const paymentMethod = order.payment_method_title || order.payment_method || 'N/A';
            paymentDetails.push(`<p><strong>${kdsamrefData.strings?.js?.paymentMethod || 'Payment Method'}:</strong> ${paymentMethod}</p>`);
        }
        
        // Payment status
        if (order.payment_status) {
            const paymentStatus = order.payment_status;
            const statusClass = paymentStatus === 'paid' ? 'payment-paid' : 'payment-pending';
            paymentDetails.push(`<p><strong>${kdsamrefData.strings?.js?.paymentStatus || 'Payment Status'}:</strong> <span class="${statusClass}">${paymentStatus}</span></p>`);
        }
        
        // Transaction ID
        if (order.transaction_id) {
            paymentDetails.push(`<p><strong>${kdsamrefData.strings?.js?.transactionId || 'Transaction ID'}:</strong> ${order.transaction_id}</p>`);
        }
        
        // Payment date
        if (order.payment_date) {
            paymentDetails.push(`<p><strong>${kdsamrefData.strings?.js?.paymentDate || 'Payment Date'}:</strong> ${formatDateTime(order.payment_date)}</p>`);
        }
        
        // Credit card last 4 digits (if available)
        if (order.card_last4) {
            paymentDetails.push(`<p><strong>${kdsamrefData.strings?.js?.cardLast4 || 'Card'}:</strong> **** **** **** ${order.card_last4}</p>`);
        }
        
        // Credit card brand (if available)
        if (order.card_brand) {
            paymentDetails.push(`<p><strong>${kdsamrefData.strings?.js?.cardBrand || 'Card Brand'}:</strong> ${order.card_brand}</p>`);
        }
        
        // Cash amount (for cash payments)
        if (order.cash_amount) {
            paymentDetails.push(`<p><strong>${kdsamrefData.strings?.js?.cashAmount || 'Cash Amount'}:</strong> ${order.cash_amount_formatted || (order.cash_amount + (order.currency_symbol || '€'))}</p>`);
        }
        
        // Change amount (for cash payments)
        if (order.change_amount) {
            paymentDetails.push(`<p><strong>${kdsamrefData.strings?.js?.changeAmount || 'Change'}:</strong> ${order.change_amount_formatted || (order.change_amount + (order.currency_symbol || '€'))}</p>`);
        }
        
        // Staff member who processed payment
        if (order.staff_name) {
            paymentDetails.push(`<p><strong>${kdsamrefData.strings?.js?.staffMember || 'Staff Member'}:</strong> ${order.staff_name}</p>`);
        }
        
        if (paymentDetails.length > 0) {
            return `<div class="detail-section">
                <h3>${kdsamrefData.strings?.js?.paymentInformation || 'Payment Information'}</h3>
                ${paymentDetails.join('')}
            </div>`;
        }
        
        return '';
    }

    /**
     * Close modal with enhanced functionality and optimized performance
     */
    function closeModal() {
        const $modal = $('#kdsamref-order-modal');
        
        // Add closing animation
        $modal.addClass('closing');
        
        // Fade out with optimized timing
        $modal.fadeOut(150, function() {
            // Remove closing class
            $modal.removeClass('closing');
            
            // Clear modal content
            $modal.find('.kdsamref-modal-body').empty();
            
            // Reset modal state and remove active class
            $modal.attr('aria-hidden', 'true').removeClass('modal-active');
            
            // Remove focus trap
            $modal.find('.kdsamref-modal-close').blur();
        });
        
        // Re-enable body scroll immediately
        $('body').removeClass('modal-open');
    }

    /**
     * Initialize date mode switch functionality
     */
    function initializeDateModeSwitch() {
        const switchElement = $('#dateModeSwitch');
        const tomorrowBtn = $('.kdsamref-tomorrow-btn');
        const switchLabels = $('.kdsamref-switch-label');
        
        // Handle switch change
        switchElement.on('change', function() {
            isDeliveryMode = this.checked;
            dateFilterType = isDeliveryMode ? 'delivery' : 'created';
            
            // Prevent notifications during switch change
            window.preventNotifications = true;
            
            // Update UI
            updateDateModeUI();
            
            // Reload current filter
            reloadCurrentFilter();
            
            // Re-enable notifications after a short delay
            setTimeout(() => {
                window.preventNotifications = false;
            }, 1000);
        });
        
        // Update UI based on current mode
        function updateDateModeUI() {
            if (isDeliveryMode) {
                // Show tomorrow button for delivery mode
                tomorrowBtn.addClass('show');
                
                // Update labels
                switchLabels.removeClass('active-mode');
                switchLabels.eq(1).addClass('active-mode'); // "Delivery Date"
            } else {
                // Hide tomorrow button for creation date mode
                tomorrowBtn.removeClass('show');
                
                // Update labels
                switchLabels.removeClass('active-mode');
                switchLabels.eq(0).addClass('active-mode'); // "Order Date"
            }
        }
        
        // Initialize UI
        updateDateModeUI();
    }

    // Cleanup on page unload
    $(window).on('beforeunload', function() {
        if (autoRefreshTimer) {
            clearInterval(autoRefreshTimer);
        }
        if (settingsCheckTimer) {
            clearInterval(settingsCheckTimer);
        }
    });

    // Make debug functions globally accessible
    window.debugDateCalculations = debugDateCalculations;
    window.testDateFiltering = testDateFiltering;
    window.checkOrderableOrders = checkOrderableOrders;
    window.testDateCalculations = testDateCalculations;
    


    /**
     * Reload current filter when date mode changes
     */
    function reloadCurrentFilter() {
        // If tomorrow is selected but we're in creation mode, switch to today
        if (currentDateFilter === 'tomorrow' && !isDeliveryMode) {
            currentDateFilter = 'today';
            $('.kdsamref-date-btn').removeClass('active');
            $('.kdsamref-date-btn[data-date="today"]').addClass('active');
        }
        
        // Reload orders with current filter
        loadOrdersByDate(currentDateFilter);
    }

    /**
     * Calculate tomorrow date as fallback
     */
    function calculateTomorrowDate() {
        const today = new Date();
        const tomorrow = new Date(today);
        tomorrow.setDate(today.getDate() + 1);
        return tomorrow.toISOString().split('T')[0];
    }


    
    // Initialize fullscreen mode
    function initializeFullscreenMode() {
        const fullscreenBtn = document.getElementById('kdsamref-fullscreen-btn');
        if (fullscreenBtn) {
            fullscreenBtn.addEventListener('click', function() {
                const dashboard = document.querySelector('.kdsamref-dashboard');
                const isFullscreen = dashboard.classList.contains('fullscreen-mode');
                
                if (isFullscreen) {
                    // Exit fullscreen
                    exitFullscreen();
                } else {
                    // Enter fullscreen
                    enterFullscreen();
                }
            });
        }
        
        // Handle ESC key to exit fullscreen
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                const dashboard = document.querySelector('.kdsamref-dashboard');
                if (dashboard.classList.contains('fullscreen-mode')) {
                    exitFullscreen();
                }
            }
        });
    }
    
    // Enter fullscreen mode with tablet support
    function enterFullscreen() {
        const dashboard = document.querySelector('.kdsamref-dashboard');
        const fullscreenBtn = document.getElementById('kdsamref-dashboard-fullscreen-btn');
        
        if (!dashboard || !fullscreenBtn) {
            console.error('Dashboard or fullscreen button not found!');
            return;
        }
        
        // Detect tablet/mobile
        const isTablet = /iPad|Android|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
        
        // On tablets/mobile, prefer CSS fullscreen mode
        if (isTablet || isTouchDevice) {
            dashboard.classList.add('fullscreen-mode');
            fullscreenBtn.classList.add('active');
            
            // Update button icon to exit fullscreen
            fullscreenBtn.innerHTML = `
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M8 3v3a2 2 0 0 1-2 2H3"/>
                    <path d="M21 8V5a2 2 0 0 0-2-2h-3"/>
                    <path d="M3 16v3a2 2 0 0 0 2 2h3"/>
                    <path d="M16 21h3a2 2 0 0 0 2-2v-3"/>
                </svg>
            `;
            
            fullscreenBtn.title = kdsamrefData.strings?.js?.exitFullscreen || 'Exit fullscreen';
            showSuccessMessage(kdsamrefData.strings?.js?.fullscreenEnabled || 'Fullscreen mode enabled! 📱');
            localStorage.setItem('kdsamref_fullscreen_mode', 'true');
            return;
        }
        
        // On desktop, try real fullscreen API
        try {
            if (dashboard.requestFullscreen) {
                dashboard.requestFullscreen().catch(() => {
                    // Fallback to CSS fullscreen mode
                    dashboard.classList.add('fullscreen-mode');
                });
            } else if (dashboard.webkitRequestFullscreen) {
                dashboard.webkitRequestFullscreen().catch(() => {
                    dashboard.classList.add('fullscreen-mode');
                });
            } else if (dashboard.msRequestFullscreen) {
                dashboard.msRequestFullscreen().catch(() => {
                    dashboard.classList.add('fullscreen-mode');
                });
            } else if (dashboard.mozRequestFullScreen) {
                dashboard.mozRequestFullScreen().catch(() => {
                    dashboard.classList.add('fullscreen-mode');
                });
            } else {
                // Fallback to CSS fullscreen mode
                dashboard.classList.add('fullscreen-mode');
            }
        } catch (error) {
            console.warn('Fullscreen API failed, using CSS fallback:', error);
            dashboard.classList.add('fullscreen-mode');
        }
        
        fullscreenBtn.classList.add('active');
        
        // Update button icon to exit fullscreen
        fullscreenBtn.innerHTML = `
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M8 3v3a2 2 0 0 1-2 2H3"/>
                <path d="M21 8V5a2 2 0 0 0-2-2h-3"/>
                <path d="M3 16v3a2 2 0 0 0 2 2h3"/>
                <path d="M16 21h3a2 2 0 0 0 2-2v-3"/>
            </svg>
        `;
        
        // Update button title
        fullscreenBtn.title = kdsamrefData.strings?.js?.exitFullscreen || 'Exit fullscreen';
        
        // Show success message
        showSuccessMessage(kdsamrefData.strings?.js?.fullscreenEnabled || 'Fullscreen mode enabled! 🖥️');
        
        // Save fullscreen state
        localStorage.setItem('kdsamref_fullscreen_mode', 'true');
    }
    
    // Exit fullscreen mode
    function exitFullscreen() {
        const dashboard = document.querySelector('.kdsamref-dashboard');
        const fullscreenBtn = document.getElementById('kdsamref-dashboard-fullscreen-btn');
        
        // Check if we're actually in fullscreen mode
        const isFullscreen = document.fullscreenElement || 
                           document.webkitFullscreenElement || 
                           document.mozFullScreenElement || 
                           document.msFullscreenElement;
        
        // Try to exit real fullscreen mode with error handling
        if (isFullscreen) {
            try {
                if (document.exitFullscreen) {
                    document.exitFullscreen().catch(() => {
                        // Fallback to CSS fullscreen mode
                        dashboard.classList.remove('fullscreen-mode');
                    });
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen().catch(() => {
                        dashboard.classList.remove('fullscreen-mode');
                    });
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen().catch(() => {
                        dashboard.classList.remove('fullscreen-mode');
                    });
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen().catch(() => {
                        dashboard.classList.remove('fullscreen-mode');
                    });
                } else {
                    // Fallback to CSS fullscreen mode
                    dashboard.classList.remove('fullscreen-mode');
                }
            } catch (error) {
                console.warn('Fullscreen exit failed, using CSS fallback:', error);
                // Fallback to CSS fullscreen mode
                dashboard.classList.remove('fullscreen-mode');
            }
        } else {
            // Not in fullscreen, just remove CSS class
            dashboard.classList.remove('fullscreen-mode');
        }
        
        fullscreenBtn.classList.remove('active');
        
        // Update button icon to enter fullscreen
        fullscreenBtn.innerHTML = `
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M8 3H5a2 2 0 0 0-2 2v3"/>
                <path d="M21 8V5a2 2 0 0 0-2-2h-3"/>
                <path d="M3 16v3a2 2 0 0 0 2 2h3"/>
                <path d="M16 21h3a2 2 0 0 0 2-2v-3"/>
            </svg>
        `;
        
        // Update button title
        fullscreenBtn.title = kdsamrefData.strings?.js?.fullscreen || 'Fullscreen';
        
        // Show success message
        showSuccessMessage(kdsamrefData.strings?.js?.normalModeRestored || 'Normal mode restored! 📱');
        
        // Save fullscreen state
        localStorage.setItem('kdsamref_fullscreen_mode', 'false');
    }
    
    // Handle fullscreen change events
    function handleFullscreenChange() {
        const dashboard = document.querySelector('.kdsamref-dashboard');
        const fullscreenBtn = document.getElementById('kdsamref-dashboard-fullscreen-btn');
        
        if (!dashboard || !fullscreenBtn) return;
        
        const isFullscreen = document.fullscreenElement || 
                           document.webkitFullscreenElement || 
                           document.mozFullScreenElement || 
                           document.msFullscreenElement;
        
        if (isFullscreen) {
            // User entered fullscreen
            dashboard.classList.add('fullscreen-mode');
            fullscreenBtn.classList.add('active');
            
            // Update button icon
            fullscreenBtn.innerHTML = `
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M8 3v3a2 2 0 0 1-2 2H3"/>
                    <path d="M21 8V5a2 2 0 0 0-2-2h-3"/>
                    <path d="M3 16v3a2 2 0 0 0 2 2h3"/>
                    <path d="M16 21h3a2 2 0 0 0 2-2v-3"/>
                </svg>
            `;
            fullscreenBtn.title = kdsamrefData.strings?.js?.exitFullscreen || 'Exit fullscreen';
        } else {
            // User exited fullscreen
            dashboard.classList.remove('fullscreen-mode');
            fullscreenBtn.classList.remove('active');
            
            // Update button icon
            fullscreenBtn.innerHTML = `
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M8 3H5a2 2 0 0 0-2 2v3"/>
                    <path d="M21 8V5a2 2 0 0 0-2-2h-3"/>
                    <path d="M3 16v3a2 2 0 0 0 2 2h3"/>
                    <path d="M16 21h3a2 2 0 0 0 2-2v-3"/>
                </svg>
            `;
            fullscreenBtn.title = kdsamrefData.strings?.js?.fullscreen || 'Fullscreen';
        }
        
        // Save state
        localStorage.setItem('kdsamref_fullscreen_mode', isFullscreen ? 'true' : 'false');
    }
    

    
    // Restore fullscreen state on page load
    function restoreFullscreenState() {
        const savedFullscreen = localStorage.getItem('kdsamref_fullscreen_mode');
        if (savedFullscreen === 'true') {
            enterFullscreen();
        }
    }
    
    // Initialize header toggle functionality
    function initializeHeaderToggle() {
        const headerToggleBtn = document.getElementById('kdsamref-header-toggle-btn');
        const headerToggleFixed = document.getElementById('kdsamref-header-toggle-fixed');
        
        // Function to handle header toggle
        function toggleHeader() {
            const dashboard = document.querySelector('.kdsamref-dashboard');
            const isHeaderHidden = dashboard.classList.contains('kdsamref-header-hidden');
            
            if (isHeaderHidden) {
                showHeader();
            } else {
                hideHeader();
            }
        }
        
        // Add event listeners to both buttons
        if (headerToggleBtn) {
            headerToggleBtn.addEventListener('click', toggleHeader);
        } else {
            console.warn('Original header toggle button not found');
        }
        
        if (headerToggleFixed) {
            headerToggleFixed.addEventListener('click', toggleHeader);
        } else {
            console.error('Fixed header toggle button not found!');
        }
        
        // Restore header state on page load
        restoreHeaderState();
    }
    
    // Hide header
    function hideHeader() {
        const dashboard = document.querySelector('.kdsamref-dashboard');
        const headerToggleBtn = document.getElementById('kdsamref-header-toggle-btn');
        const headerToggleFixed = document.getElementById('kdsamref-header-toggle-fixed');
        const header = document.querySelector('.kdsamref-header');
        const wpAdminBar = document.getElementById('wpadminbar');
        
        if (!dashboard) {
            return;
        }
        
        dashboard.classList.add('kdsamref-header-hidden');
        
        // Hide WordPress admin bar
        if (wpAdminBar) {
            wpAdminBar.style.display = 'none';
        }
        
        // Update both buttons
        if (headerToggleBtn) {
            headerToggleBtn.classList.add('active');
            headerToggleBtn.title = 'Show header';
        }
        
        if (headerToggleFixed) {
            headerToggleFixed.classList.add('active');
            headerToggleFixed.title = 'Show header';
        }
        
        // Show success message
        showSuccessMessage('Header and admin bar hidden! 📱');
        
        // Save header state
        localStorage.setItem('kdsamref_header_hidden', 'true');
        
        // Trigger resize event to adjust layout
        setTimeout(() => {
            window.dispatchEvent(new Event('resize'));
        }, 300);
    }
    
    // Show header
    function showHeader() {
        const dashboard = document.querySelector('.kdsamref-dashboard');
        const headerToggleBtn = document.getElementById('kdsamref-header-toggle-btn');
        const headerToggleFixed = document.getElementById('kdsamref-header-toggle-fixed');
        const wpAdminBar = document.getElementById('wpadminbar');
        
        if (!dashboard) {
            return;
        }
        
        dashboard.classList.remove('kdsamref-header-hidden');
        
        // Show WordPress admin bar
        if (wpAdminBar) {
            wpAdminBar.style.display = '';
        }
        
        // Update both buttons
        if (headerToggleBtn) {
            headerToggleBtn.classList.remove('active');
            headerToggleBtn.title = 'Hide header';
        }
        
        if (headerToggleFixed) {
            headerToggleFixed.classList.remove('active');
            headerToggleFixed.title = 'Hide header';
        }
        
        // Show success message
        showSuccessMessage('Header and admin bar shown! 📋');
        
        // Save header state
        localStorage.setItem('kdsamref_header_hidden', 'false');
        
        // Trigger resize event to adjust layout
        setTimeout(() => {
            window.dispatchEvent(new Event('resize'));
        }, 300);
    }
    
    // Restore header state on page load
    function restoreHeaderState() {
        const savedHeaderHidden = localStorage.getItem('kdsamref_header_hidden');
        if (savedHeaderHidden === 'true') {
            hideHeader();
        } else {
            // Ensure admin bar is visible when header is shown
            const wpAdminBar = document.getElementById('wpadminbar');
            if (wpAdminBar) {
                wpAdminBar.style.display = '';
            }
            // Ensure header is visible
            const dashboard = document.querySelector('.kdsamref-dashboard');
            if (dashboard) {
                dashboard.classList.remove('kdsamref-header-hidden');
            }
        }
    }
    
    /**
     * Initialize layout mode from localStorage
     */
    function initializeLayoutMode() {
        const savedLayoutMode = localStorage.getItem('kdsamref_layout_mode');
        const $container = $('#kdsamref-orders-container');
        const $btn = $('#kdsamref-masonry-toggle-btn');
        
        if (savedLayoutMode === 'masonry') {
            $container.addClass('masonry-layout');
            $btn.addClass('active');
            // Apply masonry layout if orders are already loaded
            setTimeout(() => {
                if ($container.find('.kdsamref-order-card').length > 0) {
                    applyMasonryLayout();
                }
            }, 100);
        } else {
            $container.removeClass('masonry-layout');
            $btn.removeClass('active');
            // Restore grid layout
            restoreGridLayout();
        }
    }
    
    /**
     * Apply masonry layout to order cards with optimized performance
     */
    function applyMasonryLayout() {
        const $container = $('#kdsamref-orders-container');
        const $cards = $container.find('.kdsamref-order-card');
        
        if ($cards.length === 0) return;
        
        // Prevent layout thrashing by using requestAnimationFrame
        requestAnimationFrame(() => {
            // Temporarily hide container to prevent flickering
            $container.css('opacity', '0');
            
            // Calculate optimal column count based on container width
            const containerWidth = $container.width();
            const cardWidth = 320; // Base card width
            const gap = 16;
            const columnCount = Math.floor((containerWidth + gap) / (cardWidth + gap));
            const actualColumns = Math.max(1, Math.min(columnCount, 4)); // Max 4 columns
            
            // Sort cards by timestamp for consistent layout
            const sortedCards = $cards.toArray().sort((a, b) => {
                const timestampA = $(a).data('timestamp') || '';
                const timestampB = $(b).data('timestamp') || '';
                
                if (timestampA && timestampB) {
                    return new Date(timestampA) - new Date(timestampB);
                }
                
                const orderIdA = parseInt($(a).data('order-id') || '0');
                const orderIdB = parseInt($(b).data('order-id') || '0');
                return orderIdA - orderIdB;
            });
            
            // Create columns array
            const columns = [];
            for (let i = 0; i < actualColumns; i++) {
                columns.push([]);
            }
            
            // Distribute cards using height-based algorithm
            sortedCards.forEach((card) => {
                // Find column with minimum height
                let minHeight = Infinity;
                let targetColumn = 0;
                
                for (let i = 0; i < actualColumns; i++) {
                    const columnHeight = columns[i].reduce((height, c) => {
                        return height + ($(c).outerHeight(true) || 0);
                    }, 0);
                    
                    if (columnHeight < minHeight) {
                        minHeight = columnHeight;
                        targetColumn = i;
                    }
                }
                
                columns[targetColumn].push(card);
            });
            
            // Clear container and apply masonry layout
            $container.empty().css({
                'display': 'flex',
                'gap': '16px',
                'align-items': 'flex-start'
            });
            
            // Create and populate columns
            columns.forEach((columnCards, columnIndex) => {
                if (columnCards.length > 0) {
                    // Get responsive column width based on screen size
                    const screenWidth = window.innerWidth;
                    let minWidth = '320px';
                    let gap = '16px';
                    
                    if (screenWidth <= 480) {
                        minWidth = '100%';
                        gap = '10px';
                    } else if (screenWidth <= 768) {
                        minWidth = '260px';
                        gap = '12px';
                    } else if (screenWidth <= 1024) {
                        minWidth = '260px';
                        gap = '14px';
                    } else if (screenWidth <= 1180) {
                        minWidth = '280px';
                        gap = '12px';
                    }
                    
                    const $column = $('<div class="masonry-column"></div>').css({
                        'flex': '1',
                        'min-width': minWidth,
                        'max-width': `${100 / actualColumns}%`,
                        'display': 'flex',
                        'flex-direction': 'column',
                        'gap': gap,
                        'align-items': 'stretch'
                    });
                    
                    columnCards.forEach(card => {
                        $(card).css('width', '100%');
                        $column.append(card);
                    });
                    
                    $container.append($column);
                }
            });
            
            // Smooth fade in
            setTimeout(() => {
                $container.css({
                    'opacity': '1',
                    'transition': 'opacity 0.2s ease-in-out'
                });
            }, 50);
        });
    }
    
    /**
     * Restore grid layout from masonry with optimized performance
     */
    function restoreGridLayout() {
        const $container = $('#kdsamref-orders-container');
        const $masonryColumns = $container.find('.masonry-column');
        
        if ($masonryColumns.length === 0) return;
        
        // Prevent layout thrashing by using requestAnimationFrame
        requestAnimationFrame(() => {
            // Temporarily hide container to prevent flickering
            $container.css('opacity', '0');
            
            // Collect all cards from masonry columns
            const allCards = [];
            $masonryColumns.each(function() {
                const $cards = $(this).find('.kdsamref-order-card');
                allCards.push(...$cards.toArray());
            });
            
            // Clear container and restore original grid structure
            // Get responsive grid settings based on screen size
            const screenWidth = window.innerWidth;
            let gridColumns = 'repeat(auto-fill, minmax(320px, 1fr))';
            let gap = '16px';
            let padding = '27px';
            
            if (screenWidth <= 480) {
                gridColumns = '1fr';
                gap = '10px';
                padding = '12px';
            } else if (screenWidth <= 768) {
                gridColumns = 'repeat(auto-fill, minmax(260px, 1fr))';
                gap = '12px';
                padding = '16px';
            } else if (screenWidth <= 1024) {
                gridColumns = 'repeat(auto-fill, minmax(260px, 1fr))';
                gap = '14px';
                padding = '20px';
            } else if (screenWidth <= 1180) {
                gridColumns = 'repeat(auto-fill, minmax(280px, 1fr))';
                gap = '12px';
                padding = '18px';
            }
            
            // Remove masonry class and let CSS handle the grid layout
            $container.removeClass('masonry-layout').empty();
            
            // Reset container to default state - CSS will handle responsive grid
            $container.css({
                'display': 'grid',
                'margin': '0',
                'background': '#f8f9fa',
                'max-width': '100%',
                'align-items': 'stretch'
            });
            
            // Add cards back in original order
            allCards.forEach(card => {
                $(card).css('width', 'auto'); // Reset card width
                $container.append(card);
            });
            
            // Smooth fade in to prevent flickering
            setTimeout(() => {
                $container.css({
                    'opacity': '1',
                    'transition': 'opacity 0.2s ease-in-out'
                });
            }, 50);
        });
    }



})(jQuery);
