/**
 * MQTVSTREAM – interacciones del tema.
 * Sin dependencias (hls.js se carga solo si la transmisión es .m3u8).
 */
(function () {
	'use strict';

	var D = window.MQTV || {};
	var TZ = D.timezone || 'America/Argentina/Buenos_Aires';

	function $(sel, ctx) { return (ctx || document).querySelector(sel); }
	function $$(sel, ctx) { return Array.prototype.slice.call((ctx || document).querySelectorAll(sel)); }
	function el(tag, cls, text) {
		var n = document.createElement(tag);
		if (cls) { n.className = cls; }
		if (text != null) { n.textContent = text; }
		return n;
	}
	function store(key, val) {
		try {
			if (val === undefined) { return window.localStorage.getItem(key); }
			window.localStorage.setItem(key, val);
		} catch (e) { /* almacenamiento no disponible */ }
		return null;
	}
	function cap(s) { return s ? s.charAt(0).toUpperCase() + s.slice(1) : s; }
	function isHttp(u) { return /^https?:\/\//i.test(u || ''); }

	/* ---------------------------------------------------------------------
	 * Menú móvil y búsqueda
	 * ------------------------------------------------------------------- */
	function initHeader() {
		var header = $('.site-header');
		if (!header) { return; }
		var navBtn = $('.nav-toggle', header);
		var nav = $('#site-nav');
		if (navBtn && nav) {
			navBtn.addEventListener('click', function () {
				var open = header.classList.toggle('nav-open');
				navBtn.setAttribute('aria-expanded', open ? 'true' : 'false');
			});
			nav.addEventListener('click', function (e) {
				if (e.target.closest('a')) {
					header.classList.remove('nav-open');
					navBtn.setAttribute('aria-expanded', 'false');
				}
			});
		}
		var sBtn = $('.search-toggle', header);
		var sBox = $('#header-search');
		if (sBtn && sBox) {
			sBtn.addEventListener('click', function () {
				var willOpen = sBox.hidden;
				sBox.hidden = !willOpen;
				sBtn.setAttribute('aria-expanded', willOpen ? 'true' : 'false');
				if (willOpen) {
					var inp = $('input[type="search"]', sBox);
					if (inp) { inp.focus(); }
				}
			});
		}
		document.addEventListener('keydown', function (e) {
			if (e.key !== 'Escape') { return; }
			if (header.classList.contains('nav-open') && navBtn) {
				header.classList.remove('nav-open');
				navBtn.setAttribute('aria-expanded', 'false');
				navBtn.focus();
			}
			if (sBox && !sBox.hidden && sBtn) {
				sBox.hidden = true;
				sBtn.setAttribute('aria-expanded', 'false');
				sBtn.focus();
			}
		});
	}

	/* ---------------------------------------------------------------------
	 * Reloj (hora de Argentina + hora del visitante si es distinta)
	 * ------------------------------------------------------------------- */
	function initClock() {
		var box = $('#clock-time');
		if (!box) { return; }
		var dateEl = $('#clock-date');
		var localEl = $('#clock-local');

		var fmtTime, fmtDate, fmtLocal;
		try {
			fmtTime = new Intl.DateTimeFormat('es-AR', { timeZone: TZ, hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' });
			fmtDate = new Intl.DateTimeFormat('es-AR', { timeZone: TZ, weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
			fmtLocal = new Intl.DateTimeFormat('es-AR', { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
		} catch (e) { return; }

		box.textContent = '';
		var main = document.createTextNode('--:--');
		var sec = el('span', 'clock-sec', ':--');
		box.appendChild(main);
		box.appendChild(sec);

		var lastDate = '';

		function tick() {
			var now = new Date();
			var parts = {};
			fmtTime.formatToParts(now).forEach(function (p) { parts[p.type] = p.value; });
			var hm = parts.hour + ':' + parts.minute;
			main.nodeValue = hm;
			sec.textContent = ':' + parts.second;

			var d = fmtDate.format(now);
			if (d !== lastDate && dateEl) {
				dateEl.textContent = cap(d);
				lastDate = d;
			}
			if (localEl) {
				var lt = fmtLocal.format(now);
				if (lt !== hm) {
					localEl.hidden = false;
					localEl.textContent = 'Tu hora: ' + lt;
				} else {
					localEl.hidden = true;
				}
			}
			window.setTimeout(tick, 1000 - (Date.now() % 1000) + 5);
		}
		tick();
	}

	/* ---------------------------------------------------------------------
	 * Pronóstico a 7 días (Open-Meteo)
	 * ------------------------------------------------------------------- */
	var WMO = {
		0: ['☀️', 'Despejado'], 1: ['🌤️', 'Mayormente despejado'], 2: ['⛅', 'Parcialmente nublado'], 3: ['☁️', 'Nublado'],
		45: ['🌫️', 'Niebla'], 48: ['🌫️', 'Niebla con escarcha'],
		51: ['🌦️', 'Llovizna leve'], 53: ['🌦️', 'Llovizna'], 55: ['🌧️', 'Llovizna intensa'], 56: ['🌧️', 'Llovizna helada'], 57: ['🌧️', 'Llovizna helada'],
		61: ['🌧️', 'Lluvia leve'], 63: ['🌧️', 'Lluvia'], 65: ['🌧️', 'Lluvia fuerte'], 66: ['🌧️', 'Lluvia helada'], 67: ['🌧️', 'Lluvia helada'],
		71: ['🌨️', 'Nevada leve'], 73: ['🌨️', 'Nevada'], 75: ['❄️', 'Nevada fuerte'], 77: ['🌨️', 'Granizo fino'],
		80: ['🌦️', 'Chubascos leves'], 81: ['🌧️', 'Chubascos'], 82: ['⛈️', 'Chubascos fuertes'], 85: ['🌨️', 'Chubascos de nieve'], 86: ['❄️', 'Chubascos de nieve'],
		95: ['⛈️', 'Tormenta'], 96: ['⛈️', 'Tormenta con granizo'], 99: ['⛈️', 'Tormenta fuerte con granizo']
	};
	function wmo(code) { return WMO[code] || ['🌡️', 'Sin datos']; }

	function initWeather() {
		var list = $('#forecast');
		var select = $('#city-select');
		if (!list || !select) { return; }
		var cities = D.cities || [];
		if (!cities.length) { return; }

		cities.forEach(function (c) {
			var o = el('option', '', c.name);
			o.value = c.id;
			select.appendChild(o);
		});

		var saved = store('mqtv_city');
		var current = cities.filter(function (c) { return c.id === saved; })[0] ||
			cities.filter(function (c) { return c.id === D.cityDefault; })[0] || cities[0];
		select.value = current.id;

		select.addEventListener('change', function () {
			current = cities.filter(function (c) { return c.id === select.value; })[0] || current;
			store('mqtv_city', current.id);
			load();
		});

		function fail() {
			$('#now-ico').textContent = '🌡️';
			$('#now-temp').textContent = '--°';
			$('#now-desc').textContent = 'Sin datos del clima';
			$('#now-extra').textContent = '';
			list.textContent = '';
			var li = el('li', 'news-error');
			li.style.gridColumn = 'auto';
			li.appendChild(document.createTextNode('No pudimos cargar el pronóstico. '));
			var b = el('button', 'btn-primary', 'Reintentar');
			b.type = 'button';
			b.addEventListener('click', load);
			li.appendChild(b);
			list.appendChild(li);
		}

		function render(data) {
			var cur = data.current || {};
			var daily = data.daily || {};
			var days = daily.time || [];
			if (!days.length) { fail(); return; }

			var w = wmo(cur.weather_code);
			$('#now-ico').textContent = w[0];
			$('#now-temp').textContent = Math.round(cur.temperature_2m) + '°';
			$('#now-desc').textContent = w[1];
			var extra = [];
			if (cur.relative_humidity_2m != null) { extra.push('Humedad ' + Math.round(cur.relative_humidity_2m) + '%'); }
			if (cur.wind_speed_10m != null) { extra.push('Viento ' + Math.round(cur.wind_speed_10m) + ' km/h'); }
			$('#now-extra').textContent = extra.join(' · ');

			var mins = daily.temperature_2m_min, maxs = daily.temperature_2m_max;
			var gmin = Math.min.apply(null, mins), gmax = Math.max.apply(null, maxs);
			var range = (gmax - gmin) || 1;

			list.textContent = '';
			days.forEach(function (d, i) {
				var li = el('li', 'fc-row' + (i === 0 ? ' is-today' : ''));
				var label;
				if (i === 0) { label = 'Hoy'; }
				else if (i === 1) { label = 'Mañana'; }
				else {
					label = new Date(d + 'T12:00:00Z').toLocaleDateString('es-AR', { weekday: 'short', timeZone: 'UTC' }).replace('.', '');
				}
				var wi = wmo(daily.weather_code[i]);

				var day = el('span', 'fc-day', label);
				var ico = el('span', 'fc-ico', wi[0]);
				ico.title = wi[1];
				var bar = el('span', 'fc-bar');
				var fill = el('i');
				fill.style.setProperty('--l', ((mins[i] - gmin) / range * 100).toFixed(1) + '%');
				fill.style.setProperty('--w', ((maxs[i] - mins[i]) / range * 100).toFixed(1) + '%');
				bar.appendChild(fill);
				var temps = el('span', 'fc-temps');
				temps.appendChild(el('span', '', Math.round(mins[i]) + '° '));
				temps.appendChild(el('b', '', Math.round(maxs[i]) + '°'));
				var p = daily.precipitation_probability_max ? daily.precipitation_probability_max[i] : null;
				var rain = el('span', 'fc-rain' + (p >= 60 ? ' rain-2' : (p >= 30 ? ' rain-1' : '')), p == null ? '–' : '💧' + p + '%');
				rain.title = 'Probabilidad de lluvia';

				[day, ico, bar, temps, rain].forEach(function (n) { li.appendChild(n); });
				list.appendChild(li);
			});
		}

		function load() {
			var key = 'mqtv_wx_' + current.id;
			try {
				var raw = window.sessionStorage.getItem(key);
				if (raw) {
					var c = JSON.parse(raw);
					if (Date.now() - c.t < 30 * 60 * 1000) { render(c.d); return; }
				}
			} catch (e) { /* sin caché */ }

			var url = 'https://api.open-meteo.com/v1/forecast?latitude=' + current.lat + '&longitude=' + current.lon +
				'&current=temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m' +
				'&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max' +
				'&forecast_days=7&timezone=' + encodeURIComponent(TZ);

			fetch(url)
				.then(function (r) { if (!r.ok) { throw new Error('HTTP ' + r.status); } return r.json(); })
				.then(function (data) {
					try { window.sessionStorage.setItem(key, JSON.stringify({ t: Date.now(), d: data })); } catch (e) { /* ok */ }
					render(data);
				})
				.catch(fail);
		}
		load();
	}

	/* ---------------------------------------------------------------------
	 * Noticias RSS + titulares
	 * ------------------------------------------------------------------- */
	var PALETTE = ['#0A3FB5', '#0A8F1A', '#2F76B8', '#C8282B', '#9A6100', '#6B3FB5'];
	var colorMap = {}, colorIdx = 0;
	function colorFor(name) {
		if (!colorMap[name]) { colorMap[name] = PALETTE[colorIdx++ % PALETTE.length]; }
		return colorMap[name];
	}

	function timeAgo(ts) {
		if (!ts || ts < 100000) { return ''; }
		var s = Math.max(0, Math.floor(Date.now() / 1000 - ts));
		if (s < 90) { return 'Hace instantes'; }
		var m = Math.floor(s / 60);
		if (m < 60) { return 'Hace ' + m + ' min'; }
		var h = Math.floor(m / 60);
		if (h < 24) { return 'Hace ' + h + ' h'; }
		var d = Math.floor(h / 24);
		if (d < 7) { return 'Hace ' + d + (d === 1 ? ' día' : ' días'); }
		return new Date(ts * 1000).toLocaleDateString('es-AR', { day: 'numeric', month: 'short' });
	}

	function newsCard(it) {
		var color = colorFor(it.source);
		var card = el('article', 'news-card');
		card.style.setProperty('--c', color);

		var a = el('a', 'news-link');
		a.href = it.link;
		a.target = '_blank';
		a.rel = 'noopener noreferrer';

		var imgBox = el('div', 'news-img');
		function placeholder() {
			imgBox.textContent = '';
			imgBox.appendChild(el('div', 'news-ph', (it.source || '?').charAt(0)));
		}
		if (isHttp(it.image)) {
			var im = new Image();
			im.alt = '';
			im.loading = 'lazy';
			im.decoding = 'async';
			im.referrerPolicy = 'no-referrer';
			im.onerror = placeholder;
			im.src = it.image;
			imgBox.appendChild(im);
		} else {
			placeholder();
		}

		var body = el('div', 'news-body');
		body.appendChild(el('span', 'src-pill', it.source));
		body.appendChild(el('h3', '', it.title));
		body.appendChild(el('p', 'news-meta', timeAgo(it.ts)));

		a.appendChild(imgBox);
		a.appendChild(body);
		card.appendChild(a);
		return card;
	}

	function renderNews(scope, items) {
		var grid = $('#news-' + scope);
		if (!grid) { return; }
		grid.textContent = '';
		items = (items || []).filter(function (it) { return isHttp(it.link); });
		if (!items.length) {
			grid.appendChild(el('p', 'news-error', 'Por ahora no pudimos traer noticias de esta sección. Probá de nuevo en unos minutos.'));
			return;
		}
		items.forEach(function (it) { grid.appendChild(newsCard(it)); });
	}

	function buildTicker(all) {
		var box = $('#ticker');
		var track = $('#ticker-track');
		if (!box || !track || !all.length) { return; }
		track.textContent = '';
		all.forEach(function (it) {
			var a = el('a', 'ticker-item');
			a.href = it.link;
			a.target = '_blank';
			a.rel = 'noopener noreferrer';
			a.appendChild(el('b', '', it.source));
			a.appendChild(el('span', '', it.title));
			track.appendChild(a);
		});
		// Se duplica el contenido para que el bucle sea continuo.
		$$('.ticker-item', track).forEach(function (n) {
			var c = n.cloneNode(true);
			c.setAttribute('aria-hidden', 'true');
			c.tabIndex = -1;
			track.appendChild(c);
		});
		box.hidden = false;
		window.requestAnimationFrame(function () {
			var half = track.scrollWidth / 2;
			track.style.setProperty('--ticker-time', Math.max(40, Math.round(half / 70)) + 's');
		});
	}

	function initNews() {
		var tabs = $$('.tab');
		if (!tabs.length || !D.newsEndpoint) { return; }

		function setTab(scope, focus) {
			tabs.forEach(function (t) {
				var on = t.getAttribute('data-scope') === scope;
				t.setAttribute('aria-selected', on ? 'true' : 'false');
				t.tabIndex = on ? 0 : -1;
				if (on && focus) { t.focus(); }
				var panel = $('#' + t.getAttribute('aria-controls'));
				if (panel) { panel.hidden = !on; }
			});
		}
		tabs.forEach(function (t, i) {
			t.addEventListener('click', function () { setTab(t.getAttribute('data-scope')); });
			t.addEventListener('keydown', function (e) {
				var k = e.key, n = null;
				if (k === 'ArrowRight') { n = tabs[(i + 1) % tabs.length]; }
				if (k === 'ArrowLeft') { n = tabs[(i - 1 + tabs.length) % tabs.length]; }
				if (n) { e.preventDefault(); setTab(n.getAttribute('data-scope'), true); }
			});
		});

		function get(scope) {
			var sep = D.newsEndpoint.indexOf('?') > -1 ? '&' : '?';
			return fetch(D.newsEndpoint + sep + 'scope=' + scope)
				.then(function (r) { if (!r.ok) { throw new Error('HTTP ' + r.status); } return r.json(); })
				.then(function (j) { return (j && j.items) || []; })
				.catch(function () { return []; });
		}

		var results = {};
		function done() {
			if (!results.nacional || !results.internacional) { return; }
			var mix = results.nacional.slice(0, 10).concat(results.internacional.slice(0, 6));
			mix = mix.filter(function (it) { return isHttp(it.link); });
			buildTicker(mix);
		}
		['nacional', 'internacional'].forEach(function (scope) {
			get(scope).then(function (items) {
				results[scope] = items;
				renderNews(scope, items);
				done();
			});
		});
	}

	/* ---------------------------------------------------------------------
	 * Tapas de los diarios (tarjetas con nombre + enlace, sin imagen)
	 *
	 * No se muestra la foto de la tapa: cada tarjeta tiene el nombre del
	 * diario sobre un fondo de color y enlaza directo a su sitio. Así no
	 * depende de ningún servicio externo que arme o sirva esa imagen.
	 * ------------------------------------------------------------------- */
	function initTapas() {
		var track = $('#tapas-track');
		var scroller = $('#tapas-scroller');
		var section = $('#tapas');
		if (!track || !scroller) { return; }
		var list = D.tapas || [];
		if (!list.length) { if (section) { section.hidden = true; } return; }

		var dateEl = $('#tapas-date');
		if (dateEl) {
			try {
				dateEl.textContent = cap(new Date().toLocaleDateString('es-AR', { weekday: 'long', day: 'numeric', month: 'long', timeZone: TZ }));
			} catch (e) { /* sin fecha */ }
		}

		list.forEach(function (t) {
			var li = el('li', 'tapa');
			var color = colorFor(t.name);

			var card = isHttp(t.site) ? el('a', 'tapa-btn') : el('div', 'tapa-btn');
			if (isHttp(t.site)) {
				card.href = t.site;
				card.target = '_blank';
				card.rel = 'noopener noreferrer';
			}
			card.setAttribute('aria-label', 'Abrir el sitio de ' + t.name);
			card.style.setProperty('--c', color);

			var box = el('div', 'tapa-fallback');
			box.appendChild(el('span', 'tapa-ph', (t.name || '?').charAt(0)));
			box.appendChild(el('span', '', 'Ver portada'));
			if (isHttp(t.site)) { box.appendChild(el('span', '', 'Abrir ' + t.name)); }

			var nameBox = el('div', 'tapa-name');
			nameBox.appendChild(el('span', '', t.name));

			card.appendChild(box);
			card.appendChild(nameBox);
			li.appendChild(card);
			track.appendChild(li);
		});

		/* flechas */
		var prev = $('.scroll-btn[data-dir="-1"]');
		var next = $('.scroll-btn[data-dir="1"]');
		function updateBtns() {
			if (!prev || !next) { return; }
			var max = scroller.scrollWidth - scroller.clientWidth - 2;
			prev.disabled = scroller.scrollLeft <= 2;
			next.disabled = scroller.scrollLeft >= max;
		}
		[prev, next].forEach(function (b) {
			if (!b) { return; }
			b.addEventListener('click', function () {
				var dir = parseInt(b.getAttribute('data-dir'), 10);
				scroller.scrollBy({ left: dir * Math.max(240, scroller.clientWidth * 0.8), behavior: 'smooth' });
			});
		});
		var ticking = false;
		scroller.addEventListener('scroll', function () {
			if (ticking) { return; }
			ticking = true;
			window.requestAnimationFrame(function () { updateBtns(); ticking = false; });
		}, { passive: true });
		window.addEventListener('resize', updateBtns);
		window.setTimeout(updateBtns, 300);

		/* arrastrar con el mouse */
		var down = false, startX = 0, startLeft = 0, moved = false;
		scroller.addEventListener('mousedown', function (e) {
			if (e.button !== 0) { return; }
			down = true; moved = false;
			startX = e.pageX; startLeft = scroller.scrollLeft;
		});
		window.addEventListener('mousemove', function (e) {
			if (!down) { return; }
			var dx = e.pageX - startX;
			if (Math.abs(dx) > 5) { moved = true; scroller.classList.add('is-dragging'); }
			if (moved) { scroller.scrollLeft = startLeft - dx; }
		});
		window.addEventListener('mouseup', function () {
			if (!down) { return; }
			down = false;
			scroller.classList.remove('is-dragging');
		});
		scroller.addEventListener('click', function (e) {
			if (moved) { e.preventDefault(); e.stopPropagation(); moved = false; }
		}, true);
	}

	/* ---------------------------------------------------------------------
	 * Reproductor: HLS + mensajes + compartir
	 * ------------------------------------------------------------------- */
	function initPlayer() {
		var v = $('#mqtv-video');
		var msg = $('.player-msg');
		function show(t) { if (msg) { msg.textContent = t; msg.hidden = false; } }
		function hide() { if (msg) { msg.hidden = true; } }

		if (v) {
			v.addEventListener('playing', hide);
			v.addEventListener('error', function () { show('No pudimos cargar la transmisión. Probá recargar la página.'); });
			var src = v.getAttribute('data-hls');
			if (src) {
				if (window.Hls && window.Hls.isSupported()) {
					var hls = new window.Hls({ lowLatencyMode: true, backBufferLength: 30 });
					hls.loadSource(src);
					hls.attachMedia(v);
					hls.on(window.Hls.Events.ERROR, function (ev, data) {
						if (!data || !data.fatal) { return; }
						if (data.type === window.Hls.ErrorTypes.NETWORK_ERROR) {
							show('Se cortó la señal. Reconectando…');
							window.setTimeout(function () { hls.startLoad(); }, 4000);
						} else if (data.type === window.Hls.ErrorTypes.MEDIA_ERROR) {
							hls.recoverMediaError();
						} else {
							hls.destroy();
							show('La transmisión no está disponible en este momento.');
						}
					});
					hls.on(window.Hls.Events.MANIFEST_PARSED, function () {
						hide();
						if (D.stream && D.stream.autoplay) { var p = v.play(); if (p && p.catch) { p.catch(function () {}); } }
					});
				} else if (v.canPlayType('application/vnd.apple.mpegurl')) {
					v.src = src;
				} else {
					show('Tu navegador no puede reproducir esta transmisión.');
				}
			}
		}

		var share = $('.tv-share');
		if (share) {
			var label = $('span', share);
			var orig = label ? label.textContent : '';
			share.addEventListener('click', function () {
				var url = share.getAttribute('data-share') || window.location.href;
				function flash(t) {
					if (!label) { return; }
					label.textContent = t;
					window.setTimeout(function () { label.textContent = orig; }, 2200);
				}
				if (navigator.share) {
					navigator.share({ title: document.title, url: url }).catch(function () {});
					return;
				}
				if (navigator.clipboard && navigator.clipboard.writeText) {
					navigator.clipboard.writeText(url).then(function () { flash('¡Enlace copiado!'); }, function () { flash(url); });
				} else {
					var ta = el('textarea');
					ta.value = url;
					ta.style.position = 'fixed';
					ta.style.opacity = '0';
					document.body.appendChild(ta);
					ta.select();
					try { document.execCommand('copy'); flash('¡Enlace copiado!'); } catch (e) { flash(url); }
					document.body.removeChild(ta);
				}
			});
		}
	}

	/* ---------------------------------------------------------------------
	 * Inicio
	 * ------------------------------------------------------------------- */
	function init() {
		initHeader();
		initClock();
		initWeather();
		initNews();
		initTapas();
		initLightbox();
		initPlayer();
	}

	// initLightbox ya no se usa (no hay imágenes para ampliar en Tapas),
	// pero se deja una versión vacía por si algo del HTML todavía la referencia.
	function initLightbox() {
		var box = $('#lightbox');
		if (!box) { return; }
		box.hidden = true;
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', init);
	} else {
		init();
	}
}());<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="https://mqtvstream.com/sitemaps.xsl" ?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><sitemap>
							<loc>https://mqtvstream.com/post-sitemap1.xml</loc>
							<lastmod>2026-09-20T12:25:51+00:00</lastmod>
						</sitemap><sitemap>
							<loc>https://mqtvstream.com/page-sitemap1.xml</loc>
							<lastmod>2026-09-20T12:25:51+00:00</lastmod>
						</sitemap><sitemap>	
							<loc>https://mqtvstream.com/category-sitemap1.xml</loc>
							<lastmod>2026-09-21T23:26:02+00:00</lastmod>
						</sitemap></sitemapindex>