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

      canvas.height = data.length * rowH + padTop;

      var maxCount = data[0].count;

      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;

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

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

        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();

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