import './bootstrap';
import Alpine from 'alpinejs';
import * as bootstrap from 'bootstrap';
import { createIcons, icons } from 'lucide';
import Swal from 'sweetalert2';
import 'sweetalert2/dist/sweetalert2.min.css';

window.bootstrap = bootstrap;
const blank = () => ({
    application_date:'', payment_amount:'', receipt_number:'', first_payment_date:'',
    full_name:'', rut:'', birth_date:'', email:'', address:'', phone:'', delivery_address:'', profession:'', company:'', job_title:'', work_area:'',
    superintendency:'', work_phone:'', management:'', work_email:'', recommender_name:'', recommender_rut:'', recommender_signature:'',
    signature_date:'', dependents:[{id:crypto.randomUUID(),full_name:'',rut:'',birth_date:'',relationship:''}],
    board_members:[]
});

Alpine.data('applicationDetail', () => ({
    previewModal:null, attachmentModal:null, attachmentUrl:'', attachmentDownloadUrl:'', attachmentName:'',
    openPreview(){
        this.previewModal ||= bootstrap.Modal.getOrCreateInstance(document.getElementById('applicationPreviewModal'));
        this.previewModal.show();
        this.$nextTick(()=>createIcons({icons}));
    },
    openAttachment(previewUrl,downloadUrl,name){
        this.attachmentUrl=previewUrl;
        this.attachmentDownloadUrl=downloadUrl;
        this.attachmentName=name;
        this.attachmentModal ||= bootstrap.Modal.getOrCreateInstance(document.getElementById('attachmentPreviewModal'));
        this.attachmentModal.show();
        this.$nextTick(()=>createIcons({icons}));
    }
}));

Alpine.data('collapsibleSection', () => ({
    open: true,
    progress: 0,
    observer: null,
    init(){
        this.$nextTick(()=>this.updateProgress());
        this.observer=new MutationObserver(()=>this.$nextTick(()=>this.updateProgress()));
        this.observer.observe(this.$refs.content,{childList:true,subtree:true});
    },
    updateProgress(){
        const fields=[...this.$refs.content.querySelectorAll('input:not([type="button"]):not([type="submit"]),select,textarea')]
            .filter(field=>!field.disabled&&field.type!=='hidden');
        if(!fields.length){this.progress=100;return;}
        const completed=fields.filter(field=>field.type==='file'?field.files?.length:String(field.value||'').trim()!=='').length;
        this.progress=Math.round(completed/fields.length*100);
    },
    toggle(){this.open=!this.open;this.$nextTick(()=>createIcons({icons}));}
}));

