<!DOCTYPE html>
<html>
<head>
  <title>Tiny Shiny Server</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="{{base_url}}/templates/styles/main.css">
</head>
<body>
  <div class="container">
    <div class="connection-status" id="connectionStatus">
      <span class="status-indicator" id="statusIndicator"></span>
      <span class="status-text" id="statusText">Connecting...</span>
    </div>

    <div class="header">
      <h1>Tiny Shiny Server</h1>
    </div>

    <div class="apps-grid">
      {{app_cards}}
    </div>

    <div class="session-info">
      <h4>Server Information</h4>
      <pre>{{session_info}}</pre>
    </div>
  </div>

  <script>
    let refreshInterval;
    let isConnected = false; // Start as disconnected until we verify connection

    function setConnectionStatus(connected) {
      const indicator = document.getElementById("statusIndicator");
      const statusText = document.getElementById("statusText");

      if (connected) {
        indicator.className = "status-indicator connected";
        statusText.className = "status-text connected";
        statusText.textContent = "Connected";
        isConnected = true;
      } else {
        indicator.className = "status-indicator disconnected";
        statusText.className = "status-text disconnected";
        statusText.textContent = "Connection Lost";
        isConnected = false;
      }
    }

    function updateAppStatus() {
      // Create abort controller for timeout
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 3000); // 3 second timeout
      
      fetch("/api/apps", {
        method: 'GET',
        cache: 'no-cache',
        headers: {
          'Cache-Control': 'no-cache'
        },
        signal: controller.signal
      })
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
          }
          return response.json();
        })
        .then(data => {
          // Clear timeout since request succeeded
          clearTimeout(timeoutId);
          
          // Update connection status to connected if we were disconnected
          if (!isConnected) {
            setConnectionStatus(true);
          }

          Object.values(data).forEach(app => {
            const statusElement = document.getElementById("status-" + app.name);
            const connectionsElement = document.getElementById("connections-" + app.name);
            const cardElement = document.querySelector(`[data-app="${app.name}"]`);
            const linkElement = cardElement ? cardElement.closest('a') : null;

            if (statusElement) {
              statusElement.textContent = app.status;
              statusElement.className = "status-badge status-" + app.status;
            }

            if (connectionsElement) {
              const connectionText = app.connections === 1 ? "1 connection" : app.connections + " connections";
              connectionsElement.textContent = connectionText;
            }
            
            // Enable/disable link based on app status
            if (linkElement && cardElement) {
              if (app.status === "running" || app.status === "dormant") {
                // App is running or dormant (can be started on-demand) - make it clickable
                linkElement.href = "/proxy/" + app.name + "/";
                linkElement.style.pointerEvents = "auto";
                linkElement.style.cursor = "pointer";
                cardElement.classList.remove("app-disabled");
                
                if (app.status === "running") {
                  linkElement.title = "Click to open " + app.name;
                } else {
                  linkElement.title = "Click to start and open " + app.name + " (on-demand app)";
                }
              } else {
                // App is stopped or crashed - disable clicking
                linkElement.removeAttribute("href");
                linkElement.style.pointerEvents = "none";
                linkElement.style.cursor = "not-allowed";
                cardElement.classList.add("app-disabled");
                
                // Set appropriate tooltip based on status
                if (app.status === "stopped") {
                  linkElement.title = "App is stopped - use management interface to start it";
                } else if (app.status === "crashed") {
                  linkElement.title = "App has crashed - use management interface to restart it";
                } else {
                  linkElement.title = "App is not available (" + app.status + ")";
                }
              }
            }
          });
        })
        .catch(error => {
          // Clear timeout
          clearTimeout(timeoutId);
          
          console.error("Error fetching app status:", error);

          // Update connection status to disconnected
          setConnectionStatus(false);

          // Update all status badges to show error state and disable all app tiles
          document.querySelectorAll(".app-card").forEach(card => {
            const linkElement = card.closest('a');
            const statusBadge = card.querySelector('.status-badge');
            
            // Update status badge
            if (statusBadge) {
              statusBadge.textContent = "server down";
              statusBadge.className = "status-badge status-stopped";
            }
            
            // Disable the app tile
            if (linkElement) {
              linkElement.removeAttribute("href");
              linkElement.style.pointerEvents = "none";
              linkElement.style.cursor = "not-allowed";
              linkElement.title = "Server is down - apps are not accessible";
            }
            
            // Add disabled styling
            card.classList.add("app-disabled");
          });
        });
    }

    // Initial load - don't assume connected, let updateAppStatus determine status
    updateAppStatus();

    // Auto-refresh every 5 seconds
    refreshInterval = setInterval(updateAppStatus, 5000);

    // Clean up interval when page is about to unload
    window.addEventListener("beforeunload", function() {
      if (refreshInterval) {
        clearInterval(refreshInterval);
      }
    });
  </script>
</body>
</html>