/**
 * Storzen — Flash Sale Countdown JS
 * assets/js/modules/flash-countdown.js
 *
 * Reads data-end (Unix timestamp UTC) from each .sz-flash-countdown
 * and ticks the digits every second. Handles expiry gracefully.
 * Re-queries the DOM every tick so Elementor / Ajax-injected cards
 * are always included without needing a second init call.
 *
 * @package storzen
 * @since   1.1.0
 */

/* global szFlashCountdown */
( function () {
	'use strict';

	var labels = ( window.szFlashCountdown || {} ).labels || {
		days: 'd', hours: 'h', mins: 'm', secs: 's', expired: 'Sale has ended',
	};

	/** @type {number|null} */
	var intervalId = null;

	function init() {
		if ( intervalId ) return; // already running
		var found = document.querySelectorAll( '.sz-flash-countdown[data-end]' );
		if ( ! found.length ) return;

		tick(); // Run immediately to avoid flash of "--"
		intervalId = setInterval( tick, 1000 );
	}

	function tick() {
		// Re-query live each tick so dynamically injected cards are included.
		var timers = document.querySelectorAll( '.sz-flash-countdown[data-end]' );
		if ( ! timers.length ) return;

		var now        = Math.floor( Date.now() / 1000 ); // Current UTC timestamp in seconds
		var allExpired = true;

		timers.forEach( function ( el ) {
			var end = parseInt( el.dataset.end, 10 );
			if ( isNaN( end ) ) return;

			var remaining = end - now;

			if ( remaining <= 0 ) {
				markExpired( el );
			} else {
				allExpired = false;
				updateDigits( el, remaining );
			}
		} );

		if ( allExpired && intervalId ) {
			clearInterval( intervalId );
			intervalId = null;
		}
	}

	/**
	 * Update digit elements inside a countdown container.
	 *
	 * @param {HTMLElement} el
	 * @param {number}      remaining  Seconds remaining
	 */
	function updateDigits( el, remaining ) {
		var days  = Math.floor( remaining / 86400 );
		var hours = Math.floor( ( remaining % 86400 ) / 3600 );
		var mins  = Math.floor( ( remaining % 3600 )  / 60 );
		var secs  = remaining % 60;

		setDigit( el, 'days',  pad( days ) );
		setDigit( el, 'hours', pad( hours ) );
		setDigit( el, 'mins',  pad( mins ) );
		setDigit( el, 'secs',  pad( secs ) );
	}

	/**
	 * @param {HTMLElement} container
	 * @param {string}      unit
	 * @param {string}      value
	 */
	function setDigit( container, unit, value ) {
		var el = container.querySelector( '[data-unit="' + unit + '"]' );
		if ( el && el.textContent !== value ) {
			el.textContent = value;
		}
	}

	/**
	 * Show "expired" message and hide timer.
	 *
	 * @param {HTMLElement} el
	 */
	function markExpired( el ) {
		if ( el.classList.contains( 'sz-expired' ) ) return;
		el.classList.add( 'sz-expired' );

		var msg = document.createElement( 'span' );
		msg.className   = 'sz-flash-expired-msg';
		msg.textContent = labels.expired;
		el.appendChild( msg );
	}

	/**
	 * Zero-pad a number to 2 digits.
	 *
	 * @param {number} n
	 * @return {string}
	 */
	function pad( n ) {
		return n < 10 ? '0' + n : String( n );
	}

	// ── Bootstrap ──────────────────────────────────────────────────────────

	// If DOM is already ready (script loaded late / defer), run immediately.
	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', init );
	} else {
		init();
	}

	// Elementor frontend: widgets are rendered after DOMContentLoaded.
	// Hook in whether elementorFrontend exists yet or not.
	function hookElementor() {
		if ( window.elementorFrontend && window.elementorFrontend.hooks ) {
			window.elementorFrontend.hooks.addAction( 'frontend/element_ready/global', init );
		}
	}
	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', hookElementor );
	} else {
		hookElementor();
	}

	// Expose for external callers (e.g. Ajax pagination, Elementor editor preview).
	window.szFlashCountdownInit = init;

}() );
