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 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;




    // Example functions for event details and ticket purchase
    function loadEventDetails(eventUuid) {

        var eventData = "";
        $('.list-loading').addClass("show");
        // window.location.replace(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",
                ajax_nonce: eventbookings_wp_global_object.ajax_nonce
            },
            dataType: 'json',
            success: function (res) {
                eventData = res?.data?.event || "";
                customized_settings = res?.data?.customized_settings || {};
                $('.list-loading').removeClass("show");
                $('.list-loading').hide();
                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
                        }
                        window.history.back();

                    }

                });
                // $('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) {

            const eventCheckoutElement = window.EventComponents.Checkout({
                ticketData: ticketData,
                eventDetails: eventData,
                orderPayloadCallback: (data) => {
                    // console.log('Order payload data====',{data});
                    ticket_purchase(data);
                },
            });
            eventDetailsContainerSelector.html(eventCheckoutElement);
            // eventPaginationContainerSelector.hide()
            $('html, body').animate({
                scrollTop: eventDetailsContainerSelector.offset().top
            }, 00); // 600ms for smooth scroll
        }
    }

    loadEventDetails(eventbookings_wp_global_object.event_uuid)

    eventDetailsContainerSelector.on('click', '#backToEventDetails', function () {
        loadEventDetails(eventbookings_wp_global_object.event_uuid);
        // window.history.back();
    })

    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 +'?eventUuid='+eventbookings_wp_global_object.event_uuid;
        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) {
        window.history.back();
        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.');
        }
    }

});
