{% extends "base.html" %}
{% block body %}
<div class="toolbar">
  <div>
    <a class="muted" href="/raw">← Raw-посты</a>
    <h1>Raw #{{ post.id }}</h1>
    <div class="muted">
      <a href="{{ post.original_url }}" target="_blank">{{ post.source_name }}</a>
      · {{ post.source_platform }}
      · #{{ post.source_tag or "—" }}
      {% if post.posted_at_fmt %}· пост VK: {{ post.posted_at_fmt }}{% endif %}
    </div>
  </div>
  <span class="pill {{ post.stage.class }}" title="{{ post.stage.key }}">{{ post.stage.label }}</span>
</div>

<div class="detail-grid">
  <section class="panel">
    <div class="media-strip detail-media">
      {% for m in post.media_items %}
        {% if m.type == "photo" and m.url %}
        <button class="media-thumb detail-thumb" type="button" data-gallery-src="{{ m.url }}" data-gallery-title="#{{ post.id }} · фото {{ loop.index }}" title="{{ m.status }}">
          <img src="{{ m.url }}" alt="photo">
        </button>
        {% elif m.url %}
        <a class="media-thumb detail-thumb media-video" href="{{ m.url }}" target="_blank" title="{{ m.error or m.status }}">
          <span>▶</span>
        </a>
        {% endif %}
      {% endfor %}
    </div>
    {% if post.media_count %}<div class="muted media-count">{{ post.media_count }} медиа</div>{% endif %}
    <div class="raw-full-text detail-text">{{ post.raw_text }}</div>
    <div class="post-meta">Загружен парсером: {{ post.created_at_fmt }}</div>
  </section>

  <aside class="panel side-panel" id="ai">
    <h2>AI-оценка</h2>
    <a class="ai-badge detail-ai {{ post.ai_badge.class }}" href="#ai" title="{{ post.ai_badge.reason or post.ai_badge.sublabel }}">
      <span>{{ post.ai_badge.label }}</span>
      <small>{{ post.ai_badge.sublabel }}</small>
    </a>
    <dl class="kv">
      <dt>Статус</dt>
      <dd>{{ post.qualification_status or "pending" }}</dd>
      <dt>Решение модели</dt>
      <dd>{{ post.qualification_model_decision or post.qualification_decision or "—" }}</dd>
      <dt>Итог по порогу</dt>
      <dd>{{ post.qualification_decision or "—" }}</dd>
      <dt>Причина</dt>
      <dd>{{ post.qualification_reason or "—" }}</dd>
      <dt>Reject tag</dt>
      <dd>{{ post.qualification_reject_tag or "—" }}</dd>
      <dt>Модель</dt>
      <dd>{{ post.qualification_model or post.batch_model or "—" }}</dd>
      <dt>Проверен</dt>
      <dd>{{ post.qualified_at_fmt or "—" }}</dd>
      <dt>Batch</dt>
      <dd>{% if post.qualification_batch_id %}#{{ post.qualification_batch_id }}{% else %}—{% endif %}</dd>
      <dt>Токены</dt>
      <dd>{{ post.batch_total_tokens or "—" }}</dd>
    </dl>
  </aside>
</div>

<section class="panel" id="rewrite">
  <div class="toolbar">
    <div>
      <h2>Рерайт</h2>
      <div class="muted">Готовый текст для будущей редакторской проверки.</div>
    </div>
    <span class="pill {% if post.rewrite_status == 'ready' %}ok{% elif post.rewrite_status == 'failed' %}bad{% elif post.rewrite_status == 'processing' %}warn{% endif %}">
      {{ post.rewrite_status or "pending" }}
    </span>
  </div>
  {% if post.rewritten_text %}
  <div class="rewrite-text">{{ post.rewritten_text }}</div>
  {% else %}
  <div class="muted">Рерайт ещё не готов.</div>
  {% endif %}
  <dl class="kv kv-wide rewrite-meta">
    <dt>Категория</dt><dd>{{ post.rewrite_category or "—" }}</dd>
    <dt>Хэштеги</dt>
    <dd>
      {% if post.rewrite_category_tag or post.rewrite_source_tag %}
        #{{ post.rewrite_category_tag or "—" }} #{{ post.rewrite_source_tag or "—" }}
      {% else %}
        —
      {% endif %}
    </dd>
    <dt>Заметка</dt><dd>{{ post.rewrite_notes or "—" }}</dd>
    <dt>Модель</dt><dd>{{ post.rewrite_model or post.writer_batch_model or "—" }}</dd>
    <dt>Готов</dt><dd>{{ post.rewritten_at_fmt or "—" }}</dd>
    <dt>Batch</dt><dd>{% if post.rewrite_batch_id %}#{{ post.rewrite_batch_id }}{% else %}—{% endif %}</dd>
    <dt>Токены</dt><dd>{{ post.writer_total_tokens or "—" }}</dd>
    <dt>Стоимость</dt><dd>{% if post.writer_estimated_cost_usd %}${{ post.writer_estimated_cost_usd }}{% else %}—{% endif %}</dd>
  </dl>
</section>

