@extends('layouts.waiter')

@section('content')
<div class="flex-1 flex flex-col overflow-hidden" x-data="waiterApp()" x-init="init()">
    <!-- Top Header -->
    <header class="h-14 bg-zinc-900 flex items-center justify-between px-4 flex-shrink-0 shadow-lg">
        <div class="flex items-center space-x-3">
            <div class="w-7 h-7 bg-indigo-600 rounded-sm flex items-center justify-center text-white font-black text-xs">W</div>
            <h1 class="text-[10px] font-black uppercase tracking-widest text-zinc-400" x-text="getPageTitle()"></h1>
        </div>
        <div class="flex items-center space-x-4">
            <button @click="fetchTables()" class="p-2 text-zinc-500">
                <svg class="w-4 h-4" :class="isSyncing ? 'animate-spin text-indigo-400' : ''" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>
            </button>
            <form action="{{ route('waiter.logout') }}" method="POST">
                @csrf
                <button type="submit" class="p-2 text-zinc-500">
                    <svg class="w-4 h-4" 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 Content -->
    <main class="flex-1 overflow-y-auto no-scrollbar pb-24">
        <!-- view: TABLES -->
        <template x-if="view === 'tables'">
            <div class="p-4 grid grid-cols-2 gap-4">
                <template x-for="table in tables" :key="table.id">
                    <div @click="selectTable(table)" 
                        class="aspect-square rounded-sm border-2 flex flex-col items-center justify-center p-4 transition-all relative overflow-hidden group active:scale-95 shadow-sm"
                        :class="getTableClasses(table)">
                        <span class="text-2xl font-black mb-1" x-text="table.name"></span>
                        <div class="flex flex-col items-center">
                            <span class="text-[9px] font-black uppercase tracking-widest opacity-60" x-text="table.status"></span>
                            <template x-if="table.active_order_id">
                                <span class="text-[8px] font-black text-indigo-500 mt-1" x-text="'#' + table.active_order_id"></span>
                            </template>
                        </div>
                        
                        <!-- Notification for Ready Items -->
                        <template x-if="table.has_ready_items">
                            <div class="absolute top-2 right-2 flex items-center space-x-1">
                                <div class="w-2 h-2 rounded-full bg-amber-500 animate-ping"></div>
                                <span class="text-[8px] font-black text-amber-500 uppercase">Ready</span>
                            </div>
                        </template>
                    </div>
                </template>
            </div>
        </template>

        <!-- view: TABLE_DETAILS (Active Order) -->
        <template x-if="view === 'order_details'">
            <div class="flex flex-col h-full bg-zinc-50 overflow-hidden">
                <div class="p-4 bg-white border-b border-zinc-100 flex justify-between items-center">
                    <div>
                        <h2 class="text-xs font-black uppercase tracking-widest text-zinc-900" x-text="'Table ' + selectedTable?.name"></h2>
                        <p class="text-[9px] font-bold text-indigo-500 uppercase mt-1" x-text="'Active Order #' + activeOrder?.id"></p>
                    </div>
                    <button @click="view = 'menu'" class="px-4 py-2 bg-indigo-600 text-white text-[9px] font-black uppercase tracking-widest rounded-sm shadow-lg shadow-indigo-900/20">
                        Add Items
                    </button>
                </div>

                <div class="flex-1 overflow-y-auto p-4 space-y-3 pb-32">
                    <template x-for="item in activeOrder?.items" :key="item.id">
                        <div class="bg-white p-4 rounded-sm border border-zinc-100 shadow-xs">
                            <div class="flex justify-between items-start">
                                <div>
                                    <h5 class="text-[11px] font-black text-zinc-900 uppercase" x-text="item.name"></h5>
                                    <template x-if="item.notes">
                                        <p class="text-[8px] font-bold text-indigo-500 uppercase mt-0.5" x-text="'Note: ' + item.notes"></p>
                                    </template>
                                    <div class="flex items-center space-x-2 mt-1">
                                        <span class="text-[9px] font-bold text-zinc-400" x-text="'Qty: ' + item.quantity"></span>
                                        <span class="w-1 h-1 rounded-full bg-zinc-200"></span>
                                        <span class="text-[9px] font-bold text-zinc-400" x-text="'₹' + parseFloat(item.price).toFixed(2)"></span>
                                    </div>
                                </div>
                                <div class="flex flex-col items-end space-y-1">
                                    <!-- Ready status with Serve Action -->
                                    <template x-if="item.kot_items.some(k => k.status === 'ready')">
                                        <button @click="serveOrderItem(item.id)" 
                                            class="px-4 py-2 bg-emerald-600 text-white text-[8px] font-black uppercase tracking-widest rounded-sm shadow-md shadow-emerald-900/20 active:scale-95 transition-all">
                                            Mark Served
                                        </button>
                                    </template>
                                    
                                    <div class="flex flex-wrap justify-end gap-1">
                                        <template x-for="kot in item.kot_items">
                                            <span class="px-2 py-0.5 rounded-xs text-[7px] font-black uppercase tracking-tighter"
                                                :class="{
                                                    'bg-zinc-100 text-zinc-500': kot.status === 'pending',
                                                    'bg-amber-100 text-amber-600': kot.status === 'ready',
                                                    'bg-emerald-100 text-emerald-600 border border-emerald-200': kot.status === 'served'
                                                }" x-text="kot.status"></span>
                                        </template>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </template>
        <template x-if="view === 'menu'">
            <div class="flex flex-col h-full overflow-hidden">
                <!-- Fixed Header for Menu -->
                <div class="bg-white border-b border-zinc-100 flex-shrink-0 shadow-sm">
                    <!-- Search Bar -->
                    <div class="px-4 py-3">
                        <div class="relative">
                            <input type="text" x-model="search" placeholder="Search menu..." 
                                class="w-full bg-zinc-100 border-none rounded-full py-2.5 px-10 text-[11px] font-bold text-zinc-900 focus:ring-2 focus:ring-indigo-500/20 transition-all placeholder-zinc-400">
                            <svg class="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-zinc-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                            <template x-if="search">
                                <button @click="search = ''" class="absolute right-4 top-1/2 -translate-y-1/2 text-zinc-400 hover:text-zinc-600">
                                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M6 18L18 6M6 6l12 12"></path></svg>
                                </button>
                            </template>
                        </div>
                    </div>
                    
                    <div class="px-4 pb-3 flex space-x-2">
                        <button @click="fetchDeals(); showDealsView = true" 
                            class="flex-1 py-2 bg-amber-500 text-white text-[9px] font-black uppercase tracking-widest rounded-full shadow-md shadow-amber-900/20 active:scale-95 transition-all">
                            🔥 Today's Deals
                        </button>
                    </div>

                    <!-- Categories Bar -->
                    <div class="flex overflow-x-auto no-scrollbar p-3 pt-0 space-x-3">
                        <button @click="selectedCategory = null; showDealsView = false; fetchItems()" 
                            :class="!selectedCategory && !showDealsView ? 'bg-indigo-600 text-white ring-2 ring-indigo-200 shadow-lg' : 'bg-zinc-100 text-zinc-600 border border-zinc-200'"
                            class="px-5 py-2 rounded-full text-[9px] font-black uppercase whitespace-nowrap transition-all flex-shrink-0">All Items</button>
                        <template x-for="cat in categories" :key="cat.id">
                            <button @click="selectedCategory = cat.id; showDealsView = false; fetchItems()" 
                                :class="selectedCategory === cat.id ? 'bg-indigo-600 text-white ring-2 ring-indigo-200 shadow-lg' : 'bg-zinc-100 text-zinc-600 border border-zinc-200'"
                                class="px-5 py-2 rounded-full text-[9px] font-black uppercase whitespace-nowrap transition-all flex-shrink-0" x-text="cat.name"></button>
                        </template>
                    </div>
                </div>

                <!-- Items/Deals Area -->
                <div class="flex-1 overflow-y-auto no-scrollbar p-4 pb-32">
                    <!-- Deals Grid -->
                    <template x-if="showDealsView">
                        <div class="grid grid-cols-2 gap-4">
                            <template x-for="deal in deals" :key="deal.id">
                                <div @click="startDealSelection(deal)" class="bg-white p-3 rounded-sm border border-zinc-100 shadow-xs active:scale-95 transition-all relative overflow-hidden">
                                    <div class="absolute top-0 right-0 px-2 py-1 bg-amber-500 text-white text-[7px] font-black uppercase rounded-bl-sm">Deal</div>
                                    <h4 class="text-[10px] font-black uppercase tracking-tight text-zinc-900 leading-tight mb-1" x-text="deal.name"></h4>
                                    <p class="text-[10px] font-black text-amber-600" x-text="'₹' + parseFloat(deal.price).toFixed(2)"></p>
                                </div>
                            </template>
                        </div>
                    </template>

                    <!-- Normal Items Grid -->
                    <template x-if="!showDealsView">
                        <div class="grid grid-cols-2 gap-4">
                            <template x-for="item in filteredItems" :key="item.id">
                                <div class="bg-white p-3 rounded-sm border border-zinc-100 flex flex-col space-y-3 shadow-xs active:scale-[0.96] transition-all"
                                    @click="item.variants.length > 0 ? (selectedItemForVariants = item, showVariantModal = true) : addToCart(item)">
                                    <h4 class="text-[10px] font-black uppercase tracking-tight text-zinc-900 leading-tight mb-1" x-text="item.name"></h4>
                                    <p class="text-[10px] font-black text-indigo-600" x-text="'₹' + parseFloat(item.price).toFixed(2)"></p>
                                </div>
                            </template>
                        </div>
                    </template>
                </div>
            </div>
        </template>
    </main>

    <!-- Bottom Cart / Nav Bar -->
    <nav class="fixed bottom-0 left-0 right-0 bg-zinc-900 border-t border-zinc-800 z-50">
        <!-- Floating Cart Peek -->
        <template x-if="cart.length > 0">
            <div class="px-4 py-3 bg-indigo-600 flex items-center justify-between animate-bounce-in">
                <div class="flex items-center space-x-3">
                    <span class="w-6 h-6 bg-white/20 rounded-full flex items-center justify-center text-white text-[10px] font-black" x-text="cart.length"></span>
                    <span class="text-[10px] font-black text-white uppercase tracking-widest">In Staging</span>
                </div>
                <button @click="view = 'cart'" class="text-[10px] font-black text-white uppercase tracking-widest underline underline-offset-4">Review Order</button>
            </div>
        </template>

        <!-- Main Nav Buttons -->
        <div class="flex items-center justify-around h-16">
            <button @click="view = 'tables'" :class="view === 'tables' ? 'text-indigo-500' : 'text-zinc-500'" class="flex flex-col items-center space-y-1">
                <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="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"></path></svg>
                <span class="text-[8px] font-black uppercase tracking-tighter">Tables</span>
            </button>
            <button @click="view = 'menu'" :class="view === 'menu' ? 'text-indigo-500' : 'text-zinc-500'" class="flex flex-col items-center space-y-1">
                <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="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                <span class="text-[8px] font-black uppercase tracking-tighter">Menu</span>
            </button>
            <button @click="view = 'cart'" :class="view === 'cart' ? 'text-indigo-500' : 'text-zinc-500'" class="flex flex-col items-center space-y-1">
                <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="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"></path></svg>
                <span class="text-[8px] font-black uppercase tracking-tighter">Cart</span>
            </button>
        </div>
    </nav>

    <!-- Overlay: Cart Review -->
    <div x-cloak x-show="view === 'cart'" class="fixed inset-0 bg-white z-[60] flex flex-col" x-transition:enter="transition transform duration-300" x-transition:enter-start="translate-y-full" x-transition:enter-end="translate-y-0">
        <header class="h-14 bg-zinc-900 flex items-center justify-between px-4 flex-shrink-0">
            <h2 class="text-[10px] font-black uppercase tracking-widest text-white">Review Staging Cart</h2>
            <button @click="view = 'menu'" class="text-zinc-400">&times;</button>
        </header>
        <div class="flex-1 overflow-y-auto p-4 space-y-3 pb-32">
            <template x-for="(item, index) in cart" :key="index">
                <div class="bg-white p-4 rounded-sm border border-zinc-100 shadow-sm flex flex-col space-y-3">
                    <div class="flex justify-between items-start">
                        <div class="flex-1">
                            <h4 class="text-[11px] font-black uppercase text-zinc-900" x-text="item.name"></h4>
                            <template x-if="item.notes">
                                <div class="mt-1 flex items-center space-x-1">
                                    <svg class="w-3 h-3 text-indigo-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-bold text-indigo-500 uppercase" x-text="item.notes"></span>
                                </div>
                            </template>
                            <p class="text-[10px] font-bold text-zinc-400 mt-1" x-text="'₹' + item.price.toFixed(2)"></p>
                        </div>
                        <div class="flex items-center space-x-4">
                            <button @click="editingNoteIndex = index" class="w-8 h-8 flex items-center justify-center text-zinc-300 hover:text-indigo-600 active:scale-90 transition-all">
                                <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="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>
                            </button>
                            <div class="flex items-center bg-zinc-50 border border-zinc-100 rounded-sm">
                                <button @click="decrementQty(index)" class="w-8 h-8 flex items-center justify-center text-zinc-400">-</button>
                                <span class="w-8 text-center text-[11px] font-black" x-text="item.qty"></span>
                                <button @click="incrementQty(index)" class="w-8 h-8 flex items-center justify-center text-zinc-400">+</button>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
            <div x-show="cart.length === 0" class="py-20 text-center">
                <p class="text-[10px] font-black text-zinc-300 uppercase tracking-widest">Cart is Empty</p>
            </div>
        </div>
        <div class="p-4 bg-zinc-50 border-t border-zinc-100">
            <div class="flex justify-between items-center mb-4 px-2">
                <span class="text-[10px] font-black uppercase text-zinc-400">Total Payable</span>
                <span class="text-xl font-black text-zinc-900" x-text="'₹' + cartTotal.toFixed(2)"></span>
            </div>
            <button @click="fireToKitchen()" :disabled="cart.length === 0 || isSyncing" class="w-full py-4 bg-indigo-600 text-white text-[11px] font-black uppercase tracking-widest rounded-sm shadow-xl shadow-indigo-900/20 disabled:opacity-50">
                <span x-show="!isSyncing">Fire to Kitchen (KOT)</span>
                <span x-show="isSyncing">Sending Ticket...</span>
            </button>
        </div>
    </div>

    <!-- Variant Selection Modal -->
    <div x-cloak x-show="showVariantModal" class="fixed inset-0 bg-zinc-950/90 backdrop-blur-md z-[100] flex items-end justify-center" x-transition:enter="transition ease-out duration-300" x-transition:enter-start="opacity-0 translate-y-full" x-transition:enter-end="opacity-100 translate-y-0" x-transition:leave="transition ease-in duration-200" x-transition:leave-start="opacity-100 translate-y-0" x-transition:leave-end="opacity-0 translate-y-full">
        <div class="bg-white w-full rounded-t-xl shadow-2xl overflow-hidden pb-10" @click.away="showVariantModal = false">
            <div class="px-6 py-5 border-b border-zinc-100 flex justify-between items-center bg-zinc-50">
                <div>
                    <h3 class="text-sm font-black uppercase tracking-widest text-zinc-900" x-text="selectedItemForVariants?.name"></h3>
                    <p class="text-[9px] text-zinc-400 mt-1 uppercase font-black tracking-widest">Select Specification</p>
                </div>
                <button @click="showVariantModal = false" class="w-10 h-10 flex items-center justify-center text-zinc-400">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                </button>
            </div>
            <div class="p-6">
                <div class="grid grid-cols-1 gap-3">
                    <template x-if="selectedItemForVariants">
                        <template x-for="variant in selectedItemForVariants.variants" :key="variant.id">
                            <button @click="addToCart(selectedItemForVariants, variant)" 
                                class="flex items-center justify-between p-5 border border-zinc-100 rounded-sm active:bg-indigo-50 active:border-indigo-200 transition-all group">
                                <span class="text-[11px] font-black text-zinc-900 uppercase tracking-widest" x-text="variant.name"></span>
                                <span class="text-[12px] font-black text-indigo-600" x-text="'₹' + parseFloat(variant.dine_in_price).toFixed(2)"></span>
                            </button>
                        </template>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- Deal Selection Modal -->
    <div x-cloak x-show="showDealModal" class="fixed inset-0 bg-zinc-950/90 backdrop-blur-md z-[130] flex items-center justify-center p-6" x-transition.opacity>
        <div class="bg-white w-full max-w-sm rounded-sm shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
            <div class="px-6 py-4 border-b border-zinc-100 flex justify-between items-center bg-zinc-50 shrink-0">
                <div>
                    <h3 class="text-[10px] font-black uppercase tracking-widest text-zinc-900" x-text="activeDeal?.name"></h3>
                    <p class="text-[8px] font-bold text-zinc-400 uppercase mt-0.5" x-text="'Slot ' + (currentDealSlotIndex + 1) + ' of ' + activeDeal?.slots.length"></p>
                </div>
                <button @click="closeDealModal()" class="text-zinc-400"><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="M6 18L18 6M6 6l12 12"></path></svg></button>
            </div>
            
            <div class="p-6 overflow-y-auto no-scrollbar flex-1">
                <template x-if="activeDeal && activeDeal.slots[currentDealSlotIndex]">
                    <div>
                        <h4 class="text-[11px] font-black uppercase text-zinc-900 mb-4 bg-amber-50 p-2 border-l-4 border-amber-500" x-text="activeDeal.slots[currentDealSlotIndex].name"></h4>
                        <div class="grid grid-cols-1 gap-3">
                            <template x-for="slotItem in activeDeal.slots[currentDealSlotIndex].items" :key="slotItem.id">
                                <div class="bg-zinc-50 border border-zinc-100 rounded-sm p-4 flex flex-col">
                                    <h5 class="text-[10px] font-black uppercase text-zinc-900 mb-3" x-text="slotItem.item.name"></h5>
                                    
                                    <div class="space-y-2">
                                        <!-- Case 1: Pre-selected variant -->
                                        <template x-if="slotItem.variant">
                                            <button @click="selectItemForSlot(slotItem.item, slotItem.variant)" 
                                                class="w-full py-2.5 px-4 rounded-sm text-[9px] font-black uppercase transition-all flex justify-between items-center"
                                                :class="isItemSelectedInSlot(slotItem.item.id, slotItem.variant.id) ? 'bg-amber-500 text-white shadow-lg shadow-amber-900/20' : 'bg-zinc-900 text-white hover:bg-zinc-800'">
                                                <span x-text="'Select (' + slotItem.variant.name + ')'"></span>
                                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
                                            </button>
                                        </template>

                                        <!-- Case 2: Multi-variant choice -->
                                        <template x-if="!slotItem.variant && slotItem.item.variants.length > 0">
                                            <div class="grid grid-cols-1 gap-1.5">
                                                <template x-for="variant in slotItem.item.variants" :key="variant.id">
                                                    <button @click="selectItemForSlot(slotItem.item, variant)" 
                                                        class="w-full py-2 px-3 border rounded-sm text-[8px] font-black uppercase transition-all flex justify-between items-center group"
                                                        :class="isItemSelectedInSlot(slotItem.item.id, variant.id) ? 'bg-amber-500 border-amber-600 text-white' : 'bg-white border-zinc-200 text-zinc-500 hover:border-amber-500'">
                                                        <span x-text="variant.name"></span>
                                                        <svg class="w-3 h-3 opacity-0 group-hover:opacity-100 transition-opacity" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
                                                    </button>
                                                </template>
                                            </div>
                                        </template>

                                        <!-- Case 3: No variants -->
                                        <template x-if="!slotItem.variant && slotItem.item.variants.length === 0">
                                            <button @click="selectItemForSlot(slotItem.item)" 
                                                class="w-full py-2.5 px-4 rounded-sm text-[9px] font-black uppercase transition-all flex justify-between items-center"
                                                :class="isItemSelectedInSlot(slotItem.item.id) ? 'bg-amber-500 text-white shadow-lg shadow-amber-900/20' : 'bg-zinc-900 text-white hover:bg-zinc-800'">
                                                <span>Select</span>
                                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
                                            </button>
                                        </template>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                </template>
            </div>

            <div class="p-4 border-t border-zinc-100 bg-zinc-50 shrink-0 flex space-x-2">
                <button @click="prevDealSlot()" x-show="currentDealSlotIndex > 0" 
                    class="flex-1 py-3 border border-zinc-200 text-zinc-400 text-[10px] font-black uppercase tracking-widest rounded-sm">
                    Back
                </button>
                <button @click="nextDealSlot()" 
                    :disabled="!isCurrentSlotFilled()"
                    class="flex-1 py-3 text-white text-[10px] font-black uppercase tracking-widest rounded-sm shadow-lg transition-all"
                    :class="!isCurrentSlotFilled() ? 'bg-zinc-200 text-zinc-400' : 'bg-zinc-900 shadow-zinc-900/20 active:scale-95'">
                    <span x-text="currentDealSlotIndex === (activeDeal?.slots.length - 1) ? 'Finish & Add' : 'Next Step'"></span>
                </button>
            </div>
        </div>
    </div>

    <!-- Note Editing Modal -->
    <div x-cloak x-show="editingNoteIndex !== null" class="fixed inset-0 bg-zinc-950/90 backdrop-blur-md z-[120] flex items-center justify-center p-6" x-transition.opacity>
        <template x-if="editingNoteIndex !== null">
            <div class="bg-white w-full max-w-sm rounded-sm shadow-2xl overflow-hidden" @click.away="editingNoteIndex = null">
                <div class="px-6 py-4 border-b border-zinc-100 flex justify-between items-center bg-zinc-50">
                    <h3 class="text-[10px] font-black uppercase tracking-widest text-zinc-900">Special Instructions</h3>
                    <button @click="editingNoteIndex = null" class="text-zinc-400"><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="M6 18L18 6M6 6l12 12"></path></svg></button>
                </div>
                <div class="p-6">
                    <p class="text-[9px] font-bold text-zinc-400 uppercase mb-3" x-text="cart[editingNoteIndex].name"></p>
                    <textarea x-model="cart[editingNoteIndex].notes" 
                        placeholder="E.g. No onion, extra spicy, etc."
                        class="w-full bg-zinc-50 border-zinc-100 rounded-sm p-4 text-[11px] font-medium text-zinc-900 focus:ring-2 focus:ring-indigo-500/20 min-h-[100px]"></textarea>
                    <button @click="editingNoteIndex = null" class="w-full mt-4 py-3 bg-indigo-600 text-white text-[10px] font-black uppercase tracking-widest rounded-sm shadow-lg shadow-indigo-900/20">
                        Done
                    </button>
                </div>
            </div>
        </template>
    </div>

    <!-- Success Feedback Modal -->
    <div x-cloak x-show="showSuccessModal" class="fixed inset-0 z-[110] flex items-center justify-center p-6" x-transition.opacity>
        <div class="absolute inset-0 bg-zinc-950/40 backdrop-blur-sm"></div>
        <div class="bg-white p-10 rounded-sm shadow-2xl border border-zinc-200 text-center relative z-10 max-w-xs w-full">
            <div class="w-16 h-16 bg-emerald-100 text-emerald-600 rounded-full flex items-center justify-center mx-auto mb-4 animate-bounce">
                <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"></path></svg>
            </div>
            <h3 class="text-xs font-black uppercase tracking-widest text-zinc-900 mb-1">Order Fired!</h3>
            <p class="text-[9px] text-zinc-500 uppercase font-bold tracking-widest">Sent to Kitchen Successfully</p>
        </div>
    </div>

    <!-- Offline Alert Modal -->
    <div x-cloak x-show="showOfflineModal" class="fixed inset-0 z-[110] flex items-center justify-center p-6" x-transition.opacity>
        <div class="absolute inset-0 bg-zinc-950/40 backdrop-blur-sm"></div>
        <div class="bg-white p-10 rounded-sm shadow-2xl border border-rose-200 text-center relative z-10 max-w-xs w-full">
            <div class="w-16 h-16 bg-rose-100 text-rose-600 rounded-full flex items-center justify-center mx-auto mb-4 animate-pulse">
                <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>
            </div>
            <h3 class="text-xs font-black uppercase tracking-widest text-zinc-900 mb-1">No Internet!</h3>
            <p class="text-[9px] text-rose-500 uppercase font-bold tracking-widest leading-relaxed">Please connect to Wi-Fi to fire this KOT.</p>
        </div>
    </div>
