{{define "tasks"}}
<!DOCTYPE html>
<html lang="en">
<head>
    {{template "head-common" .}}
    <title>{{.Title}}</title>
</head>
<body class="bg-gray-900 text-gray-100">
    {{template "accessibility-common" .}}
    {{template "main-layout-start" .}}
    {{template "tasks-content" .}}
    {{template "main-layout-end" .}}
    {{template "body-common-scripts" .}}
    <script>
        // Initialize tasks page
        document.addEventListener("DOMContentLoaded", function () {
            const tasksNavLink = document.getElementById("tasks-nav-link");
            if (tasksNavLink) {
                tasksNavLink.classList.add("active");
                tasksNavLink.setAttribute("aria-current", "page");
            }

            loadTasks();

            setInterval(function () {
                const activeCount = document.querySelectorAll(
                    "#active-tasks-list .task-card",
                ).length;
                if (activeCount > 0) {
                    loadTasks();
                }
            }, 5000);

            const urlParams = new URLSearchParams(window.location.search);
            const jobId = urlParams.get("job");
            if (jobId) {
                setTimeout(() => {
                    window.showJobOutput(jobId);
                }, 500);
            }
        });

        async function loadTasks() {
            try {
                const response = await fetch("/api/jobs");
                if (!response.ok) {
                    throw new Error("Failed to load tasks");
                }

                const data = await response.json();
                renderActiveTasks(data.active || []);
                renderRecentTasks(data.recent || []);
            } catch (error) {
                console.error("Error loading tasks:", error);
                if (window.showToast) {
                    window.showToast("Failed to load tasks", "error");
                }
            }
        }

        window.refreshActiveTasks = function () {
            loadTasks();
        };

        function renderActiveTasks(tasks) {
            const container = document.getElementById("active-tasks-list");
            const noTasksMsg = document.getElementById("no-active-tasks");

            if (!tasks || tasks.length === 0) {
                if (noTasksMsg) noTasksMsg.classList.remove("hidden");
                container.querySelectorAll(".task-card").forEach((el) => el.remove());
                return;
            }

            if (noTasksMsg) noTasksMsg.classList.add("hidden");
            container.querySelectorAll(".task-card").forEach((el) => el.remove());

            tasks.forEach((task) => {
                const card = createActiveTaskCard(task);
                container.appendChild(card);
            });
        }

        function renderRecentTasks(tasks) {
            const container = document.getElementById("recent-tasks-list");
            const noTasksMsg = document.getElementById("no-recent-tasks");

            if (!tasks || tasks.length === 0) {
                if (noTasksMsg) noTasksMsg.classList.remove("hidden");
                container.querySelectorAll(".task-card").forEach((el) => el.remove());
                return;
            }

            if (noTasksMsg) noTasksMsg.classList.add("hidden");
            container.querySelectorAll(".task-card").forEach((el) => el.remove());

            tasks.forEach((task) => {
                const card = createRecentTaskCard(task);
                container.appendChild(card);
            });
        }

        function createActiveTaskCard(task) {
            const card = document.createElement("div");
            card.className = "task-card bg-gray-800 rounded-lg p-4 border border-gray-700";
            card.dataset.jobId = task.id;

            const statusColor = task.status === "running" ? "text-blue-400" : "text-yellow-400";
            const statusIcon = task.status === "running" ? "bx-loader-alt bx-spin" : "bx-time";
            const progress = task.progress || 0;

            card.innerHTML = `
                <div class="flex items-center justify-between mb-3">
                    <div class="flex items-center gap-3">
                        <i class="bx ${statusIcon} text-2xl ${statusColor}" aria-hidden="true"></i>
                        <div>
                            <h4 class="font-semibold text-white">${escapeHtml(task.appName || "Unknown App")}</h4>
                            <p class="text-sm text-gray-400 capitalize">${escapeHtml(task.type || "Task")}</p>
                        </div>
                    </div>
                    <div class="flex items-center gap-2">
                        <button onclick="window.showJobOutput('${task.id}')" class="text-purple-400 hover:text-purple-300 text-sm flex items-center gap-1" aria-label="View task details">
                            <i class="bx bx-detail"></i>
                            View Details
                        </button>
                        <button onclick="window.cancelJob('${task.id}')" class="text-red-400 hover:text-red-300 text-sm flex items-center gap-1" aria-label="Cancel task">
                            <i class="bx bx-x"></i>
                            Cancel
                        </button>
                    </div>
                </div>
                <div class="mb-2">
                    <div class="flex items-center justify-between text-sm mb-1">
                        <span class="text-gray-400">${escapeHtml(task.message || "Processing...")}</span>
                        <span class="text-gray-400">${progress}%</span>
                    </div>
                    <div class="w-full bg-gray-700 rounded-full h-2" role="progressbar" aria-valuenow="${progress}" aria-valuemin="0" aria-valuemax="100">
                        <div class="bg-blue-500 h-2 rounded-full transition-all duration-300 job-progress-bar" style="width: ${progress}%"></div>
                    </div>
                </div>
                <div class="text-xs text-gray-500">
                    Started: ${formatTime(task.startedAt)}
                </div>
            `;

            return card;
        }

        function createRecentTaskCard(task) {
            const card = document.createElement("div");
            card.className = "task-card bg-gray-800 rounded-lg p-4 border border-gray-700";
            card.dataset.jobId = task.id;

            const isSuccess = task.status === "complete";
            const statusColor = isSuccess ? "text-green-400" : "text-red-400";
            const statusIcon = isSuccess ? "bx-check-circle" : "bx-x-circle";
            const statusText = isSuccess ? "Completed" : "Failed";

            card.innerHTML = `
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <i class="bx ${statusIcon} text-2xl ${statusColor}" aria-hidden="true"></i>
                        <div>
                            <h4 class="font-semibold text-white">${escapeHtml(task.appName || "Unknown App")}</h4>
                            <div class="flex items-center gap-2 text-sm">
                                <span class="text-gray-400 capitalize">${escapeHtml(task.type || "Task")}</span>
                                <span class="text-gray-600">•</span>
                                <span class="${statusColor}">${statusText}</span>
                            </div>
                        </div>
                    </div>
                    <div class="flex items-center gap-2">
                        <button onclick="window.showJobOutput('${task.id}')" class="text-purple-400 hover:text-purple-300 text-sm flex items-center gap-1" aria-label="View task details">
                            <i class="bx bx-detail"></i>
                            View Details
                        </button>
                    </div>
                </div>
                ${task.error ? `
                    <div class="mt-3 p-2 bg-red-900 bg-opacity-20 rounded text-sm">
                        <span class="text-red-400">Error: ${escapeHtml(task.error)}</span>
                    </div>
                ` : ""}
                <div class="text-xs text-gray-500 mt-2">
                    Completed: ${formatTime(task.completedAt)}
                </div>
            `;

            return card;
        }

        function formatTime(timestamp) {
            if (!timestamp) return "Unknown";
            try {
                const date = new Date(timestamp);
                return date.toLocaleString();
            } catch (e) {
                return timestamp;
            }
        }

        function escapeHtml(text) {
            if (!text) return "";
            const div = document.createElement("div");
            div.textContent = text;
            return div.innerHTML;
        }
    </script>