{% if post.qualification_batch_id %}
<details class="panel">
  <summary><strong>Технический ответ AI</strong></summary>
  <dl class="kv kv-wide">
    <dt>Provider</dt><dd>{{ post.qualification_provider or "—" }}</dd>
    <dt>Batch status</dt><dd>{{ post.batch_status or "—" }}</dd>
    <dt>Создан</dt><dd>{{ post.batch_created_at_fmt or "—" }}</dd>
    <dt>Завершён</dt><dd>{{ post.batch_completed_at_fmt or "—" }}</dd>
    <dt>Постов в batch</dt><dd>{{ post.batch_posts_count or "—" }}</dd>
    <dt>Accepted / rejected / maybe</dt>
    <dd>{{ post.batch_accepted_count or 0 }} / {{ post.batch_rejected_count or 0 }} / {{ post.batch_maybe_count or 0 }}</dd>
    <dt>Токены</dt>
    <dd>{{ post.batch_prompt_tokens or 0 }} / {{ post.batch_completion_tokens or 0 }} / {{ post.batch_total_tokens or 0 }}</dd>
    <dt>Стоимость</dt><dd>{% if post.batch_estimated_cost_usd %}${{ post.batch_estimated_cost_usd }}{% else %}—{% endif %}</dd>
    <dt>Ошибка</dt><dd>{{ post.batch_error or "—" }}</dd>
  </dl>
  {% if post.batch_prompt_text %}
  <details class="nested-details">
    <summary>Использованный prompt квалификатора</summary>
    <pre class="prompt-box">{{ post.batch_prompt_text }}</pre>
  </details>
  {% endif %}
  <pre class="json-box">{{ post.batch_response_pretty or "{}" }}</pre>
</details>
{% endif %}

{% if post.rewrite_batch_id %}
<details class="panel">
  <summary><strong>Технический ответ AI-райтера</strong></summary>
  <dl class="kv kv-wide">
    <dt>Provider</dt><dd>{{ post.rewrite_provider or "—" }}</dd>
    <dt>Batch status</dt><dd>{{ post.writer_batch_status or "—" }}</dd>
    <dt>Создан</dt><dd>{{ post.writer_batch_created_at_fmt or "—" }}</dd>
    <dt>Завершён</dt><dd>{{ post.writer_batch_completed_at_fmt or "—" }}</dd>
    <dt>Постов в batch</dt><dd>{{ post.writer_batch_posts_count or "—" }}</dd>
    <dt>Ready / failed</dt><dd>{{ post.writer_batch_ready_count or 0 }} / {{ post.writer_batch_failed_count or 0 }}</dd>
    <dt>Токены</dt>
    <dd>{{ post.writer_prompt_tokens or 0 }} / {{ post.writer_completion_tokens or 0 }} / {{ post.writer_total_tokens or 0 }}</dd>
    <dt>Стоимость</dt><dd>{% if post.writer_estimated_cost_usd %}${{ post.writer_estimated_cost_usd }}{% else %}—{% endif %}</dd>
    <dt>Ошибка</dt><dd>{{ post.writer_batch_error or "—" }}</dd>
  </dl>
  {% if post.writer_batch_prompt_text %}
  <details class="nested-details">
    <summary>Использованный prompt райтера</summary>
    <pre class="prompt-box">{{ post.writer_batch_prompt_text }}</pre>
  </details>
  {% endif %}
  <pre class="json-box">{{ post.writer_batch_response_pretty or "{}" }}</pre>
</details>
{% endif %}

<div class="gallery-modal" id="galleryModal" aria-hidden="true">
  <button class="gallery-close" type="button" aria-label="Закрыть">×</button>
  <button class="gallery-nav gallery-prev" type="button" aria-label="Назад">‹</button>
  <img id="galleryImage" src="" alt="">
  <button class="gallery-nav gallery-next" type="button" aria-label="Вперёд">›</button>
  <div class="gallery-title" id="galleryTitle"></div>
</div>
<script>
(() => {
  const items = Array.from(document.querySelectorAll("[data-gallery-src]"));
  const modal = document.getElementById("galleryModal");
  const image = document.getElementById("galleryImage");
  const title = document.getElementById("galleryTitle");
  let index = 0;

  function show(nextIndex) {
    if (!items.length) return;
    index = (nextIndex + items.length) % items.length;
    const item = items[index];
    image.src = item.dataset.gallerySrc;
    title.textContent = item.dataset.galleryTitle || "";
    modal.classList.add("open");
    modal.setAttribute("aria-hidden", "false");
  }
  function close() {
    modal.classList.remove("open");
    modal.setAttribute("aria-hidden", "true");
    image.src = "";
  }

  items.forEach((item, i) => item.addEventListener("click", () => show(i)));
  modal.querySelector(".gallery-close").addEventListener("click", close);
  modal.querySelector(".gallery-prev").addEventListener("click", () => show(index - 1));
  modal.querySelector(".gallery-next").addEventListener("click", () => show(index + 1));
  modal.addEventListener("click", (event) => { if (event.target === modal) close(); });
  document.addEventListener("keydown", (event) => {
    if (!modal.classList.contains("open")) return;
    if (event.key === "Escape") close();
    if (event.key === "ArrowLeft") show(index - 1);
    if (event.key === "ArrowRight") show(index + 1);
  });
})();
</script>
{% endblock %}
