{% from "_macros.html" import icon %}
{#
  The rebuild's state, swapped into itself.

  It polls while a rebuild is running and stops when it is not: `hx-trigger` is
  only emitted in the running branch, so the last frame is a plain fragment with
  nothing attached to it. A poller that kept going after the work finished would
  be a request every two seconds, forever, on a page somebody left open.

  `hx-target="this"` and `hx-swap="outerHTML"` are both spelled out. This lives
  inside a form on the page, and htmx resolves `hx-target` by walking up the DOM
  -- an element in there that fetches and names no target aims at whatever an
  ancestor said, which is the bug the jobs chip had.
#}
<div id="index-progress"
     {% if progress.running %}
     hx-get="/admin/extraction/progress"
     hx-trigger="every 2s"
     hx-target="this"
     hx-swap="outerHTML"
     {% endif %}>

  {% if progress.running %}
  <div class="alert">
    {{ icon("clock", "icon--sm") }}
    <span>
      Rebuilding: {{ progress.done }} of {{ progress.total }} records
      ({{ progress.percent }}%), {{ progress.written }} pieces written.
      You can leave this page — it carries on.
    </span>
  </div>
  {% elif progress.error %}
  <div class="alert alert--error">
    {{ icon("warning", "icon--sm") }} <span>{{ progress.error }}</span>
  </div>
  {% elif progress.total %}
  <div class="alert alert--success">
    {{ icon("check", "icon--sm") }}
    <span>
      Finished: {{ progress.done }} records, {{ progress.written }} pieces indexed.
    </span>
  </div>
  {% endif %}

  <p class="field__hint">
    {% if counts %}
    Indexed now:
    {% for kind, count in counts | dictsort %}
    <strong>{{ count }}</strong> from {{ kind }}s{{ "," if not loop.last }}
    {% endfor %}.
    {% else %}
    Nothing is indexed yet.
    {% endif %}
  </p>

  {% if ready %}
  <button class="btn" type="button"
          hx-post="/admin/extraction/rebuild"
          hx-target="#index-progress"
          hx-swap="outerHTML"
          {{ 'disabled' if progress.running }}>
    {{ icon("sparkle", "icon--sm") }}
    {{ "Rebuilding…" if progress.running else "Rebuild the index" }}
  </button>
  {% endif %}
</div>
