// Server Status Polling - Real-time App Server Online indicator

(function () {
	"use strict";

	// Polling intervals in milliseconds
	const POLL_INTERVAL_ONLINE = 30000;  // 30 seconds when online
	const POLL_INTERVAL_OFFLINE = 5000;  // 5 seconds when offline

	// API endpoint for server status
	const API_ENDPOINT = "/api/server/status";

	// DOM element IDs
	const STATUS_ORB_ID = "status-orb";
	const STATUS_TEXT_ID = "status-text";

	// Track previous online state for detecting state changes
	let wasOnline = null;
	let pollIntervalId = null;

	/**
	 * Update the server status display in the sidebar
	 * @param {boolean} isOnline - Whether the server is online
	 */
	function updateServerStatus(isOnline) {
		const statusOrb = document.getElementById(STATUS_ORB_ID);
		const statusText = document.getElementById(STATUS_TEXT_ID);

		if (!statusOrb || !statusText) {
			return;
		}

		if (isOnline) {
			statusOrb.className = "w-2 h-2 rounded-full bg-green-400";
			statusText.className = "text-sm font-medium text-green-400";
			statusText.textContent = "App Online";
		} else {
			statusOrb.className = "w-2 h-2 rounded-full bg-red-400";
			statusText.className = "text-sm font-medium text-red-400";
			statusText.textContent = "App Offline";
		}
	}

	/**
	 * Adjust polling interval based on server status
	 * @param {boolean} isOnline - Whether the server is online
	 */
	function adjustPollingInterval(isOnline) {
		const newInterval = isOnline ? POLL_INTERVAL_ONLINE : POLL_INTERVAL_OFFLINE;
		const currentInterval = wasOnline === null ? 0 : (wasOnline ? POLL_INTERVAL_ONLINE : POLL_INTERVAL_OFFLINE);
		
		// Only restart interval if it changed
		if (currentInterval !== newInterval) {
			if (pollIntervalId) {
				clearInterval(pollIntervalId);
			}
			pollIntervalId = setInterval(checkServerStatus, newInterval);
			console.log(`[ServerStatus] Polling interval changed to ${newInterval}ms (${isOnline ? 'online' : 'offline'})`);
		}
	}

	/**
	 * Handle server status change, triggering page refresh on reconnect
	 * @param {boolean} isOnline - Current online status
	 */
	function handleStatusChange(isOnline) {
		// Check if this is a transition from offline to online
		if (wasOnline === false && isOnline === true) {
			console.log("[ServerStatus] Server back online, refreshing page...");
			// Refresh the page to sync UI with server state
			window.location.reload();
			return; // Page will reload, no need to continue
		}

		// Log state changes for debugging
		if (wasOnline !== null && wasOnline !== isOnline) {
			console.log(`[ServerStatus] Status changed: ${wasOnline ? 'online' : 'offline'} → ${isOnline ? 'online' : 'offline'}`);
		}

		// Update previous state
		wasOnline = isOnline;

		// Adjust polling interval based on status
		adjustPollingInterval(isOnline);
	}

	/**
	 * Fetch server status from API
	 * @returns {Promise<boolean>} - Resolves to true if server is online, false otherwise
	 */
	async function fetchServerStatus() {
		try {
			const response = await fetch(API_ENDPOINT);
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			const data = await response.json();
			return data.status === "online";
		} catch (error) {
			console.error("[ServerStatus] Failed to fetch server status:", error);
			return false;
		}
	}

	/**
	 * Check server status and update UI
	 */
	async function checkServerStatus() {
		const isOnline = await fetchServerStatus();
		updateServerStatus(isOnline);
		handleStatusChange(isOnline);
	}

	/**
	 * Initialize server status polling
	 */
	function initServerStatus() {
		// Initial check
		checkServerStatus();

		// Set up polling with offline interval initially (will adjust after first check)
		pollIntervalId = setInterval(checkServerStatus, POLL_INTERVAL_OFFLINE);
	}

	// Initialize when DOM is ready
	if (document.readyState === "loading") {
		document.addEventListener("DOMContentLoaded", initServerStatus);
	} else {
		initServerStatus();
	}
})();