Alpine.data('applicationForm', () => ({
    type: '', form: blank(), errors:{}, files:{identity_front:null,identity_back:null,family_document:null}, signatureData:'', signaturePresent:false,
    submitting:false, authorizationUrl:'', authorizationDownloadUrl:'', authorizationModal:null, toastMessage:'', canvas:null, ctx:null, drawing:false,
    attachmentTypes:[{key:'identity_front',label:'Cédula de identidad · anverso'},{key:'identity_back',label:'Cédula de identidad · reverso'},{key:'family_document',label:'Documento de cargas familiares'}],
    init(){ this.$watch('form',()=>this.saveDraft(false),{deep:true}); this.$nextTick(()=>createIcons({icons})); },
    selectType(type){ this.type=type; const saved=localStorage.getItem(`ccr-draft-${type}`); this.form=saved ? {...blank(),...JSON.parse(saved)} : blank(); this.$nextTick(()=>{this.setupCanvas();createIcons({icons});window.scrollTo(0,0);}); },
    goHome(){ this.type=''; this.errors={}; this.$nextTick(()=>createIcons({icons})); },
    fieldChanged(name){ delete this.errors[name]; if(name.toLowerCase().includes('rut')){this.form[name]=this.formatRut(this.form[name]);this.validateRutField(name,this.form[name]);} if(name==='payment_amount') this.form.payment_amount=this.money(this.form.payment_amount); },
    formatRut(value=''){ let v=String(value).replace(/[^0-9kK]/g,'').toUpperCase().slice(0,9); if(v.length<2)return v; return `${Number(v.slice(0,-1)).toLocaleString('es-CL')}-${v.slice(-1)}`; },
    validateRutField(key,value){const clean=String(value).replace(/[^0-9kK]/g,'');delete this.errors[key];if(clean.length>=8&&!this.validRut(value))this.errors[key]='Ingresa un RUT chileno válido.';},
    validRut(rut){ const clean=rut.replace(/\./g,'').replace('-','').toUpperCase(); if(clean.length<8)return false; let sum=0,m=2; for(let i=clean.length-2;i>=0;i--){sum+=Number(clean[i])*m;m=m===7?2:m+1;} const d=11-(sum%11), expected=d===11?'0':d===10?'K':String(d); return expected===clean.slice(-1); },
    money(v){ const n=String(v).replace(/\D/g,''); return n ? '$ '+Number(n).toLocaleString('es-CL') : ''; },
    addDependent(){this.form.dependents.push({id:crypto.randomUUID(),full_name:'',rut:'',birth_date:'',relationship:''});this.refreshIcons();this.animateLatest('.dynamic-dependent');},
    async removeDependent(i){const result=await Swal.fire({title:'¿Eliminar esta carga?',text:'Los datos ingresados en esta fila se perderán.',icon:'warning',showCancelButton:true,confirmButtonText:'Sí, eliminar',cancelButtonText:'Cancelar',confirmButtonColor:'#a84f2a',reverseButtons:true});if(result.isConfirmed)this.form.dependents.splice(i,1);},
    addBoardMember(){this.form.board_members.push({id:crypto.randomUUID(),name:'',rut:'',signature:''});this.refreshIcons();this.animateLatest('.dynamic-card');},
    async removeBoardMember(i){const result=await Swal.fire({title:'¿Eliminar este integrante?',text:'La información y la firma de esta fila se perderán.',icon:'warning',showCancelButton:true,confirmButtonText:'Sí, eliminar',cancelButtonText:'Cancelar',confirmButtonColor:'#a84f2a',reverseButtons:true});if(result.isConfirmed)this.form.board_members.splice(i,1);},
    animateLatest(selector){this.$nextTick(()=>{const items=document.querySelectorAll(selector),el=items[items.length-1];el?.classList.add('dynamic-enter');setTimeout(()=>el?.classList.remove('dynamic-enter'),550);el?.scrollIntoView({behavior:'smooth',block:'center'});});},
    refreshIcons(){this.$nextTick(()=>createIcons({icons}));},
    setupCanvas(){ const c=document.querySelector('.signature-canvas');if(!c)return; this.canvas=c; const resize=()=>{const old=this.signatureData;c.width=c.offsetWidth*devicePixelRatio;c.height=180*devicePixelRatio;this.ctx=c.getContext('2d');this.ctx.scale(devicePixelRatio,devicePixelRatio);this.ctx.lineWidth=2;this.ctx.lineCap='round';this.ctx.strokeStyle='#3c2b23';if(old)this.drawImage(old);};resize();
        const point=e=>{const r=c.getBoundingClientRect(),p=e.touches?.[0]||e;return [p.clientX-r.left,p.clientY-r.top]};
        const start=e=>{e.preventDefault();this.drawing=true;this.ctx.beginPath();this.ctx.moveTo(...point(e))}; const move=e=>{if(!this.drawing)return;e.preventDefault();this.ctx.lineTo(...point(e));this.ctx.stroke();this.signaturePresent=true}; const end=()=>{if(this.drawing){this.drawing=false;this.signatureData=c.toDataURL('image/png');this.saveDraft(false)}};
        c.addEventListener('mousedown',start);c.addEventListener('mousemove',move);window.addEventListener('mouseup',end);c.addEventListener('touchstart',start,{passive:false});c.addEventListener('touchmove',move,{passive:false});c.addEventListener('touchend',end);
    },
    drawImage(src){const img=new Image();img.onload=()=>this.ctx.drawImage(img,0,0,this.canvas.offsetWidth,180);img.src=src;},
    clearSignature(){this.ctx?.clearRect(0,0,this.canvas.width,this.canvas.height);this.signatureData='';this.signaturePresent=false;},
    uploadSignature(e){const f=e.target.files[0];if(!f)return;const r=new FileReader();r.onload=()=>{this.clearSignature();this.signatureData=r.result;this.signaturePresent=true;this.drawImage(r.result)};r.readAsDataURL(f);},
    loadSimpleSignature(e,key){const f=e.target.files[0];if(!f)return;const r=new FileReader();r.onload=()=>this.form[key]=r.result;r.readAsDataURL(f);},
    loadBoardSignature(e,i){const f=e.target.files[0];if(!f)return;const r=new FileReader();r.onload=()=>this.form.board_members[i].signature=r.result;r.readAsDataURL(f);},
    setFile(e,key){const f=e.target.files[0];if(!f)return;if(f.size>5*1024*1024){this.notify('El archivo supera el límite de 5 MB.','warning');e.target.value='';return;}this.files[key]=f;this.notify('Archivo adjuntado correctamente.');},
    formatBytes(b){return b<1048576?`${(b/1024).toFixed(0)} KB`:`${(b/1048576).toFixed(1)} MB`;},
    saveDraft(show){ if(!this.type)return;const data={...this.form};localStorage.setItem(`ccr-draft-${this.type}`,JSON.stringify(data));if(show)this.notify('Borrador guardado en este dispositivo.');},
    async clearForm(){const result=await Swal.fire({title:'¿Limpiar el formulario?',text:'Se eliminarán todos los datos y el borrador guardado en este dispositivo.',icon:'warning',showCancelButton:true,confirmButtonText:'Sí, limpiar',cancelButtonText:'Conservar datos',confirmButtonColor:'#a84f2a',reverseButtons:true,focusCancel:true});if(!result.isConfirmed)return;localStorage.removeItem(`ccr-draft-${this.type}`);this.form=blank();this.files={identity_front:null,identity_back:null,family_document:null};this.clearSignature();this.errors={};await Swal.fire({title:'Formulario limpio',text:'Puedes comenzar una nueva solicitud.',icon:'success',confirmButtonColor:'#a84f2a',timer:1800,timerProgressBar:true});},
    validate(){const e={}, f=this.form, req=['full_name','rut','birth_date','email','address','phone','signature_date'];if(this.type!=='particular')req.push('delivery_address');req.forEach(k=>{if(!f[k])e[k]='Este campo es obligatorio.'});if(f.rut&&!this.validRut(f.rut))e.rut='Ingresa un RUT chileno válido.';if(f.email&&!/^\S+@\S+\.\S+$/.test(f.email))e.email='Ingresa un correo válido.';if(f.phone&&!/^\+?[0-9\s-]{8,16}$/.test(f.phone))e.phone='Ingresa un teléfono válido.';if(!this.files.identity_front)e.identity_front='Debes adjuntar el anverso de tu cédula.';if(!this.files.identity_back)e.identity_back='Debes adjuntar el reverso de tu cédula.';if(['particular','radomiro'].includes(this.type)&&!this.files.family_document)e.family_document='Debes adjuntar el documento de cargas familiares.';f.dependents.forEach((d,i)=>{if(!d.full_name||!d.rut||!d.birth_date||!d.relationship)e[`dependent_${i}`]=`Completa todos los datos de la carga familiar ${i+1}.`;if(d.rut&&!this.validRut(d.rut))e[`dependent_rut_${i}`]='Ingresa un RUT chileno válido.';});if(f.recommender_rut&&!this.validRut(f.recommender_rut))e.recommender_rut='Ingresa un RUT chileno válido.';if(!this.signaturePresent)e.signature='La firma del socio es obligatoria.';this.errors=e;if(Object.keys(e).length){this.notify('Revisa los campos marcados antes de continuar.');const el=document.querySelector('.is-invalid,.field-error:not(:empty)');el?.scrollIntoView({behavior:'smooth',block:'center'});}return !Object.keys(e).length;},
    async submitApplication(){if(!this.validate())return;if(['radomiro','gabriela'].includes(this.type)){await this.reviewPayrollAuthorization();return;}await this.sendApplication();},
    async reviewPayrollAuthorization(){this.submitting=true;try{const res=await fetch(`/solicitudes/autorizacion-${this.type}/vista-previa`,{method:'POST',headers:{'X-CSRF-TOKEN':document.querySelector('meta[name=csrf-token]').content,'Content-Type':'application/json','Accept':'application/pdf'},body:JSON.stringify({type:this.type,data:{...this.form,signature:this.signatureData}})});if(!res.ok)throw new Error('No fue posible generar la autorización.');const blob=await res.blob();if(this.authorizationUrl)URL.revokeObjectURL(this.authorizationUrl);this.authorizationUrl=URL.createObjectURL(blob);this.authorizationModal ||= bootstrap.Modal.getOrCreateInstance(document.getElementById('payrollAuthorizationModal'));this.authorizationModal.show();}catch(e){this.notify(e.message,'error');}finally{this.submitting=false;}},
    async sendApplication(){this.submitting=true;Swal.fire({title:'Enviando solicitud',text:'Estamos guardando tus antecedentes.',allowOutsideClick:false,showConfirmButton:false,didOpen:()=>Swal.showLoading()});try{const fd=new FormData();fd.append('type',this.type);['full_name','rut','birth_date','email','phone','application_date'].forEach(k=>fd.append(k,this.form[k]));fd.append('data',JSON.stringify({...this.form,signature:this.signatureData}));Object.entries(this.files).filter(([,file])=>file).forEach(([key,file])=>fd.append(`files[${key}]`,file));const res=await fetch('/solicitudes',{method:'POST',headers:{'X-CSRF-TOKEN':document.querySelector('meta[name=csrf-token]').content,'Accept':'application/json'},body:fd});const json=await res.json();if(!res.ok)throw new Error(json.message||Object.values(json.errors||{})[0]?.[0]||'No fue posible enviar la solicitud.');localStorage.removeItem(`ccr-draft-${this.type}`);this.authorizationModal?.hide();await Swal.fire({title:'¡Solicitud recibida!',html:`Tu folio de seguimiento es:<br><strong class="swal-folio">${json.folio}</strong>`,icon:'success',confirmButtonText:'Finalizar',confirmButtonColor:'#a84f2a'});this.goHome();}catch(e){Swal.fire({title:'No pudimos enviar la solicitud',text:e.message,icon:'error',confirmButtonText:'Revisar',confirmButtonColor:'#a84f2a'});}finally{this.submitting=false;}},
    get previewSections(){const f=this.form,personal=[['Nombre completo',f.full_name],['RUT',f.rut],['Fecha de nacimiento',this.formatDate(f.birth_date)],['Correo electrónico',f.email],['Dirección',f.address],['Teléfono',f.phone]];if(this.type!=='particular')personal.push(['Dirección de entrega',f.delivery_address]);const work=this.type==='particular'?[['Profesión',f.profession],['Empresa',f.company],['Cargo',f.job_title],['Teléfono laboral',f.work_phone],['Correo laboral',f.work_email]]:[['Profesión',f.profession],['Área de trabajo',f.work_area],['Superintendencia',f.superintendency],['Teléfono laboral',f.work_phone],['Gerencia',f.management],['Correo laboral',f.work_email]];return [{title:'Datos personales',rows:personal},{title:'Datos laborales',rows:work},{title:'Recomendación de socio',rows:[['Nombre',f.recommender_name],['RUT',f.recommender_rut]]},{title:'Firma y fecha',rows:[['Calama, con fecha de',this.formatDate(f.signature_date)]]}];},
    formatDate(v){if(!v)return '—';const [y,m,d]=v.split('-');return `${d} / ${m} / ${y}`;},
    notify(message,icon='success'){Swal.fire({toast:true,position:'top-end',icon,title:message,showConfirmButton:false,timer:2600,timerProgressBar:true});}
}));

window.Alpine=Alpine;Alpine.start();document.addEventListener('DOMContentLoaded',()=>{
    createIcons({icons});
    if(document.body.classList.contains('admin-body')){
        const keepSessionAlive=()=>fetch('/session/keep-alive',{method:'POST',headers:{'X-CSRF-TOKEN':document.querySelector('meta[name=csrf-token]').content,'Accept':'application/json'},credentials:'same-origin'}).catch(()=>{});
        window.setInterval(keepSessionAlive,10*60*1000);
        document.addEventListener('visibilitychange',()=>{if(!document.hidden)keepSessionAlive();});
    }
});
