<x-tenant-layout>
    <div class="h-[calc(100vh-4rem)] flex flex-col bg-[#F3F3F3] font-sans overflow-hidden text-[#323130]" 
         x-data="sellApp()" 
         @keydown.f1.window.prevent="$refs.productSearch.focus()"
         @keydown.f2.window.prevent="showCustomerModal = true"
         @keydown.f8.window.prevent="holdSale()"
         @keydown.f10.window.prevent="processCheckout()"
         @keydown.escape.window="closeModals()">

        <!-- Top Status Bar -->
        <div class="h-10 bg-[#2B2B2B] text-white flex items-center justify-between px-4 text-xs font-semibold">
            <div class="flex items-center space-x-6">
                <div class="flex items-center"><span class="text-green-400 mr-2">●</span> ONLINE</div>
                <div>TERMINAL: <span class="text-gray-400">POS-01</span></div>
                <div>USER: <span class="text-gray-400">{{ Auth::user()->name }}</span></div>
            </div>
            <div class="flex items-center space-x-4 uppercase tracking-wider">
                <span class="bg-[#107C10] px-2 py-0.5 rounded text-[10px]">F1: Search</span>
                <span class="bg-[#107C10] px-2 py-0.5 rounded text-[10px]">F2: Customer</span>
                <span class="bg-[#107C10] px-2 py-0.5 rounded text-[10px]">F8: Hold</span>
                <span class="bg-[#107C10] px-2 py-0.5 rounded text-[10px]">F10: Pay</span>
            </div>
        </div>

        <div class="flex-1 flex overflow-hidden">
            <!-- Left Column: Product Selection -->
            <div class="flex-1 flex flex-col p-4 space-y-4 overflow-hidden">
                <!-- Search and Filters -->
                <div class="bg-white p-3 shadow-sm border border-gray-200 flex space-x-4">
                    <div class="flex-1 relative">
                        <span class="absolute left-3 top-2.5 text-gray-400">🔍</span>
                        <input type="text" 
                               x-ref="productSearch"
                               x-model="searchQuery" 
                               @input.debounce.300ms="filterProducts()"
                               placeholder="Search Product (F1)..." 
                               class="w-full pl-10 pr-4 py-2 border-gray-300 focus:border-[#107C10] focus:ring-0 text-sm">
                    </div>
                    <select x-model="selectedCategory" @change="filterProducts()" class="w-48 border-gray-300 focus:border-[#107C10] focus:ring-0 text-sm">
                        <option value="">All Categories</option>
                        @foreach($categories as $category)
                            <option value="{{ $category->id }}">{{ $category->name }}</option>
                        @endforeach
                    </select>
                </div>

                <!-- Product List (Compact Grid, No Images) -->
                <div class="flex-1 overflow-y-auto">
                    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-2">
                        <template x-for="product in filteredProducts" :key="product.id">
                            <div @click="addToCart(product)" 
                                 class="bg-white border border-gray-200 p-3 cursor-pointer hover:border-[#107C10] hover:shadow-md transition-all group relative">
                                <div class="text-[10px] text-gray-500 font-bold uppercase tracking-tighter mb-1" x-text="product.category_name"></div>
                                <div class="text-sm font-bold text-[#323130] leading-tight mb-2 h-10 overflow-hidden" x-text="product.name"></div>
                                <div class="flex justify-between items-end mt-auto">
                                    <div class="text-[#107C10] font-black text-lg" x-text="'$' + product.price.toFixed(2)"></div>
                                    <div class="text-[10px] text-gray-400 font-bold" x-text="product.stock + ' IN STOCK'"></div>
                                </div>
                                <div x-show="product.has_variants" class="absolute top-2 right-2">
                                    <span class="bg-blue-100 text-blue-800 text-[8px] px-1 py-0.5 rounded font-bold">VARIANTS</span>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>

                <!-- Bottom Shortcuts/Menu -->
                <div class="h-12 bg-white border border-gray-200 flex items-center px-4 space-x-2">
                    <button @click="showHoldModal = true" class="px-4 py-2 text-[11px] font-bold bg-gray-100 hover:bg-gray-200 transition">HELD SALES (<span x-text="heldSales.length"></span>)</button>
                    <button @click="window.print()" class="px-4 py-2 text-[11px] font-bold bg-gray-100 hover:bg-gray-200 transition">PRINT PREVIEW</button>
                    <button @click="location.reload()" class="px-4 py-2 text-[11px] font-bold bg-gray-100 hover:bg-gray-200 transition">REFRESH (F5)</button>
                </div>
            </div>

            <!-- Right Column: Cart & Summary -->
            <div class="w-[450px] bg-white border-l border-gray-200 flex flex-col shadow-2xl">
                <!-- Customer Section -->
                <div class="p-4 border-b border-gray-100 bg-gray-50 flex items-center justify-between">
                    <div class="flex items-center space-x-3">
                        <div class="w-10 h-10 rounded-full bg-[#107C10] flex items-center justify-center text-white font-bold">
                            <span x-text="selectedCustomer ? selectedCustomer.name.charAt(0) : 'G'"></span>
                        </div>
                        <div>
                            <div class="text-xs font-bold text-gray-500 uppercase tracking-tighter">Customer</div>
                            <div class="text-sm font-black" x-text="selectedCustomer ? selectedCustomer.name : 'Walk-in Customer'"></div>
                        </div>
                    </div>
                    <button @click="showCustomerModal = true" class="p-2 hover:bg-gray-200 rounded-full transition">
                        <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="M12 4v16m8-8H4"></path></svg>
                    </button>
                </div>

                <!-- Cart Items Table -->
                <div class="flex-1 overflow-y-auto">
                    <table class="w-full text-left border-collapse">
                        <thead class="sticky top-0 bg-white shadow-sm z-10">
                            <tr class="text-[10px] font-black text-gray-400 uppercase tracking-widest border-b">
                                <th class="p-4">Item</th>
                                <th class="p-4 text-center">Qty</th>
                                <th class="p-4 text-right">Price</th>
                                <th class="p-4 text-right">Total</th>
                                <th class="p-4"></th>
                            </tr>
                        </thead>
                        <tbody class="text-sm">
                            <template x-for="(item, index) in cart" :key="index">
                                <tr class="border-b border-gray-50 hover:bg-gray-50 group">
                                    <td class="p-4">
                                        <div class="font-bold text-[#323130]" x-text="item.name"></div>
                                        <div class="flex items-center mt-1 space-x-2">
                                            <!-- Unit Selector -->
                                            <select x-model="item.product_unit_id" @change="updateItemPrice(index)" class="text-[9px] py-0 border-none bg-gray-100 rounded font-bold focus:ring-0">
                                                <template x-for="unit in item.available_units" :key="unit.id">
                                                    <option :value="unit.id" x-text="unit.name"></option>
                                                </template>
                                            </select>
                                            <!-- Item Discount -->
                                            <button @click="openItemDiscount(index)" class="text-[9px] font-bold text-blue-600 hover:underline">DISCOUNT</button>
                                        </div>
                                    </td>
                                    <td class="p-4 text-center">
                                        <div class="flex items-center justify-center space-x-2">
                                            <button @click="updateQty(index, -1)" class="w-6 h-6 border border-gray-300 flex items-center justify-center hover:bg-gray-100">-</button>
                                            <input type="number" x-model.number="item.quantity" @input="calculateTotals()" class="w-10 text-center border-none p-0 focus:ring-0 font-bold bg-transparent">
                                            <button @click="updateQty(index, 1)" class="w-6 h-6 border border-gray-300 flex items-center justify-center hover:bg-gray-100">+</button>
                                        </div>
                                    </td>
                                    <td class="p-4 text-right font-bold" x-text="'$' + item.price.toFixed(2)"></td>
                                    <td class="p-4 text-right font-black text-[#107C10]" x-text="'$' + ((item.price * item.quantity) - (item.discount || 0)).toFixed(2)"></td>
                                    <td class="p-4 text-right">
                                        <button @click="removeFromCart(index)" class="text-red-400 opacity-0 group-hover:opacity-100 transition">✕</button>
                                    </td>
                                </tr>
                            </template>
                        </tbody>
                    </table>
                    <template x-if="cart.length === 0">
                        <div class="h-full flex flex-col items-center justify-center text-gray-400 p-10 opacity-50">
                            <svg class="w-16 h-16 mb-4" 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>
                            <div class="text-sm font-bold uppercase">Cart is Empty</div>
                        </div>
                    </template>
                </div>

                <!-- Summary & Checkout -->
                <div class="p-6 bg-white border-t-2 border-gray-100 space-y-4 shadow-[0_-10px_20px_-10px_rgba(0,0,0,0.1)]">
                    <div class="space-y-2">
                        <div class="flex justify-between text-xs font-bold text-gray-500">
                            <span>SUBTOTAL</span>
                            <span x-text="'$' + subtotal.toFixed(2)"></span>
                        </div>
                        <div class="flex justify-between text-xs font-bold text-gray-500">
                            <span>TOTAL DISCOUNT</span>
                            <span class="text-red-500" x-text="'-$' + totalDiscount.toFixed(2)"></span>
                        </div>
                        <div class="flex justify-between items-center pt-2 border-t border-gray-100">
                            <span class="text-sm font-black">TOTAL PAYABLE</span>
                            <span class="text-3xl font-black text-[#107C10]" x-text="'$' + total.toFixed(2)"></span>
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-2">
                        <button @click="holdSale()" :disabled="cart.length === 0" class="py-4 bg-[#F3F3F3] text-[#323130] font-black text-xs uppercase tracking-widest hover:bg-gray-200 transition disabled:opacity-50">Hold Sale (F8)</button>
                        <button @click="processCheckout()" :disabled="cart.length === 0" class="py-4 bg-[#107C10] text-white font-black text-xs uppercase tracking-widest hover:bg-[#0E6C0E] transition shadow-lg shadow-green-100 disabled:opacity-50">Checkout (F10)</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modals -->
        <!-- Customer Modal -->
        <div x-show="showCustomerModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" x-cloak>
            <div class="bg-white w-full max-w-md shadow-2xl">
                <div class="p-4 border-b flex justify-between items-center bg-gray-50">
                    <h3 class="font-black uppercase tracking-tighter">Select Customer</h3>
                    <button @click="showCustomerModal = false" class="text-gray-400 hover:text-black">✕</button>
                </div>
                <div class="p-4 space-y-4">
                    <input type="text" x-model="customerSearch" placeholder="Search customer..." class="w-full border-gray-300 focus:border-[#107C10] focus:ring-0 text-sm">
                    <div class="max-h-60 overflow-y-auto border border-gray-100">
                        <template x-for="customer in filteredCustomers" :key="customer.id">
                            <div @click="selectCustomer(customer)" class="p-3 hover:bg-gray-50 cursor-pointer flex justify-between items-center border-b last:border-0">
                                <div>
                                    <div class="text-sm font-bold" x-text="customer.name"></div>
                                    <div class="text-[10px] text-gray-500" x-text="customer.contact"></div>
                                </div>
                                <span x-show="customer.is_sub_dealer" class="text-[8px] bg-blue-100 text-blue-800 px-1 font-bold rounded">SUB-DEALER</span>
                            </div>
                        </template>
                    </div>
                    <button class="w-full py-2 bg-[#107C10] text-white font-bold text-xs uppercase tracking-widest">+ Add New Customer</button>
                </div>
            </div>
        </div>

        <!-- Item Discount Modal -->
        <div x-show="showItemDiscountModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" x-cloak>
            <div class="bg-white w-full max-w-xs shadow-2xl">
                <div class="p-4 border-b flex justify-between items-center bg-gray-50">
                    <h3 class="font-black uppercase tracking-tighter text-xs">Item Discount</h3>
                    <button @click="showItemDiscountModal = false" class="text-gray-400 hover:text-black">✕</button>
                </div>
                <div class="p-4 space-y-4">
                    <div class="flex space-x-2">
                        <button @click="discountType = 'fixed'" :class="discountType === 'fixed' ? 'bg-[#107C10] text-white' : 'bg-gray-100'" class="flex-1 py-2 text-[10px] font-bold uppercase">Fixed ($)</button>
                        <button @click="discountType = 'percent'" :class="discountType === 'percent' ? 'bg-[#107C10] text-white' : 'bg-gray-100'" class="flex-1 py-2 text-[10px] font-bold uppercase">Percent (%)</button>
                    </div>
                    <input type="number" x-model.number="discountValue" class="w-full border-gray-300 focus:border-[#107C10] focus:ring-0 text-center font-black text-2xl py-4">
                    <button @click="applyItemDiscount()" class="w-full py-3 bg-[#107C10] text-white font-black text-xs uppercase tracking-widest">Apply Discount</button>
                </div>
            </div>
        </div>

        <!-- Checkout/Payment Modal -->
        <div x-show="showCheckoutModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" x-cloak>
            <div class="bg-white w-full max-w-2xl shadow-2xl flex flex-col md:flex-row">
                <div class="flex-1 p-8 bg-gray-50 border-r border-gray-100">
                    <h3 class="font-black uppercase tracking-tighter text-xl mb-6">Payment</h3>
                    <div class="space-y-4">
                        <div class="grid grid-cols-2 gap-4">
                            <button @click="paymentMethod = 'cash'" :class="paymentMethod === 'cash' ? 'border-[#107C10] bg-green-50' : 'border-gray-200'" class="p-4 border-2 flex flex-col items-center hover:bg-gray-50 transition">
                                <span class="text-2xl mb-2">💵</span>
                                <span class="text-xs font-black uppercase">Cash</span>
                            </button>
                            <button @click="paymentMethod = 'card'" :class="paymentMethod === 'card' ? 'border-[#107C10] bg-green-50' : 'border-gray-200'" class="p-4 border-2 flex flex-col items-center hover:bg-gray-50 transition">
                                <span class="text-2xl mb-2">💳</span>
                                <span class="text-xs font-black uppercase">Card</span>
                            </button>
                        </div>
                        <div class="space-y-2">
                            <label class="text-[10px] font-black text-gray-400 uppercase">Amount Paid</label>
                            <input type="number" x-model.number="paidAmount" class="w-full border-gray-300 focus:border-[#107C10] focus:ring-0 text-3xl font-black text-right p-4">
                        </div>
                        <div class="flex justify-between items-center p-4 bg-white border border-gray-200">
                            <span class="text-xs font-black text-gray-500">CHANGE</span>
                            <span class="text-2xl font-black text-[#107C10]" x-text="'$' + Math.max(0, paidAmount - total).toFixed(2)"></span>
                        </div>
                    </div>
                </div>
                <div class="w-full md:w-72 p-8 flex flex-col justify-between">
                    <div>
                        <div class="text-[10px] font-black text-gray-400 uppercase mb-4">Summary</div>
                        <div class="space-y-2">
                            <div class="flex justify-between text-xs font-bold">
                                <span>Subtotal</span>
                                <span x-text="'$' + subtotal.toFixed(2)"></span>
                            </div>
                            <div class="flex justify-between text-xs font-bold text-red-500">
                                <span>Discount</span>
                                <span x-text="'-$' + totalDiscount.toFixed(2)"></span>
                            </div>
                            <div class="flex justify-between text-xl font-black pt-4 border-t border-gray-100">
                                <span>TOTAL</span>
                                <span x-text="'$' + total.toFixed(2)"></span>
                            </div>
                        </div>
                    </div>
                    <div class="mt-8 space-y-2">
                        <button @click="submitSale()" :disabled="paidAmount < total" class="w-full py-4 bg-[#107C10] text-white font-black text-xs uppercase tracking-widest hover:bg-[#0E6C0E] transition disabled:opacity-50">Complete Sale</button>
                        <button @click="showCheckoutModal = false" class="w-full py-4 bg-gray-100 text-gray-500 font-black text-xs uppercase tracking-widest hover:bg-gray-200 transition">Cancel</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Held Sales Modal -->
        <div x-show="showHoldModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" x-cloak>
            <div class="bg-white w-full max-w-lg shadow-2xl">
                <div class="p-4 border-b flex justify-between items-center bg-gray-50">
                    <h3 class="font-black uppercase tracking-tighter">Held Sales</h3>
                    <button @click="showHoldModal = false" class="text-gray-400 hover:text-black">✕</button>
                </div>
                <div class="p-4">
                    <div class="max-h-80 overflow-y-auto space-y-2">
                        <template x-for="(sale, index) in heldSales" :key="sale.id">
                            <div class="p-4 border border-gray-100 hover:border-[#107C10] transition flex justify-between items-center">
                                <div>
                                    <div class="text-xs font-black text-gray-400 uppercase tracking-widest" x-text="sale.time"></div>
                                    <div class="font-bold text-sm" x-text="sale.customer ? sale.customer.name : 'Walk-in Customer'"></div>
                                    <div class="text-[10px] text-gray-500" x-text="sale.items.length + ' Items'"></div>
                                </div>
                                <div class="flex items-center space-x-4">
                                    <div class="text-right">
                                        <div class="text-sm font-black text-[#107C10]" x-text="'$' + sale.total.toFixed(2)"></div>
                                    </div>
                                    <button @click="resumeSale(index)" class="px-3 py-1 bg-[#107C10] text-white text-[10px] font-black uppercase tracking-widest hover:bg-[#0E6C0E]">Resume</button>
                                </div>
                            </div>
                        </template>
                        <template x-if="heldSales.length === 0">
                            <div class="text-center py-10 text-gray-400 text-xs font-bold uppercase tracking-widest">No Held Sales</div>
                        </template>
                    </div>
                </div>
            </div>
        </div>

        <!-- Variant Selection Modal -->
        <div x-show="showVariantModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" x-cloak>
            <div class="bg-white w-full max-w-lg shadow-2xl">
                <div class="p-4 border-b flex justify-between items-center bg-gray-50">
                    <h3 class="font-black uppercase tracking-tighter" x-text="activeProduct ? activeProduct.name : 'Select Variant'"></h3>
                    <button @click="showVariantModal = false" class="text-gray-400 hover:text-black">✕</button>
                </div>
                <div class="p-4">
                    <div class="grid grid-cols-2 gap-3 max-h-96 overflow-y-auto">
                        <template x-for="variant in (activeProduct ? activeProduct.variants : [])" :key="variant.id">
                            <button @click="selectVariant(variant)" class="p-4 border-2 border-gray-100 hover:border-[#107C10] hover:bg-green-50 text-left transition flex flex-col justify-between">
                                <div class="text-sm font-black uppercase" x-text="variant.name"></div>
                                <div class="flex justify-between items-end mt-4">
                                    <div class="text-[10px] text-gray-400 font-bold uppercase" x-text="'SKU: ' + variant.sku"></div>
                                    <div class="text-lg font-black text-[#107C10]" x-text="'$' + variant.price"></div>
                                </div>
                            </button>
                        </template>
                    </div>
                </div>
            </div>
        </div>

        <!-- Receipt Print (Hidden) -->
        <div id="printReceipt" class="hidden">
            <!-- Simple Receipt Layout -->
        </div>
    </div>

    <script>
        function sellApp() {
            return {
                searchQuery: '',
                selectedCategory: '',
                products: @json($products),
                units: @json($units),
                customers: @json($customers),
                filteredProducts: [],
                cart: [],
                subtotal: 0,
                totalDiscount: 0,
                total: 0,
                
                showCustomerModal: false,
                customerSearch: '',
                selectedCustomer: null,
                
                showItemDiscountModal: false,
                activeItemIndex: null,
                discountType: 'fixed',
                discountValue: 0,
                
                showCheckoutModal: false,
                paymentMethod: 'cash',
                paidAmount: 0,
                
                showHoldModal: false,
                heldSales: [],

                showVariantModal: false,
                activeProduct: null,

                init() {
                    this.filterProducts();
                    this.paidAmount = 0;
                },

                filterProducts() {
                    this.filteredProducts = this.products.filter(p => {
                        const matchesSearch = p.name.toLowerCase().includes(this.searchQuery.toLowerCase()) || 
                                            (p.variants && p.variants.some(v => v.sku.toLowerCase().includes(this.searchQuery.toLowerCase())));
                        const matchesCategory = !this.selectedCategory || p.category_id == this.selectedCategory;
                        return matchesSearch && matchesCategory;
                    }).map(p => {
                        const mainVariant = p.variants[0] || { prices: [] };
                        const prodUnits = p.product_units || p.productUnits || [];
                        
                        // Find default sale unit
                        let saleUnit = prodUnits.find(u => u.is_sale) || prodUnits.find(u => u.is_base) || prodUnits[0];
                        
                        // Find price for that unit
                        let price = mainVariant.price || 0;
                        if (saleUnit) {
                            let priceData = mainVariant.prices ? mainVariant.prices.find(pr => pr.product_unit_id == saleUnit.id) : null;
                            if (priceData) {
                                price = parseFloat(priceData.price);
                            }
                        }

                        return {
                            ...p,
                            price: price,
                            stock: mainVariant.stock || 0,
                            variant_id: mainVariant.id || null,
                            unit_id: saleUnit ? saleUnit.id : null,
                            conversion_factor: saleUnit ? saleUnit.conversion_factor : 1,
                            category_name: p.category?.name || 'General',
                            available_units: prodUnits,
                            prices: mainVariant.prices || []
                        };
                    });
                },

                addToCart(product) {
                    // Check if product has variants and we need to show selection modal
                    if (product.has_variants && product.variants.length > 1 && !product.is_variant_selection) {
                        this.activeProduct = product;
                        this.showVariantModal = true;
                        return;
                    }

                    const existingItem = this.cart.find(i => i.variant_id === product.variant_id && i.product_unit_id === product.unit_id);
                    if (existingItem) {
                        existingItem.quantity++;
                    } else {
                        this.cart.push({
                            name: product.variant_name || product.name,
                            variant_id: product.variant_id,
                            product_unit_id: product.unit_id,
                            conversion_factor: product.conversion_factor || 1,
                            price: product.price || 0,
                            quantity: 1,
                            discount: 0,
                            available_units: product.available_units || [],
                            prices: product.prices || []
                        });
                    }
                    this.calculateTotals();
                    this.searchQuery = '';
                    this.filterProducts();
                    this.showVariantModal = false;
                    this.$refs.productSearch.focus();
                },

                selectVariant(variant) {
                    const prodUnits = this.activeProduct.product_units || this.activeProduct.productUnits || [];
                    
                    // Find default sale unit
                    let saleUnit = prodUnits.find(u => u.is_sale) || prodUnits.find(u => u.is_base) || prodUnits[0];
                    
                    // Find price for that unit for this specific variant
                    let price = variant.price || 0;
                    if (saleUnit) {
                        let priceData = variant.prices ? variant.prices.find(pr => pr.product_unit_id == saleUnit.id) : null;
                        if (priceData) {
                            price = parseFloat(priceData.price);
                        }
                    }

                    const productToCart = {
                        ...this.activeProduct,
                        variant_id: variant.id,
                        variant_name: this.activeProduct.name + ' (' + variant.name + ')',
                        price: price,
                        unit_id: saleUnit ? saleUnit.id : null,
                        conversion_factor: saleUnit ? saleUnit.conversion_factor : 1,
                        available_units: prodUnits,
                        prices: variant.prices || [],
                        is_variant_selection: true
                    };

                    this.addToCart(productToCart);
                },

                updateItemPrice(index) {
                    const item = this.cart[index];
                    const unit = item.available_units.find(u => u.id == item.product_unit_id);
                    if (unit) {
                        item.conversion_factor = unit.conversion_factor;
                        const priceData = item.prices.find(pr => pr.product_unit_id == unit.id);
                        if (priceData) {
                            item.price = parseFloat(priceData.price);
                        } else {
                            // If no specific price set for this unit, we can't do much without a base price
                            // But usually there should be a price set in variant_prices for each unit
                        }
                    }
                    this.calculateTotals();
                },

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

                updateQty(index, delta) {
                    this.cart[index].quantity = Math.max(1, this.cart[index].quantity + delta);
                    this.calculateTotals();
                },

                calculateTotals() {
                    this.subtotal = this.cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
                    this.totalDiscount = this.cart.reduce((sum, item) => sum + (item.discount || 0), 0);
                    this.total = this.subtotal - this.totalDiscount;
                    this.paidAmount = this.total;
                },

                openItemDiscount(index) {
                    this.activeItemIndex = index;
                    this.discountValue = this.cart[index].discount || 0;
                    this.showItemDiscountModal = true;
                },

                applyItemDiscount() {
                    if (this.activeItemIndex !== null) {
                        let discount = 0;
                        if (this.discountType === 'fixed') {
                            discount = this.discountValue;
                        } else {
                            discount = (this.cart[this.activeItemIndex].price * this.cart[this.activeItemIndex].quantity) * (this.discountValue / 100);
                        }
                        this.cart[this.activeItemIndex].discount = discount;
                        this.calculateTotals();
                    }
                    this.showItemDiscountModal = false;
                },

                get filteredCustomers() {
                    if (!this.customerSearch) return this.customers;
                    return this.customers.filter(c => 
                        c.name.toLowerCase().includes(this.customerSearch.toLowerCase()) || 
                        (c.contact && c.contact.includes(this.customerSearch))
                    );
                },

                selectCustomer(customer) {
                    this.selectedCustomer = customer;
                    this.showCustomerModal = false;
                },

                holdSale() {
                    if (this.cart.length === 0) return;
                    const heldSale = {
                        id: Date.now(),
                        customer: this.selectedCustomer,
                        items: JSON.parse(JSON.stringify(this.cart)),
                        subtotal: this.subtotal,
                        total: this.total,
                        time: new Date().toLocaleTimeString()
                    };
                    this.heldSales.push(heldSale);
                    this.cart = [];
                    this.selectedCustomer = null;
                    this.calculateTotals();
                    this.$refs.productSearch.focus();
                },

                resumeSale(index) {
                    const sale = this.heldSales[index];
                    this.cart = JSON.parse(JSON.stringify(sale.items));
                    this.selectedCustomer = sale.customer;
                    this.calculateTotals();
                    this.heldSales.splice(index, 1);
                    this.showHoldModal = false;
                    this.$refs.productSearch.focus();
                },

                processCheckout() {
                    if (this.cart.length === 0) return;
                    this.showCheckoutModal = true;
                },

                submitSale() {
                    const saleData = {
                        customer_id: this.selectedCustomer ? this.selectedCustomer.id : null,
                        items: this.cart,
                        subtotal: this.subtotal,
                        discount: this.totalDiscount,
                        total: this.total,
                        paid_amount: this.paidAmount,
                        payment_method: this.paymentMethod,
                        _token: '{{ csrf_token() }}'
                    };

                    fetch('{{ route("tenant.sell.store") }}', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(saleData)
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            alert('Sale Completed Successfully!');
                            this.cart = [];
                            this.selectedCustomer = null;
                            this.calculateTotals();
                            this.showCheckoutModal = false;
                            // Trigger Print
                        } else {
                            alert('Error: ' + data.message);
                        }
                    });
                },

                closeModals() {
                    this.showCustomerModal = false;
                    this.showItemDiscountModal = false;
                    this.showCheckoutModal = false;
                    this.showHoldModal = false;
                }
            }
        }
    </script>

    <style>
        [x-cloak] { display: none !important; }
        input::-webkit-outer-spin-button,
        input::-webkit-inner-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }
        input[type=number] {
            -moz-appearance: textfield;
        }
    </style>
</x-tenant-layout>
