/**
 * Languages Page JavaScript
 * Handles two-step hierarchical language selection:
 * Step 1: Select Major Language
 * Step 2: Select Regional Variant
 * Priority list management with up/down/reordering
 *
 * Features:
 * - Two-step hierarchical selection (major -> regional)
 * - Search functionality for major languages
 * - "Major language only" option in Step 2
 * - Major regional variants with visual indicator
 * - Population display for regional variants
 * - Multi-select with priority ordering
 * - Up/down/remove buttons for priority lists
 */

(function () {
	"use strict";

	// State management
	const state = {
		currentStep: 1, // 1 = major, 2 = regional
		selectedMajorLanguage: null,
		majorLanguages: [],
		regionalVariants: [],
		allLocales: [], // All locales for regional variant search
		audioPriority: [],
		subtitlePriority: [],
		activeRegionalRequest: null, // Track active request to prevent race conditions
		currentRegionalRequestId: null, // Unique ID for current regional request
		debugMode: false, // Disable debug logging in production
	};

	// Drag-and-drop state
	let draggedItem = null;
	let draggedType = null;
	let draggedIndex = null;

	/**
	 * Get flag display for locale (always use image flags)
	 * @param {string} locale - Locale code (e.g., "en", "en-US", "zh-CN")
	 * @param {string} emojiFlag - Emoji flag (not used, for API compatibility)
	 * @returns {string} Flag as <img> tag
	 */
	function getFlagDisplay(locale, emojiFlag) {
		// Extract country code from locale
		let countryCode = locale;
		if (locale.includes("-")) {
			// Extract country code from locale (e.g., "en-US" -> "US")
			countryCode = locale.split("-")[1];
		} else {
			// For major languages, map to common country codes
			// This is a simplified mapping for display purposes
			const langToCountry = {
				en: "US", // English -> United States
				zh: "CN", // Chinese -> China
				es: "ES", // Spanish -> Spain
				fr: "FR", // French -> France
				de: "DE", // German -> Germany
				ja: "JP", // Japanese -> Japan
				ko: "KR", // Korean -> South Korea
				ru: "RU", // Russian -> Russia
				ar: "SA", // Arabic -> Saudi Arabia
				pt: "BR", // Portuguese -> Brazil
				hi: "IN", // Hindi -> India
				it: "IT", // Italian -> Italy
				cs: "CZ", // Czech -> Czech Republic
				da: "DK", // Danish -> Denmark
				el: "GR", // Greek -> Greece
				he: "IL", // Hebrew -> Israel
				sv: "SE", // Swedish -> Sweden
				fil: "PH", // Filipino -> Philippines
			};
			countryCode = langToCountry[locale] || locale.toUpperCase();
		}

		// Always return image tag for all platforms
		return `<img src="/static/flags/${countryCode}.png" alt="${locale}" class="w-8 h-8 shadow-sm" onerror="this.src='/static/flags/UN.png'">`;
	}

	/**
	 * Initialize languages page
	 */
	async function init() {
		console.log("[Languages] Initializing languages page...");

		// Load both preferences and major languages in parallel
		await Promise.all([loadPreferences(), loadMajorLanguages()]);

		// Now that both are loaded, render priority lists
		renderPriorityList("audio");
		renderPriorityList("subtitle");

		// Setup event listeners
		setupEventListeners();

		console.log("[Languages] Languages page initialized");
	}

	/**
	 * Load current language preferences from API
	 */
	async function loadPreferences() {
		try {
			console.log(
				"[Languages] Loading preferences from /api/languages/load...",
			);
			const response = await fetch("/api/languages/load");

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

			const data = await response.json();
			console.log("[Languages] Loaded preferences:", data);

			// Update state
			state.audioPriority = data.audio_languages || [];
			state.subtitlePriority = data.subtitle_languages || [];

			// Don't render priority lists here - wait for major languages to load
			// Rendering is done after Promise.all in init()
		} catch (error) {
			console.error("[Languages] Failed to load preferences:", error);
			showMessage(
				"Failed to load language preferences. Using defaults.",
				"error",
			);
		}
	}

	/**
	 * Load major languages from API
	 */
	async function loadMajorLanguages() {
		try {
			console.log(
				"[Languages] Loading major languages from /api/languages/major...",
			);
			const response = await fetch("/api/languages/major");

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

			const data = await response.json();
			state.majorLanguages = data.major_languages || [];
			console.log("[Languages] Loaded major languages:", state.majorLanguages);

			// Also load all locales for regional variant search
			await loadAllLocales();

			// Render major language list
			renderMajorLanguageList();

			// Hide loading indicator
			const loadingEl = document.getElementById("major-loading");
			if (loadingEl) {
				loadingEl.classList.add("hidden");
			}
		} catch (error) {
			console.error("[Languages] Failed to load major languages:", error);
			const loadingEl = document.getElementById("major-loading");
			if (loadingEl) {
				loadingEl.innerHTML = `
                    <div class="text-red-400 text-center">
                        <i class="bx bx-error-circle text-3xl"></i>
                        <p class="mt-2 text-sm">Failed to load major languages</p>
                        <p class="text-gray-400 text-xs mt-1">${error.message}</p>
                    </div>
                `;
			}
			showMessage(
				"Failed to load major languages. Please refresh the page.",
				"error",
			);
		}
	}

	/**
	 * Load all locales for regional variant search
	 */
	async function loadAllLocales() {
		try {
			console.log("[Languages] Loading all locales for search...");
			const response = await fetch("/api/languages/regions");

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

			const data = await response.json();
			state.allLocales = data.locales || [];
			console.log("[Languages] Loaded all locales:", state.allLocales.length);
		} catch (error) {
			console.error("[Languages] Failed to load all locales:", error);
			// Not critical - major languages will still work, just search won't find regional variants
		}
	}

	/**
	 * Render major language list
	 */
	function renderMajorLanguageList() {
		const list = document.getElementById("major-language-list");
		const searchTerm = document
			.getElementById("major-language-search")
			.value.trim()
			.toLowerCase();

		// Filter major languages
		let filteredLanguages = state.majorLanguages.filter((lang) => {
			if (!searchTerm) return true;
			return (
				lang.language_name.toLowerCase().includes(searchTerm) ||
				lang.language_local.toLowerCase().includes(searchTerm) ||
				lang.language_code.toLowerCase().includes(searchTerm)
			);
		});

		// If searching and no exact matches in major languages, search for regional variants
		// and include their parent languages
		if (
			searchTerm &&
			filteredLanguages.length === 0 &&
			state.allLocales.length > 0
		) {
			// Find all locales matching search term
			const matchedLocales = state.allLocales.filter((locale) => {
				return (
					locale.language_name.toLowerCase().includes(searchTerm) ||
					locale.language_local.toLowerCase().includes(searchTerm) ||
					locale.locale.toLowerCase().includes(searchTerm) ||
					locale.country_name.toLowerCase().includes(searchTerm)
				);
			});

			// Get unique parent language codes from matched locales
			const parentCodes = [
				...new Set(matchedLocales.map((l) => l.language_code)),
			];

			// Filter major languages to show only parents of matched regional variants
			filteredLanguages = state.majorLanguages.filter((lang) => {
				return parentCodes.includes(lang.language_code);
			});
		}

		// Update result count
		document.getElementById("major-language-count").textContent =
			filteredLanguages.length;

		// Clear list (keep loading indicator)
		const items = list.querySelectorAll(".major-language-item");
		items.forEach((item) => item.remove());

		// Render filtered languages
		filteredLanguages.forEach((lang, index) => {
			const isSelected =
				state.selectedMajorLanguage &&
				state.selectedMajorLanguage.language_code === lang.language_code;

			const item = document.createElement("label");
			item.className = `major-language-item flex items-center gap-3 p-3 bg-gray-700 rounded-lg cursor-pointer hover:bg-gray-600 transition ${isSelected ? "ring-2 ring-purple-500" : ""}`;
			item.dataset.languageCode = lang.language_code;
			item.title = "Click to view regional variants";

			item.innerHTML = `
                ${getFlagDisplay(lang.language_code, lang.flag)}
                <div class="ml-3 flex-1">
                    <p class="font-medium text-white">${lang.language_name}</p>
                    <p class="text-gray-400 text-sm">${lang.language_local}</p>
                </div>
                <div class="text-right">
                    <p class="text-blue-400 text-sm font-mono">${lang.language_code}</p>
                    <p class="text-gray-500 text-xs mt-1">Click to view variants</p>
                </div>
            `;

			// Add click handler with closure to capture current lang object
			item.addEventListener("click", function handleClick(event) {
				console.log("[Languages] Clicked major language item:", lang);
				console.log("[Languages] Language code:", lang.language_code);
				handleMajorLanguageSelection(lang);
			});

			list.appendChild(item);
		});
	}

	/**
	 * Handle major language selection
	 */
	function handleMajorLanguageSelection(majorLanguage) {
		if (state.debugMode) {
			console.log("[Languages] === handleMajorLanguageSelection START ===");
			console.log("[Languages] Selected major language:", majorLanguage);
			console.log(
				"[Languages] Selected language code:",
				majorLanguage.language_code,
			);
			console.log(
				"[Languages] Current selectedMajorLanguage before update:",
				state.selectedMajorLanguage,
			);
		}

		// Clear previous regional variants to prevent showing old data
		state.selectedMajorLanguage = majorLanguage;
		state.regionalVariants = [];

		if (state.debugMode) {
			console.log(
				"[Languages] Current selectedMajorLanguage after update:",
				state.selectedMajorLanguage,
			);
		}

		// Load regional variants for this major language
		if (state.debugMode) {
			console.log(
				"[Languages] About to call loadRegionalVariants for:",
				majorLanguage.language_code,
			);
		}
		loadRegionalVariants(majorLanguage.language_code);

		// Transition to Step 2
		state.currentStep = 2;

		if (state.debugMode) {
			console.log(
				"[Languages] About to call updateStepDisplay, currentStep:",
				state.currentStep,
			);
		}
		updateStepDisplay();

		if (state.debugMode) {
			console.log("[Languages] === handleMajorLanguageSelection END ===");
		}
	}

	/**
	 * Load regional variants from API
	 */
	async function loadRegionalVariants(majorCode) {
		// Generate unique request ID
		const requestId = Date.now() + Math.random();

		if (state.debugMode) {
			console.log("[Languages] === loadRegionalVariants START ===");
			console.log(
				"[Languages] Loading regional variants for:",
				majorCode,
				"(request ID:",
				requestId,
				")",
			);
			console.log(
				"[Languages] Current state.selectedMajorLanguage:",
				state.selectedMajorLanguage,
			);
			console.log("[Languages] Current state.currentStep:", state.currentStep);
		}

		try {
			// Abort previous request if it exists
			if (state.activeRegionalRequest) {
				console.log(
					"[Languages] Aborting previous regional variants request (old ID:",
					state.currentRegionalRequestId,
					")",
				);
				state.activeRegionalRequest.abort();
			}

			// Set this as current request ID
			state.currentRegionalRequestId = requestId;
			state.activeRegionalRequest = new AbortController();

			// Clear regional variants in state BEFORE fetching
			state.regionalVariants = [];

			// Get DOM elements with defensive checks
			const flagEl = document.getElementById("selected-major-flag");
			const nameEl = document.getElementById("selected-major-name");
			const localEl = document.getElementById("selected-major-local");
			const loadingEl = document.getElementById("regional-loading");
			const listElement = document.getElementById("regional-variants-list");

			// Clear display elements if they exist
			if (flagEl) flagEl.textContent = "";
			if (nameEl) nameEl.textContent = "";
			if (localEl) localEl.textContent = "";

			if (state.debugMode) {
				console.log("[Languages] DOM elements status:", {
					loading: loadingEl ? "found" : "NOT FOUND",
					list: listElement ? "found" : "NOT FOUND",
					flag: flagEl ? "found" : "NOT FOUND",
					name: nameEl ? "found" : "NOT FOUND",
				});
			}

			// Show loading indicator if element exists
			if (loadingEl) {
				loadingEl.classList.remove("hidden");
				loadingEl.innerHTML =
					'<div class="text-gray-400 text-center py-4">Loading regional variants...</div>';
			} else {
				console.warn("[Languages] Warning: regional-loading element not found");
			}

			// Clear list if element exists
			if (listElement) {
				listElement.innerHTML = "";
			} else {
				console.warn(
					"[Languages] Warning: regional-variants-list element not found",
				);
			}

			// Add timestamp and random number to prevent caching
			const cacheBuster = `${Date.now()}_${Math.random()}`;
			if (state.debugMode) {
				console.log("[Languages] Fetching API with cache buster:", cacheBuster);
			}

			const response = await fetch(
				`/api/languages/regional?method_id=${majorCode}&_t=${cacheBuster}`,
				{
					signal: state.activeRegionalRequest.signal,
				},
			);

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

			const data = await response.json();

			if (state.debugMode) {
				console.log("[Languages] API Response received");
				console.log(
					"[Languages] Has regional_variants?",
					!!data.regional_variants,
				);
				console.log(
					"[Languages] Number of variants:",
					data.regional_variants?.length || 0,
				);
			}

			// Always update state (this IS the current request, we set requestId before calling fetch)
			state.regionalVariants = data.regional_variants || [];

			if (state.debugMode) {
				console.log(
					"[Languages] State updated with",
					state.regionalVariants.length,
					"variants",
				);
			}

			// Update major language display
			if (data.major_language) {
				if (state.debugMode) {
					console.log(
						"[Languages] Calling updateSelectedMajorDisplay with:",
						data.major_language,
					);
				}
				updateSelectedMajorDisplay(data.major_language);
			} else {
				console.warn("[Languages] Warning: No major_language in API response");
			}

			// Render regional variant list
			if (state.debugMode) {
				console.log("[Languages] About to call renderRegionalVariantList()");
			}
			renderRegionalVariantList();
			if (state.debugMode) {
				console.log("[Languages] renderRegionalVariantList() returned");
			}

			// Hide loading indicator if element exists
			if (loadingEl) {
				loadingEl.classList.add("hidden");
			}
		} catch (error) {
			// Ignore errors from aborted requests
			if (error.name === "AbortError") {
				console.log(
					"[Languages] Request aborted for",
					majorCode,
					"(request ID:",
					requestId,
					")",
				);
				return;
			}

			console.error("[Languages] Failed to load regional variants:", error);

			// Show error message if loading element exists
			const loadingEl = document.getElementById("regional-loading");
			if (loadingEl) {
				loadingEl.innerHTML = `
                    <div class="text-red-400">
                        <i class="bx bx-error-circle text-3xl"></i>
                        <p class="mt-2">Failed to load regional variants</p>
                        <p class="text-sm text-gray-400">${error.message}</p>
                    </div>
                `;
			}
		} finally {
			// Clear active request
			state.activeRegionalRequest = null;
			if (state.debugMode) {
				console.log("[Languages] === loadRegionalVariants END ===");
			}
		}
	}

	function updateSelectedMajorDisplay(majorLanguage) {
		console.log(
			"[Languages] updateSelectedMajorDisplay called with:",
			majorLanguage,
		);

		// Safety check: Verify that the language code matches the currently selected one
		if (
			state.selectedMajorLanguage &&
			state.selectedMajorLanguage.language_code !== majorLanguage.language_code
		) {
			console.warn(
				"[Languages] Mismatch detected! Current selected:",
				state.selectedMajorLanguage.language_code,
				"but updating with:",
				majorLanguage.language_code,
			);
			console.warn("[Languages] SKIPPING update to prevent incorrect display");
			return;
		}

		const flagEl = document.getElementById("selected-major-flag");
		const nameEl = document.getElementById("selected-major-name");
		const localEl = document.getElementById("selected-major-local");

		if (!flagEl || !nameEl || !localEl) {
			console.error(
				"[Languages] Selected major language display elements not found!",
			);
			return;
		}

		flagEl.innerHTML = getFlagDisplay(
			majorLanguage.language_code,
			majorLanguage.flag,
		);
		nameEl.textContent = majorLanguage.language_name;
		localEl.textContent = majorLanguage.language_local;

		console.log("[Languages] Updated display to:", majorLanguage.language_name);
	}

	/**
	 * Render regional variant list
	 */
	function renderRegionalVariantList() {
		const list = document.getElementById("regional-variants-list");

		if (!list) {
			console.error("[Languages] Regional variants list element not found!");
			return;
		}

		// Safety check - should not render if no major language selected
		if (!state.selectedMajorLanguage) {
			console.log("[Languages] No major language selected, skipping render");
			list.innerHTML = `
                <div class="text-gray-400 text-sm italic text-center py-4">
                    No language selected
                </div>
            `;
			return;
		}

		if (state.debugMode) {
			console.log("[Languages] === renderRegionalVariantList START ===");
			console.log(
				"[Languages] Rendering regional variants for:",
				state.selectedMajorLanguage.language_code,
			);
			console.log(
				"[Languages] Number of regional variants in state:",
				state.regionalVariants.length,
			);
		}

		// Get currently selected list type for dynamic text
		const languageTypeSelect = document.getElementById("language-type-select");
		const selectedType = languageTypeSelect ? languageTypeSelect.value : "audio";
		const selectedTypeName = selectedType === "audio" ? "Audio" : "Subtitle";

		// Force a complete DOM rebuild by creating a new fragment
		const fragment = document.createDocumentFragment();

		// Helper function to create a row with entry + quick-add buttons
		function createVariantRow(locale, flag, name, local, code, isMajor, isMajorOnly, variant) {
			const row = document.createElement("div");
			row.className = "flex items-center gap-2";
			
			// The language entry (clickable)
			const entry = document.createElement("label");
			entry.className = `regional-variant-item flex-1 flex items-center gap-3 p-3 bg-gray-700 rounded-lg cursor-pointer hover:bg-gray-600 transition ${isMajorOnly ? "border-2 border-yellow-500" : isMajor ? "border-2 border-blue-500" : ""}`;
			entry.dataset.locale = locale;
			entry.title = `Click to add to ${selectedTypeName} list`;

			entry.innerHTML = `
                ${flag}
                <div class="ml-3 flex-1">
                    <p class="font-medium text-white">${name} ${isMajor && !isMajorOnly ? '<span class="text-blue-400 text-sm ml-2">★</span>' : ""}</p>
                    <p class="text-gray-400 text-sm">${local}</p>
                </div>
                <div class="text-right">
                    <p class="${isMajorOnly ? 'text-yellow-400' : 'text-blue-400'} text-sm font-mono">${code}</p>
                    <p class="text-green-400 text-xs mt-1 flex items-center justify-end gap-1">
                        <span>Click to add to ${selectedTypeName}</span>
                        <i class="bx bx-arrow-big-right-line"></i>
                    </p>
                </div>
            `;

			// Main click handler (adds to selected list)
			entry.addEventListener("click", (e) => {
				handleRegionalVariantSelection(variant);
			});

			// Quick-add buttons container (outside the entry)
			const quickAddContainer = document.createElement("div");
			quickAddContainer.className = "flex flex-col gap-1 flex-shrink-0";
			
			const audioBtn = document.createElement("button");
			audioBtn.className = "quick-add-audio bg-gray-600 hover:bg-purple-600 text-white p-1.5 rounded transition flex items-center";
			audioBtn.title = "Add to Audio list";
			audioBtn.innerHTML = '<i class="bx bx-speaker text-sm"></i><i class="bx bx-arrow-big-right-line text-sm text-green-400 ml-1"></i>';
			audioBtn.addEventListener("click", (e) => {
				e.preventDefault();
				e.stopPropagation();
				handleRegionalVariantSelection(variant, "audio");
			});

			const subtitleBtn = document.createElement("button");
			subtitleBtn.className = "quick-add-subtitle bg-gray-600 hover:bg-purple-600 text-white p-1.5 rounded transition flex items-center";
			subtitleBtn.title = "Add to Subtitle list";
			subtitleBtn.innerHTML = '<i class="bx bx-captions text-sm"></i><i class="bx bx-arrow-big-right-line text-sm text-green-400 ml-1"></i>';
			subtitleBtn.addEventListener("click", (e) => {
				e.preventDefault();
				e.stopPropagation();
				handleRegionalVariantSelection(variant, "subtitle");
			});

			quickAddContainer.appendChild(audioBtn);
			quickAddContainer.appendChild(subtitleBtn);

			row.appendChild(entry);
			row.appendChild(quickAddContainer);

			return row;
		}

		// Add "Major language only" option (top of list)
		const majorOnlyRow = createVariantRow(
			state.selectedMajorLanguage.language_code,
			getFlagDisplay(state.selectedMajorLanguage.language_code, state.selectedMajorLanguage.flag),
			state.selectedMajorLanguage.language_name,
			state.selectedMajorLanguage.language_local,
			state.selectedMajorLanguage.language_code,
			false,
			true,
			{
				locale: state.selectedMajorLanguage.language_code,
				country_name: "Major language only",
				country_local: "No regional preference",
				flag: getFlagDisplay(state.selectedMajorLanguage.language_code, state.selectedMajorLanguage.flag),
				major_regional_variant: true,
				population: 0,
			}
		);
		fragment.appendChild(majorOnlyRow);

		// Add regional variants
		if (state.debugMode) {
			console.log("[Languages] Starting to render regional variants items...");
		}

		state.regionalVariants.forEach((variant, index) => {
			if (state.debugMode) {
				console.log(`[Languages] Rendering variant ${index}:`, variant);
			}

			if (!variant || !variant.locale) {
				console.warn("[Languages] Skipping invalid variant:", variant);
				return;
			}

			const isMajor = variant.major_regional_variant;

			// Build display names for regional variants
			let displayName = `${state.selectedMajorLanguage.language_name} - ${variant.country_name}`;
			let displayNative = `${state.selectedMajorLanguage.language_local} - ${variant.country_local}`;

			const variantRow = createVariantRow(
				variant.locale,
				getFlagDisplay(variant.locale, variant.flag),
				displayName,
				displayNative,
				variant.locale,
				isMajor,
				false,
				variant
			);

			fragment.appendChild(variantRow);
		});

		// Clear list and append fragment (this is more efficient than innerHTML)
		if (state.debugMode) {
			console.log(
				"[Languages] Appending",
				fragment.children.length,
				"items to list",
			);
		}

		list.innerHTML = "";
		list.appendChild(fragment);

		if (state.debugMode) {
			console.log("[Languages] === renderRegionalVariantList END ===");
		}
	}

	/**
	 * Handle regional variant selection - directly adds to priority list
	 */
	function handleRegionalVariantSelection(variant, forceType = null) {
		console.log(
			"[Languages] Adding regional variant to priority list:",
			variant,
		);

		// Get current language type (use forced type if provided, otherwise use selector)
		const languageTypeSelect = document.getElementById("language-type-select");
		const languageType = forceType || (languageTypeSelect ? languageTypeSelect.value : "audio");

		// Try to add to priority list (returns false if already exists)
		const added = addToPriorityList(variant.locale, languageType);

		if (!added) {
			// Already in list
			showMessage(`${variant.locale} is already in your ${languageType} list`, "warning");
			return;
		}

		// Get display name for toast
		let displayName = variant.locale;
		if (variant.country_name && variant.country_name !== "Major language only") {
			displayName = `${state.selectedMajorLanguage?.language_name || ''} - ${variant.country_name}`;
		} else if (state.selectedMajorLanguage) {
			displayName = state.selectedMajorLanguage.language_name;
		}

		// Show toast notification
		showMessage(`Added "${displayName}" to ${languageType} list`, "success");

		// Show visual feedback on clicked item
		const clickedItem = document.querySelector(
			`.regional-variant-item[data-locale="${variant.locale}"]`,
		);
		if (clickedItem) {
			// Briefly flash green to show success
			clickedItem.classList.add("ring-2", "ring-green-500");
			setTimeout(() => {
				clickedItem.classList.remove("ring-2", "ring-green-500");
			}, 500);
		}

		// Don't clear selection - stay in Step 2 so user can add more variants
	}
	/**
	 * Handle back to major languages button
	 */
	function handleBackToMajor() {
		if (state.debugMode) {
			console.log("[Languages] === handleBackToMajor START ===");
			console.log("[Languages] Current step before:", state.currentStep);
		}

		// Abort any in-progress regional variants request
		if (state.activeRegionalRequest) {
			console.log("[Languages] Aborting regional variants request on back");
			state.activeRegionalRequest.abort();
		}

		state.currentStep = 1;
		state.selectedMajorLanguage = null;
		state.selectedRegionalVariant = null;
		state.regionalVariants = [];
		state.currentRegionalRequestId = null;

		if (state.debugMode) {
			console.log(
				"[Languages] State reset to step 1, majorLanguage:",
				state.selectedMajorLanguage,
			);
		}

		// Clear "Selected Major Language" display in Step 2
		const flagEl = document.getElementById("selected-major-flag");
		const nameEl = document.getElementById("selected-major-name");
		const localEl = document.getElementById("selected-major-local");
		if (flagEl) flagEl.textContent = "";
		if (nameEl) nameEl.textContent = "";
		if (localEl) localEl.textContent = "";

		// Clear the regional variants list and hide loading
		const listElement = document.getElementById("regional-variants-list");
		const loadingEl = document.getElementById("regional-loading");

		if (listElement) {
			listElement.innerHTML = "";
		} else if (state.debugMode) {
			console.warn(
				"[Languages] Warning: regional-variants-list not found during back",
			);
		}

		if (loadingEl) {
			loadingEl.classList.add("hidden");
			loadingEl.innerHTML = "";
		} else if (state.debugMode) {
			console.warn(
				"[Languages] Warning: regional-loading not found during back",
			);
		}

		updateStepDisplay();

		if (state.debugMode) {
			console.log("[Languages] === handleBackToMajor END ===");
		}
	}

	/**
	 * Update step display (show/hide Step 1 and Step 2)
	 */
	function updateStepDisplay() {
		const step1Container = document.getElementById("step-1-container");
		const step2Container = document.getElementById("step-2-container");

		if (state.currentStep === 1) {
			step1Container.classList.remove("hidden");
			step2Container.classList.add("hidden");
		} else {
			step1Container.classList.add("hidden");
			step2Container.classList.remove("hidden");
		}
	}

	/**
	 * Add locale to priority list
	 * @returns {boolean} true if added, false if already exists
	 */
	function addToPriorityList(locale, type) {
		console.log(`[Languages] Adding ${locale} to ${type} priority list`);

		if (type === "audio") {
			if (!state.audioPriority.includes(locale)) {
				state.audioPriority.push(locale);
				renderPriorityList("audio");
				return true;
			}
		} else if (type === "subtitle") {
			if (!state.subtitlePriority.includes(locale)) {
				state.subtitlePriority.push(locale);
				renderPriorityList("subtitle");
				return true;
			}
		}
		return false;
	}

	/**
	 * Render priority list
	 */
	function renderPriorityList(type) {
		const container = document.getElementById(`${type}-priority-list`);
		const priorityList =
			type === "audio" ? state.audioPriority : state.subtitlePriority;

		if (priorityList.length === 0) {
			container.innerHTML = `
                <div class="text-gray-400 text-sm italic text-center py-4">
                    No ${type} languages selected
                </div>
            `;
			return;
		}

		container.innerHTML = "";

		priorityList.forEach((locale, index) => {
			// Find language data
			let langData = null;
			let parentLang = null;
			let isMajorOnly = false;

			// Check major languages first
			const majorLang = state.majorLanguages.find(
				(l) => l.language_code === locale,
			);
			if (majorLang) {
				parentLang = majorLang;
				langData = {
					locale: majorLang.language_code,
					flag: majorLang.flag,
					name: majorLang.language_name,
					local: majorLang.language_local,
				};
				isMajorOnly = true;
			}

			// Check all locales for regional variants (not just current major language)
			if (!langData && locale.includes("-")) {
				const variant = state.allLocales.find((v) => v.locale === locale);
				if (variant) {
					// Extract language code from locale (e.g., "pt-BR" -> "pt")
					const langCode = locale.split("-")[0];

					// Find parent major language for display
					const parentMajorLang = state.majorLanguages.find(
						(l) => l.language_code === langCode
					);
					if (parentMajorLang) {
						parentLang = parentMajorLang;
					}

					langData = {
						locale: variant.locale,
						flag: variant.flag,
						name: variant.country_name,
						local: variant.country_local,
					};
				}
			}

			if (!langData) {
				langData = {
					locale: locale,
					flag: "🏳️",
					name: locale,
					local: "",
				};
			}

			// Build display names
			let displayName;
			let displayNative;

			if (isMajorOnly) {
				// Major language only: show just the language name
				displayName = langData.name;
				displayNative = langData.local;
			} else if (parentLang && !isMajorOnly) {
				// Regional variant: combine parent and region names
				displayName = `${parentLang.language_name} - ${langData.name}`;
				displayNative = `${parentLang.language_local} - ${langData.local}`;
			} else {
				// Fallback
				displayName = langData.name;
				displayNative = langData.local;
			}

			const item = document.createElement("div");
			item.className = "priority-list-item flex items-center gap-3 p-3 bg-gray-700 rounded-lg cursor-grab active:cursor-grabbing";
			item.dataset.index = index;
			item.dataset.locale = locale;
			item.dataset.type = type;
			item.draggable = true;

			item.innerHTML = `
                <!-- Drag Handle -->
                <div class="drag-handle flex-shrink-0" title="Drag to reorder">
                    <i class="bx bx-menu text-xl"></i>
                </div>
                ${getFlagDisplay(langData.locale, langData.flag)}
                <div class="flex-1">
                    <p class="font-medium text-white">${displayName}</p>
                    ${displayNative ? `<p class="text-gray-400 text-sm">${displayNative}</p>` : ''}
                </div>
                <div class="text-right">
                    <p class="text-blue-400 text-sm font-mono">${langData.locale}</p>
                </div>
                <div class="flex gap-1">
                    <button class="move-up-btn bg-gray-600 hover:bg-gray-500 text-white p-2 rounded transition"
                            title="Move up">
                        <i class="bx bx-arrow-up-wide-narrow"></i>
                    </button>
                    <button class="move-down-btn bg-gray-600 hover:bg-gray-500 text-white p-2 rounded transition"
                            title="Move down">
                        <i class="bx bx-arrow-down-narrow-wide"></i>
                    </button>
                    <button class="remove-btn bg-red-600 hover:bg-red-700 text-white p-2 rounded transition"
                            title="Remove">
                        <i class="bx bx-trash"></i>
                    </button>
                </div>
            `;

			// Disable up/down buttons for first/last items
			if (index === 0) {
				item.querySelector(".move-up-btn").disabled = true;
				item
					.querySelector(".move-up-btn")
					.classList.add("opacity-50", "cursor-not-allowed");
			}
			if (index === priorityList.length - 1) {
				item.querySelector(".move-down-btn").disabled = true;
				item
					.querySelector(".move-down-btn")
					.classList.add("opacity-50", "cursor-not-allowed");
			}

			container.appendChild(item);
		});
	}

	/**
	 * Handle priority list actions (up/down/remove)
	 */
	function handlePriorityListAction(event) {
		const btn = event.target.closest("button");
		if (!btn) return;

		const item = btn.closest("[data-index]");
		const index = parseInt(item.dataset.index);
		const locale = item.dataset.locale;
		const type = item.dataset.type;
		const priorityList =
			type === "audio" ? state.audioPriority : state.subtitlePriority;

		if (btn.classList.contains("move-up-btn") && index > 0) {
			// Swap with previous item
			[priorityList[index], priorityList[index - 1]] = [
				priorityList[index - 1],
				priorityList[index],
			];
			renderPriorityList(type);
		} else if (
			btn.classList.contains("move-down-btn") &&
			index < priorityList.length - 1
		) {
			// Swap with next item
			[priorityList[index], priorityList[index + 1]] = [
				priorityList[index + 1],
				priorityList[index],
			];
			renderPriorityList(type);
		} else if (btn.classList.contains("remove-btn")) {
			// Get display name before removing
			const removedLocale = priorityList[index];
			
			// Remove from list
			priorityList.splice(index, 1);
			renderPriorityList(type);
			
			// Show toast notification
			showMessage(`Removed "${removedLocale}" from ${type} list`, "info");
		}
	}

	/**
	 * Handle drag start event
	 */
	function handleDragStart(event) {
		const item = event.target.closest(".priority-list-item");
		if (!item) return;

		draggedItem = item;
		draggedType = item.dataset.type;
		draggedIndex = parseInt(item.dataset.index);

		// Set data transfer for compatibility
		event.dataTransfer.effectAllowed = "move";
		event.dataTransfer.setData("text/plain", draggedIndex.toString());

		// Add dragging class after a small delay to allow the drag image to be captured
		setTimeout(() => {
			item.classList.add("dragging");
		}, 0);

		console.log(`[Languages] Drag start: index=${draggedIndex}, type=${draggedType}`);
	}

	/**
	 * Handle drag over event
	 */
	function handleDragOver(event) {
		event.preventDefault();
		event.dataTransfer.dropEffect = "move";

		const item = event.target.closest(".priority-list-item");
		if (!item || item === draggedItem) return;

		const rect = item.getBoundingClientRect();
		const midpoint = rect.top + rect.height / 2;

		// Clear all drag-over classes first
		item.parentElement.querySelectorAll(".priority-list-item").forEach(el => {
			el.classList.remove("drag-over", "drag-over-bottom");
		});

		// Add appropriate class based on mouse position
		if (event.clientY < midpoint) {
			item.classList.add("drag-over");
		} else {
			item.classList.add("drag-over-bottom");
		}
	}

	/**
	 * Handle drag leave event
	 */
	function handleDragLeave(event) {
		const item = event.target.closest(".priority-list-item");
		if (item) {
			item.classList.remove("drag-over", "drag-over-bottom");
		}
	}

	/**
	 * Handle drop event
	 */
	function handleDrop(event) {
		event.preventDefault();

		const targetItem = event.target.closest(".priority-list-item");
		if (!targetItem || targetItem === draggedItem) return;

		const targetType = targetItem.dataset.type;
		const targetIndex = parseInt(targetItem.dataset.index);

		// Only allow dropping within the same list
		if (targetType !== draggedType) return;

		// Get the priority list
		const priorityList = targetType === "audio" ? state.audioPriority : state.subtitlePriority;

		// Calculate the new position based on drop location
		const rect = targetItem.getBoundingClientRect();
		const midpoint = rect.top + rect.height / 2;
		let newIndex;
		
		if (event.clientY < midpoint) {
			// Drop above target
			newIndex = targetIndex;
		} else {
			// Drop below target
			newIndex = targetIndex + 1;
		}

		// Adjust for removing the dragged item
		if (draggedIndex < newIndex) {
			newIndex--;
		}

		// Don't do anything if dropping to the same position
		if (draggedIndex === newIndex || 
			(draggedIndex === targetIndex && event.clientY >= midpoint && draggedIndex === priorityList.length - 1)) {
			return;
		}

		console.log(`[Languages] Drop: from ${draggedIndex} to ${newIndex}`);

		// Remove the item from its current position
		const [item] = priorityList.splice(draggedIndex, 1);
		
		// Insert at new position
		priorityList.splice(newIndex, 0, item);

		// Re-render the list
		renderPriorityList(targetType);
	}

	/**
	 * Handle drag end event
	 */
	function handleDragEnd(event) {
		// Clean up all visual states
		document.querySelectorAll(".priority-list-item").forEach(item => {
			item.classList.remove("dragging", "drag-over", "drag-over-bottom");
		});

		// Reset drag state
		draggedItem = null;
		draggedType = null;
		draggedIndex = null;

		console.log("[Languages] Drag end");
	}

	/**
	 * Format population number for display
	 */
	function formatPopulation(population) {
		if (population === 0 || !population) {
			return "N/A";
		}
		if (population >= 1000000) {
			return (population / 1000000).toFixed(1) + "B";
		}
		if (population >= 1000) {
			return (population / 1000).toFixed(1) + "M";
		}
		return population.toString();
	}

	/**
	 * Setup event listeners
	 */
	function setupEventListeners() {
		// Major language search with debounce
		const searchInput = document.getElementById("major-language-search");
		let searchTimeout;
		searchInput.addEventListener("input", () => {
			clearTimeout(searchTimeout);
			searchTimeout = setTimeout(() => {
				renderMajorLanguageList();
			}, 300);
		});

		// Clear search button
		const clearSearchBtn = document.getElementById("clear-search-btn");
		if (clearSearchBtn) {
			clearSearchBtn.addEventListener("click", () => {
				searchInput.value = "";
				renderMajorLanguageList();
				searchInput.focus();
			});
		}

		// Language type selector buttons (now in priority list headers)
		const audioSelector = document.getElementById("selector-audio");
		const subtitleSelector = document.getElementById("selector-subtitle");
		const languageTypeSelect = document.getElementById("language-type-select");

		function updateSelectorUI(type) {
			// Update Audio selector button
			if (audioSelector) {
				if (type === "audio") {
					audioSelector.className = "selector-btn bg-green-600 text-white px-4 py-2 rounded-lg transition text-sm font-medium flex items-center gap-2 focus:outline-none focus:ring-2 focus:ring-green-500";
					audioSelector.innerHTML = '<i class="bx bx-check"></i><span>Selected for Adding</span>';
					audioSelector.title = "Audio is selected for adding languages";
				} else {
					audioSelector.className = "selector-btn bg-gray-700 hover:bg-gray-600 text-white px-4 py-2 rounded-lg transition text-sm font-medium flex items-center gap-2 focus:outline-none focus:ring-2 focus:ring-gray-500";
					audioSelector.innerHTML = '<i class="bx bx-plus"></i><span>Select for Adding</span>';
					audioSelector.title = "Click to select Audio for adding languages";
				}
			}

			// Update Subtitle selector button
			if (subtitleSelector) {
				if (type === "subtitle") {
					subtitleSelector.className = "selector-btn bg-green-600 text-white px-4 py-2 rounded-lg transition text-sm font-medium flex items-center gap-2 focus:outline-none focus:ring-2 focus:ring-green-500";
					subtitleSelector.innerHTML = '<i class="bx bx-check"></i><span>Selected for Adding</span>';
					subtitleSelector.title = "Subtitle is selected for adding languages";
				} else {
					subtitleSelector.className = "selector-btn bg-gray-700 hover:bg-gray-600 text-white px-4 py-2 rounded-lg transition text-sm font-medium flex items-center gap-2 focus:outline-none focus:ring-2 focus:ring-gray-500";
					subtitleSelector.innerHTML = '<i class="bx bx-plus"></i><span>Select for Adding</span>';
					subtitleSelector.title = "Click to select Subtitle for adding languages";
				}
			}

			// Update hidden select element
			if (languageTypeSelect) {
				languageTypeSelect.value = type;
			}

			// Re-render regional variant list to update the "Click to add to X" text
			// Only if we're in Step 2 (regional variants view)
			if (state.currentStep === 2 && state.selectedMajorLanguage) {
				renderRegionalVariantList();
			}
		}

		// Add click handlers for selector buttons
		if (audioSelector) {
			audioSelector.addEventListener("click", function () {
				updateSelectorUI("audio");
				// Note: Do NOT reset the language list - selector state persists
			});
		}

		if (subtitleSelector) {
			subtitleSelector.addEventListener("click", function () {
				updateSelectorUI("subtitle");
				// Note: Do NOT reset the language list - selector state persists
			});
		}

		// Initialize with audio selected
		updateSelectorUI("audio");

		// Back to major button
		document
			.getElementById("back-to-major-btn")
			.addEventListener("click", handleBackToMajor);

		// Priority list actions (event delegation)
		const audioPriorityList = document.getElementById("audio-priority-list");
		const subtitlePriorityList = document.getElementById("subtitle-priority-list");

		// Click handlers for buttons
		audioPriorityList.addEventListener("click", handlePriorityListAction);
		subtitlePriorityList.addEventListener("click", handlePriorityListAction);

		// Drag and drop handlers (event delegation)
		[audioPriorityList, subtitlePriorityList].forEach(list => {
			list.addEventListener("dragstart", handleDragStart);
			list.addEventListener("dragover", handleDragOver);
			list.addEventListener("dragleave", handleDragLeave);
			list.addEventListener("drop", handleDrop);
			list.addEventListener("dragend", handleDragEnd);
		});

		// Save button
		document
			.getElementById("save-languages-btn")
			.addEventListener("click", handleSavePreferences);
	}

	/**
	 * Handle save preferences
	 */
	async function handleSavePreferences() {
		console.log("[Languages] Saving preferences...");
		console.log("[Languages] Audio priority:", state.audioPriority);
		console.log("[Languages] Subtitle priority:", state.subtitlePriority);

		const saveButton = document.getElementById("save-languages-btn");
		const originalContent = saveButton.innerHTML;

		// Show loading state
		saveButton.disabled = true;
		saveButton.innerHTML =
			'<i class="bx bx-loader-alt bx-spin"></i> Saving...';

		try {
			const response = await fetch("/api/languages/save", {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
				},
				body: JSON.stringify({
					audio_languages: state.audioPriority,
					subtitle_languages: state.subtitlePriority,
				}),
			});

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

			const data = await response.json();
			console.log("[Languages] Save response:", data);

			// Show success message
			showMessage("Language preferences saved successfully!", "success");

			// Reload page after 2 seconds
			setTimeout(() => {
				window.location.reload();
			}, 2000);
		} catch (error) {
			console.error("[Languages] Failed to save preferences:", error);
			// Restore button state
			saveButton.disabled = false;
			saveButton.innerHTML = originalContent;
			showMessage(
				"Failed to save language preferences. " + error.message,
				"error",
			);
		}
	}

	/**
	 * Show a message to the user (uses global toast system if available)
	 */
	function showMessage(message, type = "info") {
		// Try to use global toast system if available
		if (window.showToast) {
			window.showToast(message, type);
			return;
		}

		// Fallback: Create toast element at bottom-right
		const toastContainer = document.querySelector('.toast-container') || (() => {
			const container = document.createElement('div');
			container.className = 'toast-container';
			document.body.appendChild(container);
			return container;
		})();

		const toast = document.createElement('div');
		toast.className = `toast toast-${type}`;
		toast.innerHTML = `
			<div class="toast-content">
				<i class="toast-icon bx ${
					type === "success"
						? "bx-check-circle"
						: type === "error"
							? "bx-error-circle"
							: type === "warning"
								? "bx-warning"
								: "bx-info-circle"
				}"></i>
				<span class="toast-message">${message}</span>
			</div>
			<button class="toast-close" onclick="this.parentElement.remove()">
				<i class="bx bx-x"></i>
			</button>
		`;

		toastContainer.appendChild(toast);

		// Trigger animation
		requestAnimationFrame(() => {
			toast.classList.add('toast-visible');
		});

		// Auto-remove after 4 seconds
		setTimeout(() => {
			toast.classList.remove('toast-visible');
			toast.classList.add('toast-dismissing');
			setTimeout(() => toast.remove(), 300);
		}, 4000);
	}

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