import CountdownTimer from '@10up/countdown-timer';

export const TIME_UNITS = ['days','hours','minutes','seconds'];

function getOptions(el) {
	return {
		target: new Date( el.getAttribute( 'datetime' ) ),
		days: { plural: el.getAttribute( 'data-label-days' ) || '' },
		hours: { plural: el.getAttribute( 'data-label-hours' ) || '' },
		minutes: { plural: el.getAttribute( 'data-label-minutes' ) || '' },
		seconds: { plural: el.getAttribute( 'data-label-seconds' ) || '' },
		onTick(values) {
			if (values) {
				let allowedParts = el.getAttribute('data-units') ? JSON.parse(el.getAttribute('data-units')) : TIME_UNITS;
				let displayValues = { ...values };

				if ( !allowedParts.includes('years') ) {
					displayValues.weeks += displayValues.years * 52;
				}

				if ( !allowedParts.includes('weeks') ) {
					displayValues.days += displayValues.weeks * 7;
				}

				if ( !allowedParts.includes('days') ) {
					displayValues.hours += displayValues.days * 24;
				}

				if ( !allowedParts.includes('hours') ) {
					displayValues.minutes += displayValues.hours * 60;
				}

				if ( !allowedParts.includes('minutes') ) {
					displayValues.seconds += displayValues.minutes * 60;
				}

				el.innerHTML = TIME_UNITS.map(unit => {
					if (!allowedParts.includes(unit)) return '';

					const value = displayValues[unit];
					const showLabel = el.getAttribute('data-show-label') === 'true';
					const label = showLabel ? `<div class="countdown__label">${el.getAttribute(`data-label-${unit}`) || unit}</div>` : '';

					return `
						<div class="countdown__part countdown__part--${unit}">
							<div class="countdown__number">${value}</div>
							${label}
						</div>
					`;
				}).join('');
			}
		},
		onEnd( instance ) {
			const afterTypeRaw = el.getAttribute( 'data-after-type' ) || '["message"]';
			const afterMessage = el.getAttribute( 'data-after-message' ) || '';
			const afterRedirect = el.getAttribute( 'data-after-redirect' ) || '';
			let afterType = [];
			try {
				afterType = JSON.parse( afterTypeRaw );
				if ( !Array.isArray( afterType ) ) {
					afterType = ['message'];
				}
			} catch ( e ) {
				afterType = ['message'];
			}

			if ( afterType.includes( 'hide' ) ) {
				el.classList.add( 'countdown__timer--hidden' );
			}

			if ( afterType.includes( 'message' ) ) {
				const messageEl = el.parentNode.querySelector( '.countdown__message' );
				messageEl.textContent = afterMessage;
				el.classList.add( 'countdown__timer--hidden' );
				messageEl.classList.add('countdown__message--show');
			}

			if ( afterType.includes( 'redirect' ) && afterRedirect ) {
				window.location.href = afterRedirect;
			}
		}
	}
}

export function createSingleCountdown(id, el) {
	return new CountdownTimer(id, getOptions(el));
}

document.addEventListener('DOMContentLoaded', () => {
	document.querySelectorAll('.countdown__timer').forEach((el, i) => {
		if (!el.id) {
			el.id = `countdown-${i}`;
		}

		new CountdownTimer(`#${el.id}`, getOptions(el));
	});
});
