{% extends "base.html" %}
{% load static %}
{% block title %}Dashboard — Fossilrepo{% endblock %}

{% block extra_head %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4/dist/chart.umd.min.js"></script>
{% endblock %}

{% block content %}
<div class="mb-6">
  <h1 class="text-2xl font-bold text-gray-100">Dashboard</h1>
  <p class="mt-1 text-sm text-gray-400">Welcome back, {{ user.get_full_name|default:user.username }}</p>
</div>

<!-- Stats cards -->
<div class="grid grid-cols-2 gap-4 sm:grid-cols-4 mb-6">
  <div class="rounded-lg bg-gray-800 border border-gray-700 p-4 shadow-sm hover:border-gray-600 transition-colors">
    <div class="text-2xl font-bold text-gray-100">{{ total_projects }}</div>
    <div class="text-xs text-gray-500 mt-1">Projects</div>
  </div>
  <div class="rounded-lg bg-gray-800 border border-gray-700 p-4 shadow-sm hover:border-gray-600 transition-colors">
    <div class="text-2xl font-bold text-gray-100">{{ total_checkins|default:"0" }}</div>
    <div class="text-xs text-gray-500 mt-1">Total Checkins</div>
  </div>
  <div class="rounded-lg bg-gray-800 border border-gray-700 p-4 shadow-sm hover:border-gray-600 transition-colors">
    <div class="text-2xl font-bold text-gray-100">{{ total_tickets|default:"0" }}</div>
    <div class="text-xs text-gray-500 mt-1">Tickets</div>
  </div>
  <div class="rounded-lg bg-gray-800 border border-gray-700 p-4 shadow-sm hover:border-gray-600 transition-colors">
    <div class="text-2xl font-bold text-gray-100">{{ total_wiki|default:"0" }}</div>
    <div class="text-xs text-gray-500 mt-1">Wiki Pages</div>
  </div>
</div>

<!-- Activity heatmap (all projects, last year) -->
{% if heatmap_json %}
<div class="rounded-lg bg-gray-800 border border-gray-700 p-4 mb-6 shadow-sm">
  <h3 class="text-sm font-medium text-gray-300 mb-3">Activity (last year)</h3>
  <div id="heatmap" class="overflow-x-auto"></div>
  <div class="flex items-center justify-end gap-1 mt-2 text-xs text-gray-500">
    <span>Less</span>
    <span class="inline-block w-3 h-3 rounded-sm bg-gray-700"></span>
    <span class="inline-block w-3 h-3 rounded-sm" style="background:#14532d"></span>
    <span class="inline-block w-3 h-3 rounded-sm" style="background:#166534"></span>
    <span class="inline-block w-3 h-3 rounded-sm" style="background:#22c55e"></span>
    <span class="inline-block w-3 h-3 rounded-sm" style="background:#4ade80"></span>
    <span>More</span>
  </div>
</div>
{% endif %}

<div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
  <!-- Main column -->
  <div class="lg:col-span-2 space-y-6">
    {% if system_activity_json and system_activity_json != "[]" %}
    <!-- System-wide activity chart -->
    <div class="rounded-lg bg-gray-800 border border-gray-700 p-4 shadow-sm">
      <h3 class="text-sm font-medium text-gray-300 mb-3">System Activity (26 weeks)</h3>
      <div style="height: 140px;">
        <canvas id="systemChart"></canvas>
      </div>
    </div>
    {% endif %}

    {% if recent_across_all %}
    <!-- Recent activity across all projects -->
    <div class="rounded-lg bg-gray-800 border border-gray-700 shadow-sm">
      <div class="px-4 py-3 border-b border-gray-700">
        <h3 class="text-sm font-medium text-gray-300">Recent Activity</h3>
      </div>
      <div class="divide-y divide-gray-700">
        {% for item in recent_across_all %}
        <div class="px-4 py-3 flex items-start gap-3 hover:bg-gray-700/30 transition-colors">
          <div class="flex-shrink-0 mt-1">
            <div class="w-2.5 h-2.5 rounded-full bg-brand"></div>
          </div>
          <div class="flex-1 min-w-0">
            <a href="{% url 'fossil:checkin_detail' slug=item.project.slug checkin_uuid=item.entry.uuid %}"
               class="text-sm text-gray-200 hover:text-brand-light">{{ item.entry.comment|truncatechars:70 }}</a>
            <div class="mt-0.5 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-xs text-gray-500">
              <a href="{% url 'projects:detail' slug=item.project.slug %}" class="text-brand-light hover:text-brand">{{ item.project.name }}</a>
              <a href="{% url 'fossil:user_activity' slug=item.project.slug username=item.entry.user %}" class="hover:text-gray-300">{{ item.entry.user }}</a>
              <a href="{% url 'fossil:checkin_detail' slug=item.project.slug checkin_uuid=item.entry.uuid %}" class="font-mono text-brand-light hover:text-brand">{{ item.entry.uuid|truncatechars:10 }}</a>
              <span>{{ item.entry.timestamp|timesince }} ago</span>
            </div>
          </div>
        </div>
        {% endfor %}
      </div>
    </div>
    {% elif not system_activity_json or system_activity_json == "[]" %}
    <!-- Empty state when no activity exists -->
    <div class="rounded-lg bg-gray-800 border border-gray-700 p-8 text-center">
      <svg class="mx-auto h-12 w-12 text-gray-600" fill="none" viewBox="0 0 24 24" stroke-width="1" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
      <h3 class="mt-2 text-sm font-semibold text-gray-300">No recent activity</h3>
      <p class="mt-1 text-sm text-gray-500">Activity from your projects will appear here once repositories have checkins.</p>
    </div>
    {% endif %}
  </div>

  <!-- Sidebar -->
  <div class="space-y-4">
    <!-- Quick links -->
    {% if perms.projects.view_project %}
    <a href="{% url 'projects:list' %}" class="block rounded-lg bg-gray-800 border border-gray-700 p-4 shadow-sm hover:border-brand hover:shadow-md transition-all">
      <h3 class="text-sm font-semibold text-gray-100">Projects</h3>
      <p class="mt-1 text-xs text-gray-500">Manage projects and team access</p>
    </a>
    {% endif %}
    {% if perms.organization.view_team %}
    <a href="{% url 'organization:team_list' %}" class="block rounded-lg bg-gray-800 border border-gray-700 p-4 shadow-sm hover:border-brand hover:shadow-md transition-all">
      <h3 class="text-sm font-semibold text-gray-100">Teams</h3>
      <p class="mt-1 text-xs text-gray-500">Organize members into teams</p>
    </a>
    {% endif %}
    {% if perms.pages.view_page %}
    <a href="{% url 'pages:list' %}" class="block rounded-lg bg-gray-800 border border-gray-700 p-4 shadow-sm hover:border-brand hover:shadow-md transition-all">
      <h3 class="text-sm font-semibold text-gray-100">FossilRepo Docs</h3>
      <p class="mt-1 text-xs text-gray-500">Guides, runbooks, documentation</p>
    </a>
    {% endif %}
    {% if perms.organization.view_organization %}
    <a href="{% url 'organization:settings' %}" class="block rounded-lg bg-gray-800 border border-gray-700 p-4 shadow-sm hover:border-brand hover:shadow-md transition-all">
      <h3 class="text-sm font-semibold text-gray-100">Settings</h3>
      <p class="mt-1 text-xs text-gray-500">Organization configuration</p>
    </a>
    {% endif %}
    {% if user.is_staff %}
    <a href="{% url 'admin:index' %}" class="block rounded-lg bg-gray-800 border border-gray-700 p-4 shadow-sm hover:border-brand hover:shadow-md transition-all">
      <h3 class="text-sm font-semibold text-gray-100">Admin</h3>
      <p class="mt-1 text-xs text-gray-500">Users, groups, permissions</p>
    </a>
    {% endif %}
  </div>
</div>

{% if system_activity_json and system_activity_json != "[]" %}
<script>
  new Chart(document.getElementById('systemChart').getContext('2d'), {
    type: 'bar',
    data: {
      labels: {{ system_activity_json|safe }}.map((_, i) => ''),
      datasets: [{
        data: {{ system_activity_json|safe }},
        backgroundColor: '#DC394C',
        borderRadius: 2,
        barPercentage: 0.8,
        categoryPercentage: 0.9,
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: { legend: { display: false }, tooltip: {
        callbacks: { title: (items) => { const w = 25 - items[0].dataIndex; return w === 0 ? 'This week' : w + ' week' + (w > 1 ? 's' : '') + ' ago'; } }
      }},
      scales: {
        x: { display: false, grid: { display: false } },
        y: { display: false, grid: { display: false }, beginAtZero: true }
      }
    }
  });
</script>
{% endif %}

{% if heatmap_json %}
<script>
(function() {
  var data = {{ heatmap_json|safe }};
  var counts = {};
  data.forEach(function(d) { counts[d.date] = d.count; });

  // Generate 365 days ending today
  var today = new Date();
  var days = [];
  for (var i = 364; i >= 0; i--) {
    var d = new Date(today);
    d.setDate(d.getDate() - i);
    var key = d.toISOString().slice(0, 10);
    days.push({ date: key, count: counts[key] || 0, dow: d.getDay() });
  }

  var cellSize = 12;
  var cellGap = 2;
  var step = cellSize + cellGap;
  var labelWidth = 28;
  var monthHeight = 16;

  // The first day may not be Sunday (dow=0). We need to offset the first column.
  var startDow = days[0].dow;
  var totalSlots = days.length + startDow;
  var weeks = Math.ceil(totalSlots / 7);
  var svgWidth = labelWidth + weeks * step;
  var svgHeight = monthHeight + 7 * step;

  var svg = '<svg width="' + svgWidth + '" height="' + svgHeight + '" class="text-gray-500">';

  // Day-of-week labels (Mon, Wed, Fri)
  var dayLabels = ['', 'Mon', '', 'Wed', '', 'Fri', ''];
  for (var di = 0; di < dayLabels.length; di++) {
    if (dayLabels[di]) {
      svg += '<text x="0" y="' + (monthHeight + di * step + cellSize - 2) + '" fill="currentColor" font-size="9" font-family="sans-serif">' + dayLabels[di] + '</text>';
    }
  }

  // Month labels -- find the first occurrence of each month in the grid
  var monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  var lastMonth = -1;
  for (var mi = 0; mi < days.length; mi++) {
    var monthNum = parseInt(days[mi].date.slice(5, 7), 10) - 1;
    if (monthNum !== lastMonth) {
      lastMonth = monthNum;
      var weekIdx = Math.floor((mi + startDow) / 7);
      var x = labelWidth + weekIdx * step;
      svg += '<text x="' + x + '" y="10" fill="currentColor" font-size="9" font-family="sans-serif">' + monthNames[monthNum] + '</text>';
    }
  }

  // Color scale
  function getColor(count) {
    if (count === 0) return '#1f2937';
    if (count <= 2) return '#14532d';
    if (count <= 5) return '#166534';
    if (count <= 10) return '#22c55e';
    return '#4ade80';
  }

  // Render cells
  for (var ci = 0; ci < days.length; ci++) {
    var day = days[ci];
    var wk = Math.floor((ci + startDow) / 7);
    var dow = (ci + startDow) % 7;
    var cx = labelWidth + wk * step;
    var cy = monthHeight + dow * step;
    var color = getColor(day.count);
    svg += '<rect x="' + cx + '" y="' + cy + '" width="' + cellSize + '" height="' + cellSize + '" rx="2" fill="' + color + '">';
    svg += '<title>' + day.date + ': ' + day.count + ' commit' + (day.count !== 1 ? 's' : '') + '</title>';
    svg += '</rect>';
  }

  svg += '</svg>';
  document.getElementById('heatmap').innerHTML = svg;
})();
</script>
{% endif %}
{% endblock %}
