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_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 eventPaginationContainerSelector = $(`.eb-wp-event-lists-pagination-${eventbookings_wp_global_object.render_id}`);
    var search = null;
    var position = 1;
    var rows = 10;
    var eventbookings_wp_atts = $(`#eb_wp_atts_${eventbookings_wp_global_object.render_id}`).data("item");
    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_public",
                render_id: eventbookings_wp_global_object.render_id,
                search: search,
                position: position,
                rows: rows,
                eventbookings_wp_atts: eventbookings_wp_atts,

                ajax_nonce: eventbookings_wp_global_object.ajax_nonce
            },
            cache: true,
            dataType: 'json',
            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)
                }
                // Remove loader
                $('.list-loading').removeClass("show");

                // Render events
                if (window.EventComponents && window.EventComponents.EventCard) {
                    eventContainerSelector.empty();
                    if (eventList.length) {
                        eventList.forEach(function (eventDetails) {
                            var eventDetailsElement = EventComponents.EventCard({
                                eventDetails: eventDetails,
                                customized_settings: customized_settings,
                                bookNowCallback: function (eventDetails, customized_settings) {
                                    loadEventDetails(eventDetails, customized_settings, eventList);
                                }
                            });
                            eventContainerSelector.append(eventDetailsElement);
                        });
                    } 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.');
                }

                // Build pagination UI if pagination data exists.
                if (res?.data?.result?.pagination && res.data.result.pagination.records > res.data.result.pagination.limit) {
                    buildPagination(res.data.result.pagination);
                    eventPaginationContainerSelector.show()
                }
            },
            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");
            }
        });
    }

    function buildPagination(pagination) {
        // Assume pagination contains current_page and total_pages.
        var currentPage = pagination.current_page || 1;
        var paginationHtml = '';
        var totalRecords = pagination.records || 0;
        var perPage = pagination.limit || 10;
        var totalPages = Math.ceil(totalRecords / perPage);
        // Previous button
        if (currentPage > 1) {
            paginationHtml += '<button class="eb-pagination-btn" data-page="' + (currentPage - 1) + '">Previous</button>';
        }

        // Page numbers (simplified: show all page numbers; for many pages consider a sliding window)
        for (var i = 1; i <= totalPages; i++) {
            var activeClass = (i === currentPage) ? 'active' : '';
            paginationHtml += '<button class="eb-pagination-btn ' + activeClass + '" data-page="' + i + '">' + i + '</button>';
        }

        // Next button
        if (currentPage < totalPages) {
            paginationHtml += '<button class="eb-pagination-btn" data-page="' + (currentPage + 1) + '">Next</button>';
        }

        eventPaginationContainerSelector.html(paginationHtml);
    }

    // Initial load
    loadEvents(position);

    // Listen for pagination button clicks
    eventPaginationContainerSelector.on('click', '.eb-pagination-btn', function () {
        var newPage = parseInt($(this).data('page'));
        if (newPage && newPage !== position) {
            position = newPage;
            loadEvents(position);
        }
    });

    // 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");
        // console.log(customized_settings)
        window.location.href = eventbookings_wp_global_object.details_slug+'?eventUuid='+eventUuid;
        // $.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
        //                 }
        //                 generateEventListHtml(eventList, customized_settings);
        //             }
        //         });
        //
        //         eventContainerSelector.html(eventDetailsElement);
        //         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();
            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.');
        }
    }

});
