document.addEventListener("DOMContentLoaded", function () {
    var successModal = new bootstrap.Modal(document.getElementById('successModal'));
    successModal.show();
    jQuery(document).on('click', '.close-modal', function () {
        successModal.hide();
        const url = window.location.origin + window.location.pathname;
        window.history.replaceState({}, document.title, url);
    })
});

document.addEventListener("DOMContentLoaded", function () {
    var successModal = new bootstrap.Modal(document.getElementById('errorModal'));
    successModal.show();
    jQuery(document).on('click', '.close-modal', function () {
        successModal.hide();
        const url = window.location.origin + window.location.pathname;
        window.history.replaceState({}, document.title, url);
    })
});

jQuery(document).ready(function ($) {
    var renderContainer = document.querySelector('[id^="eb_wp_feature_atts_"]'); // or a specific #id
    var localizedObjectName = renderContainer.getAttribute('data-localize-object');

    var eventbookings_wp_global_object = window[localizedObjectName];


    var eventContainerSelector = $(`.eb-wp-event-lists-${eventbookings_wp_global_object.render_id}`);
    var eventDetailsContainerSelector = $(`.eb-wp-event-details-${eventbookings_wp_global_object.render_id}`);

    var search = null;
    var customized_settings = {};

    var cacheeventList = null;
    var cachewidgetConfig = null;
    var cacheeventDetails = null;

    function loadEvents(position) {
        $('.list-loading').addClass("show");
        $.ajax({
            type: "GET",
            url: eventbookings_wp_global_object.ajaxurl,
            data: {
                action: "eventbookings_wp_get_events_featured",
                render_id: eventbookings_wp_global_object.render_id,
                search: search,
                position: position,
                ajax_nonce: eventbookings_wp_global_object.ajax_nonce
            },
            dataType: 'json',
            cache: true,
            success: function (res) {
                var eventList = [];
                customized_settings = {};
                if (res?.data?.result?.events) {
                    eventList = res.data.result.events;
                }
                if (res?.data?.result?.customized_settings) {
                    customized_settings = res.data.result.customized_settings;
                    console.log(customized_settings)
                }

                $('.list-loading').removeClass("show");

                if (window.EventComponents && window.EventComponents.EventCard) {
                    // Empty container
                    eventContainerSelector.empty();

                    if (eventList.length) {
                        // Create owl-carousel wrapper
                        var $carousel = $('<div class="owl-carousel"></div>');

                        // Append each event card into carousel
                        eventList.forEach(function (eventDetails) {
                            var eventDetailsElement = EventComponents.EventCard({
                                eventDetails: eventDetails,
                                customized_settings: customized_settings,
                                bookNowCallback: function (eventDetails, customized_settings) {
                                    loadEventDetails(eventDetails, customized_settings, eventList);
                                }
                            });
                            // Wrap in item container for owl
                            $carousel.append($('<div class="item"></div>').append(eventDetailsElement));
                        });

                        // Add carousel to DOM
                        eventContainerSelector.append($carousel);

                        // Initialize OwlCarousel
                        $carousel.owlCarousel({
                            loop: true,
                            autoplay: true,
                            autoplayTimeout: 3000,
                            autoplayHoverPause: true,
                            nav: true,
                            dots: false,
                            responsive: {
                                0: {items: 1},
                                600: {items: 3},
                                1000: {items: 3},
                                1400: {items: 3}
                            }
                        });

                    } else {
                        eventContainerSelector.html('<p class="no-events-found" style="width: 100%;display: flex;align-items: center;justify-content: center;color: rgb(104, 38, 114);font-size: 28px;">No events found.</p>');
                    }
                } else {
                    console.error('EventComponents or EventCard is not defined.');
                }
            },
            error: function (xhr, status, error) {
                console.error('AJAX error:', error);
                eventContainerSelector.html('<p>Failed to load events. Please try again later.</p>');
                $('.list-loading').removeClass("show");
            }
        });
    }

// Initial load
    loadEvents(1);


    // Example functions for event details and ticket purchase
    function loadEventDetails(eventDetails, widgetConfig, eventList) {

        var eventUuid = eventDetails.uuid;
        var eventData = "";
        cacheeventList = eventList;
        cachewidgetConfig = widgetConfig;
        cacheeventDetails = eventDetails;
        // $('.list-loading').addClass("show");
        window.location.href = eventbookings_wp_global_object.details_slug+'?eventUuid='+eventUuid;
        // console.log(customized_settings)
        // $.ajax({
        //     url: eventbookings_wp_global_object.ajaxurl,
        //     method: 'POST',
        //     data: {
        //         eventUuid: eventUuid,
        //         action: "eventbookings_wp_get_event_details",
        //         _nonce: eventbookings_wp_global_object.ajax_nonce
        //     },
        //     dataType: 'json',
        //     success: function (res) {
        //         eventData = res?.event || "";
        //         $('.list-loading').removeClass("show");
        //         var eventDetailsElement = EventComponents.EventDetails({
        //             eventDetails: eventData,
        //             widgetConfig: customized_settings,
        //             bookNowCallback: function (ticketData) {
        //                 // bookNowCallback: function (eventDetails) {
        //                 console.log(ticketData)
        //                 renderCheckoutPage(ticketData);
        //                 // ticket_purchase(eventDetails);
        //             },
        //             backToHomeCallback: function (eventDetails, widgetConfig, event) {
        //                 if (event && event.preventDefault) {
        //                     event.preventDefault(); // stop link navigation
        //                 }
        //                 eventContainerSelector.show()
        //                 generateEventListHtml(eventList, customized_settings);
        //             }
        //
        //         });
        //         $('body').children().not('header, footer, .eb-wp-event-details').hide();
        //         eventContainerSelector.hide()
        //         eventDetailsContainerSelector.html(eventDetailsElement);
        //         eventDetailsContainerSelector.show();
        //         // eventPaginationContainerSelector.hide()
        //     },
        //     error: function () {
        //         $('.list-loading').removeClass("show");
        //         console.error('Failed to load event details.');
        //     }
        // });

        function renderCheckoutPage(ticketData) {
            console.log(eventData)
            console.log("wp")
            const eventCheckoutElement = window.EventComponents.Checkout({
                ticketData: ticketData,
                eventDetails: eventData,
                orderPayloadCallback: (data) => {
                    // console.log('Order payload data====',{data});
                    ticket_purchase(data);
                },
            });
            eventContainerSelector.html(eventCheckoutElement);
            eventPaginationContainerSelector.hide()
        }
    }

    eventContainerSelector.on('click', '#backToEventDetails', function () {
        loadEventDetails(cacheeventDetails, cachewidgetConfig, cacheeventList);

    })

    function ticket_purchase(eventDetails) {
        eventDetails.append("action", "eventbookings_wp_ticket_purchase");
        eventDetails.append("ajax_nonce", eventbookings_wp_global_object.ajax_nonce);
        $('.list-loading').addClass("show");
        $.ajax({
            url: eventbookings_wp_global_object.ajaxurl,
            method: 'POST',
            data: eventDetails,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function (res) {
                res = JSON.parse(res);

                console.log('res 201')
                console.log(res)
                handleGuestOrderResponse(res);


            },
            error: function (res) {
                $('.list-loading').removeClass("show");

                $('.js-error-modal-msg').text(res.message)
                var successModal = new bootstrap.Modal(document.getElementById('errorModalGlobal'));
                successModal.show();

                jQuery(document).on('click', '.close-modal', function () {
                    successModal.hide();
                    const url = window.location.origin + window.location.pathname;
                    window.history.replaceState({}, document.title, url);
                })

            },
            complete: function () {
                console.log('ticket_purchase complete');
            }
        });
    }

    function handleGuestOrderResponse(order) {
        console.log('Order')
        console.log(order)
        var redirectUri = window.location.origin + window.location.pathname;
        if (!order || order.error) {
            $('.list-loading').removeClass("show");

            $('.js-error-modal-msg').text(order.message)
            var successModal = new bootstrap.Modal(document.getElementById('errorModalGlobal'));
            successModal.show();

            return;
        }
        var orderData = order.order;
        if (!orderData) {
            $('.list-loading').removeClass("show");

            $('.js-error-modal-msg').text(order.message)
            var successModal = new bootstrap.Modal(document.getElementById('errorModalGlobal'));
            successModal.show();

            return;
        }
        var uuid = orderData.uuid;
        var tmp_order = orderData.tmp_order;
        var seat_plan_redirect_url = orderData.seat_plan_redirect_url;

        setTimeout(function () {
            if (uuid) {
                window.location = redirectUri + '?status=success';
            } else if (tmp_order?.uuid) {
                window.location = eventbookings_wp_global_object.EVENTBOOKINGS_REMOTE_PAYMENT_URL + tmp_order.uuid + '?custom_redirect_url=' + redirectUri;
            } else if (seat_plan_redirect_url) {
                // window.location = eb_wp_global_object.EB_SEATPLAN_URL + seat_plan_redirect_url + '&custom_redirect_url=' + redirectUri;
                window.location = seat_plan_redirect_url + '&custom_redirect_url=' + redirectUri;
            } else {
                alert('Unexpected order response!');
            }
            $('.list-loading').removeClass("show");
        }, 1000)

    }

    function generateEventListHtml(eventList, widgetConfig) {
        if (window.EventComponents && window.EventComponents.EventCard) {
            // eventContainerSelector.empty();
            eventDetailsContainerSelector.hide();
            // if (eventList.length) {
            //     eventList.forEach(function (eventDetails) {
            //         var eventDetailsElement = EventComponents.EventCard({
            //             eventDetails: eventDetails,
            //             widgetConfig: widgetConfig,
            //             bookNowCallback: function (eventDetails, widgetConfig) {
            //                 loadEventDetails(eventDetails, widgetConfig, eventList);
            //             }
            //         });
            //         eventContainerSelector.append(eventDetailsElement);
            //     });
            //     eventPaginationContainerSelector.show()
            // }
        } else {
            console.error('EventComponents or EventCard is not defined.');
        }
    }

});
