<!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 }} - Dashboard</title>

    <!-- Favicon -->
    <link rel="icon" href="/static/FenLiu.png" type="image/png" />
    <link rel="apple-touch-icon" href="/static/FenLiu.png" />

    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>

    <!-- Font Awesome -->
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
    />

    <style>
      .stat-card {
        transition:
          transform 0.2s,
          box-shadow 0.2s;
      }

      .stat-card:hover {
        transform: translateY(-4px);
        box-shadow:
          0 10px 25px -5px rgba(0, 0, 0, 0.1),
          0 10px 10px -5px rgba(0, 0, 0, 0.04);
      }

      .water-wave {
        position: relative;
        overflow: hidden;
      }

      .water-wave::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(
          90deg,
          transparent,
          rgba(59, 130, 246, 0.1),
          transparent
        );
        /* Animation removed to prevent loading cycle appearance */
        opacity: 0.3;
      }

      .post-content {
        line-height: 1.6;
        word-wrap: break-word;
      }

      .post-content a {
        color: #3b82f6;
        text-decoration: underline;
      }

      .post-content a:hover {
        color: #1d4ed8;
      }

      /* Mastodon-like post styling */
      .mastodon-post {
        border-left: 3px solid #6366f1;
        transition: all 0.2s ease;
      }

      .mastodon-post:hover {
        border-left-color: #4f46e5;
        background-color: #f8fafc;
      }

      .avatar-placeholder {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        background: linear-gradient(135deg, #6366f1, #8b5cf6);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: bold;
        font-size: 18px;
      }

      .post-engagement {
        color: #6b7280;
      }

      .post-engagement span {
        transition: color 0.2s ease;
      }

      .post-engagement span:hover {
        color: #4f46e5;
      }

      .boost-count:hover {
        color: #10b981 !important;
      }

      .like-count:hover {
        color: #ef4444 !important;
      }

      .reply-count:hover {
        color: #3b82f6 !important;
      }

      .author-handle {
        color: #6b7280;
      }

      .post-timestamp {
        color: #9ca3af;
      }

      .content-preview {
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      /* Mastodon-like media attachments styling */
      .media-attachments {
        margin: 12px 0;
      }

      /* Grid layouts based on number of attachments (like Mastodon) */
      .media-grid {
        display: grid;
        gap: 8px;
        border-radius: 8px;
        overflow: hidden;
      }

      /* 1 attachment: full width */
      .media-grid.single {
        grid-template-columns: 1fr;
        max-width: 100%;
      }

      /* 2 attachments: 2 columns */
      .media-grid.double {
        grid-template-columns: 1fr 1fr;
      }

      /* 3 attachments: 2 columns, first spans 2 rows */
      .media-grid.triple {
        grid-template-columns: 1fr 1fr;
        grid-template-rows: 1fr 1fr;
      }

      /* 4+ attachments: 2x2 grid */
      .media-grid.multiple {
        grid-template-columns: 1fr 1fr;
        grid-template-rows: 1fr 1fr;
      }

      .media-item {
        position: relative;
        background-color: #f3f4f6;
        overflow: hidden;
      }

      /* Single attachment styling */
      .media-grid.single .media-item {
        aspect-ratio: 16/9;
      }

      /* Multiple attachments styling */
      .media-grid:not(.single) .media-item {
        aspect-ratio: 1;
      }

      /* Triple grid: first item spans 2 rows */
      .media-grid.triple .media-item:first-child {
        grid-row: span 2;
      }

      .media-item img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: block;
      }

      .media-item.video::before {
        content: "▶";
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(0, 0, 0, 0.7);
        color: white;
        width: 48px;
        height: 48px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        z-index: 1;
        pointer-events: none;
      }

      .fetch-modal {
        backdrop-filter: blur(2px);
      }

      .media-count {
        position: absolute;
        top: 8px;
        right: 8px;
        background: rgba(0, 0, 0, 0.7);
        color: white;
        font-size: 12px;
        padding: 4px 8px;
        border-radius: 12px;
        z-index: 1;
        pointer-events: none;
      }

      .media-description {
        font-size: 13px;
        color: #6b7280;
        margin-top: 6px;
        line-height: 1.4;
        padding: 0 4px;
      }

      /* Hover effects */
      .media-item {
        transition: opacity 0.2s ease;
      }

      .media-item:hover {
        opacity: 0.95;
      }

      .spam-score-low {
        background-color: #d1fae5;
        color: #065f46;
      }

      .spam-score-medium {
        background-color: #fef3c7;
        color: #92400e;
      }

      .spam-score-high {
        background-color: #fde68a;
        color: #92400e;
      }

      .spam-score-very-high {
        background-color: #fecaca;
        color: #991b1b;
      }
    </style>
  </head>
  <body class="bg-gray-50 min-h-screen">
    {{ header('dashboard') }}

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

      <!-- Welcome header -->
      <div class="mb-8 text-center">
        <h2 class="text-3xl font-bold text-gray-800 mb-4">
          Welcome to {{ app_name }}
        </h2>
        <p class="text-gray-600 max-w-2xl mx-auto mb-2">
          Monitor Fediverse hashtags, filter content, and export quality posts
          for boosting.
        </p>
        <p class="text-gray-600 max-w-2xl mx-auto">
          Inspired by
          <a
            href="https://en.wikipedia.org/wiki/Dujiangyan"
            target="_blank"
            class="text-blue-600 hover:text-blue-800 underline"
            >ancient Chinese water management</a
          >
          principles.
        </p>
      </div>

      <!-- Statistics cards -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-6">
        <div class="stat-card bg-white rounded-xl shadow-md p-4 water-wave">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-xs text-gray-500 uppercase tracking-wider">
                Total Streams
              </p>
              <p class="text-2xl font-bold text-blue-600 mt-1">
                {{ total_streams }}
              </p>
            </div>
            <div class="text-blue-500 text-2xl">
              <i class="fas fa-hashtag"></i>
            </div>
          </div>
          <div class="mt-2">
            <p class="text-xs text-gray-600">
              <span class="font-semibold text-green-600"
                >{{ active_streams }}</span
              >
              active
            </p>
          </div>
        </div>

        <div class="stat-card bg-white rounded-xl shadow-md p-4">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-xs text-gray-500 uppercase tracking-wider">
                Total Posts
              </p>
              <p class="text-2xl font-bold text-green-600 mt-1">
                {{ total_posts }}
              </p>
            </div>
            <div class="text-green-500 text-2xl">
              <i class="fas fa-stream"></i>
            </div>
          </div>
          <div class="mt-2">
            <p class="text-xs text-gray-600">
              <span class="font-semibold text-blue-600"
                >{{ processed_posts }}</span
              >
              processed
            </p>
          </div>
        </div>

        <div class="stat-card bg-white rounded-xl shadow-md p-4">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-xs text-gray-500 uppercase tracking-wider">
                Active Streams
              </p>
              <p class="text-2xl font-bold text-purple-600 mt-1">
                {{ active_streams }}
              </p>
            </div>
            <div class="text-purple-500 text-2xl">
              <i class="fas fa-satellite-dish"></i>
            </div>
          </div>
          <div class="mt-2">
            <p class="text-xs text-gray-600">Monitoring in real-time</p>
          </div>
        </div>
      </div>

      <!-- Quick Actions -->
      <div
        class="mb-8 bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl shadow-md p-6"
      >
        <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
          <i class="fas fa-bolt mr-2 text-yellow-500"></i>
          Quick Actions
        </h3>

        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <a
            href="/streams"
            class="bg-white rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow text-left group block"
          >
            <div class="flex items-center mb-2">
              <div
                class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center mr-3 group-hover:bg-blue-200 transition-colors"
              >
                <i class="fas fa-hashtag text-blue-600"></i>
              </div>
              <h4 class="font-medium text-gray-800">Add Hashtag</h4>
            </div>
            <p class="text-sm text-gray-600">Start monitoring a new hashtag</p>
          </a>

          <button
            id="dashboardFetchAllBtn"
            class="bg-white rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow text-left group block w-full"
          >
            <div class="flex items-center mb-2">
              <div
                class="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center mr-3 group-hover:bg-purple-200 transition-colors"
              >
                <i class="fas fa-cloud-download-alt text-purple-600"></i>
              </div>
              <h4 class="font-medium text-gray-800">Fetch All Streams</h4>
            </div>
            <p class="text-sm text-gray-600">
              Fetch new posts from all active streams
            </p>
          </button>

          <a
            href="/review"
            class="bg-white rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow text-left group block"
          >
            <div class="flex items-center mb-2">
              <div
                class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center mr-3 group-hover:bg-green-200 transition-colors"
              >
                <i class="fas fa-stream text-green-600"></i>
              </div>
              <h4 class="font-medium text-gray-800">Review Posts</h4>
            </div>
            <p class="text-sm text-gray-600">Process and score recent posts</p>
          </a>

          <a
            href="/stats"
            class="bg-white rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow text-left group block"
          >
            <div class="flex items-center mb-2">
              <div
                class="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center mr-3 group-hover:bg-purple-200 transition-colors"
              >
                <i class="fas fa-chart-bar text-purple-600"></i>
              </div>
              <h4 class="font-medium text-gray-800">View Stats</h4>
            </div>
            <p class="text-sm text-gray-600">See analytics and metrics</p>
          </a>
        </div>
      </div>

      <!-- Two column layout -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <!-- Curated Queue Posts -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800 flex items-center">
              <i class="fas fa-inbox mr-2 text-blue-500"></i>
              Curation Queue
            </h3>
          </div>

          <div class="divide-y divide-gray-100">
            {% if curated_posts %} {% for post in curated_posts %}
            <div class="p-6 hover:bg-gray-50 transition-colors mastodon-post">
              <div class="flex space-x-4">
                <!-- Avatar -->
                <div class="flex-shrink-0">
                  <div class="avatar-placeholder">
                    {% if post.author_display_name %} {{
                    post.author_display_name[0]|upper }} {% else %} {{
                    post.author_username[0]|upper if post.author_username else
                    '?' }} {% endif %}
                  </div>
                </div>

                <!-- Post content -->
                <div class="flex-1 min-w-0">
                  <!-- Author info and timestamp -->
                  <div class="flex justify-between items-start mb-2">
                    <div>
                      <div class="flex items-center space-x-2">
                        <h4 class="font-bold text-gray-900">
                          {% if post.author_display_name %} {{
                          post.author_display_name }} {% else %} {{
                          post.author_username }} {% endif %}
                        </h4>
                        <span class="author-handle text-sm">
                          @{{ post.author_username }}
                        </span>
                        {% if post.spam_score is not none %} {% set spam_class =
                        'spam-score-low' if post.spam_score <= 25 else
                        'spam-score-medium' if post.spam_score <= 50 else
                        'spam-score-high' if post.spam_score <= 75 else
                        'spam-score-very-high' %}
                        <span
                          class="{{ spam_class }} px-2 py-0.5 text-xs rounded-full"
                        >
                          Score: {{ post.spam_score }}
                        </span>
                        {% else %}
                        <span
                          class="px-2 py-0.5 text-xs rounded-full bg-gray-100 text-gray-800"
                        >
                          Unprocessed
                        </span>
                        {% endif %}
                      </div>
                      <p class="post-timestamp text-sm">
                        <span
                          data-time="{{ post.created_at.isoformat() if post.created_at else post.fetched_at.isoformat() }}"
                        >
                          {{ post.created_at.strftime('%b %d, %H:%M') if
                          post.created_at else post.fetched_at.strftime('%b %d,
                          %H:%M') }}
                        </span>
                        {% if post.instance %} • {{ post.instance }} {% endif %}
                      </p>
                    </div>
                  </div>

                  <!-- Post content preview -->
                  <div class="post-content text-gray-800 mb-4 content-preview">
                    {{ post.content|safe }}
                  </div>

                  <!-- Media attachments (inline like Mastodon) -->
                  {% if post.media_attachments and post.media_attachments|length
                  > 0 %}
                  <div class="media-attachments">
                    {% set media_count = post.media_attachments|length %} {% set
                    display_count = media_count if media_count <= 4 else 4 %} {%
                    if display_count == 1 %} {% set grid_class = 'single' %} {%
                    elif display_count == 2 %} {% set grid_class = 'double' %}
                    {% elif display_count == 3 %} {% set grid_class = 'triple'
                    %} {% else %} {% set grid_class = 'multiple' %} {% endif %}

                    <div class="media-grid {{ grid_class }}">
                      {% for media in post.media_attachments[:display_count] %}
                      <div
                        class="media-item {{ 'video' if media.type == 'video' else 'image' }}"
                      >
                        <img
                          src="{{ media.preview_url or media.url }}"
                          alt="{{ media.description or 'Media attachment' }}"
                          loading="lazy"
                        />
                        {% if media_count > 4 and loop.index == 4 %}
                        <div class="media-count">+{{ media_count - 4 }}</div>
                        {% endif %}
                      </div>
                      {% endfor %}
                    </div>

                    {% if post.media_attachments[0].description %}
                    <div class="media-description">
                      {{ post.media_attachments[0].description }}
                    </div>
                    {% endif %}
                  </div>
                  {% endif %}

                  <!-- Engagement metrics -->
                  <div
                    class="post-engagement flex items-center space-x-6 text-sm"
                  >
                    <span
                      class="reply-count flex items-center space-x-1 cursor-pointer"
                    >
                      <i class="fas fa-reply text-gray-400"></i>
                      <span>{{ post.replies }}</span>
                    </span>
                    <span
                      class="boost-count flex items-center space-x-1 cursor-pointer"
                    >
                      <i class="fas fa-retweet text-gray-400"></i>
                      <span>{{ post.boosts }}</span>
                    </span>
                    <span
                      class="like-count flex items-center space-x-1 cursor-pointer"
                    >
                      <i class="fas fa-heart text-gray-400"></i>
                      <span>{{ post.likes }}</span>
                    </span>
                  </div>
                </div>
              </div>
            </div>
            {% endfor %} {% else %}
            <div class="p-8 text-center text-gray-500">
              <div class="flex justify-center mb-4">
                <div class="avatar-placeholder opacity-50">
                  <i class="fas fa-inbox"></i>
                </div>
              </div>
              <p class="text-lg font-medium text-gray-700">
                Curation queue is empty
              </p>
              <p class="text-sm text-gray-500 mt-2">
                Approved posts will appear here for export
              </p>
            </div>
            {% endif %}
          </div>
        </div>

        <!-- Active Streams -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800 flex items-center">
              <i class="fas fa-satellite-dish mr-2 text-green-500"></i>
              Active Streams
            </h3>
          </div>

          <div class="divide-y divide-gray-100">
            {% if active_streams_list %} {% for stream in active_streams_list %}
            <div class="p-6 hover:bg-gray-50 transition-colors">
              <div class="flex justify-between items-center mb-3">
                <div>
                  <h4 class="font-medium text-gray-800 flex items-center">
                    <i class="fas fa-hashtag text-blue-500 mr-2"></i>
                    #{{ stream.hashtag }}
                  </h4>
                  <p class="text-sm text-gray-500">
                    {{ stream.instance }} {% if stream.last_check %} • Last
                    checked:
                    <span data-time="{{ stream.last_check.isoformat() }}"
                      >{{ stream.last_check.strftime('%Y-%m-%d %H:%M') }}</span
                    >
                    {% endif %}
                  </p>
                </div>
                <span
                  class="px-3 py-1 text-xs rounded-full bg-green-100 text-green-800 font-medium"
                >
                  Active
                </span>
              </div>

              <div class="flex justify-between items-center mt-4">
                <div class="text-sm text-gray-600">
                  <i class="fas fa-database mr-1"></i>
                  {{ stream.post_count }} posts
                </div>
                <div class="flex space-x-2">
                  <button
                    class="px-3 py-1 text-sm bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition-colors"
                    onclick="fetchStream({{ stream.id }}, this)"
                  >
                    <i class="fas fa-sync-alt mr-1"></i>
                    Fetch
                  </button>
                  <a
                    href="/streams#stream-{{ stream.id }}"
                    class="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors"
                  >
                    <i class="fas fa-cog mr-1"></i>
                    Manage
                  </a>
                </div>
              </div>
            </div>
            {% endfor %} {% else %}
            <div class="p-8 text-center text-gray-500">
              <i class="fas fa-hashtag text-4xl mb-4 opacity-50"></i>
              <p class="text-lg">No active streams</p>
              <p class="text-sm mt-2">Add hashtags to start monitoring</p>
            </div>
            {% endif %}
          </div>

          <div class="px-6 py-4 border-t border-gray-200 bg-gray-50">
            <div class="flex justify-between items-center">
              <a
                href="/streams"
                class="text-blue-600 hover:text-blue-800 font-medium flex items-center"
              >
                <i class="fas fa-hashtag mr-2"></i>
                Manage Streams
              </a>
              <a
                href="/streams"
                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center"
              >
                <i class="fas fa-plus mr-2"></i>
                Add Stream
              </a>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- Footer -->
    <footer class="bg-gray-800 text-white py-8 mt-12">
      <div class="container mx-auto px-4">
        <div class="flex flex-col md:flex-row justify-between items-center">
          <div class="mb-4 md:mb-0">
            <div class="flex items-center space-x-2">
              <div class="text-2xl">🌊</div>
              <div>
                <h2 class="text-xl font-bold">{{ app_name }}</h2>
                <p class="text-sm opacity-80">分流 - Divide the Flow</p>
              </div>
            </div>
            <p class="mt-2 text-sm opacity-80 max-w-md">
              Applying ancient Chinese water management principles to modern
              Fediverse content streams. Inspired by the Dujiangyan irrigation
              system (256 BC).
            </p>
          </div>

          <div class="text-center md:text-right">
            <p class="text-sm opacity-80">Version {{ app_version }}</p>
            <p class="text-sm opacity-80 mt-1">
              &copy; 2024 {{ app_name }} Project. AGPL-3.0 License.
            </p>
          </div>
        </div>
      </div>
    </footer>

    <!-- JavaScript -->
    <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 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);
      }

      function fetchStream(streamId, btn) {
        if (btn) {
          btn.disabled = true;
          btn.classList.add("opacity-50", "cursor-not-allowed");
        }
        fetch(`/api/v1/hashtags/${streamId}/fetch`, {
          method: "POST",
          headers: getHeaders("POST"),
        })
          .then((response) => response.json())
          .then((data) => {
            if (data.success) {
              location.reload();
            } else {
              showFlash(
                `Error: ${data.error_message || "Failed to fetch posts"}`,
                "error",
              );
              if (btn) {
                btn.disabled = false;
                btn.classList.remove("opacity-50", "cursor-not-allowed");
              }
            }
          })
          .catch((error) => {
            showFlash(`Error: ${error.message}`, "error");
            if (btn) {
              btn.disabled = false;
              btn.classList.remove("opacity-50", "cursor-not-allowed");
            }
          });
      }

      // Format relative time
      function formatRelativeTime(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const diffMs = now - date;
        const diffSec = Math.floor(diffMs / 1000);
        const diffMin = Math.floor(diffSec / 60);
        const diffHour = Math.floor(diffMin / 60);
        const diffDay = Math.floor(diffHour / 24);

        if (diffSec < 60) {
          return "just now";
        } else if (diffMin < 60) {
          return `${diffMin} minute${diffMin !== 1 ? "s" : ""} ago`;
        } else if (diffHour < 24) {
          return `${diffHour} hour${diffHour !== 1 ? "s" : ""} ago`;
        } else if (diffDay < 7) {
          return `${diffDay} day${diffDay !== 1 ? "s" : ""} ago`;
        } else {
          return date.toLocaleDateString();
        }
      }

      // Fetch All Active Streams
      document
        .getElementById("dashboardFetchAllBtn")
        .addEventListener("click", async function () {
          const btn = this;
          const originalHTML = btn.innerHTML;

          btn.disabled = true;
          btn.classList.add("opacity-50", "cursor-not-allowed");
          btn.innerHTML =
            '<i class="fas fa-spinner fa-spin mr-2"></i>Fetching...';

          try {
            const response = await fetch("/api/v1/hashtags", {
              headers: getHeaders("GET"),
            });
            if (!response.ok) {
              throw new Error("Failed to fetch streams");
            }
            const streams = await response.json();
            const activeStreams = streams.filter((s) => s.active);

            if (activeStreams.length === 0) {
              showFlash("No active streams to fetch.", "error");
              btn.disabled = false;
              btn.classList.remove("opacity-50", "cursor-not-allowed");
              btn.innerHTML = originalHTML;
              return;
            }

            let totalFetched = 0;
            let totalSaved = 0;
            let errors = 0;

            for (const stream of activeStreams) {
              try {
                const fetchResponse = await fetch(
                  `/api/v1/hashtags/${stream.id}/fetch`,
                  {
                    method: "POST",
                    headers: getHeaders("POST"),
                  },
                );

                if (fetchResponse.ok) {
                  const result = await fetchResponse.json();
                  totalFetched += result.posts_fetched || 0;
                  totalSaved += result.posts_saved || 0;
                } else {
                  errors++;
                }
              } catch (error) {
                errors++;
              }
            }

            btn.disabled = false;
            btn.classList.remove("opacity-50", "cursor-not-allowed");
            btn.innerHTML = originalHTML;

            if (errors > 0) {
              showFlash(
                `Fetched ${totalSaved} posts (${errors} streams had errors)`,
                "error",
              );
            } else {
              showFlash(
                `Successfully fetched ${totalSaved} new posts from ${activeStreams.length} streams`,
                "success",
              );
            }

            // Reload page after 1 second to show updated stats
            setTimeout(() => location.reload(), 1000);
          } catch (error) {
            showFlash(`Network error: ${error.message}`, "error");
            btn.disabled = false;
            btn.classList.remove("opacity-50", "cursor-not-allowed");
            btn.innerHTML = originalHTML;
          }
        });

      // Apply relative time formatting
      document.addEventListener("DOMContentLoaded", function () {
        const timeElements = document.querySelectorAll("[data-time]");
        timeElements.forEach(function (element) {
          const timeString = element.getAttribute("data-time");
          if (timeString) {
            element.textContent = formatRelativeTime(timeString);
            element.title = new Date(timeString).toLocaleString();
          }
        });
      });
    </script>
  </body>
</html>
