(function () {
	"use strict";

	const default_lang = "es";
	const language = localStorage.getItem("language");

	function initLanguage() {
		const saved = localStorage.getItem("language") || default_lang;
		setLanguage(saved, false); // solo actualiza bandera y lang
		document.querySelectorAll('.language').forEach(a => {
			a.addEventListener('click', () => setLanguage(a.dataset.lang, true));
		});
	}

	function setLanguage(lang, redirect = true) {
		const already = document.documentElement.lang === lang;

		// Actualiza <html lang> y bandera
		document.documentElement.lang = lang;
		document.getElementById("header-lang-img").src =
			lang === "en" ? "/assets/images/flags/gb.svg"
				: "/assets/images/flags/spain.svg";
		localStorage.setItem("language", lang);

		// Redirige si cambia el idioma
		if (!already && redirect) {
			const url = new URL(location.href);
			url.searchParams.set("lang", lang);
			location.href = url.toString();
		}
	}

	// Llama al inicializador de idioma en cuanto el DOM esté listo
	document.addEventListener("DOMContentLoaded", function () {
		initLanguage();
	});
})();
