@extends('layouts.biller')

@section('title', 'Terminal')
@section('page_title', 'POS Terminal')
@section('content_padding', 'p-0')

@section('content')
<div class="h-full flex flex-col bg-zinc-50 text-zinc-900 select-none overflow-hidden" x-data="posApp()" x-init="init()">


    <!-- Settlement Modal -->
    <div x-cloak x-show="showSettlementModal" class="fixed inset-0 bg-zinc-950/90 backdrop-blur-md z-50 flex items-center justify-center p-6" x-transition.opacity>


        <div class="bg-white w-full max-w-lg rounded-sm shadow-2xl border border-zinc-200 relative" @click.away="showSettlementModal = false">
            <!-- Discount Modal (Deeply nested to solve click-away race condition) -->
            <div x-cloak x-show="showDiscountModal" class="absolute inset-0 bg-white/50 backdrop-blur-xs z-[60] flex items-center justify-center p-6 rounded-sm">
                <div class="bg-white w-full max-w-sm rounded-sm shadow-2xl border border-zinc-200" @click.away="showDiscountModal = false">
                    <div class="px-6 py-4 border-b border-zinc-100 flex justify-between items-center">
                        <h3 class="text-[11px] font-black uppercase tracking-widest text-zinc-500">Apply Campaign Discount</h3>
                        <button @click="showDiscountModal = false" class="text-zinc-400 hover:text-zinc-900 transition-colors">&times;</button>
                    </div>
                    <div class="p-8 space-y-6">
                        <div class="flex bg-zinc-50 p-1 rounded-sm border border-zinc-200">
                            <button @click="discountType = 'fixed'" :class="discountType === 'fixed' ? 'bg-indigo-600 text-white shadow-lg' : 'text-zinc-400'" class="flex-1 py-2 text-[10px] font-black uppercase rounded-sm transition-all">Flat Amount</button>
                            <button @click="discountType = 'percentage'" :class="discountType === 'percentage' ? 'bg-indigo-600 text-white shadow-lg' : 'text-zinc-400'" class="flex-1 py-2 text-[10px] font-black uppercase rounded-sm transition-all">Percentage %</button>
                        </div>
                        <div>
                            <input type="number" x-model="discountValue" min="0" class="w-full text-center text-4xl font-black py-6 bg-transparent border-b-2 border-zinc-100 text-indigo-600 focus:border-indigo-600 outline-hidden" placeholder="0">
                        </div>
                        <button @click="showDiscountModal = false" class="w-full py-4 bg-zinc-900 text-white text-[11px] font-black uppercase tracking-widest rounded-sm hover:bg-zinc-800 transition-all">Confirm & Apply</button>
                    </div>
                </div>
            </div>
            <div class="px-8 py-6 bg-zinc-50 border-b border-zinc-100 flex justify-between items-center">
                <div>
                    <h3 class="text-xs font-black uppercase tracking-widest text-zinc-900">Finalize Settlement</h3>
                    <p class="text-[10px] text-zinc-500 mt-1 uppercase font-black tracking-widest" x-text="'Payable: ₹' + total.toFixed(2)"></p>
                </div>
                <button @click="showSettlementModal = false" class="text-zinc-400 hover:text-zinc-900 transition-colors">&times;</button>
            </div>
            
            <div class="p-8">
                <label class="text-[9px] font-black text-zinc-400 uppercase tracking-widest mb-4 block">Select Gateway</label>
                <div class="grid grid-cols-4 gap-3 mb-8">
                    <button @click="paymentMethod = 'cash'" :class="paymentMethod === 'cash' ? 'bg-indigo-600 text-white border-indigo-500 shadow-xl shadow-indigo-900/20' : 'bg-zinc-50 text-zinc-400 border-zinc-200 hover:border-zinc-300'" class="py-4 border rounded-sm text-[10px] font-black uppercase transition-all">Cash</button>
                    <button @click="paymentMethod = 'card'" :class="paymentMethod === 'card' ? 'bg-indigo-600 text-white border-indigo-500 shadow-xl shadow-indigo-900/20' : 'bg-zinc-50 text-zinc-400 border-zinc-200 hover:border-zinc-300'" class="py-4 border rounded-sm text-[10px] font-black uppercase transition-all">Card</button>
                    <button @click="paymentMethod = 'upi'" :class="paymentMethod === 'upi' ? 'bg-indigo-600 text-white border-indigo-500 shadow-xl shadow-indigo-900/20' : 'bg-zinc-50 text-zinc-400 border-zinc-200 hover:border-zinc-300'" class="py-4 border rounded-sm text-[10px] font-black uppercase transition-all">UPI</button>
                    <button @click="paymentMethod = 'split'" :class="paymentMethod === 'split' ? 'bg-indigo-600 text-white border-indigo-500 shadow-xl shadow-indigo-900/20' : 'bg-zinc-50 text-zinc-400 border-zinc-200 hover:border-zinc-300'" class="py-4 border rounded-sm text-[10px] font-black uppercase transition-all">Split</button>
                </div>
                
                <div x-show="paymentMethod === 'split'" class="space-y-4 mb-8 p-6 bg-zinc-50 border border-zinc-100 rounded-sm">
                    <div class="flex items-center space-x-4">
                        <label class="w-20 text-[10px] font-black uppercase text-zinc-500 tracking-widest">Cash</label>
                        <input type="number" x-model="splitCash" class="flex-1 bg-transparent border-b border-zinc-200 py-2 px-3 text-sm font-black text-zinc-900 focus:border-indigo-600 outline-hidden" placeholder="0">
                    </div>
                    <div class="flex items-center space-x-4">
                        <label class="w-20 text-[10px] font-black uppercase text-zinc-500 tracking-widest">Card</label>
                        <input type="number" x-model="splitCard" class="flex-1 bg-transparent border-b border-zinc-200 py-2 px-3 text-sm font-black text-zinc-900 focus:border-indigo-600 outline-hidden" placeholder="0">
                    </div>
                    <div class="flex items-center space-x-4">
                        <label class="w-20 text-[10px] font-black uppercase text-zinc-500 tracking-widest">UPI</label>
                        <input type="number" x-model="splitUpi" class="flex-1 bg-transparent border-b border-zinc-200 py-2 px-3 text-sm font-black text-zinc-900 focus:border-indigo-600 outline-hidden" placeholder="0">
                    </div>
                </div>

                <!-- Discount Summary in Settlement -->
                <div class="mb-8 p-4 bg-indigo-50/50 rounded-sm border border-indigo-100 flex items-center justify-between">
                    <div>
                        <p class="text-[9px] font-black text-indigo-400 uppercase tracking-widest mb-1">Applied Promotions</p>
                        <p class="text-[11px] font-black text-indigo-900 uppercase tracking-tight" x-text="discountAmount > 0 ? (discountType === 'percentage' ? discountValue + '% Discount' : '₹' + discountValue + ' Flat Off') : 'No Discount Applied'"></p>
                    </div>
                    <button @click="showDiscountModal = true" class="px-4 py-2 bg-indigo-600 text-white text-[9px] font-black uppercase tracking-widest rounded-sm hover:bg-indigo-700 transition-all">
                        Modify
                    </button>
                </div>
                
                <button @click="payAndSettle()" :disabled="isProcessing" class="w-full py-5 bg-emerald-600 text-white text-[11px] font-black uppercase tracking-widest rounded-sm hover:bg-emerald-700 transition-all shadow-2xl shadow-emerald-900/40 disabled:opacity-50 flex items-center justify-center space-x-3">
                    <span x-show="!isProcessing">Confirm Transaction</span>
                    <span x-show="isProcessing">Processing...</span>
                </button>
            </div>
        </div>
    </div>

    <!-- Running Orders Modal -->
    <div x-cloak x-show="showRunningOrdersModal" class="fixed inset-0 bg-zinc-950/90 backdrop-blur-md z-50 flex items-center justify-center p-6" x-transition.opacity>
        <div class="bg-white w-full max-w-6xl h-[85vh] flex flex-col rounded-sm shadow-2xl border border-zinc-200" @click.away="showRunningOrdersModal = false">
            <div class="px-8 py-6 border-b border-zinc-100 flex justify-between items-center bg-zinc-50 flex-shrink-0">
                <div class="flex items-center space-x-6">
                    <h3 class="text-xs font-black uppercase tracking-widest text-zinc-900">Live Transactions</h3>
                    <div class="h-4 w-[1px] bg-zinc-200"></div>
                    <span class="text-[10px] font-black text-indigo-600 uppercase tracking-widest" x-text="activeOrders.length + ' Active Buffers'"></span>
                </div>
                <button @click="showRunningOrdersModal = false" class="text-zinc-400 hover:text-zinc-900 transition-colors">
                    <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-8 flex-1 overflow-y-auto bg-zinc-50">
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                    <template x-for="order in activeOrders" :key="order.id">
                        <div class="bg-white border border-zinc-200 rounded-sm shadow-sm hover:border-indigo-600 transition-all cursor-pointer overflow-hidden flex flex-col group" @click="resumeOrder(order)">
                            <div class="bg-zinc-900 px-5 py-3 flex justify-between items-center">
                                <span class="text-[11px] font-black text-white uppercase tracking-widest" x-text="order.order_type === 'dine_in' ? 'Table ' + (order.table ? order.table.name : 'N/A') : 'Direct Order'"></span>
                                <span class="text-[9px] font-black text-indigo-400 uppercase tracking-widest px-2 py-0.5 bg-zinc-800 rounded-sm" x-text="order.order_type.replace('_', ' ')"></span>
                            </div>
                            <div class="p-5 flex-1 flex flex-col space-y-4">
                                <div class="flex justify-between items-start">
                                    <div>
                                        <p class="text-[9px] font-black text-zinc-400 uppercase tracking-widest mb-1">Entity</p>
                                        <p class="text-[10px] font-black text-zinc-900 uppercase tracking-tight" x-text="order.order_type === 'dine_in' ? (order.waiter ? order.waiter.name : 'Steward') : (order.customer_name || 'Walk-in')"></p>
                                    </div>
                                    <div class="text-right">
                                        <p class="text-[9px] font-black text-zinc-400 uppercase tracking-widest mb-1">Items</p>
                                        <p class="text-[10px] font-black text-zinc-900" x-text="order.items.length"></p>
                                    </div>
                                </div>
                                <div class="mt-auto pt-4 border-t border-zinc-100 flex justify-between items-end">
                                    <div>
                                        <p class="text-[8px] font-black text-zinc-400 uppercase tracking-widest mb-1">TXN ID</p>
                                        <p class="text-[9px] font-black text-zinc-500" x-text="'#' + order.id"></p>
                                    </div>
                                    <div class="text-right">
                                        <p class="text-[8px] font-black text-zinc-400 uppercase tracking-widest mb-1">Value</p>
                                        <p class="text-xs font-black text-indigo-600 tracking-tight" x-text="'₹' + parseFloat(order.grand_total).toFixed(2)"></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
                
                <div x-show="activeOrders.length === 0" class="flex flex-col items-center justify-center h-full text-zinc-300">
                    <svg class="w-16 h-16 mb-6 opacity-20" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path></svg>
                    <p class="text-xs font-black uppercase tracking-widest opacity-40">No active buffers found</p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Variant Selection Modal -->
    <div x-cloak x-show="showVariantModal" class="fixed inset-0 bg-zinc-950/90 backdrop-blur-md z-[60] flex items-center justify-center p-6" x-transition.opacity>
        <div class="bg-white w-full max-w-md rounded-sm shadow-2xl border border-zinc-200" @click.away="showVariantModal = false">
            <div class="px-8 py-6 border-b border-zinc-100 flex justify-between items-center bg-zinc-50 rounded-t-sm">
                <div>
                    <h3 class="text-xs 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 Required Specification</p>
                </div>
                <button @click="showVariantModal = false" class="text-zinc-400 hover:text-zinc-900 transition-colors">
                    <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-8">
                <div class="grid grid-cols-2 gap-4">
                    <template x-if="selectedItemForVariants">
                        <template x-for="variant in selectedItemForVariants.variants" :key="variant.id">
                            <button @click="addToCart(selectedItemForVariants, variant)" 
                                class="flex flex-col items-center justify-center p-6 border-2 border-zinc-100 rounded-sm hover:border-indigo-600 hover:bg-indigo-50 transition-all group">
                                <span class="text-[10px] font-black text-zinc-900 uppercase tracking-widest group-hover:text-indigo-600 mb-2" x-text="variant.name"></span>
                                <span class="text-[11px] font-black text-zinc-400" 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-[65] flex items-center justify-center p-6" x-transition.opacity>
        <div class="bg-white w-full max-w-4xl h-[80vh] flex flex-col rounded-sm shadow-2xl border border-zinc-200" @click.away="showDealModal = false">
            <div class="px-8 py-6 border-b border-zinc-100 flex justify-between items-center bg-zinc-50 rounded-t-sm flex-shrink-0">
                <div>
                    <h3 class="text-xs font-black uppercase tracking-widest text-zinc-900" x-text="activeDeal?.name"></h3>
                    <div class="flex items-center space-x-2 mt-1">
                        <template x-for="(slot, index) in activeDeal?.slots" :key="slot.id">
                            <div class="flex items-center">
                                <div :class="index === currentSlotIndex ? 'bg-amber-500 text-white' : (index < currentSlotIndex ? 'bg-emerald-500 text-white' : 'bg-zinc-200 text-zinc-400')" 
                                    class="w-5 h-5 rounded-full flex items-center justify-center text-[8px] font-black transition-colors" x-text="index + 1"></div>
                                <div x-show="index < activeDeal.slots.length - 1" class="w-4 h-[1px] bg-zinc-200 mx-1"></div>
                            </div>
                        </template>
                        <span class="text-[9px] text-zinc-400 uppercase font-black tracking-widest ml-4" x-text="'Choose ' + activeDeal?.slots[currentSlotIndex]?.name"></span>
                    </div>
                </div>
                <button @click="showDealModal = false" class="text-zinc-400 hover:text-zinc-900 transition-colors">
                    <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="flex-1 overflow-y-auto p-8 bg-zinc-50">
                <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                    <template x-if="activeDeal?.slots[currentSlotIndex]">
                        <template x-for="slotItem in activeDeal.slots[currentSlotIndex].items" :key="slotItem.id">
                            <div class="bg-white border border-zinc-200 rounded-sm p-4 flex flex-col hover:border-amber-500 transition-all shadow-sm">
                                <h4 class="text-[10px] font-black text-zinc-900 uppercase tracking-tight mb-3 line-clamp-1" x-text="slotItem.item.name"></h4>
                                
                                <div class="space-y-2 mt-auto">
                                    <!-- Case 1: Specific variant already pre-selected for this slot -->
                                    <template x-if="slotItem.variant">
                                        <button @click="selectDealItem(slotItem.item, slotItem.variant)" 
                                            class="w-full py-2.5 px-4 bg-zinc-900 text-white text-[9px] font-black uppercase tracking-widest rounded-sm hover:bg-amber-500 transition-all flex justify-between items-center">
                                            <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: No specific variant pre-selected, let user choose from all available variants -->
                                    <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="selectDealItem(slotItem.item, variant)" 
                                                    class="w-full py-2 px-3 bg-zinc-50 border border-zinc-100 rounded-sm text-[8px] font-black uppercase text-zinc-500 hover:bg-amber-500 hover:text-white hover:border-amber-500 transition-all text-left flex justify-between items-center group">
                                                    <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: Item has no variants at all -->
                                    <template x-if="!slotItem.variant && slotItem.item.variants.length === 0">
                                        <button @click="selectDealItem(slotItem.item)" 
                                            class="w-full py-2.5 px-4 bg-zinc-900 text-white text-[9px] font-black uppercase tracking-widest rounded-sm hover:bg-amber-500 transition-all flex justify-between items-center">
                                            <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>
                    </template>
                </div>
            </div>
            
            <div class="px-8 py-4 bg-white border-t border-zinc-100 flex justify-between items-center flex-shrink-0">
                <button @click="if(currentSlotIndex > 0) currentSlotIndex--" :disabled="currentSlotIndex === 0" 
                    class="px-6 py-2 border border-zinc-200 text-zinc-400 text-[9px] font-black uppercase tracking-widest rounded-sm hover:bg-zinc-50 transition-all disabled:opacity-30">
                    Previous Step
                </button>
                <div class="text-[9px] font-black text-zinc-400 uppercase tracking-widest">
                    Step <span class="text-zinc-900" x-text="currentSlotIndex + 1"></span> of <span class="text-zinc-900" x-text="activeDeal?.slots.length"></span>
                </div>
            </div>
        </div>
    </div>
    <!-- Visual Floor Map Modal -->
    <div x-cloak x-show="showFloorMap" class="fixed inset-0 bg-zinc-950/95 backdrop-blur-xl z-[150] flex flex-col" x-transition.opacity>
        <div class="h-20 flex-shrink-0 flex items-center justify-between px-8 border-b border-white/5">
            <div>
                <h3 class="text-xs font-black uppercase tracking-[0.3em] text-white" x-text="isEditLayoutMode ? 'Floor Map Designer' : 'Interactive Floor Map'"></h3>
                <p class="text-[9px] font-bold text-zinc-500 uppercase tracking-widest mt-1" x-text="isEditLayoutMode ? 'Drag tables to arrange your restaurant layout' : 'Select a table to manage its order'"></p>
            </div>
            <div class="flex items-center space-x-6">
                <template x-if="!isEditLayoutMode">
                    <div class="flex items-center space-x-4 px-4 py-2 bg-white/5 rounded-full border border-white/5">
                        <div class="flex items-center space-x-1.5">
                            <div class="w-2 h-2 rounded-full bg-zinc-600"></div>
                            <span class="text-[8px] font-black text-zinc-500 uppercase">Available</span>
                        </div>
                        <div class="flex items-center space-x-1.5">
                            <div class="w-2 h-2 rounded-full bg-indigo-500 shadow-[0_0_8px_rgba(99,102,241,0.5)]"></div>
                            <span class="text-[8px] font-black text-zinc-500 uppercase">Occupied</span>
                        </div>
                        <div class="flex items-center space-x-1.5">
                            <div class="w-2 h-2 rounded-full bg-amber-500 shadow-[0_0_8px_rgba(245,158,11,0.5)] animate-pulse"></div>
                            <span class="text-[8px] font-black text-zinc-500 uppercase">Ready items</span>
                        </div>
                    </div>
                </template>

                <div class="flex items-center space-x-3">
                    <template x-if="!isEditLayoutMode">
                        <button @click="isEditLayoutMode = true" class="px-4 py-2 bg-white/5 border border-white/10 text-[9px] font-black text-white uppercase tracking-widest rounded-full hover:bg-white/10 transition-all">
                            Edit Layout
                        </button>
                    </template>
                    <template x-if="isEditLayoutMode">
                        <div class="flex items-center space-x-3">
                            <button @click="isEditLayoutMode = false" class="px-4 py-2 text-[9px] font-black text-zinc-500 uppercase tracking-widest hover:text-white transition-all">
                                Cancel
                            </button>
                            <button @click="saveLayout()" class="px-6 py-2 bg-emerald-600 text-[9px] font-black text-white uppercase tracking-widest rounded-full hover:bg-emerald-500 shadow-lg shadow-emerald-900/20 transition-all">
                                Save Arrangement
                            </button>
                        </div>
                    </template>
                    <button @click="showFloorMap = false" class="w-10 h-10 flex items-center justify-center rounded-full bg-white/10 text-white hover:bg-rose-500 transition-all">
                        &times;
                    </button>
                </div>
            </div>
        </div>

        <div class="flex-1 overflow-hidden relative bg-[radial-gradient(#1e1e24_1px,transparent_1px)] [background-size:32px_32px]">
            <div class="absolute inset-0 flex items-center justify-center overflow-auto p-20"
                @mousemove="handleDrag($event)"
                @mouseup="handleDragEnd()"
                @mouseleave="handleDragEnd()"
            >
                <!-- Map Container -->
                <div id="floor-map-container" class="relative bg-zinc-900/50 border border-white/5 rounded-lg shadow-2xl transition-all" 
                    style="width: 1200px; height: 800px;">
                    
                    <template x-for="table in tables" :key="table.id">
                        <div 
                            @mousedown="handleDragStart($event, table)"
                            @click="if(isEditLayoutMode) return; 
                                    let activeOrderFromList = activeOrders.find(o => o.table_id === table.id);
                                    if(activeOrderFromList) {
                                        resumeOrder(activeOrderFromList);
                                        showFloorMap = false;
                                    } else if(table.active_order || table.activeOrder) {
                                        resumeOrder(table.active_order || table.activeOrder);
                                        showFloorMap = false;
                                    } else {
                                        selectedTable = table.id;
                                        showFloorMap = false;
                                    }"
                            class="absolute transition-all duration-75 group select-none"
                            :class="isEditLayoutMode ? 'cursor-move z-50' : 'cursor-pointer'"
                            :style="`left: ${table.pos_x || 0}px; top: ${table.pos_y || 0}px; width: ${table.width || 100}px; height: ${table.height || 100}px;`"
                        >
                            <!-- Table Glow Effect -->
                            <div class="absolute inset-0 rounded-lg blur-xl opacity-0 group-hover:opacity-100 transition-opacity"
                                :class="table.has_ready_items ? 'bg-amber-500/30' : (table.status === 'occupied' ? 'bg-indigo-500/30' : 'bg-white/10')"></div>
                            
                            <!-- Table Body -->
                            <div class="absolute inset-0 border flex flex-col items-center justify-center transition-all duration-300"
                                :class="[
                                    table.shape === 'circle' ? 'rounded-full' : 'rounded-lg',
                                    isEditLayoutMode ? 'border-dashed border-white/40 bg-zinc-800/80' : 
                                    (table.has_ready_items ? 'bg-amber-500 border-amber-400 shadow-[0_0_20px_rgba(245,158,11,0.4)] animate-pulse' : 
                                    (table.status === 'occupied' ? 'bg-indigo-600 border-indigo-400 shadow-[0_0_15px_rgba(99,102,241,0.3)]' : 'bg-zinc-800 border-white/10 hover:border-white/20'))
                                ]"
                            >
                                <span class="text-[10px] font-black uppercase tracking-[0.2em]" 
                                    :class="table.status === 'occupied' || table.has_ready_items ? 'text-white' : 'text-zinc-500 group-hover:text-white'"
                                    x-text="table.name"></span>
                                
                                <template x-if="!isEditLayoutMode">
                                    <div class="mt-1 flex space-x-0.5">
                                        <template x-for="i in parseInt(table.capacity)" :key="i">
                                            <div class="w-1 h-1 rounded-full opacity-30"
                                                :class="table.status === 'occupied' || table.has_ready_items ? 'bg-white' : 'bg-zinc-600'"></div>
                                        </template>
                                    </div>
                                </template>

                                <!-- Edit Overlay -->
                                <template x-if="isEditLayoutMode">
                                    <div class="absolute inset-0 flex items-center justify-center bg-black/20">
                                        <svg class="w-4 h-4 text-white/50" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"></path></svg>
                                    </div>
                                </template>

                                <!-- Ready Items Alert Badge -->
                                <template x-if="table.has_ready_items && !isEditLayoutMode">
                                    <div class="absolute -top-2 -right-2 bg-white text-amber-600 text-[7px] font-black px-1.5 py-0.5 rounded-full border-2 border-amber-500 shadow-lg">
                                        READY
                                    </div>
                                </template>
                            </div>
                        </div>
                    </template>

                    <!-- Restaurant Layout Accents -->
                    <div class="absolute top-0 left-1/2 -translate-x-1/2 px-10 py-2 bg-zinc-800 border-x border-b border-white/5 rounded-b-xl text-[8px] font-black text-zinc-600 uppercase tracking-[0.4em]">Kitchen Entrance</div>
                </div>
            </div>
        </div>

        <div class="h-16 bg-zinc-950 border-t border-white/5 flex items-center justify-center">
            <button @click="showFloorMap = false" class="text-[10px] font-black text-zinc-500 uppercase tracking-widest hover:text-white transition-colors">Return to Dashboard</button>
        </div>
    </div>

    <!-- Success Feedback Modal -->
    <div x-cloak x-show="showSuccessModal" class="fixed inset-0 z-[100] flex items-center justify-center p-6" x-transition:enter="transition ease-out duration-300" x-transition:enter-start="opacity-0 scale-90" x-transition:enter-end="opacity-100 scale-100" x-transition:leave="transition ease-in duration-200" x-transition:leave-start="opacity-100 scale-100" x-transition:leave-end="opacity-0 scale-90">
        <div class="absolute inset-0 bg-zinc-950/40 backdrop-blur-sm"></div>
        <div class="bg-white p-12 rounded-sm shadow-2xl border border-zinc-200 text-center relative z-10 max-w-xs w-full">
            <div class="w-20 h-20 bg-emerald-100 text-emerald-600 rounded-full flex items-center justify-center mx-auto mb-6 animate-bounce">
                <svg class="w-10 h-10" 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-sm font-black uppercase tracking-widest text-zinc-900 mb-2">Order Fired!</h3>
            <p class="text-[10px] text-zinc-500 uppercase font-bold tracking-widest">Sent to Kitchen Successfully</p>
        </div>
    </div>

    <div class="flex-1 flex flex-col md:flex-row overflow-hidden h-full">
        <!-- Menu Explorer -->
        <div class="flex-1 flex flex-col overflow-hidden bg-zinc-50">
            <!-- Navigation Tabs -->
            <div class="h-16 bg-white border-b border-zinc-200 px-6 flex items-center justify-between flex-shrink-0 shadow-xs">
                <div class="flex items-center space-x-3 overflow-x-auto no-scrollbar">
                    <button
                        @click="selectedCategory = null; showDealsView = false"
                        :class="selectedCategory === null && !showDealsView ? 'bg-indigo-600 text-white shadow-lg shadow-indigo-900/20' : 'bg-white border border-zinc-200 text-zinc-500 hover:text-zinc-900'"
                        class="px-6 py-2.5 text-[10px] font-black uppercase tracking-widest rounded-sm transition-all whitespace-nowrap">
                        Catalog
                    </button>
                    <button
                        @click="showDealsView = true; selectedCategory = null"
                        :class="showDealsView ? 'bg-amber-500 text-white shadow-lg shadow-amber-900/20 border-amber-500' : 'bg-white border border-zinc-200 text-zinc-500 hover:text-zinc-900'"
                        class="px-6 py-2.5 text-[10px] font-black uppercase tracking-widest rounded-sm transition-all whitespace-nowrap">
                        🔥 Today's Deals
                    </button>
                    <template x-for="category in categories" :key="category.id">
                        <button
                            @click="selectedCategory = category.id; showDealsView = false"
                            :class="selectedCategory === category.id ? 'bg-indigo-600 text-white shadow-lg shadow-indigo-900/20' : 'bg-white border border-zinc-200 text-zinc-500 hover:text-zinc-900'"
                            class="px-6 py-2.5 text-[10px] font-black uppercase tracking-widest rounded-sm transition-all whitespace-nowrap"
                            x-text="category.name">
                        </button>
                    </template>
                </div>

                <div class="flex items-center space-x-4 flex-shrink-0 ml-4">
                    <button @click="showRunningOrdersModal = true" class="h-10 px-4 bg-white border border-zinc-200 rounded-sm flex items-center space-x-3 hover:border-indigo-600 transition-all group">
                        <div class="w-2 h-2 rounded-full bg-indigo-600 animate-pulse"></div>
                        <span class="text-[9px] font-black text-zinc-500 group-hover:text-zinc-900 uppercase tracking-widest">Active Buffers</span>
                    </button>
                </div>
            </div>

            <!-- Catalog Content -->
            <div class="p-8 flex-1 overflow-y-auto no-scrollbar" @click="if($event.target === $el) { selectedCategory = null; showDealsView = false; }">
                <div class="flex flex-col md:flex-row md:items-center justify-between mb-8 gap-4" x-show="!showDealsView">
                    <div class="relative w-full max-w-lg">
                        <input type="text" x-model="search" placeholder="Quick Search (F2)"
                            class="w-full pl-12 pr-4 py-4 bg-white border border-zinc-200 rounded-sm text-xs font-black uppercase tracking-widest text-zinc-900 focus:outline-hidden focus:border-indigo-600 transition-all shadow-sm">
                        <svg class="w-5 h-5 absolute left-4 top-4 text-zinc-400" 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>
                    </div>
                    <div class="flex items-center space-x-3">
                        <span class="text-[9px] font-black text-zinc-400 uppercase tracking-widest">Layout</span>
                        <div class="flex bg-white border border-zinc-200 rounded-sm p-1 shadow-xs">
                            <button @click="layout = 'grid'" :class="layout === 'grid' ? 'bg-zinc-100 text-zinc-900 shadow-xs' : 'text-zinc-400 hover:text-zinc-600'" class="px-4 py-1.5 rounded-sm text-[9px] font-black uppercase transition-all">Grid</button>
                            <button @click="layout = 'list'" :class="layout === 'list' ? 'bg-zinc-100 text-zinc-900 shadow-xs' : 'text-zinc-400 hover:text-zinc-600'" class="px-4 py-1.5 rounded-sm text-[9px] font-black uppercase transition-all">List</button>
                        </div>
                    </div>
                </div>

                <!-- Grid Layout -->
                <div x-show="layout === 'grid' && !showDealsView" class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6">
                    <template x-for="item in filteredItems" :key="item.id">
                        <button
                            @click="addToCart(item)"
                            class="bg-white border border-zinc-200 rounded-sm p-5 text-left hover:border-indigo-600 hover:shadow-xl transition-all relative group flex flex-col h-full min-h-[160px] shadow-xs">
                            <div class="flex justify-between items-start mb-4">
                                <div class="w-4 h-4 border-2 p-0.5 flex items-center justify-center rounded-sm" :class="item.is_veg ? 'border-emerald-600' : 'border-rose-600'">
                                    <div class="w-1.5 h-1.5 rounded-full" :class="item.is_veg ? 'bg-emerald-600' : 'bg-rose-600'"></div>
                                </div>
                                <span class="text-[11px] font-black text-zinc-900 tracking-tighter" x-text="'₹' + parseFloat(item.price).toFixed(2)"></span>
                            </div>
                            <h4 class="text-[11px] font-black text-zinc-900 leading-snug mb-2 uppercase tracking-tight line-clamp-2" x-text="item.name"></h4>
                            <p class="text-[8px] text-zinc-400 font-black uppercase tracking-widest mt-auto" x-text="item.category ? item.category.name : 'MISC'"></p>

                            <template x-if="item.variants && item.variants.length > 0">
                                <div class="absolute inset-0 bg-indigo-600 flex flex-col items-center justify-center opacity-0 group-hover:opacity-100 transition-all rounded-sm p-4">
                                    <span class="text-[10px] font-black text-white uppercase tracking-widest mb-4">Select Specification</span>
                                    <div class="flex flex-wrap justify-center gap-2">
                                        <template x-for="variant in item.variants">
                                            <div @click.stop="addToCart(item, variant)" class="px-3 py-1.5 bg-white text-indigo-600 text-[9px] font-black uppercase rounded-sm hover:bg-zinc-100 shadow-xl transition-all" x-text="variant.name"></div>
                                        </template>
                                    </div>
                                </div>
                            </template>
                        </button>
                    </template>
                </div>

                <!-- Deals Grid -->
                <div x-show="showDealsView" class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6">
                    <template x-for="deal in deals" :key="deal.id">
                        <button
                            @click="startDealSelection(deal)"
                            class="bg-white border border-zinc-200 rounded-sm p-5 text-left hover:border-amber-500 hover:shadow-xl transition-all relative group flex flex-col h-full min-h-[160px] shadow-xs">
                            <div class="flex justify-between items-start mb-4">
                                <div class="px-2 py-1 bg-amber-500 text-white text-[7px] font-black uppercase rounded-sm">Today's Deal</div>
                                <span class="text-[11px] font-black text-zinc-900 tracking-tighter" x-text="'₹' + parseFloat(deal.price).toFixed(2)"></span>
                            </div>
                            <h4 class="text-[11px] font-black text-zinc-900 leading-snug mb-2 uppercase tracking-tight line-clamp-2" x-text="deal.name"></h4>
                            <p class="text-[8px] text-zinc-400 font-black uppercase tracking-widest mt-auto line-clamp-2" x-text="deal.description || 'Limited time bundle offer'"></p>
                        </button>
                    </template>
                    <template x-if="deals.length === 0">
                        <div class="col-span-full py-20 text-center opacity-30">
                            <p class="text-xs font-black uppercase tracking-widest">No active deals found</p>
                        </div>
                    </template>
                </div>

                <!-- List Layout -->
                <div x-show="layout === 'list' && !showDealsView" class="bg-white border border-zinc-200 rounded-sm overflow-hidden shadow-xs">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="bg-zinc-50 border-b border-zinc-200">
                                <th class="px-6 py-4 text-[9px] font-black text-zinc-400 uppercase tracking-widest">Type</th>
                                <th class="px-6 py-4 text-[9px] font-black text-zinc-400 uppercase tracking-widest">Item Description</th>
                                <th class="px-6 py-4 text-[9px] font-black text-zinc-400 uppercase tracking-widest">Category</th>
                                <th class="px-6 py-4 text-[9px] font-black text-zinc-400 uppercase tracking-widest">Price</th>
                                <th class="px-6 py-4 text-[9px] font-black text-zinc-400 uppercase tracking-widest text-right">Action</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-zinc-100">
                            <template x-for="item in filteredItems" :key="item.id">
                                <tr class="hover:bg-zinc-50 transition-colors group">
                                    <td class="px-6 py-4">
                                        <div class="w-3 h-3 border p-0.5 flex items-center justify-center rounded-[2px]" :class="item.is_veg ? 'border-emerald-600' : 'border-rose-600'">
                                            <div class="w-1 h-1 rounded-full" :class="item.is_veg ? 'bg-emerald-600' : 'bg-rose-600'"></div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="flex flex-col">
                                            <span class="text-[10px] font-black text-zinc-900 uppercase tracking-tight" x-text="item.name"></span>
                                            <div class="flex flex-wrap gap-1 mt-1.5" x-show="item.variants && item.variants.length > 0">
                                                <template x-for="variant in item.variants">
                                                    <button @click="addToCart(item, variant)" class="px-2 py-0.5 bg-indigo-50 text-indigo-600 text-[8px] font-black uppercase tracking-widest border border-indigo-100 rounded-sm hover:bg-indigo-600 hover:text-white transition-all" x-text="variant.name"></button>
                                                </template>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="text-[9px] font-black text-zinc-400 uppercase tracking-widest" x-text="item.category ? item.category.name : 'MISC'"></span>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="text-[10px] font-black text-zinc-900" x-text="'₹' + parseFloat(item.price).toFixed(2)"></span>
                                    </td>
                                    <td class="px-6 py-4 text-right">
                                        <button @click="addToCart(item)" class="px-4 py-2 bg-zinc-900 text-white text-[9px] font-black uppercase tracking-widest rounded-sm opacity-0 group-hover:opacity-100 transition-all hover:bg-indigo-600">
                                            Add +
                                        </button>
                                    </td>
                                </tr>
                            </template>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Transaction Stack -->
        <div class="w-full md:w-[400px] flex flex-col bg-white overflow-hidden border-l border-zinc-200 z-10 shadow-[-10px_0_30px_rgba(0,0,0,0.05)]">
            <!-- Session Context -->
            <div class="p-3 bg-white border-b border-zinc-100 space-y-3 flex-shrink-0">
                <div class="flex items-center space-x-2">
                    <button
                        @click="orderType = 'dine_in'"
                        :class="orderType === 'dine_in' ? 'bg-indigo-600 text-white shadow-lg shadow-indigo-900/20 border-indigo-600' : 'bg-zinc-50 text-zinc-400 border-zinc-200'"
                        class="flex-1 py-2 text-[9px] font-black uppercase tracking-widest rounded-sm transition-all border">Dine</button>
                    <button
                        @click="orderType = 'takeaway'"
                        :class="orderType === 'takeaway' ? 'bg-indigo-600 text-white shadow-lg shadow-indigo-900/20 border-indigo-600' : 'bg-zinc-50 text-zinc-400 border-zinc-200'"
                        class="flex-1 py-2 text-[9px] font-black uppercase tracking-widest rounded-sm transition-all border">Take</button>
                    <button
                        @click="orderType = 'delivery'"
                        :class="orderType === 'delivery' ? 'bg-indigo-600 text-white shadow-lg shadow-indigo-900/20 border-indigo-600' : 'bg-zinc-50 text-zinc-400 border-zinc-200'"
                        class="flex-1 py-2 text-[9px] font-black uppercase tracking-widest rounded-sm transition-all border">Ship</button>
                </div>

                <div x-show="orderType === 'dine_in'" class="space-y-4">
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <div class="flex items-center justify-between mb-2">
                                <label class="text-[9px] font-black text-zinc-400 uppercase tracking-widest block">Entity ID (Table)</label>
                                <button @click="showFloorMap = true" class="text-[8px] font-black text-indigo-600 uppercase tracking-widest hover:underline flex items-center transition-all">
                                    <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7"></path></svg>
                                    Visual Map
                                </button>
                            </div>
                            <select x-model="selectedTable" class="w-full bg-zinc-50 border border-zinc-200 text-zinc-900 rounded-sm px-2 py-2 text-[10px] font-black uppercase tracking-tight focus:border-indigo-600 outline-hidden appearance-none">
                                <option value="">SCAN / SELECT</option>
                                <template x-for="table in tables" :key="table.id">
                                    <option :value="table.id" :disabled="table.status === 'occupied' && selectedTable != table.id" x-text="table.name + ' - ' + table.status.toUpperCase()"></option>
                                </template>
                            </select>
                        </div>
                        <div>
                            <label class="text-[9px] font-black text-zinc-400 uppercase tracking-widest mb-2 block">Steward Assignment</label>
                            <select x-model="selectedWaiter" class="w-full bg-zinc-50 border border-zinc-200 text-zinc-900 rounded-sm px-2 py-2 text-[10px] font-black uppercase tracking-tight focus:border-indigo-600 outline-hidden appearance-none">
                                <option value="">STAFF ID</option>
                                <template x-for="waiter in waiters" :key="waiter.id">
                                    <option :value="waiter.id" x-text="waiter.name"></option>
                                </template>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div x-show="orderType === 'takeaway' || orderType === 'delivery'" class="space-y-4">
                    <div class="grid grid-cols-2 gap-4">
                        <div :class="orderType === 'delivery' ? 'col-span-1' : 'col-span-2'">
                            <label class="text-[9px] font-black text-zinc-400 uppercase tracking-widest mb-2 block">Client Identifier</label>
                            <input type="text" x-model="customerName" placeholder="NAME / REF" class="w-full bg-zinc-50 border border-zinc-200 text-zinc-900 rounded-sm px-4 py-2.5 text-[11px] font-black uppercase tracking-tight focus:border-indigo-600 outline-hidden shadow-xs">
                        </div>
                        <div x-show="orderType === 'delivery'">
                            <label class="text-[9px] font-black text-zinc-400 uppercase tracking-widest mb-2 block">Contact</label>
                            <input type="text" x-model="customerPhone" placeholder="MOBILE" class="w-full bg-zinc-50 border border-zinc-200 text-zinc-900 rounded-sm px-4 py-2.5 text-[11px] font-black uppercase tracking-tight focus:border-indigo-600 outline-hidden shadow-xs">
                        </div>
                    </div>
                    <div x-show="orderType === 'delivery'">
                        <label class="text-[9px] font-black text-zinc-400 uppercase tracking-widest mb-2 block">Fulfillment Address</label>
                        <textarea x-model="deliveryAddress" rows="2" placeholder="STREET, LANDMARK, CITY" class="w-full bg-zinc-50 border border-zinc-200 text-zinc-900 rounded-sm px-4 py-3 text-[11px] font-black uppercase tracking-tight focus:border-indigo-600 outline-hidden resize-none shadow-xs"></textarea>
                    </div>
                </div>
            </div>

            <!-- Cart Ledger -->
            <div class="flex-1 overflow-y-auto no-scrollbar px-4 py-2 bg-zinc-50/30">
                <div class="flex items-center justify-between py-2 border-b border-zinc-100 mb-2 sticky top-0 bg-white/80 backdrop-blur-md z-10 px-2 rounded-sm">
                    <span class="text-[9px] font-black text-zinc-900 uppercase tracking-widest">Transaction Ledger</span>
                    <button @click="cart = cart.filter(i => isItemLocked(i)); if(cart.some(i => isItemLocked(i))) { /* keep locked items */ } else { cart = []; }" class="text-[8px] font-black text-rose-500 uppercase tracking-widest hover:underline">Flush Stack</button>
                </div>

                <div class="space-y-2">
                    <template x-for="(item, index) in cart" :key="index">
                        <div class="flex items-center justify-between group bg-white p-3 rounded-sm border border-zinc-100 hover:border-indigo-200 transition-all">
                            <div class="flex-1 min-w-0 pr-4">
                                <div class="flex items-center space-x-2 mb-0.5">
                                    <h5 class="text-[11px] font-black text-zinc-900 uppercase tracking-tight truncate" x-text="item.name"></h5>
                                    <template x-if="getItemStatus(item) === 'served'">
                                        <span class="px-1.5 py-0.5 bg-blue-100 text-blue-600 text-[7px] font-black uppercase rounded-xs">Served</span>
                                    </template>
                                    <template x-if="getItemStatus(item) === 'ready'">
                                        <span class="px-1.5 py-0.5 bg-emerald-100 text-emerald-600 text-[7px] font-black uppercase rounded-xs">Ready</span>
                                    </template>
                                    <template x-if="getItemStatus(item) === 'preparing'">
                                        <span class="px-1.5 py-0.5 bg-amber-100 text-amber-600 text-[7px] font-black uppercase rounded-xs">Prep</span>
                                    </template>
                                </div>
                                <div class="flex items-center space-x-2">
                                    <p class="text-[9px] text-zinc-400 font-bold uppercase" x-text="'₹' + parseFloat(item.price).toFixed(2)"></p>
                                    <template x-if="item.variant">
                                        <span class="text-[8px] text-zinc-300 font-black uppercase tracking-widest" x-text="'/ ' + item.variant.name"></span>
                                    </template>
                                </div>
                            </div>

                            <div class="flex items-center space-x-3">
                                <div class="flex items-center bg-zinc-50 border border-zinc-100 rounded-sm overflow-hidden">
                                    <button @click="decrementQty(index)" :disabled="item.qty <= getMinQty(item)" 
                                        :class="item.qty <= getMinQty(item) ? 'opacity-20 cursor-not-allowed' : 'hover:bg-rose-500 hover:text-white'"
                                        class="w-7 h-7 flex items-center justify-center text-zinc-400 transition-all text-[10px] font-black">-</button>
                                    
                                    <span class="w-8 text-center text-[11px] font-black text-zinc-900" x-text="item.qty"></span>
                                    
                                    <button @click="incrementQty(index)" 
                                        class="w-7 h-7 flex items-center justify-center text-zinc-400 hover:bg-indigo-600 hover:text-white transition-all text-[10px] font-black">+</button>
                                </div>

                                <button @click="removeFromCart(index)" :disabled="isItemLocked(item)"
                                    :class="isItemLocked(item) ? 'opacity-20 cursor-not-allowed' : 'hover:text-rose-500'"
                                    class="p-1 text-zinc-200 transition-colors">
                                    <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                </button>
                            </div>
                        </div>
                    </template>

                    <!-- Empty State -->
                    <div class="py-20 text-center" x-show="cart.length === 0">
                        <svg class="w-16 h-16 mx-auto text-zinc-200 mb-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"></path></svg>
                        <p class="text-[10px] font-black uppercase tracking-widest text-zinc-300">Ledger is empty</p>
                    </div>
                </div>
            </div>

            <!-- Checkout Hub -->
            <div class="p-4 bg-zinc-950 flex-shrink-0 relative shadow-[0_-20px_40px_rgba(0,0,0,0.1)]">
                <div class="space-y-1.5 mb-2 border-b border-zinc-800 pb-2 relative group cursor-pointer" @click="showDiscountModal = true">
                    <div class="absolute inset-0 bg-white/5 opacity-0 group-hover:opacity-100 transition-opacity rounded-sm -m-1 p-1"></div>
                    <div class="flex justify-between text-[10px] font-black uppercase tracking-widest text-zinc-500">
                        <span>Gross Value</span>
                        <span class="text-zinc-400" x-text="'₹' + subtotal.toFixed(2)"></span>
                    </div>
                    <div class="flex justify-between text-[10px] font-black uppercase tracking-widest text-zinc-500">
                        <span>Tax (GST 5%)</span>
                        <span class="text-zinc-400" x-text="'₹' + gst.toFixed(2)"></span>
                    </div>
                    <template x-if="discountAmount > 0">
                        <div class="flex justify-between text-[10px] font-black uppercase tracking-widest text-emerald-500">
                            <span x-text="'Promotion ' + (discountType === 'percentage' ? '('+discountValue+'%)' : '(Flat)')"></span>
                            <span x-text="'- ₹' + discountAmount.toFixed(2)"></span>
                        </div>
                    </template>
                    <div class="flex justify-between items-end pt-1 border-t border-zinc-800">
                        <span class="text-[9px] font-black uppercase tracking-widest text-white">Net Payable</span>
                        <span class="text-xl font-black text-indigo-400 tracking-tighter" x-text="'₹' + total.toFixed(2)"></span>
                    </div>
                </div>
                
                <div class="grid grid-cols-2 gap-2 mb-2">
                    <button 
                        @click="holdOrder()"
                        :disabled="isProcessing"
                        class="py-2 bg-zinc-900 text-zinc-500 text-[10px] font-black uppercase tracking-widest rounded-sm hover:text-white hover:border-zinc-700 transition-all border border-zinc-800">
                        Hold
                    </button>
                    <button 
                        @click="printKot()"
                        :disabled="isProcessing"
                        class="py-2 bg-white text-zinc-950 text-[10px] font-black uppercase tracking-widest rounded-sm hover:bg-zinc-200 transition-all border border-white">
                        KOT
                    </button>
                </div>
                <button
                    @click="openSettlement()"
                    :disabled="cart.length === 0 || isProcessing"
                    :class="cart.length === 0 ? 'opacity-30 cursor-not-allowed' : 'hover:bg-indigo-500 active:scale-[0.98]'"
                    class="w-full py-3 bg-indigo-600 text-white text-[10px] font-black uppercase tracking-widest rounded-sm transition-all shadow-2xl shadow-indigo-900/40">
                    Settle Transaction (F12)
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<style>
    .no-scrollbar::-webkit-scrollbar { display: none; }
    .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
