(function() {
    'use strict';

    var messages = document.getElementById('mati-agent-messages');
    var footer = document.getElementById('mati-agent-footer');
    var typingEl = document.getElementById('mati-typing');
    var statusEl = document.getElementById('mati-status-text');
    var debugEl = document.getElementById('mati-debug');
    var servicesApp = document.getElementById('mati-services-app');
    var providersApp = document.getElementById('mati-providers-app');
    var scheduleApp = document.getElementById('mati-schedule-app');
    var widgetConfigForm = document.getElementById('mati-widget-config-form');

    // ═══════════════════════════════════════════════════════
    // WIDGET CONFIG PAGE — Preview en vivo, plantillas, etc.
    // ═══════════════════════════════════════════════════════
    if (widgetConfigForm) { initWidgetConfig(); return; }

    if (servicesApp) { initServicesManager(); return; }
    if (providersApp) { initProvidersManager(); return; }
    if (scheduleApp) { initScheduleManager(); return; }
    if (!messages || !footer) return;
    if (debugEl) debugEl.style.display = 'none';

    var userData = {}, historyStack = [], msgCount = 0, TYP_MIN = 500, TYP_MAX = 900;
    (function(){var e=document.getElementById('mati-particles');if(!e)return;var c=['#1A5D4A','#0D9488','#2D8A6E','#FF6B5B','#F59E0B','#8B5CF6','#EC4899','#3B82F6'];for(var i=0;i<40;i++){var p=document.createElement('div');p.className='mati-particle';p.style.left=Math.random()*100+'%';p.style.background=c[Math.floor(Math.random()*c.length)];var s=3+Math.random()*7;p.style.width=s+'px';p.style.height=s+'px';p.style.animationDuration=(5+Math.random()*10)+'s';p.style.animationDelay=Math.random()*6+'s';e.appendChild(p);}})();
    function sleep(ms){return new Promise(function(r){setTimeout(r,ms);});}
    function scroll(){var b=document.querySelector('.mati-agent-body');if(b)b.scrollTop=b.scrollHeight;}
    function addMsg(t,u,c){var d=document.createElement('div');d.className='mati-message '+(u?'mati-message-user':'mati-message-agent');if(c)d.classList.add('mati-message-'+c);d.innerHTML='<div class="mati-message-inner">'+t+'</div>';messages.appendChild(d);requestAnimationFrame(function(){d.classList.add('mati-message-visible');});msgCount++;scroll();return d;}
    function setFt(h){footer.innerHTML=h||'';scroll();}
    function getMc(){return messages.querySelectorAll('.mati-message').length;}
    function rmFrom(n){var a=messages.querySelectorAll('.mati-message');for(var i=a.length-1;i>=n;i--)a[i].remove();}
    function addInfo(){if(document.getElementById('mati-info-bar'))return;var b=document.createElement('div');b.id='mati-info-bar';b.className='mati-info-bar';b.innerHTML='💡 <strong>Podrás cambiar todo en cualquier momento</strong> desde el panel de Mati.';var c=document.getElementById('mati-agent');if(c)c.insertBefore(b,c.querySelector('.mati-agent-body'));}
    function showTyp(msg){if(statusEl)statusEl.textContent=msg||'Escribiendo...';if(typingEl)typingEl.style.display='flex';scroll();return sleep(TYP_MIN+Math.random()*(TYP_MAX-TYP_MIN));}
    function hideTyp(){if(typingEl)typingEl.style.display='none';if(statusEl)statusEl.textContent='Activo · En línea';}
    async function say(t,d){if(d)await sleep(d);await showTyp('Escribiendo...');hideTyp();addMsg(t,false);await sleep(250);}
    function addBack(step){var e=footer.querySelector('.mati-back-row');if(e)e.remove();var r=document.createElement('div');r.className='mati-back-row';var b=document.createElement('button');b.className='mati-back-btn';b.innerHTML='← Volver';b.addEventListener('click',function(){goBack(step);});r.appendChild(b);footer.insertBefore(r,footer.firstChild);}
    function goBack(s){var idx=-1;for(var i=historyStack.length-1;i>=0;i--){if(historyStack[i].step!==s){idx=i;break;}}if(idx<0){location.reload();return;}var sv=historyStack[idx];userData=JSON.parse(JSON.stringify(sv.userData));historyStack=historyStack.slice(0,idx+1);rmFrom(sv.messageCount);msgCount=sv.messageCount;reStep(sv.step,sv.userData);}
    function reStep(step,d){setFt('');switch(step){case'specialty':new Promise(function(r){renderChoiceCards(P[d.bizType]?P[d.bizType].specs:[],r);}).then(function(s){userData.specialty=s.label;saveState('specialty');contSpec(s);});break;case'name':new Promise(function(r){renderChatInput(P[d.bizType]?P[d.bizType].namePH:'',null,r);}).then(function(n){userData.name=n;saveState('name');contName(n);});break;case'color':new Promise(function(r){renderColor(r);}).then(function(c){userData.color=c;saveState('color');contColor(c);});break;case'services':new Promise(function(r){renderSvcEdit(d.services||[],r);}).then(function(s){userData.services=s;saveState('services');contSvc(s);});break;case'schedule':new Promise(function(r){renderTime(r);}).then(function(t){userData.schedule=t;saveState('schedule');contSched(t);});break;case'days':new Promise(function(r){renderDays(r);}).then(function(d){userData.days=d;saveState('days');contDays(d);});break;case'providers':new Promise(function(r){renderChatInput(P[d.bizType]?P[d.bizType].provPH:'',['1','2','3','5','10'],r);}).then(function(p){userData.providers=parseInt(p)||2;saveState('providers');contProv(userData.providers);});break;}}
    function saveState(s){historyStack.push({step:s,userData:JSON.parse(JSON.stringify(userData)),messageCount:msgCount});}

    function renderPills(o,cb){addBack('greeting');var h='<div class="mati-quick-actions mati-input-enter">';o.forEach(function(o,i){h+='<button class="mati-pill" style="animation-delay:'+(0.04*i)+'s">'+o.label+'</button>';});h+='</div>';setFt(h);setTimeout(function(){var p=footer.querySelectorAll('.mati-pill');p.forEach(function(b,i){b.addEventListener('click',function(){p.forEach(function(pp){pp.classList.add('selected');pp.disabled=true;});addMsg(o[i].label,true);cb(o[i].value,o[i].label);});});},100);}
    function renderChoiceCards(o,cb){addBack('specialty');var h='<div class="mati-choice-grid mati-input-enter">';o.forEach(function(o,i){h+='<button class="mati-choice-card" style="animation-delay:'+(0.05*i)+'s">'+(o.icon?'<span class="mati-choice-icon">'+o.icon+'</span>':'')+'<span class="mati-choice-label">'+o.label+'</span>'+(o.desc?'<span class="mati-choice-desc">'+o.desc+'</span>':'')+'</button>';});h+='</div>';setFt(h);setTimeout(function(){var c=footer.querySelectorAll('.mati-choice-card');c.forEach(function(cc,i){cc.addEventListener('click',function(){c.forEach(function(x){x.classList.add('selected');x.disabled=true;});addMsg(o[i].label,true);cb(o[i]);});});},100);}
    function renderChatInput(ph,sug,cb){var h='<div class="mati-chat-input-wrap mati-input-enter">';if(sug&&sug.length){h+='<div class="mati-chat-pills">';sug.forEach(function(s,i){h+='<button class="mati-chat-pill" style="animation-delay:'+(0.04*i)+'s">'+s+'</button>';});h+='</div>';}h+='<div class="mati-chat-input-row"><input type="text" class="mati-chat-input" placeholder="'+(ph||'Escribe...')+'" /><button class="mati-send-btn"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22,2 15,22 11,13 2,9"/></svg></button></div></div>';setFt(h);var inp=footer.querySelector('.mati-chat-input'),btn=footer.querySelector('.mati-send-btn');function send(){var v=inp.value.trim();if(!v)return;inp.disabled=true;btn.disabled=true;var p=footer.querySelectorAll('.mati-chat-pill');p.forEach(function(pp){pp.disabled=true;pp.style.opacity='0.4';});setFt('');addMsg(v,true);cb(v);}btn.addEventListener('click',send);inp.addEventListener('keydown',function(e){if(e.key==='Enter')send();});if(sug&&sug.length){footer.querySelectorAll('.mati-chat-pill').forEach(function(p){p.addEventListener('click',function(){inp.value=p.textContent;send();});});}setTimeout(function(){inp.focus();},500);}
    function renderColor(cb){addBack('color');var presets=['#1A5D4A','#0D6B5A','#2563EB','#0EA5E9','#0891B2','#6366F1','#8B5CF6','#7C3AED','#EC4899','#DB2777','#F59E0B','#D97706','#10B981','#059669','#14B8A6','#0D9488','#EF4444','#DC2626','#3B82F6','#84CC16','#65A30D','#F97316','#EA580C','#8B5A2B'];var h='<div class="mati-color-section mati-input-enter"><div class="mati-color-palette">';presets.forEach(function(c,i){h+='<button class="mati-color-dot" style="background:'+c+';animation-delay:'+(0.03*i)+'s"></button>';});h+='</div><div class="mati-color-custom"><div class="mati-color-custom-preview" id="mati-color-preview" style="background:'+(userData.color||'#1A5D4A')+'"></div><input type="text" class="mati-color-input" id="mati-color-input" placeholder="#1A5D4A" maxlength="7" /><button class="mati-btn mati-btn-primary" id="mati-color-apply">Aplicar</button></div></div>';setFt(h);function sel(c){document.querySelectorAll('.mati-color-dot').forEach(function(d){d.style.opacity=d.style.background.replace(/ /g,'')===c?'1':'0.25';d.style.transform=d.style.background.replace(/ /g,'')===c?'scale(1.3)':'scale(0.75)';});document.getElementById('mati-color-preview').style.background=c;document.getElementById('mati-color-input').value=c;addMsg('Color <span class="mati-inline-color" style="background:'+c+'"></span> '+c,true);setTimeout(function(){cb(c);},350);}document.querySelectorAll('.mati-color-dot').forEach(function(d){d.addEventListener('click',function(){sel(d.style.background);});});document.getElementById('mati-color-apply').addEventListener('click',function(){var c=document.getElementById('mati-color-input').value.trim();if(/^#[0-9A-Fa-f]{3,6}$/.test(c))sel(c.toUpperCase());});document.getElementById('mati-color-input').addEventListener('keydown',function(e){if(e.key==='Enter')document.getElementById('mati-color-apply').click();});}
    function renderSvcEdit(cur,cb){addBack('services');var s=cur&&cur.length?cur.slice():defSvc(userData.bizType);var h='<div class="mati-services-editor mati-input-enter"><div class="mati-services-edit-list" id="mati-svc-list">';s.forEach(function(s,i){h+='<div class="mati-svc-row" data-idx="'+i+'"><span class="mati-svc-num">'+(i+1)+'</span><input type="text" class="mati-svc-name" value="'+(s.name||'')+'" placeholder="Nombre" /><input type="number" class="mati-svc-dur" value="'+(s.duration||'30')+'" min="5" step="5" style="width:65px" /><span class="mati-svc-unit">min</span><button type="button" class="mati-svc-remove">×</button></div>';});h+='</div><button class="mati-svc-add" id="mati-svc-add">+ Agregar</button><button class="mati-btn mati-btn-primary mati-btn-lg" id="mati-svc-confirm" style="margin-top:0.75rem;width:100%">Confirmar →</button></div>';setFt(h);document.getElementById('mati-svc-add').addEventListener('click',function(){var l=document.getElementById('mati-svc-list');var i=l.children.length;var r=document.createElement('div');r.className='mati-svc-row';r.setAttribute('data-idx',i);r.innerHTML='<span class="mati-svc-num">'+(i+1)+'</span><input type="text" class="mati-svc-name" placeholder="Nombre" /><input type="number" class="mati-svc-dur" value="30" min="5" step="5" style="width:65px" /><span class="mati-svc-unit">min</span><button type="button" class="mati-svc-remove">×</button>';l.appendChild(r);r.querySelector('.mati-svc-remove').addEventListener('click',function(){r.remove();renum();});});document.querySelectorAll('.mati-svc-remove').forEach(function(b){b.addEventListener('click',function(){b.parentElement.remove();renum();});});document.getElementById('mati-svc-confirm').addEventListener('click',function(){var r=[];document.querySelectorAll('.mati-svc-row').forEach(function(rr){var n=rr.querySelector('.mati-svc-name').value.trim();if(n)r.push({name:n,duration:parseInt(rr.querySelector('.mati-svc-dur').value)||30});});if(!r.length)return;setFt('');addMsg(r.length+' servicios ✓',true);cb(r);});}
    function renum(){document.querySelectorAll('.mati-svc-row').forEach(function(r,i){r.querySelector('.mati-svc-num').textContent=i+1;});}
    function defSvc(t){var d={'Consultorio Médico':[{name:'Consulta General',duration:30},{name:'Consulta Especialidad',duration:45},{name:'Control',duration:20},{name:'Telemedicina',duration:30}],'Salón de Belleza':[{name:'Corte',duration:30},{name:'Coloración',duration:90},{name:'Manicura',duration:45}],'Gimnasio / Fitness':[{name:'Entrenamiento Personal',duration:60},{name:'Clase Grupal',duration:45},{name:'Evaluación Física',duration:30}],'Centro Educativo':[{name:'Clase Particular',duration:60},{name:'Taller Grupal',duration:90}],'Consultoría / Servicios':[{name:'Consultoría',duration:60},{name:'Mentoría',duration:45}],'Otro tipo de negocio':[{name:'Servicio 1',duration:30},{name:'Servicio 2',duration:45}]};return d[t]||[{name:'Servicio',duration:30}];}
    function renderTime(cb){addBack('schedule');var s=[{icon:'🌅',label:'08:00 - 16:00',desc:'Jornada diurna',start:'08:00',end:'16:00'},{icon:'🏢',label:'09:00 - 18:00',desc:'Comercial',start:'09:00',end:'18:00'},{icon:'☀️',label:'07:00 - 19:00',desc:'Jornada 12h',start:'07:00',end:'19:00'},{icon:'⚙️',label:'Personalizar',desc:'Horas exactas',start:'custom',end:'custom'}];var h='<div class="mati-time-grid mati-input-enter">';s.forEach(function(s,i){h+='<button class="mati-time-card" style="animation-delay:'+(0.06*i)+'s"><span class="mati-time-icon">'+s.icon+'</span><span class="mati-time-label">'+s.label+'</span><span class="mati-time-desc">'+s.desc+'</span></button>';});h+='</div>';setFt(h);setTimeout(function(){var c=footer.querySelectorAll('.mati-time-card');c.forEach(function(cc,i){cc.addEventListener('click',function(){c.forEach(function(x){x.classList.add('selected');x.disabled=true;});addMsg(s[i].label,true);cb(s[i]);});});},100);}
    function renderDays(cb){addBack('days');var d=['Lun','Mar','Mié','Jue','Vie','Sáb','Dom'];var h='<div class="mati-input-enter"><div class="mati-days-picker">';d.forEach(function(dd,i){h+='<button class="mati-day-chip" style="animation-delay:'+(0.05*i)+'s">'+dd+'</button>';});h+='</div><button class="mati-btn mati-btn-primary mati-btn-lg" style="margin-top:1rem" id="mati-days-confirm">Confirmar →</button></div>';setFt(h);var sel=[];setTimeout(function(){footer.querySelectorAll('.mati-day-chip').forEach(function(c,i){c.addEventListener('click',function(){c.classList.toggle('active');if(c.classList.contains('active'))sel.push(d[i]);else sel=sel.filter(function(x){return x!==d[i];});});});footer.querySelector('#mati-days-confirm').addEventListener('click',function(){if(!sel.length)return;footer.querySelectorAll('.mati-day-chip, #mati-days-confirm').forEach(function(x){x.disabled=true;x.style.opacity='0.5';});addMsg(sel.join(', '),true);cb(sel);});},100);}
    function renderCeleb(d){setFt('');addMsg('<div class="mati-celebration"><div class="mati-celebration-orb"><div class="mati-celebration-orb-ring"></div><div class="mati-celebration-orb-ring"></div><div class="mati-celebration-orb-ring"></div><div class="mati-celebration-orb-core">✨</div></div><p class="mati-celebration-title">¡Todo configurado!</p><p class="mati-celebration-detail">'+(d.services||5)+' servicios · '+d.providers+' profesionales · '+d.template+'</p><div class="mati-celebration-stats"><div class="mati-celebration-stat"><span class="mati-celebration-stat-value">'+(d.services||5)+'</span><span class="mati-celebration-stat-label">Servicios</span></div><div class="mati-celebration-stat"><span class="mati-celebration-stat-value">'+d.providers+'</span><span class="mati-celebration-stat-label">Profesionales</span></div><div class="mati-celebration-stat"><span class="mati-celebration-stat-value">64%</span><span class="mati-celebration-stat-label">Menos No-Shows</span></div></div></div>',false,'celebration');}

    var P={'Consultorio Médico':{icon:'🏥',template:'MediBook Pro',greeting:'¡Hola! Soy <strong>Mati</strong>. Veo que tienes un <strong>Consultorio Médico</strong>. Voy a configurar todo para que recibas pacientes en minutos.',specQ:'¿Cuál es tu <strong>especialidad médica</strong>?',specs:[{icon:'🏥',label:'Medicina General',desc:'Consultas y chequeos'},{icon:'🦷',label:'Odontología',desc:'Consultorio dental'},{icon:'👁️',label:'Oftalmología',desc:'Salud visual'},{icon:'🫀',label:'Cardiología',desc:'Salud cardiovascular'},{icon:'🧠',label:'Neurología',desc:'Sistema nervioso'},{icon:'🦴',label:'Traumatología',desc:'Lesiones y fracturas'},{icon:'👶',label:'Pediatría',desc:'Atención infantil'},{icon:'🧴',label:'Dermatología',desc:'Piel y estética'},{icon:'🩺',label:'Ginecología',desc:'Salud femenina'},{icon:'🧠',label:'Psicología',desc:'Salud mental'},{icon:'🩻',label:'Otra',desc:'La defino yo'}],afterSpec:function(s){return '¡<strong>'+s.label+'</strong>!';},nameQ:'¿Cómo se llama tu consultorio?',namePH:'Ej: Clínica Dental Sonrisa...',afterName:function(n){return '<strong>'+n+'</strong> — ¿Color? 🎨';},afterColor:'<span class="mati-inline-color" style="background:{c}"></span> perfecto.',servicesQ:'Configuremos tus <strong>servicios</strong>:',afterServices:function(n){return n+' servicios ✓';},scheduleQ:'¿Horario de atención?',daysQ:'¿Días?',afterDays:function(d){return d.join(', ')+'. ¿Profesionales?';},provPH:'Ej: 3',afterProv:function(n){return n+' profesional'+(n==1?'':'es')+' — ¡listo!';},buildSummary:function(d){return '<div class="mati-summary"><h3>📋 Configuración</h3><div class="mati-summary-grid"><div>🏥 <strong>'+d.specialty+'</strong></div><div>📛 <strong>'+d.name+'</strong></div><div>🎨 <span class="mati-inline-color" style="background:'+d.color+'"></span></div><div>📋 <strong>'+d.services+'</strong> servicios</div><div>🕐 <strong>'+d.schedule+'</strong></div><div>📅 <strong>'+d.days+'</strong></div><div>👥 <strong>'+d.providers+'</strong> profesionales</div></div></div>';}},'Salón de Belleza':{icon:'💇',template:'SalonFlow',greeting:'¡Hola! Soy <strong>Mati</strong>. Veo un <strong>Salón de Belleza</strong>. 💇',specQ:'¿Qué servicios ofreces?',specs:[{icon:'💇',label:'Peluquería'},{icon:'💅',label:'Manicura'},{icon:'🧖',label:'Estética Facial'},{icon:'💆',label:'Masajes'},{icon:'✨',label:'Completo'}],afterSpec:function(s){return '¡'+s.label+'!';},nameQ:'¿Nombre del salón?',namePH:'Ej: Beauty Studio...',afterName:function(n){return '<strong>'+n+'</strong> — ¿Color? 🎨';},afterColor:'¡Personalidad!',servicesQ:'Tus <strong>servicios</strong>:',afterServices:function(n){return n+' servicios ✓';},scheduleQ:'¿Horario?',daysQ:'¿Días?',afterDays:function(d){return d.join(', ')+'. ¿Profesionales?';},provPH:'Ej: 4',afterProv:function(n){return n+' profesional'+(n==1?'':'es')+' — ¡listo!';}},'Gimnasio / Fitness':{icon:'💪',template:'FitSchedule',greeting:'¡Hola! Soy <strong>Mati</strong>. Veo un <strong>Gimnasio</strong>. 💪',specQ:'¿Tipo de entrenamiento?',specs:[{icon:'🏋️',label:'Personal'},{icon:'🧘',label:'Yoga/Pilates'},{icon:'🔥',label:'HIIT'},{icon:'💪',label:'Completo'}],afterSpec:function(s){return '¡'+s.label+'!';},nameQ:'¿Nombre?',namePH:'Ej: PowerFit...',afterName:function(n){return '<strong>'+n+'</strong> — ¿Color? 🎨';},afterColor:'¡Energía!',servicesQ:'Tus <strong>clases</strong>:',afterServices:function(n){return n+' clases ✓';},scheduleQ:'¿Horario?',daysQ:'¿Días?',afterDays:function(d){return d.join(', ')+'. ¿Entrenadores?';},provPH:'Ej: 5',afterProv:function(n){return n+' entrenador'+(n==1?'':'es')+' — ¡equipo!';}},'Centro Educativo':{icon:'📚',template:'EduPlan',greeting:'¡Hola! Soy <strong>Mati</strong>. Veo un <strong>Centro Educativo</strong>. 📚',specQ:'¿Tipo de educación?',specs:[{icon:'🗣️',label:'Idiomas'},{icon:'🎹',label:'Música/Arte'},{icon:'💻',label:'Tecnología'},{icon:'🎓',label:'Formación'}],afterSpec:function(s){return '¡'+s.label+'!';},nameQ:'¿Nombre?',namePH:'Ej: Instituto Cambridge...',afterName:function(n){return '<strong>'+n+'</strong> — ¿Color? 🎨';},afterColor:'Representativo.',servicesQ:'Tus <strong>clases</strong>:',afterServices:function(n){return n+' clases ✓';},scheduleQ:'¿Horario?',daysQ:'¿Días?',afterDays:function(d){return d.join(', ')+'. ¿Docentes?';},provPH:'Ej: 8',afterProv:function(n){return n+' docente'+(n==1?'':'s')+' — ¡equipo!';}},'Consultoría / Servicios':{icon:'💼',template:'ConsultiQ',greeting:'¡Hola! Soy <strong>Mati</strong>. Veo <strong>Consultoría</strong>. 💼',specQ:'¿Tipo de consultoría?',specs:[{icon:'📊',label:'Empresarial'},{icon:'⚖️',label:'Legal'},{icon:'📈',label:'Financiera'},{icon:'💻',label:'Tech'},{icon:'🎯',label:'Coaching'}],afterSpec:function(s){return '¡'+s.label+'!';},nameQ:'¿Firma?',namePH:'Ej: López & Asociados...',afterName:function(n){return '<strong>'+n+'</strong> — ¿Color? 🎨';},afterColor:'Sobrio.',servicesQ:'Tus <strong>servicios</strong>:',afterServices:function(n){return n+' servicios ✓';},scheduleQ:'¿Horario?',daysQ:'¿Días?',afterDays:function(d){return d.join(', ')+'. ¿Consultores?';},provPH:'Ej: 2',afterProv:function(n){return n+' consultor'+(n==1?'':'es')+'.';}},'Otro tipo de negocio':{icon:'✨',template:'Universal',greeting:'¡Hola! Soy <strong>Mati</strong>. Voy a configurar todo. ✨',specQ:'¿Tipo de negocio?',specs:[{icon:'🔧',label:'Taller'},{icon:'🐾',label:'Veterinaria'},{icon:'🚗',label:'Automotriz'},{icon:'🍽️',label:'Gastronomía'},{icon:'🏡',label:'Hogar'},{icon:'✨',label:'Otro'}],afterSpec:function(s){return '¡'+s.label+'!';},nameQ:'¿Nombre?',namePH:'Ej: TechFix...',afterName:function(n){return '<strong>'+n+'</strong> — ¿Color? 🎨';},afterColor:'¡Excelente!',servicesQ:'Tus <strong>servicios</strong>:',afterServices:function(n){return n+' servicios ✓';},scheduleQ:'¿Horario?',daysQ:'¿Días?',afterDays:function(d){return d.join(', ')+'. ¿Personas?';},provPH:'Ej: 2',afterProv:function(n){return n+' — confirmado.';}}};
    function buildGenSum(d){return '<div class="mati-summary"><h3>📋 Listo</h3><div class="mati-summary-grid"><div>📛 <strong>'+d.name+'</strong></div><div>🎨 <span class="mati-inline-color" style="background:'+d.color+'"></span></div><div>📋 <strong>'+d.services+'</strong> servicios</div><div>🕐 <strong>'+d.schedule+'</strong></div><div>📅 <strong>'+d.days+'</strong></div><div>👥 <strong>'+d.providers+'</strong> profesionales</div></div></div>';}

    // ═══════════════════════════════════════════════════════
    // SITE ANALYZER — Mati analiza el sitio WordPress
    // ═══════════════════════════════════════════════════════
    function analyzeSite() {
        var findings = {};

        // Detectar nombre del sitio
        var siteTitle = document.title.replace(' ‹ Mati — WordPress','').replace('Mati ‹ ','').trim();
        if (!siteTitle || siteTitle === '') {
            var h1 = document.querySelector('h1');
            if (h1) siteTitle = h1.textContent.trim();
        }
        findings.siteTitle = siteTitle || '';

        // Analizar nombre del sitio para inferir tipo de negocio
        var titleLower = findings.siteTitle.toLowerCase();
        var bizHints = {
            'Consultorio Médico': ['clinica','consultorio','medic','dental','doctor','salud','paciente','hospital','odontolog','cardio','pediat','traumatolog','dermatolog'],
            'Salón de Belleza': ['salon','belleza','peluquer','barber','spa','manicur','estetic','hair','nail','beauty'],
            'Gimnasio / Fitness': ['gimnasio','fitness','crossfit','yoga','pilates','entrenamiento','deport','muscul'],
            'Centro Educativo': ['colegio','instituto','academia','escuela','curso','clase','aprender','educat','enseñ'],
            'Consultoría / Servicios': ['consultor','asesor','legal','abogado','estudio','financ','contable','estrateg'],
        };
        findings.detectedBiz = null;
        for (var biz in bizHints) {
            for (var i=0; i<bizHints[biz].length; i++) {
                if (titleLower.indexOf(bizHints[biz][i]) !== -1) {
                    findings.detectedBiz = biz;
                    break;
                }
            }
            if (findings.detectedBiz) break;
        }

        // Detectar plugins relevantes
        findings.hasWooCommerce = typeof woocommerce_params !== 'undefined' || document.querySelector('.woocommerce') !== null;
        findings.hasElementor = typeof elementor !== 'undefined' || document.querySelector('.elementor') !== null;

        // Detectar color del theme
        var themeColor = getComputedStyle(document.body).getPropertyValue('--wp--preset--color--primary');
        findings.themePrimaryColor = themeColor && themeColor.trim() ? themeColor.trim() : null;

        return findings;
    }

    function getSmartGreeting(bizType, findings) {
        var parts = [];
        if (findings.detectedBiz && bizType === findings.detectedBiz) {
            parts.push('Analicé tu sitio y detecté que ya tenés orientación a <strong>'+bizType+'</strong> — ¡vamos por buen camino!');
        }
        if (findings.hasWooCommerce) {
            parts.push('Veo que usás WooCommerce. Mati se integra perfecto para vender servicios como productos con pagos integrados.');
        }
        if (findings.hasElementor) {
            parts.push('Tenés Elementor instalado — podés usar los shortcodes de Mati en cualquier página arrastrando un bloque HTML.');
        }
        return parts;
    }

    async function runConv(bt){var p=P[bt];if(!p)return;userData.bizType=bt;historyStack=[];msgCount=getMc();addInfo();saveState('greeting');await say(p.greeting,300);var tips=getSmartGreeting(bt,userData.siteFindings);if(tips.length){await sleep(300);for(var i=0;i<tips.length;i++){await showTyp('Analizando...');hideTyp();addMsg(tips[i],false);await sleep(400);}}await sleep(200);await showTyp('Escribiendo...');hideTyp();addMsg(p.specQ,false);await sleep(200);var spec=await new Promise(function(r){renderChoiceCards(p.specs,r);});userData.specialty=spec.label;saveState('specialty');await contSpec(spec);}
    async function contSpec(s){var p=P[userData.bizType];await say(p.afterSpec(s),300);await showTyp('Escribiendo...');hideTyp();addMsg(p.nameQ,false);var n=await new Promise(function(r){renderChatInput(p.namePH,null,r);});userData.name=n;saveState('name');await contName(n);}
    async function contName(n){var p=P[userData.bizType];var t=typeof p.afterName==='function'?p.afterName(n):p.afterName;await say(t,200);var c=await new Promise(function(r){renderColor(r);});userData.color=c;saveState('color');await contColor(c);}
    async function contColor(c){var p=P[userData.bizType];var t=(p.afterColor||'¡Buen gusto!').replace('{c}',c);await say(t,200);await showTyp('Escribiendo...');hideTyp();addMsg(p.servicesQ||'Configuremos tus servicios:',false);await sleep(200);var sv=await new Promise(function(r){renderSvcEdit(null,r);});userData.services=sv;saveState('services');await contSvc(sv);}
    async function contSvc(s){var p=P[userData.bizType];var t=typeof p.afterServices==='function'?p.afterServices(s.length):s.length+' servicios ✓';await say(t,200);await showTyp('Escribiendo...');hideTyp();addMsg(p.scheduleQ||'¿Horario?',false);var tm=await new Promise(function(r){renderTime(r);});userData.schedule=tm;saveState('schedule');await contSched(tm);}
    async function contSched(t){var p=P[userData.bizType];await showTyp('Escribiendo...');hideTyp();addMsg(p.daysQ||'¿Días?',false);var d=await new Promise(function(r){renderDays(r);});userData.days=d;saveState('days');await contDays(d);}
    async function contDays(d){var p=P[userData.bizType];var t=typeof p.afterDays==='function'?p.afterDays(d):d.join(', ')+'.';await say(t,200);var pr=await new Promise(function(r){renderChatInput(p.provPH||'Ej: 3',['1','2','3','5','10'],r);});userData.providers=parseInt(pr)||2;saveState('providers');await contProv(userData.providers);}
    async function contProv(pr){var p=P[userData.bizType];var t=typeof p.afterProv==='function'?p.afterProv(pr):pr+' — confirmado.';await say(t,300);await sleep(400);await showTyp('Preparando...');hideTyp();var sd={name:userData.name,specialty:userData.specialty,color:userData.color,services:(userData.services||[]).length,schedule:(userData.schedule&&userData.schedule.label)||'',days:(userData.days||[]).join(', '),providers:pr};var sh=p.buildSummary?p.buildSummary(sd):buildGenSum(sd);addMsg(sh,false);await sleep(400);renderCeleb({template:p.template,name:userData.name,services:(userData.services||[]).length,providers:pr});await sleep(300);await say('Todo listo. Widget activo. <strong>¿Empezamos?</strong> 🚀',200);addMsg('Gestioná todo desde el panel de Mati.',false);setFt('<div style="text-align:center;padding:1rem 0 2rem"><button class="mati-btn mati-btn-primary mati-btn-lg mati-btn-glow" id="mati-launch">🚀 Ir al Panel →</button></div>');scroll();document.getElementById('mati-launch').addEventListener('click',save);}

    function start(){
        // FASE 0: Análisis del sitio
        var findings = analyzeSite();
        userData.siteFindings = findings;
        var siteName = findings.siteTitle || 'tu sitio';

        sleep(1000).then(function(){
            if(statusEl)statusEl.textContent='Analizando tu sitio...';
            return showTyp('Analizando tu sitio WordPress...');
        }).then(function(){return sleep(1000);}).then(function(){
            hideTyp();
            // Saludo con datos del análisis
            addMsg('👋 ¡Hola! Soy <strong>Mati</strong>, tu agente de IA.', false);
            return sleep(500);
        }).then(function(){
            addMsg('Acabo de <strong>analizar tu sitio WordPress</strong>. Veo que se llama <strong>"'+siteName+'"</strong>.', false);
            return sleep(600);
        }).then(function(){
            var recos = [];
            if (findings.detectedBiz) {
                recos.push('Por el nombre y contenido de tu sitio, <strong>detecté que probablemente seas un <strong>'+findings.detectedBiz+'</strong></strong>. ¿Acerté?');
            }
            if (findings.hasElementor) {
                recos.push('Usás Elementor — podés embeber los paneles de Mati en cualquier página arrastrando un shortcode.');
            }
            if (findings.hasWooCommerce) {
                recos.push('Veo que tenés WooCommerce. Mati se integra para vender servicios con pagos — como una tienda + reservas.');
            }
            if (!findings.detectedBiz && !findings.hasElementor && !findings.hasWooCommerce) {
                recos.push('Tu sitio es bastante estándar — eso es bueno, Mati se adapta a cualquier rubro.');
            }
            recos.push('Voy a configurar <strong>todo tu sistema de reservas</strong>. En solo 2 minutos tendrás: ✅ Widget flotante ✅ Agenda IA ✅ Clientes ✅ Recordatorios ✅ Panel completo');

            var chain = Promise.resolve();
            recos.forEach(function(r){
                chain = chain.then(function(){
                    return showTyp('Analizando...').then(function(){
                        hideTyp();
                        addMsg(r, false);
                        return sleep(500);
                    });
                });
            });
            return chain;
        }).then(function(){
            return showTyp('Escribiendo...');
        }).then(function(){
            hideTyp();
            addMsg('<strong>Empecemos:</strong> ¿qué tipo de negocio tienes?', false);
            if (findings.detectedBiz) {
                addMsg('(Basado en mi análisis, creo que puede ser <strong>'+findings.detectedBiz+'</strong> — ¿es correcto?)', false);
            }
            return sleep(300);
        }).then(function(){
            // Ordenar pills: poner la sugerencia detectada primero
            var opts = [
                {value:'Consultorio Médico',label:'🏥 Consultorio Médico'},
                {value:'Salón de Belleza',label:'💇 Salón de Belleza'},
                {value:'Gimnasio / Fitness',label:'💪 Gimnasio / Fitness'},
                {value:'Centro Educativo',label:'📚 Centro Educativo'},
                {value:'Consultoría / Servicios',label:'💼 Consultoría / Servicios'},
                {value:'Otro tipo de negocio',label:'✨ Otro tipo de negocio'}
            ];
            if (findings.detectedBiz) {
                // Mover la sugerencia al principio
                var idx = -1;
                for (var i=0;i<opts.length;i++) { if (opts[i].value === findings.detectedBiz) { idx = i; break; } }
                if (idx > 0) {
                    var sug = opts.splice(idx, 1)[0];
                    sug.label = sug.label + ' ⭐';
                    opts.unshift(sug);
                }
            }
            return new Promise(function(r){renderPills(opts,function(v){r(v);});});
        }).then(function(bt){return runConv(bt);}).catch(function(e){console.error('[Mati]',e);setFt('<div style="text-align:center;padding:1rem;color:#ef4444">Error. <a href="javascript:location.reload()">Recargar</a></div>');});
    }
    start();

    function save(){var b=document.getElementById('mati-launch');if(b){b.textContent='⏳...';b.disabled=true;}var fd=new FormData();fd.append('action','mati_save_setup');fd.append('nonce',matiData.nonce);fd.append('business_name',userData.name||'');fd.append('business_type',userData.bizType||'');fd.append('business_color',userData.color||'');fd.append('business_schedule_start',(userData.schedule&&userData.schedule.start)||'');fd.append('business_schedule_end',(userData.schedule&&userData.schedule.end)||'');fd.append('business_days',(userData.days||[]).join(','));fd.append('business_providers',userData.providers||1);fd.append('business_specialty',userData.specialty||'');fd.append('services',JSON.stringify(userData.services||[]));fetch(matiData.ajaxurl,{method:'POST',body:fd}).then(function(r){return r.json();}).then(function(res){if(res.success){document.body.classList.add('mati-exit');setTimeout(function(){window.location.href=res.data.redirect;},400);}}).catch(function(){window.location.href=window.location.href;});}

    function initServicesManager(){var l=document.getElementById('mati-services-list'),a=document.getElementById('mati-add-service'),s=document.getElementById('mati-save-services'),st=document.getElementById('mati-services-status');if(!l||!a||!s)return;a.addEventListener('click',function(){var e=l.querySelector('.mati-services-empty');if(e)e.remove();var r=document.createElement('div');r.className='mati-service-row';r.setAttribute('data-index',l.children.length);r.innerHTML='<input type="text" class="mati-service-input" placeholder="Nombre" /><input type="number" class="mati-service-duration" value="30" min="5" step="5" style="width:75px" /><span class="mati-service-unit">min</span><button type="button" class="mati-service-remove">×</button>';l.appendChild(r);r.querySelector('.mati-service-remove').addEventListener('click',function(){r.remove();if(!l.querySelectorAll('.mati-service-row').length)l.innerHTML='<div class="mati-services-empty">🎯 No hay servicios.</div>';});});l.querySelectorAll('.mati-service-remove').forEach(function(b){b.addEventListener('click',function(){b.parentElement.remove();if(!l.querySelectorAll('.mati-service-row').length)l.innerHTML='<div class="mati-services-empty">🎯 No hay servicios.</div>';});});s.addEventListener('click',function(){var sv=[];l.querySelectorAll('.mati-service-row').forEach(function(r){var n=r.querySelector('.mati-service-input').value.trim();if(n)sv.push({name:n,duration:parseInt(r.querySelector('.mati-service-duration').value)||30});});var fd=new FormData();fd.append('action','mati_save_services');fd.append('nonce',matiData.nonce);fd.append('services',JSON.stringify(sv));s.disabled=true;s.textContent='⏳...';st.textContent='';fetch(matiData.ajaxurl,{method:'POST',body:fd}).then(function(r){return r.json();}).then(function(){st.textContent='✅ Guardado en mati.com.';st.style.color='#16A34A';s.disabled=false;s.textContent='💾 Guardar';setTimeout(function(){st.textContent='';},3000);}).catch(function(){st.textContent='❌ Error.';st.style.color='#EF4444';s.disabled=false;s.textContent='💾 Guardar';});});}
    function initProvidersManager(){var l=document.getElementById('mati-providers-list'),a=document.getElementById('mati-add-provider'),s=document.getElementById('mati-save-providers'),st=document.getElementById('mati-providers-status');if(!l||!a||!s)return;a.addEventListener('click',function(){var e=l.querySelector('.mati-services-empty');if(e)e.remove();var r=document.createElement('div');r.className='mati-provider-row';r.innerHTML='<div class="mati-provider-fields"><input type="text" class="mati-provider-name" placeholder="Nombre" /><input type="email" class="mati-provider-email" placeholder="Email" /><input type="text" class="mati-provider-role" placeholder="Rol" style="width:140px" /><button type="button" class="mati-service-remove">×</button></div>';l.appendChild(r);r.querySelector('.mati-service-remove').addEventListener('click',function(){r.remove();if(!l.querySelectorAll('.mati-provider-row').length)l.innerHTML='<div class="mati-services-empty">👥 No hay profesionales.</div>';});});l.querySelectorAll('.mati-service-remove').forEach(function(b){b.addEventListener('click',function(){b.closest('.mati-provider-row').remove();if(!l.querySelectorAll('.mati-provider-row').length)l.innerHTML='<div class="mati-services-empty">👥 No hay profesionales.</div>';});});s.addEventListener('click',function(){var pv=[];l.querySelectorAll('.mati-provider-row').forEach(function(r){var n=r.querySelector('.mati-provider-name').value.trim();if(n)pv.push({name:n,email:r.querySelector('.mati-provider-email').value.trim(),role:r.querySelector('.mati-provider-role').value.trim()||'Profesional'});});var fd=new FormData();fd.append('action','mati_save_providers');fd.append('nonce',matiData.nonce);fd.append('providers',JSON.stringify(pv));fd.append('count',String(pv.length));s.disabled=true;s.textContent='⏳...';st.textContent='';fetch(matiData.ajaxurl,{method:'POST',body:fd}).then(function(r){return r.json();}).then(function(){st.textContent='✅ Guardado en mati.com.';st.style.color='#16A34A';s.disabled=false;s.textContent='💾 Guardar Equipo';setTimeout(function(){st.textContent='';},3000);}).catch(function(){st.textContent='❌ Error.';st.style.color='#EF4444';s.disabled=false;s.textContent='💾 Guardar Equipo';});});}
    function initScheduleManager(){var s=document.getElementById('mati-save-schedule'),st=document.getElementById('mati-schedule-status');if(!s)return;s.addEventListener('click',function(){var sch={};document.querySelectorAll('.mati-schedule-day').forEach(function(d){var day=d.getAttribute('data-day');var cb=d.querySelector('.mati-sched-active');var s=d.querySelector('.mati-sched-start');var e=d.querySelector('.mati-sched-end');sch[day]={active:cb?cb.checked:true,start:s?s.value:'09:00',end:e?e.value:'18:00'};});var fd=new FormData();fd.append('action','mati_save_schedule');fd.append('nonce',matiData.nonce);fd.append('schedule',JSON.stringify(sch));s.disabled=true;s.textContent='⏳...';fetch(matiData.ajaxurl,{method:'POST',body:fd}).then(function(r){return r.json();}).then(function(){st.textContent='✅ Guardado en mati.com.';st.style.color='#16A34A';s.disabled=false;s.textContent='💾 Guardar Horarios';setTimeout(function(){st.textContent='';},3000);}).catch(function(){st.textContent='❌ Error.';st.style.color='#EF4444';s.disabled=false;s.textContent='💾 Guardar Horarios';});});}

    // ═══════════════════════════════════════════════════════
    // WIDGET CONFIG — Plantillas, preview, copiar, paneles
    // ═══════════════════════════════════════════════════════
    function initWidgetConfig() {
        var previewIframe = document.getElementById('mati-preview-iframe');
        var embedCodeBlock = document.getElementById('mati-embed-code');
        var panelsJson = document.getElementById('mati-panels-json');
        var slug = matiData.slug || '';
        var baseUrl = matiData.dashboardUrl ? matiData.dashboardUrl.replace('/dashboard', '') : 'http://localhost:3000';

        // Presets de plantillas
        var templates = {
            clasico:   { color: '#1A5D4A', greeting: '¡Hola! ¿En qué puedo ayudarte?', variant: 'default' },
            moderno:   { color: '#6366F1', greeting: 'Bienvenido/a. Reservá tu cita en segundos.', variant: 'modern' },
            minimal:   { color: '#334155', greeting: 'Hacé tu reserva.', variant: 'minimal' },
            oscuro:    { color: '#0F172A', greeting: '¿Listo para reservar?', variant: 'dark' },
            salud:     { color: '#0D9488', greeting: '¡Hola! Agenda tu consulta médica hoy.', variant: 'default' },
            belleza:   { color: '#DB2777', greeting: '¡Bienvenida! Reservá tu turno de belleza.', variant: 'default' },
            fitness:   { color: '#EA580C', greeting: '¡Vamos! Reservá tu clase de entrenamiento.', variant: 'default' },
            educacion: { color: '#7C3AED', greeting: '¡Hola! Reservá tu clase o tutoría.', variant: 'default' }
        };

        // Click en tarjeta de plantilla
        document.querySelectorAll('.mati-template-card').forEach(function(card){
            card.addEventListener('click', function(){
                var key = this.dataset.template;
                var t = templates[key];
                if (!t) return;
                // Quitar active de todas
                document.querySelectorAll('.mati-template-card').forEach(function(c){ c.classList.remove('active'); });
                this.classList.add('active');
                document.getElementById('mati-widget-variant').value = t.variant;
                document.getElementById('mati-color-picker').value = t.color;
                document.getElementById('mati-color-text').value = t.color;
                document.getElementById('mati-greeting').value = t.greeting;
                updatePreview();
                updateEmbed();
            });
        });

        // Inputs que disparan actualización de preview
        var inputs = ['mati-widget-variant','mati-position','mati-theme','mati-language','mati-color-picker','mati-button-text','mati-greeting','mati-auto-open','mati-agent-mode','mati-voice'];
        inputs.forEach(function(id){
            var el = document.getElementById(id);
            if (!el) return;
            el.addEventListener('change', function(){ updatePreview(); updateEmbed(); });
            if (el.tagName === 'INPUT' && el.type === 'text') {
                el.addEventListener('input', debounce(function(){ updatePreview(); updateEmbed(); }, 400));
            }
        });

        // Sincronizar color picker ↔ texto
        var colorPicker = document.getElementById('mati-color-picker');
        var colorText = document.getElementById('mati-color-text');
        if (colorPicker && colorText){
            colorPicker.addEventListener('input', function(){ colorText.value = this.value; updatePreview(); updateEmbed(); });
            colorText.addEventListener('change', function(){
                if (/^#[0-9A-Fa-f]{3,6}$/.test(this.value)) colorPicker.value = this.value;
                updatePreview(); updateEmbed();
            });
        }

        // Toggles de paneles actualizan campo JSON oculto
        document.querySelectorAll('.mati-panel-toggles input[type="checkbox"]').forEach(function(cb){
            cb.addEventListener('change', function(){
                var panels = {admin:false, provider:false, customer:false};
                document.querySelectorAll('.mati-panel-toggles input[type="checkbox"]').forEach(function(c){
                    var key = c.getAttribute('data-panel');
                    if (key) panels[key] = c.checked;
                });
                if (panelsJson) panelsJson.value = JSON.stringify(panels);
            });
        });

        // Tabs del preview
        document.querySelectorAll('.mati-preview-tab').forEach(function(tab){
            tab.addEventListener('click', function(){
                document.querySelectorAll('.mati-preview-tab').forEach(function(t){ t.classList.remove('active'); });
                this.classList.add('active');
                updatePreview();
            });
        });

        function getActiveTab(){
            var active = document.querySelector('.mati-preview-tab.active');
            return active ? active.dataset.tab : 'widget';
        }

        function updatePreview(){
            if (!previewIframe) return;
            var tab = getActiveTab();
            var variant = document.getElementById('mati-widget-variant').value;
            var theme = document.getElementById('mati-theme').value;
            var color = document.getElementById('mati-color-picker').value;
            var greeting = document.getElementById('mati-greeting').value;
            var apiKey = matiData.apiKey || '';
            var url = baseUrl;
            if (tab === 'widget') {
                url += '/widget/' + encodeURIComponent(slug) + '?variant=' + encodeURIComponent(variant) + '&theme=' + encodeURIComponent(theme) + '&color=' + encodeURIComponent(color) + '&greeting=' + encodeURIComponent(greeting);
            } else if (tab === 'admin') {
                url += '/widget/panel/admin/' + encodeURIComponent(slug) + '?apiKey=' + encodeURIComponent(apiKey) + '&theme=light&color=' + encodeURIComponent(color);
            } else if (tab === 'provider') {
                url += '/widget/panel/provider/' + encodeURIComponent(slug) + '?apiKey=' + encodeURIComponent(apiKey) + '&theme=light&color=' + encodeURIComponent(color);
            } else if (tab === 'customer') {
                url += '/widget/panel/customer/' + encodeURIComponent(slug) + '?apiKey=' + encodeURIComponent(apiKey) + '&theme=light&color=' + encodeURIComponent(color);
            }
            previewIframe.src = url;
        }

        function updateEmbed(){
            if (!embedCodeBlock) return;
            var variant = document.getElementById('mati-widget-variant').value;
            var position = document.getElementById('mati-position').value;
            var theme = document.getElementById('mati-theme').value;
            var lang = document.getElementById('mati-language').value;
            var color = document.getElementById('mati-color-picker').value;
            var btnText = document.getElementById('mati-button-text').value;
            var greeting = document.getElementById('mati-greeting').value;
            var autoOpen = document.getElementById('mati-auto-open').value;
            var agentMode = document.getElementById('mati-agent-mode').value;

            var code = '&lt;script src="' + (matiData.scriptUrl || '') + '"\n' +
                '  data-slug="' + slug + '"\n' +
                '  data-variant="' + variant + '"\n' +
                '  data-position="' + position + '"\n' +
                '  data-theme="' + theme + '"\n' +
                '  data-language="' + lang + '"\n' +
                '  data-primary-color="' + color + '"\n' +
                '  data-button-text="' + btnText + '"\n' +
                '  data-greeting="' + greeting + '"\n' +
                '  data-auto-open="' + autoOpen + '"\n' +
                '  data-agent-mode="' + agentMode + '"\n' +
                '  async&gt;&lt;/script&gt;';
            embedCodeBlock.innerHTML = code;
        }

        // Copiar al portapapeles
        document.querySelectorAll('.mati-shortcode-copy').forEach(function(btn){
            btn.addEventListener('click', function(){
                var text = this.dataset.clipboard;
                if (!text && this.dataset.clipboardTarget) {
                    var el = document.getElementById(this.dataset.clipboardTarget);
                    text = el ? el.textContent.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&') : '';
                }
                if (!text) return;
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(text).then(function(){ showCopyFeedback(btn); });
                } else {
                    var ta = document.createElement('textarea');
                    ta.value = text;
                    document.body.appendChild(ta);
                    ta.select();
                    document.execCommand('copy');
                    document.body.removeChild(ta);
                    showCopyFeedback(btn);
                }
            });
        });

        function showCopyFeedback(btn){
            var orig = btn.textContent;
            btn.textContent = '✅ Copiado';
            setTimeout(function(){ btn.textContent = orig; }, 1500);
        }

        function debounce(fn, ms){
            var t;
            return function(){
                clearTimeout(t);
                t = setTimeout(fn, ms);
            };
        }
    }
})();
