(function(){
    'use strict';

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

    const state={environment:'sandbox',sourceType:'quote',sourceId:0,source:null,guideId:0,preview:null,searchTimer:null};
    const $=id=>document.getElementById(id);
    const esc=v=>String(v==null?'':v).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]));
    const money=v=>new Intl.NumberFormat('es-CL',{style:'currency',currency:'CLP',maximumFractionDigits:0}).format(Number(v||0));
    const dateText=v=>{if(!v)return'-';const p=String(v).slice(0,10).split('-');return p.length===3?`${p[2]}-${p[1]}-${p[0]}`:String(v);};
    const today=()=>new Date().toISOString().slice(0,10);
    const layers={source:'documentLayerGuideSource',prepare:'documentLayerGuidePrepare',preview:'documentLayerGuidePreview',confirm:'documentLayerGuideConfirm',result:'documentLayerGuideResult'};

    function icons(){if(window.lucide&&window.lucide.createIcons)window.lucide.createIcons();}
    function modalFooter(rightActions,leftActions=''){return `${leftActions?`<div class="modal-footer-actions-left">${leftActions}</div>`:''}<div class="modal-footer-actions-right">${rightActions||''}</div>`;}
    function syncGuideAvailability(){const b=$('newDispatchGuideBtn');if(b){b.disabled=false;b.title='Crear guía de despacho';}}
    async function jsonFetch(url,options){const r=await fetch(url,options||{});let p=null;try{p=await r.json();}catch(e){}if(!r.ok||!p||p.success===false)throw new Error(p&&p.message?p.message:`Error HTTP ${r.status}`);return p;}
    function openModal(){const m=$('documentModal');if(!m)return;m.style.display='flex';m.classList.add('show');m.setAttribute('aria-hidden','false');document.body.classList.add('is-modal-open');icons();}
    function closeModal(){const m=$('documentModal');if(!m)return;m.classList.remove('show');m.setAttribute('aria-hidden','true');setTimeout(()=>{if(!m.classList.contains('show'))m.style.display='none';},120);document.body.classList.remove('is-modal-open');}
    function setLayer(name){document.querySelectorAll('#documentModal .documents-modal-layer').forEach(el=>el.classList.remove('active'));const el=$(layers[name]);if(el){el.classList.add('active');const body=el.querySelector('.product-modal-body');if(body)body.scrollTop=0;}icons();}
    function steps(active){return `<div class="guide-steps">${[['source','1. Origen'],['prepare','2. Preparar'],['preview','3. Preview'],['confirm','4. Confirmar'],['result','5. Resultado']].map(([k,l])=>`<div class="guide-step${k===active?' active':''}">${l}</div>`).join('')}</div>`;}
    function guideTypeOptions(){return [[1,'Operación constituye venta'],[2,'Ventas por efectuar'],[3,'Consignación'],[4,'Entrega gratuita'],[5,'Traslado interno'],[6,'Otros traslados no venta'],[7,'Devolución'],[8,'Traslado para exportación'],[9,'Venta para exportación']].map(([v,l])=>`<option value="${v}">${l}</option>`).join('');}
    function transferTypeOptions(){return [[1,'Despacho por cuenta del receptor'],[2,'Despacho por cuenta del emisor a instalaciones del receptor'],[3,'Despacho por cuenta del emisor a otras instalaciones']].map(([v,l])=>`<option value="${v}"${v===2?' selected':''}>${l}</option>`).join('');}

    function openSourceSelector(sourceType){
        state.sourceType=sourceType||'quote';state.sourceId=0;state.source=null;state.guideId=0;state.preview=null;
        state.environment=$('documentsEnv')?.value||'sandbox';
        $('guideSourceBody').innerHTML=`${steps('source')}<div class="documents-alert"><strong>Guía de despacho ${esc(state.environment)}.</strong> El flujo no modifica stock ni genera cuentas por cobrar.</div><div class="guide-source-tabs"><button type="button" class="btn btn-secondary guide-source-tab${state.sourceType==='quote'?' active':''}" data-source-tab="quote">Desde cotización</button><button type="button" class="btn btn-secondary guide-source-tab${state.sourceType==='invoice'?' active':''}" data-source-tab="invoice">Desde factura</button></div><div class="documents-field crm-ui-field"><label>Buscar origen</label><input id="guideSourceSearch" type="search" placeholder="Folio, cotización, cliente o RUT" autocomplete="off"></div><div id="guideSourceError" class="documents-layer-error"></div><div id="guideSourceResults" class="guide-source-list"><p class="documents-muted">Cargando...</p></div>`;
        $('guideSourceFooter').innerHTML=modalFooter('<button type="button" class="btn btn-outline documents-flow-close"><i data-lucide="x"></i><span>Cerrar</span></button>');
        setLayer('source');openModal();loadSources();
    }

    async function loadSources(){
        const results=$('guideSourceResults'),err=$('guideSourceError');if(!results)return;
        if(err){err.classList.remove('show');err.textContent='';}results.innerHTML='<p class="documents-muted">Cargando...</p>';
        const params=new URLSearchParams({source_type:state.sourceType,search:$('guideSourceSearch')?.value.trim()||'',environment:state.environment});
        try{const p=await jsonFetch('/modules/billing/dispatch_guide_sources_ajax.php?'+params);renderSources(p.rows||[]);}catch(e){results.innerHTML='';if(err){err.textContent=e.message;err.classList.add('show');}}
    }
    function renderSources(rows){
        const box=$('guideSourceResults');if(!rows.length){box.innerHTML='<p class="documents-muted">No se encontraron orígenes disponibles.</p>';return;}
        box.innerHTML=rows.map(r=>`<div class="guide-source-item"><div><strong>${esc(state.sourceType==='invoice'?'Factura '+r.number:'Cotización '+r.number)}</strong><div class="guide-source-meta"><span>${esc(r.customer||'-')}</span><span>${esc(r.tax_id||'-')}</span><span>${dateText(r.date)}</span><span>${money(r.total_amount)}</span>${r.status?`<span>${esc(r.status)}</span>`:''}</div></div><button type="button" class="btn btn-primary guide-use-source" data-source-type="${esc(r.source_type)}" data-source-id="${Number(r.id)}">Usar</button></div>`).join('');
    }

    async function chooseSource(type,id){
        state.sourceType=type;state.sourceId=Number(id);state.environment=$('documentsEnv')?.value||state.environment;
        $('guidePrepareBody').innerHTML='<p>Cargando origen...</p>';$('guidePrepareFooter').innerHTML='';setLayer('prepare');openModal();
        try{const p=await jsonFetch(`/modules/billing/dispatch_guide_source_ajax.php?source_type=${encodeURIComponent(type)}&source_id=${encodeURIComponent(id)}&environment=${encodeURIComponent(state.environment)}`);state.source=p.source;renderPrepare();}
        catch(e){$('guidePrepareBody').innerHTML=`<div class="documents-layer-error show">${esc(e.message)}</div>`;$('guidePrepareFooter').innerHTML=modalFooter('<button class="btn btn-outline" data-guide-back="source"><i data-lucide="arrow-left"></i><span>Volver</span></button>');}
    }

    function renderPrepare(){
        const s=state.source,c=s.customer||{};
        $('guidePrepareTitle').textContent='Preparar guía de despacho';
        $('guidePrepareSubtitle').textContent=`${s.type==='invoice'?'Factura':'Cotización'} ${s.number} · ${c.legal_name||'-'}`;
        const lines=(s.lines||[]).map((l,i)=>{const available=Number(l.available_quantity??l.source_quantity??0),disabled=available<=0;return `<tr><td><input type="checkbox" class="guide-line-enabled" data-index="${i}" ${disabled?'disabled':'checked'}></td><td>${esc(l.sku||'-')}</td><td><strong>${esc(l.description)}</strong><div class="documents-muted">${esc(l.long_description||'')}</div></td><td>${esc(l.original_quantity??l.source_quantity)}</td><td>${esc(l.dispatched_quantity??0)}</td><td><strong>${esc(available)}</strong></td><td><input class="documents-input guide-line-qty" type="number" min="0" max="${esc(available)}" step="0.0001" value="${esc(available)}" data-index="${i}" ${disabled?'disabled':''}></td><td>${esc(l.unit_measure||'UN')}</td><td>${money(l.unit_price)}</td></tr>`;}).join('');
        $('guidePrepareBody').innerHTML=`${steps('prepare')}<div id="guidePrepareError" class="documents-layer-error"></div><div class="documents-grid crm-ui-form-grid"><div class="documents-section crm-ui-section"><h3>Origen</h3><p><strong>${esc(s.type==='invoice'?'Factura':'Cotización')}:</strong> ${esc(s.number)}</p><p><strong>Cliente:</strong> ${esc(c.legal_name||'-')}</p><p><strong>RUT:</strong> ${esc(c.tax_id||'-')}</p></div><div class="documents-section crm-ui-section"><h3>Regla operativa</h3><p>Las cantidades pueden ser parciales, pero no superar el documento de origen.</p><p>Esta fase no descuenta stock automáticamente.</p></div></div><div class="documents-grid crm-ui-form-grid"><div class="documents-field crm-ui-field"><label>Fecha emisión</label><input id="guideIssueDate" type="date" value="${today()}"></div><div class="documents-field crm-ui-field"><label>Tipo de guía</label><select id="guideType">${guideTypeOptions()}</select></div><div class="documents-field crm-ui-field" id="guideTransferTypeField"><label>Tipo de traslado</label><select id="guideTransferType">${transferTypeOptions()}</select></div><div class="documents-field crm-ui-field"><label>Dirección destino</label><input id="guideAddress" value="${esc(c.address||'')}"></div><div class="documents-field crm-ui-field"><label>Comuna destino</label><input id="guideDistrict" value="${esc(c.district||'')}"></div><div class="documents-field crm-ui-field"><label>Ciudad destino</label><input id="guideCity" value="${esc(c.city||'')}"></div></div><div class="documents-field crm-ui-field"><label>Observaciones</label><textarea id="guideObservations" maxlength="220" placeholder="Datos de despacho o indicaciones internas"></textarea></div><div class="documents-section crm-ui-section"><h3>Detalle a despachar</h3><div class="documents-scroll-table crm-ui-inner-table-wrap"><table class="guide-lines-table"><thead><tr><th></th><th>SKU</th><th>Producto</th><th>Origen</th><th>Ya despachado</th><th>Disponible</th><th>Despachar</th><th>Unidad</th><th>Prc. unit.</th></tr></thead><tbody>${lines}</tbody></table></div></div>`;
        $('guidePrepareFooter').innerHTML=modalFooter('<button type="button" class="btn btn-primary" id="previewDispatchGuideBtn"><i data-lucide="eye"></i><span>Previsualizar</span></button>');
        syncTransferField();icons();
    }

    function syncTransferField(){const type=Number($('guideType')?.value||1),field=$('guideTransferTypeField');if(field)field.style.display=type===5?'none':'flex';}
    function selectedLines(){const source=state.source?.lines||[];const out=[];document.querySelectorAll('.guide-line-enabled').forEach(cb=>{if(!cb.checked)return;const i=Number(cb.dataset.index),qty=Number(document.querySelector(`.guide-line-qty[data-index="${i}"]`)?.value||0);if(source[i]&&qty>0)out.push({source_line_id:source[i].source_line_id,quantity:qty});});return out;}

    async function previewGuide(){
        const btn=$('previewDispatchGuideBtn'),err=$('guidePrepareError');if(btn)btn.disabled=true;if(err){err.textContent='';err.classList.remove('show');}
        const form=new URLSearchParams({environment:state.environment,source_type:state.sourceType,source_id:String(state.sourceId),issue_date:$('guideIssueDate').value,guide_type:$('guideType').value,transfer_type:$('guideTransferType')?.value||'',dispatch_address:$('guideAddress').value.trim(),dispatch_district:$('guideDistrict').value.trim(),dispatch_city:$('guideCity').value.trim(),observations:$('guideObservations').value.trim(),lines_json:JSON.stringify(selectedLines())});
        try{const p=await jsonFetch('/modules/billing/dispatch_guide_preview_ajax.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'},body:form});state.preview=p.data;state.guideId=Number(p.data.guide_id);renderPreview(p.data);}catch(e){if(err){err.textContent=e.message;err.classList.add('show');}}finally{if(btn)btn.disabled=false;}
    }

    function renderPreview(d){
        $('guidePreviewTitle').textContent=`Preview guía FACTO ${state.environment}`;$('guidePreviewSubtitle').textContent=`Origen ${d.source.number} · ${d.source.customer}`;
        $('guidePreviewBody').innerHTML=`${steps('preview')}<div class="guide-preview-note"><strong>VISTA PREVIA — NO VÁLIDA TRIBUTARIAMENTE.</strong> No se envía al SII, no modifica stock y no genera cuentas por cobrar.</div><div class="documents-success"><strong>Preview verificable.</strong> FACTO devolvió document_id temporal y PDF.</div><div class="documents-summary crm-ui-summary-grid"><div class="crm-ui-summary-card"><span>Líneas</span><strong>${Number(d.line_count)}</strong></div><div class="crm-ui-summary-card"><span>Total referencial</span><strong>${money(d.amounts.total_amount)}</strong></div><div class="crm-ui-summary-card"><span>Tipo</span><strong>${esc(d.guide_type_label)}</strong></div></div><div class="documents-grid crm-ui-form-grid"><div class="documents-section crm-ui-section"><h3>Traslado</h3><p><strong>Modalidad:</strong> ${esc(d.transfer_type_label)}</p><p><strong>Destino:</strong> ${esc(d.destination.address)}</p><p>${esc(d.destination.district)} · ${esc(d.destination.city)}</p></div><div class="documents-section crm-ui-section"><h3>Preview FACTO</h3><p><strong>document_id temporal:</strong> ${esc(d.preview.document_id)}</p><p><strong>Referencia temporal:</strong> ${esc(d.preview.document_number||'-')}</p><p><strong>PDF:</strong> ${d.preview.pdf_available?'Disponible':'No disponible'}</p></div></div>${d.preview.pdf_available?`<h3>PDF preliminar</h3><iframe class="documents-preview-frame" src="/modules/billing/dispatch_guide_file.php?guide_id=${Number(d.guide_id)}&kind=pdf&stage=preview"></iframe>`:''}`;
        $('guidePreviewFooter').innerHTML=modalFooter('<button type="button" class="btn btn-primary" id="continueDispatchGuideBtn"><i data-lucide="arrow-right"></i><span>Continuar</span></button>');setLayer('preview');
    }

    function renderConfirm(){
        const d=state.preview;$('guideConfirmTitle').textContent=`Confirmar emisión ${state.environment}`;$('guideConfirmSubtitle').textContent=`Guía desde ${d.source.number}`;
        $('guideConfirmBody').innerHTML=`${steps('confirm')}<div id="guideConfirmError" class="documents-layer-error"></div><div class="documents-warning"><strong>Operación tributaria irreversible.</strong> Se emitirá una guía definitiva en FACTO ${esc(state.environment)}. No se aplicará efecto de stock en esta fase.</div><div class="documents-summary crm-ui-summary-grid"><div class="crm-ui-summary-card"><span>Origen</span><strong>${esc(d.source.number)}</strong></div><div class="crm-ui-summary-card"><span>Líneas</span><strong>${Number(d.line_count)}</strong></div><div class="crm-ui-summary-card"><span>Total</span><strong>${money(d.amounts.total_amount)}</strong></div></div><div class="documents-field crm-ui-field"><label>Confirmación</label><input id="guideIssueConfirmation" autocomplete="off" placeholder="Escribe ${state.environment==='production'?'EMITIR PRODUCCION':'EMITIR'}"></div>`;
        $('guideConfirmFooter').innerHTML=modalFooter('<button type="button" class="btn btn-danger" id="issueDispatchGuideBtn" disabled><i data-lucide="triangle-alert"></i><span>Confirmar guía</span></button>');setLayer('confirm');
    }

    async function issueGuide(){
        const btn=$('issueDispatchGuideBtn'),err=$('guideConfirmError');if(btn)btn.disabled=true;if(err){err.textContent='';err.classList.remove('show');}
        const form=new URLSearchParams({guide_id:String(state.guideId),confirmation:$('guideIssueConfirmation').value});
        try{const p=await jsonFetch('/modules/billing/dispatch_guide_issue_ajax.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'},body:form});renderResult(p.data);$('reloadDocumentsBtn')?.click();}catch(e){if(err){err.textContent=e.message;err.classList.add('show');}if(btn)btn.disabled=false;}
    }

    function renderResult(d){
        $('guideResultTitle').textContent=d.status==='issued'?'Guía emitida':'Resultado guía';$('guideResultSubtitle').textContent=d.document_number?`Folio ${d.document_number}`:`Origen ${d.source_number||''}`;
        $('guideResultBody').innerHTML=`${steps('result')}<div class="${d.status==='issued'?'documents-success':'documents-warning'}"><strong>${d.status==='issued'?'Guía emitida y registrada correctamente.':'La guía requiere revisión.'}</strong></div><div class="documents-summary crm-ui-summary-grid"><div class="crm-ui-summary-card"><span>Estado</span><strong>${esc(d.status)}</strong></div><div class="crm-ui-summary-card"><span>FACTO document_id</span><strong>${esc(d.facto_document_id||'-')}</strong></div><div class="crm-ui-summary-card"><span>Folio definitivo</span><strong>${esc(d.document_number||'-')}</strong></div></div><div class="documents-file-actions">${d.pdf_available?`<a class="btn btn-secondary" target="_blank" href="/modules/billing/dispatch_guide_file.php?guide_id=${Number(d.guide_id)}&kind=pdf&stage=issued">Ver PDF</a>`:''}${d.xml_available?`<a class="btn btn-secondary" href="/modules/billing/dispatch_guide_file.php?guide_id=${Number(d.guide_id)}&kind=xml&stage=issued">Descargar XML</a>`:''}${d.transfer_copy_pdf_available?`<a class="btn btn-secondary" target="_blank" href="/modules/billing/dispatch_guide_file.php?guide_id=${Number(d.guide_id)}&kind=transfer_pdf&stage=issued">Ver copia cedible</a>`:''}</div>${d.error_message?`<div class="documents-layer-error show">${esc(d.error_message)}</div>`:''}`;
        $('guideResultFooter').innerHTML=modalFooter('<button type="button" class="btn btn-primary" data-guide-back="close"><i data-lucide="arrow-left"></i><span>Volver a documentos</span></button>');setLayer('result');
    }


    async function repairGuide(id){
        if(!confirm('¿Reintentar únicamente el cierre local de esta guía ya identificada en FACTO?'))return;
        const form=new URLSearchParams({guide_id:String(id)});
        try{await jsonFetch('/modules/billing/dispatch_guide_repair_ajax.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'},body:form});alert('Cierre local reparado.');$('reloadDocumentsBtn')?.click();if(document.querySelector('.documents-modal-layer.active')?.id==='documentLayerDetail'){const current=document.querySelector('.create-dispatch-guide-btn')?.dataset.sourceId;if(current)document.querySelector(`.document-open-btn[data-id="${current}"]`)?.click();}}catch(e){alert(e.message);}
    }

    function prefillFromQuery(){const q=new URLSearchParams(location.search);if(q.get('new_guide')==='1'){const type=q.get('source_type')||'quote',id=Number(q.get('source_id')||0);setTimeout(()=>{if(id>0)chooseSource(type,id);else openSourceSelector(type);},150);}}

    on(document, 'click',e=>{
        const tab=e.target.closest('[data-source-tab]');if(tab){state.sourceType=tab.dataset.sourceTab;document.querySelectorAll('.guide-source-tab').forEach(x=>x.classList.toggle('active',x===tab));loadSources();return;}
        const use=e.target.closest('.guide-use-source');if(use){chooseSource(use.dataset.sourceType,use.dataset.sourceId);return;}
        const create=e.target.closest('.create-dispatch-guide-btn');if(create){chooseSource(create.dataset.sourceType,create.dataset.sourceId);return;}
        if(e.target.closest('#newDispatchGuideBtn')){openSourceSelector('quote');return;}
        if(e.target.closest('#previewDispatchGuideBtn')){previewGuide();return;}
        if(e.target.closest('#continueDispatchGuideBtn')){renderConfirm();return;}
        if(e.target.closest('#issueDispatchGuideBtn')){issueGuide();return;}
        const repair=e.target.closest('.repair-dispatch-guide-btn');if(repair){repairGuide(repair.dataset.guideId);return;}
        const back=e.target.closest('[data-guide-back]');if(back){const target=back.dataset.guideBack;if(target==='source')openSourceSelector(state.sourceType);else if(target==='prepare')renderPrepare();else if(target==='preview')renderPreview(state.preview);else if(target==='close'){closeModal();$('reloadDocumentsBtn')?.click();}return;}
    });
    on(document, 'input',e=>{if(e.target?.id==='guideSourceSearch'){clearTimeout(state.searchTimer);state.searchTimer=setTimeout(loadSources,250);}if(e.target?.id==='guideIssueConfirmation'){const b=$('issueDispatchGuideBtn');if(b)b.disabled=e.target.value.trim().toUpperCase()!==(state.environment==='production'?'EMITIR PRODUCCION':'EMITIR');}});
    on(document, 'change',e=>{if(e.target?.id==='documentsEnv')syncGuideAvailability();if(e.target?.id==='guideType')syncTransferField();if(e.target?.classList?.contains('guide-line-enabled')){const i=e.target.dataset.index,q=document.querySelector(`.guide-line-qty[data-index="${i}"]`);if(q)q.disabled=!e.target.checked;}});
    syncGuideAvailability();prefillFromQuery();icons();
})();
