{% extends "pxy_dashboard/partials/base.html" %}
{% load static %}

{% block title %}Sites · Recent runs{% endblock title %}

{% block pagetitle %}
  {% include "pxy_dashboard/partials/page-title.html" with pagetitle="Sites" title="Recent runs" %}
{% endblock pagetitle %}

{% block content %}
<div class="row">
  <div class="col-12">
    <div class="card">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <div>
            <h4 class="header-title mb-0">Latest runs</h4>
            <small class="text-muted">Click a card to open the interactive viewer</small>
          </div>
          <div class="d-flex align-items-center">
            <label class="me-2">Limit</label>
            <select id="limitSel" class="form-select form-select-sm" style="width:auto">
              <option>6</option><option selected>12</option><option>24</option><option>36</option>
            </select>
          </div>
        </div>

        <div id="runsGrid" class="row g-3"></div>

        <div id="runsEmpty" class="text-center text-muted py-5 d-none">
          <div class="mb-2">No runs yet</div>
          <small>Trigger a run via <code>/api/sites/search</code> and refresh.</small>
        </div>
      </div>
    </div>
  </div>
</div>
{% endblock content %}

{% block extra_js %}
<script>
(function(){
  const grid   = document.getElementById('runsGrid');
  const empty  = document.getElementById('runsEmpty');
  const limitSel = document.getElementById('limitSel');

  limitSel.addEventListener('change', loadRuns);
  loadRuns();

  function asAbs(url) {
    if (!url) return null;
    if (url.startsWith('http')) return url;
    return window.location.origin + url;
  }

  async function loadRuns() {
    grid.innerHTML = '';
    empty.classList.add('d-none');
    const limit = parseInt(limitSel.value || '12', 10);
    const resp = await fetch(`/api/sites/runs/recent?limit=${limit}`);
    if (!resp.ok) { empty.classList.remove('d-none'); return; }
    const data = await resp.json();
    const items = (data && data.items) || [];
    if (!items.length) { empty.classList.remove('d-none'); return; }

    items.forEach(item => {
      const preview = asAbs(item.map_url) || asAbs((item.download||{}).main); // fallback
      const title   = `${item.business || '—'} @ ${item.city || '—'}`;
      const when    = new Date(item.created_at).toLocaleString();

      const card = document.createElement('div');
      card.className = 'col-12 col-sm-6 col-lg-4';
      card.innerHTML = `
        <div class="card h-100 shadow-sm">
          <div class="ratio ratio-4x3 bg-light">
            ${preview ? `<img src="${preview}" class="card-img-top object-fit-cover" alt="preview">` : `<div class="d-flex align-items-center justify-content-center text-muted">No preview</div>`}
          </div>
          <div class="card-body">
            <h5 class="card-title mb-1" style="min-height: 2.2rem">${title}</h5>
            <div class="text-muted small mb-2">${when}</div>
            <div class="d-flex gap-2 flex-wrap">
              <a class="btn btn-primary btn-sm" href="/apps/sites/viewer?search_id=${encodeURIComponent(item.search_id)}">
                Open viewer
              </a>
              ${item.download?.main ? `<a class="btn btn-outline-secondary btn-sm" href="${item.download.main}" target="_blank">Download PNG</a>` : ``}
              ${item.geojson?.candidates ? `<a class="btn btn-outline-secondary btn-sm" href="${item.geojson.candidates}" target="_blank">Candidates GeoJSON</a>` : ``}
            </div>
          </div>
        </div>
      `;
      grid.appendChild(card);
    });
  }
})();
</script>
{% endblock extra_js %}
