/**
 * Event Monster Calendar Integration
 * FullCalendar integration for event display
 */

// jQuery compatibility check
if (typeof jQuery === 'undefined') {
    console.error('❌ Event Monster Calendar: jQuery is not loaded');
} else {
    console.log('✅ Event Monster Calendar: jQuery is available');
}

// Global calendar instances
window.emCalendars = window.emCalendars || {};

// Ensure modal styles are available (fallback)
function ensureModalStyles() {
    if (!document.getElementById('em-modal-fallback-styles')) {
        const style = document.createElement('style');
        style.id = 'em-modal-fallback-styles';
        style.textContent = `
            .em-modal-overlay {
                position: fixed !important;
                top: 0 !important;
                left: 0 !important;
                right: 0 !important;
                bottom: 0 !important;
                background-color: rgba(0, 0, 0, 0.8) !important;
                display: flex;
                align-items: center !important;
                justify-content: center !important;
                z-index: 999999 !important;
                padding: 1rem !important;
            }

            .em-event-modal-content {
                background: white !important;
                border-radius: 1rem !important;
                max-width: 800px !important;
                width: 100% !important;
                height:100% !important
                overflow-y: auto !important;
                box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5) !important;
                position: relative !important;
            }

            .em-modal-header {
                display: flex !important;
                justify-content: space-between !important;
                align-items: center !important;
                padding: 1rem !important;
                border-bottom: 1px solid #e5e7eb !important;
                background: #f8fafc !important;
                border-radius: 1rem 1rem 0 0 !important;
            }

            .em-modal-title {
                font-size: 1.5rem !important;
                font-weight: 700 !important;
                color: #111827 !important;
                margin: 0 !important;
            }

            .em-modal-close {
                background: none !important;
                border: none !important;
                font-size: 1.5rem !important;
                color: #6b7280 !important;
                cursor: pointer !important;
                padding: 0.5rem !important;
                border-radius: 0.5rem !important;
                transition: all 0.2s !important;
                line-height: 1 !important;
                width: 2rem !important;
                height: 2rem !important;
                display: flex !important;
                align-items: center !important;
                justify-content: center !important;
            }

            .em-modal-close:hover {
                background: #e5e7eb !important;
                color: #374151 !important;
            }

            .em-modal-body {
                padding: 0 !important;
                max-height: calc(90vh - 80px) !important;
                overflow-y: auto !important;
            }

            .em-modal-body .em-single-event-container,
            .em-modal-body .em-single-event-content,
            .em-modal-body .em-container {
                max-width: none !important;
                width: 100% !important;
                margin: 0 !important;
                padding: 0 !important;
            }

            .em-modal-body .em-single-event-template {
                padding: 1.5rem !important;
            }

            /* Disable blur on main event modal */
            #em-event-modal {
                backdrop-filter: none !important;
            }

            /* Ensure registration modals work properly in calendar modal */
            .em-modal-overlay:not(.em-hidden) {
                display: flex !important;
                position: fixed !important;
                top: 0 !important;
                left: 0 !important;
                right: 0 !important;
                bottom: 0 !important;
                background-color: rgba(0, 0, 0, 0.5) !important;
                align-items: center !important;
                justify-content: center !important;
                z-index: 999999 !important;
            }

            .em-modal-overlay.em-hidden {
                display: none !important;
            }

            /* Ensure ticket quantity fields are properly styled and clickable */
            select[id^="qty-"]:not(:disabled),
            select[id^="modal-qty-"]:not(:disabled) {
                opacity: 1 !important;
                pointer-events: auto !important;
                background-color: white !important;
                border: 1px solid #d1d5db !important;
                cursor: pointer !important;
            }

            select[id^="qty-"]:disabled,
            select[id^="modal-qty-"]:disabled {
                opacity: 0.5 !important;
                pointer-events: none !important;
                background-color: #f3f4f6 !important;
                cursor: not-allowed !important;
            }

            /* Force enable styling for modal quantity fields */
            .modal-ticket-quantity:not([disabled]) {
                opacity: 1 !important;
                pointer-events: auto !important;
                background-color: white !important;
                border: 1px solid #d1d5db !important;
                cursor: pointer !important;
            }

            body.em-modal-open {
                overflow: hidden !important;
            }

            @media (max-width: 768px) {
                .em-event-modal-content {
                    max-width: 95vw !important;
                    max-height: 95vh !important;
                    margin: 1rem !important;
                }

                .em-modal-header {
                    padding: 1rem !important;
                }

                .em-modal-title {
                    font-size: 1.25rem !important;
                }
            }
        `;
        document.head.appendChild(style);
    }
}

