/* Estimated Delivery Date — storefront "order within" countdown.
 * Ticks down from a server-rendered, timezone-correct remaining-seconds value,
 * so it stays correct regardless of the visitor's own clock. */
( function () {
	var CFG = window.edfwFrontend || {};
	var TEMPLATE = CFG.orderWithin || 'Order within %s';
	var PASSED = CFG.cutoffPassed || 'Cutoff passed — ships next business day';
	var loadTime = Date.now();

	function format( seconds ) {
		var h = Math.floor( seconds / 3600 );
		var m = Math.floor( ( seconds % 3600 ) / 60 );
		var parts = ( h > 0 ? h + 'h ' : '' ) + m + 'm';
		return TEMPLATE.replace( '%s', parts );
	}

	function tick() {
		var nodes = document.querySelectorAll( '.edfw-countdown[data-remaining]' );
		var elapsed = Math.floor( ( Date.now() - loadTime ) / 1000 );
		for ( var i = 0; i < nodes.length; i++ ) {
			var el = nodes[ i ];
			var start = parseInt( el.getAttribute( 'data-remaining' ), 10 ) || 0;
			var remaining = start - elapsed;
			if ( remaining <= 0 ) {
				el.textContent = PASSED;
				el.classList.add( 'edfw-countdown--passed' );
			} else {
				el.textContent = format( remaining );
			}
		}
	}

	function start() {
		tick();
		setInterval( tick, 30000 );
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', start );
	} else {
		start();
	}
}() );
