/**
 * Booking Calendar - Calendly-style booking system
 * Uses Air Datepicker (CDN) to avoid Livewire conflicts
 */

class BookingCalendar {
    constructor() {
        this.currentStep = 1;
        this.selectedCheckinDate = null;
        this.selectedCheckinTime = null;
        this.selectedCheckoutDate = null;
        this.selectedCheckoutTime = null;

        this.bookedPeriods = window.bookingData?.booked_periods || {};
        this.bufferPeriods = window.bookingData?.buffer_periods || {};
        this.bufferHours = window.bufferHours || 0;

        this.init();
    }

    init() {
        console.log('Booking Calendar initialized');
        console.log('Booking data:', window.bookingData);

        this.initCheckinCalendar();
    }

    initCheckinCalendar() {
        const self = this;

        new AirDatepicker('#checkin-calendar', {
            inline: true,
            minDate: new Date(),
            dateFormat: 'yyyy-MM-dd',
            onSelect({date, formattedDate}) {
                if (date) {
                    self.selectedCheckinDate = formattedDate;
                    self.showSelectedCheckin(formattedDate);
                    self.showCheckinTimeSlots(formattedDate);
                    self.goToStep(2);
                }
            },
            onRenderCell({date, cellType}) {
                if (cellType === 'day') {
                    const dateStr = self.formatDate(date);
                    const status = self.getDayStatus(dateStr);

                    let className = '';
                    let disabled = false;

                    if (status.isFullyBooked) {
                        className = 'bg-red-100 text-red-500 line-through';
                        disabled = true;
                    } else if (status.availableCount > 0) {
                        className = 'bg-green-100 text-green-700 font-bold';
                    } else if (status.bufferCount > 0) {
                        className = 'bg-yellow-100 text-yellow-700';
                    }

                    return {
                        disabled: disabled,
                        classes: className,
                        attrs: {
                            title: status.isFullyBooked ? 'Fully Booked' :
                                   `${status.availableCount} hours available`
                        }
                    };
                }
            }
        });
    }

    initCheckoutCalendar() {
        const self = this;

        // Set min date to checkin date
        const minDate = new Date(this.selectedCheckinDate);

        new AirDatepicker('#checkout-calendar', {
            inline: true,
            minDate: minDate,
            dateFormat: 'yyyy-MM-dd',
            onSelect({date, formattedDate}) {
                if (date) {
                    self.selectedCheckoutDate = formattedDate;
                    document.getElementById('checkout-date-display').textContent = self.formatDateDisplay(formattedDate);
                    self.showCheckoutTimeSlots(formattedDate);

                    // Show checkout time section
                    document.getElementById('checkout-time-section').style.display = 'block';
                    document.getElementById('checkout-time-section').scrollIntoView({ behavior: 'smooth' });
                }
            },
            onRenderCell({date, cellType}) {
                if (cellType === 'day') {
                    const dateStr = self.formatDate(date);
                    const status = self.getDayStatus(dateStr);

                    let className = '';
                    let disabled = false;

                    if (status.isFullyBooked) {
                        className = 'bg-red-100 text-red-500 line-through';
                        disabled = true;
                    } else if (status.availableCount > 0) {
                        className = 'bg-green-100 text-green-700 font-bold';
                    } else if (status.bufferCount > 0) {
                        className = 'bg-yellow-100 text-yellow-700';
                    }

                    return {
                        disabled: disabled,
                        classes: className
                    };
                }
            }
        });
    }

    showSelectedCheckin(dateStr) {
        const displayDiv = document.getElementById('selected-checkin');
        const displayText = document.getElementById('checkin-date-display');

        displayDiv.classList.remove('hidden');
        displayText.textContent = this.formatDateDisplay(dateStr);
    }

    showCheckinTimeSlots(dateStr) {
        const container = document.getElementById('checkin-timeslots');
        const dateDisplay = document.getElementById('step2-date-display');

        dateDisplay.textContent = this.formatDateDisplay(dateStr);

        const slots = this.getTimeSlots(dateStr);
        container.innerHTML = '';

        slots.forEach(slot => {
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'timeslot-btn timeslot-' + slot.status;
            btn.textContent = slot.label;
            btn.disabled = slot.status !== 'available';

            if (slot.status === 'available') {
                btn.onclick = () => this.selectCheckinTime(slot.hour);
            }

            container.appendChild(btn);
        });
    }

    showCheckoutTimeSlots(dateStr) {
        const container = document.getElementById('checkout-timeslots');
        const slots = this.getTimeSlots(dateStr);

        container.innerHTML = '';

        slots.forEach(slot => {
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'timeslot-btn timeslot-' + slot.status;
            btn.textContent = slot.label;
            btn.disabled = slot.status !== 'available';

            if (slot.status === 'available') {
                btn.onclick = () => this.selectCheckoutTime(slot.hour);
            }

            container.appendChild(btn);
        });
    }

    selectCheckinTime(hour) {
        this.selectedCheckinTime = hour;

        // Update Livewire hidden inputs
        document.getElementById('hidden_check_in').value = this.selectedCheckinDate;
        document.getElementById('hidden_check_in').dispatchEvent(new Event('input'));

        document.getElementById('hidden_check_in_hour').value = String(hour).padStart(2, '0');
        document.getElementById('hidden_check_in_hour').dispatchEvent(new Event('input'));

        // Show checkout calendar
        document.getElementById('checkout-section').style.display = 'block';
        this.initCheckoutCalendar();

        // Scroll to checkout section
        document.getElementById('checkout-section').scrollIntoView({ behavior: 'smooth' });
    }

