document.addEventListener('DOMContentLoaded', function () {
    jQuery(function ($) {
 //------------------------------------------------------------------------------------------------
 //------------------------------------------------------------------------------------------------
        // Find all calendar instances
        $('.frontend_kalender[data-instance]').each(function() {
            if (!window.TerminKalender.ter_kal_calendars) {
                window.TerminKalender.ter_kal_calendars = {};
            }
            const $wrapper = $(this);
            const instance_id = $wrapper.data('instance');
            const show_time = $wrapper.data('show_time') || 'start_end';
            // ter_kal_CHANGE: Initialize active filters from block settings
            if (!window.TerminKalender.active_filters) {
                window.TerminKalender.active_filters = {};
            }
            const hiddenCategories = $wrapper.data('hidden-categories') || [];
            window.TerminKalender.active_filters[instance_id] = new Set(hiddenCategories);
            const hide_buttons = $wrapper.data('hide-buttons') === 1; // ter_kal_CHANGE: Read hide buttons flag

        var ter_kal_lang = terminKalenderData.ter_kal_lang;
        const INPUT_FORMAT = 'YYYY-MM-DDTHH:mm';
        if (terminKalenderData.TERMIN_KALENDER_PRO_ON == 'on' && terminKalenderData.is_user_logged_in == 1 ) {
            var pro_button_login_link = '';
            var pro_button_login = '';
        }   else if (terminKalenderData.is_user_logged_in == 0 ) {
            var pro_button_login_link = terminKalenderData.calendar_login_link;
            var proLoginButton = 'LoginButton';
        }
            var calendarEl = document.getElementById('ter_kal_simple_calendar_' + instance_id);
        if (!calendarEl) {
            return;
        }
//------------------------------------------------------------------------------------------------
        var ter_kal_simple_calendar = new FullCalendar.Calendar(calendarEl, {
            // Native FullCalendar responsive settings
            height: 'auto',           // Grows/shrinks based on content
            contentHeight: 'auto',
            handleWindowResize: true, // Automatically adjusts on window resize (default: true)
            windowResizeDelay: 100,   // Debounce resize (ms)
            // For compact display:
            expandRows: false,        // Rows only as tall as needed
            dayMaxEvents: 3,          // Show max 3 events, rest as "+2 more"
            // Responsive view switching:
        /*    windowResize: function(view) {
                if (window.innerWidth < 500) {
                    ter_kal_simple_calendar.changeView('listWeek'); // Switch to list on mobile
                }
            },*/
            locale: ter_kal_lang,
            customButtons: {
                LoginButton: {
                  text: terminKalenderData.strings.calendar_login ,
                  click: function() { window.location.href = pro_button_login_link; }
                }
              },
            footerToolbar: {
    			left: proLoginButton,
    			center: '',
                right: '',
    		},
            headerToolbar: {
                left: 'prev,next,today',
                center: 'title',
                    right: 'multiMonthYear,dayGridMonth,timeGridWeek,listYear',
            },
            editable: false,
                timeZone: 'UTC',
            eventDisplay: 'block',
		    firstDay: 1,
		    weekNumbers: true,
                navLinks: true,
            dayMaxEventRows: 4,
            eventMaxStack: 3,
                listDayFormat: { weekday: 'long', day: 'numeric', month: 'long' },
                listDaySideFormat: false,
            events: terminKalenderData.TERMIN_KALENDER_DATEN ,
            eventDidMount: function(info) {
                $(info.el).attr('title', info.event.title);
            },
            viewDidMount: function(info) {
                if (info.view.type === 'multiMonthYear') {
                    ter_kal_simple_calendar.setOption('dayMaxEventRows', 3);
                }
                if (info.view.type === 'dayGridMonth') {
                    ter_kal_simple_calendar.setOption('dayMaxEventRows', 4);
                }
            },
            eventClick: function (info) {
                    openEventDialog(info.event, instance_id, show_time);
            }
        });
//------------------------------------------------------------------------------------------------
       // window.ter_kal_simple_calendar = ter_kal_simple_calendar;
        ter_kal_simple_calendar.render();
        // ter_kal_CHANGE: Store instance globally by instance_id
        window.TerminKalender.ter_kal_calendars[instance_id] = ter_kal_simple_calendar;
            // Detect if running in widget area
/*            const isInWidget = $wrapper.closest('.widget-area, .sidebar, aside').length > 0;
            if (isInWidget) {
                ter_kal_simple_calendar.setOption('height', 'auto');
                ter_kal_simple_calendar.setOption('contentHeight', 400);
            }*/
//------------------------------------------------------------------------------------------------
            // Initialize event dialog native listeners
            const dialogEl = document.getElementById('event-dialog-' + instance_id);
            if (dialogEl) {
                // Close button click
                const closeBtn = dialogEl.querySelector('.ter_kal_dialog_close');
                if (closeBtn) {
                    closeBtn.addEventListener('click', () => dialogEl.close());
                }
                // Backdrop click to close
                dialogEl.addEventListener('click', (e) => {
                    const rect = dialogEl.getBoundingClientRect();
                    // Fallback close check for backdrop click
                    const isInDialog = (rect.top <= e.clientY && e.clientY <= rect.top + rect.height &&
                                        rect.left <= e.clientX && e.clientX <= rect.left + rect.width);
                    if (!isInDialog) {
                        dialogEl.close();
                    }
                });
                // On close event, blur fullcalendar
                dialogEl.addEventListener('close', () => {
                    $('.fc-view-outer *').blur();
                });
            }

//------------------------------------------------------------------------------------------------
            window.TerminKalender.openEventDialogFrontend = window.TerminKalender.openEventDialogFrontend || {};
            window.TerminKalender.openEventDialogFrontend[instance_id] = function(event, id, time) {
                openEventDialog(event, id, time);
            };

            function openEventDialog(event, instance_id, show_time) {
                const dialog_selector = '#event-dialog-' + instance_id;
                const dialogEl = document.getElementById('event-dialog-' + instance_id);
                if (!dialogEl) return;

                const ter_kal_link = window.location.href;

                // Generate buttons
                const buttonsObj = window.TerminKalender.share_buttons_calendar_ical(event, 'frontent_calendar', ter_kal_link);
                const footerEl = document.getElementById('event-footer-' + instance_id);
                window.TerminKalender.render_dialog_footer_buttons(dialogEl, footerEl, event, 'frontent_calendar', ter_kal_link);

                if (dialogEl.open) {
                    dialogEl.close();
                }
            $('#event-form').attr('data-event-id', event ? event.id : '');

            var categoryData    = event ? event.extendedProps.category : null;
            var details         = event ? event.extendedProps.details : '';
            var location        = event ? event.extendedProps.location : '';
            var title           = event ? event.title : '';
            var dayName         = moment.utc(event.start).format('dddd');
            var utcStart_kurz   = moment.utc(event.start).format('D MMMM YYYY');
            var utcEnd_kurz     = moment.utc(event.end).format('D MMMM YYYY');
            var utcStart_kurzStd = moment.utc(event.start).format('HH:mm');
            var utcEnd_kurzStd   = ' - ' + moment.utc(event.end).format('HH:mm');
            var event_allday_string =  terminKalenderData.strings.all_day ;
            var freq                = event.extendedProps.freq ? event.extendedProps.freq : '' ;
            if (freq) {
               var freq_translated  = terminKalenderData.strings[freq] ;
               var until            = event.extendedProps.until ? event.extendedProps.until  : '';
               var utcEnd_kurz      = moment.utc(until).format('D MMMM YYYY');
               var utcEnd_kurzStd   = ' - ' + moment.utc(until).format('HH:mm');
            } else {
               var freq_translated  = ' ' ;
            }
            //-----------------------------------------------------------------------------
            //                 var isImplicitAllDay = event.end && moment.utc(event.end).diff(moment.utc(event.start), 'hours') === 24;

            var isImplicitAllDay = utcStart_kurzStd === '00:00' &&
                                   moment.utc(event.end).format('HH:mm') === '00:00' &&
                                   moment.utc(event.end).diff(moment.utc(event.start), '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;

            // Update instance-specific elements
//-----------------------------------------------------------------------------
            if (location) {     // event_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>';
                $('#event-location_link-' + instance_id).html( location );
            } else {
                $('#event-location_link-' + instance_id).html('');
            }
//-----------------------------------------------------------------------------
            var utcTage = hasValidEnd ? utcStart_kurz + ' - ' + utcEnd_kurz : utcStart_kurz;
            //-----------------------------------------------------------------------------
            $('#event-time-' + instance_id).html('<b>' + dayName + ',</b> ' + utcTage +
            '<br>' + freq_translated + ' <b><span class="utc_std">' + utcStart_kurzStd + ' <span class="utc_std_end"> ' + utcEnd_kurzStd  + '</span></span></b> ' );
//-----------------------------------------------------------------------------
            $('#event-title-' + instance_id).text( title );
            $('#event-details-html-' + instance_id).html( details );
//-----------------------------------------------------------------------------
                // Apply category styling
                applyDialogStyles(categoryData, 'event', dialog_selector);
//--------------------------------------------------------------------------
            // Handle show_time visibility
                var $dialog = $(dialog_selector);
            if (show_time == 'hide') {
                    $dialog.find('.utc_std').hide();
            } else if (show_time == 'start') {
                    $dialog.find('.utc_std_end').hide();
            } else  {
                    $dialog.find('.utc_std').show();
            }
//--------------------------------------------------------------------------
                dialogEl.showModal();
        } // end open event dialog
        //---------------------------------------------------------------------------
        //---------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------
            function applyDialogStyles(category, dialogType, dialog_selector) {
                const dialogEl = document.querySelector(dialog_selector);
                if (!dialogEl) return;
                
                const header = dialogEl.querySelector('.ter_kal_dialog_header');
                const title = dialogEl.querySelector('.ter_kal_dialog_title');
                
                if (category) {
                    if (header) {
                        header.style.backgroundColor = category.backgroundColor;
                        header.style.color = category.textColor;
                    }
                    if (dialogType === 'event' && title) {
                        title.innerHTML = '<span class="dialog_title_icon dashicons ' + category.icon + '"></span>' +
                                          '<span style="vertical-align:middle;">' + (category.label || terminKalenderData.strings.new_category) + '</span>';
                    }
                } else {
                    if (header) {
                        header.style.backgroundColor = '';
                        header.style.color = '';
                    }
                    if (dialogType === 'event' && title) {
                        title.innerHTML = '<span>' + terminKalenderData.strings.event_title + '</span>';
                    } else if (dialogType === 'category' && title) {
                        title.innerHTML = '<span>' + terminKalenderData.strings.new_category + '</span>';
                    }
                }
            }

        loadCategories(instance_id);
//------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------
        //  Add category filtering to frontend calendar
        function loadCategories(instance_id) {
            var categories = terminKalenderData.TERMIN_KALENDER_KATEGORIEN,
                $catSelect = $('#event-category_' + instance_id),
                $catRow = $('#kategoriezeile_' + instance_id);

            $catSelect.empty();
            $catRow.empty();

            // ter_kal_CHANGE: Get initial hidden categories
            var activeFilters = window.TerminKalender.active_filters[instance_id];


            $.each(categories, function (i, cat) {
                // Überspringe die "To Do" Kategorie komplett
                if (cat.label === 'To Do') {
                    return true; 
                }
                $('<option>')
                    .val(cat.label)
                    .text(cat.label)
                    .data('category', cat)
                    .appendTo($catSelect);

                var $btn = $('<div class="category-button">')
                    .css({ backgroundColor: cat.backgroundColor, color: cat.textColor })
                    .data('category-label', cat.label) // ter_kal_CHANGE: Store label for filtering
                    .addClass(activeFilters.has(cat.label) ? 'ter_kal_filtered' : '')
                    .css('display', (hide_buttons && activeFilters.has(cat.label)) ? 'none' : '')
                    .append(
                        $('<span class="dashicons ' + cat.icon + '"></span>'),
                        $('<span class="tk_kalender_button_text">').text(cat.label)
                    )
                    // ter_kal_CHANGE: Add click handler to toggle category filter
                    .on('click', function() {
                        var label = $(this).data('category-label');
                        if (activeFilters.has(label)) {
                            activeFilters.delete(label);
                            $(this).removeClass('ter_kal_filtered');
                        } else {
                            activeFilters.add(label);
                            $(this).addClass('ter_kal_filtered');
                        }

                        ter_kal_applyEventFilter(instance_id);
                    });

                $catRow.append($btn);
            });

            // ter_kal_CHANGE: Apply initial filter after calendar renders
            if (activeFilters.size > 0) {
                ter_kal_applyEventFilter(instance_id);
            }

            if (typeof callback === 'function') {
                callback();
            }

            localStorage.setItem('termin_kalender_kategorien', JSON.stringify(categories));
        }


        // ter_kal_CHANGE: Use CSS classNames to preserve event styling (CORRECTED LOGIC)
        function ter_kal_applyEventFilter(instance_id) {
            var calendar = window.TerminKalender.ter_kal_calendars[instance_id];
            if (!calendar) return;

            var activeFilters = window.TerminKalender.active_filters[instance_id];

            calendar.getEvents().forEach(function(event) {
                var eventCategory = event.extendedProps.category ? event.extendedProps.category.label : null;

                // ter_kal_CHANGE: Hide matched categories (clicked buttons are filtered OUT)
                if (activeFilters.size === 0 || !activeFilters.has(eventCategory)) {
                    // Show: remove hidden class
                    event.setProp('classNames', event.classNames.filter(c => c !== 'ter-kal-hidden'));
                } else {
                    // Hide: add hidden class when category IS in activeFilters
                    if (!event.classNames.includes('ter-kal-hidden')) {
                        event.setProp('classNames', [...event.classNames, 'ter-kal-hidden']);
                    }
                }
            });
        }

    //---------------------------------------------------------------------------
    //---------------------------------------------------------------------------
    }); // end each calendar instance
    //---------------------------------------------------------------------------
    //---------------------------------------------------------------------------

  }); // end jQuery

}); // document.addEventListener
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------