(() => {
  'use strict';
  const root=document.querySelector('[data-share-url]');if(!root)return;
  const base=document.querySelector('meta[name="app-base-url"]')?.content||'';
  const csrf=document.querySelector('meta[name="csrf-token"]')?.content||'';
  const info={
    partidaId:Number(root.dataset.partidaId||0),url:root.dataset.shareUrl||location.href,score:Number(root.dataset.shareScore||0),auraId:root.dataset.shareAuraId||'',
    nome:root.dataset.shareName||'Aura Farmer',aura:Number(root.dataset.shareAura||0),likes:Number(root.dataset.shareLikes||0),superlikes:Number(root.dataset.shareSuperlikes||0),
    combo:Number(root.dataset.shareCombo||1),grade:root.dataset.shareGrade||'D',rank:Number(root.dataset.shareRank||0),avatar:root.dataset.shareAvatar||'',replay:root.dataset.replayUrl||''
  };
  const feedback=document.querySelector('[data-share-feedback]');const modal=document.querySelector('[data-share-studio]');const canvas=document.querySelector('[data-share-canvas]');
  let format='story',template='neon',lastBlob=null;
  const show=t=>{if(!feedback)return;feedback.textContent=t;setTimeout(()=>feedback.textContent='',4000)};
  const register=async channel=>{try{await fetch(`${base}/api/v1/matches/share.php`,{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json','X-CSRF-Token':csrf},body:JSON.stringify({url:info.url,canal:channel})})}catch(_){}};
  const rr=(ctx,x,y,w,h,r)=>{ctx.beginPath();ctx.roundRect(x,y,w,h,r)};
  function fitText(ctx,text,maxWidth,start,min=24){let size=start;while(size>min){ctx.font=`900 ${size}px Arial`;if(ctx.measureText(text).width<=maxWidth)break;size-=2}return size}
  async function loadImage(src){if(!src)return null;return new Promise(resolve=>{const i=new Image();i.crossOrigin='anonymous';i.onload=()=>resolve(i);i.onerror=()=>resolve(null);i.src=src})}
  async function render(){if(!canvas)return null;const story=format==='story';canvas.width=1080;canvas.height=story?1920:1080;const ctx=canvas.getContext('2d'),W=canvas.width,H=canvas.height;
    const colors=template==='maximum'?['#130400','#4a0900','#ff5c00']:template==='purple'?['#050014','#25034e','#7c2cff']:['#02040d','#071c31','#6a17c9'];
    const bg=ctx.createLinearGradient(0,0,W,H);bg.addColorStop(0,colors[0]);bg.addColorStop(.55,colors[1]);bg.addColorStop(1,colors[2]);ctx.fillStyle=bg;ctx.fillRect(0,0,W,H);
    ctx.globalCompositeOperation='screen';for(let i=0;i<90;i++){ctx.globalAlpha=.08+(i%7)*.02;ctx.fillStyle=i%3===0?'#fff':(i%2?'#00e5ff':'#b04dff');ctx.beginPath();ctx.arc((i*173)%W,(i*307)%H,2+(i%8),0,Math.PI*2);ctx.fill()}ctx.globalAlpha=1;ctx.globalCompositeOperation='source-over';
    const center=W/2;ctx.strokeStyle='rgba(0,229,255,.28)';ctx.lineWidth=35;ctx.beginPath();ctx.arc(center,story?650:430,story?270:210,0,Math.PI*2);ctx.stroke();ctx.strokeStyle='rgba(177,77,255,.35)';ctx.lineWidth=10;ctx.beginPath();ctx.arc(center,story?650:430,story?330:255,0,Math.PI*2);ctx.stroke();
    ctx.textAlign='center';ctx.fillStyle='#fff';ctx.font='900 92px Arial';ctx.fillText('AURA',center,story?145:95);ctx.fillStyle='#00e5ff';ctx.font='800 28px Arial';ctx.fillText('FARMING',center,story?190:130);
    const img=await loadImage(info.avatar);if(img){ctx.save();ctx.beginPath();ctx.arc(center,story?470:320,96,0,Math.PI*2);ctx.clip();ctx.drawImage(img,center-96,(story?470:320)-96,192,192);ctx.restore();ctx.strokeStyle='#00e5ff';ctx.lineWidth=8;ctx.beginPath();ctx.arc(center,story?470:320,102,0,Math.PI*2);ctx.stroke()}
    ctx.fillStyle='#fff';ctx.font=`900 ${fitText(ctx,info.nome,850,48)}px Arial`;ctx.fillText(info.nome,center,story?600:420);ctx.fillStyle='#9eeeff';ctx.font='700 24px Arial';ctx.fillText(info.auraId,center,story?640:455);
    ctx.fillStyle='#d9b9ff';ctx.font='900 30px Arial';ctx.fillText('EU FARMEI',center,story?790:540);ctx.fillStyle='#fff';ctx.font=`900 ${story?128:96}px Arial`;ctx.fillText(info.score.toLocaleString('pt-BR',{maximumFractionDigits:2}),center,story?920:645);ctx.fillStyle='#00e5ff';ctx.font='800 30px Arial';ctx.fillText('PONTOS DE AURA',center,story?970:690);
    const cards=[['AURA',Math.round(info.aura)],['COMBO',`x${info.combo}`],['LIKES',info.likes],['GLOBAL',info.rank?`${info.rank}º`:'—']];const cardW=story?420:230,cardH=story?150:120,gap=story?40:20,startX=story?100:30,startY=story?1080:755;
    cards.forEach((c,i)=>{const x=story?startX+(i%2)*(cardW+gap):startX+i*(cardW+gap),y=story?startY+Math.floor(i/2)*(cardH+gap):startY;rr(ctx,x,y,cardW,cardH,25);ctx.fillStyle='rgba(255,255,255,.08)';ctx.fill();ctx.textAlign='left';ctx.fillStyle='#92eaff';ctx.font='700 20px Arial';ctx.fillText(c[0],x+25,y+42);ctx.fillStyle='#fff';ctx.font=`900 ${story?48:38}px Arial`;ctx.fillText(String(c[1]),x+25,y+(story?112:92));ctx.textAlign='center'});
    const qr=document.createElement('canvas');qr.width=qr.height=190;try{window.AuraQRCode?.render(qr,info.url,190);ctx.fillStyle='#fff';rr(ctx,story?445:445,story?1530:900,190,190,18);ctx.fill();ctx.drawImage(qr,story?445:445,story?1530:900,190,190)}catch(_){}
    ctx.fillStyle='#fff';ctx.font=`900 ${story?40:30}px Arial`;ctx.fillText('VOCÊ CONSEGUE SUPERAR?',center,story?1480:875);ctx.fillStyle='#9eeeff';ctx.font='700 23px Arial';ctx.fillText('ESCANEIE • ENTRE • FARME',center,story?1765:1040);
    ctx.fillStyle='rgba(255,255,255,.65)';ctx.font='600 18px Arial';ctx.fillText('Resultado oficial validado pelo Aura Farming',center,H-55);
    lastBlob=await new Promise(resolve=>canvas.toBlob(resolve,'image/png',.95));return lastBlob;
  }
  async function download(){const b=await render();if(!b)return;const a=document.createElement('a');a.href=URL.createObjectURL(b);a.download=`aura-${info.auraId}-${format}.png`;a.click();setTimeout(()=>URL.revokeObjectURL(a.href),2000);register(format==='story'?'instagram':'outro');show('Card PNG gerado!')}
  async function nativeShare(){const b=await render();const text=`Eu farmei ${info.score.toLocaleString('pt-BR')} pontos de Aura! Tente superar ${info.auraId}.`;try{const file=new File([b],`aura-${info.auraId}.png`,{type:'image/png'});if(navigator.canShare?.({files:[file]})){await navigator.share({title:'Meu resultado no Aura Farming',text,url:info.url,files:[file]})}else if(navigator.share){await navigator.share({title:'Meu resultado no Aura Farming',text,url:info.url})}else{await navigator.clipboard.writeText(`${text} ${info.url}`)}register('webshare');show('Resultado compartilhado!')}catch(e){if(e?.name!=='AbortError')show('Compartilhamento cancelado ou indisponível.')}}
  function openNetwork(channel){const text=encodeURIComponent(`Eu farmei ${info.score.toLocaleString('pt-BR')} pontos de Aura! Tente superar ${info.auraId}.`),url=encodeURIComponent(info.url);let target='';if(channel==='whatsapp')target=`https://wa.me/?text=${text}%20${url}`;if(channel==='facebook')target=`https://www.facebook.com/sharer/sharer.php?u=${url}`;if(channel==='x')target=`https://twitter.com/intent/tweet?text=${text}&url=${url}`;if(target)window.open(target,'_blank','noopener,noreferrer');register(channel)}
  async function createChallenge(){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:info.partidaId,template})});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! Link copiado.');window.open(d.desafio.url,'_blank','noopener')}catch(e){show(e.message||'Não foi possível criar o desafio.')}}
  document.querySelector('[data-share-result]')?.addEventListener('click',()=>{modal?.classList.add('is-open');modal?.setAttribute('aria-hidden','false');render()});
  document.querySelectorAll('[data-close-share]').forEach(b=>b.addEventListener('click',()=>{modal?.classList.remove('is-open');modal?.setAttribute('aria-hidden','true')}));
  document.querySelectorAll('[data-share-format]').forEach(b=>b.addEventListener('click',()=>{format=b.dataset.shareFormat;document.querySelectorAll('[data-share-format]').forEach(x=>x.classList.toggle('active',x===b));render()}));
  document.querySelectorAll('[data-share-template]').forEach(b=>b.addEventListener('click',()=>{template=b.dataset.shareTemplate;document.querySelectorAll('[data-share-template]').forEach(x=>x.classList.toggle('active',x===b));render()}));
  document.querySelector('[data-download-card]')?.addEventListener('click',download);document.querySelector('[data-native-share]')?.addEventListener('click',nativeShare);document.querySelectorAll('[data-create-viral-challenge]').forEach(b=>b.addEventListener('click',createChallenge));
  document.querySelectorAll('[data-share-network]').forEach(b=>b.addEventListener('click',async()=>{const c=b.dataset.shareNetwork;if(c==='instagram'||c==='tiktok'){await download();show(`Card salvo. Abra o ${c==='instagram'?'Instagram':'TikTok'} e publique o arquivo.`)}else openNetwork(c)}));
  document.querySelector('[data-copy-result]')?.addEventListener('click',async()=>{try{await navigator.clipboard.writeText(info.url);register('copiar');show('Link copiado!')}catch(_){prompt('Copie o link:',info.url)}});
  modal?.addEventListener('click',e=>{if(e.target===modal){modal.classList.remove('is-open');modal.setAttribute('aria-hidden','true')}});
})();