</div>

<script>
    function waiterApp() {
        return {
            view: 'tables', // tables, menu, cart
            tables: [],
            categories: [],
            items: [],
            cart: [],
            selectedTable: null,
            selectedCategory: null,
            isSyncing: false,
            search: '',
            showVariantModal: false,
            selectedItemForVariants: null,
            showSuccessModal: false,
            showOfflineModal: false,
            activeOrder: null,
            editingNoteIndex: null,
            deals: [],
            showDealsView: false,
            showDealModal: false,
            activeDeal: null,
            currentDealSlotIndex: 0,
            dealSelections: [], // [{slot_id, item}]

            init() {
                this.fetchTables();
                this.fetchCategories();
                this.fetchItems();
                
                // Start optimized polling loop
                this.startPolling();

                // Revalidate on Focus (SWR Style)
                // Instantly refreshes tables when the waiter wakes up their phone or returns to the tab
                document.addEventListener('visibilitychange', () => {
                    if (document.visibilityState === 'visible') {
                        this.fetchTables();
                    }
                });

                this.requestNotificationPermission();
            },

            async requestNotificationPermission() {
                if ('Notification' in window && Notification.permission === 'default') {
                    await Notification.requestPermission();
                }
            },

            startPolling() {
                setTimeout(async () => {
                    // Only poll if we are on the tables view to save bandwidth
                    if (this.view === 'tables' || this.view === 'order_details') {
                        await this.fetchTables();
                    }
                    this.startPolling(); // Recursively call for next interval
                }, 10000);
            },

            getPageTitle() {
                if (this.view === 'tables') return 'Table Grid';
                if (this.view === 'order_details') return 'Current Table Order';
                if (this.view === 'menu') return this.selectedTable ? 'Ordering: ' + this.selectedTable.name : 'Quick Menu';
                if (this.view === 'cart') return 'Review Order Staging';
            },

            get filteredItems() {
                if (!this.search) return this.items;
                const s = this.search.toLowerCase();
                return this.items.filter(i => i.name.toLowerCase().includes(s));
            },

            async fetchTables() {
                if (this.isSyncing) return; // Prevent duplicate overlapping calls
                this.isSyncing = true;
                try {
                    const res = await fetch('{{ route("waiter.api.tables") }}');
                    const newTables = await res.json();
                    
                    // Check for new "Ready" items to notify the waiter
                    newTables.forEach(table => {
                        const oldTable = this.tables.find(t => t.id === table.id);
                        if (table.has_ready_items && (!oldTable || !oldTable.has_ready_items)) {
                            this.sendReadyNotification(table);
                        }
                    });

                    this.tables = newTables;
                } finally {
                    this.isSyncing = false;
                }
            },

            async fetchCategories() {
                const res = await fetch('{{ route("waiter.api.categories") }}');
                this.categories = await res.json();
            },

            async fetchItems() {
                let url = '{{ route("waiter.api.items") }}';
                if (this.selectedCategory) url += '?category_id=' + this.selectedCategory;
                const res = await fetch(url);
                this.items = await res.json();
            },

            async fetchDeals() {
                const res = await fetch('{{ route("waiter.api.deals") }}');
                this.deals = await res.json();
            },

            startDealSelection(deal) {
                this.activeDeal = deal;
                this.currentDealSlotIndex = 0;
                this.dealSelections = [];
                this.showDealModal = true;
            },

            selectItemForSlot(item, variant = null) {
                const slot = this.activeDeal.slots[this.currentDealSlotIndex];
                // Replace if already selected in this slot (since quantity is usually 1)
                this.dealSelections = this.dealSelections.filter(s => s.slot_id !== slot.id);
                this.dealSelections.push({
                    slot_id: slot.id,
                    item: item,
                    variant: variant
                });
            },

            isItemSelectedInSlot(itemId, variantId = null) {
                const slot = this.activeDeal?.slots[this.currentDealSlotIndex];
                return this.dealSelections.some(s => 
                    s.slot_id === slot?.id && 
                    s.item.id === itemId && 
                    (variantId ? (s.variant && s.variant.id === variantId) : !s.variant)
                );
            },

            isCurrentSlotFilled() {
                const slot = this.activeDeal?.slots[this.currentDealSlotIndex];
                return this.dealSelections.some(s => s.slot_id === slot?.id);
            },

            nextDealSlot() {
                if (this.currentDealSlotIndex < this.activeDeal.slots.length - 1) {
                    this.currentDealSlotIndex++;
                } else {
                    this.addDealToCart();
                }
            },

            prevDealSlot() {
                if (this.currentDealSlotIndex > 0) {
                    this.currentDealSlotIndex--;
                }
            },

            addDealToCart() {
                const selectionsText = this.dealSelections.map(s => s.item.name + (s.variant ? ' (' + s.variant.name + ')' : '')).join(' + ');
                this.cart.push({
                    id: 'deal_' + this.activeDeal.id + '_' + Date.now(), // Unique ID for cart entry
                    deal_id: this.activeDeal.id,
                    name: this.activeDeal.name + ' (' + selectionsText + ')',
                    price: parseFloat(this.activeDeal.price),
                    qty: 1,
                    notes: null,
                    selections: this.dealSelections.map(s => ({ 
                        item_id: s.item.id, 
                        variant_id: s.variant ? s.variant.id : null,
                        name: s.item.name + (s.variant ? ' (' + s.variant.name + ')' : '') 
                    }))
                });
                this.closeDealModal();
                this.view = 'cart';
            },

            closeDealModal() {
                this.showDealModal = false;
                this.activeDeal = null;
                this.dealSelections = [];
            },

            selectTable(table) {
                this.selectedTable = table;
                this.cart = []; // Clear cart when switching tables
                if (table.status === 'occupied') {
                    this.loadActiveOrder(table);
                } else {
                    this.activeOrder = null;
                    this.view = 'menu';
                }
            },

            async loadActiveOrder(table) {
                this.isSyncing = true;
                try {
                    const res = await fetch(`{{ url('waiter/api/order') }}/${table.id}`);
                    this.activeOrder = await res.json();
                    this.view = 'order_details';
                } finally {
                    this.isSyncing = false;
                }
            },

            addToCart(item, variant = null) {
                const price = variant ? parseFloat(variant.dine_in_price) : parseFloat(item.price);
                const name = variant ? item.name + ' (' + variant.name + ')' : item.name;
                const variantId = variant ? variant.id : null;

                const existing = this.cart.find(i => i.id === item.id && i.variant_id === variantId);
                
                if (existing) {
                    existing.qty++;
                } else {
                    this.cart.push({
                        id: item.id,
                        variant_id: variantId,
                        name: name,
                        price: price,
                        qty: 1,
                        notes: null
                    });
                }
                
                this.showVariantModal = false;
                this.selectedItemForVariants = null;
            },

            incrementQty(index) { this.cart[index].qty++; },
            decrementQty(index) { 
                if (this.cart[index].qty > 1) this.cart[index].qty--;
                else this.cart.splice(index, 1);
            },

            get cartTotal() {
                return this.cart.reduce((sum, item) => sum + (item.price * item.qty), 0);
            },

            getTableClasses(table) {
                if (table.has_ready_items) return 'bg-amber-50 border-amber-500 text-amber-600 shadow-lg shadow-amber-900/10';
                if (table.status === 'occupied') return 'bg-indigo-50 border-indigo-500 text-indigo-600';
                return 'bg-white border-zinc-100 text-zinc-900';
            },

            async fireToKitchen() {
                if (!this.selectedTable) return alert('Select a table first');
                this.isSyncing = true;
                
                try {
                    const payload = {
                        table_id: this.selectedTable.id,
                        cart: this.cart,
                        subtotal: this.cartTotal,
                        gst_amount: this.cartTotal * 0.05,
                        grand_total: this.cartTotal * 1.05
                    };

                    const res = await fetch('{{ route("waiter.api.order.kot") }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        },
                        body: JSON.stringify(payload)
                    });

                    if (res.ok) {
                        this.cart = [];
                        this.view = 'tables';
                        this.fetchTables();
                        this.showSuccessModal = true;
                        setTimeout(() => { this.showSuccessModal = false; }, 2000);
                    } else {
                        alert('Server error. Please check your connection.');
                    }
                } catch (err) {
                    console.error('Network error during KOT:', err);
                    this.showOfflineModal = true;
                    setTimeout(() => { this.showOfflineModal = false; }, 3000);
                } finally {
                    this.isSyncing = false;
                }
            },

            async serveOrderItem(orderItemId) {
                if (this.isSyncing) return;
                this.isSyncing = true;

                try {
                    const res = await fetch('{{ route("waiter.api.order.item.serve") }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        },
                        body: JSON.stringify({ order_item_id: orderItemId })
                    });

                    if (res.ok) {
                        // Refresh order details immediately
                        this.loadActiveOrder(this.selectedTable);
                        this.fetchTables(); // Update table grid ready indicator
                    }
                } finally {
                    this.isSyncing = false;
                }
            },

            sendReadyNotification(table) {
                if ('Notification' in window && Notification.permission === 'granted') {
                    new Notification(`Table ${table.name} Ready!`, {
                        body: 'Items are waiting at the kitchen pass.',
                        icon: '/favicon.ico', // You can replace this with a kitchen icon
                        tag: 'table-ready-' + table.id,
                        renotify: true
                    });
                    
                    // Play a subtle alert sound if possible
                    try {
                        const audio = new Audio('https://assets.mixkit.co/active_storage/sfx/2869/2869-preview.mp3');
                        audio.play();
                    } catch (e) {}
                }
            }
        }
    }
</script>

<style>
    @keyframes bounce-in {
        0% { transform: translateY(20px); opacity: 0; }
        100% { transform: translateY(0); opacity: 1; }
    }
    .animate-bounce-in { animation: bounce-in 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
</style>
@endsection
