<!doctype html>
<html class="sl-theme-dark">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta content="Comet" property="og:title" />
    <meta content="Comet Dashboard" property="og:description" />
    <meta content="#6b6ef8" data-react-helmet="true" name="theme-color" />

    <title>Comet - Dashboard</title>
    <link
      id="favicon"
      rel="icon"
      type="image/x-icon"
      href="https://raw.githubusercontent.com/g0ldyy/comet/refs/heads/main/comet/assets/icon.png"
    />

    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/themes/dark.css"
    />
    <script
      type="module"
      src="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/shoelace-autoloader.js"
    ></script>

    <style>
      :not(:defined) {
        visibility: hidden;
      }

      ::-webkit-scrollbar {
        overflow: hidden;
      }

      body {
        margin: 0;
        padding: 20px;
        background: radial-gradient(
          ellipse at bottom,
          #25292c 0%,
          #0c0d13 100%
        );
        font-family:
          system-ui,
          -apple-system,
          "Segoe UI",
          Roboto,
          "Helvetica Neue",
          "Noto Sans",
          "Liberation Sans",
          Arial,
          sans-serif,
          "Apple Color Emoji",
          "Segoe UI Emoji",
          "Segoe UI Symbol",
          "Noto Color Emoji";
        font-size: 1rem;
        font-weight: 400;
        min-height: 100vh;
      }

      .container {
        max-width: 1400px;
        margin: 0 auto;
      }

      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
        padding: 20px;
        background-color: #1a1d20;
        border-radius: 0.5rem;
        box-shadow: 0 0.25rem 0.75rem rgba(0, 0, 0, 0.15);
      }

      .header-left {
        display: flex;
        align-items: center;
        gap: 15px;
      }

      .comet-text {
        font-size: 1.8rem;
        font-weight: 500;
        margin: 0;
        color: #ffffff;
      }

      .emoji {
        width: 1em;
        height: 1em;
        vertical-align: middle;
      }

      .admin-badge {
        background: linear-gradient(135deg, #6366f1, #8b5cf6);
        color: white;
        padding: 4px 12px;
        border-radius: 12px;
        font-size: 0.8rem;
        font-weight: 500;
      }

      .header-right {
        display: flex;
        align-items: center;
        gap: 15px;
      }

      .nav-links {
        display: flex;
        gap: 10px;
        align-items: center;
      }

      .dashboard-container {
        background-color: #1a1d20;
        border-radius: 0.5rem;
        box-shadow: 0 0.25rem 0.75rem rgba(0, 0, 0, 0.15);
        overflow: hidden;
      }

      .tab-content {
        padding: 30px;
        min-height: 500px;
      }

      .connections-table {
        width: 100%;
        margin-top: 20px;
        border-collapse: collapse;
        background-color: #374151;
        border-radius: 0.5rem;
        overflow: hidden;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      }

      .connections-table th,
      .connections-table td {
        padding: 12px 16px;
        text-align: left;
        border-bottom: 1px solid #4b5563;
      }

      .connections-table th {
        background-color: #4b5563;
        font-weight: 600;
        font-size: 0.875rem;
        color: #f3f4f6;
        text-transform: uppercase;
        letter-spacing: 0.05em;
      }

      .connections-table td {
        color: #e5e7eb;
        font-size: 0.875rem;
      }

      .connections-table tr:last-child td {
        border-bottom: none;
      }

      .connections-table tr:hover {
        background-color: #4b5563;
      }

      .connection-id {
        font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
        font-size: 0.75rem;
        background-color: #1f2937;
        padding: 4px 8px;
        border-radius: 4px;
        color: #9ca3af;
      }

      .ip-tag {
        background-color: #065f46;
        color: #d1fae5;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 0.75rem;
        font-weight: 500;
      }

      .duration-tag {
        background-color: #1e40af;
        color: #dbeafe;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 0.75rem;
        font-weight: 500;
      }

      .logs-container {
        background-color: #0f1419;
        border-radius: 0.375rem;
        padding: 20px;
        height: 500px;
        overflow-y: auto;
        font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
        font-size: 0.875rem;
        line-height: 1.5;
        border: 1px solid #374151;
      }

      .log-entry {
        margin-bottom: 8px;
        padding: 4px 8px;
        border-radius: 4px;
        white-space: pre-wrap;
        word-break: break-word;
      }

      .log-timestamp {
        color: #9ca3af;
        font-weight: 500;
      }

      .log-level {
        font-weight: 600;
        margin: 0 8px;
      }

      .log-message {
        color: #e5e7eb;
      }

      .log-module {
        color: #60a5fa;
        font-style: italic;
      }

      .stats-cards {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
      }

      .stat-card {
        background-color: #374151;
        padding: 20px;
        border-radius: 0.5rem;
        text-align: center;
      }

      .stat-number {
        font-size: 2rem;
        font-weight: 700;
        color: #10b981;
        margin-bottom: 8px;
      }

      .stat-label {
        color: #9ca3af;
        font-size: 0.875rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
      }

      .logs-controls {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        flex-wrap: wrap;
        gap: 15px;
      }

      .auto-refresh-control {
        display: flex;
        align-items: center;
        gap: 10px;
      }

      .empty-state {
        text-align: center;
        padding: 40px;
        color: #9ca3af;
      }

      .empty-state sl-icon {
        font-size: 3rem;
        margin-bottom: 15px;
        color: #6b7280;
      }

      .stars {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 120%;
        transform: rotate(-45deg);
        z-index: -1;
      }

      .star {
        --star-color: var(--primary-color);
        --star-tail-length: 6em;
        --star-tail-height: 2px;
        --star-width: calc(var(--star-tail-length) / 6);
        --fall-duration: 9s;
        --tail-fade-duration: var(--fall-duration);
        position: absolute;
        top: var(--top-offset);
        left: 0;
        width: var(--star-tail-length);
        height: var(--star-tail-height);
        color: var(--star-color);
        background: linear-gradient(45deg, currentColor, transparent);
        border-radius: 50%;
        filter: drop-shadow(0 0 6px currentColor);
        transform: translate3d(104em, 0, 0);
        animation:
          fall var(--fall-duration) var(--fall-delay) linear infinite,
          tail-fade var(--tail-fade-duration) var(--fall-delay) ease-out
            infinite;
      }

      @media screen and (max-width: 750px) {
        .star {
          animation: fall var(--fall-duration) var(--fall-delay) linear infinite;
        }
      }

      .star::before,
      .star::after {
        position: absolute;
        content: "";
        top: 0;
        left: calc(var(--star-width) / -2);
        width: var(--star-width);
        height: 100%;
        background: linear-gradient(
          45deg,
          transparent,
          currentColor,
          transparent
        );
        border-radius: inherit;
        animation: blink 2s linear infinite;
      }

      .star::before {
        transform: rotate(45deg);
      }

      .star::after {
        transform: rotate(-45deg);
      }

      @keyframes fall {
        to {
          transform: translate3d(-30em, 0, 0);
        }
      }

      @keyframes tail-fade {
        0%,
        50% {
          width: var(--star-tail-length);
          opacity: 1;
        }

        70%,
        80% {
          width: 0;
          opacity: 0.4;
        }

        100% {
          width: 0;
          opacity: 0;
        }
      }

      @keyframes blink {
        50% {
          opacity: 0.6;
        }
      }

      @media (max-width: 768px) {
        body {
          padding: 10px;
        }

        .header {
          flex-direction: column;
          gap: 15px;
          align-items: flex-start;
        }

        .header-right {
          width: 100%;
          justify-content: space-between;
        }

        .tab-content {
          padding: 20px 15px;
        }

        .logs-container {
          height: 400px;
        }
      }

      /* 📊 METRICS STYLES */
      .metrics-grid {
        display: flex;
        flex-direction: column;
        gap: 20px;
        margin-top: 20px;
      }

      .metric-section {
        background: rgba(255, 255, 255, 0.06);
        border: 1px solid rgba(255, 255, 255, 0.15);
        border-radius: 12px;
        padding: 20px;
        backdrop-filter: blur(10px);
      }

      .metric-section-compact {
        padding: 15px;
      }

      .metric-section-compact .metric-content {
        margin: 0;
      }

      .metric-section-compact .metric-subsection {
        margin-bottom: 15px;
      }

      .metric-section h3 {
        margin: 0 0 15px 0;
        color: #ffffff;
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 1.1rem;
        font-weight: 600;
      }

      .metric-section h4 {
        margin: 0 0 12px 0;
        color: #ffffff;
        font-size: 0.95rem;
        font-weight: 500;
      }

      .metric-content {
        margin: var(--sl-spacing-medium) 0;
      }

      .metric-subsection {
        margin-bottom: 25px;
      }

      .metric-subsection:last-child {
        margin-bottom: 0;
      }

      /* Tracker Statistics */
      .data-list {
        margin: var(--sl-spacing-small) 0;
      }

      .tracker-item {
        background: rgba(255, 255, 255, 0.08);
        border: 1px solid rgba(255, 255, 255, 0.12);
        border-radius: 8px;
        padding: 12px;
        margin-bottom: 8px;
        transition: background-color 0.2s ease;
      }

      .tracker-item:hover {
        background: rgba(255, 255, 255, 0.12);
      }

      .tracker-name {
        font-weight: 600;
        color: #ffffff;
        margin-bottom: 4px;
        font-size: 0.9rem;
      }

      .tracker-stats {
        display: flex;
        gap: 15px;
        flex-wrap: wrap;
        font-size: 0.8rem;
        color: #e0e0e0;
      }

      .tracker-stats span {
        background: rgba(255, 255, 255, 0.12);
        padding: 2px 6px;
        border-radius: 4px;
      }

      /* Size Distribution Chart */
      .size-chart {
        margin: var(--sl-spacing-small) 0;
      }

      .size-bar {
        margin-bottom: 12px;
      }

      .size-label {
        font-size: 0.85rem;
        color: #ffffff;
        margin-bottom: 4px;
        font-weight: 500;
      }

      .size-progress {
        position: relative;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 6px;
        height: 20px;
        overflow: hidden;
      }

      .size-fill {
        height: 100%;
        background: linear-gradient(
          90deg,
          var(--sl-color-primary-600),
          var(--sl-color-primary-500)
        );
        border-radius: 6px;
        transition: width 0.6s ease-in-out;
      }

      .size-percentage {
        position: absolute;
        top: 50%;
        left: 8px;
        transform: translateY(-50%);
        font-size: 0.75rem;
        color: var(--sl-color-neutral-50);
        font-weight: 600;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
      }

      /* Quality Metrics Grid */
      .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
        gap: 15px;
      }

      .stat-item {
        text-align: center;
        background: rgba(255, 255, 255, 0.08);
        border-radius: 8px;
        padding: 15px 10px;
        border: 1px solid rgba(255, 255, 255, 0.12);
      }

      .stat-value {
        display: block;
        font-size: 1.2rem;
        font-weight: 700;
        color: var(--sl-color-primary-400);
        margin-bottom: 4px;
      }

      .stat-desc {
        display: block;
        font-size: 0.75rem;
        color: #d0d0d0;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      }

      /* Search Analytics */
      .search-timeline {
        display: flex;
        justify-content: space-around;
        gap: 20px;
      }

      .timeline-item {
        text-align: center;
        flex: 1;
        background: rgba(255, 255, 255, 0.08);
        border-radius: 10px;
        padding: 20px 15px;
        border: 1px solid rgba(255, 255, 255, 0.12);
      }

      .timeline-period {
        font-size: 0.8rem;
        color: #d0d0d0;
        margin-bottom: 8px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
      }

      .timeline-count {
        font-size: 1.8rem;
        font-weight: 700;
        color: var(--sl-color-primary-400);
      }

      /* Media Distribution */
      .media-stats {
        display: flex;
        gap: 30px;
        justify-content: center;
      }

      .media-item {
        display: flex;
        align-items: center;
        gap: 15px;
        background: rgba(255, 255, 255, 0.08);
        border-radius: 10px;
        padding: 20px;
        border: 1px solid rgba(255, 255, 255, 0.12);
        flex: 1;
        min-width: 150px;
      }

      .media-icon {
        font-size: 2rem;
        color: var(--sl-color-primary-400);
      }

      .media-type {
        font-weight: 600;
        color: #ffffff;
        margin-bottom: 4px;
        font-size: 0.9rem;
      }

      .media-count {
        font-size: 1.1rem;
        font-weight: 700;
        color: var(--sl-color-primary-400);
      }

      /* Loading States */
      .loading-state {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        padding: 40px;
        color: #e0e0e0;
        font-size: 0.9rem;
      }

      /* Debrid Cache Styles */
      .debrid-performance {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: 15px;
        margin-bottom: 20px;
      }

      .debrid-stat {
        text-align: center;
        background: rgba(255, 255, 255, 0.08);
        border-radius: 8px;
        padding: 15px;
        border: 1px solid rgba(255, 255, 255, 0.12);
      }

      .debrid-label {
        font-weight: 600;
        color: #ffffff;
        margin-bottom: 8px;
        font-size: 0.85rem;
      }

      .debrid-value {
        font-size: 1.4rem;
        font-weight: 700;
        color: var(--sl-color-primary-400);
      }

      .debrid-service-item {
        background: rgba(255, 255, 255, 0.08);
        border: 1px solid rgba(255, 255, 255, 0.12);
        border-radius: 8px;
        padding: 12px;
        margin-bottom: 8px;
        transition: background-color 0.2s ease;
      }

      .debrid-service-item:hover {
        background: rgba(255, 255, 255, 0.12);
      }

      .debrid-service-name {
        font-weight: 600;
        color: #ffffff;
        margin-bottom: 4px;
        font-size: 0.9rem;
        text-transform: capitalize;
      }

      .debrid-service-stats {
        display: flex;
        gap: 15px;
        flex-wrap: wrap;
        font-size: 0.8rem;
        color: #e0e0e0;
      }

      .debrid-service-stats span {
        background: rgba(255, 255, 255, 0.12);
        padding: 2px 6px;
        border-radius: 4px;
      }

      /* Responsive Design for Metrics */
      @media (max-width: 768px) {
        .search-timeline {
          flex-direction: column;
          gap: 15px;
        }

        .media-stats {
          flex-direction: column;
          gap: 15px;
        }

        .tracker-stats {
          flex-direction: column;
          gap: 8px;
        }

        .stats-grid {
          grid-template-columns: repeat(2, 1fr);
        }
      }
    </style>
  </head>

  <body>
    <div class="stars"></div>

    <script>
      let hasTouchScreen = false;
      if ("maxTouchPoints" in navigator) {
        hasTouchScreen = navigator.maxTouchPoints > 0;
      } else if ("msMaxTouchPoints" in navigator) {
        hasTouchScreen = navigator.msMaxTouchPoints > 0;
      } else {
        const mQ = matchMedia?.("(pointer:coarse)");
        if (mQ?.media === "(pointer:coarse)") {
          hasTouchScreen = !!mQ.matches;
        } else if ("orientation" in window) {
          hasTouchScreen = true;
        } else {
          const UA = navigator.userAgent;
          hasTouchScreen =
            /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
            /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA);
        }
      }

      if (!hasTouchScreen) {
        document.addEventListener("DOMContentLoaded", function () {
          const starsContainer = document.querySelector(".stars");
          const starCount = 30;

          for (let i = 0; i < starCount; i++) {
            const star = document.createElement("div");
            star.classList.add("star");

            const randomTopOffset = Math.random() * 100;
            const randomLeftOffset = 80 + Math.random() * 40;
            const randomTailLength = 5 + Math.random() * 2.5;
            const randomFallDuration = 6 + Math.random() * 6;

            star.style.setProperty("--top-offset", `${randomTopOffset}vh`);
            star.style.setProperty(
              "--star-tail-length",
              `${randomTailLength}em`,
            );
            star.style.setProperty("--fall-duration", `${randomFallDuration}s`);
            star.style.setProperty("--fall-delay", "0s");
            star.style.transform = `translate3d(${randomLeftOffset}em, 0, 0)`;

            starsContainer.appendChild(star);
          }
        });
      }
    </script>

    <div class="container">
      <div class="header">
        <div class="header-left">
          <h1 class="comet-text">
            <img
              class="emoji"
              src="https://fonts.gstatic.com/s/e/notoemoji/latest/1f4ab/512.gif"
            />
            Comet
          </h1>
          <div class="admin-badge">Dashboard</div>
        </div>
        <div class="header-right">
          <div class="nav-links">
            <sl-button
              variant="neutral"
              size="small"
              onclick="window.open('/configure', '_blank')"
            >
              <sl-icon slot="prefix" name="gear"></sl-icon>
              Configuration
            </sl-button>
          </div>
          <form method="post" action="/admin/logout" style="margin: 0">
            <sl-button type="submit" variant="danger" size="small">
              <sl-icon slot="prefix" name="box-arrow-right"></sl-icon>
              Logout
            </sl-button>
          </form>
        </div>
      </div>

      <div class="dashboard-container">
        <sl-tab-group>
          <sl-tab slot="nav" panel="connections">
            <sl-icon name="wifi"></sl-icon>
            &nbsp;Active Connections
          </sl-tab>
          <sl-tab slot="nav" panel="logs">
            <sl-icon name="list-ul"></sl-icon>
            &nbsp;System Logs
          </sl-tab>
          <sl-tab slot="nav" panel="metrics">
            <sl-icon name="bar-chart"></sl-icon>
            &nbsp;Metrics
          </sl-tab>

          <sl-tab-panel name="connections">
            <div class="tab-content">
              <div class="stats-cards">
                <div class="stat-card">
                  <div class="stat-number" id="total-connections">0</div>
                  <div class="stat-label">Active Connections</div>
                </div>
                <div class="stat-card">
                  <div class="stat-number" id="unique-ips">0</div>
                  <div class="stat-label">Unique IPs</div>
                </div>
                <div class="stat-card">
                  <div class="stat-number" id="avg-duration">0s</div>
                  <div class="stat-label">Avg Duration</div>
                </div>
                <div class="stat-card">
                  <div class="stat-number" id="total-speed">0 B/s</div>
                  <div class="stat-label">Total Speed</div>
                </div>
                <div class="stat-card">
                  <div class="stat-number" id="session-bandwidth">0 B</div>
                  <div class="stat-label">Session Bandwidth</div>
                </div>
                <div class="stat-card">
                  <div class="stat-number" id="alltime-bandwidth">0 B</div>
                  <div class="stat-label">All-time Bandwidth</div>
                </div>
              </div>

              <div id="connections-content">
                <div class="empty-state">
                  <sl-icon name="wifi-off"></sl-icon>
                  <p>No active connections</p>
                </div>
              </div>
            </div>
          </sl-tab-panel>

          <sl-tab-panel name="logs">
            <div class="tab-content">
              <div class="logs-controls">
                <div>
                  <sl-button id="clear-logs" variant="neutral" size="small">
                    <sl-icon slot="prefix" name="trash"></sl-icon>
                    Clear Display
                  </sl-button>
                  <sl-button id="download-logs" variant="neutral" size="small">
                    <sl-icon slot="prefix" name="download"></sl-icon>
                    Download Logs
                  </sl-button>
                </div>
                <div class="auto-refresh-control">
                  <sl-switch id="hide-api-logs" checked
                    >Hide API Logs</sl-switch
                  >
                  <sl-switch id="auto-refresh" checked>Auto Refresh</sl-switch>
                  <sl-select
                    id="refresh-interval"
                    value="5000"
                    size="small"
                    style="width: 120px"
                  >
                    <sl-option value="1000">1s</sl-option>
                    <sl-option value="2000">2s</sl-option>
                    <sl-option value="5000">5s</sl-option>
                    <sl-option value="10000">10s</sl-option>
                  </sl-select>
                </div>
              </div>

              <div class="logs-container" id="logs-container">
                <div class="empty-state">
                  <sl-icon name="journal-text"></sl-icon>
                  <p>Loading system logs...</p>
                </div>
              </div>
            </div>
          </sl-tab-panel>

          <sl-tab-panel name="metrics">
            <div class="tab-content">
              <!-- Overview Cards -->
              <div class="stats-cards">
                <div class="stat-card">
                  <div class="stat-number" id="total-torrents">0</div>
                  <div class="stat-label">Total Torrents</div>
                </div>
                <div class="stat-card">
                  <div class="stat-number" id="unique-searches">0</div>
                  <div class="stat-label">Unique Searches</div>
                </div>
                <div class="stat-card">
                  <div class="stat-number" id="active-scrapers">0</div>
                  <div class="stat-label">Active Scrapers</div>
                </div>
              </div>

              <!-- Metrics Sections -->
              <div class="metrics-grid">
                <!-- Media Distribution -->
                <div class="metric-section metric-section-compact">
                  <h3><sl-icon name="film"></sl-icon> Media Distribution</h3>
                  <div class="metric-content">
                    <div id="media-distribution" class="media-chart">
                      <div class="loading-state">
                        <sl-spinner></sl-spinner>
                        <span>Loading media distribution...</span>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- Torrents Section -->
                <div class="metric-section">
                  <h3><sl-icon name="download"></sl-icon> Torrents Analysis</h3>
                  <div class="metric-content">
                    <div class="metric-subsection">
                      <div
                        style="
                          display: flex;
                          justify-content: space-between;
                          align-items: center;
                          margin-bottom: 12px;
                        "
                      >
                        <h4 style="margin: 0">Top Trackers</h4>
                        <sl-select
                          id="tracker-limit"
                          size="small"
                          value="5"
                          style="width: 110px"
                        >
                          <sl-option value="5">Top 5</sl-option>
                          <sl-option value="10">Top 10</sl-option>
                          <sl-option value="20">Top 20</sl-option>
                          <sl-option value="50">Top 50</sl-option>
                          <sl-option value="all">All</sl-option>
                        </sl-select>
                      </div>
                      <div id="tracker-stats" class="data-list">
                        <div class="loading-state">
                          <sl-spinner></sl-spinner>
                          <span>Loading tracker statistics...</span>
                        </div>
                      </div>
                    </div>

                    <div class="metric-subsection">
                      <h4>Size Distribution</h4>
                      <div id="size-distribution" class="chart-container">
                        <div class="loading-state">
                          <sl-spinner></sl-spinner>
                          <span>Loading size distribution...</span>
                        </div>
                      </div>
                    </div>

                    <div class="metric-subsection">
                      <h4>Quality Metrics</h4>
                      <div id="quality-metrics" class="stats-grid">
                        <div class="stat-item">
                          <span class="stat-value" id="avg-seeders">-</span>
                          <span class="stat-desc">Avg Seeders</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-value" id="max-seeders">-</span>
                          <span class="stat-desc">Max Seeders</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-value" id="avg-size">-</span>
                          <span class="stat-desc">Avg Size</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-value" id="max-size">-</span>
                          <span class="stat-desc">Max Size</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- Debrid Cache Distribution -->
                <div class="metric-section">
                  <h3>
                    <sl-icon name="cloud-arrow-down"></sl-icon> Debrid Cache
                    Distribution
                  </h3>
                  <div class="metric-content">
                    <div class="metric-subsection">
                      <h4>Cache Performance</h4>
                      <div class="debrid-performance">
                        <div class="debrid-stat">
                          <div class="debrid-label">Total Cached Items</div>
                          <div class="debrid-value" id="debrid-total">0</div>
                        </div>
                      </div>
                    </div>

                    <div class="metric-subsection">
                      <h4>By Service Provider</h4>
                      <div id="debrid-services" class="data-list">
                        <div class="loading-state">
                          <sl-spinner></sl-spinner>
                          <span>Loading debrid services...</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- Search Analytics -->
                <div class="metric-section metric-section-compact">
                  <h3><sl-icon name="search"></sl-icon> Search Analytics</h3>
                  <div class="metric-content">
                    <div class="search-timeline">
                      <div class="timeline-item">
                        <div class="timeline-period">Last 24h</div>
                        <div class="timeline-count" id="searches-24h">0</div>
                      </div>
                      <div class="timeline-item">
                        <div class="timeline-period">Last 7 days</div>
                        <div class="timeline-count" id="searches-7d">0</div>
                      </div>
                      <div class="timeline-item">
                        <div class="timeline-period">Last 30 days</div>
                        <div class="timeline-count" id="searches-30d">0</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </sl-tab-panel>
        </sl-tab-group>
      </div>
    </div>

    <script>
      document.addEventListener("DOMContentLoaded", async () => {
        await Promise.allSettled([
          customElements.whenDefined("sl-tab-group"),
          customElements.whenDefined("sl-tab"),
          customElements.whenDefined("sl-tab-panel"),
          customElements.whenDefined("sl-button"),
          customElements.whenDefined("sl-icon"),
          customElements.whenDefined("sl-spinner"),
          customElements.whenDefined("sl-switch"),
          customElements.whenDefined("sl-select"),
          customElements.whenDefined("sl-option"),
        ]);

        document.body.classList.add("ready");

        // Initialize dashboard
        initializeDashboard();
      });

      let currentMetricsData = null;
      let connectionsInterval;
      let logsInterval;
      let lastLogTimestamp = 0;

      function initializeDashboard() {
        // Load initial data
        loadConnections();
        loadLogs();

        // Set up auto-refresh
        setupAutoRefresh();

        // Event listeners
        document
          .getElementById("clear-logs")
          .addEventListener("click", clearLogsDisplay);
        document
          .getElementById("download-logs")
          .addEventListener("click", downloadLogs);
        document
          .getElementById("auto-refresh")
          .addEventListener("sl-change", toggleAutoRefresh);
        document
          .getElementById("refresh-interval")
          .addEventListener("sl-change", updateRefreshInterval);
        document
          .getElementById("hide-api-logs")
          .addEventListener("sl-change", toggleApiLogsVisibility);
        document
          .getElementById("tracker-limit")
          .addEventListener("sl-change", () => {
            if (currentMetricsData) {
              updateTorrentsSection(currentMetricsData.torrents);
            }
          });

        // Tab change handler
        document
          .querySelector("sl-tab-group")
          .addEventListener("sl-tab-show", handleTabChange);
      }

      function setupAutoRefresh() {
        // Connections refresh every 5 seconds
        connectionsInterval = setInterval(loadConnections, 5000);

        // Logs refresh based on selected interval
        const interval = parseInt(
          document.getElementById("refresh-interval").value,
        );
        logsInterval = setInterval(loadLogs, interval);
      }

      function toggleAutoRefresh(e) {
        if (e.target.checked) {
          setupAutoRefresh();
        } else {
          clearInterval(connectionsInterval);
          clearInterval(logsInterval);
        }
      }

      function updateRefreshInterval() {
        if (document.getElementById("auto-refresh").checked) {
          clearInterval(logsInterval);
          const interval = parseInt(
            document.getElementById("refresh-interval").value,
          );
          logsInterval = setInterval(loadLogs, interval);
        }
      }

      function handleTabChange(e) {
        const activePanel = e.detail.name;
        if (activePanel === "connections") {
          loadConnections();
        } else if (activePanel === "logs") {
          loadLogs();
        } else if (activePanel === "metrics") {
          loadMetrics();
        }
      }

      async function loadConnections() {
        try {
          const response = await fetch("/admin/api/connections");
          const data = await response.json();

          updateConnectionsStats(data.connections, data.global_stats);
          renderConnectionsTable(data.connections);
        } catch (error) {
          console.error("Failed to load connections:", error);
          document.getElementById("connections-content").innerHTML =
            '<div class="empty-state"><sl-icon name="exclamation-triangle"></sl-icon><p>Failed to load connections</p></div>';
        }
      }

      function updateConnectionsStats(connections, globalStats) {
        const totalConnections = connections.length;
        const uniqueIPs = [...new Set(connections.map((c) => c.ip))].length;
        const avgDuration =
          connections.length > 0
            ? Math.round(
                connections.reduce((sum, c) => sum + c.duration, 0) /
                  connections.length,
              )
            : 0;

        document.getElementById("total-connections").textContent =
          totalConnections;
        document.getElementById("unique-ips").textContent = uniqueIPs;
        document.getElementById("avg-duration").textContent = `${avgDuration}s`;

        if (globalStats) {
          document.getElementById("total-speed").textContent =
            globalStats.total_current_speed_formatted || "0 B/s";
          document.getElementById("session-bandwidth").textContent =
            globalStats.total_bytes_session_formatted || "0 B";
          document.getElementById("alltime-bandwidth").textContent =
            globalStats.total_bytes_alltime_formatted || "0 B";
        }
      }

      function renderConnectionsTable(connections) {
        const container = document.getElementById("connections-content");

        if (connections.length === 0) {
          container.innerHTML =
            '<div class="empty-state"><sl-icon name="wifi-off"></sl-icon><p>No active connections</p></div>';
          return;
        }

        const tableHTML = `
                    <table class="connections-table">
                        <thead>
                            <tr>
                                <th>Connection ID</th>
                                <th>IP Address</th>
                                <th>Content</th>
                                <th>Started</th>
                                <th>Duration</th>
                                <th>Transferred</th>
                                <th>Current Speed</th>
                                <th>Peak Speed</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${connections
                              .map(
                                (conn) => `
                                <tr>
                                    <td>
                                        <span class="connection-id">${conn.id.substring(
                                          0,
                                          8,
                                        )}...</span>
                                    </td>
                                    <td>
                                        <span class="ip-tag">${conn.ip}</span>
                                    </td>
                                    <td>
                                        <span title="${escapeHtml(
                                          conn.content,
                                        )}">${
                                          conn.content.length > 25
                                            ? escapeHtml(
                                                conn.content.substring(0, 25),
                                              ) + "..."
                                            : escapeHtml(conn.content)
                                        }</span>
                                    </td>
                                    <td>
                                        <span style="font-size: 0.875rem; color: #9ca3af;">${
                                          conn.formatted_time
                                        }</span>
                                    </td>
                                    <td>
                                        <span class="duration-tag">${Math.round(
                                          conn.duration,
                                        )}s</span>
                                    </td>
                                    <td>
                                        <span class="bandwidth-tag" style="background-color: #059669; color: #d1fae5; padding: 4px 8px; border-radius: 4px; font-size: 0.75rem; font-weight: 500;">${
                                          conn.bytes_transferred_formatted ||
                                          "0 B"
                                        }</span>
                                    </td>
                                    <td>
                                        <span class="speed-tag" style="background-color: #7c3aed; color: #e9d5ff; padding: 4px 8px; border-radius: 4px; font-size: 0.75rem; font-weight: 500;">${
                                          conn.current_speed_formatted ||
                                          "0 B/s"
                                        }</span>
                                    </td>
                                    <td>
                                        <span class="peak-speed-tag" style="background-color: #dc2626; color: #fecaca; padding: 4px 8px; border-radius: 4px; font-size: 0.75rem; font-weight: 500;">${
                                          conn.peak_speed_formatted || "0 B/s"
                                        }</span>
                                    </td>
                                </tr>
                            `,
                              )
                              .join("")}
                        </tbody>
                    </table>
                `;

        container.innerHTML = tableHTML;
      }

      async function loadLogs() {
        try {
          const response = await fetch(
            `/admin/api/logs?since=${lastLogTimestamp}`,
          );
          const data = await response.json();

          appendLogs(data.logs);

          if (data.logs.length > 0) {
            lastLogTimestamp = Math.max(...data.logs.map((log) => log.created));
          }
        } catch (error) {
          console.error("Failed to load logs:", error);
        }
      }

      function appendLogs(logs) {
        const container = document.getElementById("logs-container");
        const hideApiLogs = document.getElementById("hide-api-logs").checked;

        // Remove empty state if present
        if (container.querySelector(".empty-state")) {
          container.innerHTML = "";
        }

        logs.forEach((log) => {
          // Filter out API logs if hideApiLogs is enabled
          if (hideApiLogs && isApiLog(log)) {
            return;
          }

          const logEntry = document.createElement("div");
          logEntry.className = "log-entry";

          // Add data attribute to identify API logs for toggling
          if (isApiLog(log)) {
            logEntry.setAttribute("data-api-log", "true");
          }

          logEntry.innerHTML = `<span class="log-timestamp">${
            log.timestamp
          }</span> <span class="log-level" style="color: ${log.color};">${
            log.icon
          } ${log.level}</span> <span class="log-module">${log.module}.${
            log.function
          }</span> - <span class="log-message">${escapeHtml(
            log.message,
          )}</span>`;

          container.appendChild(logEntry);
        });

        // Auto-scroll to bottom
        container.scrollTop = container.scrollHeight;

        // Limit number of log entries to prevent memory issues
        const maxEntries = 500;
        while (container.children.length > maxEntries) {
          container.removeChild(container.firstChild);
        }
      }

      function clearLogsDisplay() {
        document.getElementById("logs-container").innerHTML = "";
        lastLogTimestamp = Date.now() / 1000;
      }

      function downloadLogs() {
        const logEntries = Array.from(document.querySelectorAll(".log-entry"));
        const logText = logEntries.map((entry) => entry.textContent).join("\n");

        const blob = new Blob([logText], { type: "text/plain" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `comet-logs-${new Date()
          .toISOString()
          .slice(0, 19)
          .replace(/:/g, "-")}.txt`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }

      function isApiLog(log) {
        return log.message.includes("/admin/api/");
      }

      function toggleApiLogsVisibility() {
        const hideApiLogs = document.getElementById("hide-api-logs").checked;
        const container = document.getElementById("logs-container");
        const apiLogEntries = container.querySelectorAll(
          '[data-api-log="true"]',
        );

        apiLogEntries.forEach((entry) => {
          entry.style.display = hideApiLogs ? "none" : "block";
        });
      }

      function escapeHtml(text) {
        const div = document.createElement("div");
        div.textContent = text;
        return div.innerHTML;
      }

      // 📊 METRICS FUNCTIONS
      async function loadMetrics() {
        try {
          const response = await fetch("/admin/api/metrics");
          const data = await response.json();
          currentMetricsData = data;

          updateMetricsOverview(data);
          updateTorrentsSection(data.torrents);
          updateSearchSection(data.searches);
          updateMediaDistribution(data.torrents.media_distribution);
          updateDebridCacheSection(data.debrid_cache);
        } catch (error) {
          console.error("Failed to load metrics:", error);
          showMetricsError();
        }
      }

      function updateMetricsOverview(data) {
        document.getElementById("total-torrents").textContent =
          data.torrents.total.toLocaleString();
        document.getElementById("unique-searches").textContent =
          data.searches.total_unique.toLocaleString();
        document.getElementById("active-scrapers").textContent =
          data.scrapers.active_locks;
      }

      function updateTorrentsSection(torrentsData) {
        // Update tracker statistics
        const trackerContainer = document.getElementById("tracker-stats");
        const limitSelect = document.getElementById("tracker-limit");
        const limit = limitSelect ? limitSelect.value : "5";

        let displayTrackers = torrentsData.by_tracker;
        if (limit !== "all") {
          displayTrackers = displayTrackers.slice(0, parseInt(limit));
        }

        if (displayTrackers.length === 0) {
          trackerContainer.innerHTML =
            '<div class="empty-state"><sl-icon name="database-slash"></sl-icon><p>No tracker data available</p></div>';
        } else {
          trackerContainer.innerHTML = displayTrackers
            .map(
              (tracker) => `
            <div class="tracker-item">
              <div class="tracker-name">${escapeHtml(
                tracker.tracker || "Unknown",
              )}</div>
              <div class="tracker-stats">
                <span class="tracker-count">${tracker.count.toLocaleString()} torrents</span>
                <span class="tracker-seeders">${
                  tracker.avg_seeders
                } avg seeders</span>
                <span class="tracker-size">${
                  tracker.avg_size_formatted
                } avg size</span>
              </div>
            </div>
          `,
            )
            .join("");
        }

        // Update size distribution chart
        updateSizeDistribution(torrentsData.size_distribution);

        // Update quality metrics
        document.getElementById("avg-seeders").textContent =
          torrentsData.quality.avg_seeders;
        document.getElementById("max-seeders").textContent =
          torrentsData.quality.max_seeders.toLocaleString();
        document.getElementById("avg-size").textContent =
          torrentsData.quality.avg_size_formatted;
        document.getElementById("max-size").textContent =
          torrentsData.quality.max_size_formatted;
      }

      function updateSizeDistribution(sizeData) {
        const container = document.getElementById("size-distribution");
        if (sizeData.length === 0) {
          container.innerHTML =
            '<div class="empty-state"><sl-icon name="pie-chart"></sl-icon><p>No size data available</p></div>';
          return;
        }

        const total = sizeData.reduce((sum, item) => sum + item.count, 0);
        container.innerHTML = `
          <div class="size-chart">
            ${sizeData
              .map((item) => {
                const percentage = ((item.count / total) * 100).toFixed(1);
                return `
                <div class="size-bar">
                  <div class="size-label">${item.range}</div>
                  <div class="size-progress">
                    <div class="size-fill" style="width: ${percentage}%"></div>
                    <span class="size-percentage">${percentage}% (${item.count.toLocaleString()})</span>
                  </div>
                </div>
              `;
              })
              .join("")}
          </div>
        `;
      }

      function updateSearchSection(searchData) {
        document.getElementById("searches-24h").textContent =
          searchData.last_24h.toLocaleString();
        document.getElementById("searches-7d").textContent =
          searchData.last_7d.toLocaleString();
        document.getElementById("searches-30d").textContent =
          searchData.last_30d.toLocaleString();
      }

      function updateMediaDistribution(mediaData) {
        const container = document.getElementById("media-distribution");
        if (mediaData.length === 0) {
          container.innerHTML =
            '<div class="empty-state"><sl-icon name="film"></sl-icon><p>No media data available</p></div>';
          return;
        }

        const total = mediaData.reduce((sum, item) => sum + item.count, 0);
        container.innerHTML = `
          <div class="media-stats">
            ${mediaData
              .map((item) => {
                const percentage = ((item.count / total) * 100).toFixed(1);
                const icon = item.type === "Movies" ? "film" : "tv";
                return `
                <div class="media-item">
                  <div class="media-icon">
                    <sl-icon name="${icon}"></sl-icon>
                  </div>
                  <div class="media-details">
                    <div class="media-type">${item.type}</div>
                    <div class="media-count">${item.count.toLocaleString()} (${percentage}%)</div>
                  </div>
                </div>
              `;
              })
              .join("")}
          </div>
        `;
      }

      function showMetricsError() {
        const sections = document.querySelectorAll(
          ".metric-section .loading-state",
        );
        sections.forEach((section) => {
          section.innerHTML =
            '<sl-icon name="exclamation-triangle"></sl-icon><span>Failed to load metrics</span>';
        });
      }

      function updateDebridCacheSection(debridData) {
        // Update performance stats
        document.getElementById("debrid-total").textContent =
          debridData.total.toLocaleString();

        // Update services list
        const servicesContainer = document.getElementById("debrid-services");
        if (debridData.by_service.length === 0) {
          servicesContainer.innerHTML =
            '<div class="empty-state"><sl-icon name="cloud-slash"></sl-icon><p>No debrid cache data available</p></div>';
        } else {
          servicesContainer.innerHTML = debridData.by_service
            .map(
              (service) => `
                <div class="debrid-service-item">
                  <div class="debrid-service-name">${escapeHtml(
                    service.service,
                  )}</div>
                  <div class="debrid-service-stats">
                    <span class="service-count">${service.count.toLocaleString()} files</span>
                    <span class="service-avg-size">Avg: ${
                      service.avg_size_formatted
                    }</span>
                    <span class="service-total-size">Total: ${
                      service.total_size_formatted
                    }</span>
                  </div>
                </div>
              `,
            )
            .join("");
        }
      }
    </script>
  </body>
</html>
