document.addEventListener('DOMContentLoaded', function () {

	const wrapperSelector = '.repeater-wrapper';
	const dateSelector = 'input[type="date"]';
	const today = new Date().toISOString().split('T')[0];

	function applyMin(input) {
		if (input) input.setAttribute('min', today);
	}

	function getInputs() {
		return document.querySelectorAll(`${wrapperSelector} ${dateSelector}`);
	}

	function getCount(wrapper) {
		return wrapper.querySelectorAll(dateSelector).length;
	}

	function showError(message) {
		if (typeof Swal !== 'undefined') {
			Swal.fire({
				icon: 'error',
				title: 'Oops...',
				text: message,
				confirmButtonColor: '#d33'
			});
		} else {
			alert(message); // fallback
		}
	}

	// INITIAL LOAD
	getInputs().forEach(applyMin);

	// CLICK EVENTS
	document.addEventListener('click', function (e) {

		// ADD ROW
		if (e.target.classList.contains('add-row')) {

			const wrapper = e.target.previousElementSibling;
			if (!wrapper) return;

			const maxLimit = parseInt(wrapper.getAttribute('data-max')) || 10;
			const currentCount = getCount(wrapper);

			// 🚫 MAX LIMIT
			if (currentCount >= maxLimit) {
				showError(`Maximum ${maxLimit} holidays allowed.`);
				return;
			}

			const fieldName = wrapper.getAttribute('data-name') || 'custom_dates[]';

			const row = document.createElement('div');
			row.className = 'repeater-row';

			row.innerHTML = `
				<input type="date" name="${fieldName}" />
				<button type="button" class="button remove-row">Remove</button>
			`;

			wrapper.appendChild(row);

			applyMin(row.querySelector('input'));
		}

		// REMOVE ROW
		if (e.target.classList.contains('remove-row')) {
			const row = e.target.closest('.repeater-row');
			if (row) row.remove();
		}
	});

	// CHANGE EVENT (Duplicate validation)
	document.addEventListener('change', function (e) {

		if (e.target.matches(`${wrapperSelector} ${dateSelector}`)) {

			const currentValue = e.target.value;
			if (!currentValue) return;

			const inputs = getInputs();
			let count = 0;

			inputs.forEach(input => {
				if (input.value === currentValue) count++;
			});

			// 🚫 DUPLICATE BLOCK
			if (count > 1) {

				e.target.value = '';

				showError('This date is already selected. Please choose another.');
			}
		}
	});

});
