jQuery(function ($) {
   // Early exit if form doesn't exist
    if (!$('.eventlist').length) {
        return;
    }
    //--------------------------------
    window.TerminKalender = window.TerminKalender || {};
    const INPUT_FORMAT = 'YYYY-MM-DDTHH:mm';
    var ter_kal_lang = terminKalenderData.ter_kal_lang;
    var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    var months_to_fetch = isMobile ? 6 : 13;
    // Create calendar once (shared data source)
    const calendar_list = new FullCalendar.Calendar(document.createElement('div'), {
        locale: ter_kal_lang,
        timeZone: 'UTC',
        initialView: 'multiMonthYearPlus',
        views: {
            multiMonthYearPlus: {
                type: 'multiMonth',
                duration: { months: months_to_fetch }
            }
        },
        events: terminKalenderData.TERMIN_KALENDER_DATEN
    });
    //--------------------------------------------------------------------------------------------
    // Load and render events for a specific list instance
    //window.TerminKalender.all_parsed_events = calendar_list.getEvents();
        // Initialize once
        TerminKalender.init = function() {
            if (!TerminKalender.all_parsed_events) {
                TerminKalender.all_parsed_events = calendar_list.getEvents();
            }
            return TerminKalender.all_parsed_events;
        };
    //--------------------------------------------------------------------------------------------
    TerminKalender.load_data_for_list = function($eventList, instanceId, show_time, selectedCategory, items_to_show, template, template_html) {
        var all_events = TerminKalender.all_parsed_events || TerminKalender.init();  // TerminKalender.all_parsed_events; // calendar_list.getEvents();
            const now = new Date();
            const startOfToday = new Date(Date.UTC(
                now.getUTCFullYear(),
                now.getUTCMonth(),
                now.getUTCDate()
            ));
            let filteredEvents = all_events.filter(event => {
                let eventEnd;
                if (event.allDay) {
                    eventEnd = event.end ? new Date(event.end) : new Date(event.start);
                    if (event.end) {
                        eventEnd = new Date(eventEnd.getTime() - 86400000);
                    }
                } else {
                    eventEnd = event.end ? new Date(event.end) : new Date(event.start);
                }
                return eventEnd >= startOfToday;
            });
            if (selectedCategory) {
                filteredEvents = filteredEvents.filter(
                    event => event.extendedProps?.category?.label === selectedCategory
                );
            }
            filteredEvents = filteredEvents
                .sort((a, b) => new Date(a.start) - new Date(b.start))
                .slice(0, items_to_show);   
            // No events found
            if (filteredEvents.length === 0) {
                $eventList
                    .hide(500)
                    .html(terminKalenderData.strings.no_data_found)
                    .delay(500)
                    .fadeIn(500);
                return;
            }
        //--------------------------------------------------------------------------------------------------------------------------------
        // Title Colors and Icon
        //--------------------------------------------------------------------------------------------------------------------------------
        if (selectedCategory && filteredEvents.length > 0) {
            var headerTextColor = (filteredEvents[0].extendedProps.category?.backgroundColor)
                ? filteredEvents[0].extendedProps.category.backgroundColor
                : '#ffffff';
            var headerBgColor = (filteredEvents[0].extendedProps.category?.textColor)
                ? filteredEvents[0].extendedProps.category.textColor
                : '#3788d8';
            var dashicon = (filteredEvents[0].extendedProps.category?.icon)
                ? filteredEvents[0].extendedProps.category.icon
                : 'dashicons-calendar-alt';
        //--------------------------------------------------------------------------------------------------------------------------------
            // Style the category header (exists in DOM, rendered by PHP)
            $('.' + template + ' #tk_kategorie_title_' + instanceId).css({
                'color':  headerTextColor,
            });
            if ( template == 'template_event_color' || template == 'template_standard' ) {
                $('.' + template + ' #tk_kategorie_title_' + instanceId).css({
                    'background-color': headerBgColor,
                });
            }

            $('.' + template + ' #tk_kategorie_title_dashicon_' + instanceId)
                .removeClass(function(index, className) {
                    return (className.match(/\bdashicons-\S+/g) || []).join(' ');
                })
                .addClass('dashicons ' + dashicon);
        }
        //--------------------------------------------------------------------------------------------------------------------------------
        // For legacy compatibility: Store filtered events globally
        //document.filteredEvents = filteredEvents;
        //--------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
        // for legacy compatibility:
       $('#eventlist').addClass('eventlist');
//--------------------------------------------------------------------------------------------

        // Build HTML
        var expandedEvents_html = '';
        filteredEvents.forEach(function(event) {
            //-----------------------------------------------------------------------------
            // Category & Colors
            var categoryData = event.extendedProps.category;
            var category = categoryData ? categoryData.label : '';
            var backgroundColor = categoryData ? categoryData.backgroundColor : '';
            var backgroundColorLight = hexToRgba(backgroundColor, '0.2');
            var backgroundColorBorder = hexToRgba(backgroundColor, '0.5');
            var textColor = categoryData ? categoryData.textColor : '';
            // Basic Event Data
            var details = event.extendedProps.details || '';
            var location = event.extendedProps.location || '';
            var title = event.title || '';
            var id =  event.id || '';
            //-----------------------------------------------------------------------------
            // Date Formatting
            var eventStart = moment.utc(event.start);
            var eventEnd = event.end ? moment.utc(event.end) : null;
            // Recurrence - check early to potentially use as fallback end date
            var freq = event.extendedProps.freq || '';
            var freq_translated = '';
            var until = '';
            if (freq) {
                freq_translated = terminKalenderData.strings[freq] || '';
                until = event.extendedProps.until || '';
                // If no event.end but we have recurring until, use that
                if (!eventEnd && until) {
                    eventEnd = moment.utc(until);
                }
            }
            var dayName = eventStart.format('dddd');
            var weekdayShort = eventStart.format('ddd').toUpperCase();
            var utcStart_kurz = eventStart.format('D MMMM YYYY');
            var utcEnd_kurz = eventEnd ? eventEnd.format('D MMMM YYYY') : '';
            var utcStart_kurzStd = eventStart.format('HH:mm');
            var utcEnd_kurzStd = eventEnd ? ' - ' + eventEnd.format('HH:mm') : '';
            var event_allday_string = event.allDay ? terminKalenderData.strings.all_day : '';
            var flatpick_start = eventStart.format('YYYY-MM-DDTHH:mm');
            //var flatpick_end =   eventEnd.format('YYYY-MM-DDTHH:mm') ;
            //var flatpick_end =   eventEnd.format('YYYY-MM-DDTHH:mm') ;
            //var flatpick_end =  eventEnd.format('YYYY-MM-DDTHH:mm') || flatpick_start ;
            var flatpick_end = eventEnd ? eventEnd.format('YYYY-MM-DDTHH:mm') : moment.utc(flatpick_start).add(1, 'hour').format('YYYY-MM-DDTHH:mm');
            //var flatpick_end = eventEnd.format('YYYY-MM-DDTHH:mm') || flatpick_start;


            // Prüfe auf echtes Ganztags-Event oder implizites (00:00 - 00:00 Folgetag)
            var isImplicitAllDay = eventEnd &&
                                   utcStart_kurzStd === '00:00' &&
                                   eventEnd.format('HH:mm') === '00:00' &&
                                   eventEnd.diff(eventStart, 'days') === 1;
            if (event.allDay || isImplicitAllDay) {
                utcStart_kurzStd = event_allday_string;
                utcEnd_kurzStd = '';
            }
            // Zeige nur Startdatum wenn Enddatum ungültig, leer, identisch oder implizites Ganztags-Event
            var hasValidEnd = utcEnd_kurz &&
                              utcEnd_kurz !== 'Invalid date' &&
                              utcEnd_kurz.trim() !== '' &&
                              utcEnd_kurz !== utcStart_kurz &&
                              !isImplicitAllDay;
            var utcTage = hasValidEnd ? utcStart_kurz + ' - ' + utcEnd_kurz : utcStart_kurz;
            //-----------------------------------------------------------------------------
            // event_location
            if (location) {
                location = '<button type="button" class="bootstrap_button bootstrap_dark" onclick="window.open(\'https://www.google.com/maps/search/?api=1&query=' +
                           encodeURIComponent(location) + '\')">' +
                           terminKalenderData.strings.event_location + location + '</button>';
            }
            //-----------------------------------------------------------------------------
            // Extract images from details
            var $details = $('<div>' + details + '</div>');
            var images = $details.find('img.wp-block-image');
            var images_html = '';
            images.each(function() {
                images_html += $(this).prop('outerHTML');
                $(this).remove(); // Remove the image from the $details object
            });
            var details_no_images = $details.html();
            //-----------------------------------------------------------------------------
            // Template rendering
            if (!template || template === 'template_standard') {
                template_html =
                    '<h3 id="tkh3'+instanceId+'" style="color: {{textColor}}; background-color: {{backgroundColor}};">' +
                        '<span id="tkicon'+instanceId+'" class="accordeon_icon dashicons dashicons-calendar-alt" style="color: {{textColor}}; background-color: {{backgroundColor}};"></span>' +
                        '<span id="tkhead'+instanceId+'" class="header-text">' +
                        '<span id="tkacdy'+instanceId+'" class="accordeon_day" style="color: {{textColor}};">{{weekdayShort}}</span> {{utcStart_kurz}}' +
                            ' <span id=tkst"'+instanceId+'" class="utc_std">, {{utcStart_kurzStd}} <span id="tkend'+instanceId+'" class="utc_std_end">{{utcEnd_kurzStd}}</span></span>: <b>{{title}}</b>' +
                        '</span>' +
                    '</h3>' +
                            '<div id="tkcont'+instanceId+'"><div id="tkdt'+instanceId+'" class="eventlist_daytime" style="color: {{backgroundColor}}; background-color: {{textColor}};">' +
                                '<b>{{dayName}},</b> {{utcTage}}' +
                                '<span class="utc_std">, {{utcStart_kurzStd}} <span class="utc_std_end">{{utcEnd_kurzStd}}</span></span>' +
                                '<br>{{freq_translated}}<b>{{category}}</b></div>' +
                                '<h2 id="tkh2'+instanceId+'">{{title}}</h2>' +
                                '<div class="ter_kal_event_details">{{details}}</div><br>' +
                                '{{location}}' +
                            '</div>';
            }
//---------------------------------------------------------------------------------------------------
            //-----------------------------------------------------------------------------
            // HTML OUTPUT TEMPLATE -------------------------------------------------------
            var data = {
                textColor: textColor,
                backgroundColor: backgroundColor,
                backgroundColorLight: backgroundColorLight,
                backgroundColorBorder: backgroundColorBorder,
                utcStart_kurz: utcStart_kurz,
                utcStart_kurzStd: utcStart_kurzStd,
                utcEnd_kurzStd: utcEnd_kurzStd,
                title: title,
                dayName: dayName,
                weekdayShort: weekdayShort,
                utcTage: utcTage,
                freq_translated: freq_translated,
                category: category,
                details: details,
                details_no_images: details_no_images,
                images_html: images_html,
                location: location,
                id: id,
                flatpick_start: flatpick_start,
                flatpick_end: flatpick_end
            };
            //-----------------------------------------------------------------------------
            var html = template_html.replace(/{{(.*?)}}/g, function(match, key) {
                return data[key.trim()];
            });
            expandedEvents_html += html;
            //-----------------------------------------------------------------------------
            //-----------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------
            }); // end foreach
//---------------------------------------------------------------------------------------------------
        $eventList.html(expandedEvents_html);
//---------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------
            // Initialize accordion for this specific instance
        if (template === '' || template === 'template_standard') {
           $eventList.accordion({
                heightStyle: "content",
                collapsible: true,
                active: false
            });
        }

        // Show/hide time based on data attribute
        if (show_time === 'hide') {
            $eventList.find('.utc_std').hide();
        } else if (show_time === 'start') {
            $eventList.find('.utc_std_end').hide();
        }

    }; // end TerminKalender.load_data_for_list
//---------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------  
    function hexToRgba(hex, alpha) {
        if (!hex) return '';
        hex = hex.replace('#', '');
        var r = parseInt(hex.substring(0, 2), 16);
        var g = parseInt(hex.substring(2, 4), 16);
        var b = parseInt(hex.substring(4, 6), 16);
        return 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')';
    }


//--------------------------------------------------------------------------------------------
// Process each  list instance
//--------------------------------------------------------------------------------------------
    $('.eventlist[data-instance]').each(function() {
        const $eventList = $(this);
        const instanceId = $eventList.data('instance');
        const show_time = $eventList.data('show_time') || 'start_end';
        const selectedCategory = $eventList.data('category') || '';
        const items_to_show = $eventList.data('items_to_show') || 20;
        const template = $eventList.data('template') || '';
        const template_html = $eventList.data('template_html') || '';
        TerminKalender.load_data_for_list($eventList, instanceId, show_time, selectedCategory, items_to_show, template, template_html);
    });
//--------------------------------------------------------------------------------------------

}); // end jQ
//--------------------------------------------------------------------------------------------