/**
 * Initialize Event Calendar
 */
function initializeEventCalendar(calendarId) {
    console.log('Initializing calendar:', calendarId);

    // Ensure modal styles are available
    ensureModalStyles();

    const calendarEl = document.getElementById(calendarId + '-fullcalendar');
    if (!calendarEl) {
        console.error('Calendar element not found:', calendarId + '-fullcalendar');
        return;
    }

    const initialView = calendarEl.dataset.initialView || 'dayGridMonth';
    const height = calendarEl.dataset.height || 'auto';
    const category = calendarEl.dataset.category || '';

    // Initialize FullCalendar
    const calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: initialView,
        height: height,
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
        },
        buttonText: {
            today: emCalendar.strings.viewDetails || 'Today',
            month: 'Month',
            week: 'Week',
            day: 'Day',
            list: 'List'
        },
        events: function(info, successCallback, failureCallback) {
            loadCalendarEvents(info, successCallback, failureCallback, category);
        },
        eventClick: function(info) {
            info.jsEvent.preventDefault();

            const eventId = info.event.extendedProps.eventId;
            const viewMode = calendarEl.dataset.viewMode || 'modal';

            if (eventId) {
                if (viewMode === 'modal') {
                    showEventModal(eventId);
                } else {
                    // Redirect to event page
                    window.location.href = '?em_single=' + eventId;
                }
            }
        },
        eventMouseEnter: function(info) {
            // Show tooltip on hover
            showEventTooltip(info);
        },
        eventMouseLeave: function(info) {
            // Hide tooltip
            hideEventTooltip();
        },
        loading: function(isLoading) {
            const loadingEl = document.getElementById('em-calendar-loading-' + calendarId);
            console.log('Calendar loading state:', isLoading, 'Element:', loadingEl);

            if (loadingEl) {
                if (isLoading) {
                    loadingEl.classList.remove('em-hidden');
                    loadingEl.style.display = 'flex';
                } else {
                    loadingEl.classList.add('em-hidden');
                    loadingEl.style.display = 'none';
                }
            }
        },
        eventDidMount: function(info) {
            // Add custom styling based on category
            const category = info.event.extendedProps.category;
            if (category) {
                info.el.setAttribute('data-category', category.toLowerCase());
                info.el.title = info.event.title + ' (' + category + ')';
            }
        }
    });

    // Store calendar instance
    window.emCalendars[calendarId] = calendar;

    // Render calendar
    calendar.render();

    // Setup filter event listeners
    setupCalendarFilters(calendarId, calendar);

    console.log('Calendar initialized successfully:', calendarId);
}

/**
 * Load calendar events via AJAX
 */
function loadCalendarEvents(info, successCallback, failureCallback, category = '') {
    console.log('Loading calendar events for range:', info.startStr, 'to', info.endStr);

    jQuery.ajax({
        url: emCalendar.ajaxUrl,
        type: 'POST',
        data: {
            action: 'em_get_calendar_events',
            nonce: emCalendar.nonce,
            start: info.startStr,
            end: info.endStr,
            category: category
        },
        success: function(response) {
            if (response.success) {
                console.log('Calendar events loaded:', response.data.length);
                successCallback(response.data);
            } else {
                console.error('Failed to load calendar events:', response.data);
                failureCallback(response.data);
            }
        },
        error: function(xhr, status, error) {
            console.error('AJAX error loading calendar events:', error);
            failureCallback(error);
        }
    });
}

