console.log("Launcher UI loaded");

new QWebChannel(qt.webChannelTransport, function(channel) {
    const bridge = channel.objects.bridge;

    const startButton = document.querySelector(".start");
    const settingsButton = document.querySelector(".settings");
    const statusIcon = document.getElementById("status-icon");
    const onlineCount = document.getElementById("online-count");
    const fill = document.getElementById("online-fill");
    const updateIcon = document.getElementById("update-icon");
    const progressText = document.querySelector(".update-progress");
    const progressFill = document.getElementById("progress-fill");

    const settingsDialog = document.getElementById("settings-dialog");
    const buttonsDiv = document.querySelector(".buttons");
    
    // Кнопка AdminCP (по умолчанию скрыта)
    const adminButton = document.createElement("button");
    adminButton.className = "admincp";
    adminButton.style.display = "none";
    adminButton.innerHTML = `
      <img src="../images/icon_admin.png" alt="Admin" style="width: 16px; vertical-align: middle; margin-right: 4px;" />
      AdminCP
    `;
    adminButton.addEventListener("click", () => {
      bridge.open_admincp();
    });
    buttonsDiv.appendChild(adminButton);
    
    // Надёжная проверка на стороне Python
    function checkAdminAccess() {
      bridge.should_show_admincp(function(shouldShow) {
        adminButton.style.display = shouldShow ? "inline-block" : "none";
      });
    }
    
    setInterval(checkAdminAccess, 5000);
    checkAdminAccess();
	
    const resolutionSelect = document.getElementById("resolution-select");
    const toggleSound = document.getElementById("toggle-sound");
    const toggleSfx = document.getElementById("toggle-sfx");
	const toggleEmbed = document.getElementById("toggle-embed");
	const languageSelect = document.getElementById("language-select"); // ← добавь эту строку
    const saveSettingsBtn = document.getElementById("save-settings");
    const cancelSettingsBtn = document.getElementById("cancel-settings");

	function applyTranslations(langCode) {
		bridge.get_translation(langCode, function(raw) {
			try {
				const dict = JSON.parse(raw);
	
				document.title = dict.title;

				const onlineLabel = document.getElementById("online-label");
				if (onlineLabel) {
					const count = document.getElementById("online-count")?.textContent || "?";
					onlineLabel.innerHTML = `${dict.online_players} <span id="online-count">${count}</span>/500`;
				}

				const h1 = document.querySelector("h1");
				if (h1) h1.textContent = dict.title;
	
				const desc = document.querySelector(".center p");
				if (desc) desc.textContent = dict.description;
	
				const startBtn = document.querySelector(".start");
				if (startBtn) startBtn.innerHTML = `<img src="../images/icon_start.png" alt="Start" style="width: 16px; vertical-align: middle; margin-right: 4px;" /> ${dict.start}`;
	
				const settingsBtn = document.querySelector(".settings");
				if (settingsBtn) settingsBtn.innerHTML = `<img src="../images/icon_settings.png" alt="Settings" style="width: 16px; vertical-align: middle; margin-right: 4px;" /> ${dict.settings}`;
				
				const guidesBtn = document.querySelector(".guides");
				if (guidesBtn) guidesBtn.innerHTML = `<img src="../images/icon_guides.png" alt="Guides" style="width: 16px; vertical-align: middle; margin-right: 4px;" /> ${dict.guides}`;
	
				const resLabel = document.querySelector("label[for='resolution-select']");
				if (resLabel) resLabel.textContent = dict.resolution;
	
				const soundSpan = document.querySelector("#toggle-sound + span");
				if (soundSpan) soundSpan.textContent = dict.music;
				
				const sfxSpan = document.querySelector("#toggle-sfx + span");
				if (sfxSpan) sfxSpan.textContent = dict.sfx;

				const langLabel = document.querySelector("label[for='language-select']");
				if (langLabel) langLabel.textContent = dict.language;
	
				const saveBtn = document.getElementById("save-settings");
				if (saveBtn) saveBtn.textContent = dict.save;
	
				const cancelBtn = document.getElementById("cancel-settings");
				if (cancelBtn) cancelBtn.textContent = dict.cancel;
	
				const panelTitles = document.querySelectorAll(".panel h3");
				if (panelTitles[0]) panelTitles[0].innerHTML = `<img src="../images/icon_news.png" style="width: 22px; vertical-align: middle; margin-right: 6px;" /> ${dict.news}`;
				if (panelTitles[1]) panelTitles[1].innerHTML = `<img src="../images/icon_changelogs.png" style="width: 22px; vertical-align: middle; margin-right: 6px;" /> ${dict.changelogs}`;
				if (panelTitles[2]) panelTitles[2].innerHTML = `<img src="../images/icon_events.png" style="width: 22px; vertical-align: middle; margin-right: 6px;" /> ${dict.events}`;
	
				const footer = document.querySelector(".footer span");
				if (footer) footer.innerHTML = `${dict.status} <b class="offline">ONLINE</b>`;
	
			} catch (e) {
				console.error("❌ Failed to apply translations:", e);
			}
		});
	}

	// ✅ Загрузить config.json при запуске
	bridge.load_config(function(json) {
		try {
			const config = JSON.parse(json);
	
			// Применяем настройки
			if (config.resolution) {
				localStorage.setItem("resolution", config.resolution);
				if (bridge.launcher_set_resolution) {
					bridge.launcher_set_resolution(config.resolution);
				}
			}
	
			if (config.language) {
				localStorage.setItem("language", config.language);
				if (bridge.launcher_set_language) {
					bridge.launcher_set_language(config.language);
				}
				applyTranslations(config.language); // ✅ ЗАГРУЗКА ЯЗЫКА ПРИ СТАРТЕ
			}
	
			if (typeof config.music === "boolean") {
				localStorage.setItem("sound", config.music);
			}
	
			if (typeof config.sfx === "boolean") {
				localStorage.setItem("sfx", config.sfx);
			}

			if (typeof config.embed === "boolean") {
				localStorage.setItem("embed", config.embed);
				toggleEmbed.checked = config.embed;
			}

			// Загружаем новости, ченджлоги и ивенты на выбранном языке
			loadHomePanel("news", "get_home_news", 0);
			loadHomePanel("changelogs", "get_home_changelogs", 1);
			loadHomePanel("events", "get_home_events", 2);

		} catch (e) {
			console.error("❌ Failed to apply config.json:", e);
		}
	});

	// ✅ Загрузка list.json через bridge.get_resolutions()
	bridge.get_resolutions(function(json) {
		try {
			const list = JSON.parse(json);
			resolutionSelect.innerHTML = "";
	
			list.forEach(entry => {
				const option = document.createElement("option");
				option.value = entry.value;
				option.textContent = entry.label;
				resolutionSelect.appendChild(option);
			});
	
			const savedRes = localStorage.getItem("resolution");
			if (savedRes && list.some(r => r.value === savedRes)) {
				resolutionSelect.value = savedRes;
			}
		} catch (e) {
			console.error("❌ Failed to parse resolution list:", e);
		}
	
		// 🔒 Отключить SETTINGS если main.exe уже запущен
		bridge.is_game_running(function(isRunning) {
			if (isRunning) {
				settingsButton.disabled = true;
				settingsButton.style.opacity = 0.6;
				settingsButton.style.cursor = "not-allowed";
				settingsButton.title = "Close all main.exe to change settings";
			}
		});
	});
	
    function waitForLicenseElementsAndFill() {
      const ownerElem = document.getElementById("license-owner");
      const validElem = document.getElementById("license-valid");
    
      if (!ownerElem || !validElem) {
        return setTimeout(waitForLicenseElementsAndFill, 100);  // повтор каждые 100мс
      }
    
      if (typeof bridge !== 'undefined' && bridge.getLicenseInfo) {
        bridge.getLicenseInfo().then(function(data) {
          try {
            const info = JSON.parse(data);
            ownerElem.innerText = info.owner || "Unknown";
            validElem.innerText = info.valid_until || "Unknown";
    
            const today = new Date();
            const until = new Date(info.valid_until);
            if (until < today) {
              validElem.style.color = "#ff4f4f";
            }
          } catch (e) {
            console.warn("Failed to parse license info", e);
          }
        });
      }
    }
    
    setTimeout(waitForLicenseElementsAndFill, 100);

    // 👥 Обновление онлайна
    function updateOnline() {
        bridge.get_online_json(function(data) {
            try {
                const parsed = typeof data === "string" ? JSON.parse(data) : data;
                let online = 0;
                for (let key in parsed) {
                    if (parsed[key]?.ConnectStat === 1) online++;
                }
                const boosted = online + 0;
                onlineCount.textContent = boosted;

                let iconName = "icon_on0.png";
                if (boosted > 10 && boosted <= 50) iconName = "icon_on1.png";
                else if (boosted > 50 && boosted <= 100) iconName = "icon_on2.png";
                else if (boosted > 100 && boosted <= 200) iconName = "icon_on3.png";
                else if (boosted > 200) iconName = "icon_on4.png";
                statusIcon.src = `../images/${iconName}`;

                const maxPlayers = 500;
                const percent = Math.min((boosted / maxPlayers) * 100, 100);
                fill.style.width = `${percent}%`;

                if (boosted <= 10) fill.style.backgroundColor = "#555";
                else if (boosted <= 50) fill.style.backgroundColor = "#4caf50";
                else if (boosted <= 100) fill.style.backgroundColor = "#2196f3";
                else if (boosted <= 200) fill.style.backgroundColor = "#ffc107";
                else fill.style.backgroundColor = "#f44336";
            } catch (e) {
                console.error("❌ Failed to parse memb_stat.json:", e);
            }
        });
    }

    // 📥 Обновление лаунчера
    function runUpdateAndStart() {
        updateIcon.src = "../images/icon_upload.png";
        progressText.textContent = "Checking for updates...";
        progressFill.style.width = "0%";
        bridge.run_update();
    }

    window.updateProgress = function(percent) {
        progressFill.style.width = percent + "%";
        progressText.textContent = `Downloading... ${percent}%`;
    };

    bridge.update_result.connect(function(raw) {
        let response = {};
        try {
            response = typeof raw === "string" ? JSON.parse(raw) : raw;
        } catch (e) {
            console.error("❌ Invalid JSON from update_result:", raw);
            response = { status: "unknown" };
        }

        switch (response.status) {
            case "success":
                updateIcon.src = "../images/icon_uploaddone.png";
                progressText.textContent = "Successful update!";
                progressFill.style.width = "100%";
                setTimeout(() => bridge.start_game(), 300);
                break;
            case "download_error":
                updateIcon.src = "../images/icon_uploaderror.png";
                progressText.textContent = "Download failed";
                progressFill.style.width = "0%";
                break;
            case "extract_error":
                updateIcon.src = "../images/icon_uploadwarning.png";
                progressText.textContent = "Extract error";
                progressFill.style.width = "0%";
                break;
            case "missing_file":
            case "invalid_file":
            case "error_reading":
                const labelMap = {
                    missing_file: "Missing",
                    invalid_file: "Corrupted",
                    error_reading: "Error"
                };
                const rawName = response.file.split("/").pop();
                const short = rawName.length > 20 ? rawName.slice(0, 17) + "..." : rawName;
                progressText.textContent = `${labelMap[response.status]}: ${short}`;
                updateIcon.src = "../images/icon_uploaderror.png";
                progressFill.style.width = "0%";
                break;
            default:
                updateIcon.src = "../images/icon_uploadwarning.png";
                progressText.textContent = "Unknown error";
                progressFill.style.width = "0%";
                break;
        }
    });

    startButton.addEventListener("click", () => {
        console.log("▶ START GAME clicked");
        runUpdateAndStart();
    });

	settingsButton.addEventListener("click", () => {
		bridge.is_game_running(function(isRunning) {
			if (isRunning) {
				const existing = document.getElementById("block-settings-dialog");
				if (existing) existing.remove();
	
				const errorDialog = document.createElement("div");
				errorDialog.id = "block-settings-dialog";
				errorDialog.className = "settings-dialog";
				errorDialog.style.display = "flex";
	
				errorDialog.innerHTML = `
					<div class="dialog-box">
						<h2 style="color: #ff4f4f;">Cannot Open Settings</h2>
						<p style="margin-top: 10px; color: #ddd;">
							The game is currently running.<br>
							Please close all <code>main.exe</code> instances before changing resolution or sound settings.
						</p>
						<div class="dialog-buttons" style="margin-top: 20px;">
							<button id="close-block-dialog">OK</button>
						</div>
					</div>
				`;
	
				document.body.appendChild(errorDialog);
	
				document.getElementById("close-block-dialog").addEventListener("click", () => {
					errorDialog.remove();
				});
	
				return;
			}
	
			// Открытие настроек
			resolutionSelect.value = localStorage.getItem("resolution") || "1360x768";
			toggleSound.checked = localStorage.getItem("sound") !== "false";
			toggleSfx.checked = localStorage.getItem("sfx") !== "false";
			languageSelect.value = localStorage.getItem("language") || "en";  // ✅ язык
	
			settingsDialog.style.display = "flex";
		});
	});

	function loadHomePanel(section, method, containerIndex) {
		const resolution = localStorage.getItem("resolution") || "1360x768";
		const panel = document.querySelectorAll(".panel")[containerIndex];
	
		// Задаём высоту панели по разрешению
		let panelHeight = 360;
		switch (resolution) {
			case "800x600":       panelHeight = 150; break;  // 600 - 450
			case "1024x768":      panelHeight = 318; break;  // 768 - 450
			case "1280x720":      panelHeight = 270; break;  // 720 - 450
			case "1360x768":      panelHeight = 318; break;  // 768 - 450
			case "1280x1024":     panelHeight = 574; break;  // 1024 - 450
			case "IGCN-0":        panelHeight = 150; break;  // 800x600
			case "IGCN-1":        panelHeight = 150; break;  // 800x600
			case "IGCN-2":        panelHeight = 318; break;  // 1024x768
			case "IGCN-3":        panelHeight = 270; break;  // 1280x720
			case "IGCN-4":        panelHeight = 510; break;  // 1280x960 → 960 - 450
			case "IGCN-5":        panelHeight = 450; break;  // 1600x900  → 900 - 450
			case "IGCN-6":        panelHeight = 600; break;  // 1680x1050 → 1050 - 450
			case "IGCN-7":        panelHeight = 540; break;  // 1760x990  → 990 - 450
			case "IGCN-8":        panelHeight = 630; break;  // допустим 1080p → 1080 - 450
			default:              panelHeight = 360;
		}

	
		panel.style.height = `${panelHeight}px`;
		panel.style.overflow = "hidden";
		panel.style.position = "relative";
	
		const container = panel.querySelector("ul");
		container.innerHTML = "";
		container.style.maxHeight = `${panelHeight - 70}px`;
		container.style.overflow = "hidden";
	
		let pagination = panel.querySelector(".pagination");
		if (!pagination) {
			pagination = document.createElement("div");
			pagination.className = "pagination";
			panel.appendChild(pagination);
		}
		pagination.style.position = "absolute";
		pagination.style.bottom = "10px";
		pagination.style.left = "0";
		pagination.style.right = "0";
		pagination.style.textAlign = "center";
	
		let currentPage = 1;
	
		bridge[method](function(json) {
			try {
				const data = JSON.parse(json);
				const lang = localStorage.getItem("language") || "en";
				const list = data[lang] || [];
	
				// Возвращает индекс следующего старта (после заполнения высоты)
				function paginateByHeight(startIndex) {
					const testContainer = document.createElement("ul");
					testContainer.style.visibility = "hidden";
					testContainer.style.position = "absolute";
					testContainer.style.top = "0";
					testContainer.style.left = "0";
					testContainer.style.width = container.clientWidth + "px";
					document.body.appendChild(testContainer);
	
					let height = 0;
					let count = 0;
					for (let i = startIndex; i < list.length; i++) {
						const li = document.createElement("li");
						li.innerHTML = `<strong>${list[i].title}</strong><br>${list[i].text}`;
						testContainer.appendChild(li);
						height += li.offsetHeight;
						if (height > panelHeight - 70) break;
						count++;
					}
					testContainer.remove();
					return Math.max(1, count);
				}
	
				// Предрасчёт всех страниц
				const pages = [];
				for (let i = 0; i < list.length;) {
					const count = paginateByHeight(i);
					pages.push(list.slice(i, i + count));
					i += count;
				}
	
				function renderPage(pageIndex) {
					container.innerHTML = "";
					const items = pages[pageIndex - 1] || [];
	
					items.forEach(item => {
						const li = document.createElement("li");
						li.innerHTML = `<strong>${item.title}</strong><br>${item.text}`;
						container.appendChild(li);
					});
	
					renderPagination(pages.length, pageIndex);
				}
	
				function renderPagination(totalPages, pageIndex) {
					pagination.innerHTML = "";
					if (totalPages <= 1) return;
	
					const createBtn = (text, page, active = false) => {
						const btn = document.createElement("button");
						btn.textContent = text;
						if (active) btn.classList.add("active");
						btn.onclick = () => {
							currentPage = page;
							renderPage(page);
						};
						return btn;
					};
	
					if (pageIndex > 1) pagination.appendChild(createBtn("<", pageIndex - 1));
					pagination.appendChild(createBtn("1", 1, pageIndex === 1));
	
					if (pageIndex > 3)
						pagination.appendChild(Object.assign(document.createElement("span"), { textContent: "...", className: "dots" }));
	
					for (let i = pageIndex - 1; i <= pageIndex + 1; i++) {
						if (i > 1 && i < totalPages)
							pagination.appendChild(createBtn(i, i, pageIndex === i));
					}
	
					if (pageIndex < totalPages - 2)
						pagination.appendChild(Object.assign(document.createElement("span"), { textContent: "...", className: "dots" }));
	
					if (totalPages > 1)
						pagination.appendChild(createBtn(totalPages, totalPages, pageIndex === totalPages));
	
					if (pageIndex < totalPages)
						pagination.appendChild(createBtn(">", pageIndex + 1));
				}
	
				renderPage(currentPage);
			} catch (e) {
				console.error(`❌ Failed to load ${section}:`, e);
			}
		});
	}

	// ⬇️ вызываем для всех 3 секций:
	loadHomePanel("news", "get_home_news", 0);
	loadHomePanel("changelogs", "get_home_changelogs", 1);
	loadHomePanel("events", "get_home_events", 2);

	saveSettingsBtn.addEventListener("click", () => {
		const selectedResolution = resolutionSelect.value;
		const selectedLanguage = languageSelect.value;
		const musicEnabled = toggleSound.checked;
		const sfxEnabled = toggleSfx.checked;
		const embedEnabled = toggleEmbed.checked;
	
		// Сохраняем в localStorage
		localStorage.setItem("resolution", selectedResolution);
		localStorage.setItem("sound", musicEnabled);
		localStorage.setItem("sfx", sfxEnabled);
		localStorage.setItem("embed", embedEnabled);
		localStorage.setItem("language", selectedLanguage);
		// 🆕 уведомляем другие вкладки (включая rankings.html)
		window.dispatchEvent(new Event("languageChanged"));
		
		// Применяем resolution и язык (на стороне Python)
		if (bridge?.launcher_set_resolution) {
			bridge.launcher_set_resolution(selectedResolution);
		}
		if (bridge?.launcher_set_language) {
			bridge.launcher_set_language(selectedLanguage);
		}
	
		// Сохраняем в config.json
		if (bridge?.save_config) {
			bridge.save_config(
				selectedResolution,
				selectedLanguage,
				musicEnabled,
				sfxEnabled,
				embedEnabled
			);
		}
	
		// ✅ Применяем перевод для всего UI
		applyTranslations(selectedLanguage);
	
		// Обновляем панели
		loadHomePanel("news", "get_home_news", 0);
		loadHomePanel("changelogs", "get_home_changelogs", 1);
		loadHomePanel("events", "get_home_events", 2);
	
		// Закрываем окно настроек
		settingsDialog.style.display = "none";
	});

	cancelSettingsBtn.addEventListener("click", () => {
		settingsDialog.style.display = "none";
	});

    updateOnline();
    setInterval(updateOnline, 10000);
});
