(function () {
	function formatCountdown(hours, minutes, seconds) {
		var format = window.macaHoldStrings.countdownFormat;
		return format
			.replace('%1$d', String(hours))
			.replace('%2$d', String(minutes))
			.replace('%3$d', String(seconds));
	}

	document.addEventListener('DOMContentLoaded', function () {
		var node = document.querySelector('.maca-hold-countdown');
		if (!node) {
			return;
		}

		var target = parseInt(node.getAttribute('data-countdown-target'), 10) * 1000;
		var value = node.querySelector('.maca-hold-countdown-value');
		if (!value || !window.macaHoldStrings) {
			return;
		}

		var soonLabel = window.macaHoldStrings.countdownSoon;

		function tick() {
			var diff = target - Date.now();
			if (diff <= 0) {
				value.textContent = soonLabel;
				return;
			}

			var hours = Math.floor(diff / 3600000);
			var minutes = Math.floor((diff % 3600000) / 60000);
			var seconds = Math.floor((diff % 60000) / 1000);
			value.textContent = formatCountdown(hours, minutes, seconds);
		}

		tick();
		setInterval(tick, 1000);
	});
}());
