/**
 * Password Modal for Keyring Authentication
 * Handles sudo password prompts for package manager installations
 */

(function () {
	"use strict";

	// Password modal state
	let keyringStatus = null;
	let pendingCallback = null;
	let isAuthenticating = false;
	let previousActiveElement = null;

	// Methods that require sudo (package managers)
	const SUDO_REQUIRED_METHODS = [
		"mpv-package",
		"celluloid-package",
		"mpv-snap",
		"celluloid-snap",
		"mpv-flatpak",
		"celluloid-flatpak",
		"mpv-brew", // macOS Homebrew may require sudo for some operations
	];

	/**
	 * Initialize the password modal system
	 */
	function init() {
		console.log("[PasswordModal] init() called, document.readyState:", document.readyState);

		// Check keyring status on page load
		checkKeyringStatus();

		// Set up event listeners
		setupEventListeners();

		console.log("[PasswordModal] Initialized successfully");
	}

	/**
	 * Set up event listeners for modal interactions
	 */
	function setupEventListeners() {
		// Close button
		const closeBtn = document.getElementById("password-modal-close");
		if (closeBtn) {
			closeBtn.addEventListener("click", hidePasswordModal);
		}

		// Cancel button
		const cancelBtn = document.getElementById("password-modal-cancel");
		if (cancelBtn) {
			cancelBtn.addEventListener("click", hidePasswordModal);
		}

		// Authenticate button
		const authBtn = document.getElementById("password-modal-authenticate");
		if (authBtn) {
			authBtn.addEventListener("click", submitPassword);
		}

		// Toggle password visibility
		const toggleBtn = document.getElementById("toggle-password-visibility");
		if (toggleBtn) {
			toggleBtn.addEventListener("click", togglePasswordVisibility);
		}

		// Submit on Enter key
		const passwordInput = document.getElementById("password-input");
		if (passwordInput) {
			passwordInput.addEventListener("keydown", (e) => {
				if (e.key === "Enter") {
					e.preventDefault();
					submitPassword();
				}
			});
		}

		// Click outside to close
		const modal = document.getElementById("password-modal");
		if (modal) {
			modal.addEventListener("click", (e) => {
				if (e.target === modal) {
					hidePasswordModal();
				}
			});
		}

		// Escape key to close
		document.addEventListener("keydown", (e) => {
			if (e.key === "Escape") {
				const modal = document.getElementById("password-modal");
				if (modal && !modal.classList.contains("hidden")) {
					hidePasswordModal();
				}
			}
		});
	}

	/**
	 * Check keyring status from server
	 */
	async function checkKeyringStatus() {
		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("[PasswordModal] Keyring status:", keyringStatus);

			// Show setup info if needed
			if (keyringStatus.needsSetup) {
				showKeyringSetupInfo(keyringStatus.installHint);
			}
		} catch (error) {
			console.error("[PasswordModal] Failed to check keyring status:", error);
			// Default to assuming keyring is available
			keyringStatus = {
				hasPassword: false,
				available: true,
			};
		}
	}

	/**
	 * Show keyring setup information
	 */
	function showKeyringSetupInfo(hint) {
		const infoDiv = document.getElementById("keyring-setup-info");
		const hintText = document.getElementById("keyring-install-hint");

		if (infoDiv && hintText) {
			hintText.textContent = hint || "Install a keyring service to store passwords securely.";
			infoDiv.classList.remove("hidden");
		}
	}

	/**
	 * Hide keyring setup information
	 */
	function hideKeyringSetupInfo() {
		const infoDiv = document.getElementById("keyring-setup-info");
		if (infoDiv) {
			infoDiv.classList.add("hidden");
		}
	}

	/**
	 * Check if a method requires sudo
	 */
	function methodRequiresSudo(methodId) {
		return SUDO_REQUIRED_METHODS.includes(methodId);
	}

	/**
	 * Check if we have a stored password
	 */
	function hasStoredPassword() {
		return keyringStatus && keyringStatus.hasPassword;
	}

	/**
	 * Show the password modal
	 * @param {Function} callback - Function to call after successful authentication
	 */
	function showPasswordModal(callback) {
		// Store the callback for after authentication
		pendingCallback = callback;

		// Store the previously focused element
		previousActiveElement = document.activeElement;

		// Get modal elements
		const modal = document.getElementById("password-modal");
		const passwordInput = document.getElementById("password-input");
		const errorDiv = document.getElementById("password-error");

		if (!modal) {
			console.error("[PasswordModal] Modal element not found");
			return;
		}

		// Clear previous state
		if (passwordInput) {
			passwordInput.value = "";
		}
		if (errorDiv) {
			errorDiv.classList.add("hidden");
		}

		// Show/hide keyring setup info
		if (keyringStatus && keyringStatus.needsSetup) {
			showKeyringSetupInfo(keyringStatus.installHint);
		} else {
			hideKeyringSetupInfo();
		}

		// Reset button state
		setAuthButtonLoading(false);

		// Show modal
		modal.classList.remove("hidden");
		modal.classList.add("flex");
		modal.classList.remove("closing");

		// Focus password input
		setTimeout(() => {
			if (passwordInput) {
				passwordInput.focus();
			}
		}, 100);

		console.log("[PasswordModal] Modal shown");
	}

	/**
	 * Hide the password modal
	 */
	function hidePasswordModal() {
		const modal = document.getElementById("password-modal");

		if (!modal) return;

		// Add closing animation
		modal.classList.add("closing");

		setTimeout(() => {
			modal.classList.add("hidden");
			modal.classList.remove("flex");
			modal.classList.remove("closing");

			// Clear pending callback
			pendingCallback = null;

			// Restore focus
			if (
				previousActiveElement &&
				typeof previousActiveElement.focus === "function"
			) {
				previousActiveElement.focus();
			}
		}, 200);

		console.log("[PasswordModal] Modal hidden");
	}

	/**
	 * Toggle password visibility
	 */
	function togglePasswordVisibility() {
		const passwordInput = document.getElementById("password-input");
		const toggleBtn = document.getElementById("toggle-password-visibility");

		if (!passwordInput || !toggleBtn) return;

		const icon = toggleBtn.querySelector("i");
		if (!icon) return;

		if (passwordInput.type === "password") {
			passwordInput.type = "text";
			icon.classList.remove("bx-hide");
			icon.classList.add("bx-show");
		} else {
			passwordInput.type = "password";
			icon.classList.remove("bx-show");
			icon.classList.add("bx-hide");
		}
	}

	/**
	 * Set the authenticate button loading state
	 */
	function setAuthButtonLoading(loading) {
		const authBtn = document.getElementById("password-modal-authenticate");
		const authText = document.getElementById("password-modal-auth-text");

		if (!authBtn) return;

		isAuthenticating = loading;

		if (loading) {
			authBtn.disabled = true;
			authBtn.innerHTML =
				'<i class="bx bx-loader-alt bx-spin"></i> Authenticating...';
		} else {
			authBtn.disabled = false;
			authBtn.innerHTML = '<i class="bx bx-check"></i> Authenticate';
		}
	}

	/**
	 * Show error message in modal
	 */
	function showError(message) {
		const errorDiv = document.getElementById("password-error");
		const errorMessage = document.getElementById("password-error-message");

		if (errorDiv && errorMessage) {
			errorMessage.textContent = message;
			errorDiv.classList.remove("hidden");
		}
	}

	/**
	 * Hide error message
	 */
	function hideError() {
		const errorDiv = document.getElementById("password-error");
		if (errorDiv) {
			errorDiv.classList.add("hidden");
		}
	}

	/**
	 * Submit password for authentication
	 */
	async function submitPassword() {
		if (isAuthenticating) return;

		const passwordInput = document.getElementById("password-input");
		const rememberCheckbox = document.getElementById("remember-password");

		if (!passwordInput) {
			console.error("[PasswordModal] Password input not found");
			return;
		}

		const password = passwordInput.value;

		if (!password) {
			showError("Please enter your password");
			return;
		}

		hideError();
		setAuthButtonLoading(true);

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

			const data = await response.json();

			if (!response.ok || !data.success) {
				throw new Error(data.error || "Authentication failed");
			}

			console.log("[PasswordModal] Authentication successful");

			// Update keyring status
			if (keyringStatus) {
				keyringStatus.hasPassword = true;
			}

			// Close modal
			hidePasswordModal();

			// Execute pending callback
			if (pendingCallback && typeof pendingCallback === "function") {
				console.log("[PasswordModal] Executing pending callback");
				pendingCallback();
			}
		} catch (error) {
			console.error("[PasswordModal] Authentication failed:", error);
			showError(error.message || "Authentication failed. Please try again.");

			// Clear password input
			passwordInput.value = "";
			passwordInput.focus();
		} finally {
			setAuthButtonLoading(false);
		}
	}

	/**
	 * Ensure password is available before proceeding with an action
	 * Shows modal if needed, calls callback immediately if password is already stored
	 * @param {string} methodId - The installation method ID
	 * @param {Function} callback - Function to call after ensuring password
	 * @returns {Promise<boolean>} - True if proceeding, false if modal shown
	 */
	async function ensurePassword(methodId, callback) {
		// Check if this method requires sudo
		if (!methodRequiresSudo(methodId)) {
			console.log(
				"[PasswordModal] Method does not require sudo, proceeding:",
				methodId
			);
			if (callback) callback();
			return true;
		}

		// Refresh keyring status
		await checkKeyringStatus();

		// Check if we already have a password stored
		if (hasStoredPassword()) {
			console.log("[PasswordModal] Password already stored, proceeding");
			if (callback) callback();
			return true;
		}

		// Show modal and store callback
		console.log("[PasswordModal] No password stored, showing modal");
		showPasswordModal(callback);
		return false;
	}

	// Public API
	window.PasswordModal = {
		init: init,
		show: showPasswordModal,
		hide: hidePasswordModal,
		ensurePassword: ensurePassword,
		methodRequiresSudo: methodRequiresSudo,
		hasStoredPassword: hasStoredPassword,
		checkStatus: checkKeyringStatus,
	};

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