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

	const wrapper = document.getElementById('availability-wrapper');
	const addBtn = document.getElementById('add-row');

	if (!wrapper || !addBtn) return;

	const today = new Date().toISOString().split('T')[0];
	const fieldName = wrapper.getAttribute('data-name') || 'provider_availability[]';

	// ✅ Apply min date to all inputs
	function applyMinDates() {
		wrapper.querySelectorAll('input[type="date"]').forEach(input => {
			input.setAttribute('min', today);
		});
	}

	// ✅ Get all selected dates
	function getAllDates() {
		return Array.from(wrapper.querySelectorAll('input[type="date"]'))
			.map(input => input.value)
			.filter(val => val !== '');
	}

	// ✅ Prevent duplicate dates
	function handleDuplicate(input) {
		const value = input.value;
		if (!value) return;

		const dates = getAllDates();
		const count = dates.filter(d => d === value).length;

		if (count > 1) {
			input.value = '';

			// Simple message (replace with SweetAlert if needed)
			alert('This date is already selected. Please choose another.');
		}
	}

	// INITIAL LOAD
	applyMinDates();

	// ADD ROW
	addBtn.addEventListener('click', function () {

		const row = document.createElement('div');
		row.classList.add('availability-row');

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

		wrapper.appendChild(row);
	});

	// REMOVE ROW
	wrapper.addEventListener('click', function (e) {
		if (e.target.classList.contains('remove-row')) {
			e.target.closest('.availability-row').remove();
		}
	});

	// CHANGE EVENT → duplicate check
	wrapper.addEventListener('change', function (e) {
		if (e.target.matches('input[type="date"]')) {
			handleDuplicate(e.target);
		}
	});

});