/**
 * Setup calendar filter event listeners
 */
function setupCalendarFilters(calendarId, calendar) {
    const categoryFilter = document.getElementById('em-calendar-category-' + calendarId);
    const viewFilter = document.getElementById('em-calendar-view-' + calendarId);
    const todayButton = document.getElementById('em-calendar-today-' + calendarId);

    // Category filter
    if (categoryFilter) {
        categoryFilter.addEventListener('change', function() {
            const selectedCategory = this.value;
            console.log('Category filter changed:', selectedCategory);
            
            // Update calendar events source
            calendar.removeAllEventSources();
            calendar.addEventSource(function(info, successCallback, failureCallback) {
                loadCalendarEvents(info, successCallback, failureCallback, selectedCategory);
            });
        });
    }

    // View filter
    if (viewFilter) {
        viewFilter.addEventListener('change', function() {
            const selectedView = this.value;
            console.log('View changed:', selectedView);
            calendar.changeView(selectedView);
        });
    }

    // Today button
    if (todayButton) {
        todayButton.addEventListener('click', function() {
            console.log('Going to today');
            calendar.today();
        });
    }
}

/**
 * Show event tooltip on hover
 */
function showEventTooltip(info) {
    const event = info.event;
    const props = event.extendedProps;

    // Create tooltip element
    const tooltip = document.createElement('div');
    tooltip.id = 'em-event-tooltip';
    tooltip.className = 'em-event-tooltip';

    let tooltipContent = '';

    // Add event image if available
    if (props.image) {
        tooltipContent += `
            <div class="em-tooltip-image">
                <img src="${props.image}" alt="${event.title}" style="width: 100%; height: 100px; object-fit: cover; border-radius: 6px; margin-bottom: 8px;">
            </div>
        `;
    }

    tooltipContent += `<div class="em-tooltip-title">${event.title}</div>`;

    if (props.category) {
        tooltipContent += `<div class="em-tooltip-category">🏷️ ${props.category}</div>`;
    }

    if (props.location) {
        tooltipContent += `<div class="em-tooltip-location">📍 ${props.location}</div>`;
    }

    if (event.start) {
        const startDate = event.start.toLocaleDateString();
        const startTime = event.start.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
        const endTime = event.end ? event.end.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}) : '';
        const timeText = endTime && endTime !== startTime ? `${startTime} - ${endTime}` : startTime;
        tooltipContent += `<div class="em-tooltip-time">🕒 ${startDate} ${timeText}</div>`;
    }

    // Add description preview if available
    if (props.description) {
        const shortDesc = props.description.length > 80 ?
            props.description.substring(0, 80) + '...' :
            props.description;
        tooltipContent += `<div class="em-tooltip-description">${shortDesc}</div>`;
    }

    tooltipContent += `<div class="em-tooltip-action">Click to view details</div>`;

    tooltip.innerHTML = tooltipContent;

    // Position tooltip
    const rect = info.el.getBoundingClientRect();
    tooltip.style.position = 'fixed';
    tooltip.style.left = (rect.left + rect.width / 2) + 'px';
    tooltip.style.top = (rect.top - 10) + 'px';
    tooltip.style.transform = 'translateX(-50%) translateY(-100%)';
    tooltip.style.zIndex = '9999';

    document.body.appendChild(tooltip);
}

/**
 * Hide event tooltip
 */
function hideEventTooltip() {
    const tooltip = document.getElementById('em-event-tooltip');
    if (tooltip) {
        tooltip.remove();
    }
}

/**
 * Initialize ticket quantity fields for AJAX loaded content
 */
