// High-Performance Interactive Canvas & Metrics Engine
class UESCharts {
  static renderCategoryChart(canvasId, categoryData) {
    const canvas = document.getElementById(canvasId);
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const width = canvas.width;
    const height = canvas.height;

    ctx.clearRect(0, 0, width, height);

    const categories = Object.keys(categoryData || {});
    const values = Object.values(categoryData || {});
    if (categories.length === 0) {
      ctx.fillStyle = '#64748b';
      ctx.font = '13px Poppins, sans-serif';
      ctx.textAlign = 'center';
      ctx.fillText('Run scrapers from the Dashboard to load real-time telemetry.', width / 2, height / 2);
      return;
    }

    const maxVal = Math.max(...values, 10);
    const numBars = categories.length;
    const availableWidth = width - 80;
    const barWidth = Math.min(65, Math.max(35, (availableWidth / numBars) - 16));
    const startX = 50;
    const startY = height - 40;
    const chartHeight = height - 75;

    // Draw light subtle gridlines
    ctx.strokeStyle = 'rgba(0, 0, 0, 0.06)';
    ctx.lineWidth = 1;
    for (let i = 0; i <= 4; i++) {
      const lineY = startY - (chartHeight * (i / 4));
      ctx.beginPath();
      ctx.moveTo(startX - 10, lineY);
      ctx.lineTo(width - 30, lineY);
      ctx.stroke();
    }

    categories.forEach((cat, idx) => {
      const val = values[idx];
      const barHeight = Math.max(6, (val / maxVal) * chartHeight);
      const x = startX + idx * (barWidth + 18);
      const y = startY - barHeight;

      // Clean Purple Gradient Bar
      const grad = ctx.createLinearGradient(0, y, 0, startY);
      if (idx % 2 === 0) {
        grad.addColorStop(0, '#8b5cf6');
        grad.addColorStop(1, '#7c3aed');
      } else {
        grad.addColorStop(0, '#6366f1');
        grad.addColorStop(1, '#4f46e5');
      }
      ctx.fillStyle = grad;

      // Rounded bar
      ctx.beginPath();
      if (ctx.roundRect) {
        ctx.roundRect(x, y, barWidth, barHeight, [6, 6, 0, 0]);
      } else {
        ctx.rect(x, y, barWidth, barHeight);
      }
      ctx.fill();

      // Top value badge (Dark Black)
      ctx.fillStyle = '#09090b';
      ctx.font = 'bold 11.5px Poppins, sans-serif';
      ctx.textAlign = 'center';
      ctx.fillText(val.toString(), x + barWidth / 2, y - 8);

      // Bottom Category Label (Slate)
      ctx.fillStyle = '#475569';
      ctx.font = '500 11px Poppins, sans-serif';
      ctx.textAlign = 'center';
      const shortName = cat.length > 11 ? cat.substring(0, 10) + '..' : cat;
      ctx.fillText(shortName, x + barWidth / 2, startY + 22);
    });
  }

  static renderBreakdownList(containerId, dataObj, totalCount) {
    const container = document.getElementById(containerId);
    if (!container) return;
    container.innerHTML = '';

    const keys = Object.keys(dataObj || {});
    if (keys.length === 0 || !totalCount) {
      container.innerHTML = '<div style="color: #94a3b8; font-size: 12px; text-align: center; padding: 20px;">Run scrapers to populate statistics.</div>';
      return;
    }

    keys.forEach(key => {
      const count = dataObj[key];
      const pct = Math.round((count / totalCount) * 100) || 0;
      const row = document.createElement('div');
      row.style.cssText = 'display: flex; flex-direction: column; gap: 4px;';
      row.innerHTML = `
        <div style="display: flex; justify-content: space-between; font-size: 12.5px;">
          <span style="color: #09090b; font-weight: 600;">${key}</span>
          <span style="color: #64748b; font-size: 11.5px; font-weight: 500;">${count} courses (${pct}%)</span>
        </div>
        <div style="width: 100%; height: 6px; background: #e2e8f0; border-radius: 9999px; overflow: hidden;">
          <div style="width: ${pct}%; height: 100%; background: linear-gradient(90deg, #8b5cf6, #7c3aed); border-radius: 9999px;"></div>
        </div>
      `;
      container.appendChild(row);
    });
  }
}

window.UESCharts = UESCharts;
