(function () {
    'use strict';
    if (window.__ICY_TREASURY_MODULE_ACTIVE) return;
    window.__ICY_TREASURY_MODULE_ACTIVE = true;
    const controller = new AbortController();
    const on = (target, event, handler) => target && target.addEventListener(event, handler, { signal: controller.signal });
    window.ICY_PAGE_CLEANUPS = window.ICY_PAGE_CLEANUPS || [];
    window.ICY_PAGE_CLEANUPS.push(() => { controller.abort(); window.__ICY_TREASURY_MODULE_ACTIVE = false; document.body.style.overflow = ''; });

    const state = { start: window.ICY_TREASURY_INITIAL_START || today(), scenario: 'base', accountId: '', data: null };
    const $ = (id) => document.getElementById(id);
    const esc = (value) => String(value == null ? '' : value).replace(/[&<>'"]/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;' }[c]));
    const money = (value) => (Number(value || 0) < 0 ? '-$' : '$') + Math.round(Math.abs(Number(value || 0))).toLocaleString('es-CL');
    const iconRefresh = () => { if (window.lucide && typeof window.lucide.createIcons === 'function') window.lucide.createIcons(); };
    const labels = {
        direction: { inflow:'Entrada', outflow:'Salida' }, activity: { operations:'Operación', investment:'Inversión', financing:'Financiamiento', internal_transfer:'Transferencia interna' },
        statement: { pending:'Pendiente', matched:'Conciliado', converted:'Convertido', ignored:'Ignorado' }, source: { billing:'Facturación', manual:'Manual' }
    };

    function today() { const d=new Date(); return [d.getFullYear(),String(d.getMonth()+1).padStart(2,'0'),String(d.getDate()).padStart(2,'0')].join('-'); }
    function showNotice(message,type){const el=$('treasuryNotice');if(!el)return;el.hidden=!message;el.textContent=message||'';el.className='treasury-notice'+(type?' is-'+type:'');if(message&&type==='success')window.setTimeout(()=>{if(el.textContent===message)el.hidden=true;},5500);}
    async function request(url,options){const response=await fetch(url,Object.assign({credentials:'same-origin'},options||{}));const text=await response.text();let payload;try{payload=JSON.parse(text);}catch(e){throw new Error(text||'El servidor entregó una respuesta no válida.');}if(!response.ok||payload.success===false)throw new Error(payload.message||'No fue posible completar la operación.');return payload;}
    async function action(input){let data;if(input instanceof HTMLFormElement)data=new FormData(input);else{data=new FormData();Object.keys(input||{}).forEach((key)=>data.append(key,input[key]==null?'':input[key]));}const token=document.querySelector('meta[name="csrf-token"]');if(token&&!data.has('_csrf_token'))data.append('_csrf_token',token.content);return request('/modules/treasury/action_ajax.php',{method:'POST',body:data});}

    async function loadData(message){showNotice('','');const quality=$('treasuryQuality');if(quality){quality.className='treasury-quality';quality.innerHTML='<i data-lucide="loader-circle"></i><span>Actualizando posición de caja…</span>';iconRefresh();}try{const query=new URLSearchParams({start:state.start,scenario:state.scenario});if(state.accountId)query.set('account_id',state.accountId);const payload=await request('/modules/treasury/data_ajax.php?'+query.toString());state.data=payload.data;state.start=payload.data.start_date;renderAll();if(message)showNotice(message,'success');}catch(error){showNotice(error.message,'error');if(quality){quality.className='treasury-quality is-provisional';quality.innerHTML='<i data-lucide="circle-alert"></i><span>'+esc(error.message)+'</span>';iconRefresh();}}}

    function renderAll(){if(!state.data)return;syncControls();renderQuality();renderKpis();renderForecast();renderLedger();renderAccounts();renderReconciliation();renderScenarios();applyPermissions();fillCatalogs();iconRefresh();}
    function syncControls(){$('treasuryStart').value=state.data.start_date;$('treasuryScenario').value=state.data.scenario_key;const options='<option value="">Todas las cuentas</option>'+state.data.accounts.map((a)=>'<option value="'+a.id+'">'+esc(a.account_name)+'</option>').join('');$('treasuryAccount').innerHTML=options;$('treasuryAccount').value=state.accountId;}
    function renderQuality(){const q=state.data.quality;const el=$('treasuryQuality');const valid=q==='validated';el.className='treasury-quality '+(valid?'is-validated':'is-provisional');el.innerHTML='<i data-lucide="'+(valid?'badge-check':'triangle-alert')+'"></i><span><strong>'+(valid?'Cobertura validada':'Cifras provisionales')+':</strong> '+esc(state.data.summary.quality_note)+'</span>';}
    function renderKpis(){const s=state.data.summary;const cards=[
        ['Caja disponible',money(s.current_balance),'Saldo realizado a hoy',Number(s.current_balance)<0],
        ['Inicio del forecast',money(s.opening_balance),'Corte al domingo anterior',Number(s.opening_balance)<0],
        ['Saldo mínimo',money(s.minimum_balance),'Menor cierre semanal',Number(s.minimum_balance)<0],
        ['Cierre semana 13',money(s.projected_end_balance),'Escenario '+scenarioName(state.data.scenario_key),Number(s.projected_end_balance)<0],
        ['Runway',s.runway_months==null?'N/D':Number(s.runway_months).toLocaleString('es-CL',{maximumFractionDigits:1})+' meses','Salida bruta promedio',false],
        ['Semanas en déficit',Number(s.deficit_weeks||0).toLocaleString('es-CL'),s.first_deficit_date?'Primera: '+formatDate(s.first_deficit_date):'Sin déficit proyectado',Number(s.deficit_weeks)>0]
    ];$('treasuryKpis').innerHTML=cards.map((c)=>'<article class="treasury-kpi'+(c[3]?' is-danger':'')+'"><span>'+esc(c[0])+'</span><strong>'+esc(c[1])+'</strong><small>'+esc(c[2])+'</small></article>').join('');}
    function renderForecast(){let opening=Number(state.data.summary.opening_balance||0);$('forecastBody').innerHTML=(state.data.weeks||[]).map((w)=>{const scenarioNet=Number(w.scenario_inflows||0)-Number(w.scenario_outflows||0);const startBalance=opening;opening=Number(w.ending_balance||0);return '<tr class="'+(opening<0?'is-negative':'')+'"><td><strong>S'+esc(w.index)+' · '+esc(formatDate(w.start))+'</strong><small>al '+esc(formatDate(w.end))+' · '+esc(w.items)+' partida(s)</small></td><td class="number">'+esc(money(startBalance))+'</td><td class="number">'+esc(money(w.realized_inflows))+'</td><td class="number">'+esc(money(w.realized_outflows))+'</td><td class="number">'+esc(money(w.committed_inflows))+'</td><td class="number">'+esc(money(w.committed_outflows))+'</td><td class="number '+(scenarioNet<0?'negative':'')+'">'+esc(money(scenarioNet))+'</td><td class="number '+(Number(w.net_flow)<0?'negative':'')+'"><strong>'+esc(money(w.net_flow))+'</strong></td><td class="number"><strong>'+esc(money(w.ending_balance))+'</strong></td></tr>';}).join('');const c=state.data.coverage||{};$('coverageSources').innerHTML='<div class="source-chips"><span>CxC: <strong>'+Number(c.receivables||0)+'</strong></span><span>CxP: <strong>'+Number(c.payables||0)+'</strong></span><span>Costos aprobados sin CxP: <strong>'+Number(c.costs||0)+'</strong></span><span>Recurrencias futuras: <strong>'+Number(c.recurring_rules||0)+'</strong></span><span title="Se excluyen hasta contar con vínculo OC–DTE para evitar duplicidad">OC excluidas por control: <strong>'+Number(c.purchase_orders_excluded||0)+'</strong></span></div>';const confirmation=state.data.coverage_confirmation||{};const checks=['payroll_complete','taxes_complete','financing_complete','other_expenses_complete'].filter((key)=>Number(confirmation[key])).length;$('coverageStatus').textContent='Cobertura declarada: '+checks+'/4 · '+(confirmation.confirmed_through?'revisada hasta '+formatDate(confirmation.confirmed_through):'sin fecha de revisión');}
    function renderLedger(){const search=($('ledgerSearch').value||'').trim().toLowerCase();const rows=(state.data.ledger||[]).filter((r)=>!search||[r.detail,r.external_reference,r.document_number,r.account_name,r.center_name].join(' ').toLowerCase().includes(search));$('ledgerBody').innerHTML=rows.length?rows.map((r)=>{const incoming=r.direction==='inflow';const editable=r.source==='manual'&&state.data.permissions.edit;const status=r.status==='draft'?'<span class="status-pill pending">Borrador</span>':'';return '<tr><td><strong>'+esc(formatDate(r.movement_date))+'</strong></td><td><strong>'+esc(r.account_name||'Sin cuenta')+'</strong><small>'+esc(labels.source[r.source]||r.source)+(r.transfer_group?' · Transferencia':'')+'</small></td><td>'+status+'<strong>'+esc(r.detail||'Movimiento')+'</strong><small>'+esc(r.external_reference||r.document_number||'Sin referencia')+'</small></td><td>'+esc(r.center_name||'Sin centro')+'</td><td class="number">'+(incoming?'<strong>'+esc(money(r.amount))+'</strong>':'—')+'</td><td class="number">'+(!incoming?'<strong>'+esc(money(r.amount))+'</strong>':'—')+'</td><td><div class="row-actions">'+(editable?'<button class="btn btn-outline btn-sm" type="button" data-void-movement="'+r.id+'" title="Anular"><i data-lucide="ban"></i></button>':'')+'</div></td></tr>';}).join(''):'<tr><td colspan="7" class="treasury-empty">No hay movimientos que coincidan.</td></tr>';iconRefresh();}
    function renderAccounts(){const positions={};(state.data.account_positions||[]).forEach((p)=>{positions[p.account_id]=p;});$('accountCards').innerHTML=state.data.accounts.map((a)=>{const p=positions[a.id];const b=p&&p.opening?p.opening:null;return '<article class="account-card"><header><div><span class="label">'+esc(accountType(a.account_type))+'</span><strong>'+esc(a.account_name)+'</strong></div><i data-lucide="'+(a.account_type==='bank'?'landmark':'wallet-cards')+'"></i></header><strong>'+(b?esc(money(p.amount)):'Sin saldo inicial')+'</strong><small>'+(b?'Posición a hoy · corte '+esc(formatDate(b.balance_date))+' · '+(Number(b.is_reconciled)?'Conciliado':'Pendiente de conciliar'):'Configura un corte para incorporarla')+'</small></article>';}).join('');$('openingBody').innerHTML=(state.data.opening_balances||[]).length?state.data.opening_balances.map((b)=>'<tr><td>'+esc(formatDate(b.balance_date))+'</td><td><strong>'+esc(b.account_name)+'</strong><small>'+esc(accountType(b.account_type))+'</small></td><td>'+esc(b.currency_code)+'</td><td><span class="status-pill '+(Number(b.is_reconciled)?'matched':'pending')+'">'+(Number(b.is_reconciled)?'Conciliado':'Provisional')+'</span></td><td class="number"><strong>'+esc(money(b.amount))+'</strong></td><td>'+esc(b.notes||'—')+'</td></tr>').join(''):'<tr><td colspan="6" class="treasury-empty">Aún no se registran saldos iniciales.</td></tr>';}
    function renderReconciliation(){const s=state.data.statement.summary||{};$('reconciliationSummary').innerHTML=[['Pendientes',s.pending],['Conciliados',s.matched],['Convertidos',s.converted],['Ignorados',s.ignored]].map((r)=>'<div class="reconciliation-stat"><strong>'+Number(r[1]||0)+'</strong><small>'+esc(r[0])+'</small></div>').join('');const filter=$('statementStatusFilter').value;const rows=(state.data.statement.rows||[]).filter((r)=>!filter||r.reconciliation_status===filter);$('statementBody').innerHTML=rows.length?rows.map((r)=>{const pending=r.reconciliation_status==='pending';const amount=Number(r.signed_amount);return '<tr><td>'+esc(formatDate(r.row_date))+'</td><td>'+esc(r.account_name)+'</td><td><strong>'+esc(r.description)+'</strong><small>'+esc(r.reference||'Sin referencia')+'</small></td><td><span class="status-pill '+esc(r.reconciliation_status)+'">'+esc(labels.statement[r.reconciliation_status]||r.reconciliation_status)+'</span></td><td class="number '+(amount<0?'negative':'')+'"><strong>'+esc(money(amount))+'</strong></td><td><div class="row-actions">'+(pending&&state.data.permissions.reconcile?'<button class="btn btn-outline btn-sm" type="button" data-convert-row="'+r.id+'" title="Convertir en movimiento"><i data-lucide="book-plus"></i></button><button class="btn btn-outline btn-sm" type="button" data-ignore-row="'+r.id+'" title="Ignorar"><i data-lucide="eye-off"></i></button>':'')+'</div></td></tr>';}).join(''):'<tr><td colspan="6" class="treasury-empty">No hay filas en este estado.</td></tr>';iconRefresh();}
    function renderScenarios(){const rows=state.data.scenario_items||[];$('scenarioBody').innerHTML=rows.length?rows.map((r)=>'<tr><td>'+esc(formatDate(r.expected_date))+'</td><td><strong>'+esc(r.scenario_name)+'</strong></td><td><strong>'+esc(r.description)+'</strong><small>'+esc((labels.direction[r.item_type]||r.item_type)+(r.counterparty?' · '+r.counterparty:''))+'</small></td><td>'+esc(labels.activity[r.cash_activity]||r.cash_activity)+'<small>'+esc(r.center_name||'Sin centro')+'</small></td><td>'+Number(r.probability_pct).toLocaleString('es-CL',{maximumFractionDigits:2})+'%</td><td class="number"><strong>'+esc(money(r.amount))+'</strong><small>Ponderado '+esc(money(Number(r.amount)*Number(r.probability_pct)/100))+'</small></td><td><div class="row-actions">'+(state.data.permissions.scenarios?'<button class="btn btn-outline btn-sm" type="button" data-edit-scenario="'+r.id+'"><i data-lucide="pencil"></i></button><button class="btn btn-outline btn-sm" type="button" data-cancel-scenario="'+r.id+'"><i data-lucide="ban"></i></button>':'')+'</div></td></tr>').join(''):'<tr><td colspan="7" class="treasury-empty">No existen partidas activas de escenario.</td></tr>';}

    function fillCatalogs(){const accountOptions=state.data.accounts.map((a)=>'<option value="'+a.id+'">'+esc(a.account_name)+'</option>').join('');['openingAccount','movementAccount','transferFrom','transferTo','statementAccount'].forEach((id)=>{const el=$(id);const previous=el.value;el.innerHTML='<option value="">Seleccionar…</option>'+accountOptions;if(previous)el.value=previous;});const centers='<option value="">Sin centro</option>'+state.data.finance_centers.map((c)=>'<option value="'+c.id+'">'+esc(c.center_code+' · '+c.center_name)+'</option>').join('');['movementCenter','scenarioCenter'].forEach((id)=>{$(id).innerHTML=centers;});$('scenarioItemScenario').innerHTML=state.data.scenarios.map((s)=>'<option value="'+s.id+'">'+esc(s.scenario_name)+'</option>').join('');const bank=state.data.accounts.find((a)=>a.account_type==='bank')||state.data.accounts[0];if(bank&&!$('statementAccount').value)$('statementAccount').value=bank.id;}
    function applyPermissions(){const p=state.data.permissions||{};['newMovementBtn','newTransferBtn','newOpeningBtn','coverageBtn'].forEach((id)=>{$(id).hidden=!p.edit;});$('newScenarioItemBtn').hidden=!p.scenarios;$('statementForm').hidden=!p.reconcile;$('autoReconcileBtn').hidden=!p.reconcile;}
    function openModal(id){const el=$(id);if(!el)return;el.classList.add('is-open');el.setAttribute('aria-hidden','false');document.body.style.overflow='hidden';iconRefresh();}
    function closeModal(id){const el=$(id);if(!el)return;el.classList.remove('is-open');el.setAttribute('aria-hidden','true');if(!document.querySelector('.treasury-modal.is-open'))document.body.style.overflow='';}
    function activateTab(name){document.querySelectorAll('[data-treasury-tab]').forEach((b)=>b.classList.toggle('is-active',b.dataset.treasuryTab===name));document.querySelectorAll('[data-treasury-panel]').forEach((p)=>p.classList.toggle('is-active',p.dataset.treasuryPanel===name));}
    function scenarioName(key){const found=(state.data.scenarios||[]).find((s)=>s.scenario_key===key);return found?found.scenario_name:key;}
    function accountType(type){return ({bank:'Banco',cash:'Efectivo',gateway:'Pasarela',other:'Otra cuenta'})[type]||type;}
    function formatDate(value){if(!value)return'—';const parts=String(value).slice(0,10).split('-');return parts.length===3?parts[2]+'-'+parts[1]+'-'+parts[0]:value;}

    on($('treasuryRefresh'),'click',()=>{state.start=$('treasuryStart').value;state.scenario=$('treasuryScenario').value;state.accountId=$('treasuryAccount').value;loadData();});
    on($('treasuryScenario'),'change',()=>{state.scenario=$('treasuryScenario').value;loadData();});
    on($('treasuryAccount'),'change',()=>{state.accountId=$('treasuryAccount').value;loadData();});
    on($('ledgerSearch'),'input',renderLedger);on($('statementStatusFilter'),'change',renderReconciliation);
    document.querySelectorAll('[data-treasury-tab]').forEach((button)=>on(button,'click',()=>activateTab(button.dataset.treasuryTab)));
    document.querySelectorAll('[data-close]').forEach((button)=>on(button,'click',()=>closeModal(button.dataset.close)));
    document.querySelectorAll('.treasury-modal').forEach((modal)=>on(modal,'click',(event)=>{if(event.target===modal)closeModal(modal.id);}));

    on($('newOpeningBtn'),'click',()=>{$('openingForm').reset();fillCatalogs();$('openingDate').value=today();openModal('openingModal');});
    on($('newMovementBtn'),'click',()=>{$('movementForm').reset();fillCatalogs();$('movementDate').value=today();openModal('movementModal');});
    on($('newTransferBtn'),'click',()=>{$('transferForm').reset();fillCatalogs();$('transferDate').value=today();openModal('transferModal');});
    on($('newScenarioItemBtn'),'click',()=>{$('scenarioForm').reset();fillCatalogs();$('scenarioItemDate').value=today();const selected=state.data.scenarios.find((s)=>s.scenario_key===state.scenario);if(selected)$('scenarioItemScenario').value=selected.id;openModal('scenarioModal');});
    on($('coverageBtn'),'click',()=>{const form=$('coverageForm');form.reset();const row=state.data.coverage_confirmation||{};['payroll_complete','taxes_complete','financing_complete','other_expenses_complete'].forEach((key)=>{form.elements[key].checked=Number(row[key])===1;});form.elements.confirmed_through.value=row.confirmed_through||state.data.end_date;form.elements.notes.value=row.notes||'';openModal('coverageModal');});

    ['openingForm','movementForm','transferForm','scenarioForm','coverageForm','statementForm'].forEach((id)=>on($(id),'submit',async(event)=>{event.preventDefault();const form=event.currentTarget;const button=document.querySelector('[form="'+form.id+'"]')||form.querySelector('[type="submit"]');if(button)button.disabled=true;try{const result=await action(form);if(id==='statementForm')form.reset();else closeModal(form.closest('.treasury-modal').id);let message='Información guardada y flujo recalculado.';if(id==='statementForm')message=Number(result.data.rows_imported||0)+' fila(s) importada(s) sin duplicar.';await loadData(message);}catch(error){showNotice(error.message,'error');}finally{if(button)button.disabled=false;}}));

    on($('autoReconcileBtn'),'click',async()=>{const account=$('statementAccount').value;if(!account){showNotice('Selecciona una cuenta para conciliar.','error');return;}try{const payload=await action({action:'auto_reconcile',cash_account_id:account});await loadData(Number(payload.data.matched||0)+' coincidencia(s) conciliada(s). '+Number(payload.data.ambiguous||0)+' quedó(aron) para revisión.');}catch(error){showNotice(error.message,'error');}});

    on(document,'click',async(event)=>{
        const voidBtn=event.target.closest&&event.target.closest('[data-void-movement]');if(voidBtn){if(!window.confirm('¿Anular este movimiento? Si es transferencia, se anulará el par completo.'))return;try{await action({action:'void_movement',id:voidBtn.dataset.voidMovement});await loadData('Movimiento anulado.');}catch(error){showNotice(error.message,'error');}return;}
        const convertBtn=event.target.closest&&event.target.closest('[data-convert-row]');if(convertBtn){if(!window.confirm('La fila se convertirá en un movimiento confirmado de caja. ¿Continuar?'))return;try{await action({action:'convert_statement_row',id:convertBtn.dataset.convertRow});await loadData('Fila bancaria convertida y conciliada.');}catch(error){showNotice(error.message,'error');}return;}
        const ignoreBtn=event.target.closest&&event.target.closest('[data-ignore-row]');if(ignoreBtn){if(!window.confirm('¿Ignorar esta fila? No afectará el saldo de caja.'))return;try{await action({action:'ignore_statement_row',id:ignoreBtn.dataset.ignoreRow});await loadData('Fila bancaria ignorada.');}catch(error){showNotice(error.message,'error');}return;}
        const cancelBtn=event.target.closest&&event.target.closest('[data-cancel-scenario]');if(cancelBtn){if(!window.confirm('¿Cancelar esta partida de escenario?'))return;try{await action({action:'cancel_scenario_item',id:cancelBtn.dataset.cancelScenario});await loadData('Partida cancelada.');}catch(error){showNotice(error.message,'error');}return;}
        const editBtn=event.target.closest&&event.target.closest('[data-edit-scenario]');if(editBtn){const row=state.data.scenario_items.find((item)=>String(item.id)===String(editBtn.dataset.editScenario));if(!row)return;const form=$('scenarioForm');form.reset();fillCatalogs();Object.keys(row).forEach((key)=>{if(form.elements[key])form.elements[key].value=row[key]==null?'':row[key];});openModal('scenarioModal');}
    });

    on(document,'keydown',(event)=>{if(event.key==='Escape'){const modal=document.querySelector('.treasury-modal.is-open');if(modal)closeModal(modal.id);}});
    loadData();
})();
