<!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 }} - Topical Tags</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" />
  </head>
  <body class="bg-gray-50 min-h-screen">
    {{ header('topical_tags') }}

    <main class="container mx-auto px-4 py-8">
      <!-- Flash message area -->
      <div id="flash" class="hidden mb-4"></div>

      <div class="mb-8 flex items-center justify-between">
        <div>
          <h2 class="text-3xl font-bold text-gray-800">Topical Tags</h2>
          <p class="text-gray-600 mt-2">
            Mark hashtags as topical for a specific day — so consumers can
            request topical content via the curated queue.
          </p>
        </div>
        <button
          id="openCreateBtn"
          class="bg-indigo-600 text-white px-4 py-2 rounded-lg font-semibold hover:bg-indigo-700"
        >
          <i class="fas fa-plus mr-2"></i>Add Rule
        </button>
      </div>

      <!-- Tag list -->
      <div class="bg-white rounded-lg shadow-md p-6">
        {% if tags %}
        <div class="space-y-4">
          {% for tag in tags %}
          <div
            class="border border-gray-200 rounded-lg p-4 flex items-start justify-between"
          >
            <div>
              <h3 class="text-lg font-semibold text-gray-800">
                <i class="fas fa-hashtag mr-1 text-indigo-500"></i>{{ tag.hashtag }}
              </h3>
              <div class="mt-2 flex flex-wrap gap-2">
                {% if tag.topical_day_of_week_name %}
                <span
                  class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800"
                >
                  <i class="fas fa-calendar-week mr-1"></i>{{ tag.topical_day_of_week_name }}s
                </span>
                {% endif %} {% if tag.topical_month_day %}
                <span
                  class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800"
                >
                  <i class="fas fa-calendar-day mr-1"></i>{{ tag.topical_month_day }}
                </span>
                {% endif %} {% if not tag.topical_day_of_week_name and not
                tag.topical_month_day %}
                <span
                  class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-500"
                >
                  No day configured
                </span>
                {% endif %}
              </div>
              <p class="text-gray-400 text-xs mt-2">
                <i class="far fa-clock mr-1"></i>Created {{ tag.created_at }}
              </p>
            </div>
            <div class="flex flex-col space-y-2 ml-4">
              <button
                class="edit-btn bg-yellow-500 text-white px-3 py-1 rounded text-sm hover:bg-yellow-600"
                data-id="{{ tag.id }}"
                data-hashtag="{{ tag.hashtag }}"
                data-topical-day-of-week="{{ tag.topical_day_of_week_name or '' }}"
                data-topical-month-day="{{ tag.topical_month_day or '' }}"
              >
                <i class="fas fa-edit mr-1"></i>Edit
              </button>
              <button
                class="delete-btn bg-red-500 text-white px-3 py-1 rounded text-sm hover:bg-red-600"
                data-id="{{ tag.id }}"
                data-hashtag="{{ tag.hashtag }}"
              >
                <i class="fas fa-trash mr-1"></i>Delete
              </button>
            </div>
          </div>
          {% endfor %}
        </div>
        {% else %}
        <div class="text-center py-12">
          <i class="fas fa-calendar-alt text-4xl text-gray-300 mb-4"></i>
          <p class="text-gray-500 mb-2">No topical tag rules configured yet.</p>
          <p class="text-gray-400 text-sm">
            Topical tags let you mark a hashtag as relevant for a specific day
            (e.g. <em>#caturday</em> on Saturdays). Consumers can then request
            topical posts via the curated queue. You can also configure
            stream-level topical days on the
            <a href="/streams" class="text-indigo-600 hover:underline">Streams</a> page.
          </p>
        </div>
        {% endif %}
      </div>
    </main>

    <!-- Create Rule Modal -->
    <div
      id="createModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50"
    >
      <div class="bg-white rounded-lg p-6 w-full max-w-md">
        <h3 class="text-xl font-bold text-gray-800 mb-4">Add Topical Rule</h3>
        <form id="createForm">
          <div class="mb-4">
            <label class="block text-gray-700 mb-2" for="createHashtag"
              >Hashtag</label
            >
            <input
              type="text"
              id="createHashtag"
              class="w-full px-4 py-2 border border-gray-300 rounded-lg"
              placeholder="caturday"
              required
            />
            <p class="text-gray-500 text-xs mt-1">Enter without the # symbol</p>
          </div>
          <div class="mb-4">
            <label class="block text-gray-700 text-sm mb-1" for="createTopicalDayOfWeek"
              >Day of week (optional)</label
            >
            <select
              id="createTopicalDayOfWeek"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
            >
              <option value="">— not set —</option>
              <option value="Monday">Monday</option>
              <option value="Tuesday">Tuesday</option>
              <option value="Wednesday">Wednesday</option>
              <option value="Thursday">Thursday</option>
              <option value="Friday">Friday</option>
              <option value="Saturday">Saturday</option>
              <option value="Sunday">Sunday</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-gray-700 text-sm mb-1" for="createTopicalMonthDay"
              >Calendar date MM-DD (optional, e.g. 03-17 for St. Patrick's Day)</label
            >
            <input
              type="text"
              id="createTopicalMonthDay"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
              pattern="\d{2}-\d{2}"
              placeholder="MM-DD"
              maxlength="5"
            />
          </div>
          <div class="flex justify-end space-x-4">
            <button
              type="button"
              id="cancelCreateBtn"
              class="px-4 py-2 border border-gray-300 rounded-lg"
            >
              Cancel
            </button>
            <button
              type="submit"
              class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
            >
              <i class="fas fa-plus mr-1"></i>Create
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Edit Rule Modal -->
    <div
      id="editModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50"
    >
      <div class="bg-white rounded-lg p-6 w-full max-w-md">
        <h3 class="text-xl font-bold text-gray-800 mb-4">Edit Topical Rule</h3>
        <form id="editForm">
          <input type="hidden" id="editTagId" />
          <div class="mb-4">
            <label class="block text-gray-700 mb-2" for="editHashtag"
              >Hashtag</label
            >
            <input
              type="text"
              id="editHashtag"
              class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-100"
              readonly
            />
          </div>
          <div class="mb-4">
            <label class="block text-gray-700 text-sm mb-1" for="editTopicalDayOfWeek"
              >Day of week (optional)</label
            >
            <select
              id="editTopicalDayOfWeek"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
            >
              <option value="">— not set —</option>
              <option value="Monday">Monday</option>
              <option value="Tuesday">Tuesday</option>
              <option value="Wednesday">Wednesday</option>
              <option value="Thursday">Thursday</option>
              <option value="Friday">Friday</option>
              <option value="Saturday">Saturday</option>
              <option value="Sunday">Sunday</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-gray-700 text-sm mb-1" for="editTopicalMonthDay"
              >Calendar date MM-DD (optional, e.g. 03-17 for St. Patrick's Day)</label
            >
            <input
              type="text"
              id="editTopicalMonthDay"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
              pattern="\d{2}-\d{2}"
              placeholder="MM-DD"
              maxlength="5"
            />
          </div>
          <div class="flex justify-end space-x-4">
            <button
              type="button"
              id="cancelEditBtn"
              class="px-4 py-2 border border-gray-300 rounded-lg"
            >
              Cancel
            </button>
            <button
              type="submit"
              class="px-4 py-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600"
            >
              Save Changes
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div
      id="deleteModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50"
    >
      <div class="bg-white rounded-lg p-6 w-full max-w-sm">
        <h3 class="text-xl font-bold text-gray-800 mb-2">Delete Rule</h3>
        <p class="text-gray-600 mb-6">
          Remove topical rule for
          <strong id="deleteHashtag" class="text-gray-800"></strong>?
          This cannot be undone.
        </p>
        <div class="flex justify-end space-x-4">
          <button
            type="button"
            id="cancelDeleteBtn"
            class="px-4 py-2 border border-gray-300 rounded-lg"
          >
            Cancel
          </button>
          <button
            type="button"
            id="confirmDeleteBtn"
            class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600"
          >
            <i class="fas fa-trash mr-1"></i>Delete
          </button>
        </div>
      </div>
    </div>

    <footer class="bg-gray-800 text-white mt-12">
      <div class="container mx-auto px-4 py-8">
        <div class="flex flex-col md:flex-row justify-between items-center">
          <div class="mb-6 md:mb-0">
            <div class="flex items-center mb-4">
              <div class="rounded-full p-2 bg-white/10 mr-4">
                <i class="fas fa-water"></i>
              </div>
              <div>
                <h2 class="text-xl font-bold">{{ app_name }}</h2>
                <p class="text-gray-300">Fediverse Content Stream Filtering</p>
              </div>
            </div>
            <p class="text-gray-400">
              Inspired by the ancient Dujiangyan irrigation system
            </p>
          </div>
          <div class="text-center md:text-right">
            <p class="text-gray-400">Version {{ app_version }}</p>
            <p class="text-gray-400">分流 - Divide the Flow</p>
          </div>
        </div>
      </div>
    </footer>

    <script>
      let apiKey = "{{ api_key }}";

      function getHeaders(method = "GET") {
        const headers = { "Content-Type": "application/json" };
        if (apiKey) headers["X-API-Key"] = apiKey;
        return headers;
      }

      function showFlash(message, type) {
        const el = document.getElementById("flash");
        const colours =
          type === "error"
            ? "bg-red-100 border border-red-400 text-red-700"
            : "bg-green-100 border border-green-400 text-green-700";
        el.className = `${colours} px-4 py-3 rounded mb-4`;
        el.textContent = message;
        el.classList.remove("hidden");
        setTimeout(() => el.classList.add("hidden"), 4000);
      }

      // ── Create modal ──────────────────────────────────────────────────────
      const createModal = document.getElementById("createModal");
      const createForm = document.getElementById("createForm");

      document.getElementById("openCreateBtn").addEventListener("click", () => {
        createForm.reset();
        createModal.classList.remove("hidden");
      });

      document.getElementById("cancelCreateBtn").addEventListener("click", () => {
        createModal.classList.add("hidden");
      });

      createForm.addEventListener("submit", async function (e) {
        e.preventDefault();
        const hashtag = document
          .getElementById("createHashtag")
          .value.trim()
          .replace(/^#/, "");
        const dayOfWeek =
          document.getElementById("createTopicalDayOfWeek").value || null;
        const monthDay =
          document.getElementById("createTopicalMonthDay").value.trim() || null;

        if (!dayOfWeek && !monthDay) {
          showFlash(
            "Please set a day of week or a calendar date (MM-DD).",
            "error",
          );
          return;
        }

        try {
          const response = await fetch("/api/v1/topical-tags", {
            method: "POST",
            headers: getHeaders("POST"),
            body: JSON.stringify({
              hashtag: hashtag,
              topical_day_of_week: dayOfWeek,
              topical_month_day: monthDay,
            }),
          });

          if (response.ok) {
            window.location.reload();
          } else {
            const error = await response.json();
            showFlash(
              "Error: " + (error.detail || error.error || "Unknown error"),
              "error",
            );
          }
        } catch (error) {
          showFlash("Network error: " + error.message, "error");
        }
      });

      // ── Edit modal ────────────────────────────────────────────────────────
      const editModal = document.getElementById("editModal");
      const editForm = document.getElementById("editForm");
      let currentEditId = null;

      document.addEventListener("click", function (e) {
        const btn = e.target.classList.contains("edit-btn")
          ? e.target
          : e.target.closest(".edit-btn");
        if (!btn) return;
        currentEditId = btn.dataset.id;
        document.getElementById("editTagId").value = currentEditId;
        document.getElementById("editHashtag").value = "#" + btn.dataset.hashtag;
        document.getElementById("editTopicalDayOfWeek").value =
          btn.dataset.topicalDayOfWeek || "";
        document.getElementById("editTopicalMonthDay").value =
          btn.dataset.topicalMonthDay || "";
        editModal.classList.remove("hidden");
      });

      document.getElementById("cancelEditBtn").addEventListener("click", () => {
        editModal.classList.add("hidden");
        currentEditId = null;
      });

      editForm.addEventListener("submit", async function (e) {
        e.preventDefault();
        if (!currentEditId) return;

        const dayOfWeek =
          document.getElementById("editTopicalDayOfWeek").value || null;
        const monthDay =
          document.getElementById("editTopicalMonthDay").value.trim() || null;

        if (!dayOfWeek && !monthDay) {
          showFlash(
            "Please set a day of week or a calendar date (MM-DD).",
            "error",
          );
          return;
        }

        try {
          const response = await fetch(
            `/api/v1/topical-tags/${currentEditId}`,
            {
              method: "PATCH",
              headers: getHeaders("PATCH"),
              body: JSON.stringify({
                topical_day_of_week: dayOfWeek,
                topical_month_day: monthDay,
              }),
            },
          );

          if (response.ok) {
            window.location.reload();
          } else {
            const error = await response.json();
            showFlash(
              "Error: " + (error.detail || error.error || "Unknown error"),
              "error",
            );
          }
        } catch (error) {
          showFlash("Network error: " + error.message, "error");
        }
      });

      // ── Delete modal ──────────────────────────────────────────────────────
      const deleteModal = document.getElementById("deleteModal");
      let currentDeleteId = null;

      document.addEventListener("click", function (e) {
        const btn = e.target.classList.contains("delete-btn")
          ? e.target
          : e.target.closest(".delete-btn");
        if (!btn) return;
        currentDeleteId = btn.dataset.id;
        document.getElementById("deleteHashtag").textContent =
          "#" + btn.dataset.hashtag;
        deleteModal.classList.remove("hidden");
      });

      document.getElementById("cancelDeleteBtn").addEventListener("click", () => {
        deleteModal.classList.add("hidden");
        currentDeleteId = null;
      });

      document
        .getElementById("confirmDeleteBtn")
        .addEventListener("click", async function () {
          if (!currentDeleteId) return;

          try {
            const response = await fetch(
              `/api/v1/topical-tags/${currentDeleteId}`,
              {
                method: "DELETE",
                headers: getHeaders("DELETE"),
              },
            );

            if (response.ok) {
              window.location.reload();
            } else {
              try {
                const error = await response.json();
                showFlash(
                  "Error: " +
                    (error.detail || error.error || "Failed to delete rule"),
                  "error",
                );
              } catch (_) {
                showFlash("Error: Failed to delete rule", "error");
              }
            }
          } catch (error) {
            showFlash("Network error: " + error.message, "error");
          }
        });

      // Close modals when clicking the backdrop
      window.addEventListener("click", function (e) {
        if (e.target === createModal) createModal.classList.add("hidden");
        if (e.target === editModal) editModal.classList.add("hidden");
        if (e.target === deleteModal) deleteModal.classList.add("hidden");
      });
    </script>
  </body>
</html>
