(function () {
    'use strict';

    const API = {
        async listar(params = {}) {
            const q = new URLSearchParams();
            if (params.query) q.set('query', params.query);
            if (params.page) q.set('page', params.page);
            if (params.limit) q.set('limit', params.limit);
            if (params.lugar_compra) q.set('lugar_compra', params.lugar_compra);
            if (params.fecha_compra) q.set('fecha_compra', params.fecha_compra);
            const res = await fetch('api/productos/catalogo/listar.php?' + q.toString());
            const data = await res.json();
            if (!data.success) throw new Error(data.message || 'Error de servidor');
            return data.data;
        },
        async crearProducto(data) {
            const res = await fetch('api/inventario/productos/crear.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data),
            });
            const r = await res.json();
            if (!r.success) throw new Error(r.message || 'Error al crear');
            return r;
        },
        async eliminarProducto(id) {
            const res = await fetch('api/inventario/productos/eliminar.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id }),
            });
            const r = await res.json();
            if (!r.success) throw new Error(r.message || 'Error al eliminar');
        },
        async getLocations() {
            const res = await fetch('api/inventario/lugares/listar.php');
            const r = await res.json();
            return r.success ? (r.data || []) : [];
        },
        async createLocation(nombre) {
            const res = await fetch('api/inventario/lugares/crear.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ nombre }),
            });
            const r = await res.json();
            if (!r.success) throw new Error(r.message);
            return r;
        },
    };

    function showToast(message, type, duration) {
        type = type || 'info';
        duration = duration || 3000;
        const container = document.getElementById('toastContainer');
        const icons = { success: 'fa-check-circle', error: 'fa-times-circle', info: 'fa-info-circle', warning: 'fa-exclamation-triangle' };
        const toast = document.createElement('div');
        toast.className = 'toast toast-' + type;
        toast.innerHTML = '<i class="fas ' + (icons[type] || icons.info) + '"></i> ' + message;
        container.appendChild(toast);
        setTimeout(function () {
            toast.classList.add('toast-out');
            setTimeout(function () { toast.remove(); }, 300);
        }, duration);
    }

    function escapeHtml(str) {
        if (!str) return '';
        var d = document.createElement('div');
        d.textContent = str;
        return d.innerHTML;
    }

    function formatCurrency(val) {
        var n = parseFloat(val) || 0;
        return 'Q ' + n.toFixed(2);
    }

    function formatDate(dateStr) {
        if (!dateStr) return '---';
        var d = new Date(dateStr + 'T00:00:00');
        if (isNaN(d)) return dateStr;
        var dd = String(d.getDate()).padStart(2, '0');
        var mm = String(d.getMonth() + 1).padStart(2, '0');
        var yy = String(d.getFullYear()).slice(-2);
        return dd + '/' + mm + '/' + yy;
    }

    var App = {
        currentPage: 1,
        currentQuery: '',
        currentLugar: '',
        currentFecha: '',
        limit: 50,
        totalPages: 0,
        totalProducts: 0,
        lugaresCompra: [],
        fechasCompra: [],
        searchTimeout: null,

        init: function () {
            this.loadLocations();
            this.bindEvents();
            this.loadProducts();
        },

        bindEvents: function () {
            var self = this;

            document.getElementById('searchQuery').addEventListener('input', function () {
                if (self.searchTimeout) clearTimeout(self.searchTimeout);
                self.searchTimeout = setTimeout(function () {
                    self.currentQuery = document.getElementById('searchQuery').value.trim();
                    self.currentPage = 1;
                    self.loadProducts();
                }, 350);
            });

            document.getElementById('filterLugarCompra').addEventListener('change', function () {
                self.currentLugar = this.value;
                self.currentPage = 1;
                self.loadProducts();
            });

            document.getElementById('filterFechaCompra').addEventListener('change', function () {
                self.currentFecha = this.value;
                self.currentPage = 1;
                self.loadProducts();
            });

            document.getElementById('btnAddProduct').addEventListener('click', function () {
                self.openAddModal();
            });
        },

        loadLocations: function () {
            var self = this;
            API.getLocations().then(function (lugares) {
                self.lugaresCompra = lugares;
                var select = document.getElementById('filterLugarCompra');
                select.innerHTML = '<option value="">Todos los lugares</option>';
                lugares.forEach(function (l) {
                    select.innerHTML += '<option value="' + l.id + '">' + escapeHtml(l.nombre) + '</option>';
                });
            }).catch(function (err) {
                console.error('Error loading locations', err);
            });
        },

        loadProducts: function () {
            var self = this;
            var tbody = document.getElementById('catalogBody');
            tbody.innerHTML = '<tr><td colspan="7"><div class="loading-state"><i class="fas fa-spinner fa-pulse"></i><p>Cargando productos...</p></div></td></tr>';

            var params = {
                query: self.currentQuery,
                page: self.currentPage,
                limit: self.limit,
            };
            if (self.currentLugar) params.lugar_compra = self.currentLugar;
            if (self.currentFecha) params.fecha_compra = self.currentFecha;

            API.listar(params).then(function (data) {
                self.totalProducts = data.total || 0;
                self.totalPages = data.pages || 0;
                self.renderProducts(data.productos || []);
                self.renderPagination();
                document.getElementById('statsCount').textContent = self.totalProducts;
            }).catch(function (err) {
                tbody.innerHTML = '<tr><td colspan="7"><div class="empty-state"><i class="fas fa-exclamation-triangle"></i><p>Error al cargar</p><small>' + escapeHtml(err.message) + '</small></div></td></tr>';
                showToast('Error: ' + err.message, 'error');
            });
        },

        renderProducts: function (productos) {
            var tbody = document.getElementById('catalogBody');

            if (!productos || productos.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7"><div class="empty-state"><i class="fas fa-box-open"></i><p>No se encontraron productos</p><small>Intenta con otra búsqueda o agrega un nuevo producto</small></div></td></tr>';
                return;
            }

            var html = '';
            for (var i = 0; i < productos.length; i++) {
                var p = productos[i];
                html += this.renderRow(p, i);
            }
            tbody.innerHTML = html;

            this.bindRowEvents();
        },

        renderRow: function (p, idx) {
            var pres = p.presentaciones || [];
            var lugares = p.lugares || [];

            var presHtml = '';
            for (var j = 0; j < pres.length; j++) {
                var pp = pres[j];
                if (pp.factor <= 1) continue;
                var label = pp.nombre.toLowerCase() === 'blister' ? 'Cuantas unidades tiene el blister' :
                            pp.nombre.toLowerCase() === 'caja' ? 'Cuantas unidades tiene la caja' :
                            escapeHtml(pp.nombre);
                presHtml += '<div class="pres-item">';
                presHtml += '  <span class="pres-name">' + label + '</span>';
                presHtml += '  <span class="pres-factor">' + pp.factor + ' unidades</span>';
                presHtml += '</div>';
            }

            var priceHtml = '';
            priceHtml += '<div class="price-costo" style="font-weight:600;color:var(--text)">Costo unitario: ' + formatCurrency(p.costo_unidad) + '</div>';
            for (var j = 0; j < pres.length; j++) {
                var pp = pres[j];
                if (pp.factor <= 1) continue;
                var label = pp.nombre.toLowerCase() === 'blister' ? 'Costo blister' :
                            pp.nombre.toLowerCase() === 'caja' ? 'Costo caja' :
                            'Costo ' + escapeHtml(pp.nombre);
                priceHtml += '<div class="price-costo" style="font-size:0.68rem;color:var(--text-light)">';
                priceHtml += label + ': <span style="color:var(--text)">' + formatCurrency(pp.costo) + '</span>';
                priceHtml += '</div>';
            }
            priceHtml += '<div style="margin-top:0.25rem;border-top:1px solid var(--border-light);padding-top:0.2rem;">';
            for (var j = 0; j < pres.length; j++) {
                var pp = pres[j];
                if (pp.factor <= 1) continue;
                var label = pp.nombre.toLowerCase() === 'blister' ? 'Venta blister' :
                            pp.nombre.toLowerCase() === 'caja' ? 'Venta caja' :
                            'Venta ' + escapeHtml(pp.nombre);
                priceHtml += '<div class="price-venta">' + label + ': ' + formatCurrency(pp.precio_venta) + '</div>';
            }
            priceHtml += '<div class="price-margen">Margen: ' + p.margen + '%</div>';
            priceHtml += '</div>';

            var lugaresHtml = '';
            if (lugares.length > 0) {
                for (var j = 0; j < lugares.length; j++) {
                    var l = lugares[j];
                    lugaresHtml += '<span class="lugar-badge" title="' + escapeHtml(l.lugar_nombre) + '">';
                    lugaresHtml += '  <i class="fas fa-store"></i> ' + escapeHtml(l.lugar_nombre.length > 15 ? l.lugar_nombre.substring(0, 15) + '\u2026' : l.lugar_nombre);
                    lugaresHtml += '</span>';
                }
            } else {
                lugaresHtml = '<span style="color:var(--text-light);font-size:0.68rem;">Sin lugares asignados</span>';
            }

            var exentoIcon = p.exento_iva ? '<span class="check-mark"><i class="fas fa-check-circle"></i></span>' : '<span class="check-none"><i class="fas fa-circle"></i></span>';

            var html = '';
            html += '<tr class="product-main-row" data-id="' + p.id + '">';
            html += '  <td class="cod-cell">';
            html += '    <div class="cod-interno">' + escapeHtml(p.CodigoInterno) + '</div>';
            html += '    <div class="cod-barra">' + escapeHtml(p.CodigoBarra) + '</div>';
            html += '  </td>';
            html += '  <td class="prod-cell">';
            html += '    <div class="prod-nombre">' + escapeHtml(p.NombreComercial) + '</div>';
            html += '    <div class="prod-generico">' + escapeHtml(p.NombreGenerico) + '</div>';
            if (p.FuncionMedica) {
                html += '    <div class="prod-funcion">' + escapeHtml(p.FuncionMedica) + '</div>';
            }
            html += '    <div class="prod-laboratorio"><i class="fas fa-flask" style="font-size:0.6rem"></i> ' + escapeHtml(p.laboratorio) + '</div>';
            html += '  </td>';
            html += '  <td class="pres-cell">' + presHtml + '</td>';
            html += '  <td class="price-cell">' + priceHtml + '</td>';
            html += '  <td class="date-cell">';
            html += '    <div class="date-compra"><i class="fas fa-calendar-plus" style="font-size:0.6rem;color:var(--text-light)"></i> ' + formatDate(p.fecha_compra) + '</div>';
            html += '    <div class="date-venc"><i class="fas fa-calendar-times" style="font-size:0.6rem"></i> Vence: ' + formatDate(p.fecha_vencimiento) + '</div>';
            html += '  </td>';
            html += '  <td class="exento-cell">' + exentoIcon + '</td>';
            html += '  <td class="action-cell">';
            html += '    <button class="btn-action edit" title="Editar" onclick="alert(\'Editar producto #' + p.id + '\')"><i class="fas fa-pen"></i></button>';
            html += '    <button class="btn-action delete btn-delete" title="Eliminar"><i class="fas fa-trash"></i></button>';
            html += '  </td>';
            html += '</tr>';
            html += '<tr class="lugares-subrow" data-id="' + p.id + '">';
            html += '  <td colspan="7"><div class="lugares-list">' + lugaresHtml + '</div></td>';
            html += '</tr>';

            return html;
        },

        renderPagination: function () {
            var container = document.getElementById('pagination');
            var p = this;
            if (p.totalPages <= 1) {
                container.innerHTML = '<span class="page-info">' + p.totalProducts + ' producto(s)</span>';
                return;
            }

            var html = '';
            html += '<button class="page-btn" data-page="' + (p.currentPage - 1) + '"' + (p.currentPage <= 1 ? ' disabled' : '') + '><i class="fas fa-chevron-left"></i></button>';

            var maxVisible = 7;
            var start = Math.max(1, p.currentPage - Math.floor(maxVisible / 2));
            var end = Math.min(p.totalPages, start + maxVisible - 1);
            if (end - start < maxVisible - 1) start = Math.max(1, end - maxVisible + 1);

            if (start > 1) {
                html += '<button class="page-btn" data-page="1">1</button>';
                if (start > 2) html += '<span class="page-info">\u2026</span>';
            }
            for (var i = start; i <= end; i++) {
                html += '<button class="page-btn' + (i === p.currentPage ? ' active' : '') + '" data-page="' + i + '">' + i + '</button>';
            }
            if (end < p.totalPages) {
                if (end < p.totalPages - 1) html += '<span class="page-info">\u2026</span>';
                html += '<button class="page-btn" data-page="' + p.totalPages + '">' + p.totalPages + '</button>';
            }

            html += '<button class="page-btn" data-page="' + (p.currentPage + 1) + '"' + (p.currentPage >= p.totalPages ? ' disabled' : '') + '><i class="fas fa-chevron-right"></i></button>';
            html += '<span class="page-info">' + p.totalProducts + ' productos</span>';

            container.innerHTML = html;

            var self = this;
            container.querySelectorAll('.page-btn').forEach(function (btn) {
                btn.addEventListener('click', function () {
                    var pg = parseInt(this.dataset.page);
                    if (!isNaN(pg) && pg >= 1 && pg <= self.totalPages) {
                        self.currentPage = pg;
                        self.loadProducts();
                    }
                });
            });
        },

        bindRowEvents: function () {
            var self = this;
            document.querySelectorAll('.btn-delete').forEach(function (btn) {
                btn.addEventListener('click', function () {
                    var row = this.closest('.product-main-row');
                    if (!row) return;
                    var id = row.dataset.id;
                    var nameEl = row.querySelector('.prod-nombre');
                    var name = nameEl ? nameEl.textContent : 'este producto';
                    if (!confirm('\u00bfEliminar "' + name.trim() + '"?\nEsta acci\u00f3n no se puede deshacer.')) return;

                    API.eliminarProducto(id).then(function () {
                        var subRow = row.nextElementSibling;
                        row.style.transition = 'opacity 300ms, transform 300ms';
                        row.style.opacity = '0';
                        row.style.transform = 'translateX(20px)';
                        if (subRow && subRow.classList.contains('lugares-subrow')) {
                            subRow.style.transition = 'opacity 300ms, transform 300ms';
                            subRow.style.opacity = '0';
                            subRow.style.transform = 'translateX(20px)';
                            setTimeout(function () { subRow.remove(); }, 300);
                        }
                        setTimeout(function () { row.remove(); }, 300);
                        showToast('Producto eliminado', 'success');
                        self.loadProducts();
                    }).catch(function (err) {
                        showToast('Error: ' + err.message, 'error');
                    });
                });
            });
        },

        openAddModal: function () {
            var modalHtml = '';
            modalHtml += '<div class="modal-overlay" id="addModalOverlay">';
            modalHtml += '  <div class="modal-container">';
            modalHtml += '    <div class="modal-header">';
            modalHtml += '      <h2 style="font-size:1.15rem;font-weight:700;margin:0;"><i class="fas fa-plus-circle" style="color:var(--primary-light)"></i> Nuevo Producto</h2>';
            modalHtml += '      <button id="modalCloseBtn" class="modal-close">&times;</button>';
            modalHtml += '    </div>';
            modalHtml += '    <div class="modal-body">';
            modalHtml += '      <form id="addProductForm">';
            modalHtml += '        <div style="margin-bottom:1.5rem;border-bottom:1px solid var(--border);padding-bottom:1rem;">';
            modalHtml += '          <h3 style="font-size:0.9rem;margin-bottom:1rem;color:var(--primary-color);font-weight:600;"><i class="fas fa-info-circle"></i> Informaci\u00f3n B\u00e1sica</h3>';
            modalHtml += '          <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">';
            modalHtml += '            <div><label style="font-size:0.75rem;font-weight:600;color:var(--text-muted);display:block;margin-bottom:0.3rem;">Nombre Comercial <span style="color:var(--danger)">*</span></label><input type="text" id="fNombreComercial" class="input-text" required style="width:100%;box-sizing:border-box;"></div>';
            modalHtml += '            <div><label style="font-size:0.75rem;font-weight:600;color:var(--text-muted);display:block;margin-bottom:0.3rem;">Nombre Gen\u00e9rico <span style="color:var(--danger)">*</span></label><input type="text" id="fNombreGenerico" class="input-text" required style="width:100%;box-sizing:border-box;"></div>';
            modalHtml += '            <div><label style="font-size:0.75rem;font-weight:600;color:var(--text-muted);display:block;margin-bottom:0.3rem;">C\u00f3digo de Barras</label><input type="text" id="fCodigoBarra" class="input-text" style="width:100%;box-sizing:border-box;"></div>';
            modalHtml += '            <div><label style="font-size:0.75rem;font-weight:600;color:var(--text-muted);display:block;margin-bottom:0.3rem;">Laboratorio <span style="color:var(--danger)">*</span></label><input type="text" id="fLaboratorio" class="input-text" required style="width:100%;box-sizing:border-box;"></div>';
            modalHtml += '            <div style="grid-column:span 2;"><label style="font-size:0.75rem;font-weight:600;color:var(--text-muted);display:block;margin-bottom:0.3rem;">Funci\u00f3n M\u00e9dica</label><textarea id="fFuncionMedica" class="input-text" rows="2" placeholder="Descripci\u00f3n del uso terap\u00e9utico..." style="width:100%;box-sizing:border-box;font-family:inherit;"></textarea></div>';
            modalHtml += '          </div>';
            modalHtml += '        </div>';
            modalHtml += '        <div style="margin-bottom:1.5rem;border-bottom:1px solid var(--border);padding-bottom:1rem;">';
            modalHtml += '          <h3 style="font-size:0.9rem;margin-bottom:1rem;color:var(--primary-color);font-weight:600;"><i class="fas fa-layer-group"></i> Presentaciones</h3>';
            modalHtml += '          <div style="display:flex;flex-direction:column;gap:0.75rem;">';
            modalHtml += '            <div><label style="font-size:0.85rem;font-weight:600;color:var(--text);display:block;margin-bottom:0.3rem;">Cuantas unidades tiene el blister</label><input type="number" id="fUnidadesBlister" class="input-text" min="1" placeholder="ej: 10" style="width:100%;text-align:center;box-sizing:border-box;"></div>';
            modalHtml += '            <div><label style="font-size:0.85rem;font-weight:600;color:var(--text);display:block;margin-bottom:0.3rem;">Cuantas unidades tiene la caja</label><input type="number" id="fUnidadesCaja" class="input-text" min="1" placeholder="ej: 100" style="width:100%;text-align:center;box-sizing:border-box;"></div>';
            modalHtml += '          </div>';
            modalHtml += '        </div>';
            modalHtml += '        <div style="margin-bottom:1.5rem;border-bottom:1px solid var(--border);padding-bottom:1rem;">';
            modalHtml += '          <h3 style="font-size:0.9rem;margin-bottom:1rem;color:var(--primary-color);font-weight:600;"><i class="fas fa-tags"></i> Precios de Venta (Iniciales)</h3>';
            modalHtml += '          <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:1rem;">';
            modalHtml += '            <div><label style="font-size:0.75rem;font-weight:600;color:var(--text-muted);display:block;margin-bottom:0.3rem;"><i class="fas fa-pills"></i> Unidad</label><input type="number" step="0.01" class="input-text" id="fPrecioUnidad" value="0" style="width:100%;box-sizing:border-box;"></div>';
            modalHtml += '            <div><label style="font-size:0.75rem;font-weight:600;color:var(--text-muted);display:block;margin-bottom:0.3rem;"><i class="fas fa-tablets"></i> Blister</label><input type="number" step="0.01" class="input-text" id="fPrecioBlister" value="0" style="width:100%;box-sizing:border-box;"></div>';
            modalHtml += '            <div><label style="font-size:0.75rem;font-weight:600;color:var(--text-muted);display:block;margin-bottom:0.3rem;"><i class="fas fa-box"></i> Caja</label><input type="number" step="0.01" class="input-text" id="fPrecioMayor" value="0" style="width:100%;box-sizing:border-box;"></div>';
            modalHtml += '            <div><label style="font-size:0.75rem;font-weight:600;color:var(--text-muted);display:block;margin-bottom:0.3rem;"><i class="fas fa-boxes-stacked"></i> Mixto</label><input type="number" step="0.01" class="input-text" id="fPrecioMixto" value="0" style="width:100%;box-sizing:border-box;"></div>';
            modalHtml += '          </div>';
            modalHtml += '        </div>';
            modalHtml += '        <div>';
            modalHtml += '          <h3 style="font-size:0.9rem;margin-bottom:1rem;color:var(--primary-color);font-weight:600;"><i class="fas fa-cubes"></i> Inventario</h3>';
            modalHtml += '          <div style="display:flex;gap:1rem;align-items:center;">';
            modalHtml += '            <div><label style="font-size:0.75rem;font-weight:600;color:var(--text-muted);display:block;margin-bottom:0.3rem;">Fecha Vencimiento</label><input type="date" class="input-text" id="fFechaVencimiento" style="outline:none;"></div>';
            modalHtml += '            <div><label style="font-size:0.75rem;font-weight:600;color:var(--text-muted);display:block;margin-bottom:0.3rem;">Existencias</label><input type="number" class="input-text" id="fExistencia" value="0" min="0" style="width:100px;outline:none;"></div>';
            modalHtml += '            <div style="padding-top:1.2rem;"><label style="display:flex;align-items:center;gap:0.4rem;cursor:pointer;font-size:0.85rem;"><input type="checkbox" id="fExentoIva" style="width:16px;height:16px;cursor:pointer;"> <i class="fas fa-percent"></i> Exento IVA</label></div>';
            modalHtml += '          </div>';
            modalHtml += '        </div>';
            modalHtml += '      </form>';
            modalHtml += '    </div>';
            modalHtml += '    <div class="modal-footer">';
            modalHtml += '      <button class="btn btn-secondary" id="btnCancelProduct"><i class="fas fa-times"></i> Cancelar</button>';
            modalHtml += '      <button class="btn btn-primary" id="btnSaveProduct"><i class="fas fa-save"></i> Guardar Producto</button>';
            modalHtml += '    </div>';
            modalHtml += '  </div>';
            modalHtml += '</div>';

            var el = document.createElement('div');
            el.innerHTML = modalHtml;
            document.body.appendChild(el);

            document.getElementById('modalCloseBtn').addEventListener('click', function () { el.remove(); });
            document.getElementById('btnCancelProduct').addEventListener('click', function () { el.remove(); });
            el.addEventListener('click', function (e) { if (e.target === el) el.remove(); });
            document.getElementById('btnSaveProduct').addEventListener('click', function () {
                var nombre = document.getElementById('fNombreComercial').value.trim();
                var generico = document.getElementById('fNombreGenerico').value.trim();
                var lab = document.getElementById('fLaboratorio').value.trim();
                if (!nombre || !generico || !lab) {
                    showToast('Completa los campos obligatorios', 'warning');
                    return;
                }

                var data = {
                    NombreComercial: nombre,
                    NombreGenerico: generico,
                    laboratorio: lab,
                    CodigoBarra: document.getElementById('fCodigoBarra').value.trim(),
                    FuncionMedica: document.getElementById('fFuncionMedica').value.trim(),
                    id_lugarCompra: null,
                    CostoUnidad: 0,
                    CostoBlister: 0,
                    CostoMayor: 0,
                    CostoMixto: 0,
                    PrecioVentaUnidad: parseFloat(document.getElementById('fPrecioUnidad').value) || 0,
                    PrecioVentaBlister: parseFloat(document.getElementById('fPrecioBlister').value) || 0,
                    PrecioVentaMayor: parseFloat(document.getElementById('fPrecioMayor').value) || 0,
                    PrecioVentaMixto: parseFloat(document.getElementById('fPrecioMixto').value) || 0,
                    FechaVencimiento: document.getElementById('fFechaVencimiento').value || null,
                    existencia: parseInt(document.getElementById('fExistencia').value) || 0,
                    con_factura: false,
                    exento_iva: document.getElementById('fExentoIva').checked,
                    unidades_por_caja: parseInt(document.getElementById('fUnidadesCaja').value) || 0,
                    unidades_por_blister: parseInt(document.getElementById('fUnidadesBlister').value) || 0,
                };

                var btn = document.getElementById('btnSaveProduct');
                btn.disabled = true;
                btn.innerHTML = '<i class="fas fa-spinner fa-pulse"></i> Guardando...';

                API.crearProducto(data).then(function (res) {
                    showToast('Producto creado: ' + (res.data && res.data.CodigoInterno ? res.data.CodigoInterno : ''), 'success');
                    el.remove();
                    App.loadProducts();
                }).catch(function (err) {
                    showToast('Error: ' + err.message, 'error');
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-save"></i> Guardar Producto';
                });
            });
        },
    };

    document.addEventListener('DOMContentLoaded', function () { App.init(); });
})();
