<!doctype html>
<html lang="en">
  {% from "partials/header.html" import header with context %}
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>{{ app_name }} v{{ app_version }} - Queue Preview</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
    />
    <!-- Favicon -->
    <link rel="icon" href="/static/FenLiu.png" type="image/png" />
    <link rel="apple-touch-icon" href="/static/FenLiu.png" />
    <style>
      .status-badge {
        padding: 0.25rem 0.75rem;
        border-radius: 9999px;
        font-size: 0.875rem;
        font-weight: 500;
      }
      .status-pending {
        background-color: #fef3c7;
        color: #92400e;
      }
      .status-reserved {
        background-color: #bfdbfe;
        color: #1e3a8a;
      }
      .status-delivered {
        background-color: #dcfce7;
        color: #166534;
      }
      .status-error {
        background-color: #fee2e2;
        color: #991b1b;
      }
    </style>
  </head>
  <body class="bg-gray-50 min-h-screen">
    {{ header('queue') }}

    <main class="container mx-auto px-4 py-8 max-w-7xl">
      <div class="mb-8">
        <h2 class="text-3xl font-bold text-gray-800">
          <i class="fas fa-list mr-3 text-indigo-600"></i>Queue Preview
        </h2>
        <p class="text-gray-600 mt-2">
          Curated Queue status and post management. Shows all approved posts and their export eligibility.
        </p>
      </div>

      <!-- Queue Status Cards -->
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <button
          onclick="filterByStatus('pending')"
          class="bg-white rounded-lg shadow-md p-6 border-l-4 border-amber-400 cursor-pointer transition-all duration-200 hover:shadow-lg hover:scale-105 {% if current_status_filter == 'pending' %}ring-2 ring-amber-400{% endif %}"
        >
          <div class="flex items-center justify-between">
            <div>
              <p class="text-gray-600 text-sm font-medium">Pending</p>
              <p class="text-3xl font-bold text-amber-600">
                {{ all_time_pending }}
              </p>
              <p class="text-xs text-gray-500 mt-1">{{ pending_count }} active</p>
            </div>
            <i
              class="fas fa-hourglass-half text-amber-400 text-3xl opacity-20"
            ></i>
          </div>
        </button>

        <button
          onclick="filterByStatus('reserved')"
          class="bg-white rounded-lg shadow-md p-6 border-l-4 border-blue-400 cursor-pointer transition-all duration-200 hover:shadow-lg hover:scale-105 {% if current_status_filter == 'reserved' %}ring-2 ring-blue-400{% endif %}"
        >
          <div class="flex items-center justify-between">
            <div>
              <p class="text-gray-600 text-sm font-medium">Reserved</p>
              <p class="text-3xl font-bold text-blue-600">
                {{ reserved_count }}
              </p>
            </div>
            <i class="fas fa-lock text-blue-400 text-3xl opacity-20"></i>
          </div>
        </button>

        <button
          onclick="filterByStatus('delivered')"
          class="bg-white rounded-lg shadow-md p-6 border-l-4 border-green-400 cursor-pointer transition-all duration-200 hover:shadow-lg hover:scale-105 {% if current_status_filter == 'delivered' %}ring-2 ring-green-400{% endif %}"
        >
          <div class="flex items-center justify-between">
            <div>
              <p class="text-gray-600 text-sm font-medium">Delivered</p>
              <p class="text-3xl font-bold text-green-600">
                {{ all_time_delivered }}
              </p>
              <p class="text-xs text-gray-500 mt-1">{{ delivered_count }} active</p>
            </div>
            <i
              class="fas fa-check-circle text-green-400 text-3xl opacity-20"
            ></i>
          </div>
        </button>

        <button
          onclick="filterByStatus('error')"
          class="bg-white rounded-lg shadow-md p-6 border-l-4 border-red-400 cursor-pointer transition-all duration-200 hover:shadow-lg hover:scale-105 {% if current_status_filter == 'error' %}ring-2 ring-red-400{% endif %}"
        >
          <div class="flex items-center justify-between">
            <div>
              <p class="text-gray-600 text-sm font-medium">Errors</p>
              <p class="text-3xl font-bold text-red-600">{{ error_count }}</p>
            </div>
            <i
              class="fas fa-exclamation-circle text-red-400 text-3xl opacity-20"
            ></i>
          </div>
        </button>
      </div>

      <!-- Flash message area -->
      <div id="flash" class="hidden mb-4"></div>

      <!-- Posts List -->
      <div class="bg-white rounded-lg shadow-md p-6">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-6">
          <h3 class="text-xl font-bold text-gray-800">
            <i class="fas fa-inbox mr-2 text-indigo-500"></i>Approved Posts
          </h3>
          <div class="flex flex-col sm:flex-row gap-3 mt-4 sm:mt-0">
            <!-- Status Filter -->
            <div class="flex items-center gap-2">
              <label class="text-sm font-medium text-gray-700">Filter:</label>
              <select
                id="statusFilter"
                class="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                onchange="applyFilterSort()"
              >
                <option value="all" {% if current_status_filter == "all" %}selected{% endif %}>All</option>
                <option value="pending" {% if current_status_filter == "pending" %}selected{% endif %}>Pending</option>
                <option value="reserved" {% if current_status_filter == "reserved" %}selected{% endif %}>Reserved</option>
                <option value="delivered" {% if current_status_filter == "delivered" %}selected{% endif %}>Delivered</option>
                <option value="error" {% if current_status_filter == "error" %}selected{% endif %}>Errors</option>
              </select>
            </div>

            <!-- Sort By -->
            <div class="flex items-center gap-2">
              <label class="text-sm font-medium text-gray-700">Sort:</label>
              <select
                id="sortBy"
                class="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                onchange="applyFilterSort()"
              >
                <option value="reviewed_at" {% if current_sort_by == "reviewed_at" %}selected{% endif %}>Recently Reviewed</option>
                <option value="spam_score" {% if current_sort_by == "spam_score" %}selected{% endif %}>Spam Score</option>
                <option value="author" {% if current_sort_by == "author" %}selected{% endif %}>Author</option>
                <option value="errored_at" {% if current_sort_by == "errored_at" %}selected{% endif %}>Error Date</option>
                <option value="reserved_at" {% if current_sort_by == "reserved_at" %}selected{% endif %}>Reserved Date</option>
              </select>
            </div>

            <!-- Sort Order -->
            <div class="flex items-center gap-2">
              <button
                id="sortOrder"
                class="px-3 py-2 border border-gray-300 rounded-md text-sm hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 transition"
                onclick="toggleSortOrder()"
                title="Toggle sort order"
              >
                {% if current_sort_order == "desc" %}
                <i class="fas fa-arrow-down-z-a mr-1"></i>Desc
                {% else %}
                <i class="fas fa-arrow-up-a-z mr-1"></i>Asc
                {% endif %}
              </button>
            </div>

            <!-- Cleanup Buttons -->
            <div class="flex items-center gap-2">
              <button
                id="cleanupBtn"
                onclick="cleanupDeliveredPosts()"
                class="px-3 py-2 border border-gray-300 rounded-md text-sm bg-blue-50 text-blue-700 hover:bg-blue-100 focus:outline-none focus:ring-2 focus:ring-blue-500 transition"
                title="Delete delivered posts older than 7 days"
              >
                <i class="fas fa-trash mr-1"></i>Purge old delivered
              </button>
              <button
                id="trimBtn"
                onclick="trimPendingPosts()"
                class="px-3 py-2 border border-gray-300 rounded-md text-sm bg-amber-50 text-amber-700 hover:bg-amber-100 focus:outline-none focus:ring-2 focus:ring-amber-500 transition"
                title="Delete excess pending posts beyond consumption buffer"
              >
                <i class="fas fa-scissors mr-1"></i>Trim excess pending
              </button>
            </div>
          </div>
        </div>

        {% if posts %}
        <div class="overflow-x-auto">
          <table class="w-full">
            <thead class="border-b-2 border-gray-200">
              <tr>
                <th class="text-left py-3 px-4 font-semibold text-gray-700">
                  Author
                </th>
                <th class="text-left py-3 px-4 font-semibold text-gray-700">
                  Content
                </th>
                <th class="text-left py-3 px-4 font-semibold text-gray-700">
                  Score
                </th>
                <th class="text-left py-3 px-4 font-semibold text-gray-700">
                  Status
                </th>
                <th class="text-left py-3 px-4 font-semibold text-gray-700 min-w-max">
                  Details
                </th>
              </tr>
            </thead>
            <tbody>
              {% for item in posts %}
              <tr class="border-b border-gray-100 hover:bg-gray-50">
                <td class="py-4 px-4">
                  <div class="text-sm font-medium text-gray-900">
                    {{ item.post.author_display_name or
                    item.post.author_username or "Unknown" }}
                  </div>
                  <div class="text-xs text-gray-500">
                    @{{ item.post.author_username or "unknown" }}
                  </div>
                </td>
                <td class="py-4 px-4">
                  <div class="text-sm text-gray-700 max-w-xs truncate">
                    {% if item.post.content %} {{ item.post.content[:100] }}{%
                    if item.post.content|length > 100 %}...{% endif %} {% else
                    %}
                    <span class="text-gray-400">No content</span>
                    {% endif %}
                  </div>
                  {% if item.post.hashtags and item.post.hashtags|length > 0 %}
                  <div class="text-xs text-indigo-600 mt-1">
                    {% for hashtag in item.post.hashtags[:3] %}
                    <span>#{{ hashtag }}</span>
                    {% if not loop.last %}<span class="mx-1">·</span>{% endif %}
                    {% endfor %} {% if item.post.hashtags|length > 3 %}
                    <span class="text-gray-500"
                      >+{{ item.post.hashtags|length - 3 }}</span
                    >
                    {% endif %}
                  </div>
                  {% endif %} {% if item.post.media_attachments and
                  item.post.media_attachments|length > 0 %}
                  <div class="flex gap-2 mt-3">
                    {% for attachment in item.post.media_attachments[:3] %}
                    <div class="relative group">
                      {% if attachment.url or attachment.preview_url %}
                      <img
                        src="{{ attachment.url or attachment.preview_url }}"
                        alt="Post attachment"
                        class="h-12 w-12 object-cover rounded border border-gray-200 hover:border-gray-400 cursor-pointer"
                        data-attachments='{{ item.post.media_attachments | tojson | replace("'", "&#39;") }}'
                        onclick="openImageModal(JSON.parse(this.dataset.attachments), 0)"
                      />
                      {% else %}
                      <div
                        class="h-12 w-12 bg-gray-100 rounded border border-gray-200 flex items-center justify-center"
                      >
                        <i class="fas fa-file text-gray-400"></i>
                      </div>
                      {% endif %}
                    </div>
                    {% endfor %} {% if item.post.media_attachments|length > 3 %}
                    <div
                      class="h-12 w-12 bg-gray-100 rounded border border-gray-200 flex items-center justify-center text-xs font-semibold text-gray-600"
                    >
                      +{{ item.post.media_attachments|length - 3 }}
                    </div>
                    {% endif %}
                  </div>
                  {% endif %}
                </td>
                <td class="py-4 px-4">
                  <div class="text-sm font-semibold text-gray-900">
                    {{ item.post.spam_score }}
                  </div>
                  {% if item.post.media_attachments and
                  item.post.media_attachments|length > 0 %}
                  <div class="text-xs text-gray-500 mt-1">
                    <i class="fas fa-image mr-1"></i>{{
                    item.post.media_attachments|length }}
                  </div>
                  {% endif %}
                </td>
                <td class="py-4 px-4">
                  <span class="status-badge status-{{ item.queue_status }}">
                    {{ item.queue_status|title }}
                  </span>
                  {% if item.queue_status == 'error' and item.error_reason %}
                  <div class="text-xs text-red-700 mt-2 max-w-xs">
                    {{ item.error_reason }}
                  </div>
                  {% endif %}
                </td>
                <td class="py-4 px-4 min-w-max">
                  {% if item.queue_status == 'reserved' and item.reserved_at %}
                  <div class="text-xs text-blue-700">
                    <i class="fas fa-clock mr-1"></i>{{
                    item.reserved_at.strftime('%H:%M:%S') }}
                  </div>
                  <button
                    onclick="deletePost({{ item.post.id }})"
                    class="text-xs mt-2 block px-3 py-1 bg-red-100 text-red-700 rounded hover:bg-red-200 transition"
                  >
                    Delete
                  </button>
                  {% elif item.queue_status == 'error' and item.errored_at %}
                  <div class="text-xs text-red-700">
                    <i class="fas fa-calendar mr-1"></i>{{
                    item.errored_at.strftime('%Y-%m-%d %H:%M') }}
                  </div>
                  <div class="flex flex-wrap gap-2 mt-2">
                    <button
                      onclick="requeuePost({{ item.post.id }})"
                      class="text-xs px-3 py-1 bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition whitespace-nowrap"
                    >
                      Re-queue
                    </button>
                    <button
                      onclick="deletePost({{ item.post.id }})"
                      class="text-xs px-3 py-1 bg-red-100 text-red-700 rounded hover:bg-red-200 transition whitespace-nowrap"
                    >
                      Delete
                    </button>
                  </div>
                  {% elif item.queue_status == 'pending' %}
                  <div class="text-xs text-gray-500">
                    <i class="fas fa-check-circle text-green-600 mr-1"></i
                    >Eligible
                  </div>
                  {% elif not item.eligible %}
                  <div
                    class="text-xs bg-orange-50 text-orange-700 p-2 rounded border border-orange-200 max-w-xs"
                  >
                    <i class="fas fa-ban mr-1"></i>{{ item.exclusion_reason }}
                  </div>
                  {% endif %}
                </td>
              </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
        {% else %}
        <div class="text-center py-12">
          <i class="fas fa-inbox text-gray-300 text-4xl mb-3"></i>
          <p class="text-gray-500">No approved posts yet.</p>
        </div>
        {% endif %}
      </div>
    </main>

    <script>
      // Store API key from server context
      let apiKey = "{{ api_key }}";

      // Helper function to add API key to fetch headers
      function getHeaders(method = "GET", additionalHeaders = {}) {
        const headers = {
          "Content-Type": "application/json",
          ...additionalHeaders,
        };
        if (apiKey) {
          headers["X-API-Key"] = apiKey;
        }
        return headers;
      }

      function filterByStatus(status) {
        const params = new URLSearchParams();
        params.append("status", status);
        window.location.href = `/queue?${params.toString()}`;
      }

      function applyFilterSort() {
        const status = document.getElementById("statusFilter").value;
        const sortBy = document.getElementById("sortBy").value;
        const sortOrder = document.getElementById("sortOrder").textContent.includes("Asc") ? "asc" : "desc";

        const params = new URLSearchParams();
        if (status !== "all") params.append("status", status);
        if (sortBy !== "reviewed_at") params.append("sort", sortBy);
        if (sortOrder !== "desc") params.append("order", sortOrder);

        const query = params.toString();
        window.location.href = `/queue${query ? "?" + query : ""}`;
      }

      function toggleSortOrder() {
        const button = document.getElementById("sortOrder");
        const isDesc = button.textContent.includes("Desc");
        const newOrder = isDesc ? "asc" : "desc";

        const status = document.getElementById("statusFilter").value;
        const sortBy = document.getElementById("sortBy").value;

        const params = new URLSearchParams();
        if (status !== "all") params.append("status", status);
        if (sortBy !== "reviewed_at") params.append("sort", sortBy);
        params.append("order", newOrder);

        const query = params.toString();
        window.location.href = `/queue${query ? "?" + query : ""}`;
      }

      function showFlash(message, type = "success") {
        const flashEl = document.getElementById("flash");
        const colours = {
          success: "bg-green-100 text-green-800 border-green-300",
          error: "bg-red-100 text-red-800 border-red-300",
          warning: "bg-amber-100 text-amber-800 border-amber-300",
          info: "bg-blue-100 text-blue-800 border-blue-300",
        };
        flashEl.innerHTML = `
          <div class="border-l-4 ${colours[type]} p-4 rounded">
            <p class="text-sm font-medium">${message}</p>
          </div>
        `;
        flashEl.classList.remove("hidden");
        setTimeout(() => flashEl.classList.add("hidden"), 5000);
      }

      async function requeuePost(postId) {
        try {
          const resp = await fetch(`/api/v1/curated/${postId}/requeue`, {
            method: "POST",
            headers: getHeaders("POST"),
          });
          if (!resp.ok) {
            const err = await resp.json();
            showFlash(`Error: ${err.detail || resp.status}`, "error");
            return;
          }
          showFlash("Post returned to pending queue.", "success");
          setTimeout(() => location.reload(), 1500);
        } catch (e) {
          showFlash(`Failed to requeue post: ${e.message}`, "error");
        }
      }

      async function deletePost(postId) {
        try {
          const resp = await fetch(`/api/v1/posts/${postId}`, {
            method: "DELETE",
            headers: getHeaders("DELETE"),
          });
          if (!resp.ok) {
            const err = await resp.json();
            showFlash(`Error: ${err.detail || resp.status}`, "error");
            return;
          }
          showFlash("Post deleted successfully.", "success");
          setTimeout(() => location.reload(), 1500);
        } catch (e) {
          showFlash(`Failed to delete post: ${e.message}`, "error");
        }
      }

      async function cleanupDeliveredPosts() {
        try {
          const cleanupBtn = document.getElementById("cleanupBtn");
          cleanupBtn.disabled = true;
          cleanupBtn.textContent = "Purging...";

          const resp = await fetch("/api/v1/curated/cleanup", {
            method: "POST",
            headers: getHeaders("POST"),
          });
          if (!resp.ok) {
            const err = await resp.json();
            showFlash(`Error: ${err.detail || resp.status}`, "error");
            cleanupBtn.disabled = false;
            cleanupBtn.innerHTML = '<i class="fas fa-trash mr-1"></i>Purge old delivered';
            return;
          }
          const result = await resp.json();
          showFlash(`Deleted ${result.deleted} old delivered posts.`, "success");
          setTimeout(() => location.reload(), 1500);
        } catch (e) {
          showFlash(`Failed to cleanup posts: ${e.message}`, "error");
          const cleanupBtn = document.getElementById("cleanupBtn");
          cleanupBtn.disabled = false;
          cleanupBtn.innerHTML = '<i class="fas fa-trash mr-1"></i>Purge old delivered';
        }
      }

      async function trimPendingPosts() {
        try {
          const trimBtn = document.getElementById("trimBtn");
          trimBtn.disabled = true;
          trimBtn.textContent = "Trimming...";

          const resp = await fetch("/api/v1/curated/trim-pending", {
            method: "POST",
            headers: getHeaders("POST"),
          });
          if (!resp.ok) {
            const err = await resp.json();
            showFlash(`Error: ${err.detail || resp.status}`, "error");
            trimBtn.disabled = false;
            trimBtn.innerHTML = '<i class="fas fa-scissors mr-1"></i>Trim excess pending';
            return;
          }
          const result = await resp.json();
          showFlash(`Deleted ${result.deleted} excess pending posts.`, "success");
          setTimeout(() => location.reload(), 1500);
        } catch (e) {
          showFlash(`Failed to trim posts: ${e.message}`, "error");
          const trimBtn = document.getElementById("trimBtn");
          trimBtn.disabled = false;
          trimBtn.innerHTML = '<i class="fas fa-scissors mr-1"></i>Trim excess pending';
        }
      }



      function openImageModal(attachments, startIndex = 0) {
        // Filter to only images with URLs
        const images = attachments
          .filter((a) => a.url || a.preview_url)
          .map((a) => a.url || a.preview_url);

        if (images.length === 0) return;

        let currentIndex = Math.min(startIndex, images.length - 1);

        const modal = document.createElement("div");
        modal.className =
          "fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 p-4";
        modal.id = "imageModal";

        const updateImage = () => {
          const imgContainer = modal.querySelector(".image-container");
          const counter = modal.querySelector(".image-counter");
          imgContainer.innerHTML = `<img src="${images[currentIndex]}" alt="Full preview" class="max-w-full max-h-screen object-contain rounded" />`;
          if (counter) {
            counter.textContent = `${currentIndex + 1} / ${images.length}`;
          }
        };

        modal.innerHTML = `
          <div class="relative max-w-4xl max-h-screen flex flex-col">
            <button
              onclick="document.getElementById('imageModal').remove()"
              class="absolute -top-10 right-0 text-white hover:text-gray-300 text-2xl z-10"
            >
              <i class="fas fa-times"></i>
            </button>
            <div class="image-container flex-1 flex items-center justify-center">
            </div>
            <div class="flex items-center justify-between mt-4 text-white">
              ${
                images.length > 1
                  ? `
              <button
                onclick="window.imagePrevImage()"
                class="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded transition"
              >
                <i class="fas fa-chevron-left mr-2"></i>Previous
              </button>
              `
                  : `<div></div>`
              }
              <span class="image-counter text-sm font-medium"></span>
              ${
                images.length > 1
                  ? `
              <button
                onclick="window.imageNextImage()"
                class="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded transition"
              >
                Next<i class="fas fa-chevron-right ml-2"></i>
              </button>
              `
                  : `<div></div>`
              }
            </div>
          </div>
        `;

        document.body.appendChild(modal);

        // Navigation functions
        window.imageNextImage = () => {
          currentIndex = (currentIndex + 1) % images.length;
          updateImage();
        };

        window.imagePrevImage = () => {
          currentIndex = (currentIndex - 1 + images.length) % images.length;
          updateImage();
        };

        // Keyboard navigation
        const handleKeydown = (e) => {
          if (e.key === "ArrowRight") window.imageNextImage();
          if (e.key === "ArrowLeft") window.imagePrevImage();
          if (e.key === "Escape") modal.remove();
        };

        document.addEventListener("keydown", handleKeydown);

        modal.addEventListener("click", (e) => {
          if (e.target === modal) {
            document.removeEventListener("keydown", handleKeydown);
            modal.remove();
          }
        });

        updateImage();
      }
    </script>
  </body>
</html>