</style>
<script>
    function posApp() {
        return {
            categories: [],
            items: [],
            tables: [],
            waiters: [],
            deals: [],
            cart: [],
            search: '',
            layout: 'grid',
            selectedCategory: null,
            showDealsView: false,
            selectedTable: '',
            selectedWaiter: '',
            orderType: 'dine_in',
            customerName: '',
            customerPhone: '',
            deliveryAddress: '',
            
            orderId: null,
            isProcessing: false,
            
            showDiscountModal: false,
            showSettlementModal: false,
            showRunningOrdersModal: false,
            showVariantModal: false,
            showDealModal: false,
            showFloorMap: false,
            isEditLayoutMode: false,
            draggedTable: null,
            showSuccessModal: false,
            selectedItemForVariants: null,
            activeDeal: null,
            currentSlotIndex: 0,
            dealSelections: [],
            discountType: 'fixed',
            discountValue: 0,
            
            paymentMethod: 'cash',
            splitCash: 0,
            splitCard: 0,
            splitUpi: 0,
            
            activeOrders: [],

            async init() {
                await this.fetchData();
                
                // Keyboard shortcuts
                window.addEventListener('keydown', (e) => {
                    if (e.key === 'F2') {
                        e.preventDefault();
                        document.querySelector('input[x-model="search"]').focus();
                    }
                    if (e.key === 'F12') {
                        e.preventDefault();
                        this.openSettlement();
                    }
                });
            },

            async saveLayout() {
                const layoutData = this.tables.map(t => ({
                    id: t.id,
                    pos_x: t.pos_x || 0,
                    pos_y: t.pos_y || 0
                }));

                try {
                    const res = await fetch('{{ route("biller.api.tables.layout") }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        },
                        body: JSON.stringify({ tables: layoutData })
                    });
                    
                    if (res.ok) {
                        this.isEditLayoutMode = false;
                        alert('Layout saved successfully!');
                    }
                } catch (e) {
                    alert('Failed to save layout');
                }
            },

            handleDragStart(e, table) {
                if (!this.isEditLayoutMode) return;
                this.draggedTable = table;
                const rect = e.currentTarget.getBoundingClientRect();
                this.dragOffset = {
                    x: e.clientX - rect.left,
                    y: e.clientY - rect.top
                };
            },

            handleDrag(e) {
                if (!this.draggedTable || !this.isEditLayoutMode) return;
                const container = document.getElementById('floor-map-container');
                const rect = container.getBoundingClientRect();
                
                let newX = e.clientX - rect.left - this.dragOffset.x;
                let newY = e.clientY - rect.top - this.dragOffset.y;

                // Snap to grid (10px)
                newX = Math.round(newX / 10) * 10;
                newY = Math.round(newY / 10) * 10;

                // Bounds check
                newX = Math.max(0, Math.min(newX, 1100));
                newY = Math.max(0, Math.min(newY, 700));

                this.draggedTable.pos_x = newX;
                this.draggedTable.pos_y = newY;
            },

            handleDragEnd() {
                this.draggedTable = null;
            },

            async fetchData() {
                try {
                    const [cats, items, tables, waiters] = await Promise.all([
                        fetch('{{ route('biller.api.categories') }}').then(res => res.json()),
                        fetch('{{ route('biller.api.items') }}').then(res => res.json()),
                        fetch('{{ route('biller.api.tables') }}').then(res => res.json()),
                        fetch('{{ route('biller.api.waiters') }}').then(res => res.json())
                    ]);

                    this.categories = cats;
                    this.items = items;
                    this.tables = tables;
                    this.waiters = waiters;
                    await this.fetchDeals();
                } catch (error) {
                    console.error('Failed to fetch POS data:', error);
                }
                await this.fetchActiveOrders();
            },

            async fetchActiveOrders() {
                try {
                    const res = await fetch('{{ route("biller.api.orders.active") }}');
                    this.activeOrders = await res.json();
                } catch (error) {
                    console.error('Failed to fetch active orders:', error);
                }
            },

            async fetchDeals() {
                try {
                    const res = await fetch('{{ route("biller.api.deals") }}');
                    this.deals = await res.json();
                } catch (error) {
                    console.error('Failed to fetch deals:', error);
                }
            },

            get filteredItems() {
                return this.items.filter(item => {
                    const matchesSearch = item.name.toLowerCase().includes(this.search.toLowerCase());
                    const matchesCategory = this.selectedCategory === null || item.category_id === this.selectedCategory;
                    return matchesSearch && matchesCategory;
                });
            },

            startDealSelection(deal) {
                this.activeDeal = JSON.parse(JSON.stringify(deal));
                this.currentSlotIndex = 0;
                this.dealSelections = [];
                this.showDealModal = true;
            },

            selectDealItem(item, variant = null) {
                this.dealSelections[this.currentSlotIndex] = {
                    slot_id: this.activeDeal.slots[this.currentSlotIndex].id,
                    item_id: item.id,
                    variant_id: variant ? variant.id : null,
                    name: item.name + (variant ? ' (' + variant.name + ')' : '')
                };

                if (this.currentSlotIndex < this.activeDeal.slots.length - 1) {
                    this.currentSlotIndex++;
                } else {
                    this.finalizeDeal();
                }
            },

            finalizeDeal() {
                const deal = this.activeDeal;
                const selections = this.dealSelections;
                
                // Add to cart with a unique ID for this specific deal instance
                this.cart.push({
                    id: 'deal_' + deal.id + '_' + Date.now(),
                    deal_id: deal.id,
                    name: deal.name + ' (' + selections.map(s => s.name).join(' + ') + ')',
                    price: parseFloat(deal.price),
                    qty: 1,
                    selections: selections
                });

                this.showDealModal = false;
                this.activeDeal = null;
                this.dealSelections = [];
                this.showDealsView = false;
            },

            addToCart(item, variant = null) {
                if (!variant && item.variants && item.variants.length > 0) {
                    this.selectedItemForVariants = item;
                    this.showVariantModal = true;
                    return;
                }

                const price = variant ? parseFloat(variant.dine_in_price || item.price) : parseFloat(item.price);
                const name = item.name;

                const existingIndex = this.cart.findIndex(i => i.id === item.id && (variant ? i.variant_id === variant.id : !i.variant_id));

                if (existingIndex > -1) {
                    this.cart[existingIndex].qty++;
                } else {
                    this.cart.push({
                        id: item.id,
                        variant_id: variant ? variant.id : null,
                        variant: variant,
                        name: name,
                        price: price,
                        qty: 1
                    });
                }

                this.showVariantModal = false;
                this.selectedItemForVariants = null;
            },

            removeFromCart(index) {
                this.cart.splice(index, 1);
            },

            incrementQty(index) {
                this.cart[index].qty++;
            },

            decrementQty(index) {
                if (this.cart[index].qty > this.getMinQty(this.cart[index])) {
                    this.cart[index].qty--;
                }
            },
            
            formatCurrency(amount) {
                return '₹' + parseFloat(amount || 0).toFixed(2);
            },

            get subtotal() {
                return this.cart.reduce((sum, item) => sum + (item.price * item.qty), 0);
            },
            
            get gst() {
                return this.subtotal * 0.05; // 5% GST
            },
            
            get discountAmount() {
                if (this.discountType === 'percentage') {
                    return this.subtotal * (this.discountValue / 100);
                }
                return parseFloat(this.discountValue || 0);
            },
            
            get total() {
                return Math.max(0, (this.subtotal + this.gst) - this.discountAmount);
            },

            getPayload() {
                return {
                    order_id: this.orderId,
                    order_type: this.orderType,
                    table_id: this.selectedTable,
                    waiter_id: this.selectedWaiter,
                    customer_name: this.customerName,
                    customer_phone: this.customerPhone,
                    delivery_address: this.deliveryAddress,
                    cart: this.cart,
                    subtotal: this.subtotal,
                    gst_amount: this.gst,
                    discount_type: this.discountType,
                    discount_value: this.discountValue,
                    discount_amount: this.discountAmount,
                    grand_total: this.total,
                    payment_method: this.paymentMethod,
                    split_cash: this.splitCash,
                    split_card: this.splitCard,
                    split_upi: this.splitUpi
                };
            },

            getMinQty(item) {
                if (!item.kot_items || item.kot_items.length === 0) return 0;
                return item.kot_items.reduce((sum, k) => sum + parseInt(k.quantity), 0);
            },

            getItemStatus(item) {
                if (!item.kot_items || item.kot_items.length === 0) return null;
                const statuses = item.kot_items.map(k => k.status);
                if (statuses.every(s => s === 'served')) return 'served';
                if (statuses.every(s => s === 'ready' || s === 'served')) return 'ready';
                if (statuses.some(s => s === 'preparing' || s === 'ready')) return 'preparing';
                return 'pending';
            },

            isItemLocked(item) {
                return item.kot_items && item.kot_items.length > 0;
            },

            async submitOrder(action) {
                if (this.cart.length === 0) return alert('Cart is empty!');
                if (this.orderType === 'dine_in' && !this.selectedTable) return alert('Please select a table!');
                
                this.isProcessing = true;
                
                let endpoint = '';
                if (action === 'hold') endpoint = '{{ route("biller.api.orders.hold") }}';
                if (action === 'kot') endpoint = '{{ route("biller.api.orders.kot") }}';
                
                try {
                    const res = await fetch(endpoint, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        },
                        body: JSON.stringify(this.getPayload())
                    });
                    
                    const data = await res.json();
                    
                    if (data.success) {
                        this.orderId = data.order_id;
                        
                        if (action === 'kot') {
                            this.showSuccessModal = true;
                            // Reset cart and context
                            this.cart = [];
                            this.orderId = null;
                            this.selectedTable = '';
                            this.selectedWaiter = '';
                            this.customerName = '';
                            this.customerPhone = '';
                            this.deliveryAddress = '';
                            
                            setTimeout(() => { this.showSuccessModal = false; }, 2000);
                        }
                        
                        await this.fetchData(); // Refresh tables and active orders
                    } else {
                        alert('Something went wrong!');
                    }
                } catch (e) {
                    console.error(e);
                    alert('Failed to connect to server.');
                } finally {
                    this.isProcessing = false;
                }
            },
            
            async holdOrder() {
                await this.submitOrder('hold');
            },
            
            async printKot() {
                await this.submitOrder('kot');
            },
            
            openSettlement() {
                if (this.cart.length === 0) return alert('Cart is empty!');
                if (this.orderType === 'dine_in' && !this.selectedTable) return alert('Please select a table!');
                this.showSettlementModal = true;
            },
            
            async payAndSettle() {
                if (this.cart.length === 0) return alert('Cart is empty!');
                if (!this.orderId) {
                    // Automatically hold the order if not already held
                    await this.holdOrder();
                }
                
                if (this.paymentMethod === 'split') {
                    const splitTotal = parseFloat(this.splitCash || 0) + parseFloat(this.splitCard || 0) + parseFloat(this.splitUpi || 0);
                    if (Math.abs(splitTotal - this.total) > 0.1) {
                        return alert('Split payment amounts must equal the Grand Total!');
                    }
                }
                
                this.isProcessing = true;
                
                try {
                    const res = await fetch('{{ route("biller.api.orders.settle") }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        },
                        body: JSON.stringify(this.getPayload())
                    });
                    
                    const data = await res.json();
                    
                    if (data.success) {
                        // alert('Order settled successfully!');
                        this.showSettlementModal = false;
                        
                        // Reset POS
                        this.cart = [];
                        this.orderId = null;
                        this.selectedTable = '';
                        this.selectedWaiter = '';
                        this.customerName = '';
                        this.customerPhone = '';
                        this.deliveryAddress = '';
                        this.discountType = 'fixed';
                        this.discountValue = 0;
                        this.paymentMethod = 'cash';
                        this.splitCash = 0;
                        this.splitCard = 0;
                        this.splitUpi = 0;
                        
                        await this.fetchData(); // Refresh tables and active orders
                    }
                } catch (e) {
                    console.error(e);
                    alert('Failed to settle order.');
                } finally {
                    this.isProcessing = false;
                }
            },
            
            resumeOrder(order) {
                if (this.cart.length > 0) {
                    if (!confirm("You have unsaved items in your cart. Are you sure you want to clear them and load the selected order?")) {
                        return;
                    }
                }
                
                this.orderId = order.id;
                this.selectedTable = order.table_id || '';
                this.selectedWaiter = order.waiter_id || '';
                this.orderType = order.order_type || 'dine_in';
                this.customerName = order.customer_name || '';
                this.customerPhone = order.customer_phone || '';
                this.deliveryAddress = order.delivery_address || '';
                
                // Populate cart from order.items
                this.cart = order.items.map(i => ({
                    id: i.item_id,
                    variant_id: i.variant_id,
                    variant: i.variant,
                    name: i.item ? i.item.name : i.name,
                    price: parseFloat(i.price),
                    qty: parseInt(i.quantity),
                    kot_items: i.kot_items || []
                }));
                
                this.showRunningOrdersModal = false;
            }
        }
    }
</script>
@endpush
