<x-app-layout>
    <x-slot name="header">
        <div class="flex items-center justify-between">
            <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight flex items-center gap-2">
                <svg class="w-6 h-6 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 11h.01M12 11h.01M15 11h.01M4 19h16a2 2 0 002-2V7a2 2 0 00-2-2H4a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                </svg>
                Punto de Venta (POS)
            </h2>
            <span id="scan-status" class="px-3 py-1 rounded-full text-sm font-bold bg-emerald-100 text-emerald-700 flex items-center gap-1">
                <span class="w-2 h-2 bg-emerald-500 rounded-full animate-pulse inline-block"></span>
                Listo para escanear
            </span>
        </div>
    </x-slot>

    <div x-data="posSystem()" x-init="init()" @keydown.f12.window.prevent="triggerCheckout()" class="py-4">

        {{-- ───────── BARRA DE TICKETS ───────── --}}
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 mb-4">
            <div class="pos-tabs-wrapper flex items-center gap-2 overflow-x-auto no-scrollbar">
                {{-- Tab activo --}}
                <div class="pos-tab-active flex-shrink-0 flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-bold bg-indigo-600 text-white shadow-lg whitespace-nowrap">
                    <span class="w-1.5 h-1.5 bg-white rounded-full flex-shrink-0 animate-pulse"></span>
                    <span x-text="currentTicketLabel">Ticket Nuevo</span>
                    <template x-if="cart.length > 0">
                        <span x-text="cart.length" class="bg-white text-indigo-600 rounded-full w-4 h-4 flex items-center justify-center text-[10px] font-black"></span>
                    </template>
                </div>

                {{-- Tickets en espera --}}
                @foreach($heldSales as $hs)
                <button type="button"
                        @click="resumeHeldSale({{ $hs->id }}, {{ json_encode($hs->items) }}, {{ json_encode($hs->label) }}, {{ $hs->client_id ?? 'null' }}, {{ json_encode($hs->customer_name) }}, {{ json_encode($hs->payment_method) }})"
                        class="pos-tab-held flex-shrink-0 flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-bold border border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400 hover:bg-amber-500/20 transition-all whitespace-nowrap">
                    <span class="w-1.5 h-1.5 bg-amber-500 rounded-full flex-shrink-0"></span>
                    {{ $hs->label }}
                    <span class="bg-amber-500 text-white rounded-full px-1.5 py-0.5 text-[10px] font-black">{{ count($hs->items) }}</span>
                </button>
                @endforeach

                <div class="flex-1"></div>

                {{-- Botón Espera --}}
                <button type="button" @click="holdCurrentSale()"
                        x-show="cart.length > 0"
                        style="display:none"
                        class="flex-shrink-0 inline-flex items-center gap-1.5 px-4 py-1.5 rounded-full text-xs font-bold bg-amber-500 hover:bg-amber-600 text-white shadow-lg transition-all active:scale-95 whitespace-nowrap">
                    ⏸ Poner en Espera
                </button>
            </div>
        </div>

        {{-- ───────── CUERPO PRINCIPAL ───────── --}}
        <div class="max-w-[98%] mx-auto px-2 lg:px-4 flex flex-col md:flex-row gap-4">

            {{-- ══ COLUMNA IZQUIERDA: Catálogo (70%) ══ --}}
            <div class="w-full md:w-[68%] flex flex-col gap-4">

                {{-- ── Zona de Escaneo ── --}}
                <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-100 dark:border-gray-700 p-5">
                    <div class="flex items-center gap-2 mb-3">
                        <svg class="w-5 h-5 text-indigo-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z"/></svg>
                        <span class="font-bold text-gray-700 dark:text-gray-200 text-sm uppercase tracking-widest">Escanear Código de Barras</span>
                    </div>
                    <div class="relative">
                        <input type="text"
                               id="scan-input"
                               x-ref="scanInput"
                               x-model="scanBuffer"
                               @keydown.enter.prevent="handleBarcodeScan()"
                               @blur="refocusScan()"
                               placeholder="🔍 Escanea o escribe el código..."
                               autocomplete="off"
                               class="w-full px-5 py-4 text-xl font-bold rounded-xl border-2 border-indigo-300 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-200/50 bg-indigo-50 dark:bg-gray-700 dark:border-indigo-600 text-gray-800 dark:text-white placeholder-indigo-300 transition-all shadow-inner">
                        <div x-show="scanBuffer.length > 0" style="display:none" class="absolute right-3 top-1/2 -translate-y-1/2">
                            <kbd class="bg-indigo-600 text-white text-xs px-2 py-1 rounded font-bold">ENTER</kbd>
                        </div>
                    </div>
                    {{-- Alerta error --}}
                    <div x-show="scanError" x-transition style="display:none"
                         class="mt-3 flex items-center gap-3 bg-red-50 border-2 border-red-300 rounded-xl px-4 py-3 text-red-700 font-bold text-sm">
                        <svg class="w-5 h-5 text-red-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"/></svg>
                        <div>
                            <div class="font-black">⚠️ Código No Reconocido</div>
                            <div x-text="scanErrorMessage" class="text-xs font-normal text-red-600 mt-0.5"></div>
                            <div class="text-xs text-red-500 mt-1">Aparte este artículo para registrarlo después.</div>
                        </div>
                    </div>
                    {{-- Alerta éxito --}}
                    <div x-show="scanSuccess" x-transition style="display:none"
                         class="mt-3 flex items-center gap-3 bg-emerald-50 border-2 border-emerald-300 rounded-xl px-4 py-3 text-emerald-700 font-bold text-sm">
                        <svg class="w-5 h-5 text-emerald-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                        <span x-text="scanSuccessMessage"></span>
                    </div>
                </div>

                {{-- ── Botones Rápidos "Varios" ── --}}
                @if($quickProducts->isNotEmpty())
                <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-100 dark:border-gray-700 p-5">
                    <div class="flex items-center gap-2 mb-3">
                        <svg class="w-5 h-5 text-orange-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"/></svg>
                        <span class="font-bold text-gray-700 dark:text-gray-200 text-sm uppercase tracking-widest">Botones Rápidos — Varios</span>
                        <span class="text-xs text-gray-400">(Sin código)</span>
                    </div>
                    <div class="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-3">
                        @foreach($quickProducts as $qp)
                        <button type="button"
                                @click="addToCart({{ json_encode(['id'=>$qp->id,'name'=>$qp->name,'sku'=>$qp->sku,'sale_price'=>(float)$qp->sale_price,'stock'=>(int)$qp->stock,'min_stock'=>(int)$qp->min_stock,'image'=>$qp->image]) }})"
                                class="quick-btn flex flex-col items-center justify-center p-3 rounded-xl border-2 border-orange-200 hover:border-orange-400 bg-orange-50 hover:bg-orange-100 transition-all duration-200 active:scale-95 group">
                            @if($qp->image)
                                <img src="{{ asset('storage/'.$qp->image) }}" alt="{{ $qp->name }}" class="w-12 h-12 object-cover rounded-lg mb-2 shadow-sm">
                            @else
                                <div class="w-12 h-12 rounded-lg bg-orange-200 flex items-center justify-center mb-2 text-2xl">🛒</div>
                            @endif
                            <span class="text-xs font-bold text-gray-700 text-center leading-tight line-clamp-2">{{ $qp->name }}</span>
                            <span class="text-sm font-black text-orange-600 mt-1">S/ {{ number_format($qp->sale_price, 2) }}</span>
                        </button>
                        @endforeach
                    </div>
                </div>
                @endif

                {{-- ── Catálogo con carga AJAX paginada ── --}}
                <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-100 dark:border-gray-700 p-5">
                    {{-- Header del catálogo --}}
                    <div class="flex flex-wrap justify-between items-center gap-3 mb-4">
                        <h3 class="text-base font-bold text-gray-800 dark:text-gray-100 flex items-center gap-2">
                            <svg class="w-5 h-5 text-indigo-500" 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"/></svg>
                            Catálogo
                            <span class="text-xs font-normal text-gray-400" x-show="catalogTotal > 0" style="display:none"
                                  x-text="'(' + catalogTotal + ' productos)'"></span>
                        </h3>
                        {{-- Buscador con debounce --}}
                        <div class="relative">
                            <svg class="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><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"/></svg>
                            <input type="text"
                                   x-model="search"
                                   @input.debounce.400ms="fetchProducts(1)"
                                   placeholder="Buscar producto..."
                                   class="pl-8 pr-3 py-2 border border-gray-200 rounded-lg text-sm focus:border-indigo-400 focus:ring-2 focus:ring-indigo-200 bg-gray-50 dark:bg-gray-700 dark:border-gray-600 w-48">
                        </div>
                    </div>

                    {{-- Categorías --}}
                    <div class="flex gap-2 overflow-x-auto pb-3 mb-4 custom-scrollbar">
                        <button @click="setCategory('')"
                                :class="activeCategory === '' ? 'bg-indigo-600 text-white shadow-md' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'"
                                class="px-3 py-1.5 rounded-full text-xs font-bold transition whitespace-nowrap">Todos</button>
                        @foreach($categories as $category)
                        <button @click="setCategory({{ $category->id }})"
                                :class="activeCategory === {{ $category->id }} ? 'bg-indigo-600 text-white shadow-md' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'"
                                class="px-3 py-1.5 rounded-full text-xs font-bold transition whitespace-nowrap">{{ $category->name }}</button>
                        @endforeach
                    </div>

                    {{-- Estado de carga --}}
                    <div x-show="catalogLoading" style="display:none" class="flex justify-center items-center py-8">
                        <svg class="animate-spin h-8 w-8 text-indigo-500" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                        </svg>
                        <span class="ml-3 text-sm text-gray-500">Cargando productos...</span>
                    </div>

                    {{-- Grid de productos (Filas de 4) --}}
                    <div x-show="!catalogLoading" class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-4 xl:grid-cols-4 gap-3 max-h-[65vh] overflow-y-auto pr-1 custom-scrollbar content-start"
                         @scroll="onCatalogScroll($event)">
                        <template x-for="product in catalogProducts" :key="product.id">
                            <div class="border border-gray-100 dark:border-gray-700 rounded-xl p-2 cursor-pointer hover:shadow-lg hover:-translate-y-0.5 hover:border-indigo-200 transition-all duration-200 flex flex-col bg-white dark:bg-gray-700 group relative overflow-hidden"
                                 @click="addToCart(product)">
                                <div class="absolute top-1 left-1 z-10 flex flex-col gap-0.5 pointer-events-none">
                                    <span class="bg-white/90 text-[9px] px-1.5 py-0.5 rounded text-gray-700 font-bold shadow-sm" x-text="product.sku"></span>
                                    <span class="text-[9px] px-1.5 py-0.5 rounded text-white font-bold shadow-sm"
                                          :class="product.stock <= product.min_stock ? 'bg-red-500' : 'bg-emerald-500'"
                                          x-text="product.stock + ' disp.'"></span>
                                </div>
                                <div class="w-full bg-gray-50 rounded-lg overflow-hidden mb-1.5 relative" style="aspect-ratio:1/1">
                                    <template x-if="product.image">
                                        <img :src="storageBase + product.image" alt="" class="w-full h-full object-cover absolute inset-0" loading="lazy">
                                    </template>
                                    <template x-if="!product.image">
                                        <div class="absolute inset-0 flex items-center justify-center text-3xl">📦</div>
                                    </template>
                                </div>
                                <div class="font-bold text-gray-800 dark:text-gray-100 leading-tight text-[11px] line-clamp-2 group-hover:text-indigo-600 transition-colors" x-text="product.name"></div>
                                <div class="text-indigo-600 font-black text-xs mt-0.5">S/<span x-text="parseFloat(product.sale_price).toFixed(2)"></span></div>
                            </div>
                        </template>

                        {{-- Estado vacío --}}
                        <template x-if="!catalogLoading && catalogProducts.length === 0">
                            <div class="col-span-full text-center text-gray-400 py-8">
                                <div class="text-3xl mb-2">🔍</div>
                                <div class="text-sm">No se encontraron productos.</div>
                            </div>
                        </template>
                    </div>

                    {{-- Paginación / carga más --}}
                    <div x-show="catalogPage < catalogLastPage && !catalogLoading" style="display:none" class="mt-4 text-center">
                        <button @click="fetchProducts(catalogPage + 1, true)"
                                class="px-4 py-2 bg-indigo-50 text-indigo-600 rounded-lg text-xs font-bold hover:bg-indigo-100 transition border border-indigo-200">
                            <span x-show="!loadingMore">Cargar más productos ↓</span>
                            <span x-show="loadingMore" style="display:none">Cargando...</span>
                        </button>
                        <span class="text-xs text-gray-400 ml-3">
                            Mostrando <span x-text="catalogProducts.length"></span> de <span x-text="catalogTotal"></span>
                        </span>
                    </div>
                </div>
            </div>

            {{-- ══ COLUMNA DERECHA: Cobro (30%) ══ --}}
            <div class="w-full md:w-[30%] flex flex-col gap-4 sticky md:top-4 h-fit">

                {{-- ── Panel de Cobro ── --}}
                <div class="bg-gray-900 rounded-2xl shadow-2xl p-5 text-white">
                    <div class="text-center mb-4">
                        <div class="text-xs text-gray-400 uppercase tracking-widest mb-1">Total a Cobrar</div>
                        <div class="total-display font-black text-white leading-none">
                            S/ <span x-text="total.toFixed(2)">0.00</span>
                        </div>
                        <div class="flex justify-center gap-6 mt-2 text-xs text-gray-400">
                            <span>Subtotal: S/<span x-text="subtotal.toFixed(2)"></span></span>
                            <span>IGV 18%: S/<span x-text="tax.toFixed(2)"></span></span>
                        </div>
                    </div>
                    <div class="border-t border-gray-700 pt-4 mb-4">
                        <div class="grid grid-cols-2 gap-2 mb-4">
                            <button type="button" @click="paymentMethod = 'Contado'"
                                    :class="paymentMethod === 'Contado' ? 'bg-emerald-600 text-white shadow-lg ring-2 ring-emerald-300' : 'bg-gray-800 text-gray-400 hover:bg-gray-700'"
                                    class="flex flex-col items-center justify-center p-3 rounded-xl transition-all duration-200">
                                <span class="text-xl">💵</span>
                                <span class="text-[10px] font-black mt-1 uppercase">Contado</span>
                            </button>
                            <button type="button" @click="paymentMethod = 'Crédito'"
                                    :disabled="!hasCredit()"
                                    :class="paymentMethod === 'Crédito' ? 'bg-amber-600 text-white shadow-lg ring-2 ring-amber-300' : 'bg-gray-800 text-gray-400 hover:bg-gray-700'"
                                    class="flex flex-col items-center justify-center p-3 rounded-xl transition-all duration-200 disabled:opacity-30 disabled:grayscale">
                                <span class="text-xl">💳</span>
                                <span class="text-[10px] font-black mt-1 uppercase">Crédito</span>
                            </button>
                        </div>
                        <template x-if="paymentMethod === 'Crédito'">
                            <div class="mt-1.5 text-xs text-amber-400 animate-pulse font-bold text-center italic">* Venta a cuenta registrada.</div>
                        </template>
                    </div>
                    <button type="button" id="cobrar-btn" @click="triggerCheckout()" :disabled="cart.length === 0"
                            class="cobrar-btn w-full rounded-xl py-5 text-xl font-black text-white transition-all duration-200 flex flex-col items-center justify-center gap-1 disabled:opacity-50 disabled:cursor-not-allowed active:scale-95 shadow-xl">
                        <div class="flex items-center gap-2">
                            <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="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
                            💰 COBRAR
                        </div>
                        <kbd class="text-xs font-mono bg-white/20 px-2 py-0.5 rounded">F12</kbd>
                    </button>
                </div>

                {{-- ── Cliente ── --}}
                <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-100 dark:border-gray-700 p-4">
                    <label class="block text-xs font-bold text-gray-500 uppercase tracking-widest mb-2">Cliente</label>
                    <div x-data="{
                        initSelect2() {
                            $(this.$refs.clientSelect).select2({
                                placeholder: 'Público General...',
                                allowClear: true, width: '100%', language: 'es'
                            }).on('change', (e) => {
                                this.selectedClientId = e.target.value;
                                const client = this.clients.find(c => c.id == e.target.value);
                                if (client && (client.credit_limit - client.credit_balance) > 0) {
                                    this.paymentMethod = 'Crédito';
                                } else {
                                    this.paymentMethod = 'Contado';
                                }
                            });
                        }
                    }" x-init="initSelect2()">
                        <select x-ref="clientSelect" id="client-select" class="block w-full border-gray-200 rounded-lg text-sm">
                            <option value="">Público General</option>
                            @foreach($clients as $client)
                                <option value="{{ $client->id }}">{{ $client->name }}{{ $client->document_number ? ' — '.$client->document_number : '' }}</option>
                            @endforeach
                        </select>
                    </div>
                    <input type="text" x-model="customerName" placeholder="Referencia u observación"
                           class="mt-2 block w-full border border-gray-200 dark:border-gray-600 rounded-lg text-xs py-1.5 px-2 text-gray-600 dark:text-gray-300 bg-gray-50 dark:bg-gray-700">
                </div>

                {{-- ── Carrito ── --}}
                <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-100 dark:border-gray-700 p-4 flex flex-col" style="min-height:200px; max-height:40vh;">
                    <div class="flex justify-between items-center mb-3">
                        <h3 class="text-sm font-bold text-gray-700 dark:text-gray-200 flex items-center gap-1.5">
                            <svg class="w-4 h-4 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
                            Artículos
                        </h3>
                        <button type="button" x-show="cart.length > 0" @click="clearCart()" style="display:none"
                                class="text-xs text-red-400 hover:text-red-600 transition flex items-center gap-1">
                            <svg class="w-3.5 h-3.5" 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"/></svg>
                            Vaciar
                        </button>
                    </div>
                    <div class="flex-1 overflow-y-auto custom-scrollbar">
                        <template x-if="cart.length === 0">
                            <div class="text-center text-gray-400 py-8 text-sm">
                                <div class="text-3xl mb-2">🛒</div>
                                Escanea o selecciona un producto
                            </div>
                        </template>
                        <template x-for="(item, index) in cart" :key="index">
                            <div class="flex items-center gap-2 py-2 border-b border-gray-100 dark:border-gray-700 last:border-0 hover:bg-gray-50 dark:hover:bg-gray-700/50 px-1 rounded transition-colors">
                                <div class="flex-1 min-w-0">
                                    <div class="font-bold text-gray-800 dark:text-gray-100 text-xs leading-tight truncate" x-text="item.name"></div>
                                    <div class="text-[10px] text-gray-400" x-show="item.quantity > 1" x-text="'S/' + parseFloat(item.sale_price).toFixed(2) + ' c/u'"></div>
                                </div>
                                <div class="flex items-center bg-gray-100 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 h-7 shadow-inner flex-shrink-0">
                                    <button type="button" @click="decreaseQty(index)" class="w-6 h-full text-gray-500 hover:text-red-600 hover:bg-red-50 flex items-center justify-center font-black text-sm transition rounded-l-lg">−</button>
                                    <span class="w-8 text-center text-xs font-black text-indigo-700 dark:text-indigo-300 border-x border-gray-200 dark:border-gray-600 h-full flex items-center justify-center" x-text="item.quantity"></span>
                                    <button type="button" @click="increaseQty(index)" class="w-6 h-full text-gray-500 hover:text-emerald-600 hover:bg-emerald-50 flex items-center justify-center font-black text-sm transition rounded-r-lg">+</button>
                                </div>
                                <button type="button" @click="editPrice(index)" class="text-indigo-400 hover:text-indigo-600 p-1 rounded transition flex-shrink-0" title="Editar precio">
                                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                                </button>
                                <div class="text-xs font-black text-gray-800 dark:text-gray-200 text-right min-w-[52px] flex-shrink-0">
                                    S/<span x-text="(item.quantity * item.sale_price).toFixed(2)"></span>
                                </div>
                                <button type="button" @click="removeFromCart(index)" class="text-red-400 hover:text-red-600 p-1 rounded transition flex-shrink-0">
                                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                                </button>
                            </div>
                        </template>
                    </div>
                </div>

                @if(session('success'))
                    <div class="p-3 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-700 text-sm font-medium">✅ {{ session('success') }}</div>
                @endif
                @if(session('error'))
                    <div class="p-3 rounded-xl bg-red-50 border border-red-200 text-red-700 text-sm font-medium">❌ {{ session('error') }}</div>
                @endif
            </div>
        </div>

        {{-- ─── MODAL CHECKOUT ─── --}}
        <div x-show="checkoutModal" x-transition.opacity style="display:none; position: fixed; inset: 0; z-index: 60; display: flex; align-items: center; justify-content: center; background-color: rgba(15, 23, 42, 0.9); backdrop-filter: blur(8px);"
             @click.self="!isProcessing && (checkoutModal=false)">
            <div x-show="checkoutModal" x-transition 
                 style="background-color: white !important; border-radius: 1.5rem !important; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5) !important; width: 95% !important; max-width: 380px !important; margin: auto !important; overflow: hidden !important; border: 2px solid #e2e8f0 !important; position: relative !important;">
                
                {{-- Overlay de Procesando --}}
                <div x-show="isProcessing" style="display:none; position: absolute; inset: 0; z-index: 70; background-color: rgba(255, 255, 255, 0.9); display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 2rem; text-align: center;">
                    <div style="border: 4px solid #f3f3f3; border-top: 4px solid #4338ca; border-radius: 50%; width: 50px; height: 50px; animation: spin 1s linear infinite;"></div>
                    <style>@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }</style>
                    <div style="font-size: 1.25rem; font-weight: 900; color: #4338ca; margin-top: 1rem;">PROCESANDO...</div>
                    <div style="font-size: 0.75rem; color: #64748b; margin-top: 0.5rem;">Cerrando venta, espera un momento</div>
                </div>

                {{-- Cabecera Compacta --}}
                <div style="background-color: #4338ca !important; padding: 1.5rem !important; text-align: center !important; color: white !important;">
                    <div style="font-size: 0.65rem !important; font-weight: 800 !important; text-transform: uppercase !important; letter-spacing: 0.2em !important; opacity: 0.8 !important;">Confirmar Pago</div>
                    <div style="font-size: 3rem !important; font-weight: 900 !important; line-height: 1.1 !important; margin-top: 0.5rem !important;">
                        <span style="font-size: 1.2rem !important; opacity: 0.6 !important;">S/</span><span x-text="total.toFixed(2)"></span>
                    </div>
                </div>

                {{-- Resumen de Pago --}}
                <div style="padding: 1rem; background-color: #f8fafc; border-bottom: 1px solid #e2e8f0; display: flex; justify-content: center; gap: 0.75rem;">
                    <template x-if="paymentMethod === 'Contado'">
                        <span style="padding: 0.25rem 0.75rem; border-radius: 9999px; font-size: 10px; font-weight: 900; text-transform: uppercase; letter-spacing: 0.1em; background-color: #10b981; color: white; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">💵 CONTADO</span>
                    </template>
                    <template x-if="paymentMethod === 'Crédito'">
                        <span style="padding: 0.25rem 0.75rem; border-radius: 9999px; font-size: 10px; font-weight: 900; text-transform: uppercase; letter-spacing: 0.1em; background-color: #f59e0b; color: white; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">💳 CRÉDITO</span>
                    </template>
                </div>

                {{-- Detalles de la Compra (Lista de Productos) --}}
                <div style="padding: 1rem; max-height: 200px; overflow-y: auto; background-color: white;">
                    <template x-for="item in cart" :key="item.id">
                        <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.5rem 0; border-bottom: 1px solid #f1f5f9;">
                            <div style="flex: 1; padding-right: 1rem;">
                                <div style="font-size: 13px; font-weight: 700; color: #1e293b; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" x-text="item.name"></div>
                                <div style="font-size: 10px; color: #64748b;" x-text="item.quantity + ' unidad(es) x S/' + parseFloat(item.sale_price).toFixed(2)"></div>
                            </div>
                            <div style="font-size: 13px; font-weight: 900; color: #0f172a; white-space: nowrap;">
                                S/<span x-text="(item.quantity * item.sale_price).toFixed(2)"></span>
                            </div>
                        </div>
                    </template>
                </div>

                <form id="checkout-form" action="{{ route('sales.store') }}" method="POST" @submit="isProcessing = true">
                    @csrf
                    <template x-for="(item, index) in cart" :key="index">
                        <div>
                            <input type="hidden" :name="`items[${index}][product_id]`" :value="item.id">
                            <input type="hidden" :name="`items[${index}][quantity]`" :value="item.quantity">
                            <input type="hidden" :name="`items[${index}][price]`" :value="item.sale_price">
                        </div>
                    </template>
                    <input type="hidden" name="tax_rate" value="0.18">
                    <input type="hidden" name="payment_method" :value="paymentMethod">
                    <input type="hidden" name="client_id" :value="selectedClientId">
                    <input type="hidden" name="customer_name" :value="customerName">
                    <input type="hidden" name="held_sale_id" :value="currentHeldSaleId">
                    
                    <div class="p-5 bg-white flex flex-col gap-3">
                        <button type="submit" style="background-color: #4338ca !important;" class="w-full py-4 rounded-2xl text-white font-black text-lg shadow-xl active:scale-95 flex items-center justify-center gap-2">
                             CONFIRMAR Y COBRAR
                        </button>
                        <button type="button" @click="checkoutModal=false" :disabled="isProcessing"
                                class="w-full py-2 text-slate-400 font-bold hover:text-red-500 transition-all text-xs uppercase tracking-widest">
                            ← CANCELAR
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    @push('scripts')
    <style>
        .custom-scrollbar::-webkit-scrollbar { width: 5px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }

        .total-display { font-size: clamp(2.5rem, 6vw, 4.5rem); }

        .cobrar-btn {
            background: linear-gradient(135deg, #16a34a, #15803d);
            box-shadow: 0 8px 32px rgba(22,163,74,0.4);
        }
        .cobrar-btn:hover:not(:disabled) {
            background: linear-gradient(135deg, #15803d, #14532d);
            box-shadow: 0 12px 40px rgba(22,163,74,0.5);
            transform: translateY(-2px);
        }

        /* ── Tabs bar wrapper ── */
        .pos-tabs-wrapper {
            background: rgba(255,255,255,0.05);
            border: 1px solid rgba(99,102,241,0.15);
            border-radius: 999px;
            padding: 6px 10px;
        }
        html.dark .pos-tabs-wrapper {
            background: rgba(255,255,255,0.04);
            border-color: rgba(99,102,241,0.25);
        }

        /* Tickets en espera: pulso suave */
        .pos-tab-held { animation: pulse-amber 2.5s ease-in-out infinite; }
        @keyframes pulse-amber {
            0%,100% { box-shadow: 0 0 0 0 rgba(245,158,11,0); }
            50%      { box-shadow: 0 0 0 4px rgba(245,158,11,0.25); }
        }

        /* ── Scrollbars ── */
        .no-scrollbar::-webkit-scrollbar { display: none; }
        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }

        .custom-scrollbar::-webkit-scrollbar { width: 5px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
        html.dark .custom-scrollbar::-webkit-scrollbar-track { background: #1f2937; }
        html.dark .custom-scrollbar::-webkit-scrollbar-thumb { background: #4b5563; }
    </style>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/i18n/es.js"></script>
    {{-- SweetAlert2: already loaded globally from layouts/app.blade.php --}}

    <script>
    document.addEventListener('alpine:init', () => {
        Alpine.data('posSystem', () => ({
            // ─── Estado carrito ───
            cart: [],
            selectedClientId: '',
            customerName: '',
            paymentMethod: 'Contado',
            checkoutModal: false,
            isProcessing: false,
            currentHeldSaleId: null,
            currentTicketLabel: 'Ticket Nuevo',
            clients: @json($clients ?? []),
            storageBase: '{{ asset('storage/') }}/',

            // ─── Catálogo paginado ───
            catalogProducts: [],
            catalogPage: 1,
            catalogLastPage: 1,
            catalogTotal: 0,
            catalogLoading: false,
            loadingMore: false,
            activeCategory: '',
            search: '',

            // ─── Escaneo ───
            scanBuffer: '',
            scanError: false,
            scanErrorMessage: '',
            scanSuccess: false,
            scanSuccessMessage: '',
            scanStatusTimer: null,

            // ─── Init ───
            init() {
                this.fetchProducts(1);
                this.$nextTick(() => this.$refs.scanInput?.focus());
            },

            // ─── Catálogo AJAX paginado ───
            async fetchProducts(page = 1, append = false) {
                if (append) {
                    this.loadingMore = true;
                } else {
                    this.catalogLoading = true;
                    if (!append) this.catalogProducts = [];
                }

                const params = new URLSearchParams({
                    page,
                    ...(this.activeCategory !== '' && { category: this.activeCategory }),
                    ...(this.search.trim() !== '' && { search: this.search.trim() }),
                });

                try {
                    const res = await fetch(`{{ route('sales.products') }}?${params}`, {
                        headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
                    });
                    const data = await res.json();

                    if (append) {
                        this.catalogProducts.push(...data.data);
                    } else {
                        this.catalogProducts = data.data;
                    }
                    this.catalogPage     = data.current_page;
                    this.catalogLastPage = data.last_page;
                    this.catalogTotal    = data.total;
                } catch (e) {
                    console.error('Error al cargar productos:', e);
                } finally {
                    this.catalogLoading = false;
                    this.loadingMore    = false;
                }
            },

            setCategory(id) {
                this.activeCategory = id;
                this.fetchProducts(1);
            },

            // ─── Scroll infinito en el catálogo ───
            onCatalogScroll(e) {
                const el = e.target;
                const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 60;
                if (nearBottom && this.catalogPage < this.catalogLastPage && !this.loadingMore) {
                    this.fetchProducts(this.catalogPage + 1, true);
                }
            },

            // ─── Escaneo ───
            async handleBarcodeScan() {
                const sku = this.scanBuffer.trim();
                if (!sku) return;
                this.scanBuffer = '';
                this.$refs.scanInput?.focus();

                try {
                    const res = await fetch(`{{ route('sales.lookup') }}?sku=${encodeURIComponent(sku)}`, {
                        headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
                    });
                    const data = await res.json();
                    if (data.found) {
                        this.addToCart(data.product);
                        this.showScanFeedback('success', `✅ ${data.product.name} agregado`);
                    } else {
                        this.showScanFeedback('error', data.message || 'Código no encontrado');
                    }
                } catch(e) {
                    this.showScanFeedback('error', 'Error de conexión al buscar el código.');
                }
            },

            showScanFeedback(type, msg) {
                if (this.scanStatusTimer) clearTimeout(this.scanStatusTimer);
                this.scanError = false; this.scanSuccess = false;
                if (type === 'success') {
                    this.scanSuccess = true; this.scanSuccessMessage = msg;
                    this.playBeep('success'); this.updateScanStatus('success');
                } else {
                    this.scanError = true; this.scanErrorMessage = msg;
                    this.playBeep('error'); this.updateScanStatus('error');
                }
                this.scanStatusTimer = setTimeout(() => {
                    this.scanError = false; this.scanSuccess = false;
                    this.updateScanStatus('ready');
                }, 2500);
            },

            updateScanStatus(state) {
                const el = document.getElementById('scan-status');
                if (!el) return;
                const states = {
                    success: ['bg-emerald-100 text-emerald-700', '<span class="w-2 h-2 bg-emerald-500 rounded-full inline-block"></span> Producto agregado'],
                    error:   ['bg-red-100 text-red-700',         '<span class="w-2 h-2 bg-red-500 rounded-full animate-pulse inline-block"></span> Código no encontrado'],
                    ready:   ['bg-emerald-100 text-emerald-700', '<span class="w-2 h-2 bg-emerald-500 rounded-full animate-pulse inline-block"></span> Listo para escanear'],
                };
                const [cls, html] = states[state] || states.ready;
                el.className = `px-3 py-1 rounded-full text-sm font-bold ${cls} flex items-center gap-1`;
                el.innerHTML = html;
            },

            refocusScan() {
                setTimeout(() => {
                    const active = document.activeElement?.tagName;
                    if (!['INPUT','SELECT','BUTTON','TEXTAREA'].includes(active)) {
                        this.$refs.scanInput?.focus();
                    }
                }, 100);
            },

            playBeep(type) {
                try {
                    const ctx = new (window.AudioContext || window.webkitAudioContext)();
                    const osc = ctx.createOscillator();
                    const gain = ctx.createGain();
                    osc.connect(gain); gain.connect(ctx.destination);
                    if (type === 'success') {
                        osc.frequency.setValueAtTime(880, ctx.currentTime);
                        osc.frequency.setValueAtTime(1100, ctx.currentTime + 0.08);
                        gain.gain.setValueAtTime(0.3, ctx.currentTime);
                        gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.25);
                        osc.start(ctx.currentTime); osc.stop(ctx.currentTime + 0.25);
                    } else {
                        osc.frequency.setValueAtTime(300, ctx.currentTime);
                        osc.frequency.setValueAtTime(150, ctx.currentTime + 0.15);
                        gain.gain.setValueAtTime(0.4, ctx.currentTime);
                        gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.4);
                        osc.start(ctx.currentTime); osc.stop(ctx.currentTime + 0.4);
                    }
                } catch(e) {}
            },

            // ─── Carrito ───
            addToCart(product) {
                if (product.stock <= 0) {
                    Swal.fire({ icon:'error', title:'Sin Stock', text:`${product.name} no tiene stock disponible.`, confirmButtonColor:'#4f46e5' });
                    return;
                }
                const existing = this.cart.find(i => i.id === product.id);
                if (existing) {
                    if (existing.quantity < product.stock) existing.quantity++;
                    else Swal.fire({ icon:'warning', title:'Stock Límite', text:`Solo hay ${product.stock} unidades disponibles.`, confirmButtonColor:'#f59e0b' });
                } else {
                    this.cart.push({ id: product.id, name: product.name, sku: product.sku, sale_price: product.sale_price, stock: product.stock, quantity: 1 });
                }
            },

            increaseQty(i) { if (this.cart[i].quantity < this.cart[i].stock) this.cart[i].quantity++; },
            decreaseQty(i) { if (this.cart[i].quantity > 1) this.cart[i].quantity--; else this.removeFromCart(i); },
            removeFromCart(i) { this.cart.splice(i, 1); },

            clearCart() {
                Swal.fire({ title:'¿Vaciar carrito?', icon:'warning', showCancelButton:true, confirmButtonColor:'#ef4444', cancelButtonText:'No', confirmButtonText:'Sí, vaciar' })
                    .then(r => { if(r.isConfirmed) { this.cart=[]; this.currentHeldSaleId=null; this.currentTicketLabel='Ticket Nuevo'; } });
            },

            async editPrice(i) {
                const item = this.cart[i];
                const { value } = await Swal.fire({ title:'Modificar Precio', input:'number', inputValue:item.sale_price, inputLabel:`Precio para: ${item.name}`, showCancelButton:true, confirmButtonColor:'#4f46e5', cancelButtonText:'Cancelar', confirmButtonText:'Guardar', inputValidator:v=>(!v||v<0)?'Precio inválido':null });
                if (value !== undefined) this.cart[i].sale_price = parseFloat(value);
            },

            // ─── Totales ───
            get total()    { return this.cart.reduce((s, i) => s + i.sale_price * i.quantity, 0); },
            get subtotal() { return this.total / 1.18; },
            get tax()      { return this.total - this.subtotal; },

            hasCredit() {
                if (!this.selectedClientId) return false;
                const c = this.clients.find(c => c.id == this.selectedClientId);
                return c ? (c.credit_limit - c.credit_balance) > 0 : false;
            },

            // ─── Checkout ───
            triggerCheckout() {
                if (this.cart.length === 0) return;
                if (this.paymentMethod === 'Crédito') {
                    if (!this.selectedClientId) { Swal.fire({ icon:'error', title:'Cliente Requerido', text:'Selecciona un cliente para ventas a crédito.', confirmButtonColor:'#4f46e5' }); return; }
                    const c = this.clients.find(c => c.id == this.selectedClientId);
                    if (c && this.total > (c.credit_limit - c.credit_balance)) { Swal.fire({ icon:'error', title:'Crédito Insuficiente', text:`Disponible: S/${(c.credit_limit-c.credit_balance).toFixed(2)}`, confirmButtonColor:'#4f46e5' }); return; }
                }
                this.checkoutModal = true;
            },

            // ─── Tickets en Espera ───
            async holdCurrentSale() {
                if (this.cart.length === 0) return;
                const { value: label } = await Swal.fire({ title:'Poner en Espera', input:'text', inputValue: this.currentTicketLabel === 'Ticket Nuevo' ? '' : this.currentTicketLabel, inputPlaceholder:'Ej: Cliente del mercado...', inputLabel:'Nombre del ticket (opcional)', showCancelButton:true, confirmButtonColor:'#f59e0b', cancelButtonText:'Cancelar', confirmButtonText:'⏸ Guardar en Espera' });
                if (label === undefined) return;
                try {
                    const payload = { label: label || this.currentTicketLabel, items: this.cart, client_id: this.selectedClientId || null, customer_name: this.customerName, payment_method: this.paymentMethod, total: this.total };
                    let res;
                    if (this.currentHeldSaleId) {
                        // Usamos la ruta base definida en Laravel para evitar el 404 en subdirectorios
                        const updateUrl = "{{ route('sales.held.index') }}/" + this.currentHeldSaleId;
                        res = await fetch(updateUrl, { method:'PUT', headers:{'Content-Type':'application/json','X-CSRF-TOKEN':'{{ csrf_token() }}','Accept':'application/json'}, body:JSON.stringify(payload) });
                    } else {
                        res = await fetch('{{ route("sales.held.store") }}', { method:'POST', headers:{'Content-Type':'application/json','X-CSRF-TOKEN':'{{ csrf_token() }}','Accept':'application/json'}, body:JSON.stringify(payload) });
                    }
                    const data = await res.json();
                    if (data.success) {
                        Swal.fire({ icon:'success', title:'Guardado', text:`"${payload.label}" en espera.`, confirmButtonColor:'#f59e0b', timer:1800, showConfirmButton:false });
                        this.cart=[]; this.currentHeldSaleId=null; this.currentTicketLabel='Ticket Nuevo'; this.customerName=''; this.selectedClientId=''; this.paymentMethod='Contado';
                        $('#client-select').val('').trigger('change');
                        setTimeout(() => location.reload(), 1900);
                    }
                } catch(e) { Swal.fire({ icon:'error', title:'Error', text:'No se pudo guardar el ticket.', confirmButtonColor:'#4f46e5' }); }
            },

            resumeHeldSale(heldId, items, label, clientId, customerName, paymentMethod) {
                const load = () => this._loadHeldSale(heldId, items, label, clientId, customerName, paymentMethod);
                if (this.cart.length > 0) {
                    Swal.fire({ title:'¿Cambiar de ticket?', text:'El carrito actual se perderá.', icon:'warning', showCancelButton:true, confirmButtonColor:'#4f46e5', cancelButtonText:'Cancelar', confirmButtonText:'Continuar' }).then(r => { if(r.isConfirmed) load(); });
                } else { load(); }
            },

            _loadHeldSale(heldId, items, label, clientId, customerName, paymentMethod) {
                this.cart = items.map(i => ({ id:i.id, name:i.name, sku:i.sku, sale_price:i.sale_price, stock:i.stock, quantity:i.quantity }));
                this.currentHeldSaleId = heldId; this.currentTicketLabel = label;
                this.customerName = customerName || ''; this.paymentMethod = paymentMethod || 'Contado';
                this.selectedClientId = clientId || '';
                if (clientId) $('#client-select').val(clientId).trigger('change');
                this.playBeep('success');
            },
        }));
    });
    </script>
    @endpush
</x-app-layout>