function initializeTicketQuantityFields() {
    if (typeof jQuery === 'undefined') {
        console.error('❌ jQuery not available for ticket initialization');
        return;
    }

    console.log('🎫 Initializing ticket quantity fields for modal content');

    // Disable all quantity fields by default
    jQuery('select[id^="qty-"], select[id^="modal-qty-"]').prop('disabled', true).val('0');

    // Enable quantity fields for already checked tickets
    jQuery('.ticket-checkbox:checked, .modal-ticket-checkbox:checked').each(function() {
        var ticketId = jQuery(this).data('ticket-id');
        var isModal = jQuery(this).hasClass('modal-ticket-checkbox');
        var quantitySelect = isModal ? jQuery('#modal-qty-' + ticketId) : jQuery('#qty-' + ticketId);

        quantitySelect.prop('disabled', false);
        if (quantitySelect.val() == '0') {
            quantitySelect.val('1');
        }

        console.log('✅ Initialized quantity field for checked ticket:', ticketId);
    });

    // Update totals after initialization
    var hasModal = jQuery('.modal-ticket-checkbox').length > 0;
    var hasInline = jQuery('.ticket-checkbox').length > 0;

    if (hasModal) {
        updateTicketTotals(true, 'modal');
    }
    if (hasInline) {
        updateTicketTotals(false, 'inline');
    }

    console.log('🎫 Ticket field initialization complete');
}

/**
 * Global function to update ticket totals
 */
function updateTicketTotals(isModal, eventId) {
    if (typeof jQuery === 'undefined') {
        console.error('❌ jQuery not available for total calculation');
        return;
    }

    var total = 0;
    var ticketCheckboxes = isModal ? jQuery('.modal-ticket-checkbox:checked') : jQuery('.ticket-checkbox:checked');

    ticketCheckboxes.each(function() {
        var ticketId = jQuery(this).data('ticket-id'); // Use data-ticket-id
        var price = parseFloat(jQuery(this).data('price')) || 0;
        var quantity = parseInt(isModal ?
            jQuery('#modal-qty-' + ticketId).val() :  // Correct selector
            jQuery('#qty-' + ticketId).val()) || 0;   // Correct selector

        total += price * quantity;
    });

    // Update total display
    var currencySymbol = '$'; // You might want to get this from PHP
    if (isModal) {
        jQuery('#modal-total-price').html(currencySymbol + total.toFixed(2));
    } else {
        jQuery('#total-price').html(currencySymbol + total.toFixed(2));
    }

    console.log('💰 Updated total:', currencySymbol + total.toFixed(2));
}

/**
 * Show event modal (using the same system as list view)
 */
