(() => {
  'use strict';
  const canvas=document.querySelector('[data-replay-canvas]');const dataNode=document.querySelector('#replay-data');if(!canvas||!dataNode)return;
  const ctx=canvas.getContext('2d');const d=JSON.parse(dataNode.textContent||'{}');const W=canvas.width,H=canvas.height;
  const startBtn=document.querySelector('[data-replay-start]');const recordBtn=document.querySelector('[data-replay-record]');const feedback=document.querySelector('[data-replay-feedback]');
  let raf=0,start=0,playing=false,recorder=null,chunks=[];
  const show=t=>{if(feedback)feedback.textContent=t;setTimeout(()=>{if(feedback)feedback.textContent=''},4000)};
  function roundRect(x,y,w,h,r){ctx.beginPath();ctx.roundRect(x,y,w,h,r);}
  function bg(t){const g=ctx.createLinearGradient(0,0,W,H);g.addColorStop(0,'#02040d');g.addColorStop(.5,'#12052b');g.addColorStop(1,'#001b29');ctx.fillStyle=g;ctx.fillRect(0,0,W,H);ctx.globalCompositeOperation='screen';for(let i=0;i<42;i++){const a=(i*.618+t*.00008)%1;const x=(Math.sin(i*91.3)*.5+.5)*W;const y=((i*137+t*.09)%H);ctx.globalAlpha=.12+.22*Math.sin(a*Math.PI);ctx.fillStyle=i%2?'#00e5ff':'#9b4dff';ctx.beginPath();ctx.arc(x,y,3+(i%6),0,Math.PI*2);ctx.fill()}ctx.globalAlpha=1;ctx.globalCompositeOperation='source-over';}
  function text(txt,x,y,size,weight='700',align='center',fill='#fff'){ctx.font=`${weight} ${size}px Arial, sans-serif`;ctx.textAlign=align;ctx.fillStyle=fill;ctx.fillText(txt,x,y)}
  function draw(ms){const p=Math.min(1,ms/12000);bg(ms);const pulse=.5+.5*Math.sin(ms/260);ctx.save();ctx.translate(W/2,670);ctx.globalAlpha=.18+.18*pulse;ctx.strokeStyle='#00e5ff';ctx.lineWidth=30+25*p;ctx.beginPath();ctx.arc(0,0,210+110*pulse,0,Math.PI*2);ctx.stroke();ctx.strokeStyle='#9b4dff';ctx.lineWidth=12;ctx.beginPath();ctx.arc(0,0,270+80*p,0,Math.PI*2);ctx.stroke();ctx.restore();
    text('AURA',W/2,150,98,'900');text('FARMING',W/2,220,34,'800','center','#00e5ff');
    const phase=Math.floor(p*5);const messages=['A FARMADA COMEÇOU','COMBO EM ASCENSÃO','AURA EXPANDINDO','ENERGIA MÁXIMA','RESULTADO FINAL'];text(messages[Math.min(4,phase)],W/2,330,34,'900','center',phase===4?'#ffd44d':'#d7b4ff');
    text(d.player?.nome||'Aura Farmer',W/2,470,46,'800');text(d.player?.aura_id||'',W/2,520,25,'700','center','#79eaff');
    const eased=1-Math.pow(1-p,3);const score=(Number(d.score||0)*eased).toLocaleString('pt-BR',{maximumFractionDigits:2});text(score,W/2,760,120,'900');text('PONTOS DE AURA',W/2,820,28,'800','center','#9eeeff');
    const cards=[['AURA',Math.round(Number(d.aura||0)*eased)],['COMBO',`x${Math.max(1,Math.round(1+(Number(d.combo||1)-1)*eased))}`],['LIKES',Math.round(Number(d.likes||0)*eased)],['RANK',d.rank?`${d.rank}º`:'—']];cards.forEach((c,i)=>{const x=80+(i%2)*500,y=950+Math.floor(i/2)*190;roundRect(x,y,420,145,28);ctx.fillStyle='rgba(255,255,255,.07)';ctx.fill();text(c[0],x+35,y+43,20,'700','left','#86deff');text(String(c[1]),x+35,y+108,48,'900','left')});
    const lineY=1395;ctx.fillStyle='rgba(255,255,255,.1)';roundRect(80,lineY,920,18,9);ctx.fill();const grad=ctx.createLinearGradient(80,0,1000,0);grad.addColorStop(0,'#00e5ff');grad.addColorStop(1,'#b14dff');ctx.fillStyle=grad;roundRect(80,lineY,920*p,18,9);ctx.fill();
    if(p>.78){ctx.globalAlpha=Math.min(1,(p-.78)/.12);text(`NOTA ${d.grade||'D'}`,W/2,1570,82,'900','center','#ffd44d');text('VOCÊ CONSEGUE SUPERAR?',W/2,1660,42,'900');text('ENTRE • FARME • EXPANDA SUA AURA',W/2,1760,25,'700','center','#9eeeff');ctx.globalAlpha=1}
  }
  function tick(now){if(!start)start=now;const ms=now-start;draw(ms);if(ms<12000&&playing)raf=requestAnimationFrame(tick);else{playing=false;start=0;if(recorder&&recorder.state==='recording')recorder.stop();startBtn.disabled=false;}}
  function play(){cancelAnimationFrame(raf);playing=true;start=0;startBtn.disabled=true;raf=requestAnimationFrame(tick)}
  startBtn?.addEventListener('click',play);draw(12000);
  recordBtn?.addEventListener('click',()=>{if(!canvas.captureStream||typeof MediaRecorder==='undefined'){show('Seu navegador não permite gerar vídeo. Use o card PNG.');return;}try{chunks=[];const stream=canvas.captureStream(30);const mime=MediaRecorder.isTypeSupported('video/webm;codecs=vp9')?'video/webm;codecs=vp9':'video/webm';recorder=new MediaRecorder(stream,{mimeType:mime,videoBitsPerSecond:5000000});recorder.ondataavailable=e=>e.data.size&&chunks.push(e.data);recorder.onstop=()=>{const blob=new Blob(chunks,{type:mime});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=`aura-replay-${d.player?.aura_id||'resultado'}.webm`;a.click();setTimeout(()=>URL.revokeObjectURL(a.href),2000);show('Vídeo-resumo gerado!')};recorder.start();play();show('Gerando vídeo de 12 segundos…')}catch(e){show('Não foi possível gerar o vídeo neste aparelho.')}});
})();
