/* Main JS */

document.addEventListener('DOMContentLoaded', () => {
    // 1. Initialize AOS (Animate On Scroll)
    AOS.init({
        duration: 1000,
        once: true,
        offset: 100,
        easing: 'ease-out-cubic'
    });

    // 2. Navbar Scroll Effect
    const navbar = document.querySelector('.navbar');

    window.addEventListener('scroll', () => {
        if (window.scrollY > 50) {
            navbar.classList.add('scrolled');
        } else {
            navbar.classList.remove('scrolled');
        }
    });

    // 3. Smooth Scroll for Anchor Links
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });

    // 4. Dynamic Current Year in Footer
    const yearSpan = document.getElementById('current-year');
    if (yearSpan) {
        yearSpan.textContent = new Date().getFullYear();
    }

    // 5. Video Preview Interaction
    const videoWrapper = document.getElementById('video-container');
    if (videoWrapper) {
        videoWrapper.addEventListener('click', function () {
            const videoId = this.getAttribute('data-video-id');
            this.innerHTML = `
                <div class="ratio ratio-16x9 h-100">
                    <iframe src="https://www.youtube.com/embed/${videoId}?autoplay=1" 
                            title="ERA Resorts Full Tour" 
                            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                            allowfullscreen>
                    </iframe>
                </div>
            `;
            this.style.cursor = 'default';
        });
    }

    // 6. Hero Slider Animation
    const slides = document.querySelectorAll('.hero-slide');
    if (slides.length > 1) {
        let currentSlide = 0;
        setInterval(() => {
            slides[currentSlide].classList.remove('active');
            currentSlide = (currentSlide + 1) % slides.length;
            slides[currentSlide].classList.add('active');
        }, 5000); // Change image every 5 seconds
    }
    // 7. Testimonial Swiper Initialization
    if (typeof Swiper !== 'undefined' && document.querySelector('.testimonial-swiper')) {
        const testimonialSwiper = new Swiper('.testimonial-swiper', {
            slidesPerView: 1,
            spaceBetween: 30,
            loop: true,
            autoplay: {
                delay: 5000,
                disableOnInteraction: false,
            },
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },
            breakpoints: {
                // Desktop (992px+) show 2 slides
                992: {
                    slidesPerView: 2,
                    spaceBetween: 40,
                }
            }
        });
    }

    // Carousel Intersection Observer (Play on view, pause off view)
    const roomCarousels = document.querySelectorAll('.room-img-wrapper .carousel');
    if (roomCarousels.length > 0 && typeof bootstrap !== 'undefined') {
        const carouselObserver = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                const carouselElement = entry.target;
                let bsCarousel = bootstrap.Carousel.getInstance(carouselElement);
                
                if (entry.isIntersecting) {
                    if (!bsCarousel) {
                        bsCarousel = new bootstrap.Carousel(carouselElement, {
                            interval: 3000,
                            ride: 'carousel'
                        });
                    } else {
                        bsCarousel.cycle();
                    }
                } else {
                    if (bsCarousel) {
                        bsCarousel.pause();
                    }
                }
            });
        }, { threshold: 0.2 });

        roomCarousels.forEach(carousel => {
            carouselObserver.observe(carousel);
        });
    }

    // 8. WhatsApp Booking Modal Form Logic
    const initWhatsAppBooking = () => {
        const modalHTML = `
            <div class="modal fade" id="whatsappBookingModal" tabindex="-1" aria-labelledby="whatsappBookingModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content text-start">
                        <div class="modal-header">
                            <h5 class="modal-title" id="whatsappBookingModalLabel">Book via WhatsApp</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="whatsappBookingForm">
                                <div class="mb-3">
                                    <label for="wbName" class="form-label">Name *</label>
                                    <input type="text" class="form-control rounded-0" id="wbName" name="name" required>
                                </div>
                                <div class="mb-3">
                                    <label for="wbNumber" class="form-label">WhatsApp Number *</label>
                                    <input type="tel" class="form-control rounded-0" id="wbNumber" name="number" required>
                                </div>
                                <div class="mb-3">
                                    <label for="wbRoom" class="form-label">Room</label>
                                    <input type="text" class="form-control rounded-0" id="wbRoom" name="room" readonly>
                                </div>
                                <div class="row">
                                    <div class="col-6 mb-3">
                                        <label for="wbAdults" class="form-label">Adults *</label>
                                        <input type="number" class="form-control rounded-0" id="wbAdults" name="adults" min="1" value="2" required>
                                    </div>
                                    <div class="col-6 mb-3">
                                        <label for="wbChildren" class="form-label">Children</label>
                                        <input type="number" class="form-control rounded-0" id="wbChildren" name="children" min="0" value="0">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-6 mb-3">
                                        <label for="wbCheckin" class="form-label">Check-in *</label>
                                        <input type="date" class="form-control rounded-0" id="wbCheckin" name="checkin" required>
                                    </div>
                                    <div class="col-6 mb-3">
                                        <label for="wbCheckout" class="form-label">Check-out *</label>
                                        <input type="date" class="form-control rounded-0" id="wbCheckout" name="checkout" required>
                                    </div>
                                </div>
                                <button type="submit" class="btn-luxury w-100 mt-2" id="wbSubmitBtn">Check Availability</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        `;
        document.body.insertAdjacentHTML('beforeend', modalHTML);

        const waModalEl = document.getElementById("whatsappBookingModal");
        if (!waModalEl) return;
        const waModal = new bootstrap.Modal(waModalEl);
        const waForm = document.getElementById("whatsappBookingForm");
        const waRoomInput = document.getElementById("wbRoom");
        const waSubmitBtn = document.getElementById("wbSubmitBtn");
        const waCheckinInput = document.getElementById("wbCheckin");
        const waCheckoutInput = document.getElementById("wbCheckout");

        const loadFlatpickr = () => {
            if (typeof flatpickr !== 'undefined') return Promise.resolve();
            return new Promise((resolve) => {
                const link = document.createElement('link');
                link.rel = 'stylesheet';
                link.href = 'https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css';
                document.head.appendChild(link);
                const script = document.createElement('script');
                script.src = 'https://cdn.jsdelivr.net/npm/flatpickr';
                script.onload = resolve;
                document.head.appendChild(script);
            });
        };

        // Helper to format date to YYYY-MM-DD
        const formatDate = (date) => {
            const pad = (n) => n < 10 ? '0' + n : n;
            return date.getFullYear() + '-' +
                   pad(date.getMonth() + 1) + '-' +
                   pad(date.getDate());
        };

        // Set minimum check-in to current time
        const now = new Date();
        waCheckinInput.min = formatDate(now);

        waCheckinInput.addEventListener('change', () => {
            if (waCheckinInput.value) {
                waCheckoutInput.min = waCheckinInput.value;
                
                if (waCheckoutInput.value && waCheckoutInput.value < waCheckinInput.value) {
                    waCheckoutInput.value = waCheckinInput.value;
                } else if (!waCheckoutInput.value) {
                    waCheckoutInput.value = waCheckinInput.value;
                }
            }
        });

        waCheckoutInput.addEventListener('change', () => {
             if (waCheckinInput.value && waCheckoutInput.value) {
                 if (waCheckoutInput.value < waCheckinInput.value) {
                     waCheckoutInput.value = waCheckinInput.value;
                     alert("Check-out date cannot be before check-in date.");
                 }
             }
        });


        const waLinks = document.querySelectorAll('a[href^="https://wa.me/"]');
        waLinks.forEach(link => {
            if (link.textContent.toLowerCase().includes("book via whatsapp")) {
                link.addEventListener("click", event => {
                    event.preventDefault();
                    event.stopPropagation();
                    try {
                        const closestAnchor = event.target.closest("a");
                        if (closestAnchor) {
                            const url = new URL(closestAnchor.href);
                            let roomName = "";
                            if (url.searchParams.has("text")) {
                                const match = url.searchParams.get("text").match(/booking (.+)/i);
                                if (match && match[1]) {
                                    roomName = match[1].replace("Room", "").trim();
                                }
                            }
                            waRoomInput.value = roomName;
                            
                            const lockedDatesAttr = closestAnchor.getAttribute('data-locked-dates');
                            window.currentRoomLockedDates = lockedDatesAttr ? lockedDatesAttr.split(',') : [];
                        }
                    } catch (err) {
                        console.error(err);
                    }
                    waModal.show();
                    
                    loadFlatpickr().then(() => {
                        if (window.fpCheckin) window.fpCheckin.destroy();
                        if (window.fpCheckout) window.fpCheckout.destroy();
                        
                        window.fpCheckin = flatpickr("#wbCheckin", {
                            minDate: "today",
                            disable: window.currentRoomLockedDates || [],
                            onChange: function(selectedDates, dateStr, instance) {
                                if (selectedDates.length > 0) {
                                    let minCheckout = new Date(selectedDates[0]);
                                    minCheckout.setDate(minCheckout.getDate() + 1);
                                    if (window.fpCheckout) {
                                        window.fpCheckout.set("minDate", minCheckout);
                                    }
                                }
                            }
                        });
                        
                        let minCheckOutDefault = new Date();
                        minCheckOutDefault.setDate(minCheckOutDefault.getDate() + 1);
                        window.fpCheckout = flatpickr("#wbCheckout", {
                            minDate: minCheckOutDefault,
                            disable: window.currentRoomLockedDates || []
                        });
                    });
                });
            }
        });

        if (waForm) {
            waForm.addEventListener("submit", event => {
                event.preventDefault();
                const originalText = waSubmitBtn.innerHTML;
                waSubmitBtn.innerHTML = "Processing...";
                waSubmitBtn.disabled = true;

                const formData = new FormData(waForm);
                const data = Object.fromEntries(formData.entries());

                const hasLockedNightInRange = (startStr, endStr) => {
                    if (!window.currentRoomLockedDates || window.currentRoomLockedDates.length === 0) return false;
                    const start = new Date(startStr);
                    const end = new Date(endStr);
                    for (let d = new Date(start); d < end; d.setDate(d.getDate() + 1)) {
                        const dStr = formatDate(d);
                        if (window.currentRoomLockedDates.includes(dStr)) return true;
                    }
                    return false;
                };

                if (hasLockedNightInRange(data.checkin, data.checkout)) {
                    alert("Your selected date range includes unavailable dates. Please select different dates.");
                    waSubmitBtn.innerHTML = originalText;
                    waSubmitBtn.disabled = false;
                    return;
                }
                
                // Add fallback capitalized keys directly to the payload 
                // in case the Google Sheet columns are named differently.
                formData.append("Name", data.name);
                formData.append("Number", data.number);
                formData.append("Phone Number", data.number);
                formData.append("Phone", data.number);
                formData.append("Room", data.room);
                formData.append("Room Name", data.room);
                formData.append("Adults", data.adults);
                formData.append("Children", data.children);
                formData.append("Checkin", data.checkin);
                formData.append("Checkout", data.checkout);

                const scriptURL = "https://script.google.com/macros/s/AKfycbygSNjWaea_COd31beXL31mgXJexahs7TIFNrd0Q06gz8lm5V1-4yutUQ0_prs0ztiWBQ/exec";
                const whatsappNumber = "917397788995";

                const message = `Hello Era Resorts,\n\nI would like to check availability for ${data.room}.\n\n*Booking Details:*\n- Name: ${data.name}\n- Contact: ${data.number}\n- Room: ${data.room}\n- Adults: ${data.adults}\n- Children: ${data.children}\n- Check-in: ${data.checkin.replace("T", " ")}\n- Check-out: ${data.checkout.replace("T", " ")}`;
                const waUrl = `https://wa.me/${whatsappNumber}?text=${encodeURIComponent(message)}`;

                const complete = () => {
                    waModal.hide();
                    waForm.reset();
                    waSubmitBtn.innerHTML = originalText;
                    waSubmitBtn.disabled = false;
                    window.open(waUrl, "_blank");
                };

                if (scriptURL !== "YOUR_GOOGLE_SCRIPT_WEB_APP_URL" && scriptURL.startsWith("https://script.google.com/")) {
                    fetch(scriptURL, { method: "POST", body: formData })
                        .then(response => {
                            if (!response.ok) { throw new Error('Network response was not ok'); }
                            return response.text(); // Google script usually returns text or json
                        })
                        .then(() => complete())
                        .catch(err => {
                            console.error("Error logging to Google Sheets:", err);
                            complete();
                        });
                } else {
                    complete();
                }
            });
        }
    };
    initWhatsAppBooking();
});