function showEventModal(eventId) {
    console.log('Opening event modal for:', eventId);

    // Use the same AJAX system as the list view
    if (typeof jQuery !== 'undefined') {
        jQuery.ajax({
            url: emCalendar.ajaxUrl,
            type: 'POST',
            data: {
                action: 'em_get_event_modal',
                event_id: eventId,
                nonce: emCalendar.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Create modal container if it doesn't exist
                    let modalContainer = document.getElementById('em-event-modal');
                    if (!modalContainer) {
                        modalContainer = document.createElement('div');
                        modalContainer.id = 'em-event-modal';
                        modalContainer.className = 'em-modal-overlay';
                        document.body.appendChild(modalContainer);
                    }

                    // CRITICAL: Reset modal state before showing (fixes reopen issue)
                    // Remove em-hidden class that might have been added during close
                    jQuery(modalContainer).removeClass('em-hidden');
                    modalContainer.style.opacity = '1';
                    modalContainer.style.display = 'flex';

                    // Set modal content and show
                    modalContainer.innerHTML = response.data.html;
                    document.body.classList.add('em-modal-open');

                    // Make ajaxUrl available globally for registration component
                    if (typeof emCalendar !== 'undefined' && emCalendar.ajaxUrl) {
                        window.ajaxUrl = emCalendar.ajaxUrl;
                        console.log('🌐 Set global ajaxUrl for calendar modal context:', window.ajaxUrl);
                    }

                    // CRITICAL: Execute both external AND inline scripts that were inserted via innerHTML
                    setTimeout(function() {
                        // Execute external scripts
                        var externalScripts = modalContainer.querySelectorAll('script[src]');
                        externalScripts.forEach(function(scriptElement) {
                            var src = scriptElement.getAttribute('src');
                            if (src && !document.querySelector('script[src="' + src + '"]')) {
                                console.log('🔗 Loading external script:', src);
                                var script = document.createElement('script');
                                script.src = src;
                                script.async = true;
                                document.head.appendChild(script);
                            }
                        });

                        // Execute inline scripts (CRITICAL FIX for form submission handlers)
                        var inlineScripts = modalContainer.querySelectorAll('script:not([src])');
                        inlineScripts.forEach(function(scriptElement) {
                            console.log('📜 Executing inline script in calendar modal');
                            try {
                                // Create a new script element and execute it
                                var newScript = document.createElement('script');
                                newScript.textContent = scriptElement.textContent;
                                document.body.appendChild(newScript);
                                // Remove it immediately after execution
                                document.body.removeChild(newScript);
                            } catch (error) {
                                console.error('❌ Error executing inline script:', error);
                            }
                        });

                        console.log('✅ Calendar modal content loaded with external and inline script handling');
                    }, 100);

                    // Initialize maps with additional delay to ensure modal is fully rendered
                    setTimeout(function() {
                        var mapContainers = modalContainer.querySelectorAll('[id^="em-map-"]');
                        if (mapContainers.length > 0 && typeof window.initEventMap === 'function') {
                            console.log('🗺️ Found ' + mapContainers.length + ' map(s) in calendar modal, initializing...');
                            mapContainers.forEach(function(mapContainer) {
                                var mapId = mapContainer.getAttribute('id');
                                console.log('🗺️ Initializing map:', mapId);
                                window.initEventMap(mapId);
                            });
                        }
                    }, 500);

                    // The registration modal system is built into the single event template
                    // Initialize ticket quantity fields for the loaded content
                    setTimeout(function() {
                        initializeTicketQuantityFields();

                        // Force re-bind handlers to override any existing ones
                        jQuery('.modal-ticket-checkbox').off('change.calendar-modal').on('change.calendar-modal', function() {
                            var ticketId = jQuery(this).data('ticket-id');
                            var quantitySelect = jQuery('#modal-qty-' + ticketId);

                            console.log('🎫 Modal ticket checkbox changed:', ticketId, 'checked:', jQuery(this).is(':checked'));

                            if (jQuery(this).is(':checked')) {
                                quantitySelect.prop('disabled', false).val('1');
                                console.log('✅ Force enabled quantity field:', ticketId);
                            } else {
                                quantitySelect.prop('disabled', true).val('0');
                                console.log('❌ Force disabled quantity field:', ticketId);
                            }

                            // Force visual update
                            quantitySelect.removeClass('em-opacity-50').addClass('em-opacity-100');
                        });

                        console.log('🎫 Modal ticket handlers re-bound');
                    }, 200);

                    console.log('Event modal loaded with built-in registration system');
                } else {
                    console.error('Failed to load event modal:', response.data);
                    // Fallback: redirect to event page
                    window.location.href = '?em_single=' + eventId;
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error loading event modal:', error);
                // Fallback: redirect to event page
                window.location.href = '?em_single=' + eventId;
            }
        });
    } else {
        // Fallback: redirect to event page
        window.location.href = '?em_single=' + eventId;
    }
}

/**
 * Close event modal
 */
function closeEventModal() {
    const modalContainer = document.getElementById('em-event-modal');
    if (modalContainer) {
        // Destroy all maps before closing modal
        if (typeof window.destroyAllEventMaps === 'function') {
            console.log('🗑️ Destroying maps before closing modal...');
            window.destroyAllEventMaps();
        }

        // Fade out animation
        modalContainer.style.opacity = '0';

        setTimeout(function() {
            modalContainer.style.display = 'none';
            modalContainer.innerHTML = '';
            modalContainer.style.opacity = '1'; // Reset for next time
            document.body.classList.remove('em-modal-open');

            // CRITICAL: Remove any lingering backdrop/overlay classes and elements
            jQuery('body, html').removeClass('em-modal-open');

            // Hide any visible .em-modal-overlay elements (registration modals)
            // IMPORTANT: Exclude the main modal container (#em-event-modal) to avoid breaking reopen
            jQuery('.em-modal-overlay:visible').not('#em-event-modal').addClass('em-hidden').hide();

            // Also remove em-modal-open class that might have been added by registration modal
            jQuery('body').css('overflow', ''); // Reset overflow

            console.log('✅ Modal closed and all overlays cleaned up');
        }, 300); // Match CSS transition duration
    }
}

