<div class="row">
  <div class="col-12">
    {% if data.distribution %}
    {{ data.distribution|json_script:"activity-distribution-data" }}
    <p class="text-muted mb-3">
      Total scrobbles{% if current_period_label %} ({{ current_period_label }}){% endif %}: <strong>{{ data.total_count }}</strong>
    </p>
    <canvas id="activityDistChart" width="700" style="max-width:100%;"></canvas>
    <script>
    (function() {
      var el = document.getElementById('activity-distribution-data');
      if (!el) return;
      var data = JSON.parse(el.textContent);
      if (!data.length) return;
      var canvas = document.getElementById('activityDistChart');
      var ctx = canvas.getContext('2d');
      var W = canvas.width;
      var rowH = 34;
      var labelW = 140;
      var barLeft = labelW + 8;
      var barRight = W - 80;
      var barMaxW = barRight - barLeft;
      var padTop = 8;

      var maxCount = data[0].count;

      // Set canvas height based on data
      canvas.height = data.length * rowH + padTop;

      function roundRect(x, y, w, h, r) {
        ctx.beginPath();
        ctx.moveTo(x + r, y);
        ctx.lineTo(x + w - r, y);
        ctx.quadraticCurveTo(x + w, y, x + w, y + r);
        ctx.lineTo(x + w, y + h - r);
        ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
        ctx.lineTo(x + r, y + h);
        ctx.quadraticCurveTo(x, y + h, x, y + h - r);
        ctx.lineTo(x, y + r);
        ctx.quadraticCurveTo(x, y, x + r, y);
        ctx.closePath();
      }

      data.forEach(function(entry, i) {
        var y = padTop + i * rowH;
        var pct = entry.count / maxCount;
        var barW = pct * barMaxW;

        // Label
        ctx.fillStyle = '#374151';
        ctx.font = '13px sans-serif';
        ctx.textAlign = 'right';
        ctx.textBaseline = 'middle';
        ctx.fillText(entry.media_type, labelW - 6, y + rowH / 2);

        // Bar background
        ctx.fillStyle = '#f3f4f6';
        roundRect(barLeft, y + 4, barMaxW, rowH - 8, 4);
        ctx.fill();

        // Bar fill — green (top) to red (bottom)
        var hue = 120 * (1 - i / (data.length - 1 || 1));
        ctx.fillStyle = 'hsl(' + hue + ', 65%, 50%)';
        roundRect(barLeft, y + 4, Math.max(barW, 2), rowH - 8, 4);
        ctx.fill();

        // Count + percentage label on the right
        ctx.fillStyle = '#374151';
        ctx.font = 'bold 13px sans-serif';
        ctx.textAlign = 'left';
        ctx.textBaseline = 'middle';
        ctx.fillText(entry.count + ' (' + entry.pct + '%)', barRight + 6, y + rowH / 2);
      });
    })();
    </script>
    {% else %}
    <p class="text-muted">No activity data found.</p>
    {% endif %}
  </div>
</div>
