const { createApp, ref, computed, onMounted, onUnmounted, watch } = Vue;

// Order Card Component
const OrderCard = {
    props: {
        transaction: {
            type: Object,
            required: true
        },
        itemWidth: {
            type: Number,
            default: 150
        },
        cardHeight: {
            type: Number,
            default: 600
        },
        fontSize: {
            type: Number,
            default: 100
        },
        lineSpacing: {
            type: Number,
            default: 100
        },
        stackHeight: {
            type: Number,
            default: 85
        }
    },
    emits: ['start-all', 'done-all', 'toggle-item-status'],
    setup(props, { emit }) {
        const isStarted = ref(false);
        const isDone = ref(false);
        const columns = ref([]);
        
        // Check if all items are in cooking status
        const allItemsCooking = computed(() => {
            return props.transaction.items.every(item => item.status === 'cooking');
        });
        
        // Check if all items are done
        const allItemsDone = computed(() => {
            return props.transaction.items.every(item => item.status === 'done');
        });
        
        // Calculate card width based on number of columns
        const cardWidth = computed(() => {
            const columnCount = columns.value.length;
            const gap = 10; // gap between columns
            const padding = 30; // card padding
            return (columnCount * props.itemWidth) + ((columnCount - 1) * gap) + padding;
        });
        
        // Function to calculate item height based on settings
        const calculateItemHeight = (item) => {
            // Base heights adjusted by font size and line spacing
            const baseHeight = 60 * (props.fontSize / 100);
            const headerHeight = 24 * (props.fontSize / 100);
            const contentLineHeight = 20 * (props.fontSize / 100) * (props.lineSpacing / 100);
            const statusHeight = 20 * (props.fontSize / 100) * (props.lineSpacing / 100);
            const padding = 20; // Total padding (10px top + 10px bottom)
            
            let contentLines = 0;
            
            // Count topping lines
            if (item.toppings && item.toppings.length > 0) {
                contentLines += item.toppings.length;
            }
            
            // Count note line
            if (item.note) {
                contentLines += 1;
            }
            
            // Calculate total height
            const totalHeight = baseHeight + (contentLines * contentLineHeight) + padding;
            
            return totalHeight;
        };
        
        // Function to distribute items into columns based on stack height setting
        const distributeItemsIntoColumns = () => {
            const newColumns = [];
            let currentColumn = [];
            let currentHeight = 0;
            
            // Calculate max column height based on stack height setting
            const maxColumnHeight = (props.cardHeight - 100) * (props.stackHeight / 100);
            const safetyBuffer = 10; // Buffer to prevent overflow
            
            props.transaction.items.forEach(item => {
                const itemHeight = calculateItemHeight(item);
                
                // If adding this item would exceed the column height (with buffer), create a new column
                if (currentHeight + itemHeight + safetyBuffer > maxColumnHeight && currentColumn.length > 0) {
                    newColumns.push([...currentColumn]);
                    currentColumn = [];
                    currentHeight = 0;
                }
                
                currentColumn.push(item);
                currentHeight += itemHeight + 10; // Add gap between items
            });
            
            // Add the last column if it has items
            if (currentColumn.length > 0) {
                newColumns.push([...currentColumn]);
            }
            
            columns.value = newColumns;
        };
        
        const handleStartAll = () => {
            if (isStarted.value) {
                // Pause all
                emit('start-all', props.transaction.transactionId, 'pause');
            } else {
                // Start all
                emit('start-all', props.transaction.transactionId, 'start');
            }
        };
        
        const handleDoneAll = () => {
            if (isDone.value) {
                // Reset all
                emit('done-all', props.transaction.transactionId, 'reset');
            } else {
                // Done all
                emit('done-all', props.transaction.transactionId, 'done');
            }
        };
        
        const handleItemClick = (itemId) => {
            emit('toggle-item-status', itemId);
        };
        
        // Update button states based on item statuses
        watch(() => props.transaction.items, (newItems) => {
            isStarted.value = allItemsCooking.value;
            isDone.value = allItemsDone.value;
            distributeItemsIntoColumns();
        }, { deep: true });
        
        // Watch for changes in display settings
        watch([() => props.fontSize, () => props.lineSpacing, () => props.stackHeight], () => {
            distributeItemsIntoColumns();
        });
        
        // Initial distribution
        distributeItemsIntoColumns();
        
        return {
            isStarted,
            isDone,
            columns,
            cardWidth,
            allItemsCooking,
            allItemsDone,
            handleStartAll,
            handleDoneAll,
            handleItemClick
        };
    },
    template: `
        <div 
            class="order-card"
            :style="{ width: cardWidth + 'px' }"
        >
            <div class="order-card-header">
                <div class="order-card-info">
                    <div class="order-card-table">Meja {{ transaction.tableId }}</div>
                    <div class="order-card-details">
                        <div class="order-card-time">{{ formatTime(transaction.orderTime) }}</div>
                        <div class="order-card-waiter">{{ transaction.waiter }}</div>
                        <div class="order-card-timer">
                            <i class="bi bi-clock"></i>
                            <span>{{ formatElapsedTime(transaction.elapsedTime) }}</span>
                        </div>
                    </div>
                </div>
                <div class="order-card-id">{{ transaction.transactionId }}</div>
            </div>
            
            <div class="order-card-items">
                <div class="order-items-columns">
                    <div 
                        v-for="(column, columnIndex) in columns" 
                        :key="columnIndex"
                        class="order-column"
                    >
                        <div 
                            v-for="item in column" 
                            :key="item.id"
                            class="order-item"
                            :class="item.status"
                            @click="handleItemClick(item.id)"
                        >
                            <div class="item-header">
                                <div class="item-name">{{ item.itemName }}</div>
                                <div class="item-quantity">{{ item.quantity }}x</div>
                            </div>
                            
                            <div class="item-details">
                                <div v-if="item.toppings.length > 0" class="item-toppings">
                                    <div v-for="topping in item.toppings" :key="topping.id" class="topping-item">
                                        <i class="bi bi-plus-circle"></i>
                                        <span>{{ topping.itemName }}</span>
                                        <span class="topping-quantity" v-if="topping.quantity > 1">({{ topping.quantity }}x)</span>
                                    </div>
                                </div>
                                <div v-if="item.note" class="item-note">
                                    <i class="bi bi-chat-quote"></i>
                                    <span>{{ item.note }}</span>
                                </div>
                            </div>
                            
                            <div class="item-status">
                                <div class="status-dot" :class="item.status"></div>
                                <span class="status-text">{{ getStatusText(item.status) }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="order-card-footer">
                <button 
                    class="order-card-btn start"
                    :class="{ active: isStarted }"
                    @click="handleStartAll"
                >
                    <i :class="isStarted ? 'bi bi-pause-fill' : 'bi bi-play-fill'"></i>
                    {{ isStarted ? 'Pause' : 'Start' }}
                </button>
                <button 
                    class="order-card-btn done"
                    :class="{ active: isDone }"
                    @click="handleDoneAll"
                >
                    <i :class="isDone ? 'bi bi-arrow-clockwise' : 'bi bi-check-lg'"></i>
                    {{ isDone ? 'Reset' : 'Done' }}
                </button>
            </div>
        </div>
    `,
    methods: {
        formatTime(timeString) {
            const date = new Date(timeString);
            return date.toLocaleTimeString('id-ID', { 
                hour: '2-digit', 
                minute: '2-digit' 
            });
        },
        getStatusText(status) {
            switch(status) {
                case 'new': return 'Baru';
                case 'cooking': return 'Masak';
                case 'done': return 'Selesai';
                default: return status;
            }
        },
        formatElapsedTime(milliseconds) {
            if (!milliseconds) return '00:00';
            
            const totalSeconds = Math.floor(milliseconds / 1000);
            const hours = Math.floor(totalSeconds / 3600);
            const minutes = Math.floor((totalSeconds % 3600) / 60);
            const seconds = totalSeconds % 60;
            
            if (hours > 0) {
                return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            }
            
            return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }
    }
};

