(function ($) {
    "use strict";

    // Spinner
    var spinner = function () {
        setTimeout(function () {
            if ($('#spinner').length > 0) {
                $('#spinner').removeClass('show');
            }
        }, 1);
    };
    spinner();
    
    
    // Initiate the wowjs
    new WOW().init();


    // Sticky Navbar
    $(window).scroll(function () {
        if ($(this).scrollTop() > 300) {
            $('.sticky-top').addClass('bg-white shadow-sm');
        } else {
            $('.sticky-top').removeClass('bg-white shadow-sm');
        }
    });
    
    
   

    // Header carousel
    $(".header-carousel").owlCarousel({
        autoplay: true,
        smartSpeed: 1000,
        loop: true,
        dots: true,
        items: 1
    });


    // Testimonials carousel
    $(".testimonial-carousel").owlCarousel({
        items: 1,
        autoplay: true,
        smartSpeed: 1000,
        animateIn: 'fadeIn',
        animateOut: 'fadeOut',
        dots: true,
        loop: true,
        nav: false
    });

    // Show booking popup on nav button click
    $(document).on('click', '#navBookNow, .gallery-booking-trigger, #topBarQuote', function (e) {
        e.preventDefault();
        var popup = $('#bookingPopup');
        // Reset to form view before showing
        popup.find('.thank-you-message').remove();
        var form = popup.find('form');
        if (form.length) {
            form[0].reset();
        }
        form.show();
        form.siblings('.text-center.mb-4').show();
        popup.show().addClass('show-popup');
    });

    // Chatbot
    $(".chat-boat").click(function(e){
        e.preventDefault();
        $(".chat-window").fadeToggle();
    });

    // Floating Button Toggle
    $(".floating-toggle").click(function(e){
        e.preventDefault();
        $(".floating-menu").slideToggle();
    });

    $('.chat-header .btn-close').click(function() {
        $('.chat-window').fadeOut();
    });

    function addMessageToChat(message, sender) {
        var alignClass = sender === 'user' ? 'align-self-end' : 'align-self-start';
        var bgClass = sender === 'user' ? 'bg-primary text-white' : 'bg-light';

        var messageHTML = `
            <div class="d-flex flex-column">
                <div class="p-2 rounded mb-2 ${alignClass} ${bgClass}" style="max-width: 60%;">
                    ${message}
                </div>
            </div>
        `;

        var chatBody = $('.chat-body');
        chatBody.append(messageHTML);
        chatBody.scrollTop(chatBody[0].scrollHeight);
    }

    function handleSendMessage() {
        var input = $('.chat-footer input');
        var message = input.val().trim();

        if (message) {
            addMessageToChat(message, 'user');
            input.val('');

            setTimeout(function() {
                var response = "We offer luxury, deluxe and premium boats. please contact:+91 95267 88688 / +91 80867 88688";
                if (message.toLowerCase().includes('price') || message.toLowerCase().includes('package')) {
                    response = "We have several packages available! You can see them on our homepage. For specific pricing, please call us.";
                } else if (message.toLowerCase().includes('hello') || message.toLowerCase().includes('hi')) {
                    response = "Hello! How can I assist you with your houseboat booking today?";
                }
                addMessageToChat(response, 'bot');
            }, 1000);
        }
    }

    $('.chat-footer button').click(function() {
        handleSendMessage();
    });

    $('.chat-footer input').keypress(function(e) {
        if (e.which == 13) {
            handleSendMessage();
            return false;
        }
    });

    // Facts counter
    $('[data-toggle="counter-up"]').each(function () {
        var $this = $(this);
        var countTo = $this.text();
        
        $this.waypoint(function () {
            $({ countNum: 0 }).animate({
                countNum: countTo
            },
            {
                duration: 2000,
                easing: 'linear',
                step: function () {
                    $this.text(Math.floor(this.countNum));
                },
                complete: function () {
                    $this.text(this.countNum);
                }
            });
            this.destroy();
        }, {
            offset: '80%'
        });
    });
    
    // Star Rating
    $('.star-rating i').click(function(){
        var star = $(this).data('star');
        $('#rating').val(star);
        $('.star-rating i').each(function(){
            if($(this).data('star') <= star){
                $(this).removeClass('far').addClass('fas text-warning');
            }else{
                $(this).removeClass('fas text-warning').addClass('far');
            }
        });
    });

    // Booking Popup Logic
    function closeBookingPopup() {
        var popup = $('#bookingPopup');
        popup.removeClass('show-popup');
        setTimeout(function() {
            popup.hide();
            // Reset form for next time
            popup.find('.thank-you-message').remove();
            var form = popup.find('form');
            if (form.length) {
                form[0].reset();
                form.show();
                form.siblings('.text-center.mb-4').show();
                form.find('button[type="submit"]').prop('disabled', false).text('Book Now');
            }
        }, 500);
    }

    $('#closePopup').click(closeBookingPopup);
    $('#bookingPopup').click(function(e) {
        if (e.target === this) {
            closeBookingPopup();
        }
    });

    $(document).on('submit', '#bookingPopupForm', function(e) {
        e.preventDefault();

        var form = $(this);
        var submitButton = form.find('button[type="submit"]');
        submitButton.prop('disabled', true).text('Sending...');

        $.ajax({
            type: 'POST',
            url: 'save_popup_booking.php',
            data: form.serialize(),
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    form.hide();
                    form.siblings('.text-center.mb-4').hide();

                    var thankYouMessage = `
                        <div class="thank-you-message" id="bookingThankYou">
                            <i class="fa fa-check-circle fa-4x mb-3 text-success"></i>
                            <h4 class="text-primary">Thank You!</h4>
                            <p>Our team will contact you soon.</p>
                        </div>
                    `;
                    form.parent().append(thankYouMessage);
                } else {
                    alert('An error occurred: ' + response.message);
                    submitButton.prop('disabled', false).text('Book Now');
                }
            },
            error: function() {
                alert('Could not connect to the server. Please try again later.');
                submitButton.prop('disabled', false).text('Book Now');
            }
        });
    });

})(jQuery);



// Dynamic Children Age Fields
document.getElementById("children").addEventListener("input", function(){
let count = this.value;
let container = document.getElementById("childrenAges");
container.innerHTML = "";

for(let i=1;i<=count;i++){
container.innerHTML += `<input type="number" class="form-control mb-2" placeholder="Child ${i} Age" min="1" max="17">`;
}
});

// Price Calculation
function calculatePrice(){

let checkin = new Date(document.getElementById("checkin").value);
let checkout = new Date(document.getElementById("checkout").value);
let categoryPrice = document.getElementById("category").value;

if(!checkin || !checkout || !categoryPrice){
alert("Please select dates and category");
return;
}

let timeDiff = checkout - checkin;
let nights = timeDiff / (1000 * 3600 * 24);

if(nights <= 0){
alert("Check-out date must be after check-in date");
return;
}

let total = nights * categoryPrice;

document.getElementById("nights").innerText = nights;
document.getElementById("totalPrice").innerText = total;

}
