@extends('layouts.app')

@section('title', 'Transferencia')
@section('full_width', '1')



@section('content')
    @php
        $formItems = old('items', []);
    @endphp
    <div class="content-stage">
        <div class="card card-soft border-0">
            <div class="card-body p-4 p-md-5">
                <h1 class="h4 mb-2">Transferencia o prestamo de alimentos y utensilios</h1>
                <p class="text-muted-brand mb-4">Prepare los items y registre los responsables para la transferencia.</p>

                <div class="page-shell">
                    @if (session('operacion_resultado'))
                        @php
                            $resultado = session('operacion_resultado');
                        @endphp
                        <section class="section-card operation-result">
                            <div class="section-title">Resultado de operacion</div>
                            <div class="row g-2 mb-3">
                                <div class="col-12 col-md-3"><span class="text-muted-brand">Nro:</span> <strong>#{{ $resultado['numero'] ?? '-' }}</strong></div>
                                <div class="col-12 col-md-3"><span class="text-muted-brand">Destino:</span> <strong>{{ $resultado['ubicacion'] ?? '-' }}</strong></div>
                                <div class="col-12 col-md-3"><span class="text-muted-brand">Transportista:</span> <strong>{{ ($resultado['transportista'] ?? '-') . ((filled($resultado['transportista_nombre'] ?? '') ? ' - ' . $resultado['transportista_nombre'] : '')) }}</strong></div>
                                <div class="col-12 col-md-3"><span class="text-muted-brand">Items:</span> <strong>{{ $resultado['total_items'] ?? 0 }}</strong></div>
                                <div class="col-12 col-md-6"><span class="text-muted-brand">Emisor:</span> <strong>{{ ($resultado['emisor'] ?? '-') . ((filled($resultado['emisor_nombre'] ?? '') ? ' - ' . $resultado['emisor_nombre'] : '')) }}</strong></div>
                                <div class="col-12 col-md-6"><span class="text-muted-brand">Receptor:</span> <strong>{{ ($resultado['receptor'] ?? '-') . ((filled($resultado['receptor_nombre'] ?? '') ? ' - ' . $resultado['receptor_nombre'] : '')) }}</strong></div>
                            </div>
                            @if (! empty($resultado['numero']))
                                <div class="d-flex flex-wrap gap-2 mb-3">
                                    <a href="{{ $resultado['receipt_url'] ?? route('asignacion.operacion.show', ['tipo' => 'transferencia', 'numero' => $resultado['numero']]) }}" class="btn btn-outline-primary btn-sm">Ver comprobante</a>
                                    <a href="{{ $resultado['export_url'] ?? route('asignacion.operacion.export', ['tipo' => 'transferencia', 'numero' => $resultado['numero']]) }}" class="btn btn-success btn-sm">Exportar Excel (.xlsx)</a>
                                </div>
                            @endif
                            <div class="table-responsive">
                                <table class="table table-sm align-middle mb-0">
                                    <thead>
                                        <tr>
                                            <th>Codigo</th>
                                            <th>Descripcion</th>
                                            <th>Cant.</th>
                                            <th>Stock antes</th>
                                            <th>Stock despues</th>
                                            <th>Fuente despues</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach (($resultado['items'] ?? []) as $row)
                                            <tr>
                                                <td>{{ $row['codigo'] ?? '-' }}</td>
                                                <td>{{ $row['descripcion'] ?? '-' }}</td>
                                                <td>{{ $row['cantidad'] ?? 0 }}</td>
                                                <td>{{ $row['stock_antes'] ?? 0 }}</td>
                                                <td>{{ $row['stock_despues'] ?? 0 }}</td>
                                                <td>{{ $row['fuente_despues'] ?? 0 }}</td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        </section>
                    @endif

                    <section class="section-card">
                        <div class="section-title">Solicitante</div>
                        <div class="summary-bar">
                            <div class="summary-item">
                                <div class="label">Prestamista (cedula validada)</div>
                                <div class="value">{{ $prestamista }}</div>
                            </div>
                            <div class="summary-item">
                                <div class="label">Nombre completo</div>
                                <div class="value">{{ $prestamistaUser->nombre ?? 'Sin nombre' }}</div>
                            </div>
                            <div class="summary-item">
                                <div class="label">Tipo de usuario</div>
                                <div class="value">{{ $tipoLabel }}</div>
                            </div>
                            <div class="summary-item">
                                <div class="label">Numero de dependencia</div>
                                <div class="value">{{ $prestamistaUser->dependencia ?? 'Sin dependencia' }}</div>
                            </div>
                        </div>
                    </section>

                    <form id="entregar-form" method="POST" action="{{ route('asignacion.transferencia.entregar') }}" class="form-shell">
                        @csrf

                        <section class="section-card">
                            <div class="section-title-row">
                                <div class="section-title">Items agregados</div>
                                <button type="button" class="btn btn-brand action-btn" data-bs-toggle="modal" data-bs-target="#agregarItemModal">Agregar item</button>
                            </div>
                            <div class="table-wrap">
                                <div class="table-responsive">
                                    <table class="table table-sm align-middle items-table">
                                        <thead>
                                            <tr>
                                                <th class="description-col">Bien</th>
                                                <th class="type-col">Tipo / Marca</th>
                                                <th class="stock-col">Stock</th>
                                                <th class="qty-col">Cantidad</th>
                                                <th class="obs-col">Obs.</th>
                                                <th class="actions-col">Acciones</th>
                                            </tr>
                                        </thead>
                                        <tbody id="items-table-body">
                                            @forelse ($formItems as $index => $item)
                                                <tr data-item-row="true">
                                                    @include('partials.asignacion.item-row-cells-compact', [
                                                        'index' => $index,
                                                        'codigo' => $item['codigo'] ?? '-',
                                                        'codigoAttr' => $item['codigo'] ?? '',
                                                        'almacenadoAttr' => $item['almacenado'] ?? '',
                                                        'entregadoAttr' => $item['entregado'] ?? '',
                                                        'descripcion' => $item['descripcion'] ?? '-',
                                                        'descripcionAttr' => $item['descripcion'] ?? '',
                                                        'marca' => $item['marca'] ?? '-',
                                                        'marcaAttr' => $item['marca'] ?? '',
                                                        'tipo' => $item['tipo'] ?? '-',
                                                        'tipoAttr' => $item['tipo'] ?? '',
                                                        'stock' => $item['stock'] ?? '-',
                                                        'stockAttr' => $item['stock'] ?? '',
                                                        'stockDisponibleAttr' => $item['stock_disponible'] ?? 0,
                                                        'cantidadAttr' => $item['cantidad'] ?? 1,
                                                        'observacionAttr' => $item['observacion'] ?? '',
                                                    ])
                                                </tr>
                                            @empty
                                                <tr id="items-empty-row">
                                                    <td colspan="6" class="items-empty-cell">
                                                        <div class="items-empty-state">
                                                            <strong>No hay items agregados</strong>
                                                            <span>Use el boton "Agregar item" para comenzar a armar la transferencia.</span>
                                                        </div>
                                                    </td>
                                                </tr>
                                            @endforelse
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </section>

                        <section class="section-card">
                            <div class="section-title">Datos de transferencia</div>
                            <div class="delivery-grid mb-3">
                                <div>
                                    <label class="form-label" for="cedulaTransportista">Cedula del transportista</label>
                                    <select id="cedulaTransportista" name="cedulaTransportista" class="form-select" required>
                                        <option value="">Seleccione personal</option>
                                        @foreach ($personal as $persona)
                                            <option value="{{ $persona->cedula }}" {{ old('cedulaTransportista') === $persona->cedula ? 'selected' : '' }}>{{ $persona->cedula }} - {{ $persona->nombre }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div>
                                    <label class="form-label" for="emisor">Emisor</label>
                                    <select id="emisor" name="emisor" class="form-select" required>
                                        <option value="">Seleccione personal</option>
                                        @foreach ($personal as $persona)
                                            <option value="{{ $persona->cedula }}" {{ old('emisor') === $persona->cedula ? 'selected' : '' }}>{{ $persona->cedula }} - {{ $persona->nombre }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div>
                                    <label class="form-label" for="receptor">Receptor</label>
                                    <select id="receptor" name="receptor" class="form-select" required>
                                        <option value="">Seleccione personal</option>
                                        @foreach ($personal as $persona)
                                            <option value="{{ $persona->cedula }}" {{ old('receptor') === $persona->cedula ? 'selected' : '' }}>{{ $persona->cedula }} - {{ $persona->nombre }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div>
                                    <label class="form-label" for="ubicacion">Ubicacion o destino</label>
                                    <select id="ubicacion" name="ubicacion" class="form-select" required>
                                        <option value="">Seleccione un sitio o embarcacion</option>
                                        <optgroup label="Sitios">
                                            @foreach ($destinos as $destino)
                                                <option value="{{ $destino->id }}" {{ old('ubicacion') == $destino->id ? 'selected' : '' }}>{{ $destino->nombre }}</option>
                                            @endforeach
                                        </optgroup>
                                        <optgroup label="Embarcaciones">
                                            @foreach ($embarcaciones as $embarcacion)
                                                <option value="{{ $embarcacion->id }}" {{ old('ubicacion') == $embarcacion->id ? 'selected' : '' }}>{{ $embarcacion->nombre }}</option>
                                            @endforeach
                                        </optgroup>
                                    </select>
                                </div>
                            </div>

                            <div class="d-flex justify-content-end">
                                <button type="button" id="abrir-confirmacion-entrega-btn" class="btn btn-brand action-btn" data-bs-toggle="modal" data-bs-target="#confirmarEntregaModal">Entregar transferencia</button>
                            </div>
                        </section>
                    </form>
                </div>
            </div>
        </div>
    </div>

    @include('partials.items.item-selection-modal', [
        'bienes' => $bienes,
        'stockWarningId' => 'item-stock-warning',
        'submitButtonText' => 'Agregar',
        'showScanButton' => true,
        'searchHint' => 'Escanee el codigo del bien para buscarlo en el listado.',
        'previewGridClass' => 'preview-grid modal-preview',
    ])

    <div class="modal fade" id="confirmarBorradoModal" tabindex="-1" aria-labelledby="confirmarBorradoModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-sm modal-dialog-centered">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h2 class="modal-title fs-6" id="confirmarBorradoModalLabel">Confirmar borrado</h2>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <p class="mb-0 text-muted-brand">¿Desea borrar este item de la lista?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-primary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="button" id="confirmar-borrado-btn" class="btn btn-brand">Borrar</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="confirmarEntregaModal" tabindex="-1" aria-labelledby="confirmarEntregaModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-sm modal-dialog-centered">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h2 class="modal-title fs-6" id="confirmarEntregaModalLabel">Confirmar entrega</h2>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <p class="mb-0 text-muted-brand">Esta accion procesara el carrito y actualizara el inventario. Desea continuar?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-primary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="button" id="confirmar-entrega-btn" class="btn btn-brand">Confirmar</button>
                </div>
            </div>
        </div>
    </div>

    @include('partials.asignacion.item-row-template-compact')
@endsection

@include('partials.items.item-selection-modal-script')

@push('scripts')
    <script>
        (() => {
            const bienes = @json($bienesData);
            const storageKey = `asignacion-transferencia:${@json($prestamista)}`;
            const shouldClearCart = @json((bool) session('clear_transferencia_cart', false));
            const buscarInput = document.getElementById('buscarItemInput');
            const agregarItemBtn = document.getElementById('agregar-item-btn');
            const itemsTableBody = document.getElementById('items-table-body');
            const itemRowTemplate = document.getElementById('asignacion-item-row-template-compact');
            const modalTitle = document.getElementById('agregarItemModalLabel');
            const entregarForm = document.getElementById('entregar-form');
            const cedulaTransportistaInput = document.getElementById('cedulaTransportista');
            const emisorInput = document.getElementById('emisor');
            const receptorInput = document.getElementById('receptor');
            const ubicacionInput = document.getElementById('ubicacion');
            const modalObservacionInput = document.getElementById('modalObservacionInput');
            const duplicateWarning = document.getElementById('item-duplicate-warning');
            const stockWarning = document.getElementById('item-stock-warning');
            const detalleTipo = document.getElementById('detalle_tipo');
            const detalleDescripcion = document.getElementById('detalle_descripcion');
            const detalleAlmacenado = document.getElementById('detalle_almacenado');
            const detalleEnStock = document.getElementById('detalle_en_stock');
            const detalleEntregado = document.getElementById('detalle_entregado');
            const agregarItemModalElement = document.getElementById('agregarItemModal');
            const agregarItemModal = agregarItemModalElement ? bootstrap.Modal.getOrCreateInstance(agregarItemModalElement) : null;
            const confirmarBorradoModalElement = document.getElementById('confirmarBorradoModal');
            const confirmarBorradoModal = confirmarBorradoModalElement ? bootstrap.Modal.getOrCreateInstance(confirmarBorradoModalElement) : null;
            const confirmarBorradoBtn = document.getElementById('confirmar-borrado-btn');
            const confirmarEntregaModalElement = document.getElementById('confirmarEntregaModal');
            const confirmarEntregaModal = confirmarEntregaModalElement ? bootstrap.Modal.getOrCreateInstance(confirmarEntregaModalElement) : null;
            const confirmarEntregaBtn = document.getElementById('confirmar-entrega-btn');
            const scannerController = window.createBarcodeScannerBuffer({
                onScan: (value) => {
                    processScannedValue(value);
                },
            });
            let currentBien = null;
            let editingRow = null;
            let pendingDeleteRow = null;
            let rowIndex = itemsTableBody ? itemsTableBody.querySelectorAll('tr[data-item-row="true"]').length : 0;
            let isAgregarItemModalOpen = false;

            if (!buscarInput || !agregarItemBtn || !itemsTableBody || !(itemRowTemplate instanceof HTMLTemplateElement)) {
                return;
            }

            const bienSearch = window.createBienSearchEngine(bienes);
            const formatTipoMarca = (bien) => [bien?.tipo, bien?.marca]
                .map((value) => String(value ?? '').trim())
                .filter((value) => value !== '')
                .join(' / ');

            const setEmptyState = () => {
                currentBien = null;
                detalleTipo.textContent = 'N/D';
                detalleDescripcion.textContent = 'N/D';
                detalleAlmacenado.textContent = 'N/D';
                detalleEnStock.textContent = 'N/D';
                detalleEntregado.textContent = 'N/D';
            };

            const applyBien = (bien) => {
                if (!bien) {
                    setEmptyState();
                    return;
                }

                currentBien = bien;
                detalleTipo.textContent = formatTipoMarca(bien) || 'N/D';
                detalleDescripcion.textContent = bien.descripcion ?? 'N/D';
                detalleAlmacenado.textContent = bien.almacenado ?? 'N/D';
                detalleEnStock.textContent = bien.en_stock ?? 'N/D';
                detalleEntregado.textContent = bien.entregado ?? 'N/D';
            };

            const findBien = (value) => {
                return bienSearch.resolve(value);
            };

            const processScannedValue = (rawValue) => {
                const scannedValue = String(rawValue ?? '').trim();
                if (scannedValue === '') {
                    return;
                }

                const bien = findBien(scannedValue);
                if (!bien) {
                    showStockWarning(scannedValue);
                    return;
                }

                hideDuplicateWarning();
                hideStockWarning();

                if (!isAgregarItemModalOpen) {
                    addRow(bien);
                    setEmptyState();
                    return;
                }

                populateModalFromBien(bien);
            };

            const refreshRowNumbers = () => {
                const rows = itemsTableBody.querySelectorAll('tr[data-item-row="true"]');
                rows.forEach((row, index) => {
                    const cell = row.querySelector('.row-number');
                    if (cell) {
                        cell.textContent = String(index + 1);
                    }
                });
            };

            const ensureEmptyStateRow = () => {
                const rows = itemsTableBody.querySelectorAll('tr[data-item-row="true"]');
                const emptyRow = document.getElementById('items-empty-row');

                if (rows.length === 0 && !emptyRow) {
                    const row = document.createElement('tr');
                    row.id = 'items-empty-row';
                    row.innerHTML = '<td colspan="6" class="items-empty-cell"><div class="items-empty-state"><strong>No hay items agregados</strong><span>Use el boton "Agregar item" para comenzar a armar la transferencia.</span></div></td>';
                    itemsTableBody.appendChild(row);
                }

                if (rows.length > 0 && emptyRow) {
                    emptyRow.remove();
                }
            };

            const escapeAttribute = (value) => String(value ?? '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
            const escapeHtml = (value) => String(value ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
            const buildRowMarkup = (bien, itemState, index) => {
                const stockValue = bien.stock ?? bien.en_stock ?? '0';
                const stockDisponible = bien.stock_disponible ?? bien.en_stock ?? 0;
                const almacenado = bien.almacenado ?? '';
                const entregado = bien.entregado ?? '';
                const cantidad = itemState.cantidad ?? 1;
                const observacion = itemState.observacion ?? '';
                const replacements = {
                    '__INDEX__': String(index),
                    '__CODIGO__': escapeHtml(bien.codigo ?? ''),
                    '__CODIGO_ATTR__': escapeAttribute(bien.codigo ?? ''),
                    '__ALMACENADO_ATTR__': escapeAttribute(almacenado),
                    '__ENTREGADO_ATTR__': escapeAttribute(entregado),
                    '__DESCRIPCION__': escapeHtml(bien.descripcion ?? ''),
                    '__DESCRIPCION_ATTR__': escapeAttribute(bien.descripcion ?? ''),
                    '__MARCA__': escapeHtml(bien.marca ?? ''),
                    '__MARCA_ATTR__': escapeAttribute(bien.marca ?? ''),
                    '__TIPO__': escapeHtml(bien.tipo ?? ''),
                    '__TIPO_ATTR__': escapeAttribute(bien.tipo ?? ''),
                    '__STOCK__': escapeHtml(stockValue),
                    '__STOCK_ATTR__': escapeAttribute(stockValue),
                    '__STOCK_DISPONIBLE_ATTR__': escapeAttribute(stockDisponible),
                    '__CANTIDAD_ATTR__': escapeAttribute(cantidad),
                    '__OBSERVACION_ATTR__': escapeAttribute(observacion),
                    '__OBSERVACION_VISIBILITY__': String(observacion).trim() === '' ? 'd-none' : '',
                };

                return Object.entries(replacements).reduce((markup, [token, value]) => markup.replaceAll(token, value), itemRowTemplate.innerHTML);
            };

            const setModalMode = (mode) => {
                const isEditMode = mode === 'edit';
                if (modalTitle) {
                    modalTitle.textContent = isEditMode ? 'Editar item' : 'Seleccion del item';
                }
                agregarItemBtn.textContent = isEditMode ? 'Guardar cambios' : 'Agregar Item';
                buscarInput.readOnly = isEditMode;
            };

            const populateModalFromBien = (bien, observation = '') => {
                if (!bien) {
                    resetModalState();
                    return;
                }

                currentBien = bien;
                buscarInput.value = bienSearch.getSearchLabel(bien);
                detalleTipo.textContent = formatTipoMarca(bien) || 'N/D';
                detalleDescripcion.textContent = bien.descripcion ?? 'N/D';
                detalleAlmacenado.textContent = bien.almacenado ?? 'N/D';
                detalleEnStock.textContent = bien.en_stock ?? bien.stock ?? 'N/D';
                detalleEntregado.textContent = bien.entregado ?? 'N/D';
                if (modalObservacionInput) {
                    modalObservacionInput.value = observation;
                }
            };

            const collectItemsState = () => {
                return Array.from(itemsTableBody.querySelectorAll('tr[data-item-row="true"]')).map((row) => ({
                    codigo: row.querySelector('input[name$="[codigo]"]')?.value ?? '',
                    almacenado: row.querySelector('input[name$="[almacenado]"]')?.value ?? '',
                    descripcion: row.querySelector('input[name$="[descripcion]"]')?.value ?? '',
                    entregado: row.querySelector('input[name$="[entregado]"]')?.value ?? '',
                    marca: row.querySelector('input[name$="[marca]"]')?.value ?? '',
                    tipo: row.querySelector('input[name$="[tipo]"]')?.value ?? '',
                    stock: row.querySelector('input[name$="[stock]"]')?.value ?? '',
                    stock_disponible: row.querySelector('input[name$="[stock_disponible]"]')?.value ?? '0',
                    cantidad: row.querySelector('input[name$="[cantidad]"]')?.value ?? '1',
                    observacion: row.querySelector('input[name$="[observacion]"]')?.value ?? '',
                }));
            };

            const saveState = () => {
                const payload = {
                    cedulaTransportista: cedulaTransportistaInput?.value ?? '',
                    emisor: emisorInput?.value ?? '',
                    receptor: receptorInput?.value ?? '',
                    ubicacion: ubicacionInput?.value ?? '',
                    items: collectItemsState(),
                };

                sessionStorage.setItem(storageKey, JSON.stringify(payload));
            };

            const hideAllTooltips = (exceptElement = null) => {
                document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach((element) => {
                    if (element === exceptElement) {
                        return;
                    }

                    const tooltipInstance = bootstrap.Tooltip.getInstance(element);
                    if (tooltipInstance) {
                        tooltipInstance.hide();
                    }
                });
            };

            const updateObservationIndicator = (row) => {
                const observationInput = row.querySelector('input[name$="[observacion]"]');
                const indicator = row.querySelector('.observation-indicator');

                if (!observationInput || !indicator) {
                    return;
                }

                const value = observationInput.value.trim();
                const tooltipInstance = bootstrap.Tooltip.getInstance(indicator);

                if (value === '') {
                    if (tooltipInstance) {
                        tooltipInstance.hide();
                        tooltipInstance.dispose();
                    }
                    indicator.classList.add('d-none');
                    indicator.setAttribute('data-bs-title', '');
                    return;
                }

                indicator.classList.remove('d-none');
                indicator.setAttribute('data-bs-title', value);
                if (tooltipInstance) {
                    tooltipInstance.dispose();
                }
                bootstrap.Tooltip.getOrCreateInstance(indicator);
            };

            const hideDuplicateWarning = () => {
                if (duplicateWarning) {
                    duplicateWarning.classList.add('d-none');
                }
            };

            const hideStockWarning = () => {
                if (stockWarning) {
                    stockWarning.classList.add('d-none');
                    stockWarning.textContent = '';
                }
            };

            const showStockWarning = (value) => {
                if (!stockWarning) {
                    return;
                }

                const scanned = String(value ?? '').trim();
                stockWarning.textContent = scanned === ''
                    ? 'El item escaneado no esta disponible en stock.'
                    : `El item escaneado (${scanned}) no esta disponible en stock.`;
                stockWarning.classList.remove('d-none');
            };

            const showDuplicateWarning = () => {
                if (duplicateWarning) {
                    duplicateWarning.classList.remove('d-none');
                }
            };

            const findRowByCode = (codigo) => {
                const expectedCode = String(codigo ?? '');
                return Array.from(itemsTableBody.querySelectorAll('tr[data-item-row="true"]')).find((row) => {
                    const rowCode = row.querySelector('input[name$="[codigo]"]')?.value ?? '';
                    return rowCode === expectedCode;
                }) ?? null;
            };

            const increaseExistingRowQuantity = (codigo) => {
                const existingRow = findRowByCode(codigo);
                if (!existingRow) {
                    return false;
                }

                const qtyInput = existingRow.querySelector('input.cantidad-input');
                if (!(qtyInput instanceof HTMLInputElement)) {
                    return false;
                }

                const currentQty = Number(qtyInput.value || '0');
                const maxQty = Number(qtyInput.max || '0');

                if (maxQty > 0 && currentQty >= maxQty) {
                    showStockWarning(`No se puede aumentar. Stock maximo disponible para ${codigo}: ${maxQty}.`);
                    return false;
                }

                qtyInput.value = String(currentQty + 1);
                hideStockWarning();
                hideDuplicateWarning();
                saveState();
                return true;
            };

            const resetModalState = () => {
                editingRow = null;
                setModalMode('add');
                buscarInput.value = '';
                if (modalObservacionInput) {
                    modalObservacionInput.value = '';
                }
                hideDuplicateWarning();
                hideStockWarning();
                setEmptyState();
            };

            const addRow = (bien, itemState = {}) => {
                if (!bien) {
                    return false;
                }

                if (findRowByCode(bien.codigo)) {
                    return increaseExistingRowQuantity(bien.codigo);
                }

                hideDuplicateWarning();

                const cantidad = itemState.cantidad ?? 1;
                const observacion = itemState.observacion ?? modalObservacionInput?.value ?? '';

                const emptyRow = document.getElementById('items-empty-row');
                if (emptyRow) {
                    emptyRow.remove();
                }

                const row = document.createElement('tr');
                row.dataset.itemRow = 'true';
                row.innerHTML = buildRowMarkup(bien, {
                    cantidad,
                    observacion,
                }, rowIndex);

                itemsTableBody.appendChild(row);
                row.querySelectorAll('[data-bs-toggle="tooltip"]').forEach((element) => {
                    if (!element.classList.contains('d-none')) {
                        bootstrap.Tooltip.getOrCreateInstance(element);
                    }
                });
                updateObservationIndicator(row);
                rowIndex += 1;
                refreshRowNumbers();
                saveState();
                return true;
            };

            const restoreState = () => {
                const rawState = sessionStorage.getItem(storageKey);
                if (!rawState) {
                    saveState();
                    return;
                }

                try {
                    const state = JSON.parse(rawState);

                    if (cedulaTransportistaInput && typeof state.cedulaTransportista === 'string') {
                        cedulaTransportistaInput.value = state.cedulaTransportista;
                    }

                    if (emisorInput && typeof state.emisor === 'string') {
                        emisorInput.value = state.emisor;
                    }

                    if (receptorInput && typeof state.receptor === 'string') {
                        receptorInput.value = state.receptor;
                    }

                    if (ubicacionInput && typeof state.ubicacion === 'string') {
                        ubicacionInput.value = state.ubicacion;
                    }

                    if (Array.isArray(state.items)) {
                        itemsTableBody.innerHTML = '';
                        rowIndex = 0;

                        state.items.forEach((item) => {
                            addRow({
                                codigo: item.codigo,
                                almacenado: item.almacenado,
                                descripcion: item.descripcion,
                                entregado: item.entregado,
                                marca: item.marca,
                                tipo: item.tipo,
                                stock: item.stock,
                                stock_disponible: item.stock_disponible,
                            }, item);
                        });
                    }
                } catch (error) {
                    sessionStorage.removeItem(storageKey);
                }

                ensureEmptyStateRow();
                refreshRowNumbers();
            };

            buscarInput.addEventListener('input', () => {
                if (editingRow) {
                    return;
                }
                hideDuplicateWarning();
                hideStockWarning();
                applyBien(findBien(buscarInput.value));
            });

            document.addEventListener('keydown', (event) => {
                if (editingRow) {
                    return;
                }

                const target = event.target;
                const isEditableTarget = target instanceof HTMLElement
                    && (target.matches('input, textarea, select') || target.isContentEditable);

                if (!isAgregarItemModalOpen && isEditableTarget) {
                    return;
                }

                scannerController.handleKeydown(event);
            });

            agregarItemBtn.addEventListener('click', () => {
                if (!currentBien) {
                    return;
                }

                if (editingRow) {
                    const observationInput = editingRow.querySelector('input[name$="[observacion]"]');
                    if (observationInput) {
                        observationInput.value = modalObservacionInput?.value ?? '';
                    }
                    updateObservationIndicator(editingRow);
                    saveState();
                    if (agregarItemModal) {
                        agregarItemModal.hide();
                    }
                    return;
                }

                const added = addRow(currentBien);
                if (!added) {
                    return;
                }

                buscarInput.value = '';
                setEmptyState();
                hideDuplicateWarning();
                if (agregarItemModal) {
                    agregarItemModal.hide();
                }
            });

            itemsTableBody.addEventListener('click', (event) => {
                const target = event.target;
                if (!(target instanceof HTMLElement)) {
                    return;
                }

                if (target.classList.contains('editar-item-btn')) {
                    hideAllTooltips(target);
                    const row = target.closest('tr[data-item-row="true"]');
                    if (!row) {
                        return;
                    }

                    const codigo = row.querySelector('input[name$="[codigo]"]')?.value ?? '';
                    const almacenado = row.querySelector('input[name$="[almacenado]"]')?.value ?? '';
                    const descripcion = row.querySelector('input[name$="[descripcion]"]')?.value ?? '';
                    const entregado = row.querySelector('input[name$="[entregado]"]')?.value ?? '';
                    const marca = row.querySelector('input[name$="[marca]"]')?.value ?? '';
                    const tipo = row.querySelector('input[name$="[tipo]"]')?.value ?? '';
                    const stock = row.querySelector('input[name$="[stock]"]')?.value ?? '';
                    const stockDisponible = row.querySelector('input[name$="[stock_disponible]"]')?.value ?? 0;
                    const observacion = row.querySelector('input[name$="[observacion]"]')?.value ?? '';

                    editingRow = row;
                    setModalMode('edit');
                    hideDuplicateWarning();
                    hideStockWarning();
                    populateModalFromBien({
                        codigo,
                        almacenado,
                        descripcion,
                        entregado,
                        marca,
                        tipo,
                        stock,
                        en_stock: stock,
                        stock_disponible: stockDisponible,
                    }, observacion);

                    if (agregarItemModal) {
                        agregarItemModal.show();
                    }
                    return;
                }

                if (!target.classList.contains('borrar-item-btn')) {
                    if (target instanceof HTMLElement && target.classList.contains('observation-indicator')) {
                        hideAllTooltips(target);
                        const tooltipInstance = bootstrap.Tooltip.getOrCreateInstance(target);
                        window.setTimeout(() => {
                            tooltipInstance.hide();
                            target.blur();
                        }, 1200);
                    }
                    return;
                }

                target.blur();
                hideAllTooltips(target);
                const tooltipInstance = bootstrap.Tooltip.getInstance(target);
                if (tooltipInstance) {
                    tooltipInstance.hide();
                    tooltipInstance.dispose();
                }

                const row = target.closest('tr[data-item-row="true"]');
                if (row) {
                    pendingDeleteRow = row;
                    if (confirmarBorradoModal) {
                        confirmarBorradoModal.show();
                    }
                }
            });

            itemsTableBody.addEventListener('input', (event) => {
                const target = event.target;
                if (!(target instanceof HTMLInputElement)) {
                    return;
                }

                if (!target.classList.contains('cantidad-input')) {
                    return;
                }

                const max = Number(target.max || '0');
                const value = Number(target.value || '0');

                if (max > 0 && value > max) {
                    target.value = String(max);
                }

                if (value < 1 && target.value !== '') {
                    target.value = '1';
                }

                saveState();
            });

            itemsTableBody.addEventListener('mouseover', (event) => {
                const target = event.target;
                if (!(target instanceof HTMLElement)) {
                    return;
                }

                const tooltipTarget = target.closest('[data-bs-toggle="tooltip"]');
                if (tooltipTarget instanceof HTMLElement) {
                    hideAllTooltips(tooltipTarget);
                }
            });

            itemsTableBody.addEventListener('focusin', (event) => {
                const target = event.target;
                if (!(target instanceof HTMLElement)) {
                    return;
                }

                const tooltipTarget = target.closest('[data-bs-toggle="tooltip"]');
                if (tooltipTarget instanceof HTMLElement) {
                    hideAllTooltips(tooltipTarget);
                }
            });

            cedulaTransportistaInput?.addEventListener('change', saveState);
            emisorInput?.addEventListener('change', saveState);
            receptorInput?.addEventListener('change', saveState);
            ubicacionInput?.addEventListener('input', saveState);

            confirmarEntregaBtn?.addEventListener('click', () => {
                if (!entregarForm) {
                    return;
                }

                if (confirmarEntregaModal) {
                    confirmarEntregaModal.hide();
                }

                if (typeof entregarForm.requestSubmit === 'function') {
                    entregarForm.requestSubmit();
                    return;
                }

                entregarForm.submit();
            });

            confirmarBorradoBtn?.addEventListener('click', () => {
                if (!pendingDeleteRow) {
                    return;
                }

                pendingDeleteRow.remove();
                pendingDeleteRow = null;
                refreshRowNumbers();
                ensureEmptyStateRow();
                saveState();

                if (confirmarBorradoModal) {
                    confirmarBorradoModal.hide();
                }
            });

            if (shouldClearCart) {
                sessionStorage.removeItem(storageKey);
            }

            restoreState();
            setEmptyState();
            document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach((element) => {
                if (!element.classList.contains('d-none')) {
                    bootstrap.Tooltip.getOrCreateInstance(element);
                }
            });
            itemsTableBody.querySelectorAll('tr[data-item-row="true"]').forEach((row) => {
                updateObservationIndicator(row);
            });

            if (agregarItemModalElement) {
                agregarItemModalElement.addEventListener('shown.bs.modal', () => {
                    isAgregarItemModalOpen = true;
                    scannerController.reset();
                    hideDuplicateWarning();
                    hideStockWarning();
                    buscarInput.focus();
                });

                agregarItemModalElement.addEventListener('hidden.bs.modal', () => {
                    isAgregarItemModalOpen = false;
                    scannerController.reset();
                    resetModalState();
                });
            }

            if (confirmarBorradoModalElement) {
                confirmarBorradoModalElement.addEventListener('hidden.bs.modal', () => {
                    pendingDeleteRow = null;
                });
            }
        })();
    </script>
@endpush