// Main App
createApp({
    components: {
        OrderCard
    },
    setup() {
        // State
        const menuActive = ref(false);
        const showTableSelector = ref(false);
        const selectedTable = ref('');
        const currentKdsId = ref(5);
        const orders = ref([]);
        const autoRefresh = ref(true);
        const refreshInterval = ref(3);
        const soundEnabled = ref(true);
        const notifications = ref([]);
        const globalFilter = ref('all');
        const refreshTimer = ref(null);
        const ordersContainer = ref(null);
        const cardHeight = ref(600); // Default card height
        const beepSound = ref(null);
        const beep2Sound = ref(null);
        const showReport = ref(false);
        
        // Display settings - default values according to the image
        const itemWidthSetting = ref(180);    // Default: 180px
        const fontSizeSetting = ref(120);     // Default: 120%
        const lineSpacingSetting = ref(120);  // Default: 120%
        const stackHeightSetting = ref(80);   // Default: 80%
        
        // Action history for undo/redo
        const actionHistory = ref([]);
        const currentActionIndex = ref(-1);
        const canUndo = computed(() => currentActionIndex.value >= 0);
        const canRedo = computed(() => currentActionIndex.value < actionHistory.value.length - 1);
        
        // Available tables
        const availableTables = ref([
            '17f', '17a', '19', '22', 'sofa 15', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'
        ]);
        
        // Status options
        const statusOptions = ref([
            { value: 'all', label: 'Semua' },
            { value: 'new', label: 'Baru' },
            { value: 'cooking', label: 'Masak' },
            { value: 'done', label: 'Selesai' }
        ]);
        
        // Timers for transactions
        const timers = ref({});
        
        // Function to play beep sound
        const playBeepSound = () => {
            if (beepSound.value && soundEnabled.value) {
                beepSound.value.currentTime = 0;
                beepSound.value.play().catch(e => console.log('Error playing beep sound:', e));
            }
        };
        
        // Function to play beep2 sound
        const playBeep2Sound = () => {
            if (beep2Sound.value && soundEnabled.value) {
                beep2Sound.value.currentTime = 0;
                beep2Sound.value.play().catch(e => console.log('Error playing beep2 sound:', e));
            }
        };
        
        // Function to open report
        const openReport = () => {
            showReport.value = true;
        };
        
        // Function to close report
        const closeReport = () => {
            showReport.value = false;
        };
        
        // Function to update CSS variables
        const updateCSSVariables = () => {
            document.documentElement.style.setProperty('--item-width', `${itemWidthSetting.value}px`);
            document.documentElement.style.setProperty('--font-size', `${fontSizeSetting.value}%`);
            document.documentElement.style.setProperty('--line-spacing', `${lineSpacingSetting.value}%`);
            document.documentElement.style.setProperty('--stack-height', `${stackHeightSetting.value}%`);
            
            // Terapkan font size ke seluruh elemen yang relevan
            const orderItems = document.querySelectorAll('.order-item');
            orderItems.forEach(item => {
                item.style.fontSize = `${fontSizeSetting.value}%`;
            });
            
            const itemNames = document.querySelectorAll('.item-name');
            itemNames.forEach(name => {
                name.style.fontSize = `${fontSizeSetting.value}%`;
            });
            
            const itemDetails = document.querySelectorAll('.item-details');
            itemDetails.forEach(detail => {
                detail.style.fontSize = `${fontSizeSetting.value}%`;
            });
            
            const itemQuantities = document.querySelectorAll('.item-quantity');
            itemQuantities.forEach(quantity => {
                quantity.style.fontSize = `${fontSizeSetting.value}%`;
            });
            
            const toppingItems = document.querySelectorAll('.topping-item');
            toppingItems.forEach(topping => {
                topping.style.fontSize = `${fontSizeSetting.value}%`;
            });
            
            const toppingQuantities = document.querySelectorAll('.topping-quantity');
            toppingQuantities.forEach(quantity => {
                quantity.style.fontSize = `${fontSizeSetting.value}%`;
            });
            
            const itemNotes = document.querySelectorAll('.item-note');
            itemNotes.forEach(note => {
                note.style.fontSize = `${fontSizeSetting.value}%`;
            });
            
            const itemStatuses = document.querySelectorAll('.item-status');
            itemStatuses.forEach(status => {
                status.style.fontSize = `${fontSizeSetting.value}%`;
            });
        };
        
        // Function to save settings to localStorage
        const saveSettingsToLocalStorage = () => {
            const settings = {
                itemWidth: itemWidthSetting.value,
                fontSize: fontSizeSetting.value,
                lineSpacing: lineSpacingSetting.value,
                stackHeight: stackHeightSetting.value
            };
            localStorage.setItem('kdsDisplaySettings', JSON.stringify(settings));
        };
        
        // Function to load settings from localStorage
        const loadSettingsFromLocalStorage = () => {
            const savedSettings = localStorage.getItem('kdsDisplaySettings');
            if (savedSettings) {
                try {
                    const settings = JSON.parse(savedSettings);
                    itemWidthSetting.value = settings.itemWidth || 180;
                    fontSizeSetting.value = settings.fontSize || 120;
                    lineSpacingSetting.value = settings.lineSpacing || 120;
                    stackHeightSetting.value = settings.stackHeight || 80;
                } catch (e) {
                    console.error('Error parsing settings from localStorage:', e);
                    // Use defaults if parsing fails
                }
            }
        };
        
        // Function to reset display settings
        const resetDisplaySettings = () => {
            itemWidthSetting.value = 180;   // Default: 180px
            fontSizeSetting.value = 120;    // Default: 120%
            lineSpacingSetting.value = 120; // Default: 120%
            stackHeightSetting.value = 80;  // Default: 80%
            
            // CSS variables will be updated by watchers
            addNotification('info', 'Pengaturan tampilan direset ke default');
        };
        
        // Function to add action to history
        const addActionToHistory = (action) => {
            // Remove any actions after current index (for when we undo and then make a new action)
            actionHistory.value = actionHistory.value.slice(0, currentActionIndex.value + 1);
            
            // Add new action
            actionHistory.value.push(action);
            currentActionIndex.value++;
            
            // Limit history size to prevent memory issues
            if (actionHistory.value.length > 20) {
                actionHistory.value.shift();
                currentActionIndex.value--;
            }
        };
        
        // Function to undo last action
        const undoLastAction = async () => {
            if (!canUndo.value) return;
            
            const action = actionHistory.value[currentActionIndex.value];
            
            try {
                // Create opposite action
                const oppositeAction = {
                    type: action.type,
                    orderIds: action.orderIds,
                    oldStatus: action.newStatus,
                    newStatus: action.oldStatus,
                    timestamp: new Date()
                };
                
                // Update in database
                const formData = new FormData();
                formData.append('action', 'update_kds_status');
                formData.append('ids', JSON.stringify(action.orderIds));
                formData.append('status', action.oldStatus);
                
                const response = await fetch('crud.php', {
                    method: 'POST',
                    body: formData
                });
                
                const responseData = await response.text();
                
                if (responseData === "1") {
                    // Update local data
                    action.orderIds.forEach(id => {
                        const order = orders.value.find(o => o.id === id);
                        if (order) {
                            order.status = action.oldStatus;
                        }
                    });
                    
                    // Move to previous action
                    currentActionIndex.value--;
                    
                    // Add notification
                    addNotification('info', `Aksi dibatalkan: ${action.orderIds.length} item dikembalikan ke status ${getStatusText(action.oldStatus)}`);
                } else {
                    addNotification('error', 'Gagal membatalkan aksi');
                }
            } catch (error) {
                console.error('Error:', error);
                addNotification('error', 'Kesalahan koneksi');
            }
        };
        
        // Function to redo last action
        const redoLastAction = async () => {
            if (!canRedo.value) return;
            
            // Move to next action
            currentActionIndex.value++;
            const action = actionHistory.value[currentActionIndex.value];
            
            try {
                // Update in database
                const formData = new FormData();
                formData.append('action', 'update_kds_status');
                formData.append('ids', JSON.stringify(action.orderIds));
                formData.append('status', action.newStatus);
                
                const response = await fetch('crud.php', {
                    method: 'POST',
                    body: formData
                });
                
                const responseData = await response.text();
                
                if (responseData === "1") {
                    // Update local data
                    action.orderIds.forEach(id => {
                        const order = orders.value.find(o => o.id === id);
                        if (order) {
                            order.status = action.newStatus;
                        }
                    });
                    
                    // Add notification
                    addNotification('info', `Aksi diulang: ${action.orderIds.length} item diubah ke status ${getStatusText(action.newStatus)}`);
                } else {
                    addNotification('error', 'Gagal mengulang aksi');
                }
            } catch (error) {
                console.error('Error:', error);
                addNotification('error', 'Kesalahan koneksi');
            }
        };
        
        // Function to calculate elapsed time
        const calculateElapsedTime = (startTime) => {
            if (!startTime) return 0;
            
            const start = new Date(startTime);
            const now = new Date();
            const elapsed = now - start;
            
            return elapsed;
        };
        
        // Function to format elapsed time
        const formatElapsedTime = (milliseconds) => {
            if (!milliseconds) return '00:00';
            
            const totalSeconds = Math.floor(milliseconds / 1000);
            const hours = Math.floor(totalSeconds / 3600);
            const minutes = Math.floor((totalSeconds % 3600) / 60);
            const seconds = totalSeconds % 60;
            
            if (hours > 0) {
                return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            }
            
            return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        };
        
        // Function to start timer for a transaction
        const startTransactionTimer = (transactionId) => {
            // Clear existing timer if any
            if (timers.value[transactionId]) {
                clearInterval(timers.value[transactionId]);
            }
            
            // Find the transaction
            const transaction = groupedTransactions.value.find(t => t.transactionId === transactionId);
            if (!transaction) return;
            
            // Check if all items are done
            const allDone = transaction.items.every(item => item.status === 'done');
            if (allDone) return; // Don't start timer if all items are done
            
            // Start new timer
            timers.value[transactionId] = setInterval(() => {
                // Update elapsed time
                transaction.elapsedTime = calculateElapsedTime(transaction.orderTime);
            }, 1000);
        };
        
        // Function to stop timer for a transaction
        const stopTransactionTimer = (transactionId) => {
            if (timers.value[transactionId]) {
                clearInterval(timers.value[transactionId]);
                delete timers.value[transactionId];
            }
        };
        
        // Function to update timers for all active transactions
        const updateAllTimers = () => {
            // Clear all existing timers
            Object.keys(timers.value).forEach(transactionId => {
                clearInterval(timers.value[transactionId]);
            });
            timers.value = {};
            
            // Start timers for active transactions
            groupedTransactions.value.forEach(transaction => {
                startTransactionTimer(transaction.transactionId);
            });
        };
        
        // Function to save status and timestamp to database
        const updateItemStatusWithTimestamp = async (itemId, newStatus) => {
    const item = orders.value.find(order => order.id === itemId);
    if (!item) return false;
    
    try {
        const formData = new FormData();
        formData.append('action', 'update_kds_status');
        formData.append('ids', JSON.stringify([itemId]));
        formData.append('status', newStatus);
        
        const now = new Date().toISOString();
        if (newStatus === 'cooking') {
            formData.append('order_proses', now); // Update order_proses saat mulai masak
        } else if (newStatus === 'done') {
            formData.append('order_finish', now); // Update order_finish saat selesai
        }
        
        const response = await fetch('crud.php', {
            method: 'POST',
            body: formData
        });
        
        const responseData = await response.text();
        
        if (responseData === "1") {
            item.status = newStatus;
            
            // Update timestamps di state
            if (newStatus === 'cooking') {
                item.order_proses = now;
            } else if (newStatus === 'done') {
                item.order_finish = now;
            }
            
            return true;
        }
        
        return false;
    } catch (error) {
        console.error('Error:', error);
        return false;
    }
};
        
        // Computed properties
        const filteredOrders = computed(() => {
            let result = [...orders.value];
            
            // Apply global filter
            if (globalFilter.value !== 'all') {
                result = result.filter(order => order.status === globalFilter.value);
            }
            
            // Apply table filter
            if (selectedTable.value) {
                result = result.filter(order => order.table_id === selectedTable.value);
            }
            
            return result;
        });
        
        const groupedTransactions = computed(() => {
    const transactions = {};
    
    filteredOrders.value.forEach(order => {
        if (!transactions[order.transaction_id]) {
            transactions[order.transaction_id] = {
                transactionId: order.transaction_id,
                tableId: order.table_id,
                waiter: order.waiter,
                orderTime: order.order_time,
                elapsedTime: calculateElapsedTime(order.order_time),
                items: []
            };
        }
        
        if (order.item_type === 'main' && !order.parent_uid) {
            const item = {
                id: order.id,
                itemName: order.item_name,
                quantity: order.quantity,
                note: order.note,
                status: order.status,
                orderTime: order.order_time,
                orderProses: order.order_proses, // Ambil dari database
                orderFinish: order.order_finish, // Ambil dari database
                toppings: []
            };
            
            // ... kode untuk topping tetap sama ...
            
            transactions[order.transaction_id].items.push(item);
        }
    });
    
    return Object.values(transactions).filter(t => t.items.length > 0);
});
        
        // Sort transactions by order time (newest first)
const sortedTransactions = computed(() => {
    return [...groupedTransactions.value].sort((a, b) => {
        // Urutkan berdasarkan waktu order (terlama di kiri, terbaru di kanan)
        return new Date(a.orderTime) - new Date(b.orderTime);
    });
});
        
        const newOrdersCount = computed(() => {
            return orders.value.filter(order => order.status === 'new').length;
        });
        
        const cookingOrdersCount = computed(() => {
            return orders.value.filter(order => order.status === 'cooking').length;
        });
        
        const doneOrdersCount = computed(() => {
            return orders.value.filter(order => order.status === 'done').length;
        });
        
        // Methods
        const toggleMenu = () => {
            menuActive.value = !menuActive.value;
        };
        
        const selectTable = (table) => {
            selectedTable.value = table;
            showTableSelector.value = false;
            addNotification('info', `Filter meja: ${table}`);
        };
        
        const clearTableFilter = () => {
            selectedTable.value = '';
            addNotification('info', 'Filter meja dihapus');
        };
        
        const setGlobalFilter = (status) => {
            globalFilter.value = status;
        };
        
        const getStatusCount = (status) => {
            if (status === 'all') {
                return orders.value.length;
            }
            return orders.value.filter(order => order.status === status).length;
        };
        
        const getStatusText = (status) => {
            switch(status) {
                case 'new': return 'Baru';
                case 'cooking': return 'Masak';
                case 'done': return 'Selesai';
                default: return status;
            }
        };
        
        const toggleItemStatus = async (itemId) => {
            const item = orders.value.find(order => order.id === itemId);
            if (!item) return;
            
            let newStatus;
            if (item.status === 'new') {
                newStatus = 'cooking';
            } else if (item.status === 'cooking') {
                newStatus = 'done';
            } else {
                newStatus = 'new';
            }
            
            // Play beep sound when changing status
            playBeepSound();
            
            // Save action to history before making changes
            const action = {
                type: 'toggle',
                orderIds: [itemId],
                oldStatus: item.status,
                newStatus: newStatus,
                timestamp: new Date()
            };
            
            // Update status with timestamp
            const success = await updateItemStatusWithTimestamp(itemId, newStatus);
            
            if (success) {
                // Add action to history
                addActionToHistory(action);
                
                // Add notification
                addNotification('success', `Status item diperbarui menjadi ${getStatusText(newStatus)}`);
                
                // Check if all items in transaction are done
                checkTransactionCompletion(item.transaction_id);
            } else {
                addNotification('error', 'Gagal memperbarui status item');
            }
        };
        
        const handleStartAll = async (transactionId, action) => {
    const transactionOrders = orders.value.filter(order => 
        order.transaction_id === transactionId && order.item_type === 'main' && !order.parent_uid
    );
    
    const orderIds = transactionOrders.map(order => order.id);
    
    let newStatus;
    if (action === 'start') {
        newStatus = 'cooking';
    } else {
        newStatus = 'new';
    }
    
    const historyAction = {
        type: 'start-all',
        orderIds: orderIds,
        oldStatus: action === 'start' ? 'new' : 'cooking',
        newStatus: newStatus,
        timestamp: new Date()
    };
    
    const formData = new FormData();
    formData.append('action', 'update_kds_status');
    formData.append('ids', JSON.stringify(orderIds));
    formData.append('status', newStatus);
    
    const now = new Date().toISOString();
    if (newStatus === 'cooking') {
        formData.append('order_proses', now); // Update order_proses saat mulai masak
    }
    
    try {
        const response = await fetch('crud.php', {
            method: 'POST',
            body: formData
        });
        
        const responseData = await response.text();
        
        if (responseData === "1") {
            orderIds.forEach(id => {
                const order = orders.value.find(o => o.id === id);
                if (order) {
                    order.status = newStatus;
                    if (newStatus === 'cooking') {
                        order.order_proses = now; // Update di state
                    }
                }
            });
            
            addActionToHistory(historyAction);
            addNotification('success', `Semua item di transaksi ${transactionId} ${action === 'start' ? 'dimulai' : 'dijeda'}`);
        } else {
            addNotification('error', `Gagal ${action === 'start' ? 'memulai' : 'menjeda'} semua item`);
        }
    } catch (error) {
        console.error('Error:', error);
        addNotification('error', 'Kesalahan koneksi');
    }
};
        
        const handleDoneAll = async (transactionId, action) => {
    const transactionOrders = orders.value.filter(order => 
        order.transaction_id === transactionId && order.item_type === 'main' && !order.parent_uid
    );
    
    const orderIds = transactionOrders.map(order => order.id);
    
    let newStatus;
    if (action === 'done') {
        newStatus = 'done';
    } else {
        newStatus = 'new';
    }
    
    const historyAction = {
        type: 'done-all',
        orderIds: orderIds,
        oldStatus: action === 'done' ? 'cooking' : 'done',
        newStatus: newStatus,
        timestamp: new Date()
    };
    
    const formData = new FormData();
    formData.append('action', 'update_kds_status');
    formData.append('ids', JSON.stringify(orderIds));
    formData.append('status', newStatus);
    
    const now = new Date().toISOString();
    if (newStatus === 'done') {
        formData.append('order_finish', now); // Update order_finish saat selesai
    }
    
    try {
        const response = await fetch('crud.php', {
            method: 'POST',
            body: formData
        });
        
        const responseData = await response.text();
        
        if (responseData === "1") {
            orderIds.forEach(id => {
                const order = orders.value.find(o => o.id === id);
                if (order) {
                    order.status = newStatus;
                    if (newStatus === 'done') {
                        order.order_finish = now; // Update di state
                    }
                }
            });
            
            addActionToHistory(historyAction);
            addNotification('success', `Semua item di transaksi ${transactionId} ${action === 'done' ? 'selesai' : 'direset'}`);
            
            if (action === 'done') {
                checkTransactionCompletion(transactionId);
            }
        } else {
            addNotification('error', `Gagal ${action === 'done' ? 'menyelesaikan' : 'mereset'} semua item`);
        }
    } catch (error) {
        console.error('Error:', error);
        addNotification('error', 'Kesalahan koneksi');
    }
};
        
        const checkTransactionCompletion = (transactionId) => {
            const transactionOrders = orders.value.filter(order => 
                order.transaction_id === transactionId && order.item_type === 'main' && !order.parent_uid
            );
            
            // Check if all items are done
            const allDone = transactionOrders.every(order => order.status === 'done');
            
            if (allDone) {
                // Stop timer for this transaction
                stopTransactionTimer(transactionId);
                
                // Mark transaction as cleared (not delete physically) - faster removal
                setTimeout(() => {
                    const orderIds = transactionOrders.map(order => order.id);
                    
                    const formData = new FormData();
                    formData.append('action', 'update_kds_status');
                    formData.append('ids', JSON.stringify(orderIds));
                    formData.append('status', 'cleared');
                    
                    fetch('crud.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.text())
                    .then(responseData => {
                        if (responseData === "1") {
                            // Update local data
                            orderIds.forEach(id => {
                                const order = orders.value.find(o => o.id === id);
                                if (order) {
                                    order.status = 'cleared';
                                }
                            });
                            
                            addNotification('success', `Transaksi ${transactionId} selesai dan dihapus dari layar`);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
                }, 1000); // Reduced from 3000ms to 1000ms for faster removal
            }
        };
        
        const clearCompletedOrders = () => {
            const doneOrderIds = orders.value
                .filter(order => order.status === 'done')
                .map(order => order.id);
            
            if (doneOrderIds.length === 0) {
                addNotification('warning', 'Tidak ada pesanan selesai yang bisa dihapus');
                return;
            }
            
            const formData = new FormData();
            formData.append('action', 'update_kds_status');
            formData.append('ids', JSON.stringify(doneOrderIds));
            formData.append('status', 'cleared');
            
            fetch('crud.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(responseData => {
                if (responseData === "1") {
                    // Update local data
                    doneOrderIds.forEach(id => {
                        const order = orders.value.find(o => o.id === id);
                        if (order) {
                            order.status = 'cleared';
                        }
                    });
                    
                    addNotification('success', `${doneOrderIds.length} pesanan selesai dihapus`);
                } else {
                    addNotification('error', 'Gagal menghapus pesanan selesai');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                addNotification('error', 'Kesalahan koneksi');
            });
        };
        
        const addNotification = (type, message) => {
            notifications.value.push({
                type,
                message,
                id: Date.now()
            });
            
            // Auto remove after 3 seconds
            setTimeout(() => {
                removeNotification(notifications.value.findIndex(n => n.id === Date.now()));
            }, 3000);
        };
        
        const removeNotification = (index) => {
            notifications.value.splice(index, 1);
        };
        
        const getNotificationIcon = (type) => {
            switch(type) {
                case 'success': return 'bi bi-check-circle-fill';
                case 'warning': return 'bi bi-exclamation-triangle-fill';
                case 'error': return 'bi bi-x-circle-fill';
                case 'info': return 'bi bi-info-circle-fill';
                default: return 'bi bi-bell-fill';
            }
        };
        
        const loadOrders = async () => {
            try {
                const sql = `SELECT * FROM kds_orders WHERE kds_id = ${currentKdsId.value} AND status != 'cleared' ORDER BY order_time DESC`;
                const data = await ambil_select('kds_orders', sql);
                const newOrders = JSON.parse(data);
                
                // Check for new orders
                const oldOrderIds = orders.value.map(o => o.id);
                const newOrderIds = newOrders.map(o => o.id);
                const trulyNewOrders = newOrders.filter(o => !oldOrderIds.includes(o.id) && o.status === 'new');
                
                if (trulyNewOrders.length > 0 && soundEnabled.value) {
                    playBeep2Sound();
                    addNotification('info', `${trulyNewOrders.length} pesanan baru masuk`);
                }
                
                orders.value = newOrders;
            } catch (error) {
                console.error('Error loading orders:', error);
                addNotification('error', 'Gagal memuat pesanan');
            }
        };
        
        const startAutoRefresh = () => {
            if (refreshTimer.value) {
                clearInterval(refreshTimer.value);
            }
            
            if (autoRefresh.value) {
                refreshTimer.value = setInterval(() => {
                    loadOrders();
                }, refreshInterval.value * 1000);
            }
        };
        
        // Watchers for display settings - update to save to localStorage
        watch(itemWidthSetting, (newValue) => {
            updateCSSVariables();
            saveSettingsToLocalStorage();
        });
        
        watch(fontSizeSetting, (newValue) => {
            updateCSSVariables();
            saveSettingsToLocalStorage();
        });
        
        watch(lineSpacingSetting, (newValue) => {
            updateCSSVariables();
            saveSettingsToLocalStorage();
        });
        
        watch(stackHeightSetting, (newValue) => {
            updateCSSVariables();
            saveSettingsToLocalStorage();
        });
        
        // Watch for changes in grouped transactions
        watch(groupedTransactions, (newTransactions, oldTransactions) => {
            // Update timers
            updateAllTimers();
        }, { deep: true });
        
        // Other watchers
        watch(autoRefresh, () => {
            startAutoRefresh();
        });
        
        watch(refreshInterval, () => {
            startAutoRefresh();
        });
        
        watch(currentKdsId, () => {
            loadOrders();
        });
        
        // Lifecycle hooks
        onMounted(async () => {
            try {
                // Load settings from localStorage first
                loadSettingsFromLocalStorage();
                
                // Calculate card height based on viewport
                const statusIndicatorsHeight = 50;
                const containerPadding = 30;
                cardHeight.value = window.innerHeight - statusIndicatorsHeight - containerPadding;
                
                // Initialize CSS variables
                updateCSSVariables();
                
                // Initialize audio elements
                beepSound.value = document.querySelector('#app audio[ref="beepSound"]');
                beep2Sound.value = document.querySelector('#app audio[ref="beep2Sound"]');
                
                await loadOrders();
                startAutoRefresh();
                
                // Focus on container for keyboard shortcuts
                if (ordersContainer.value) {
                    ordersContainer.value.focus();
                }
                
                // Update card height on window resize
                window.addEventListener('resize', () => {
                    const statusIndicatorsHeight = 50;
                    const containerPadding = 30;
                    cardHeight.value = window.innerHeight - statusIndicatorsHeight - containerPadding;
                });
            } catch (error) {
                console.error('Error during mount:', error);
                addNotification('error', 'Gagal menginisialisasi aplikasi');
            }
        });
        
        onUnmounted(() => {
            if (refreshTimer.value) {
                clearInterval(refreshTimer.value);
            }
            
            // Clear all timers
            Object.keys(timers.value).forEach(transactionId => {
                clearInterval(timers.value[transactionId]);
            });
        });
        
        // Return all reactive data and methods
        return {
            // State
            menuActive,
            showTableSelector,
            selectedTable,
            currentKdsId,
            orders,
            autoRefresh,
            refreshInterval,
            soundEnabled,
            notifications,
            globalFilter,
            ordersContainer,
            cardHeight,
            beepSound,
            beep2Sound,
            showReport,
            
            // Display settings
            itemWidthSetting,
            fontSizeSetting,
            lineSpacingSetting,
            stackHeightSetting,
            
            // Action history
            actionHistory,
            currentActionIndex,
            canUndo,
            canRedo,
            
            // Constants
            availableTables,
            statusOptions,
            
            // Computed
            filteredOrders,
            groupedTransactions,
            sortedTransactions,
            newOrdersCount,
            cookingOrdersCount,
            doneOrdersCount,
            
            // Methods
            toggleMenu,
            selectTable,
            clearTableFilter,
            setGlobalFilter,
            getStatusCount,
            getStatusText,
            toggleItemStatus,
            handleStartAll,
            handleDoneAll,
            clearCompletedOrders,
            addNotification,
            removeNotification,
            getNotificationIcon,
            resetDisplaySettings,
            undoLastAction,
            redoLastAction,
            formatElapsedTime,
            openReport,
            closeReport
        };
    }
}).mount('#app');