</body>
</html>
{{end}}

{{define "tasks-content"}}
<div class="space-y-6">
	<div class="mb-6">
		<h2 class="text-3xl font-bold text-white">Tasks</h2>
		<p class="text-gray-400 mt-1">
			View and manage installation, update, and uninstallation tasks
		</p>
	</div>

	<!-- Active Tasks Section -->
	<section id="active-tasks" aria-labelledby="active-tasks-heading">
		<div class="flex items-center justify-between mb-4">
			<h3
				id="active-tasks-heading"
				class="text-xl font-semibold text-purple-400 flex items-center gap-2"
			>
				<i class="bx bx-loader-alt bx-spin" aria-hidden="true"></i>
				Active Tasks
			</h3>
			<button
				onclick="refreshActiveTasks()"
				class="bg-gray-700 hover:bg-gray-600 text-white px-3 py-1.5 rounded transition flex items-center gap-2 text-sm"
			>
				<i class="bx bx-refresh"></i>
				Refresh
			</button>
		</div>

		<div id="active-tasks-list" class="space-y-3">
			<!-- Active tasks will be loaded dynamically -->
			<div class="text-center py-8 text-gray-400" id="no-active-tasks">
				<i class="bx bx-check-circle text-4xl mb-2"></i>
				<p>No active tasks</p>
				<p class="text-sm">
					Start an installation from the
					<a href="/apps" class="text-purple-400 hover:underline"
						>Apps page</a
					>
				</p>
			</div>
		</div>
	</section>

	<!-- Recent Tasks Section -->
	<section
		id="recent-tasks"
		aria-labelledby="recent-tasks-heading"
		class="mt-8"
	>
		<div class="flex items-center justify-between mb-4">
			<h3
				id="recent-tasks-heading"
				class="text-xl font-semibold text-purple-400 flex items-center gap-2"
			>
				<i class="bx bx-history" aria-hidden="true"></i>
				Recently Completed
			</h3>
		</div>

		<div id="recent-tasks-list" class="space-y-3">
			<!-- Recent tasks will be loaded dynamically -->
			<div class="text-center py-8 text-gray-400" id="no-recent-tasks">
				<i class="bx bx-folder-open text-4xl mb-2"></i>
				<p>No recent tasks</p>
				<p class="text-sm">Completed tasks will appear here</p>
			</div>
		</div>
	</section>
</div>
{{end}}
