'use strict';
(() => {
  const menu = document.querySelector('[data-admin-menu]');
  const sidebar = document.getElementById('adminSidebar');
  menu?.addEventListener('click', () => sidebar?.classList.toggle('open'));
  document.addEventListener('click', (e) => {
    if (window.innerWidth <= 760 && sidebar?.classList.contains('open') && !sidebar.contains(e.target) && e.target !== menu) sidebar.classList.remove('open');
  });

  const draw = (canvas, rows, valueKey = 'partidas') => {
    if (!canvas || !rows?.length) return;
    const ctx = canvas.getContext('2d');
    const dpr = Math.min(2, window.devicePixelRatio || 1);
    const rect = canvas.getBoundingClientRect();
    canvas.width = Math.max(320, rect.width * dpr); canvas.height = Math.max(180, rect.height * dpr); ctx.scale(dpr, dpr);
    const w = rect.width, h = rect.height, pad = 28, max = Math.max(1, ...rows.map(r => Number(r[valueKey] || r.total || 0)));
    ctx.clearRect(0,0,w,h); ctx.strokeStyle='rgba(255,255,255,.08)'; ctx.lineWidth=1;
    for(let i=0;i<5;i++){const y=pad+(h-pad*2)*(i/4);ctx.beginPath();ctx.moveTo(pad,y);ctx.lineTo(w-pad,y);ctx.stroke();}
    const pts=rows.map((r,i)=>({x:pad+(w-pad*2)*(rows.length===1?0.5:i/(rows.length-1)),y:h-pad-(Number(r[valueKey]||r.total||0)/max)*(h-pad*2)}));
    const g=ctx.createLinearGradient(0,pad,0,h);g.addColorStop(0,'rgba(0,212,255,.35)');g.addColorStop(1,'rgba(123,47,255,0)');
    ctx.beginPath();ctx.moveTo(pts[0].x,h-pad);pts.forEach(p=>ctx.lineTo(p.x,p.y));ctx.lineTo(pts.at(-1).x,h-pad);ctx.closePath();ctx.fillStyle=g;ctx.fill();
    ctx.beginPath();pts.forEach((p,i)=>i?ctx.lineTo(p.x,p.y):ctx.moveTo(p.x,p.y));ctx.strokeStyle='#00d4ff';ctx.lineWidth=2;ctx.stroke();
    ctx.fillStyle='#aeb8cc';ctx.font='9px sans-serif';pts.forEach((p,i)=>{if(i===0||i===pts.length-1||i%Math.ceil(pts.length/6)===0){const label=String(rows[i].dia||'').slice(5);ctx.fillText(label,p.x-12,h-8);}});
  };
  document.querySelectorAll('[data-admin-chart]').forEach(el=>{try{draw(el.querySelector('canvas'),JSON.parse(el.dataset.adminChart),'partidas');}catch(e){}});
  document.querySelectorAll('[data-admin-users]').forEach(el=>{try{draw(el.querySelector('canvas'),JSON.parse(el.dataset.adminUsers),'total');}catch(e){}});
})();
