/**
 * Nexora V6 Custom — navegación móvil, slider de clases, scroll reveal
 */
(function () {
	"use strict";

	function initLang() {
		var wrap = document.querySelector(".nex-lang");
		var btn = document.querySelector(".nex-lang-trigger");
		var menu = wrap ? wrap.querySelector(".nex-lang-menu") : null;
		if (!wrap || !btn || !menu) return;

		wrap.addEventListener("click", function (e) {
			e.stopPropagation();
		});

		btn.addEventListener("click", function (e) {
			e.stopPropagation();
			var open = wrap.classList.toggle("is-open");
			btn.setAttribute("aria-expanded", open ? "true" : "false");
		});

		document.addEventListener("click", function () {
			wrap.classList.remove("is-open");
			btn.setAttribute("aria-expanded", "false");
		});

		menu.querySelectorAll("a").forEach(function (a) {
			a.addEventListener("click", function () {
				wrap.classList.remove("is-open");
				btn.setAttribute("aria-expanded", "false");
			});
		});
	}

	function initNav() {
		var toggle = document.querySelector(".nex-nav-toggle");
		var drawer = document.getElementById("nex-nav-drawer");
		if (!toggle || !drawer) return;
		var mobileMedia = window.matchMedia ? window.matchMedia("(max-width: 960px)") : null;
		var lastFocused = null;

		function setOpen(open, restoreFocus) {
			toggle.setAttribute("aria-expanded", open ? "true" : "false");
			drawer.setAttribute("aria-hidden", open ? "false" : "true");
			if (open) {
				lastFocused = document.activeElement;
				drawer.removeAttribute("hidden");
				toggle.classList.add("is-open");
				document.body.classList.add("nex-nav-open");
				window.requestAnimationFrame(function () {
					var firstLink = drawer.querySelector("a[href]");
					if (firstLink) firstLink.focus();
				});
			} else {
				drawer.setAttribute("hidden", "hidden");
				toggle.classList.remove("is-open");
				document.body.classList.remove("nex-nav-open");
				if (restoreFocus && lastFocused && typeof lastFocused.focus === "function") {
					lastFocused.focus();
				}
				lastFocused = null;
			}
		}

		toggle.addEventListener("click", function () {
			var open = toggle.getAttribute("aria-expanded") === "true";
			setOpen(!open);
		});

		drawer.addEventListener("click", function (e) {
			if (!e.target.closest || !e.target.closest(".nex-nav-drawer-list")) {
				setOpen(false, true);
			}
		});

		drawer.querySelectorAll("a").forEach(function (a) {
			a.addEventListener("click", function () {
				setOpen(false);
			});
		});

		document.addEventListener("keydown", function (e) {
			if (e.key === "Escape" && toggle.getAttribute("aria-expanded") === "true") {
				setOpen(false, true);
				return;
			}

			if (e.key === "Tab" && toggle.getAttribute("aria-expanded") === "true") {
				var focusable = drawer.querySelectorAll("a[href], button:not([disabled]), [tabindex]:not([tabindex='-1'])");
				if (!focusable.length) return;
				var first = focusable[0];
				var last = focusable[focusable.length - 1];
				if (e.shiftKey && document.activeElement === first) {
					e.preventDefault();
					last.focus();
				} else if (!e.shiftKey && document.activeElement === last) {
					e.preventDefault();
					first.focus();
				}
			}
		});

		function closeOnDesktop(e) {
			if (!e.matches && toggle.getAttribute("aria-expanded") === "true") {
				setOpen(false);
			}
		}

		if (mobileMedia) {
			if (typeof mobileMedia.addEventListener === "function") {
				mobileMedia.addEventListener("change", closeOnDesktop);
			} else if (typeof mobileMedia.addListener === "function") {
				mobileMedia.addListener(closeOnDesktop);
			}
		}
	}

	function initCommerceMenu() {
		var menus = Array.prototype.slice.call(document.querySelectorAll(".nex-commerce-more"));
		if (!menus.length) return;

		menus.forEach(function (menu) {
			menu.addEventListener("toggle", function () {
				if (!menu.open) return;
				menus.forEach(function (other) {
					if (other !== menu) other.open = false;
				});
			});
		});

		document.addEventListener("click", function (e) {
			menus.forEach(function (menu) {
				if (menu.open && (!e.target.closest || !e.target.closest(".nex-commerce-more"))) {
					menu.open = false;
				}
			});
		});

		document.addEventListener("keydown", function (e) {
			if (e.key !== "Escape") return;
			menus.forEach(function (menu) {
				if (menu.open) {
					menu.open = false;
					var summary = menu.querySelector("summary");
					if (summary) summary.focus();
				}
			});
		});
	}

	function initReveal() {
		var els = document.querySelectorAll(".nex-reveal");
		if (!els.length || !("IntersectionObserver" in window)) {
			els.forEach(function (el) {
				el.classList.add("is-visible");
			});
			return;
		}
		var io = new IntersectionObserver(
			function (entries) {
				entries.forEach(function (en) {
					if (en.isIntersecting) {
						en.target.classList.add("is-visible");
						io.unobserve(en.target);
					}
				});
			},
			{ rootMargin: "0px 0px 140px 0px", threshold: 0.02 }
		);
		els.forEach(function (el) {
			io.observe(el);
		});
	}

	/**
	 * Feedback localizado para formularios de autenticacion.
	 * Mantiene el name/value del boton submit (no usa disabled) y bloquea
	 * reenvios rapidos en JavaScript sin cubrir la pagina con un overlay.
	 */
	function initFormProcessing() {
		document.querySelectorAll(".nex-auth-form").forEach(function (form) {
			var processing = false;
			var button = form.querySelector(".nex-auth-submit");
			var originalLabel = button ? button.textContent : "";
			var fallbackTimer = null;

			function reset() {
				processing = false;
				form.classList.remove("is-processing");
				form.removeAttribute("aria-busy");
				if (button) {
					button.classList.remove("is-processing");
					button.removeAttribute("aria-disabled");
					button.textContent = originalLabel;
				}
				if (fallbackTimer) {
					window.clearTimeout(fallbackTimer);
					fallbackTimer = null;
				}
			}

			form.addEventListener("submit", function (e) {
				if (processing) {
					e.preventDefault();
					return;
				}

				processing = true;
				form.classList.add("is-processing");
				form.setAttribute("aria-busy", "true");

				if (button) {
					var wrap = form.closest(".nex-auth");
					var label = "Procesando...";
					if (wrap && wrap.classList.contains("nex-auth--login")) label = "Ingresando...";
					if (wrap && wrap.classList.contains("nex-auth--register")) label = "Creando cuenta...";
					if (wrap && wrap.classList.contains("nex-auth--forgot")) label = "Enviando...";
					button.classList.add("is-processing");
					button.setAttribute("aria-disabled", "true");
					button.textContent = label;
				}

				// Si el navegador no abandona la pagina por un fallo de red,
				// permite reintentar sin dejar el formulario bloqueado para siempre.
				fallbackTimer = window.setTimeout(reset, 15000);
			});

			window.addEventListener("pageshow", function (event) {
				if (event.persisted) reset();
			});
		});
	}

	/**
	 * Evita doble clic rápido en CTAs con imagen (sidebar, hero, login nav).
	 * No sustituye protección real del servidor: la consola y herramientas tipo HTTrack
	 * descargan por HTTP y no pueden bloquearse de forma fiable desde el navegador.
	 */
	function initCtaClickCooldown() {
		var SEL =
			"a.nex-sidebar-banner,a.nex-hero-banner,a.nex-nav-img-btn,a[data-nex-click-once]";
		var COOLDOWN_MS = 900;
		var lastClick = new WeakMap();

		document.addEventListener(
			"click",
			function (e) {
				if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) {
					return;
				}
				var a = e.target.closest ? e.target.closest(SEL) : null;
				if (!a || a.tagName !== "A" || !a.getAttribute("href")) {
					return;
				}
				var now = Date.now();
				var prev = lastClick.get(a) || 0;
				if (prev > 0 && now - prev < COOLDOWN_MS) {
					e.preventDefault();
					e.stopImmediatePropagation();
					return;
				}
				lastClick.set(a, now);
			},
			true
		);
	}

	function isEditableFieldTarget(el) {
		if (!el) return false;
		var n = el.nodeName;
		if (n === "INPUT" || n === "TEXTAREA" || n === "SELECT") return true;
		if (el.isContentEditable) return true;
		return false;
	}

	/** True si la página corre en máquina local (WAMP/XAMPP, etc.): sin bloqueos de UI. */
	function isNexLocalDevHost() {
		try {
			var h = (window.location.hostname || "").toLowerCase();
			if (h === "" || h === "localhost") return true;
			if (h === "127.0.0.1" || h === "::1") return true;
			if (h.length > 10 && h.slice(-10) === ".localhost") return true;
			if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h)) return true;
			return false;
		} catch (err) {
			return false;
		}
	}

	/**
	 * Sin clic derecho + bloqueo de atajos típicos DevTools / código fuente.
	 * Solo fuera de localhost / loopback (en local no se registra nada).
	 */
	function initUiHardRestrictions() {
		if (isNexLocalDevHost()) return;

		document.addEventListener(
			"contextmenu",
			function (e) {
				if (isEditableFieldTarget(e.target)) return;
				e.preventDefault();
			},
			true
		);

		document.addEventListener(
			"keydown",
			function (e) {
				if (isEditableFieldTarget(e.target)) return;

				if (e.key === "F12") {
					e.preventDefault();
					return;
				}

				var kl = (e.key || "").toLowerCase();

				if (
					e.ctrlKey &&
					e.shiftKey &&
					(kl === "i" || kl === "j" || kl === "c" || kl === "k" || kl === "m")
				) {
					e.preventDefault();
					return;
				}

				if (e.ctrlKey && !e.shiftKey && !e.altKey && kl === "u") {
					e.preventDefault();
					return;
				}

				if (e.metaKey && e.altKey && (kl === "i" || kl === "j" || kl === "c" || kl === "u")) {
					e.preventDefault();
				}
			},
			true
		);
	}

	function initCountdown() {
		var roots = document.querySelectorAll("[data-nex-countdown]");
		if (!roots.length) return;

		function padNum(n) {
			n = parseInt(n, 10);
			return n < 10 ? "0" + n : String(n);
		}

		function cleanupHost(card) {
			if (!card) return;
			var host = card.closest("[data-nex-realm-modules]");
			if (!host) return;
			var visible = host.querySelector(".nex-realm-module:not([hidden])");
			if (!visible) host.setAttribute("hidden", "");
		}

		Array.prototype.forEach.call(roots, function (root) {
			if (root.getAttribute("data-nex-countdown-ready") === "1") return;
			root.setAttribute("data-nex-countdown-ready", "1");

			var card = root.closest(".nex-realm-module");
			var targetTs = parseInt(root.getAttribute("data-target"), 10);
			if (!targetTs || isNaN(targetTs)) return;

			var showD = root.getAttribute("data-d") === "1";
			var showH = root.getAttribute("data-h") === "1";
			var showM = root.getAttribute("data-m") === "1";
			var showS = root.getAttribute("data-s") === "1";
			var afterAction = root.getAttribute("data-after-action") || "status";
			var tid = null;
			var finished = false;

			function setUnit(unit, value) {
				var el = root.querySelector('[data-unit="' + unit + '"]');
				if (el) el.textContent = value;
			}

			function finish() {
				if (finished) return;
				finished = true;
				if (tid) clearInterval(tid);

				if (afterAction === "hide") {
					if (card) {
						card.setAttribute("hidden", "");
						card.setAttribute("aria-hidden", "true");
						cleanupHost(card);
					}
					return;
				}

				root.setAttribute("hidden", "");
				root.setAttribute("aria-hidden", "true");

				if (card) {
					var post = card.querySelector("[data-nex-post-state]");
					if (post) {
						post.removeAttribute("hidden");
						post.setAttribute("aria-hidden", "false");
						card.classList.add("is-post-state");
					}
				}

				try {
					document.dispatchEvent(new CustomEvent("nexora:countdown-finished", {
						detail: { realm: root.getAttribute("data-nex-countdown") || "" }
					}));
				} catch (err) {}
			}

			function tick() {
				var now = Math.floor(Date.now() / 1000);
				var left = targetTs - now;
				if (left <= 0) {
					setUnit("days", "0");
					setUnit("hours", "00");
					setUnit("minutes", "00");
					setUnit("seconds", "00");
					finish();
					return;
				}

				if (showD) setUnit("days", String(Math.floor(left / 86400)));
				if (showH) setUnit("hours", padNum(Math.floor((left % 86400) / 3600)));
				if (showM) setUnit("minutes", padNum(Math.floor((left % 3600) / 60)));
				if (showS) setUnit("seconds", padNum(left % 60));
			}

			tick();
			if (!finished) tid = setInterval(tick, 1000);
		});
	}

	function initIntentPrefetch() {
		if (!document.head || !("HTMLLinkElement" in window)) return;
		var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
		if (connection && (connection.saveData || /(?:^|-)2g$/i.test(connection.effectiveType || ""))) return;
		var seen = Object.create(null);
		var timer = null;
		var pending = null;
		var count = 0;
		var maxPrefetch = 4;

		function eligible(anchor) {
			if (!anchor || !anchor.href || count >= maxPrefetch) return null;
			if (!anchor.closest(".nex-topbar, .nex-nav-drawer, .nex-commerce-menu, .nex-commerce-more")) return null;
			var url;
			try { url = new URL(anchor.href, window.location.href); } catch (e) { return null; }
			if (url.origin !== window.location.origin) return null;
			if (url.pathname === window.location.pathname && url.search === window.location.search) return null;
			if (/\/(?:logout|language\/switch)(?:\/|$)/i.test(url.pathname)) return null;
			if (/\.(?:zip|rar|7z|exe|msi|pdf|jpg|jpeg|png|webp|gif|mp4|mp3)$/i.test(url.pathname)) return null;
			return url.href.split("#")[0];
		}

		function schedule(anchor) {
			var href = eligible(anchor);
			if (!href || seen[href]) return;
			pending = href;
			window.clearTimeout(timer);
			timer = window.setTimeout(function () {
				if (!pending || seen[pending] || count >= maxPrefetch) return;
				var link = document.createElement("link");
				link.rel = "prefetch";
				link.href = pending;
				document.head.appendChild(link);
				seen[pending] = true;
				count += 1;
				pending = null;
			}, 120);
		}

		document.addEventListener("mouseover", function (event) {
			var anchor = event.target.closest ? event.target.closest("a[href]") : null;
			if (anchor) schedule(anchor);
		}, { passive: true });
		document.addEventListener("focusin", function (event) {
			var anchor = event.target.closest ? event.target.closest("a[href]") : null;
			if (anchor) schedule(anchor);
		});
	}

	function initStreamerDock() {
		var dock = document.getElementById("nex-stream-dock");
		if (!dock) return;

		function elPanel(id) {
			return document.getElementById("nex-stream-panel-" + id);
		}

		function unmountPanel(panel) {
			if (!panel) return;
			var mount = panel.querySelector("[data-nex-stream-mount]");
			if (!mount) return;
			var iframe = mount.querySelector("iframe");
			if (iframe) {
				iframe.src = "about:blank";
				iframe.remove();
			}
			if (!mount.querySelector(".nex-stream-dock__loading")) {
				var loading = document.createElement("span");
				loading.className = "nex-stream-dock__loading";
				loading.textContent = "La transmisión se carga al abrir este panel.";
				mount.appendChild(loading);
			}
			panel.removeAttribute("data-stream-mounted");
		}

		function closeAll() {
			dock.querySelectorAll(".nex-stream-dock__panel.is-open").forEach(function (p) {
				p.classList.remove("is-open");
				p.setAttribute("aria-hidden", "true");
				unmountPanel(p);
			});
			dock.querySelectorAll(".nex-stream-dock__btn[aria-expanded]").forEach(function (b) {
				b.setAttribute("aria-expanded", "false");
			});
		}

		function mountPanel(panel) {
			if (!panel || panel.getAttribute("data-stream-mounted") === "1") return;
			var mount = panel.querySelector("[data-nex-stream-mount]");
			if (!mount) return;
			var src = mount.getAttribute("data-stream-src") || "";
			if (!/^https:\/\//i.test(src)) return;

			panel.setAttribute("data-stream-mounted", "1");
			var iframe = document.createElement("iframe");
			iframe.title = mount.getAttribute("data-stream-title") || "Transmisión Nexora";
			iframe.loading = "lazy";
			iframe.referrerPolicy = "strict-origin-when-cross-origin";
			iframe.setAttribute("allowfullscreen", "");
			iframe.setAttribute("allow", "autoplay; fullscreen; picture-in-picture");
			iframe.addEventListener("load", function () {
				var loading = mount.querySelector(".nex-stream-dock__loading");
				if (loading) loading.remove();
			}, { once: true });
			mount.appendChild(iframe);
			iframe.src = src;
		}

		function openPanel(id) {
			var p = elPanel(id);
			if (!p) return;
			closeAll();
			mountPanel(p);
			p.classList.add("is-open");
			p.setAttribute("aria-hidden", "false");
			var btn = dock.querySelector('[data-nex-stream-panel="' + id + '"]');
			if (btn) btn.setAttribute("aria-expanded", "true");
		}

		function togglePanel(id) {
			var p = elPanel(id);
			if (!p) return;
			if (p.classList.contains("is-open")) {
				p.classList.remove("is-open");
				p.setAttribute("aria-hidden", "true");
				unmountPanel(p);
				var bt = dock.querySelector('[data-nex-stream-panel="' + id + '"]');
				if (bt) bt.setAttribute("aria-expanded", "false");
			} else {
				openPanel(id);
			}
		}

		dock.addEventListener("click", function (e) {
			var openBtn = e.target.closest("[data-nex-stream-panel]");
			var closeBtn = e.target.closest("[data-nex-stream-close]");
			if (openBtn && openBtn.getAttribute("data-nex-stream-panel")) {
				e.preventDefault();
				togglePanel(openBtn.getAttribute("data-nex-stream-panel"));
				return;
			}
			if (closeBtn && closeBtn.getAttribute("data-nex-stream-close")) {
				e.preventDefault();
				var pid = closeBtn.getAttribute("data-nex-stream-close");
				var pan = elPanel(pid);
				if (pan) {
					pan.classList.remove("is-open");
					pan.setAttribute("aria-hidden", "true");
					unmountPanel(pan);
				}
				var b2 = dock.querySelector('[data-nex-stream-panel="' + pid + '"]');
				if (b2) b2.setAttribute("aria-expanded", "false");
			}
		});

		document.addEventListener("keydown", function (e) {
			if (e.key !== "Escape") return;
			if (!dock.querySelector(".nex-stream-dock__panel.is-open")) return;
			closeAll();
		});
	}


	function initHomeStartPosition() {
		if (!document.body || !document.body.classList.contains("nex-body--home")) return;
		if (window.location.hash && window.location.hash !== "#") return;

		try {
			if ("scrollRestoration" in window.history) {
				window.history.scrollRestoration = "manual";
			}
		} catch (e) {}

		function goTop() {
			try { window.scrollTo(0, 0); } catch (e) {}
		}

		goTop();
		if (window.requestAnimationFrame) {
			window.requestAnimationFrame(goTop);
		}
		window.addEventListener("load", goTop, { once: true });
		window.addEventListener("pageshow", function (event) {
			if (event && event.persisted) goTop();
		});
	}


	function initContentHub() {
		var hub = document.querySelector("[data-nex-content-hub]");
		if (!hub) return;

		var mainEl = hub.querySelector(".nex-content-swiper");
		var tabs = Array.prototype.slice.call(hub.querySelectorAll("[data-nex-content-tab]"));
		var lightbox = hub.querySelector("[data-nex-content-lightbox]");
		var activeLightboxCard = null;

		function getPages(card) {
			if (!card) return [];
			if (!card._nexPages) {
				try { card._nexPages = JSON.parse(card.getAttribute("data-pages") || "[]"); }
				catch (e) { card._nexPages = []; }
			}
			return card._nexPages;
		}

		function getCaptions(card) {
			if (!card) return [];
			if (!card._nexCaptions) {
				try { card._nexCaptions = JSON.parse(card.getAttribute("data-captions") || "[]"); }
				catch (e) { card._nexCaptions = []; }
			}
			return card._nexCaptions;
		}

		function normalizePage(card, index) {
			var pages = getPages(card);
			if (!pages.length) return 0;
			index = parseInt(index, 10) || 0;
			if (index < 0) index = pages.length - 1;
			if (index >= pages.length) index = 0;
			return index;
		}

		function setCardPage(card, index) {
			if (!card) return;
			var pages = getPages(card);
			var captions = getCaptions(card);
			if (!pages.length) return;
			index = normalizePage(card, index);
			card.setAttribute("data-page-index", String(index));

			var img = card.querySelector(".nex-content-card__image");
			if (img && pages[index]) {
				var nextSrc = pages[index];
				if (img.getAttribute("src") !== nextSrc) {
					img.classList.add("is-loading");
					img.onload = function () { img.classList.remove("is-loading"); };
					img.onerror = function () { img.classList.remove("is-loading"); };
					img.setAttribute("src", nextSrc);
				}
			}

			card.querySelectorAll("[data-nex-page-current]").forEach(function (el) { el.textContent = String(index + 1); });
			card.querySelectorAll("[data-nex-page-current-label]").forEach(function (el) { el.textContent = String(index + 1); });
			var captionEl = card.querySelector("[data-nex-page-caption]");
			if (captionEl) captionEl.textContent = captions[index] || "";
			card.querySelectorAll("[data-nex-page-dot]").forEach(function (dot) {
				dot.classList.toggle("is-active", parseInt(dot.getAttribute("data-nex-page-dot"), 10) === index);
			});

			if (pages.length > 1) {
				var preloadIndex = index + 1 < pages.length ? index + 1 : 0;
				window.setTimeout(function () {
					var pre = new Image();
					pre.src = pages[preloadIndex];
				}, 150);
			}
		}

		function currentCard() {
			if (!mainEl) return null;
			var activeSlide = mainEl.querySelector(".swiper-slide-active");
			return activeSlide ? activeSlide.querySelector("[data-nex-content-card]") : mainEl.querySelector("[data-nex-content-card]");
		}

		function updateTabs(index, shouldScroll) {
			tabs.forEach(function (tab, i) {
				var active = i === index;
				tab.classList.toggle("is-active", active);
				tab.setAttribute("aria-selected", active ? "true" : "false");
				// Solo desplazar la tira de tabs cuando el jugador interactua con el Content Hub.
				// En la carga inicial nunca debe mover el viewport principal.
				if (shouldScroll && active && typeof tab.scrollIntoView === "function") {
					try { tab.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center" }); } catch (e) {}
				}
			});
		}

		function syncLightbox(card) {
			if (!lightbox || !card) return;
			var pages = getPages(card);
			var captions = getCaptions(card);
			if (!pages.length) return;
			var index = normalizePage(card, card.getAttribute("data-page-index"));
			var lbImg = lightbox.querySelector("[data-nex-lightbox-image]");
			var lbCurrent = lightbox.querySelector("[data-nex-lightbox-current]");
			var lbTotal = lightbox.querySelector("[data-nex-lightbox-total]");
			var lbCaption = lightbox.querySelector("[data-nex-lightbox-caption]");
			var lbTitle = lightbox.querySelector("[data-nex-lightbox-title]");
			var lbCategory = lightbox.querySelector("[data-nex-lightbox-category]");
			var title = card.querySelector(".nex-content-card__info h3");
			var category = card.querySelector(".nex-content-card__category");
			if (lbImg) lbImg.src = pages[index];
			if (lbCurrent) lbCurrent.textContent = String(index + 1);
			if (lbTotal) lbTotal.textContent = String(pages.length);
			if (lbCaption) lbCaption.textContent = captions[index] || "";
			if (lbTitle) lbTitle.textContent = title ? title.textContent : "Contenido Nexora";
			if (lbCategory) lbCategory.textContent = category ? category.textContent : "Contenido Nexora";
			lightbox.querySelectorAll("[data-nex-lightbox-prev], [data-nex-lightbox-next]").forEach(function (button) {
				button.style.display = pages.length > 1 ? "block" : "none";
			});
		}

		function openLightbox(card) {
			if (!lightbox || !card) return;
			activeLightboxCard = card;
			syncLightbox(card);
			lightbox.classList.add("is-open");
			lightbox.setAttribute("aria-hidden", "false");
			document.body.classList.add("nex-content-lightbox-open");
			var close = lightbox.querySelector(".nex-content-lightbox__close");
			if (close) close.focus();
		}

		function closeLightbox() {
			if (!lightbox) return;
			lightbox.classList.remove("is-open");
			lightbox.setAttribute("aria-hidden", "true");
			document.body.classList.remove("nex-content-lightbox-open");
			activeLightboxCard = null;
		}

		var contentSwiper = null;
		if (mainEl && typeof Swiper !== "undefined") {
			contentSwiper = new Swiper(mainEl, {
				effect: "fade",
				fadeEffect: { crossFade: true },
				speed: 420,
				rewind: true,
				autoHeight: true,
				allowTouchMove: true,
				navigation: {
					prevEl: hub.querySelector(".nex-content-guide-prev"),
					nextEl: hub.querySelector(".nex-content-guide-next")
				}
			});
			contentSwiper.on("slideChange", function () {
				updateTabs(contentSwiper.activeIndex, true);
				var card = currentCard();
				if (card) setCardPage(card, card.getAttribute("data-page-index") || 0);
			});
		}

		tabs.forEach(function (tab) {
			tab.addEventListener("click", function () {
				var index = parseInt(tab.getAttribute("data-nex-content-tab"), 10) || 0;
				if (contentSwiper) contentSwiper.slideTo(index);
				else updateTabs(index, true);
			});
		});

		hub.addEventListener("click", function (e) {
			var dot = e.target.closest ? e.target.closest("[data-nex-page-dot]") : null;
			if (dot) {
				var dotCard = dot.closest("[data-nex-content-card]");
				setCardPage(dotCard, dot.getAttribute("data-nex-page-dot"));
				return;
			}

			var prev = e.target.closest ? e.target.closest("[data-nex-page-prev]") : null;
			if (prev) {
				var prevCard = prev.closest("[data-nex-content-card]");
				setCardPage(prevCard, (parseInt(prevCard.getAttribute("data-page-index"), 10) || 0) - 1);
				return;
			}

			var next = e.target.closest ? e.target.closest("[data-nex-page-next]") : null;
			if (next) {
				var nextCard = next.closest("[data-nex-content-card]");
				setCardPage(nextCard, (parseInt(nextCard.getAttribute("data-page-index"), 10) || 0) + 1);
				return;
			}

			var open = e.target.closest ? e.target.closest("[data-nex-content-open]") : null;
			if (open) {
				openLightbox(open.closest("[data-nex-content-card]"));
				return;
			}

			var close = e.target.closest ? e.target.closest("[data-nex-lightbox-close]") : null;
			if (close) {
				closeLightbox();
				return;
			}

			var lbPrev = e.target.closest ? e.target.closest("[data-nex-lightbox-prev]") : null;
			if (lbPrev && activeLightboxCard) {
				setCardPage(activeLightboxCard, (parseInt(activeLightboxCard.getAttribute("data-page-index"), 10) || 0) - 1);
				syncLightbox(activeLightboxCard);
				return;
			}

			var lbNext = e.target.closest ? e.target.closest("[data-nex-lightbox-next]") : null;
			if (lbNext && activeLightboxCard) {
				setCardPage(activeLightboxCard, (parseInt(activeLightboxCard.getAttribute("data-page-index"), 10) || 0) + 1);
				syncLightbox(activeLightboxCard);
			}
		});

		document.addEventListener("keydown", function (e) {
			if (!lightbox || !lightbox.classList.contains("is-open")) return;
			if (e.key === "Escape") {
				closeLightbox();
				return;
			}
			if (!activeLightboxCard) return;
			if (e.key === "ArrowLeft") {
				setCardPage(activeLightboxCard, (parseInt(activeLightboxCard.getAttribute("data-page-index"), 10) || 0) - 1);
				syncLightbox(activeLightboxCard);
			}
			if (e.key === "ArrowRight") {
				setCardPage(activeLightboxCard, (parseInt(activeLightboxCard.getAttribute("data-page-index"), 10) || 0) + 1);
				syncLightbox(activeLightboxCard);
			}
		});

		var firstCard = mainEl ? mainEl.querySelector("[data-nex-content-card]") : null;
		if (firstCard) setCardPage(firstCard, 0);
		updateTabs(0, false);
	}

	var swiperLoader = null;
	function ensureSwiper(callback) {
		if (typeof window.Swiper !== "undefined") { callback(); return; }
		if (!swiperLoader) {
			swiperLoader = new Promise(function (resolve, reject) {
				if (!document.querySelector('link[data-nex-swiper-css]')) {
					var css = document.createElement("link");
					css.rel = "stylesheet";
					css.href = "https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css";
					css.setAttribute("data-nex-swiper-css", "1");
					document.head.appendChild(css);
				}
				var script = document.createElement("script");
				script.src = "https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js";
				script.async = true;
				script.onload = resolve;
				script.onerror = reject;
				document.head.appendChild(script);
			});
		}
		swiperLoader.then(function () { if (typeof window.Swiper !== "undefined") callback(); }).catch(function () {});
	}

	function initWhenNear(selector, callback, margin) {
		var element = document.querySelector(selector);
		if (!element) return;
		if (!("IntersectionObserver" in window)) { callback(); return; }
		var observer = new IntersectionObserver(function (entries) {
			entries.forEach(function (entry) {
				if (!entry.isIntersecting) return;
				observer.disconnect();
				callback();
			});
		}, { rootMargin: margin || "450px 0px", threshold: 0.01 });
		observer.observe(element);
	}

	function initDeferredHomeWidgets() {
		initWhenNear("[data-nex-content-hub]", function () { ensureSwiper(initContentHub); }, "650px 0px");
		initWhenNear(".nex-char-swiper", function () { ensureSwiper(initCharSwiper); }, "500px 0px");
	}

	function initCharSwiper() {
		var elMain = document.querySelector(".nex-char-swiper");
		var elThumb = document.querySelector(".nex-thumb-swiper");
		if (!elMain || !elThumb || typeof Swiper === "undefined") return;

		var thumbs = new Swiper(elThumb, {
			spaceBetween: 10,
			slidesPerView: "auto",
			centeredSlides: true,
			freeMode: false,
			watchSlidesProgress: true,
			slideToClickedSlide: true,
			breakpoints: {
				0: { spaceBetween: 8 },
				480: { spaceBetween: 12 },
			},
		});

		new Swiper(elMain, {
			effect: "fade",
			fadeEffect: { crossFade: true },
			speed: 550,
			rewind: true,
			autoplay: {
				delay: 5200,
				disableOnInteraction: false,
				pauseOnMouseEnter: true,
			},
			thumbs: { swiper: thumbs },
			navigation: {
				prevEl: ".nex-char-prev",
				nextEl: ".nex-char-next",
			},
		});
	}

	if (document.readyState === "loading") {
		document.addEventListener("DOMContentLoaded", function () {
			initFormProcessing();
			initLang();
			initNav();
			initCommerceMenu();
			initIntentPrefetch();
			initReveal();
			initCtaClickCooldown();
			initUiHardRestrictions();
			initCountdown();
			initStreamerDock();
			initHomeStartPosition();
			initDeferredHomeWidgets();
		});
	} else {
		initFormProcessing();
		initLang();
		initNav();
		initCommerceMenu();
		initIntentPrefetch();
		initReveal();
		initCtaClickCooldown();
		initUiHardRestrictions();
		initCountdown();
		initStreamerDock();
		initHomeStartPosition();
		initDeferredHomeWidgets();
	}
})();
