/**
 * Event List Filtering JavaScript
 * Handles filtering functionality for event lists
 */

(function($) {
    'use strict';

    // Initialize filters when document is ready
    $(document).ready(function() {
        initializeEventListFilters();
    });

    function initializeEventListFilters() {
        // Find all event list containers
        $('.em-list-container').each(function() {
            const $container = $(this);
            const listId = $container.attr('id');
            
            if (listId) {
                setupFiltersForList(listId);
            }
        });
    }

    function setupFiltersForList(listId) {
        const keywordInput = $('#em-keyword-search-' + listId);
        const categoryInput = $('#em-category-filter-' + listId);
        const dateFromInput = $('#em-date-from-' + listId);
        const dateToInput = $('#em-date-to-' + listId);
        const eventCards = $('#em-event-list-' + listId + ' .em-event-card');
        const noResultsMessage = $('#em-no-results-' + listId);
        const resultsCount = $('#em-results-count-' + listId);

        // Create global filter function for this list
        window.emFilterEvents = function(currentListId) {
            if (currentListId && currentListId !== listId) return;
            
            const keyword = keywordInput.val().toLowerCase();
            const category = categoryInput.val();
            const dateFrom = dateFromInput.val() ? new Date(dateFromInput.val()) : null;
            const dateTo = dateToInput.val() ? new Date(dateToInput.val()) : null;
            
            let visibleCount = 0;

            eventCards.each(function() {
                const $card = $(this);
                const title = $card.data('title') || '';
                const cardCategory = $card.data('category') || '';
                const cardDateStr = $card.data('start-date') || '';
                const cardDate = cardDateStr ? new Date(cardDateStr) : null;

                // Keyword match
                const keywordMatch = !keyword || title.toLowerCase().includes(keyword);

                // Category match - normalize both values for comparison
                const normalizedCategory = category.toLowerCase().trim();
                const normalizedCardCategory = cardCategory.toLowerCase().trim();
                const categoryMatch = normalizedCategory === 'all' || normalizedCardCategory === normalizedCategory;
                
                // Date range match
                const dateFromMatch = !dateFrom || !cardDate || cardDate >= dateFrom;
                const dateToMatch = !dateTo || !cardDate || cardDate <= dateTo;

                if (keywordMatch && categoryMatch && dateFromMatch && dateToMatch) {
                    $card.show();
                    visibleCount++;
                } else {
                    $card.hide();
                }
            });
            
            // Update results count
            updateResultsCount(resultsCount, visibleCount, eventCards.length);
            
            // Show or hide the "no results" message
            if (visibleCount === 0) {
                noResultsMessage.removeClass('em-hidden');
            } else {
                noResultsMessage.addClass('em-hidden');
            }
        };

        // Add event listeners to all filter inputs
        keywordInput.on('input', function() {
            window.emFilterEvents(listId);
        });
        
        categoryInput.on('change', function() {
            window.emFilterEvents(listId);
        });
        
        dateFromInput.on('change', function() {
            window.emFilterEvents(listId);
        });
        
        dateToInput.on('change', function() {
            window.emFilterEvents(listId);
        });

        // Initial count update
        updateResultsCount(resultsCount, eventCards.length, eventCards.length);
    }

    function updateResultsCount(resultsElement, visibleCount, totalCount) {
        if (resultsElement.length) {
            if (visibleCount === totalCount) {
                resultsElement.text(`Showing all ${totalCount} events`);
            } else {
                resultsElement.text(`Showing ${visibleCount} of ${totalCount} events`);
            }
        }
    }

    // Modal functionality for event details
    $(document).on('click', '.em-view-modal', function(e) {
        e.preventDefault();
        
        const eventId = $(this).data('event-id');
        if (!eventId) return;

        // Show loading state
        showEventModal(eventId);
    });

    function showEventModal(eventId) {
        console.log('Opening modal for event ID:', eventId);

        // Create modal HTML
        const modalHtml = `
            <div id="em-event-modal" class="em-modal-overlay">
                <div class="em-modal-content em-event-modal-content">
                    <div class="em-modal-header">
                        <h2 class="em-modal-title">Loading...</h2>
                      
                         <button type="button" onclick="closeEventModal()" class="em-modal-close-btn em-text-slate-400 hover:em-text-slate-600 em-text-2xl em-font-bold em-leading-none" style="padding: 5px; background: darkgrey; border-radius: 50%;">
                            <svg class="em-close-icon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="#fff" viewBox="0 0 256 256" style="transition: transform 0.3s ease-in-out; display: block;"><path d="M208.49,191.51a12,12,0,0,1-17,17L128,145,64.49,208.49a12,12,0,0,1-17-17L111,128,47.51,64.49a12,12,0,0,1,17-17L128,111l63.51-63.52a12,12,0,0,1,17,17L145,128Z"></path></svg>
                        </button>
                        
                    </div>
                    <div class="em-modal-body">
                        <div class="em-loading-spinner">
                            <div class="em-spinner"></div>
                            <p>Loading event details...</p>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // Add modal to page
        $('body').append(modalHtml);
        $('body').addClass('em-modal-open');

        // Check if AJAX object exists
        if (typeof em_ajax_object === 'undefined') {
            console.error('em_ajax_object not found');
            $('#em-event-modal .em-modal-body').html('<p>Configuration error. Please refresh the page.</p>');
            return;
        }

        console.log('Making AJAX request to:', em_ajax_object.ajax_url);
        console.log('With data:', {
            action: 'em_get_event_modal_content',
            event_id: eventId,
            nonce: em_ajax_object.nonce
        });

        // Load event content via AJAX
        $.ajax({
            url: em_ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'em_get_event_modal_content',
                event_id: eventId,
                nonce: em_ajax_object.nonce
            },
            success: function(response) {
                console.log('AJAX response:', response);
                if (response.success) {
                    // Set content using jQuery .html() which executes inline scripts
                    $('#em-event-modal .em-modal-body').html(response.data.content);
                    $('#em-event-modal .em-modal-title').text(response.data.title);

                    // Make ajaxUrl available globally for registration component
                    if (typeof em_ajax_object !== 'undefined' && em_ajax_object.ajax_url) {
                        window.ajaxUrl = em_ajax_object.ajax_url;
                        console.log('🌐 Set global ajaxUrl for event-list-filters modal context:', window.ajaxUrl);
                    }

                    // Initialize any maps in the modal content (increased delay for modal rendering)
                    setTimeout(function() {
                        var mapContainers = document.querySelectorAll('#em-event-modal [id^="em-map-"]');
                        if (mapContainers.length > 0 && typeof window.initEventMap === 'function') {
                            console.log('🗺️ Found ' + mapContainers.length + ' map(s) in list modal, initializing...');
                            mapContainers.forEach(function(mapContainer) {
                                var mapId = mapContainer.getAttribute('id');
                                console.log('🗺️ Initializing map:', mapId);
                                window.initEventMap(mapId);
                            });
                        }
                    }, 500);

                    console.log('✅ Event list filters modal content loaded');
                } else {
                    console.error('AJAX error:', response.data);
                    $('#em-event-modal .em-modal-body').html('<p>Error: ' + (response.data || 'Unknown error') + '</p>');
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX request failed:', {
                    status: status,
                    error: error,
                    responseText: xhr.responseText
                });
                $('#em-event-modal .em-modal-body').html('<p>Error loading event details: ' + error + '</p>');
            }
        });
    }

    // Global function to close modal
    window.closeEventModal = function() {
        // Destroy all maps before closing modal
        if (typeof window.destroyAllEventMaps === 'function') {
            console.log('🗑️ Destroying maps before closing modal...');
            window.destroyAllEventMaps();
        }

        $('#em-event-modal').remove();
        $('body').removeClass('em-modal-open');
    };

    // Close modal on overlay click
    $(document).on('click', '#em-event-modal', function(e) {
        if (e.target === this) {
            closeEventModal();
        }
    });

    // Close modal on escape key
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && $('#em-event-modal').length) {
            closeEventModal();
        }
    });

})(jQuery);

// Modal styles are now in compiled CSS - no need for inline styles
