<!DOCTYPE html>
<html>
  <head>
    <title>Pilgrimage Dashboard</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        min-height: 100vh;
      }
      .login-screen {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100vh;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        z-index: 1000;
      }
      .login-box {
        background: white;
        padding: 40px;
        border-radius: 10px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        width: 100%;
        max-width: 400px;
        text-align: center;
      }
      .login-box h1 {
        color: #333;
        margin-bottom: 30px;
        font-size: 28px;
      }
      .login-form {
        display: flex;
        flex-direction: column;
        gap: 20px;
      }
      .login-input {
        padding: 12px 16px;
        border: 1px solid #ddd;
        border-radius: 6px;
        font-size: 16px;
        transition: border-color 0.3s;
      }
      .login-input:focus {
        outline: none;
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
      }
      .login-button {
        padding: 12px 24px;
        background: #667eea;
        color: white;
        border: none;
        border-radius: 6px;
        font-size: 16px;
        cursor: pointer;
        transition: background 0.3s;
      }
      .login-button:hover {
        background: #5a6fd8;
      }
      .login-error {
        color: #dc3545;
        background: #f8d7da;
        border: 1px solid #f5c6cb;
        padding: 10px;
        border-radius: 4px;
        margin-top: 15px;
      }
      .main-dashboard {
        display: none;
        min-height: 100vh;
        padding: 20px;
        color: white;
      }
      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: rgba(255, 255, 255, 0.1);
        padding: 20px;
        border-radius: 10px;
        margin-bottom: 30px;
        backdrop-filter: blur(10px);
      }
      .user-info {
        color: white;
        font-size: 14px;
      }
      .logout-button {
        background: rgba(255, 255, 255, 0.2);
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 6px;
        cursor: pointer;
        transition: background 0.3s;
      }
      .logout-button:hover {
        background: rgba(255, 255, 255, 0.3);
      }
      .dashboard-container {
        max-width: 1400px;
        margin: 0 auto;
      }
      .dashboard-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
      }
      .dashboard-card {
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(10px);
        padding: 20px;
        border-radius: 10px;
        border: 1px solid rgba(255, 255, 255, 0.2);
      }
      .dashboard-card h3 {
        margin-top: 0;
        color: white;
        font-size: 18px;
      }
      .metric-value {
        font-size: 32px;
        font-weight: bold;
        color: #fff;
        margin: 10px 0;
      }
      .metric-label {
        font-size: 14px;
        opacity: 0.8;
        color: #fff;
      }
      .status-indicator {
        display: inline-block;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        margin-right: 8px;
      }
      .status-healthy {
        background-color: #28a745;
      }
      .status-warning {
        background-color: #ffc107;
      }
      .status-error {
        background-color: #dc3545;
      }
      .refresh-button {
        background: rgba(255, 255, 255, 0.2);
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 6px;
        cursor: pointer;
        margin: 10px 0;
        transition: background 0.3s;
      }
      .refresh-button:hover {
        background: rgba(255, 255, 255, 0.3);
      }
      .chart-container {
        background: rgba(255, 255, 255, 0.9);
        padding: 20px;
        border-radius: 10px;
        color: #333;
        margin-top: 20px;
      }
      .loading {
        text-align: center;
        opacity: 0.7;
        padding: 20px;
      }
      .metrics-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 15px;
        margin-bottom: 20px;
      }
      .metric-card {
        background: rgba(0, 0, 0, 0.1);
        padding: 15px;
        border-radius: 8px;
        border-left: 4px solid #007bff;
      }
      .metric-card h4 {
        margin: 0 0 10px 0;
        color: #333;
        font-size: 16px;
      }
      .metric-row {
        display: flex;
        justify-content: space-between;
        margin: 8px 0;
        font-size: 14px;
      }
      .metric-row span:first-child {
        color: #666;
      }
      .metric-row span:last-child {
        font-weight: bold;
        color: #333;
      }
      .status-healthy {
        color: #28a745;
      }
      .status-warning {
        color: #ffc107;
      }
      .status-error {
        color: #dc3545;
      }
      .status-unknown {
        color: #6c757d;
      }
      .last-updated {
        text-align: center;
        font-size: 12px;
        color: #666;
        margin-top: 15px;
        padding-top: 15px;
        border-top: 1px solid #ddd;
      }
    </style>
  </head>
  <body>
    <!-- ログイン画面 -->
    <div id="login-screen" class="login-screen">
      <div class="login-box">
        <h1>🚀 Pilgrimage Dashboard</h1>
        <form class="login-form" onsubmit="handleLogin(event)">
          <input
            type="text"
            id="login-username"
            class="login-input"
            placeholder="Username"
            required
          />
          <input
            type="password"
            id="login-password"
            class="login-input"
            placeholder="Password"
            required
          />
          <button type="submit" class="login-button">🔐 Login</button>
        </form>
        <div id="login-error" class="login-error" style="display: none"></div>
      </div>
    </div>

    <!-- メインダッシュボード -->
    <div id="main-dashboard" class="main-dashboard">
      <div class="header">
        <div class="user-info">
          <span id="user-display"
            >👤 Welcome, <span id="username-display"></span> (<span
              id="role-display"
            ></span
            >)</span
          >
        </div>
        <h1>📊 Pilgrimage Dashboard</h1>
        <button class="logout-button" onclick="handleLogout()">
          🚪 Logout
        </button>
      </div>

      <div class="dashboard-container">
        <div class="dashboard-grid">
          <div class="dashboard-card">
            <h3>🏥 Cluster Health</h3>
            <div class="metric-value" id="cluster-status">
              <span class="status-indicator status-healthy"></span>Loading...
            </div>
            <div class="metric-label">
              Active Brokers: <span id="active-brokers">-</span>
            </div>
            <div class="metric-label">
              Total Topics: <span id="total-topics">-</span>
            </div>
            <button class="refresh-button" onclick="refreshClusterHealth()">
              🔄 Refresh
            </button>
          </div>

          <div class="dashboard-card">
            <h3>📈 Throughput</h3>
            <div class="metric-value" id="messages-per-sec">-</div>
            <div class="metric-label">Messages/sec</div>
            <div class="metric-label">
              In: <span id="bytes-in">-</span> | Out:
              <span id="bytes-out">-</span>
            </div>
            <button class="refresh-button" onclick="refreshThroughput()">
              🔄 Refresh
            </button>
          </div>

          <div class="dashboard-card">
            <h3>⚡ Performance</h3>
            <div class="metric-value" id="avg-latency">-</div>
            <div class="metric-label">Avg Latency (ms)</div>
            <div class="metric-label">
              P99: <span id="p99-latency">-</span> ms
            </div>
            <button class="refresh-button" onclick="refreshPerformance()">
              🔄 Refresh
            </button>
          </div>

          <div class="dashboard-card">
            <h3>💾 Storage</h3>
            <div class="metric-value" id="total-messages">-</div>
            <div class="metric-label">Total Messages</div>
            <div class="metric-label">
              Log Size: <span id="log-size">-</span>
            </div>
            <button class="refresh-button" onclick="refreshStorage()">
              🔄 Refresh
            </button>
          </div>
        </div>

        <div class="chart-container">
          <h3>📊 Real-time Metrics</h3>
          <div id="metrics-content" class="loading">
            Loading dashboard data...
          </div>
          <button class="refresh-button" onclick="refreshDashboard()">
            🔄 Refresh All
          </button>
        </div>
      </div>
    </div>

    <script>
      // ===== Authentication Management =====
      let authToken = null;
      let currentUser = null;
      let userRole = null;

      // ===== Admin first-login password change modal =====
      function ensurePasswordModal() {
        if (document.getElementById("pwd-modal")) return;
        const modalHtml = `
        <div id="pwd-modal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.4); align-items:center; justify-content:center; z-index:1000;">
          <div style="background:#1f2937; color:#e5e7eb; width:90%; max-width:420px; border-radius:8px; padding:20px; box-shadow:0 10px 25px rgba(0,0,0,0.5);">
            <h3 style="margin:0 0 10px; font-size:18px;">Admin パスワード変更</h3>
            <p style="margin:0 0 16px; font-size:13px; color:#93c5fd;">初回ログインにはパスワード変更が必要です（localhostからのアクセス）。</p>
            <div style="display:flex; flex-direction:column; gap:10px;">
              <input id="pwd-new" type="password" placeholder="新しいパスワード (6文字以上)" style="padding:10px; border-radius:6px; border:1px solid #374151; background:#111827; color:#e5e7eb;">
              <input id="pwd-confirm" type="password" placeholder="新しいパスワード(確認)" style="padding:10px; border-radius:6px; border:1px solid #374151; background:#111827; color:#e5e7eb;">
              <div id="pwd-error" style="display:none; color:#f87171; font-size:12px;"></div>
            </div>
            <div style="display:flex; justify-content:flex-end; gap:10px; margin-top:16px;">
              <button id="pwd-cancel" style="padding:8px 12px; background:#374151; color:#e5e7eb; border:none; border-radius:6px; cursor:pointer;">キャンセル</button>
              <button id="pwd-submit" style="padding:8px 12px; background:#3b82f6; color:white; border:none; border-radius:6px; cursor:pointer;">変更</button>
            </div>
          </div>
        </div>`;
        document.body.insertAdjacentHTML("beforeend", modalHtml);
        document
          .getElementById("pwd-cancel")
          .addEventListener("click", () => togglePwdModal(false));
      }

      function togglePwdModal(show, clear = true) {
        const m = document.getElementById("pwd-modal");
        if (!m) return;
        m.style.display = show ? "flex" : "none";
        if (clear) {
          const e = document.getElementById("pwd-error");
          e.style.display = "none";
          e.textContent = "";
          const n = document.getElementById("pwd-new");
          if (n) n.value = "";
          const c = document.getElementById("pwd-confirm");
          if (c) c.value = "";
        }
        if (show) {
          const n = document.getElementById("pwd-new");
          if (n) n.focus();
        }
      }

      function getNewPasswordFromModal() {
        ensurePasswordModal();
        togglePwdModal(true);
        return new Promise((resolve) => {
          const btn = document.getElementById("pwd-submit");
          const handler = () => {
            const err = document.getElementById("pwd-error");
            const n = document.getElementById("pwd-new").value.trim();
            const c = document.getElementById("pwd-confirm").value.trim();
            if (n.length < 6) {
              err.textContent = "新しいパスワードは6文字以上にしてください";
              err.style.display = "block";
              return;
            }
            if (n !== c) {
              err.textContent = "パスワードが一致しません";
              err.style.display = "block";
              return;
            }
            btn.removeEventListener("click", handler);
            togglePwdModal(false);
            resolve(n);
          };
          btn.addEventListener("click", handler);
          const onKey = (e) => {
            if (e.key === "Enter") {
              e.preventDefault();
              handler();
            }
          };
          document.getElementById("pwd-new").addEventListener("keydown", onKey);
          document
            .getElementById("pwd-confirm")
            .addEventListener("keydown", onKey);
        });
      }

      // Auto-refresh control
      let autoRefreshInterval = null;
      let isRefreshing = false;
      let refreshErrorCount = 0;
      const MAX_REFRESH_ERRORS = 3;
      const REFRESH_INTERVAL = 30000; // 30 seconds

      // Check session on page load
      document.addEventListener("DOMContentLoaded", function () {
        checkSession();
      });

      function startAutoRefresh() {
        stopAutoRefresh(); // Clear any existing interval
        autoRefreshInterval = setInterval(() => {
          if (
            authToken &&
            !isRefreshing &&
            document.getElementById("main-dashboard").style.display !== "none"
          ) {
            console.log("Auto-refresh triggered");
            refreshDashboard();
          }
        }, REFRESH_INTERVAL);
        console.log(
          `Auto-refresh started (${REFRESH_INTERVAL / 1000} second interval)`
        );
      }

      function stopAutoRefresh() {
        if (autoRefreshInterval) {
          clearInterval(autoRefreshInterval);
          autoRefreshInterval = null;
          console.log("Auto-refresh stopped");
        }
      }

      function checkSession() {
        authToken = localStorage.getItem("authToken");
        currentUser = localStorage.getItem("currentUser");
        userRole = localStorage.getItem("userRole");

        console.log("Checking session:", {
          hasToken: !!authToken,
          user: currentUser,
          role: userRole,
        });

        if (authToken && currentUser && userRole) {
          showMainDashboard();
          // Initial load of dashboard data
          refreshDashboard().then(() => {
            // Start auto-refresh after initial load
            startAutoRefresh();
          });
        } else {
          showLoginScreen();
          stopAutoRefresh();
        }
      }

      function showLoginScreen() {
        document.getElementById("login-screen").style.display = "flex";
        document.getElementById("main-dashboard").style.display = "none";
      }

      function showMainDashboard() {
        document.getElementById("login-screen").style.display = "none";
        document.getElementById("main-dashboard").style.display = "block";
        document.getElementById("username-display").textContent = currentUser;
        document.getElementById("role-display").textContent = userRole;
      }

      async function handleLogin(event) {
        event.preventDefault();

        const username = document.getElementById("login-username").value.trim();
        const password = document.getElementById("login-password").value.trim();
        const errorDiv = document.getElementById("login-error");

        if (!username || !password) {
          showLoginError("Username and password are required");
          return;
        }

        try {
          let result = await makeRequest("/security/login", "POST", {
            username: username,
            password: password,
          });

          if (result.ok && result.status === 200) {
            const response = JSON.parse(result.body);
            console.log("Login successful, response:", response);

            // Save session information
            authToken = response.token;
            currentUser = username;
            userRole = response.role;

            console.log(
              "Saved auth token:",
              authToken ? authToken.substring(0, 20) + "..." : "null"
            );
            console.log("Saved user:", currentUser, "role:", userRole);

            localStorage.setItem("authToken", authToken);
            localStorage.setItem("currentUser", currentUser);
            localStorage.setItem("userRole", userRole);

            // Display the main dashboard
            showMainDashboard();

            // Initial load of dashboard data
            refreshDashboard().then(() => {
              // Start auto-refresh after initial load
              startAutoRefresh();
            });

            // Reset the login form
            document.getElementById("login-username").value = "";
            document.getElementById("login-password").value = "";
            errorDiv.style.display = "none";
          } else if (result.status === 403) {
            // Possibly password change required
            try {
              const data = JSON.parse(result.body || "{}");
              if (data.change_required) {
                if (data.local_only) {
                  showLoginError(
                    "初回パスワード変更はローカルホストからのみ実行可能です。サーバへ直接アクセス（またはSSHポートフォワーディング）して変更してください。"
                  );
                  return;
                }
                const newPwd = await getNewPasswordFromModal();

                const chg = await makeRequest(
                  "/security/change-password",
                  "POST",
                  {
                    username: username,
                    current_password: password,
                    new_password: newPwd,
                  }
                );

                if (chg.ok) {
                  // Retry login with new password
                  result = await makeRequest("/security/login", "POST", {
                    username: username,
                    password: newPwd,
                  });

                  if (result.ok && result.status === 200) {
                    const response = JSON.parse(result.body);
                    authToken = response.token;
                    currentUser = username;
                    userRole = response.role;

                    localStorage.setItem("authToken", authToken);
                    localStorage.setItem("currentUser", currentUser);
                    localStorage.setItem("userRole", userRole);

                    showMainDashboard();
                    // Initial load and start auto refresh
                    refreshDashboard().then(startAutoRefresh);
                    document.getElementById("login-username").value = "";
                    document.getElementById("login-password").value = "";
                    errorDiv.style.display = "none";
                    return;
                  } else {
                    showLoginError(
                      "パスワード変更後のログインに失敗しました: " +
                        (result.body || "")
                    );
                    return;
                  }
                } else {
                  showLoginError(
                    "パスワード変更に失敗しました: " + (chg.body || "")
                  );
                  return;
                }
              }
            } catch (_) {
              // fallthrough to generic error
            }
            showLoginError(result.body || "Login failed");
          } else {
            showLoginError(result.body || "Login failed");
          }
        } catch (error) {
          showLoginError("Network error: " + error.message);
        }
      }

      function showLoginError(message) {
        const errorDiv = document.getElementById("login-error");
        errorDiv.textContent = message;
        errorDiv.style.display = "block";
      }

      function handleLogout() {
        console.log("Logging out user");

        // Stop auto-refresh
        stopAutoRefresh();

        // Clear session information
        authToken = null;
        currentUser = null;
        userRole = null;
        refreshErrorCount = 0;

        localStorage.removeItem("authToken");
        localStorage.removeItem("currentUser");
        localStorage.removeItem("userRole");

        // Show login screen
        showLoginScreen();
      }

      // ===== HTTP Request Helper =====
      async function makeRequest(url, method = "GET", body = null) {
        try {
          console.log(`Making request to ${method} ${url}`, body);

          const options = {
            method,
            headers: {
              "Content-Type": "application/json",
            },
          };

          // Add JWT token to Authorization header for protected endpoints
          const publicEndpoints = [
            "/security/login",
            "/security/change-password",
            "/metrics",
            "/console",
            "/dashboard",
            "/health",
            "/api/cluster-health", // public in server
          ];
          const isPublicEndpoint = publicEndpoints.some((endpoint) =>
            url.startsWith(endpoint)
          );

          if (authToken && !isPublicEndpoint) {
            console.log(
              "Adding authorization header with token:",
              authToken.substring(0, 20) + "..."
            );
            options.headers.Authorization = `Bearer ${authToken}`;
          } else {
            console.log("Public endpoint or no token available");
          }

          if (body) {
            options.body = JSON.stringify(body);
          }

          const response = await fetch(url, options);
          const text = await response.text();

          console.log(
            `Response status: ${response.status}, ok: ${response.ok}`
          );

          // Handle authentication errors (do NOT auto-logout on 401)
          if (response.status === 401) {
            console.warn(
              "401 received; preserving session to avoid auto-logout on reload.",
              url
            );
            // Count and optionally stop auto refresh, but do not clear session
            if (!isPublicEndpoint && isRefreshing) {
              refreshErrorCount++;
              if (refreshErrorCount >= MAX_REFRESH_ERRORS) {
                console.log("Too many refresh errors, stopping auto-refresh");
                stopAutoRefresh();
              }
            }
            return {
              ok: false,
              status: response.status,
              body: "Authentication required.",
            };
          }

          return { ok: response.ok, status: response.status, body: text };
        } catch (error) {
          console.error("Request error:", error);
          return { ok: false, status: "Error", body: error.message };
        }
      }

      // ===== Dashboard Data Functions =====
      async function refreshDashboard() {
        if (isRefreshing) {
          console.log("Refresh already in progress, skipping");
          return;
        }

        if (refreshErrorCount >= MAX_REFRESH_ERRORS) {
          console.log("Too many refresh errors, stopping auto-refresh");
          stopAutoRefresh();
          return;
        }

        isRefreshing = true;
        console.log("Starting dashboard refresh");

        try {
          // Only refresh the main dashboard components sequentially
          if (authToken) {
            await refreshClusterHealth();
            await refreshThroughput();
            await refreshPerformance();
            await refreshStorage();
            await refreshMetricsContent();
          }

          refreshErrorCount = 0; // Reset error count on success
          console.log("Dashboard refresh completed successfully");
        } catch (error) {
          refreshErrorCount++;
          console.error("Dashboard refresh failed:", error);
        } finally {
          isRefreshing = false;
        }
      }

      async function refreshClusterHealth() {
        try {
          const result = await makeRequest("/api/cluster-health");
          if (result.ok) {
            const data = JSON.parse(result.body);
            document.getElementById(
              "cluster-status"
            ).innerHTML = `<span class="status-indicator status-${
              data.status === "healthy" ? "healthy" : "error"
            }"></span>${data.status}`;
            document.getElementById("active-brokers").textContent =
              data.active_brokers || 0;
            document.getElementById("total-topics").textContent =
              data.total_topics || 0;
          }
        } catch (error) {
          console.error("Failed to refresh cluster health:", error);
        }
      }

      async function refreshThroughput() {
        try {
          const result = await makeRequest("/api/dashboard");
          if (result.ok) {
            const data = JSON.parse(result.body);
            const throughput = data.throughput || {};
            document.getElementById("messages-per-sec").textContent =
              throughput.messages_in_per_sec || 0;
            document.getElementById("bytes-in").textContent = formatBytes(
              throughput.bytes_in_per_sec || 0
            );
            document.getElementById("bytes-out").textContent = formatBytes(
              throughput.bytes_out_per_sec || 0
            );
          }
        } catch (error) {
          console.error("Failed to refresh throughput:", error);
        }
      }

      async function refreshPerformance() {
        try {
          const result = await makeRequest("/api/dashboard");
          if (result.ok) {
            const data = JSON.parse(result.body);
            const performance = data.performance || {};
            document.getElementById("avg-latency").textContent = (
              performance.avg_request_latency_ms || 0
            ).toFixed(1);
            document.getElementById("p99-latency").textContent = (
              performance.p99_request_latency_ms || 0
            ).toFixed(1);
          }
        } catch (error) {
          console.error("Failed to refresh performance:", error);
        }
      }

      async function refreshStorage() {
        try {
          const result = await makeRequest("/api/dashboard");
          if (result.ok) {
            const data = JSON.parse(result.body);
            const clusterHealth = data.cluster_health || {};
            const storage = data.storage || {};
            document.getElementById("total-messages").textContent =
              clusterHealth.total_messages || 0;
            document.getElementById("log-size").textContent = formatBytes(
              storage.total_log_size_bytes || 0
            );
          }
        } catch (error) {
          console.error("Failed to refresh storage:", error);
        }
      }

      async function refreshMetricsContent() {
        try {
          const result = await makeRequest("/api/dashboard");
          if (result.ok) {
            const data = JSON.parse(result.body);

            // Create comprehensive metrics display
            const metricsHtml = `
              <div class="metrics-grid">
                <div class="metric-card">
                  <h4>🏥 Cluster Status</h4>
                  <div class="metric-row">
                    <span>Status:</span>
                    <span class="status-${
                      data.cluster_health?.status?.toLowerCase() || "unknown"
                    }">${data.cluster_health?.status || "Unknown"}</span>
                  </div>
                  <div class="metric-row">
                    <span>Active Brokers:</span>
                    <span>${data.cluster_health?.active_brokers || 0}</span>
                  </div>
                  <div class="metric-row">
                    <span>Total Topics:</span>
                    <span>${data.cluster_health?.total_topics || 0}</span>
                  </div>
                </div>

                <div class="metric-card">
                  <h4>📊 Performance</h4>
                  <div class="metric-row">
                    <span>Messages/sec:</span>
                    <span>${data.performance?.messages_per_second || 0}</span>
                  </div>
                  <div class="metric-row">
                    <span>Avg Latency:</span>
                    <span>${data.performance?.avg_latency_ms || 0} ms</span>
                  </div>
                  <div class="metric-row">
                    <span>P99 Latency:</span>
                    <span>${data.performance?.p99_latency_ms || 0} ms</span>
                  </div>
                </div>

                <div class="metric-card">
                  <h4>💾 Storage</h4>
                  <div class="metric-row">
                    <span>Total Messages:</span>
                    <span>${data.storage?.total_messages || 0}</span>
                  </div>
                  <div class="metric-row">
                    <span>Log Size:</span>
                    <span>${formatBytes(
                      data.storage?.total_log_size_bytes || 0
                    )}</span>
                  </div>
                  <div class="metric-row">
                    <span>Storage Used:</span>
                    <span>${formatBytes(
                      data.storage?.storage_used_bytes || 0
                    )}</span>
                  </div>
                </div>

                <div class="metric-card">
                  <h4>🔗 Network</h4>
                  <div class="metric-row">
                    <span>Bytes In:</span>
                    <span>${formatBytes(data.network?.bytes_in || 0)}</span>
                  </div>
                  <div class="metric-row">
                    <span>Bytes Out:</span>
                    <span>${formatBytes(data.network?.bytes_out || 0)}</span>
                  </div>
                  <div class="metric-row">
                    <span>Active Connections:</span>
                    <span>${data.network?.active_connections || 0}</span>
                  </div>
                </div>
              </div>
              <div class="last-updated">
                Last updated: ${new Date().toLocaleTimeString()}
              </div>
            `;

            document.getElementById("metrics-content").innerHTML = metricsHtml;
          } else {
            document.getElementById(
              "metrics-content"
            ).innerHTML = `<div style="color: red;">Failed to load metrics: ${result.body}</div>`;
          }
        } catch (error) {
          console.error("Failed to refresh metrics content:", error);
          document.getElementById(
            "metrics-content"
          ).innerHTML = `<div style="color: red;">Error loading metrics: ${error.message}</div>`;
        }
      }

      // Removed loadDashboardData function as /api/dashboard endpoint may not exist
      // If needed, implement specific dashboard data loading

      // ===== Utility Functions =====
      function formatBytes(bytes) {
        if (bytes === 0) return "0 B";
        const k = 1024;
        const sizes = ["B", "KB", "MB", "GB"];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
      }
    </script>
  </body>
</html>