/**
 * Global registration modal handlers for dynamically loaded content
 * These work for both list and calendar modals
 */
jQuery(document).ready(function($) {
    // Handle registration modal buttons (works for AJAX loaded content)
    $(document).on('click', 'button[id^="em-show-registration-modal-"]', function(e) {
        e.preventDefault();
        var eventId = $(this).attr('id').replace('em-show-registration-modal-', '');
        var $modal = $('#em-registration-modal-' + eventId);

        console.log('🎯 Registration button clicked for event:', eventId);
        console.log('🔍 Modal found:', $modal.length > 0);

        if ($modal.length > 0) {
            // Force show the modal
            $modal.removeClass('em-hidden').show().css({
                'display': 'flex !important',
                'visibility': 'visible',
                'opacity': '1'
            });
            $('body, html').addClass('em-modal-open');
            console.log('✅ Registration modal should now be visible');
        } else {
            console.error('❌ Registration modal not found for event:', eventId);
            console.log('🔍 Available modals:', $('div[id*="modal"]').map(function() { return this.id; }).get());
            console.log('🔍 Looking for modal ID:', 'em-registration-modal-' + eventId);
            console.log('🔍 All registration modals:', $('div[id^="em-registration-modal-"]').map(function() { return this.id; }).get());
        }
    });

    // Handle registration modal close buttons
    $(document).on('click', 'button[id^="em-close-modal-"]', function(e) {
        e.preventDefault();
        var eventId = $(this).attr('id').replace('em-close-modal-', '');
        $('#em-registration-modal-' + eventId).addClass('em-hidden').hide();
        $('body, html').removeClass('em-modal-open');
    });

    // Handle message modal close buttons
    $(document).on('click', 'button[id^="em-close-message-modal-"]', function(e) {
        e.preventDefault();
        var eventId = $(this).attr('id').replace('em-close-message-modal-', '');
        $('#em-message-modal-' + eventId).addClass('em-hidden').hide();
        $('body, html').removeClass('em-modal-open');
    });

    // Handle main event modal overlay clicks to close
    $(document).on('click', '#em-event-modal', function(e) {
        // Close if clicking on overlay (not on modal content)
        if (e.target.id === 'em-event-modal') {
            closeEventModal();
        }
    });

    // Handle main event modal close button
    $(document).on('click', '.em-modal-close', function(e) {
        e.preventDefault();
        e.stopPropagation();
        closeEventModal();
    });

    // Handle registration modal overlay clicks to close
    $(document).on('click', '.em-modal-overlay', function(e) {
        if (e.target === this) {
            $(this).addClass('em-hidden').hide();
            $('body, html').removeClass('em-modal-open');
        }
    });

    // Handle escape key to close modals
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape') {
            // Close main event modal if visible
            const mainModal = document.getElementById('em-event-modal');
            if (mainModal && mainModal.style.display === 'flex') {
                closeEventModal();
            }

            // Close registration modals if visible
            $('.em-modal-overlay:visible').addClass('em-hidden').hide();
            $('body, html').removeClass('em-modal-open');
        }
    });

    // Don't intercept registration form submissions - let the registration component handle them
    // The registration component has its own form handlers that work perfectly for both free and paid bookings
    // Intercepting them here prevents the payment section from showing properly

    console.log('📝 Calendar integration: Registration forms will be handled by registration component');

    // Handle ticket selection changes for AJAX loaded content
    $(document).on('change', '.ticket-checkbox, .modal-ticket-checkbox', function() {
        console.log('🎫 Ticket selection changed via global handler');

        var ticketId = $(this).data('ticket-id');
        var isModal = $(this).hasClass('modal-ticket-checkbox');

        console.log('🔍 Ticket details:', {
            ticketId: ticketId,
            isModal: isModal,
            checked: $(this).is(':checked')
        });

        // Enable/disable quantity field based on checkbox state
        var quantitySelect = isModal ? $('#modal-qty-' + ticketId) : $('#qty-' + ticketId);

        console.log('🔍 Quantity select:', {
            selector: isModal ? '#modal-qty-' + ticketId : '#qty-' + ticketId,
            found: quantitySelect.length > 0,
            currentlyDisabled: quantitySelect.prop('disabled')
        });

        if ($(this).is(':checked')) {
            quantitySelect.prop('disabled', false);
            quantitySelect.val('1'); // Set default quantity to 1
            console.log('✅ Enabled quantity field for ticket:', ticketId);
        } else {
            quantitySelect.prop('disabled', true);
            quantitySelect.val('0');
            console.log('❌ Disabled quantity field for ticket:', ticketId);
        }

        // Force a visual update
        quantitySelect.trigger('change');

        // Update totals - try multiple methods
        var eventId = $(this).closest('form').attr('id');
        if (eventId) {
            eventId = eventId.replace(/^em-(modal-)?booking-form-/, '');
            updateTicketTotals(isModal, eventId);
        }

        // Also trigger the modal total calculation if in modal
        if (isModal && typeof calculateModalTotal === 'function') {
            calculateModalTotal();
        }
    });

    // Handle quantity changes for AJAX loaded content
    $(document).on('change', 'input[id^="ticket_quantity_"], input[id^="modal_ticket_quantity_"]', function() {
        console.log('🔢 Ticket quantity changed via global handler');

        var isModal = $(this).attr('id').includes('modal');
        var eventId = $(this).closest('form').attr('id').replace(/^em-(modal-)?booking-form-/, '');

        // Update totals
        updateTicketTotals(isModal, eventId);
    });

    // Function moved to top of file to avoid "not defined" error

    // Function moved to top of file to avoid "not defined" error

    // Debug function to check ticket field states
    window.debugTicketFields = function() {
        console.log('🔍 Debugging ticket fields:');

        $('.ticket-checkbox, .modal-ticket-checkbox').each(function() {
            var ticketId = $(this).data('ticket-id');
            var isModal = $(this).hasClass('modal-ticket-checkbox');
            var quantitySelect = isModal ? $('#modal-qty-' + ticketId) : $('#qty-' + ticketId);

            console.log('Ticket ' + ticketId + ':', {
                checked: $(this).is(':checked'),
                quantityDisabled: quantitySelect.prop('disabled'),
                quantityValue: quantitySelect.val(),
                quantityExists: quantitySelect.length > 0
            });
        });
    };
});

