<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KDS | Live Kitchen Display</title>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
    <style>
        .no-scrollbar::-webkit-scrollbar { display: none; }
        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
        [x-cloak] { display: none !important; }
    </style>
</head>
<body class="bg-zinc-950 font-sans antialiased text-zinc-100 overflow-hidden" x-data="kdsApp()" x-init="init()">
    
    <!-- Session Expired Overlay -->
    <div x-cloak x-show="isLoggedOut" class="fixed inset-0 z-[200] bg-zinc-950 flex flex-col items-center justify-center p-8 text-center">
        <div class="w-20 h-20 bg-rose-500/20 text-rose-500 rounded-full flex items-center justify-center mb-6 animate-pulse">
            <svg class="w-10 h-10" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m0 0v2m0-2h2m-2 0H10m4-11a4 4 0 11-8 0 4 4 0 018 0zm-4 7v3"></path></svg>
        </div>
        <h2 class="text-2xl font-black uppercase tracking-[0.2em] mb-2">Session Expired</h2>
        <p class="text-zinc-500 text-sm mb-8 max-w-xs">The kitchen has been idle too long or you were logged out. Please log back in to resume orders.</p>
        <a href="{{ route('kitchen.login') }}" class="px-12 py-4 bg-white text-zinc-950 font-black uppercase tracking-widest rounded-sm hover:bg-emerald-500 transition-colors">
            Log In Again
        </a>
    </div>

    <div class="h-screen flex flex-col" :class="isLoggedOut ? 'blur-lg pointer-events-none' : ''">
        <!-- Top Bar -->
        <header class="h-16 bg-zinc-900 border-b border-zinc-800 flex items-center justify-between px-8 flex-shrink-0">
            <div class="flex items-center space-x-6">
                <div class="flex items-center space-x-3">
                    <div class="w-8 h-8 bg-emerald-600 rounded-sm flex items-center justify-center font-black text-white text-lg">K</div>
                    <h1 class="text-xs font-black uppercase tracking-widest text-zinc-400">Kitchen Display System</h1>
                </div>
                <div class="h-4 w-px bg-zinc-800"></div>
                <div class="flex items-center space-x-2">
                    <div class="w-2 h-2 rounded-full animate-pulse" :class="isOffline ? 'bg-rose-500' : 'bg-emerald-500'"></div>
                    <span class="text-[10px] font-black uppercase tracking-widest" :class="isOffline ? 'text-rose-500' : 'text-zinc-500'" x-text="isOffline ? 'OFFLINE - CHECKING...' : lastUpdate"></span>
                </div>
            </div>

            <div class="flex items-center space-x-6">
                <div class="text-right">
                    <p class="text-[10px] font-black text-zinc-400 uppercase tracking-widest" x-text="activeKots.length + ' Active Tickets'"></p>
                    <p class="text-[9px] text-zinc-600 font-bold uppercase tracking-tight">{{ auth()->user()->name }}</p>
                </div>
                <form action="{{ route('kitchen.logout') }}" method="POST">
                    @csrf
                    <button type="submit" class="p-2 text-zinc-500 hover:text-white transition-colors">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path></svg>
                    </button>
                </form>
            </div>
        </header>

        <!-- Main Workspace -->
        <main class="flex-1 flex overflow-hidden bg-zinc-950">
            <!-- Consolidated Prep View (Sidebar) -->
            <div class="w-72 bg-zinc-900 border-r border-zinc-800 flex flex-col flex-shrink-0" x-show="showPrepView" x-transition:enter="transition ease-out duration-300" x-transition:enter-start="-translate-x-full" x-transition:enter-end="translate-x-0">
                <div class="p-4 border-b border-zinc-800 flex justify-between items-center bg-zinc-900/50">
                    <h2 class="text-[10px] font-black uppercase tracking-[0.2em] text-emerald-500">Consolidated Prep</h2>
                    <span class="px-2 py-0.5 bg-zinc-800 rounded-full text-[8px] font-black text-zinc-500" x-text="consolidatedItems.length"></span>
                </div>
                <div class="flex-1 overflow-y-auto no-scrollbar p-4 space-y-2">
                    <template x-for="item in consolidatedItems" :key="item.name">
                        <div class="p-3 bg-zinc-800/50 border border-zinc-700/50 rounded-sm flex justify-between items-center group hover:bg-zinc-800 transition-colors">
                            <div class="flex-1 pr-4">
                                <p class="text-[10px] font-black uppercase tracking-tight text-zinc-100" x-text="item.name || 'Unknown Item'"></p>
                                <p class="text-[8px] font-bold text-zinc-500 uppercase mt-0.5" x-text="item.variant || 'Standard'"></p>
                            </div>
                            <div class="flex items-center space-x-3">
                                <span class="text-lg font-black text-emerald-500" x-text="item.total"></span>
                            </div>
                        </div>
                    </template>
                    <template x-if="consolidatedItems.length === 0">
                        <div class="h-full flex flex-col items-center justify-center opacity-20 py-20">
                            <svg class="w-12 h-12 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg>
                            <p class="text-[10px] font-black uppercase tracking-widest">Nothing to Prep</p>
                        </div>
                    </template>
                </div>
            </div>

            <!-- Tickets Grid -->
            <div class="flex-1 overflow-x-auto no-scrollbar p-6">
                <div class="flex items-start space-x-6 h-full pb-4">
                <template x-for="kot in activeKots" :key="kot.id">
                    <div class="w-80 flex-shrink-0 flex flex-col bg-zinc-900 border border-zinc-800 rounded-sm shadow-2xl h-full overflow-hidden">
                        <!-- Ticket Header -->
                        <div class="p-4 border-b border-zinc-800 flex justify-between items-start" :class="getKotBg(kot)">
                            <div>
                                <div class="flex items-center space-x-2 mb-1">
                                    <span class="text-lg font-black text-white" x-text="kot.order.table ? kot.order.table.name : 'Direct'"></span>
                                    <span class="text-[10px] font-black text-zinc-400 uppercase tracking-widest" x-text="'#' + kot.id"></span>
                                </div>
                                <p class="text-[9px] font-bold text-zinc-500 uppercase tracking-widest" x-text="kot.waiter ? kot.waiter.name : 'System'"></p>
                            </div>
                            <div class="text-right">
                                <p class="text-xs font-black text-white" x-text="getTimeElapsed(kot.created_at)"></p>
                                <p class="text-[9px] font-bold text-zinc-500 uppercase tracking-widest">Elapsed</p>
                            </div>
                        </div>

                        <!-- Items List -->
                        <div class="flex-1 overflow-y-auto no-scrollbar p-4 space-y-3">
                            <template x-for="item in kot.items" :key="item.id">
                                <div @click="toggleStatus(item)" 
                                    class="p-3 rounded-sm border cursor-pointer transition-all relative overflow-hidden group"
                                    :class="getItemClasses(item)">
                                    <div class="flex justify-between items-start relative z-10">
                                        <div class="flex-1 pr-4">
                                            <div class="flex items-center space-x-2">
                                                <span class="text-sm font-black uppercase tracking-tight" x-text="item.quantity + 'x'"></span>
                                                <span class="text-sm font-black uppercase tracking-tight leading-tight" x-text="item.item ? item.item.name : item.order_item.name"></span>
                                            </div>
                                            <template x-if="item.order_item.variant">
                                                <p class="text-[9px] font-black uppercase tracking-widest mt-1 opacity-60" x-text="item.order_item.variant.name"></p>
                                            </template>
                                            <template x-if="item.notes">
                                                <div class="mt-2 flex items-center space-x-1 bg-amber-500/10 px-2 py-1 rounded-xs border border-amber-500/20">
                                                    <svg class="w-3 h-3 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
                                                    <span class="text-[9px] font-black text-amber-500 uppercase tracking-wider" x-text="item.notes"></span>
                                                </div>
                                            </template>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="w-4 h-4 rounded-full border-2 flex items-center justify-center" :class="getStatusBorder(item.status)">
                                                <template x-if="item.status === 'ready' || item.status === 'served'">
                                                    <svg class="w-2.5 h-2.5" fill="currentColor" viewBox="0 0 20 20"><path d="M0 11l2-2 5 5L18 3l2 2L7 18z"/></svg>
                                                </template>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Progress Indicator -->
                                    <div class="absolute bottom-0 left-0 h-1 bg-white/20 transition-all duration-1000" :style="'width: ' + getProgressWidth(item.status) + '%'"></div>
                                </div>
                            </template>
                        </div>

                        <!-- Ticket Actions -->
                        <div class="p-4 bg-zinc-900/50 border-t border-zinc-800">
                            <button @click="bumpKot(kot)" 
                                class="w-full py-3 bg-zinc-800 hover:bg-zinc-700 text-zinc-400 hover:text-white text-[10px] font-black uppercase tracking-[0.2em] rounded-sm transition-all border border-zinc-700">
                                Clear Ticket
                            </button>
                        </div>
                    </div>
                </template>

                <!-- Empty State -->
                <div x-show="activeKots.length === 0" class="flex-1 flex flex-col items-center justify-center text-zinc-800">
                    <svg class="w-24 h-24 mb-6 opacity-10" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path></svg>
                    <p class="text-xl font-black uppercase tracking-[0.3em] opacity-10">Kitchen Quiet</p>
                </div>
            </div>
        </main>
    </div>

    <script>
        function kdsApp() {
            return {
                activeKots: [],
                lastUpdate: 'Connecting...',
                pollingInterval: null,
                showPrepView: true,
                isLoggedOut: false,
                isOffline: false,
                failCount: 0,

                init() {
                    this.fetchKots();
                    this.pollingInterval = setInterval(() => this.fetchKots(), 15000); // Poll every 15 seconds
                    
                    // Interaction tracker to prevent silent sleep
                    window.addEventListener('mousedown', () => this.isOffline = false);
                    window.addEventListener('touchstart', () => this.isOffline = false);
                    
                    // Clock for elapsed time
                    setInterval(() => {
                        this.$nextTick(); // Force update for elapsed times
                    }, 10000);
                },

                get consolidatedItems() {
                    const items = {};
                    this.activeKots.forEach(kot => {
                        kot.items.forEach(item => {
                            if (item.status === 'pending' || item.status === 'preparing') {
                                const itemName = (item.item ? item.item.name : (item.order_item ? item.order_item.name : 'Unknown'));
                                const variantName = (item.order_item && item.order_item.variant) ? item.order_item.variant.name : '';
                                const key = itemName + (variantName ? '|' + variantName : '');
                                
                                if (!items[key]) {
                                    items[key] = {
                                        name: itemName,
                                        variant: variantName,
                                        total: 0
                                    };
                                }
                                items[key].total += item.quantity;
                            }
                        });
                    });
                    return Object.values(items).sort((a, b) => b.total - a.total);
                },

                async fetchKots() {
                    try {
                        const res = await fetch('{{ route("kitchen.api.kots.active") }}');
                        
                        if (res.status === 401 || res.status === 419) {
                            this.isLoggedOut = true;
                            clearInterval(this.pollingInterval);
                            return;
                        }

                        if (!res.ok) throw new Error('Server Error');

                        this.activeKots = await res.json();
                        this.lastUpdate = 'Synced ' + new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                        this.isOffline = false;
                        this.failCount = 0;
                    } catch (e) {
                        this.failCount++;
                        if (this.failCount > 2) {
                            this.isOffline = true;
                        }
                        console.error('KDS Fetch Error:', e);
                    }
                },

                getKotBg(kot) {
                    const elapsed = (new Date() - new Date(kot.created_at)) / 1000 / 60;
                    if (elapsed > 20) return 'bg-rose-950/40 border-rose-900/50';
                    if (elapsed > 10) return 'bg-amber-950/30 border-amber-900/50';
                    return 'bg-zinc-800/50 border-zinc-700';
                },

                getItemClasses(item) {
                    if (item.status === 'ready' || item.status === 'served') {
                        return 'bg-emerald-950/40 border-emerald-500/30 text-emerald-500 opacity-60';
                    }
                    if (item.status === 'preparing') {
                        return 'bg-amber-950/40 border-amber-500/30 text-amber-500';
                    }
                    return 'bg-zinc-800 border-zinc-700 text-zinc-300';
                },

                getStatusBorder(status) {
                    if (status === 'ready' || status === 'served') return 'border-emerald-500 bg-emerald-500 text-zinc-950';
                    if (status === 'preparing') return 'border-amber-500';
                    return 'border-zinc-700';
                },

                getProgressWidth(status) {
                    if (status === 'ready' || status === 'served') return 100;
                    if (status === 'preparing') return 50;
                    return 5;
                },

                getTimeElapsed(createdAt) {
                    const diff = Math.floor((new Date() - new Date(createdAt)) / 1000);
                    const mins = Math.floor(diff / 60);
                    const secs = diff % 60;
                    return `${mins}:${secs.toString().padStart(2, '0')}`;
                },

                async toggleStatus(item) {
                    let nextStatus = 'pending';
                    if (item.status === 'pending') nextStatus = 'preparing';
                    else if (item.status === 'preparing') nextStatus = 'ready';
                    else nextStatus = 'pending'; // Toggle back or logic as needed

                    try {
                        const res = await fetch(`{{ url('kitchen/api/kots') }}/${item.id}/status`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({ status: nextStatus })
                        });
                        
                        if (res.ok) {
                            item.status = nextStatus; // Optimistic update
                            this.fetchKots(); // Refresh fully to catch KOT readiness
                        }
                    } catch (e) {
                        console.error('Status Update Failed:', e);
                    }
                },

                async bumpKot(kot) {
                    if(!confirm('Mark this entire ticket as served and clear screen?')) return;
                    
                    try {
                        const res = await fetch(`{{ url('kitchen/api/kots/ticket') }}/${kot.id}/status`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({ status: 'completed' })
                        });
                        
                        if (res.ok) {
                            this.fetchKots(); // Refresh to remove the ticket
                        }
                    } catch (e) {
                        console.error('Ticket Bump Failed:', e);
                    }
                }
            }
        }
    </script>
</body>
</html>
