document.addEventListener('DOMContentLoaded', function() {
    const dateInput = document.getElementById('selected_date');
    const timeInputs = document.querySelectorAll('input[name="visit_time"]');
    const calendarDays = document.getElementById('calendarDays');
    const currentMonthElement = document.getElementById('currentMonth');
    const selectedDateText = document.getElementById('selectedDateText');
    
    // Set timezone and locale
    moment.locale('id');
    moment.tz.setDefault('Asia/Jakarta');
    
    // Initialize variables
    let currentDate = moment().tz('Asia/Jakarta');
    let selectedDate = dateInput.value ? moment(dateInput.value).tz('Asia/Jakarta') : null;
    const today = moment().tz('Asia/Jakarta').startOf('day');
    
    function updateCalendar() {
        const year = currentDate.year();
        const month = currentDate.month();
        
        currentMonthElement.textContent = currentDate.format('MMMM YYYY');
        calendarDays.innerHTML = '';
        
        const firstDay = moment([year, month, 1]).tz('Asia/Jakarta');
        const daysInMonth = firstDay.daysInMonth();
        const startingDay = firstDay.day();
        
        // Add empty cells for padding
        for (let i = 0; i < startingDay; i++) {
            const emptyCell = document.createElement('div');
            emptyCell.classList.add('calendar-day', 'empty');
            calendarDays.appendChild(emptyCell);
        }
        
        // Add days
        for (let day = 1; day <= daysInMonth; day++) {
            const date = moment([year, month, day]).tz('Asia/Jakarta');
            const dayElement = document.createElement('div');
            dayElement.classList.add('calendar-day');
            dayElement.textContent = day;
            
            if (date.isBefore(today, 'day') || date.day() === 0 || date.day() === 6) {
                dayElement.classList.add('disabled');
            } else {
                dayElement.addEventListener('click', () => selectDate(date));
            }
            
            if (selectedDate && date.isSame(selectedDate, 'day')) {
                dayElement.classList.add('selected');
            }
            
            if (date.isSame(today, 'day')) {
                dayElement.classList.add('today');
            }
            
            calendarDays.appendChild(dayElement);
        }
    }
    
    function selectDate(date) {
        const jakartaDate = moment(date).tz('Asia/Jakarta');
        
        if (jakartaDate.day() === 0 || jakartaDate.day() === 6) {
            alert('Mohon maaf, pendaftaran hanya tersedia untuk hari kerja (Senin-Jumat)');
            return;
        }
        
        selectedDate = jakartaDate;
        dateInput.value = jakartaDate.format('YYYY-MM-DD');
        selectedDateText.textContent = jakartaDate.format('dddd, D MMMM YYYY');
        updateCalendar();
        checkQuota();
    }
    
    function checkQuota() {
        const selectedDate = dateInput.value;
        if (!selectedDate) return;
        
        timeInputs.forEach(input => {
            const selectedTime = input.value;
            fetch(`/check-quota/${selectedDate}/${selectedTime}`)
                .then(response => response.json())
                .then(data => {
                    const quotaInfo = input.nextElementSibling.querySelector('.quota-info small');
                    if (!data.available) {
                        quotaInfo.textContent = data.message || 'Kuota Penuh';
                        quotaInfo.classList.add('text-danger');
                        input.disabled = true;
                        input.nextElementSibling.classList.add('disabled');
                    } else {
                        quotaInfo.textContent = `Tersedia ${data.quota - data.used} dari ${data.quota}`;
                        quotaInfo.classList.remove('text-danger');
                        input.disabled = false;
                        input.nextElementSibling.classList.remove('disabled');
                    }
                })
                .catch(error => console.error('Error checking quota:', error));
        });
    }
    
    // Event Listeners
    document.getElementById('prevMonth').addEventListener('click', () => {
        currentDate = currentDate.clone().subtract(1, 'month');
        updateCalendar();
    });
    
    document.getElementById('nextMonth').addEventListener('click', () => {
        currentDate = currentDate.clone().add(1, 'month');
        updateCalendar();
    });
    
    // Initialize
    updateCalendar();
    
    // Check quota if date is already selected
    if (dateInput.value) {
        selectedDate = moment(dateInput.value).tz('Asia/Jakarta');
        checkQuota();
    }
});