(function () {
    'use strict';

    const boot = window.ICY_PURCHASE_ORDER_BOOTSTRAP || {};
    const $ = (id) => document.getElementById(id);
    const esc = (value) => String(value == null ? '' : value).replace(/[&<>'"]/g, (ch) => ({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#039;','"':'&quot;'}[ch]));
    const today = () => new Date().toISOString().slice(0, 10);
    const money = (value, currency) => new Intl.NumberFormat('es-CL', {minimumFractionDigits: currency === 'CLP' ? 0 : 2, maximumFractionDigits: currency === 'CLP' ? 0 : 2}).format(Number(value || 0));
    const modal = $('poCreateModal');
    const content = $('poLayerContent');
    const footer = $('poModalFooter');
    const backBtn = $('poBackBtn');
    const errorBox = $('poError');
    const steps = ['supplier', 'items', 'conditions', 'review'];
    const defaultPurchaseOrderTerms = String(boot.company?.purchase_order_default_terms || 'Precios y condiciones sujetos a lo indicado en esta orden. Informar cualquier diferencia antes del despacho.');
    let searchTimer = null;
    let productTimer = null;
    let lastSuppliers = [];
    let lastProducts = [];
    let emailOrder = null;

    const state = {
        step: 'supplier', supplier: null, items: [], result: null,
        form: {
            issue_date: today(), expected_delivery_date: '', currency_code: 'CLP', payment_terms: '', cost_center_id: '',
            supplier_email: '', delivery_address: boot.company?.delivery_address || '', delivery_district: boot.company?.delivery_district || '',
            delivery_city: boot.company?.delivery_city || '', notes: '', terms_conditions: defaultPurchaseOrderTerms
        }
    };

    async function requestJson(url, options) {
        const response = await fetch(url, options || {credentials: 'same-origin', headers: {'X-Requested-With': 'XMLHttpRequest'}});
        let data;
        try { data = await response.json(); } catch (_) { throw new Error('El servidor devolvió una respuesta no válida.'); }
        if (!response.ok || !data.success) throw new Error(data.message || 'No fue posible completar la operación.');
        return Object.prototype.hasOwnProperty.call(data, 'data') ? data.data : data;
    }

    function showError(message) {
        errorBox.textContent = message || 'Ocurrió un error.';
        errorBox.style.display = 'block';
        errorBox.scrollIntoView({behavior: 'smooth', block: 'nearest'});
    }

    function clearError() { errorBox.textContent = ''; errorBox.style.display = 'none'; }

    function reset() {
        state.step = 'supplier'; state.supplier = null; state.items = []; state.result = null;
        state.form = {
            issue_date: today(), expected_delivery_date: '', currency_code: 'CLP', payment_terms: '', cost_center_id: '', supplier_email: '',
            delivery_address: boot.company?.delivery_address || '', delivery_district: boot.company?.delivery_district || '', delivery_city: boot.company?.delivery_city || '',
            notes: '', terms_conditions: defaultPurchaseOrderTerms
        };
    }

    function openCreate() {
        reset(); clearError();
        modal.style.display = 'flex'; modal.classList.add('show'); modal.setAttribute('aria-hidden', 'false');
        document.body.classList.add('is-modal-open');
        render();
    }

    function closeCreate() {
        modal.classList.remove('show'); modal.setAttribute('aria-hidden', 'true');
        window.setTimeout(() => { if (!modal.classList.contains('show')) modal.style.display = 'none'; }, 120);
        document.body.classList.remove('is-modal-open');
    }

    function go(step) { state.step = step; clearError(); render(); }

    function render() {
        document.querySelectorAll('#poStepbar [data-step]').forEach((node) => node.classList.toggle('is-active', node.dataset.step === state.step));
        const index = steps.indexOf(state.step);
        backBtn.style.visibility = index > 0 && !state.result ? 'visible' : 'hidden';
        $('poStepbar').style.display = state.result ? 'none' : 'grid';
        if (state.result) renderResult();
        else if (state.step === 'supplier') renderSupplier();
        else if (state.step === 'items') renderItems();
        else if (state.step === 'conditions') renderConditions();
        else renderReview();
        if (window.lucide) window.lucide.createIcons();
    }

    function renderSupplier() {
        $('poModalTitle').textContent = 'Seleccionar proveedor';
        $('poModalSubtitle').textContent = 'Paso 1 de 4';
        content.innerHTML = `<section class="po-wizard-panel"><label class="po-field"><span>Buscar proveedor</span><input class="input" id="poSupplierSearch" autocomplete="off" placeholder="Razón social, RUT, contacto o email"></label><div id="poSupplierResults" class="po-search-results"><div class="po-search-hint">Escribe al menos dos caracteres para buscar.</div></div></section>`;
        footer.innerHTML = state.supplier ? `<div class="po-selected-summary"><strong>${esc(supplierName(state.supplier))}</strong><span>${esc(state.supplier.customer_tax_id || 'Sin RUT')}</span></div><button class="btn btn-primary" type="button" id="poSupplierNext">Continuar <i data-lucide="arrow-right"></i></button>` : '';
        const input = $('poSupplierSearch');
        input.focus();
        input.addEventListener('input', () => {
            clearTimeout(searchTimer);
            searchTimer = setTimeout(() => searchSuppliers(input.value), 260);
        });
        if (state.supplier) bindSupplierContinue();
    }

    async function searchSuppliers(query) {
        const results = $('poSupplierResults');
        if (!results) return;
        if (query.trim().length < 2) { results.innerHTML = '<div class="po-search-hint">Escribe al menos dos caracteres para buscar.</div>'; return; }
        results.innerHTML = '<div class="po-search-hint">Buscando proveedores…</div>';
        try {
            lastSuppliers = await requestJson(`/modules/billing/purchase_order_data_ajax.php?kind=suppliers&q=${encodeURIComponent(query)}&limit=30`);
            results.innerHTML = lastSuppliers.length ? lastSuppliers.map((supplier, index) => `<button type="button" class="po-search-option" data-supplier-index="${index}"><span><strong>${esc(supplierName(supplier))}</strong><small>${esc(supplier.customer_tax_id || 'Sin RUT')} · ${esc(supplier.contact_name || 'Sin contacto')}</small></span><span>${esc(supplier.email_dte || supplier.email || 'Sin email')}</span></button>`).join('') : '<div class="po-search-hint">No encontramos proveedores activos.</div>';
            results.querySelectorAll('[data-supplier-index]').forEach((button) => button.addEventListener('click', () => selectSupplier(lastSuppliers[Number(button.dataset.supplierIndex)])));
        } catch (error) { results.innerHTML = `<div class="po-search-hint po-search-error">${esc(error.message)}</div>`; }
    }

    function supplierName(supplier) { return supplier?.legal_name || supplier?.commercial_name || supplier?.customer_name || 'Proveedor'; }

    function selectSupplier(supplier) {
        state.supplier = supplier;
        state.form.supplier_email = supplier.email_dte || supplier.email || '';
        state.form.cost_center_id = supplier.supplier_default_cost_center_id || '';
        const term = (boot.payment_terms || []).find((row) => String(row.id) === String(supplier.supplier_payment_terms_id));
        state.form.payment_terms = term?.term_label || supplier.payment_terms || '';
        renderSupplier();
    }

    function bindSupplierContinue() { $('poSupplierNext').addEventListener('click', () => go('items')); }

    function emptyItem(product) {
        product = product || {};
        return {product_id: product.id || null, sku: product.sku || '', description: product.name || product.description || '', quantity: 1, unit_measure: product.unit || product.dte_unit_code || 'UN', unit_price: Number(product.price || 0), discount_percentage: 0, tax_exempt: String(product.tax_treatment || '').toLowerCase() === 'exento'};
    }

    function renderItems() {
        $('poModalTitle').textContent = 'Productos y servicios'; $('poModalSubtitle').textContent = 'Paso 2 de 4';
        const rows = state.items.map((item, index) => itemRow(item, index)).join('');
        const totals = calculate();
        content.innerHTML = `<section class="po-wizard-panel"><div class="po-product-toolbar"><label class="po-field"><span>Buscar en catálogo</span><input class="input" id="poProductSearch" autocomplete="off" placeholder="SKU o nombre del producto"></label><button class="btn btn-outline" type="button" id="poAddManual"><i data-lucide="plus"></i><span>Ítem manual</span></button></div><div id="poProductResults" class="po-search-results po-product-results"></div><div class="po-items-scroll"><table class="po-items-editor"><thead><tr><th>SKU</th><th>Descripción</th><th>Cantidad</th><th>Unidad</th><th>Precio</th><th>Dscto. %</th><th>IVA</th><th>Total</th><th></th></tr></thead><tbody>${rows || '<tr><td colspan="9"><div class="po-search-hint">Agrega al menos un producto o servicio.</div></td></tr>'}</tbody></table></div><div class="po-editor-total"><span>Total estimado</span><strong>${esc(state.form.currency_code)} ${money(totals.total, state.form.currency_code)}</strong></div></section>`;
        footer.innerHTML = `<button class="btn btn-primary" id="poItemsNext" type="button" ${state.items.length ? '' : 'disabled'}>Continuar <i data-lucide="arrow-right"></i></button>`;
        bindItemInputs();
        $('poAddManual').addEventListener('click', () => { captureItems(); state.items.push(emptyItem()); renderItems(); });
        $('poProductSearch').addEventListener('input', (event) => { clearTimeout(productTimer); productTimer = setTimeout(() => searchProducts(event.target.value), 260); });
        $('poItemsNext').addEventListener('click', () => { captureItems(); if (!state.items.length) return showError('Agrega al menos un producto.'); go('conditions'); });
    }

    function itemRow(item, index) {
        const line = itemAmounts(item);
        return `<tr data-item-index="${index}"><td><input class="input po-line-sku" value="${esc(item.sku)}" maxlength="80"></td><td><input class="input po-line-description" value="${esc(item.description)}" maxlength="500"></td><td><input class="input po-line-quantity" type="number" min="0.001" step="0.001" value="${esc(item.quantity)}"></td><td><input class="input po-line-unit" value="${esc(item.unit_measure)}" maxlength="20"></td><td><input class="input po-line-price" type="number" min="0" step="0.01" value="${esc(item.unit_price)}"></td><td><input class="input po-line-discount" type="number" min="0" max="100" step="0.01" value="${esc(item.discount_percentage)}"></td><td><input class="po-line-exempt" type="checkbox" ${item.tax_exempt ? 'checked' : ''} title="Exento de IVA"></td><td><strong>${money(line.total, state.form.currency_code)}</strong></td><td><button class="btn btn-outline action-square-btn po-line-remove" type="button" title="Quitar"><i data-lucide="trash-2"></i></button></td></tr>`;
    }

    function bindItemInputs() {
        content.querySelectorAll('[data-item-index] input').forEach((input) => input.addEventListener('change', () => { captureItems(); renderItems(); }));
        content.querySelectorAll('.po-line-remove').forEach((button) => button.addEventListener('click', () => { const row = button.closest('[data-item-index]'); captureItems(); state.items.splice(Number(row.dataset.itemIndex), 1); renderItems(); }));
    }

    function captureItems() {
        content.querySelectorAll('[data-item-index]').forEach((row) => {
            const item = state.items[Number(row.dataset.itemIndex)]; if (!item) return;
            item.sku = row.querySelector('.po-line-sku').value.trim(); item.description = row.querySelector('.po-line-description').value.trim();
            item.quantity = Number(row.querySelector('.po-line-quantity').value || 0); item.unit_measure = row.querySelector('.po-line-unit').value.trim();
            item.unit_price = Number(row.querySelector('.po-line-price').value || 0); item.discount_percentage = Number(row.querySelector('.po-line-discount').value || 0);
            item.tax_exempt = row.querySelector('.po-line-exempt').checked;
        });
    }

    async function searchProducts(query) {
        const results = $('poProductResults'); if (!results) return;
        if (query.trim().length < 2) { results.innerHTML = ''; return; }
        results.innerHTML = '<div class="po-search-hint">Buscando productos…</div>';
        try {
            lastProducts = await requestJson(`/modules/billing/purchase_order_data_ajax.php?kind=products&q=${encodeURIComponent(query)}&limit=30`);
            results.innerHTML = lastProducts.length ? lastProducts.map((product, index) => `<button type="button" class="po-search-option" data-product-index="${index}"><span><strong>${esc(product.name)}</strong><small>${esc(product.sku || 'Sin SKU')} · ${esc(product.unit || 'UN')}</small></span><strong>${money(product.price, state.form.currency_code)}</strong></button>`).join('') : '<div class="po-search-hint">No encontramos productos.</div>';
            results.querySelectorAll('[data-product-index]').forEach((button) => button.addEventListener('click', () => { captureItems(); state.items.push(emptyItem(lastProducts[Number(button.dataset.productIndex)])); renderItems(); }));
        } catch (error) { results.innerHTML = `<div class="po-search-hint po-search-error">${esc(error.message)}</div>`; }
    }

    function itemAmounts(item) { const base = Number(item.quantity || 0) * Number(item.unit_price || 0); const discount = base * Math.min(100, Math.max(0, Number(item.discount_percentage || 0))) / 100; const net = base - discount; const tax = item.tax_exempt ? 0 : net * 0.19; return {base, discount, net, tax, total: net + tax}; }
    function calculate() { return state.items.reduce((sum, item) => { const line = itemAmounts(item); Object.keys(sum).forEach((key) => sum[key] += line[key]); return sum; }, {base:0,discount:0,net:0,tax:0,total:0}); }

    function options(rows, value, label, selected) { return (rows || []).map((row) => `<option value="${esc(row[value])}" ${String(row[value]) === String(selected) ? 'selected' : ''}>${esc(label(row))}</option>`).join(''); }

    function renderConditions() {
        $('poModalTitle').textContent = 'Entrega y condiciones'; $('poModalSubtitle').textContent = 'Paso 3 de 4';
        content.innerHTML = `<section class="po-wizard-panel"><div class="po-form-grid"><label class="po-field"><span>Fecha de emisión</span><input class="input" id="poIssueDate" type="date" value="${esc(state.form.issue_date)}"></label><label class="po-field"><span>Entrega esperada</span><input class="input" id="poDeliveryDate" type="date" value="${esc(state.form.expected_delivery_date)}"></label><label class="po-field"><span>Moneda</span><select class="input" id="poCurrency">${options(boot.currencies, 'currency_code', (row) => `${row.currency_code} · ${row.currency_name}`, state.form.currency_code)}</select></label><label class="po-field"><span>Condición de pago</span><input class="input" id="poPaymentTerms" value="${esc(state.form.payment_terms)}" list="poPaymentTermsList"><datalist id="poPaymentTermsList">${(boot.payment_terms || []).map((row) => `<option value="${esc(row.term_label)}"></option>`).join('')}</datalist></label><label class="po-field"><span>Centro de costo</span><select class="input" id="poCostCenter"><option value="">Sin asignar</option>${options(boot.cost_centers, 'id', (row) => `${row.center_code ? row.center_code + ' · ' : ''}${row.center_name}`, state.form.cost_center_id)}</select></label><label class="po-field"><span>Email proveedor</span><input class="input" id="poSupplierEmail" type="email" value="${esc(state.form.supplier_email)}"></label><label class="po-field po-field-wide"><span>Dirección de entrega</span><input class="input" id="poDeliveryAddress" value="${esc(state.form.delivery_address)}"></label><label class="po-field"><span>Comuna</span><input class="input" id="poDeliveryDistrict" value="${esc(state.form.delivery_district)}"></label><label class="po-field"><span>Ciudad</span><input class="input" id="poDeliveryCity" value="${esc(state.form.delivery_city)}"></label><label class="po-field po-field-wide"><span>Observaciones para el proveedor</span><textarea class="input" id="poNotes" rows="3">${esc(state.form.notes)}</textarea></label><label class="po-field po-field-wide"><span>Condiciones</span><textarea class="input" id="poTerms" rows="3">${esc(state.form.terms_conditions)}</textarea></label></div></section>`;
        footer.innerHTML = `<button class="btn btn-primary" id="poConditionsNext" type="button">Revisar orden <i data-lucide="arrow-right"></i></button>`;
        $('poConditionsNext').addEventListener('click', () => { try { captureConditions(); go('review'); } catch (error) { showError(error.message); } });
    }

    function captureConditions() {
        state.form.issue_date = $('poIssueDate').value; state.form.expected_delivery_date = $('poDeliveryDate').value; state.form.currency_code = $('poCurrency').value;
        state.form.payment_terms = $('poPaymentTerms').value.trim(); state.form.cost_center_id = $('poCostCenter').value; state.form.supplier_email = $('poSupplierEmail').value.trim();
        state.form.delivery_address = $('poDeliveryAddress').value.trim(); state.form.delivery_district = $('poDeliveryDistrict').value.trim(); state.form.delivery_city = $('poDeliveryCity').value.trim();
        state.form.notes = $('poNotes').value.trim(); state.form.terms_conditions = $('poTerms').value.trim();
        if (!state.form.issue_date) throw new Error('Indica la fecha de emisión.');
        if (state.form.expected_delivery_date && state.form.expected_delivery_date < state.form.issue_date) throw new Error('La entrega no puede ser anterior a la emisión.');
    }

    function renderReview() {
        $('poModalTitle').textContent = 'Revisar orden de compra'; $('poModalSubtitle').textContent = 'Paso 4 de 4';
        const totals = calculate();
        content.innerHTML = `<div class="po-review-layout"><section class="po-wizard-panel"><h3>${esc(supplierName(state.supplier))}</h3><p>${esc(state.supplier.customer_tax_id || 'Sin RUT')} · ${esc(state.form.supplier_email || 'Sin email')}</p><div class="po-review-meta"><span><small>Emisión</small><strong>${esc(state.form.issue_date)}</strong></span><span><small>Entrega</small><strong>${esc(state.form.expected_delivery_date || 'Por coordinar')}</strong></span><span><small>Pago</small><strong>${esc(state.form.payment_terms || 'Por coordinar')}</strong></span></div><div class="po-items-scroll"><table class="po-review-table"><thead><tr><th>Descripción</th><th>Cantidad</th><th>Precio</th><th>Total</th></tr></thead><tbody>${state.items.map((item) => `<tr><td><strong>${esc(item.description)}</strong><small>${esc(item.sku || 'Sin SKU')}</small></td><td>${esc(item.quantity)} ${esc(item.unit_measure)}</td><td>${money(item.unit_price, state.form.currency_code)}</td><td><strong>${money(itemAmounts(item).total, state.form.currency_code)}</strong></td></tr>`).join('')}</tbody></table></div></section><aside class="po-total-card"><span>Total orden</span><strong>${esc(state.form.currency_code)} ${money(totals.total, state.form.currency_code)}</strong><dl><div><dt>Subtotal</dt><dd>${money(totals.base, state.form.currency_code)}</dd></div><div><dt>Descuentos</dt><dd>-${money(totals.discount, state.form.currency_code)}</dd></div><div><dt>IVA</dt><dd>${money(totals.tax, state.form.currency_code)}</dd></div></dl><p><i data-lucide="info"></i> Se generará un PDF comercial numerado por ICYLAB. No se enviará a FACTO.</p></aside></div>`;
        footer.innerHTML = `<button class="btn btn-primary" id="poCreateOrder" type="button"><i data-lucide="file-check-2"></i><span>Crear orden y generar PDF</span></button>`;
        $('poCreateOrder').addEventListener('click', createOrder);
    }

    async function createOrder() {
        const button = $('poCreateOrder'); clearError();
        try {
            button.disabled = true; button.querySelector('span').textContent = 'Generando PDF…';
            const payload = Object.assign({}, state.form, {supplier_id: state.supplier.id, items: state.items});
            const body = new URLSearchParams({payload: JSON.stringify(payload)});
            state.result = await requestJson('/modules/billing/purchase_order_create_ajax.php', {method:'POST', credentials:'same-origin', headers:{'Content-Type':'application/x-www-form-urlencoded','X-Requested-With':'XMLHttpRequest'}, body:body.toString()});
            render();
        } catch (error) { showError(error.message); button.disabled = false; button.querySelector('span').textContent = 'Crear orden y generar PDF'; }
    }

    function renderResult() {
        $('poModalTitle').textContent = 'Orden de compra creada'; $('poModalSubtitle').textContent = state.result.order_number;
        content.innerHTML = `<div class="po-result"><span class="po-result-icon"><i data-lucide="check"></i></span><h3>${esc(state.result.order_number)}</h3><p>El PDF fue generado y la orden quedó registrada correctamente.</p><div class="po-result-total"><span>Total</span><strong>${esc(state.result.currency_code)} ${money(state.result.total_amount, state.result.currency_code)}</strong></div><div class="po-result-actions"><a class="btn btn-outline" href="${esc(state.result.pdf_url)}" target="_blank" rel="noopener"><i data-lucide="file-text"></i><span>Ver PDF</span></a><button class="btn btn-primary" type="button" id="poResultSend"><i data-lucide="mail"></i><span>Enviar al proveedor</span></button></div></div>`;
        footer.innerHTML = `<a class="btn btn-outline" href="/modules/billing/purchase_orders.php">Ver todas las órdenes</a><button class="btn btn-primary" id="poResultClose" type="button">Finalizar</button>`;
        $('poResultSend').addEventListener('click', () => openEmail({id:state.result.id, order_number:state.result.order_number, email:state.result.supplier_email}));
        $('poResultClose').addEventListener('click', () => { window.location.href = '/modules/billing/purchase_orders.php'; });
    }

    function openEmail(order) {
        emailOrder = order;
        $('poEmailTo').value = order.email || '';
        $('poEmailSubject').value = `Orden de compra ${order.order_number} · ICYLAB`;
        $('poEmailBody').value = `Hola,\n\nAdjuntamos la orden de compra ${order.order_number} emitida por ICYLAB.\n\nPor favor confirma la recepción y las condiciones de entrega.\n\nSaludos,\nICYLAB`;
        $('poEmailError').style.display = 'none';
        $('poEmailModal').style.display = 'flex'; $('poEmailModal').classList.add('show'); $('poEmailModal').setAttribute('aria-hidden','false');
        if (window.lucide) window.lucide.createIcons();
    }

    function closeEmail() { $('poEmailModal').classList.remove('show'); $('poEmailModal').setAttribute('aria-hidden','true'); window.setTimeout(() => { if (!$('poEmailModal').classList.contains('show')) $('poEmailModal').style.display='none'; }, 120); }

    async function sendEmail() {
        const button = $('poEmailSend'); const error = $('poEmailError');
        try {
            button.disabled = true;
            const body = new URLSearchParams({id:String(emailOrder.id),to:$('poEmailTo').value.trim(),subject:$('poEmailSubject').value.trim(),body:$('poEmailBody').value.trim().replace(/\n/g,'<br>')});
            await requestJson('/modules/billing/purchase_order_send_ajax.php', {method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/x-www-form-urlencoded','X-Requested-With':'XMLHttpRequest'},body:body.toString()});
            closeEmail();
            if (state.result) { $('poResultSend').disabled = true; $('poResultSend').innerHTML = '<i data-lucide="check"></i><span>Enviada</span>'; if (window.lucide) window.lucide.createIcons(); }
            else window.location.reload();
        } catch (sendError) { error.textContent = sendError.message; error.style.display = 'block'; } finally { button.disabled = false; }
    }

    $('poNewBtn').addEventListener('click', openCreate);
    $('poCloseBtn').addEventListener('click', closeCreate);
    backBtn.addEventListener('click', () => { const index = steps.indexOf(state.step); if (index > 0) go(steps[index - 1]); });
    modal.addEventListener('click', (event) => { if (event.target === modal) closeCreate(); });
    document.querySelectorAll('.po-send-btn').forEach((button) => button.addEventListener('click', () => openEmail({id:Number(button.dataset.orderId),order_number:button.dataset.orderNumber,email:button.dataset.email})));
    $('poEmailClose').addEventListener('click', closeEmail); $('poEmailCancel').addEventListener('click', closeEmail); $('poEmailSend').addEventListener('click', sendEmail);
    $('poEmailModal').addEventListener('click', (event) => { if (event.target === $('poEmailModal')) closeEmail(); });
    document.addEventListener('keydown', (event) => { if (event.key === 'Escape') { if ($('poEmailModal').classList.contains('show')) closeEmail(); else if (modal.classList.contains('show')) closeCreate(); } });
    if (window.ICY_PURCHASE_ORDER_OPEN_NEW) openCreate();
})();