// CSS for tooltip
const tooltipStyles = `
<style>
.em-event-tooltip {
    background: rgba(0, 0, 0, 0.9);
    color: white;
    padding: 0.75rem;
    border-radius: 0.5rem;
    font-size: 0.875rem;
    max-width: 250px;
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
    pointer-events: none;
    backdrop-filter: blur(10px);
}

.em-tooltip-title {
    font-weight: 600;
    margin-bottom: 0.25rem;
}

.em-tooltip-category {
    color: #a5b4fc;
    font-size: 0.75rem;
    margin-bottom: 0.25rem;
}

.em-tooltip-location,
.em-tooltip-time {
    font-size: 0.75rem;
    opacity: 0.9;
    margin-bottom: 0.125rem;
}

.em-tooltip-location:last-child,
.em-tooltip-time:last-child {
    margin-bottom: 0;
}

.em-tooltip-description {
    font-size: 0.75rem;
    opacity: 0.8;
    margin-top: 0.5rem;
    line-height: 1.3;
    color: #d1d5db;
}

.em-tooltip-action {
    font-size: 0.7rem;
    opacity: 0.7;
    margin-top: 0.5rem;
    font-style: italic;
    color: #9ca3af;
}
</style>
`;

// Inject tooltip styles
document.head.insertAdjacentHTML('beforeend', tooltipStyles);

// Export for global access
window.initializeEventCalendar = initializeEventCalendar;
