(function(){
    const bindings=[];
    const on=(target,event,handler,options)=>{if(!target||!target.addEventListener)return;target.addEventListener(event,handler,options||false);bindings.push([target,event,handler,options||false]);};
    window.ICY_PAGE_CLEANUPS=window.ICY_PAGE_CLEANUPS||[];
    window.ICY_PAGE_CLEANUPS.push(()=>bindings.forEach(([target,event,handler,options])=>{try{target.removeEventListener(event,handler,options);}catch(_){}}));

    const state={rows:[],centersLoaded:false,currentKey:null,currentEnvironment:'sandbox',paymentDocument:null,paymentOptions:null};
    const $=id=>document.getElementById(id);
    const esc=value=>String(value==null?'':value).replace(/[&<>'"]/g,char=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[char]));
    const money=value=>'$'+Math.round(Number(value||0)).toLocaleString('es-CL');
    const shortDate=value=>{if(!value)return '-';const parts=String(value).slice(0,10).split('-');return parts.length===3?`${parts[2]}-${parts[1]}-${parts[0]}`:value;};
    const today=()=>new Date().toISOString().slice(0,10);
    const refreshIcons=()=>{if(window.lucide&&typeof window.lucide.createIcons==='function')window.lucide.createIcons();};
    const paymentRequestKey = (prefix) => {
        const random = (window.crypto && typeof window.crypto.randomUUID === 'function')
            ? window.crypto.randomUUID()
            : (Date.now().toString(36) + '-' + Math.random().toString(36).slice(2) + '-' + Math.random().toString(36).slice(2));
        return String(prefix || 'payment') + ':' + random;
    };

    function buildParams(extra){const params=new URLSearchParams();params.set('environment',$('agingEnv').value||'sandbox');params.set('search',$('agingSearch').value||'');params.set('bucket',$('agingBucket').value||'all');params.set('center_id',$('agingCenter').value||'all');params.set('limit','5000');Object.entries(extra||{}).forEach(([key,value])=>params.set(key,value));return params;}
    async function requestJson(url,options){const response=await fetch(url,options||{headers:{Accept:'application/json'}});const text=await response.text();let json;try{json=JSON.parse(text);}catch(_){throw new Error(text||'Respuesta no válida.');}if(!response.ok||!json||json.ok===false||json.success===false)throw new Error(json&&json.message?json.message:'Error al procesar la solicitud.');return json;}
    async function fetchData(url){const json=await requestJson(url,{headers:{Accept:'application/json'}});return json.data;}
    function optionHtml(items,valueKey,labelKey){return '<option value="">Seleccionar</option>'+(items||[]).map(item=>`<option value="${esc(item[valueKey])}">${esc(item[labelKey]||item[valueKey])}</option>`).join('');}

    function renderKpis(kpis){const values=[kpis.suppliers_count||0,money(kpis.open_balance),money(kpis.overdue_balance),money(kpis.due_7_balance),kpis.documents_count||0,money(kpis.without_center_balance)];$('agingKpis').querySelectorAll('strong').forEach((element,index)=>element.textContent=values[index]);}
    function renderCenters(centers){if(state.centersLoaded)return;const select=$('agingCenter');const options=['<option value="all">Todos los centros</option>','<option value="none">Sin centro</option>'];(centers||[]).forEach(center=>options.push(`<option value="${esc(center.id)}">${esc(center.center_name||center.center_code||'Centro')}</option>`));select.innerHTML=options.join('');state.centersLoaded=true;}
    function riskPill(row){if(Number(row.overdue_balance||0)>0)return `<span class="aging-pill is-danger">${Number(row.max_days_overdue||0)} d venc.</span>`;if(Number(row.due_7_balance||0)>0)return '<span class="aging-pill is-warning">Por vencer</span>';return '<span class="aging-pill is-ok">Al día</span>';}
    function renderRows(rows){
        state.rows=rows||[];
        if(!state.rows.length){
            $('agingRows').innerHTML='<tr><td colspan="12">Sin proveedores con saldo abierto para los filtros seleccionados.</td></tr>';
            return;
        }
        $('agingRows').innerHTML=state.rows.map(row=>`<tr>
            <td class="crm-mobile-primary"><div class="crm-ui-cell-stack"><strong>${esc(row.supplier_name||'Proveedor sin identificar')}</strong><small>${riskPill(row)}</small></div></td>
            <td class="crm-mobile-hidden">${esc(row.supplier_tax_id||'-')}</td>
            <td class="crm-mobile-hidden">${esc(row.documents_count||0)}</td>
            <td class="money crm-mobile-metric"><strong>${money(row.open_balance)}</strong></td>
            <td class="money crm-mobile-hidden">${money(row.overdue_balance)}</td>
            <td class="money crm-mobile-hidden">${money(row.due_7_balance)}</td>
            <td class="money crm-mobile-hidden">${money(row.bucket_0_30)}</td>
            <td class="money crm-mobile-hidden">${money(row.bucket_31_60)}</td>
            <td class="money crm-mobile-hidden">${money(row.bucket_61_90)}</td>
            <td class="money crm-mobile-hidden">${money(row.bucket_90_plus)}</td>
            <td class="crm-mobile-hidden">${esc(row.finance_center_name||'Sin centro')}</td>
            <td class="crm-ui-action-cell"><button type="button" class="btn btn-outline crm-ui-action-btn" data-aging-detail="${esc(row.supplier_key)}" aria-label="Ver aging de ${esc(row.supplier_name||'proveedor')}"><i data-lucide="eye" aria-hidden="true"></i></button></td>
        </tr>`).join('');
        refreshIcons();
    }
    async function loadAging(){$('agingRows').innerHTML='<tr><td colspan="12">Cargando...</td></tr>';const data=await fetchData('/modules/billing/suppliers_aging_ajax.php?'+buildParams().toString());renderCenters(data.centers||[]);renderKpis(data.kpis||{});renderRows(data.rows||[]);}
    function setFooter(html){$('agingModalFooter').innerHTML=html;refreshIcons();}
    async function openDetail(supplierKey){
        state.currentKey=supplierKey;state.currentEnvironment=$('agingEnv').value||'sandbox';
        const data=await fetchData('/modules/billing/supplier_aging_detail_ajax.php?'+buildParams({supplier_key:supplierKey}).toString());const supplier=data.supplier||{};const rows=data.rows||[];
        $('agingModalTitle').textContent=supplier.supplier_name||'Proveedor';$('agingModalSubtitle').textContent=`${supplier.supplier_tax_id||'-'} · ${rows.length} documento(s) con saldo`;
        $('agingModalBody').innerHTML=renderDetail(supplier,rows);$('agingModal').style.display='flex';$('agingModal').classList.add('show');$('agingModal').setAttribute('aria-hidden','false');document.body.classList.add('is-modal-open');
        setFooter('<div class="modal-footer-actions-right"><button type="button" class="btn btn-outline" id="closeAgingFooterBtn"><i data-lucide="x"></i><span>Cerrar</span></button></div>');refreshIcons();
    }
    function renderDetail(supplier,rows){return `<div class="aging-summary-grid crm-ui-summary-grid"><div class="aging-summary-card crm-ui-summary-card"><span>Saldo abierto</span><strong>${money(supplier.open_balance)}</strong></div><div class="aging-summary-card crm-ui-summary-card"><span>Vencido</span><strong>${money(supplier.overdue_balance)}</strong></div><div class="aging-summary-card crm-ui-summary-card"><span>Por vencer 7 días</span><strong>${money(supplier.due_7_balance)}</strong></div><div class="aging-summary-card crm-ui-summary-card"><span>Máximo atraso</span><strong>${Number(supplier.max_days_overdue||0)} días</strong></div></div><div class="aging-detail-table-wrap crm-ui-inner-table-wrap"><table class="aging-detail-table aging-detail-table--documents crm-ui-inner-table"><thead><tr><th>Folio</th><th>Tipo</th><th>Emisión</th><th>Vence</th><th>Total</th><th>Pagado</th><th>Saldo</th><th>Estado</th><th>Centro</th><th></th></tr></thead><tbody>${rows.map(row=>`<tr><td><strong>${esc(row.document_number||'-')}</strong></td><td>${esc(row.document_type_taxbureau||row.document_type_id||'-')}</td><td>${shortDate(row.document_date)}</td><td>${shortDate(row.due_date)}</td><td class="money">${money(row.aging_total_amount||row.total_amount)}</td><td class="money">${money(row.paid_amount)}</td><td class="money">${money(row.balance_amount)}</td><td>${esc(statusLabel(row.financial_status))}</td><td>${esc(row.finance_center_name||'Sin centro')}</td><td><button type="button" class="btn btn-secondary" data-aging-pay-id="${esc(row.id)}">Ir a pagar</button></td></tr>`).join('')}</tbody></table></div>`;}
    function statusLabel(value){const labels={por_pagar:'Por pagar',vencido:'Vencido',parcial:'Parcial',pagado:'Pagado',rechazado:'Rechazado',anulado:'Anulado'};return labels[value]||value||'-';}

    async function openPayment(id){
        const env=state.currentEnvironment||$('agingEnv').value||'sandbox';
        const data=await requestJson('/modules/billing/payable_detail_ajax.php?id='+encodeURIComponent(id)+'&env='+encodeURIComponent(env),{headers:{Accept:'application/json'}});
        state.paymentDocument=data.document;state.paymentOptions=data.options||{};renderPayment(data.document,data.payments||[],data.options||{},false);
    }
    function renderPayment(doc,payments,options,saved){
        const balance=Number(doc.balance_amount!=null?doc.balance_amount:doc.total_amount||0);const status=doc.collection_status||doc.payment_status||'por_pagar';
        $('agingModalTitle').textContent='Registrar pago · '+(doc.document_number||'-');$('agingModalSubtitle').textContent=(doc.supplier_name||doc.issuer_name||'Proveedor')+' · '+money(balance)+' pendiente';
        const methods=optionHtml(options.payment_methods,'id','method_name');const accounts=optionHtml(options.cash_accounts,'id','account_name');
        const history=(payments||[]).length?(payments||[]).map(p=>`<tr><td>${esc(shortDate(p.payment_date))}</td><td><strong>${money(p.amount)}</strong></td><td>${esc(p.method_name||'-')}</td><td>${esc(p.account_name||'-')}</td></tr>`).join(''):'<tr><td colspan="4">Sin pagos registrados.</td></tr>';
        $('agingModalBody').innerHTML=`<div class="aging-summary-grid crm-ui-summary-grid"><div class="aging-summary-card crm-ui-summary-card"><span>Total</span><strong>${money(doc.total_amount)}</strong></div><div class="aging-summary-card crm-ui-summary-card"><span>Pagado</span><strong>${money(doc.paid_amount)}</strong></div><div class="aging-summary-card crm-ui-summary-card"><span>Saldo</span><strong>${money(balance)}</strong></div><div class="aging-summary-card crm-ui-summary-card"><span>Estado</span><strong>${esc(statusLabel(status))}</strong></div></div>${saved?'<div class="receive-info-note" style="margin-bottom:12px;border-radius:12px"><strong>Pago guardado.</strong> La cuenta y el aging fueron actualizados.</div>':''}<div class="aging-payment-grid crm-ui-form-grid"><section class="aging-payment-card crm-ui-section"><h3>Documento</h3><p><strong>Proveedor:</strong> ${esc(doc.supplier_name||doc.issuer_name||'-')}</p><p><strong>RUT:</strong> ${esc(doc.issuer_tax_id_code||'-')}</p><p><strong>Folio:</strong> ${esc(doc.document_number||'-')}</p><p><strong>Vence:</strong> ${esc(shortDate(doc.due_date||doc.payment_due_date))}</p></section><section class="aging-payment-card crm-ui-section"><h3>Registrar pago</h3>${balance>0.5?`<form id="agingPaymentForm"><input type="hidden" name="idempotency_key" value="${esc(paymentRequestKey('aging-cxp'))}"><input type="hidden" name="expected_collection_id" value="${esc(doc.collection_id || '')}"><input type="hidden" name="expected_inbox_document_id" value="${esc(doc.inbox_document_id || '')}"><input type="hidden" name="expected_balance" value="${esc(balance.toFixed(2))}"><div class="aging-payment-field crm-ui-field"><label>Fecha</label><input type="date" name="payment_date" value="${today()}" required></div><div class="aging-payment-field crm-ui-field"><label>Monto</label><input type="number" name="amount" min="1" max="${esc(balance)}" step="0.01" value="${esc(balance)}" required></div><div class="aging-payment-field crm-ui-field"><label>Método</label><select name="payment_method_id" required>${methods}</select></div><div class="aging-payment-field crm-ui-field"><label>Caja / cuenta</label><select name="cash_account_id" required>${accounts}</select></div><div class="aging-payment-field crm-ui-field"><label>Referencia</label><input type="text" name="external_reference" maxlength="120" ${state.currentEnvironment==='production'?'required':''}></div><div class="aging-payment-field crm-ui-field"><label>Nota</label><textarea name="notes"></textarea></div></form>`:'<p>El documento está completamente pagado.</p>'}</section></div><section class="aging-payment-card crm-ui-section" style="margin-top:12px"><h3>Historial de pagos</h3><div class="aging-detail-table-wrap crm-ui-inner-table-wrap"><table class="aging-detail-table aging-detail-table--history crm-ui-inner-table"><thead><tr><th>Fecha</th><th>Monto</th><th>Método</th><th>Cuenta</th></tr></thead><tbody>${history}</tbody></table></div></section>`;
        setFooter(`<div class="modal-footer-actions-left"><button type="button" class="btn btn-outline" id="backSupplierAgingBtn"><i data-lucide="arrow-left"></i><span>Volver a aging</span></button></div><div class="modal-footer-actions-right">${balance>0.5?`<button type="button" class="btn btn-success" id="registerAgingPaymentBtn"><i data-lucide="badge-dollar-sign"></i><span>${saved?'Registrar otro pago':'Registrar pago'}</span></button>`:'<span class="billing-save-confirmation"><i data-lucide="circle-check"></i> Cuenta pagada</span>'}</div>`);
    }
    async function registerPayment(){const form=$('agingPaymentForm');if(!form||!form.reportValidity())return;const amount=Number(form.amount.value||0);const reference=String(form.external_reference.value||'').trim();if(!window.confirm(`Registrar pago por ${money(amount)}?\nReferencia: ${reference||'sin referencia'}`))return;const button=$('registerAgingPaymentBtn');if(button)button.disabled=true;try{const fd=new FormData(form);fd.append('id',state.paymentDocument.id);fd.append('environment',state.currentEnvironment);const data=await requestJson('/modules/billing/payable_register_payment_ajax.php',{method:'POST',body:fd});state.paymentDocument=data.document;renderPayment(data.document,data.payments||[],state.paymentOptions||{},true);await loadAging();}finally{if(button&&document.body.contains(button))button.disabled=false;}}
    async function backToAging(){if(state.currentKey)await openDetail(state.currentKey);}
    function syncModalBodyLock(){const hasOpenModal=Array.from(document.querySelectorAll('.product-modal-backdrop.show')).some(modal=>modal.getAttribute('aria-hidden')!=='true');document.body.classList.toggle('is-modal-open',hasOpenModal);}
    function closeModal(){$('agingModal').style.display='none';$('agingModal').classList.remove('show');$('agingModal').setAttribute('aria-hidden','true');syncModalBodyLock();}

    on(document,'click',event=>{
        if(event.target===$('agingModal')){closeModal();return;}
        const detailButton=event.target.closest('[data-aging-detail]');if(detailButton){openDetail(detailButton.getAttribute('data-aging-detail')).catch(error=>alert(error.message));return;}
        const payButton=event.target.closest('[data-aging-pay-id]');if(payButton){event.preventDefault();openPayment(payButton.getAttribute('data-aging-pay-id')).catch(error=>alert(error.message));return;}
        const action=event.target.closest('button,a');const actionId=action?action.id:'';
        if(actionId==='reloadAgingBtn'){loadAging().catch(error=>alert(error.message));return;}
        if(actionId==='registerAgingPaymentBtn'){registerPayment().catch(error=>alert(error.message));return;}
        if(actionId==='backSupplierAgingBtn'){backToAging().catch(error=>alert(error.message));return;}
        if(actionId==='closeAgingModalBtn'||actionId==='closeAgingFooterBtn')closeModal();
    });
    ['agingEnv','agingBucket','agingCenter'].forEach(id=>on($(id),'change',()=>loadAging().catch(error=>alert(error.message))));
    on($('agingSearch'),'keydown',event=>{if(event.key==='Enter')loadAging().catch(error=>alert(error.message));});
    on(document,'keydown',event=>{if(event.key==='Escape'&&$('agingModal')?.classList.contains('show'))closeModal();});
    loadAging().catch(error=>{$('agingRows').innerHTML=`<tr><td colspan="12">${esc(error.message)}</td></tr>`;});
})();
