console.log("✅ init-weather-zones.js loaded");

function formatTimeInZone(unix, timeZone, opts = {}) {
	const date = new Date(unix * 1000);
	return date.toLocaleTimeString('en-US', {
		timeZone,
		hour: 'numeric',
		minute: '2-digit',
		hour12: true,
		...opts
	});
}

function formatDateInZone(unix, timeZone, opts = {}) {
	const date = new Date(unix * 1000);
	return date.toLocaleDateString('en-US', {
		timeZone,
		weekday: 'short',
		...opts
	});
}

const timezoneCache = {};

async function getTimezone(lat, lon) {
	const key = `${lat},${lon}`;
	if (timezoneCache[key]) return timezoneCache[key];

	try {
		const res = await fetch(`/wp-json/mwpl/tz?lat=${lat}&lon=${lon}`);
		if (!res.ok) throw new Error(`HTTP ${res.status}`);
		const data = await res.json();

		if (data?.timezone) {
			timezoneCache[key] = data.timezone;
			return data.timezone;
		}
	} catch (err) {
		console.warn(`🛑 Failed to fetch timezone for ${lat}, ${lon}`, err);
	}

	return null;
}


// Expose a callable initializer so swapped cards can be re-processed (AJAX userloc).
window.mwplInitWeatherZones = async function (root) {
	const scope = root || document;
	const allCards = scope.matches && scope.matches('[data-lat][data-lon]')
		? [scope]
		: Array.from(scope.querySelectorAll('[data-lat][data-lon]'));

	for (const card of allCards) {
		const lat = card.dataset.lat;
		const lon = card.dataset.lon;
		if (!lat || !lon) continue;

		const tz = await getTimezone(lat, lon);
		if (!tz) continue;

		// Header LIVE LOCAL TIME
		const clockWrapper = card.querySelector('.mw-local-time');
		const clockSpan = clockWrapper && clockWrapper.querySelector('.mw-live-time');

		if (clockWrapper && clockSpan) {
			clockWrapper.dataset.timezone = tz;

			const updateClock = () => {
				const now = new Date();
				const localTime = now.toLocaleTimeString('en-US', {
					timeZone: tz,
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit',
					hour12: true
				});
				clockSpan.textContent = localTime;
			};

			updateClock();
			// Avoid stacking intervals on swap: only start once per card.
			if (!clockWrapper.dataset.mwplClockStarted) {
				clockWrapper.dataset.mwplClockStarted = '1';
				setInterval(updateClock, 1000);
			}
		}

		// Sunrise / Sunset / local-time spans
		card.querySelectorAll('.local-time').forEach(el => {
			const ts = parseInt(el.dataset.utc, 10);
			if (ts) el.textContent = formatTimeInZone(ts, tz);
		});

		// Hourly forecast time
		card.querySelectorAll('.mw-hour-time').forEach(el => {
			const ts = parseInt(el.dataset.unixtime, 10);
			if (ts) {
				el.textContent = formatTimeInZone(ts, tz, { hour: 'numeric', hour12: true, minute: undefined });
			}
		});

		// 7-day labels
		card.querySelectorAll('.local-day').forEach(el => {
			const ts = parseInt(el.dataset.utc, 10);
			if (ts) el.textContent = formatDateInZone(ts, tz);
		});
	}
};

document.addEventListener('DOMContentLoaded', function () {
	window.mwplInitWeatherZones(document);
});

