{% extends "base.html" %}
{% block content %}

<section class="card">
  <h1>Job <code>{{ job_id }}</code></h1>
  <p>{{ meta.filename }}</p>
  <p>
    Status: <span id="status" class="status status-{{ meta.status }}">{{ meta.status }}</span>
    <span id="message" class="muted"></span>
  </p>
  <p class="muted">
    Target render: {{ meta.target_width }} × {{ meta.target_height }} px ·
    Pages found: <span id="pagecount">{{ meta.pages }}</span> ·
    Articles found: <span id="artcount">{{ articles|length }}</span>
  </p>
  <p>
    <a class="btn" href="{{ url_for('download_zip', job_id=job_id) }}">⬇ Download all (zip)</a>
  </p>
</section>

{% if articles %}
<section class="card">
  <h2>Articles</h2>
  <div class="grid">
    {% for a in articles %}
    <div class="art">
      <div class="art-img">
        {% if a.has_image %}
        <img src="{{ url_for('article_image', job_id=job_id, art_name=a.name) }}" alt="">
        {% endif %}
      </div>
      <div class="art-meta">
        <strong>{{ a.name }}</strong>
        <span class="muted">page {{ a.page }}{% if a.grouped_by %} · grouped by {{ a.grouped_by }}{% endif %}</span>
        {% if a.dateline %}<div class="dateline">{{ a.dateline }}</div>{% endif %}
        {% if a.headline_preview %}<div class="head">{{ a.headline_preview }}</div>{% endif %}
        <div class="row">
          {% if a.has_image %}<a href="{{ url_for('article_image', job_id=job_id, art_name=a.name) }}">image</a>{% endif
          %}
          {% if a.has_text %}<a href="{{ url_for('article_text', job_id=job_id, art_name=a.name) }}">text</a>{% endif %}
        </div>
      </div>
    </div>
    {% endfor %}
  </div>
</section>
{% endif %}

<script>
  const status = document.getElementById('status');
  const msg = document.getElementById('message');
  const pagecount = document.getElementById('pagecount');
  const artcount = document.getElementById('artcount');

  async function poll() {
    if (status.textContent === 'done' || status.textContent === 'error') return;
    try {
      const r = await fetch("{{ url_for('job_status', job_id=job_id) }}");
      const data = await r.json();
      status.textContent = data.status || 'unknown';
      status.className = 'status status-' + (data.status || 'unknown');
      msg.textContent = data.message ? '· ' + data.message : '';
      if (data.meta) {
        if (data.meta.pages) pagecount.textContent = data.meta.pages;
        if (data.meta.articles) artcount.textContent = data.meta.articles;
      }
      if (data.status === 'done') {
        setTimeout(() => location.reload(), 800);
        return;
      }
    } catch (e) { }
    setTimeout(poll, 1500);
  }
  poll();
</script>

{% endblock %}