<x-layout title="Lauck - Nueva Venta">
    @push('styles')
    <style>
        /* === MODO CLARO === */
        /* Contenedor principal del input */
        .select2-container--default .select2-selection--single {
            background-color: #d1d5dc !important; /* Fondo blanco */
            border: 1px solid #a1a1a1 !important; /* Borde gray-300 */
            color: #111827 !important;            /* Texto casi negro (gray-900) */
            height: 32px !important;
            padding: 0 0.5rem;
            display: flex;
            align-items: center;
            border-radius: 0.5rem; /* rounded-lg */
            transition: all 0.3s ease;
        }
        /* Texto seleccionado */
        .select2-container--default .select2-selection--single .select2-selection__rendered { 
            color: #111827 !important; 
            line-height: 32px !important; 
            padding-left: 12px;
        }
        /* La caja desplegable (Dropdown) */
        .select2-dropdown { 
            background-color: #d1d5dc !important; 
            border: 1px solid #d1d5db !important; 
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); /* Sombra suave para modo claro */
        }
        /* Opciones de la lista (texto normal) */
        .select2-results__option {
            color: #374151 !important; /* gray-700 */
        }
        /* Placeholder */
        .select2-container--default .select2-selection--single .select2-selection__placeholder {
            color: #6b7280 !important; /* gray-500 */
        }
        /* Input de búsqueda interno */
        .select2-search--dropdown .select2-search__field {
            background-color: #f3f4f6 !important; /* gray-100 */
            color: #111827 !important;
            border: 1px solid #d1d5db !important;
            border-radius: 0.375rem !important;
            padding: 6px 12px !important;
            outline: none;
        }
        /* Color de resalto (Hover o Navegación con teclado). Mantenemos tu color de marca */
        .select2-container--default .select2-results__option--highlighted.select2-results__option--selectable { 
            background-color: #ccff00 !important; /* neon-lime */
            color: #171717 !important; /* neutral-900 */
            font-weight: bold;
        }

        /* === MODO OSCURO === */
        /* Contenedor principal */
        :is(.dark) .select2-container--default .select2-selection--single {
            background-color: #262626 !important; /* neutral-800 */
            border-color: #404040 !important;     /* neutral-700 */
        }
        /* Texto seleccionado oscuro */
        :is(.dark) .select2-container--default .select2-selection--single .select2-selection__rendered { 
            color: white !important; 
        }
        /* Caja desplegable oscura */
        :is(.dark) .select2-dropdown { 
            background-color: #262626 !important; 
            border-color: #404040 !important; 
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.5); /* Sombra más fuerte */
        }
        /* Opciones de la lista oscura */
        :is(.dark) .select2-results__option {
            color: #d4d4d4 !important; /* gray-300 */
        }
        /* Placeholder oscuro */
        :is(.dark) .select2-container--default .select2-selection--single .select2-selection__placeholder {
            color: #9ca3af !important; /* gray-400 */
        }
        /* Input de búsqueda interno oscuro */
        :is(.dark) .select2-search--dropdown .select2-search__field {
            background-color: #171717 !important; /* neutral-900 */
            color: white !important;
            border-color: #404040 !important;
        }
    </style>
    @endpush

    <x-section-header subtitle="Punto de Venta" title="Nueva " highlight="Venta" />


    
    @if($errors->any())
        <div class="bg-red-900/50 border border-red-500 text-red-300 px-4 py-3 rounded-lg mb-6 shadow-sm">
            <ul class="list-disc list-inside">
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <div class="w-full max-w-5xl mx-auto bg-gray-200 dark:bg-panel-bg border border-neutral-400 dark:border-neutral-800 rounded-xl p-8 shadow-lg">
        <form action="{{ route('sales.store') }}" method="POST">
            @csrf

            <div class="grid grid-cols-1 md:grid-cols-12 gap-6 mb-4 border-b border-neutral-400 dark:border-neutral-700 pb-8">
                <div class="md:col-span-10">
                    <x-forms.label for="client_id" value="Cliente" />
                    <div class="relative">
                        <select name="client_id" class="w-full select2-basic">
                            <option value="">-- Consumidor Final (Anónimo) --</option>
                            @foreach($clients as $client)
                                <option value="{{ $client->id }}">{{ $client->name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
                <div class="md:col-span-2 flex items-end mb-1">
                    <a href="{{ route('clients.create', ['origin' => 'sales']) }}" target="_blank" class="inline-flex items-center dark:text-neon-lime text-lime-700/80 hover:text-lime-500 dark:hover:text-[#b3e600] font-bold text-sm transition-colors" title="Crear nuevo cliente">+ Nuevo Cliente</a>
                </div>
            </div>

            <div class="mb-4">
                <div class="flex justify-between items-end mb-4">
                    <x-forms.label value="Detalle de Productos" />
                    <div class="text-sm dark:text-gray-400 text-neutral-800">
                        Total Items: <span class="dark:text-white font-mono font-bold" id="item-count">1</span>
                    </div>
                </div>
                
                <div id="items-container" class="space-y-3">
                    
                    <div class="item-row grid grid-cols-1 md:grid-cols-12 gap-4 items-start bg-neutral-300/50 dark:bg-neutral-700/50 p-4 rounded-xl border dark:border-neutral-800 border-gray-400">
                        
                        <div class="md:col-span-6">
                            <x-forms.label value="Producto" />
                            <select name="items[0][product_id]" class="w-full select2-product product-select">
                                <option value="" data-price="0" selected disabled>Buscar producto...</option>
                                @foreach($products as $product)
                                    <option value="{{ $product->id }}" data-price="{{ $product->price }}">
                                        {{ $product->sku }} - {{ $product->name }} (Stock: {{ $product->stock_quantity }})
                                    </option>
                                @endforeach
                            </select>
                        </div>

                        <div class="md:col-span-2">
                            <x-forms.label value="Cant."/>
                            <x-forms.input type="number" name="items[0][quantity]" value="1" min="1" class="quantity-input border rounded-lg block w-full py-1! px-2"/>
                        </div>

                        <div class="md:col-span-3 text-right flex flex-col justify-center h-[42px] mt-6">
                            <span class="text-xs dark:text-gray-400 text-gray-700">Subtotal</span>
                            <span class="row-total text-lg font-bold text-lime-700 dark:text-neon-lime">$0.00</span>
                        </div>

                        <div class="md:col-span-1 flex items-end justify-end h-[42px] mt-6">
                            <button type="button" class="btn-remove dark:text-neutral-400 text-neutral-600 hover:text-red-500 hover:dark:text-red-400 transition-colors p-2" title="Quitar item">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <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>
                            </button>
                        </div>
                    </div>
                </div>

                <div class="mt-4">
                    <button type="button" id="btn-add-row" class="inline-flex items-center dark:text-neon-lime text-lime-600 dark:hover:text-[#b3e600] hover:text-lime-500 font-bold text-sm transition-colors">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
                        </svg>
                        Agregar otro producto
                    </button>
                </div>

                <div class="mt-5 flex justify-end items-center border-t border-neutral-400 dark:border-neutral-700 pt-6">
                    <div class="text-right">
                        <span class="block text-gray-600 dark:text-gray-400 text-sm mb-1">Monto Total a Pagar</span>
                        <span id="grand-total" class="text-3xl font-bold">$0.00</span>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 items-end border-t border-neutral-400 dark:border-neutral-700 pt-6">
                
                <div>
                    <x-forms.label for="payment_method" value="Método de Pago" />
                    <select name="payment_method" class="bg-gray-300 dark:bg-neutral-800 border border-neutral-400 dark:border-neutral-700 text-sm rounded-lg focus:ring-neon-lime focus:border-neon-lime block w-full p-2.5">
                        <option value="Efectivo">Efectivo</option>
                        <option value="Tarjeta de Débito">Tarjeta de Débito</option>
                        <option value="Tarjeta de Crédito">Tarjeta de Crédito</option>
                        <option value="Transferencia">Transferencia</option>
                    </select>
                </div>

                <div class="flex justify-end gap-4">
                    <a href="{{ route('sales.index') }}" class="px-4 py-2.5 text-red-500 border border-red-500 hover:bg-red-500 hover:text-white rounded-lg font-semibold text-sm transition-colors flex items-center">Cancelar</a>
                    <button type="submit" class="px-8 py-2.5 bg-neutral-900 dark:bg-neon-lime text-neon-lime dark:text-neutral-900 font-bold rounded-lg hover:bg-neutral-800 hover:dark:bg-[#b3e600] transition-colors shadow-lg dark:shadow-neon-lime/20">
                        Confirmar Venta
                    </button>
                </div>
            </div>

        </form>
    </div>

    <script type="module">
        let rowCount = 0;

        $(document).ready(function() {
            initSelect2();
            actualizarBloqueos(); // Bloqueo inicial

            // --- AGREGAR FILA ---
            $('#btn-add-row').click(function() {
                rowCount++;
                const container = $('#items-container');
                const firstRow = container.find('.item-row').first();

                $('.select2-product').select2('destroy'); // Destruir

                const newRow = firstRow.clone(); // Clonar

                initSelect2(); // Reactivar originales

                // Limpiar nueva fila
                newRow.find('input').val(1);
                newRow.find('.row-total').text('$0.00');
                
                // Actualizar atributos
                newRow.find('select').attr('name', `items[${rowCount}][product_id]`).val('');
                newRow.find('input').attr('name', `items[${rowCount}][quantity]`);

                // Desbloquear opciones en la nueva fila (vital)
                newRow.find('option').prop('disabled', false);

                container.append(newRow);
                initSelect2(); // Activar nueva
                actualizarBloqueos(); // Recalcular bloqueos
                actualizarContadorItems();
            });

            // --- ELIMINAR FILA ---
            $(document).on('click', '.btn-remove', function() {
                if ($('.item-row').length > 1) {
                    $(this).closest('.item-row').remove();
                    recalcularTodo();
                    actualizarBloqueos();
                    actualizarContadorItems();
                } else {
                    alert("Debe haber al menos un producto.");
                }
            });

            // --- EVENTOS ---
            $(document).on('select2:select input', '.product-select, .quantity-input', function() {
                let row = $(this).closest('.item-row');
                calcularFila(row);
                recalcularTodo();
                
                if ($(this).hasClass('product-select')) {
                    actualizarBloqueos();
                }
            });
        });

        // --- FUNCIONES ---
        function initSelect2() {
            $('.select2-basic').select2({ width: '100%' });
            $('.select2-product').select2({ 
                width: '100%', 
                placeholder: "Buscar producto...",
                language: { noResults: () => "Sin resultados" }
            });
        }

        function calcularFila(row) {
            let select = row.find('.product-select');
            let input = row.find('.quantity-input');
            let option = select.find(':selected');
            let price = parseFloat(option.data('price')) || 0;
            let qty = parseInt(input.val()) || 0;
            let subtotal = price * qty;
            row.find('.row-total').text('$' + subtotal.toFixed(2));
        }

        function recalcularTodo() {
            let grandTotal = 0;
            $('.item-row').each(function() {
                let row = $(this);
                let price = parseFloat(row.find('.product-select').find(':selected').data('price')) || 0;
                let qty = parseInt(row.find('.quantity-input').val()) || 0;
                grandTotal += (price * qty);
            });
            $('#grand-total').text('$' + grandTotal.toFixed(2));
        }

        function actualizarContadorItems() {
            $('#item-count').text($('.item-row').length);
        }

        function actualizarBloqueos() {
            let seleccionados = [];
            $('.product-select').each(function() {
                let valor = $(this).val();
                if (valor) seleccionados.push(valor);
            });

            $('.product-select').each(function() {
                let selectActual = $(this);
                let miValor = selectActual.val();
                selectActual.find('option').each(function() {
                    let opcion = $(this);
                    let valorOpcion = opcion.val();
                    if (!valorOpcion) return;

                    if (seleccionados.includes(valorOpcion) && valorOpcion != miValor) {
                        opcion.prop('disabled', true);
                    } else {
                        opcion.prop('disabled', false);
                    }
                });
            });
        }
    </script>
</x-layout>
