// AGPL-3.0-only
//
// This is free software for the public good of a permacomputer
// hosted at permacomputer.com, an always-on computer by the people, for the
// people. One which is durable, easy to repair, and distributed like tap water
// for machine learning intelligence.
//
// The permacomputer is community-owned infrastructure optimized around
// four values:
//
//   TRUTH    - First principles, math & science, open source code
//   FREEDOM  - Voluntary partnerships, freedom from tyranny & corporate control
//   HARMONY  - Minimal waste, self-renewing systems with diverse connections
//   LOVE     - Be yourself without hurting others, cooperation through natural law
//
// This software contributes to that vision by making machine learning
// accessible to everyone through a free, open, embeddable chat interface.
// Code is seeds to sprout on any abandoned technology.
//
// Learn more: https://www.permacomputer.com
//
// NO WARRANTY. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND.
//
// Copyright 2025-2026 TimeHexOn & foxhop & russell@unturf
// https://www.permacomputer.com

// UI Translations for all supported languages
// This file contains all user interface text translations

// Import translations from individual language files
import { UI_TRANSLATIONS } from "./languages/index.js";
import { normalizeLanguageCode } from "./config.js";

// Export UI_TRANSLATIONS for use in other modules
export { UI_TRANSLATIONS };

// Get UI text in user's preferred language
export function getUIText(key, params = {}) {
	const lang = getUserLanguagePreference();
	const translations = UI_TRANSLATIONS[lang] || UI_TRANSLATIONS.en;
	let text = translations[key] || UI_TRANSLATIONS.en[key] || key;

	// Replace parameters like {lang} with actual values
	Object.entries(params).forEach(([param, value]) => {
		text = text.replace(`{${param}}`, value);
	});

	return text;
}

// Language preference management
// Priority: window.UNCLOSEAI_LANGUAGE (forced by embed) > localStorage > "en"
export function getUserLanguagePreference() {
	// Check for forced language from embed config first
	const rawEmbedLang = (typeof window !== "undefined" && window.UNCLOSEAI_LANGUAGE) ? window.UNCLOSEAI_LANGUAGE : null;
	if (rawEmbedLang) {
		const normalizedLang = normalizeLanguageCode(rawEmbedLang);
		if (normalizedLang) {
			return normalizedLang;
		}
	}

	// Fall back to vault, then default
	try {
		if (typeof window !== 'undefined' && window.UncloseVault && window.UncloseVault.isUnlocked()) {
			return window.UncloseVault.get("uncloseai_language", "en");
		}
		return "en";
	} catch (error) {
		console.warn("Failed to read language preference:", error);
		return "en";
	}
}

export function setUserLanguagePreference(langCode) {
	try {
		if (typeof window !== 'undefined' && window.UncloseVault && window.UncloseVault.isUnlocked()) {
			window.UncloseVault.set("uncloseai_language", langCode);
		} else {
			console.warn("Vault locked - language preference not persisted");
		}
		console.log("Language preference saved:", langCode);
		// Trigger UI refresh when language changes
		refreshUILanguage();
		// Also trigger the UI-specific refresh function if available
		if (typeof window !== "undefined" && window.refreshUILanguage) {
			window.refreshUILanguage();
		}
	} catch (error) {
		console.warn("Failed to save language preference:", error);
	}
}

// Dynamic UI refresh mechanism
export function refreshUILanguage() {
	if (typeof window === "undefined") return;

	try {
		// Update all elements with data-i18n attributes
		const elementsWithI18n = document.querySelectorAll("[data-i18n]");
		elementsWithI18n.forEach((element) => {
			const key = element.getAttribute("data-i18n");
			const params = element.getAttribute("data-i18n-params");
			
			let parsedParams = {};
			if (params) {
				try {
					parsedParams = JSON.parse(params);
				} catch (e) {
					console.warn("Failed to parse i18n params:", params);
				}
			}
			
			const translatedText = getUIText(key, parsedParams);
			
			// Handle different element types
			if (element.tagName === "INPUT" && element.type !== "submit") {
				if (element.hasAttribute("placeholder")) {
					element.placeholder = translatedText;
				} else {
					element.value = translatedText;
				}
			} else if (element.tagName === "INPUT" && element.type === "submit") {
				element.value = translatedText;
			} else {
				// For regular elements, check if they contain HTML
				if (translatedText.includes("<")) {
					element.innerHTML = translatedText;
				} else {
					element.textContent = translatedText;
				}
			}
		});

		// Update specific UI elements that might not have data-i18n attributes
		updateCommonUIElements();

		console.log("UI language refreshed successfully");
		
		// Dispatch custom event for other components to listen to
		window.dispatchEvent(new CustomEvent("languageChanged", {
			detail: { language: getUserLanguagePreference() }
		}));
		
	} catch (error) {
		console.warn("Failed to refresh UI language:", error);
	}
}

// Update common UI elements that might not have data-i18n attributes
function updateCommonUIElements() {
	const lang = getUserLanguagePreference();
	
	// Update button texts
	const buttons = {
		"button[onclick*='readPage']": "readPage",
		"button[onclick*='openTTSModal']": "ttsAnything", 
		"button[onclick*='translatePage']": "translate",
		"button[onclick*='smartTranslate']": "smartTranslate",
		"button[onclick*='uploadFile']": "uploadFile",
		"button[onclick*='refreshModels']": "refreshModels",
		"button[onclick*='clearChat']": "clearChat",
		"button[onclick*='downloadChat']": "downloadChat"
	};
	
	Object.entries(buttons).forEach(([selector, key]) => {
		const element = document.querySelector(selector);
		if (element) {
			element.textContent = getUIText(key);
		}
	});
	
	// Update modal titles
	const modals = document.querySelectorAll("dialog h2, .modal-title");
	modals.forEach((modal) => {
		if (modal.textContent.includes("AI Assistant") || modal.id === "ai-assistant-title") {
			modal.textContent = getUIText("aiAssistantTitle");
		} else if (modal.textContent.includes("Text-to-Speech") || modal.id === "tts-title") {
			modal.textContent = getUIText("ttsModalTitle");
		} else if (modal.textContent.includes("Translate") || modal.id === "translate-title") {
			modal.textContent = getUIText("translateModalTitle");
		}
	});
	
	// Update placeholders
	const placeholders = {
		"textarea[placeholder*='Type your message']": "typePlaceholder",
		"textarea[placeholder*='text-to-speech']": "ttsPlaceholder",
		"textarea[placeholder*='translate']": "translatePlaceholder"
	};
	
	Object.entries(placeholders).forEach(([selector, key]) => {
		const element = document.querySelector(selector);
		if (element) {
			element.placeholder = getUIText(key);
		}
	});
}

// Initialize UI refresh function on window object for backward compatibility
if (typeof window !== "undefined") {
	window.refreshUILanguage = refreshUILanguage;
}

// Translation function for UI text
export async function translateUIText(text, targetLang) {
	if (targetLang === "en" || !text) return text;

	try {
		const { translateText } = await import("./translation.js");
		const translated = await translateText(text, targetLang);
		return translated || text;
	} catch (error) {
		console.warn("UI translation failed:", error);
		return text;
	}
}
