/**
 * Settings Page JavaScript
 * Handles keyring status, password management, shortcut toggle, and data reset
 */

(function () {
	"use strict";

	// State
	let keyringStatus = null;
	let shortcutPreference = false;

	/**
	 * Initialize the settings page
	 */
	function init() {
		// Load initial data
		loadKeyringStatus();
		loadShortcutPreference();
		loadConfigFilePath();

		// Set up event listeners
		setupEventListeners();

		console.log("[Settings] Initialized");
	}

	/**
	 * Set up event listeners
	 */
	function setupEventListeners() {
		// Desktop shortcut toggle
		const shortcutToggle = document.getElementById("desktop-shortcut-toggle");
		if (shortcutToggle) {
			shortcutToggle.addEventListener("change", handleShortcutToggle);
		}

		// Password buttons
		const setPasswordBtn = document.getElementById("set-password-btn");
		if (setPasswordBtn) {
			setPasswordBtn.addEventListener("click", handleSetPassword);
		}

		const clearPasswordBtn = document.getElementById("clear-password-btn");
		if (clearPasswordBtn) {
			clearPasswordBtn.addEventListener("click", handleClearPassword);
		}

		// Reset data button and modal
		const resetDataBtn = document.getElementById("reset-data-btn");
		if (resetDataBtn) {
			resetDataBtn.addEventListener("click", showResetModal);
		}

		const resetModalClose = document.getElementById("reset-modal-close");
		if (resetModalClose) {
			resetModalClose.addEventListener("click", hideResetModal);
		}

		const resetModalCancel = document.getElementById("reset-modal-cancel");
		if (resetModalCancel) {
			resetModalCancel.addEventListener("click", hideResetModal);
		}

		const resetModalConfirm = document.getElementById("reset-modal-confirm");
		if (resetModalConfirm) {
			resetModalConfirm.addEventListener("click", handleResetData);
		}

		// Reset modal overlay click
		const resetModal = document.getElementById("reset-confirm-modal");
		if (resetModal) {
			resetModal.addEventListener("click", (e) => {
				if (e.target === resetModal) {
					hideResetModal();
				}
			});
		}

		// Escape key to close modal
		document.addEventListener("keydown", (e) => {
			if (e.key === "Escape") {
				hideResetModal();
			}
		});
	}

	/**
	 * Load keyring status from server
	 */
	async function loadKeyringStatus() {
		const container = document.getElementById("keyring-status-container");
		const actionsDiv = document.getElementById("password-actions");
		const hintDiv = document.getElementById("keyring-setup-hint");

		if (!container) return;

		try {
			const response = await fetch("/api/keyring/status");
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}

			keyringStatus = await response.json();
			console.log("[Settings] Keyring status:", keyringStatus);

			// Render status
			renderKeyringStatus(keyringStatus);

			// Show actions
			if (actionsDiv) {
				actionsDiv.classList.remove("hidden");
			}

			// Update password button text
			updatePasswordButtonText();

			// Show/hide setup hint
			if (hintDiv) {
				if (keyringStatus.needsSetup || !keyringStatus.daemonRunning) {
					hintDiv.classList.remove("hidden");
					const cmdElement = document.getElementById("keyring-install-cmd");
					if (cmdElement && keyringStatus.installHint) {
						cmdElement.textContent = keyringStatus.installHint;
					}
				} else {
					hintDiv.classList.add("hidden");
				}
			}
		} catch (error) {
			console.error("[Settings] Failed to load keyring status:", error);
			container.innerHTML = `
				<div class="bg-red-900/30 border border-red-600/50 rounded-lg p-4">
					<div class="flex items-center gap-2">
						<i class="bx bx-error text-red-400"></i>
						<span class="text-red-400">Failed to load keyring status</span>
					</div>
				</div>
			`;
		}
	}

	/**
	 * Render keyring status display
	 */
	function renderKeyringStatus(status) {
		const container = document.getElementById("keyring-status-container");
		if (!container) return;

		const items = [
			{
				label: "Keyring Backend",
				value: formatBackendName(status.activeBackend),
				icon: "bx-server",
				status: status.activeBackend !== "none" ? "success" : "error",
			},
			{
				label: "Daemon Running",
				value: status.daemonRunning ? "Yes" : "No",
				icon: "bx-play-circle",
				status: status.daemonRunning ? "success" : "warning",
			},
			{
				label: "Password Stored",
				value: status.hasPassword ? "Yes" : "No",
				icon: "bx-key",
				status: status.hasPassword ? "success" : "neutral",
			},
		];

		container.innerHTML = `
			<div class="grid gap-3">
				${items
					.map((item) => {
						const statusColor =
							item.status === "success"
								? "text-green-400"
								: item.status === "warning"
									? "text-yellow-400"
									: item.status === "error"
										? "text-red-400"
										: "text-gray-400";
						return `
							<div class="flex items-center justify-between p-3 bg-gray-700 rounded-lg">
								<div class="flex items-center gap-3">
									<i class="bx ${item.icon} text-gray-400"></i>
									<span class="text-gray-300">${item.label}</span>
								</div>
								<span class="${statusColor} font-medium">${item.value}</span>
							</div>
						`;
					})
					.join("")}
			</div>
		`;

		// Update clear button visibility
		const clearBtn = document.getElementById("clear-password-btn");
		if (clearBtn) {
			if (status.hasPassword) {
				clearBtn.classList.remove("hidden");
			} else {
				clearBtn.classList.add("hidden");
			}
		}
	}

	/**
	 * Format backend name for display
	 */
	function formatBackendName(backend) {
		const names = {
			"secret-service": "GNOME Keyring",
			kwallet: "KDE Wallet",
			pass: "pass (password-store)",
			file: "Encrypted File",
			none: "Not Available",
		};
		return names[backend] || backend;
	}

	/**
	 * Update password button text based on current state
	 */
	function updatePasswordButtonText() {
		const btnText = document.getElementById("set-password-btn-text");
		if (btnText && keyringStatus) {
			btnText.textContent = keyringStatus.hasPassword
				? "Change Password"
				: "Set Password";
		}
	}

	/**
	 * Handle set/change password button click
	 */
	function handleSetPassword() {
		// Use the password modal system
		if (window.PasswordModal) {
			window.PasswordModal.show(() => {
				// Refresh status after successful authentication
				loadKeyringStatus();
				if (window.showToast) {
					window.showToast("Password saved successfully", "success");
				}
			});
		}
	}

	/**
	 * Handle clear password button click
	 */
	async function handleClearPassword() {
		if (!confirm("Are you sure you want to remove the stored password?")) {
			return;
		}

		try {
			const response = await fetch("/api/keyring/auth", {
				method: "DELETE",
			});

			const data = await response.json();

			if (!response.ok || !data.success) {
				throw new Error(data.error || "Failed to clear password");
			}

			console.log("[Settings] Password cleared successfully");

			// Refresh status
			loadKeyringStatus();

			if (window.showToast) {
				window.showToast("Password removed successfully", "success");
			}
		} catch (error) {
			console.error("[Settings] Failed to clear password:", error);
			if (window.showToast) {
				window.showToast(error.message, "error");
			}
		}
	}

	/**
	 * Load shortcut preference from server
	 */
	async function loadShortcutPreference() {
		const toggle = document.getElementById("desktop-shortcut-toggle");
		const statusDiv = document.getElementById("shortcut-status");

		if (!toggle) return;

		try {
			const response = await fetch("/api/settings");
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}

			const data = await response.json();
			shortcutPreference = data.desktop_shortcut_enabled || false;

			toggle.checked = shortcutPreference;

			// Update status
			if (statusDiv) {
				statusDiv.innerHTML = shortcutPreference
					? '<i class="bx bx-check text-green-400 mr-1"></i>Desktop shortcut creation is enabled'
					: '<i class="bx bx-x text-gray-500 mr-1"></i>Desktop shortcut creation is disabled';
			}
		} catch (error) {
			console.error("[Settings] Failed to load shortcut preference:", error);
		}
	}

	/**
	 * Handle desktop shortcut toggle
	 */
	async function handleShortcutToggle(event) {
		const toggle = event.target;
		const enabled = toggle.checked;
		const statusDiv = document.getElementById("shortcut-status");

		try {
			const response = await fetch("/api/settings/shortcut", {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
				},
				body: JSON.stringify({ enabled: enabled }),
			});

			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}

			const data = await response.json();
			shortcutPreference = enabled;

			// Update status
			if (statusDiv) {
				statusDiv.innerHTML = enabled
					? '<i class="bx bx-check text-green-400 mr-1"></i>Desktop shortcut creation is enabled'
					: '<i class="bx bx-x text-gray-500 mr-1"></i>Desktop shortcut creation is disabled';
			}

			if (window.showToast) {
				window.showToast(
					enabled
						? "Desktop shortcut creation enabled"
						: "Desktop shortcut creation disabled",
					"success"
				);
			}
		} catch (error) {
			console.error("[Settings] Failed to update shortcut preference:", error);
			// Revert toggle
			toggle.checked = shortcutPreference;
			if (window.showToast) {
				window.showToast("Failed to update preference", "error");
			}
		}
	}

	/**
	 * Load config file path
	 */
	async function loadConfigFilePath() {
		const pathElement = document.getElementById("config-file-path");
		if (!pathElement) return;

		try {
			const response = await fetch("/api/settings");
			if (!response.ok) return;

			const data = await response.json();
			if (data.config_file_path) {
				pathElement.textContent = data.config_file_path;
			}
		} catch (error) {
			console.error("[Settings] Failed to load config file path:", error);
		}
	}

	/**
	 * Show reset confirmation modal
	 */
	function showResetModal() {
		const modal = document.getElementById("reset-confirm-modal");
		if (!modal) return;

		modal.classList.remove("hidden");
		modal.classList.add("flex");
	}

	/**
	 * Hide reset confirmation modal
	 */
	function hideResetModal() {
		const modal = document.getElementById("reset-confirm-modal");
		if (!modal) return;

		modal.classList.add("hidden");
		modal.classList.remove("flex");
	}

	/**
	 * Handle reset data confirmation
	 */
	async function handleResetData() {
		const confirmBtn = document.getElementById("reset-modal-confirm");
		const confirmText = document.getElementById("reset-modal-confirm-text");

		if (confirmBtn) {
			confirmBtn.disabled = true;
		}
		if (confirmText) {
			confirmText.innerHTML =
				'<i class="bx bx-loader-alt bx-spin"></i> Resetting...';
		}

		try {
			const response = await fetch("/api/settings/reset", {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
				},
			});

			if (!response.ok) {
				const data = await response.json();
				throw new Error(data.message || "Failed to reset data");
			}

			console.log("[Settings] Data reset successfully");

			// Close modal
			hideResetModal();

			// Show success toast
			if (window.showToast) {
				window.showToast(
					"MPV Manager data has been reset. The page will reload.",
					"success"
				);
			}

			// Reload page after a short delay
			setTimeout(() => {
				window.location.reload();
			}, 1500);
		} catch (error) {
			console.error("[Settings] Failed to reset data:", error);
			if (window.showToast) {
				window.showToast(error.message, "error");
			}

			// Reset button state
			if (confirmBtn) {
				confirmBtn.disabled = false;
			}
			if (confirmText) {
				confirmText.innerHTML = "Reset Data";
			}
		}
	}

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