(() => {
  'use strict';
  const root=document.querySelector('.viral-center');if(!root)return;
  const base=document.querySelector('meta[name="app-base-url"]')?.content||'';
  const csrf=document.querySelector('meta[name="csrf-token"]')?.content||'';
  const invite=root.dataset.inviteUrl||'';
  const feedback=document.querySelector('[data-viral-feedback]');
  const show=t=>{if(!feedback)return;feedback.textContent=t;setTimeout(()=>feedback.textContent='',3500)};
  document.querySelectorAll('[data-qr-value]').forEach(c=>{try{window.AuraQRCode?.render(c,c.dataset.qrValue,210)}catch(_){}});
  document.querySelector('[data-copy-invite]')?.addEventListener('click',async()=>{try{await navigator.clipboard.writeText(invite);show('Link pessoal copiado!')}catch(_){prompt('Copie o link:',invite)}});
  document.querySelector('[data-share-invite]')?.addEventListener('click',async()=>{const text='Entre no Aura Farming pelo meu convite e tente superar minha aura!';try{if(navigator.share){await navigator.share({title:'Aura Farming',text,url:invite});show('Convite compartilhado!')}else{await navigator.clipboard.writeText(`${text} ${invite}`);show('Convite copiado!')}}catch(e){if(e?.name!=='AbortError')show('Não foi possível compartilhar.')}});
  document.querySelectorAll('[data-create-challenge]').forEach(btn=>btn.addEventListener('click',async()=>{
    const row=btn.closest('[data-result-id]');if(!row)return;btn.disabled=true;const old=btn.textContent;btn.textContent='CRIANDO…';
    try{const r=await fetch(`${base}/api/v1/viral/challenge.php`,{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json','X-CSRF-Token':csrf},body:JSON.stringify({partida_id:Number(row.dataset.resultId),template:'neon'})});const d=await r.json();if(!r.ok||!d.ok)throw new Error(d.erro||'Falha ao criar desafio.');await navigator.clipboard.writeText(d.desafio.url);show('Desafio criado e link copiado!');window.location.href=d.desafio.url;}catch(e){show(e.message||'Não foi possível criar o desafio.');btn.disabled=false;btn.textContent=old;}
  }));
})();