    selectCheckoutTime(hour) {
        this.selectedCheckoutTime = hour;

        // Update Livewire hidden inputs
        document.getElementById('hidden_check_out').value = this.selectedCheckoutDate;
        document.getElementById('hidden_check_out').dispatchEvent(new Event('input'));

        document.getElementById('hidden_check_out_hour').value = String(hour).padStart(2, '0');
        document.getElementById('hidden_check_out_hour').dispatchEvent(new Event('input'));

        // Update summary
        this.updateSummary();

        // Go to step 3
        this.goToStep(3);
    }

    updateSummary() {
        const checkinStr = `${this.formatDateDisplay(this.selectedCheckinDate)} at ${this.formatHour(this.selectedCheckinTime)}`;
        const checkoutStr = `${this.formatDateDisplay(this.selectedCheckoutDate)} at ${this.formatHour(this.selectedCheckoutTime)}`;

        document.getElementById('summary-checkin').textContent = checkinStr;
        document.getElementById('summary-checkout').textContent = checkoutStr;

        // Calculate duration
        const checkin = new Date(this.selectedCheckinDate + ' ' + String(this.selectedCheckinTime).padStart(2, '0') + ':00');
        const checkout = new Date(this.selectedCheckoutDate + ' ' + String(this.selectedCheckoutTime).padStart(2, '0') + ':00');
        const hours = Math.round((checkout - checkin) / (1000 * 60 * 60));
        const days = Math.ceil(hours / 24);

        document.getElementById('summary-duration').textContent = `${days} day${days > 1 ? 's' : ''} (${hours} hours)`;
    }

    getTimeSlots(dateStr) {
        const slots = [];
        const bookedPeriods = this.bookedPeriods[dateStr] || [];
        const bufferPeriods = this.bufferPeriods[dateStr] || [];

        for (let hour = 0; hour < 24; hour++) {
            const hourDateTime = new Date(dateStr + ' ' + String(hour).padStart(2, '0') + ':00:00');
            let status = 'available';

            // Check if booked
            for (let period of bookedPeriods) {
                const start = new Date(period.start);
                const end = new Date(period.end);
                if (hourDateTime >= start && hourDateTime < end) {
                    status = 'booked';
                    break;
                }
            }

            // Check if buffer (only if not booked)
            if (status === 'available') {
                for (let period of bufferPeriods) {
                    const start = new Date(period.start);
                    const end = new Date(period.end);
                    if (hourDateTime >= start && hourDateTime < end) {
                        status = 'buffer';
                        break;
                    }
                }
            }

            slots.push({
                hour: hour,
                label: this.formatHour(hour),
                status: status
            });
        }

        return slots;
    }

    getDayStatus(dateStr) {
        const bookedPeriods = this.bookedPeriods[dateStr] || [];
        const bufferPeriods = this.bufferPeriods[dateStr] || [];

        let bookedHours = 0;
        let bufferHours = 0;
        let availableHours = 0;

        for (let hour = 0; hour < 24; hour++) {
            const hourDateTime = new Date(dateStr + ' ' + String(hour).padStart(2, '0') + ':00:00');
            let isBooked = false;
            let isBuffer = false;

            for (let period of bookedPeriods) {
                const start = new Date(period.start);
                const end = new Date(period.end);
                if (hourDateTime >= start && hourDateTime < end) {
                    isBooked = true;
                    break;
                }
            }

            if (!isBooked) {
                for (let period of bufferPeriods) {
                    const start = new Date(period.start);
                    const end = new Date(period.end);
                    if (hourDateTime >= start && hourDateTime < end) {
                        isBuffer = true;
                        break;
                    }
                }
            }

            if (isBooked) bookedHours++;
            else if (isBuffer) bufferHours++;
            else availableHours++;
        }

        return {
            isFullyBooked: availableHours === 0 && bufferHours === 0,
            availableCount: availableHours,
            bufferCount: bufferHours,
            bookedCount: bookedHours
        };
    }

    goToStep(stepNumber) {
        // Hide all steps
        document.querySelectorAll('.booking-step').forEach(step => {
            step.classList.remove('active');
        });

        // Show target step
        document.getElementById(`step-${stepNumber}`).classList.add('active');

        // Update step indicator
        document.querySelectorAll('.step-item').forEach((item, index) => {
            item.classList.remove('active', 'completed');
            if (index + 1 < stepNumber) {
                item.classList.add('completed');
            } else if (index + 1 === stepNumber) {
                item.classList.add('active');
            }
        });

        this.currentStep = stepNumber;

        // Scroll to top
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    formatDateDisplay(dateStr) {
        const date = new Date(dateStr);
        return date.toLocaleDateString('en-US', {
            weekday: 'short',
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        });
    }

    formatHour(hour) {
        const h = hour === 0 ? 12 : (hour > 12 ? hour - 12 : hour);
        const period = hour < 12 ? 'AM' : 'PM';
        return `${h}:00 ${period}`;
    }
}

// Initialize when DOM is ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        window.bookingCalendar = new BookingCalendar();
    });
} else {
    window.bookingCalendar = new BookingCalendar();
}
