// Termin-Kalender UI Dialogs Logic
document.addEventListener('DOMContentLoaded', function () {
    jQuery(function ($) {
        window.TerminKalender = window.TerminKalender || {};
        window.TerminKalender.UI = window.TerminKalender.UI || {};

        const data = window.terminKalenderData || {};
        const INPUT_FORMAT = 'YYYY-MM-DDTHH:mm';

        // ---------------------------------------------------------------------------------------------------------------
        // Initialize event and category dialogs
        $('#event-dialog,#category-dialog,#help-dialog').dialog(
            {
                dialogClass: 'ter_kal_ui_dialog ter_kal_calendar_admin',
                closeText: terminKalenderData.strings.close,
                create: function (event, ui) {
                    $(this).parent().draggable('option', 'handle', '.ui-dialog-titlebar, .ui-dialog-buttonpane');
                },
                autoOpen: false, modal: true, width: '98%', closeOnEscape: true
            });

        //---------------------------------------------------------------------------------
        $('#event-dialog').dialog({
            buttons: {
                [terminKalenderData.strings.save_event]: saveEventFromDialog,
                [terminKalenderData.strings.copy_event]: {
                    text: terminKalenderData.strings.copy_event,
                    class: "tk_btn_copy",
                    click: copyEvent
                },
                ...(terminKalenderData.termin_kalender_delete && {
                    [terminKalenderData.strings.delete_event]: {
                        text: terminKalenderData.strings.delete_event,
                        class: "tk_btn_delete",
                        click: deleteEvent
                    },
                }),
                [terminKalenderData.strings.cancel]: {
                    text: terminKalenderData.strings.cancel,
                    class: 'tk_btn_cancel',
                    click: function () {
                        $(this).dialog('close');
                    }
                }
            },
            open: function () {
                if (terminKalenderData.TERMIN_KALENDER_PRO_ON == 'on') {
                    $('#event-recurrings').show(2000);
                    $('#event-extensions').show(2000);
                    $('#event-recurrings_info_pro').hide(2000);
                    $('#event-extensions_info_pro').hide(2000);
                }
            },
            close: function () {
                $('.fc-view-outer *').blur(); // focus von der liste nehmen!,  //window.calendar.unselect(); funktioniert hier nicht
                sessionStorage.removeItem('original_start');
                sessionStorage.removeItem('original_end');
                $('.no_rec_duplicate').hide();
            },
        });

        //---------------------------------------------------------------------------------
        $('#category-dialog').dialog({
            buttons: {
                [terminKalenderData.strings.save_category]: saveCategoryFromDialog,
                ...(terminKalenderData.termin_kalender_delete && {
                    [terminKalenderData.strings.delete_category]: {
                        text: terminKalenderData.strings.delete_category,
                        class: "tk_btn_delete",
                        click: deleteCategory
                    },
                }),
                [terminKalenderData.strings.cancel]: {
                    text: terminKalenderData.strings.cancel,
                    class: 'tk_btn_cancel',
                    click: function () {
                        $(this).dialog('close');
                    }
                }
            },
            open: function () {
                loadDashicons(); // Load Dashicons when the category dialog is opened
                var cat = getCategoryByID($('#categoryID').val());
                applyDialogStyles(cat, 'category');
            }
        });

        //---------------------------------------------------------------------------------
        $('#help-dialog').dialog({
            open: function () {
                $('.ui-dialog-titlebar').css({
                    'background-color': '#0000FF',
                    'color': '#FFFFFF'
                });
                $('.ui-dialog-title').html(
                    '<span class="dialog_title_icon dashicons dashicons-admin-generic"></span>' +
                    '<span>' + terminKalenderData.strings.help + '</span>'
                );
            }
        });

        //---------------------------------------------------------------------------------
        window.TerminKalender.handleEventClickBackend = function (clickInfo) {
            // Handle Google Calendar events
            if (clickInfo.event.extendedProps && clickInfo.event.extendedProps.google_url) {
                if (clickInfo.jsEvent && typeof clickInfo.jsEvent.preventDefault === 'function') {
                    clickInfo.jsEvent.preventDefault();
                    clickInfo.jsEvent.stopPropagation();
                }
                clickInfo.event.setProp('url', null);
                window.open(clickInfo.event.extendedProps.google_url, 'gcalEditWin', 'width=800,height=600');
                return false;
            }

            // Intercept PRO "todo" events
            if (clickInfo.event.id && String(clickInfo.event.id).startsWith('todo-')) {
                if (window.TerminKalender.openTodoDialog && typeof window.TerminKalender.openTodoDialog === 'function') {
                    window.TerminKalender.openTodoDialog(clickInfo.event, clickInfo);
                    return false;
                }
            }

            // Intercept PRO "teammessage" events
            if (clickInfo.event.id && String(clickInfo.event.id).startsWith('teammessage-')) {
                if (window.TerminKalender.openTeammessageDialog && typeof window.TerminKalender.openTeammessageDialog === 'function') {
                    window.TerminKalender.openTeammessageDialog(clickInfo.event, clickInfo);
                    return false;
                }
            }

            // Only handle local events if NOT a Google event
            openEventDialog(clickInfo.event);
        };

        function openEventDialog(event, dateStr) {
            $('.ui-dialog-content').dialog('close');
            $('#event-dialog').dialog('open');
            $('#event-form').attr('data-event-id', event ? event.id : '');
            $('#event-title').val(event ? event.title : '');
            $('#event-details').val(event ? event.extendedProps.details : '');
            $('#event-details-html').html(event ? event.extendedProps.details : '');
            $('#event-notes').val(event ? event.extendedProps.notes : '');
            $('#event-location').val(event ? event.extendedProps.location : '');
            $('#interval').val(event ? event.extendedProps.interval : 1);
            $('#bysetpos').val(event ? event.extendedProps.bysetpos : '');
            $('#event-allday').prop('checked', event ? event.allDay : null);
            var freq_val = event ? event.extendedProps.freq : '';    // Initialize frequency fields for new events as well
            $('#event-recurring').val(freq_val);
            $('#excluding-days').val(event ? event.extendedProps.exdate : '');
            $('#show_more').text($('#show_more').data('text-show'));
            $('#event-byweekday').val(event ? event.extendedProps.byweekday : '');
            $('.tk_btn_delete').show();
            if (terminKalenderData.TERMIN_KALENDER_PRO_ON == 'on') {
                var post_link = event ? event.extendedProps.post_link : '';
                $('#post_link').val(post_link);
                $('#show_event_post_link').html('<a href="' + post_link + '" target="_blank">' + post_link + '</a>');
                $('#create_post').val('');
                $('#post_info').hide(700);
                if (post_link) {
                    $('#create_event_post').hide(300);
                    $('#show_event_post').show(300);
                } else {
                    $('#show_event_details').show(300);
                    $('#create_event_post').show(300);
                    $('#show_event_post').hide(300);
                    $('#bootstrap_button_line').show(700);
                }
            } else {
                $('#create_post').val('');
                $('#post_info').hide(300);
                $('#create_event_post').hide(300);
                $('#show_event_details').show();
                $('#show_event_post').hide(300);
                $('#bootstrap_button_line').show();
                $('#back_to_calendar_only').hide(300);
            }
            var location = event ? event.extendedProps.location : '';
            // Check if the location is not empty
            if (location) {
                // Encode the location for the URL
                var encoded_location = encodeURIComponent(location);
                // Create the Google Maps URL
                var google_maps_url = '<a href="https://www.google.com/maps/search/?api=1&query=' + encoded_location + '" target="_blank">' + location + '</a>';
                // Set the HTML content of the element with ID 'event-location_link'
                $('#event-location_link').html(google_maps_url);
            } else {
                // If the location is empty, clear the link
                $('#event-location_link').html('');
            }
            $('#show_more_div').hide(300);
            //--------------------------------------------------------------------------------------------------
            // Use label to set event-category
            $('#event-category').val((event && event.extendedProps && event.extendedProps.category && event.extendedProps.category.label) || $('#event-category option:not([value=""]):first').val());
            // Pass the category object directly
            applyDialogStyles(event && event.extendedProps.category ? event.extendedProps.category : null, 'event');
            //--------------------------------------------------------------------------------------------------
            // set initial select appearance to match category
            var initialCat = event && event.extendedProps.category;
            if (initialCat) {
                $('#event-category').css({
                    'background-color': initialCat.backgroundColor,
                    'color': initialCat.textColor,
                    'font-weight': '600'
                });
            } else {
                $('#event-category').css({
                    'background-color': '',
                    'color': '',
                    'font-weight': ''
                });
            }
            //--------------------------------------------------------------------------------------------------
            // Parse dates as UTC, Initialize from event or fallback to dateStr
            var date = moment.utc(dateStr);
            var start, end, dtstart, until;
            if (event) {
                dtstart = event.extendedProps?.dtstart ? moment.utc(event.extendedProps.dtstart) : null;
                until = event.extendedProps?.until ? moment.utc(event.extendedProps.until) : null;
                start = event.start ? moment.utc(event.start) : (dtstart || date);
                end = event.end ? moment.utc(event.end) : (until || start.clone());
                dtstart = dtstart && dtstart.isValid() ? dtstart : start;
                until = until && until.isValid() ? until : end;
            } else {  // neuer event
                start = date.add(8, 'hours');
                end = start.clone().add(8, 'hours');
            }

            if (freq_val) {   // If freq_val is set, it's a recurring event
                // RECURRING: Use dtstart/until
                $('#event-start').val(dtstart.format(INPUT_FORMAT));
                $('#event-dtstart').val(dtstart.format(INPUT_FORMAT));
                $('#event-until').val(until.format(INPUT_FORMAT));
                $('#event-end').val(until.format(INPUT_FORMAT));
                $('.tk_btn_copy').hide(700);
                $('#event-until, label[for="event-until"]').show(700);
                $('#event-end, label[for="event-end"]').hide(700);
            } else {
                // SIMPLE: Use start/end (keep existing time)
                $('#event-start').val(start.format(INPUT_FORMAT));
                $('#event-end').val(end.format(INPUT_FORMAT));
                $('#event-dtstart').val('');
                $('#event-until').val('');
                $('.tk_btn_copy').show(700);
                $('#event-until, label[for="event-until"]').hide(700);
                $('#event-end, label[for="event-end"]').show(700);
            }
            //--------------------------------------------------------------------------------------------------
            if (!event) {
                $('.tk_btn_copy, .tk_btn_delete').hide(700);
            }
            //--------------------------------------------------------------------------------------------------
            if (terminKalenderData.TERMIN_KALENDER_PRO_ON == 'on') {
                if (typeof window.TerminKalender?.update_recurring === 'function') {
                    window.TerminKalender.update_recurring();
                } else if (typeof window.terminkalender?.update_recurring === 'function') {
                    // fallback for version before 1.2.4
                    window.terminkalender.update_recurring();
                }
            }
            //--------------------------------------------------------------------------------------------------
            // abschliessend, textfelder anpassen
            //--------------------------------------------------------------------------------------------------
            updatePreviewMode();
            // textarea size grows with input
            $('textarea').on('input', function () {
                $(this).height('auto').height(this.scrollHeight + 'px');
            }).trigger('input');
        }
        window.TerminKalender.UI.openEventDialog = openEventDialog;
        //--------------------------------------------------------------------------------------------------
        // Add visual feedback when category changes in event dialog
        $('#event-category').on('change', function () {
            set_yes_for_post_update();
            var $selected = $(this).find(':selected');
            var categoryData = $selected.data('category');

            // Update dialog header styles immediately
            applyDialogStyles(categoryData, 'event');

            // Update the select element's own appearance
            if (categoryData) {
                $(this).css({
                    'background-color': categoryData.backgroundColor,
                    'color': categoryData.textColor,
                    'font-weight': '600'
                });
            } else {
                $(this).css({
                    'background-color': '',
                    'color': '',
                    'font-weight': ''
                });
            }
        });
        //---------------------------------------------------------------------------------
        function copyEvent() {
            var eventID = $('#event-form').attr('data-event-id');

            if (eventID) {
                var event = window.TerminKalender.calendar.getEventById(eventID);
                if (event) {
                    $('#event-form').removeAttr('data-event-id');
                    $('#event-title').val(event.title + ' +');
                    $('#event-details').val(event.extendedProps.details);
                    $('#event-notes').val(event.extendedProps.notes);
                    $('#event-location').val(event ? event.extendedProps.location : '');
                    $('#event-start').val(moment.utc(event.startStr).format(INPUT_FORMAT));
                    $('#event-end').val(moment.utc(event.endStr).format(INPUT_FORMAT));
                    $('#event-until').val(moment.utc(event.extendedProps.until).format(INPUT_FORMAT));
                    $('#event-freq').val(event.extendedProps.freq);
                    $('#excluding-days').val(event ? event.exdate : '');
                    $('#event-byweekday').val(event.extendedProps.byweekday);
                    $('#event-category').val(event.extendedProps.category.label);
                    $('#event-allday').val(event ? event.allDay : '');
                    $('#interval').val(event ? event.extendedProps.interval : '1');
                    $('#bysetpos').val(event ? event.extendedProps.bysetpos : '');
                    $('#post_link').val(event ? event.extendedProps.post_link : '');
                    applyDialogStyles(event.extendedProps.category);
                    saveEventFromDialog();
                    $('#event-dialog').dialog('close');
                } else {
                    alert(terminKalenderData.strings.error_copying_event);
                }
            } else {
                alert(terminKalenderData.strings.error_copying_event);
            }
        }
        //---------------------------------------------------------------------------------
        function deleteEvent() {
            var eventID = $('#event-form').attr('data-event-id');
            if (eventID && confirm(terminKalenderData.strings.confirm_delete_event)) {
                window.TerminKalender.API.deleteEvent(eventID)
                    .then(function (response) {
                        if (response.success) {
                            window.TerminKalender.calendar.refetchEvents();
                            $('#event-dialog').dialog('close');
                        } else {
                            alert(terminKalenderData.strings.error_deleting_event);
                        }
                    })
                    .catch(function () {
                        alert(terminKalenderData.strings.error_deleting_event);
                    });
            }
        }
        //---------------------------------------------------------------------------------
        function saveEventFromDialog() {
            var $sel = $('#event-category').find(':selected');
            var categoryData = $sel.data('category');
            var data = {
                id: $('#event-form').attr('data-event-id'),
                title: $('#event-title').val() || terminKalenderData.strings.event_title,
                start: $('#event-start').val(),
                end: $('#event-end').val(),
                until: $('#event-until').val(),
                details: $('#event-details').val(),
                notes: $('#event-notes').val(),
                location: $('#event-location').val(),
                freq: $("#event-recurring").find(":selected").val(),
                byweekday: $('#event-byweekday').val(),
                exdate: $('#excluding-days').val(),
                interval: $('#interval').val(),
                bysetpos: $('#bysetpos').val(),
                post_link: $('#post_link').val(),
                create_post: $('#create_post').val(),
                allDay: $('#event-allday').prop('checked'),
                category: categoryData ? categoryData.label : '',
                backgroundColor: categoryData ? categoryData.backgroundColor : '',
                textColor: categoryData ? categoryData.textColor : ''
            };

            window.TerminKalender.API.saveEvent(data)
                .then(function (response) {
                    if (response.id) {
                        $('#event-dialog').dialog('close');
                        if (window.TerminKalender.calendar) {
                            window.TerminKalender.calendar.refetchEvents();
                            if (!data.id) {
                                setTimeout(function () {
                                    const updatedEvent = window.TerminKalender.calendar.getEventById(response.id);
                                    if (updatedEvent) {
                                        openEventDialog(updatedEvent);
                                        $('#event-form').prepend(
                                            '<div class="tk-success-message" style="background:#d7f8e0;border-left:4px solid #46b450;padding:10px;margin-bottom:15px;color:#155724;">' +
                                            (response.message) +
                                            '</div>'
                                        );
                                        setTimeout(function () {
                                            $('.tk-success-message').fadeOut(700, function () { $(this).remove(); });
                                        }, 4000);
                                    }
                                }, 500);
                            }
                        }
                    } else {
                        alert(terminKalenderData.strings.error_saving_event);
                    }
                })
                .catch(function () {
                    alert(terminKalenderData.strings.error_saving_event);
                });
        }
        //---------------------------------------------------------------------------------
        function loadCategories(callback) {
            window.TerminKalender.API.getCategories()
                .then(function (response) {
                    if (Array.isArray(response)) {
                        var categories = response,
                            $catSelect = $('#event-category'),
                            $catRow = $('#kategoriezeile');

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

                        $('<div class="category-button tk_kalender_button_text" id="show_ter_kal_help">')
                            .css({ backgroundColor: '#343A40', color: '#fff' })
                            .append($('<span class="dashicons dashicons-admin-generic kategorie_help_plus"></span>'))
                            .on('click', function () { show_ter_kal_help(); })
                            .appendTo($catRow);

                        $.each(categories, function (i, cat) {
                            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 })
                                .append(
                                    $('<span class="dashicons ' + cat.icon + '"></span>'),
                                    $('<span class="tk_kalender_button_text">').text(cat.label)
                                )
                                .on('click', function () { openCategoryDialog(cat); });
                            $catRow.append($btn);
                        });

                        $('<div class="category-button tk_kalender_button_text" id="add_button">')
                            .css({ backgroundColor: '#343A40', color: '#fff' })
                            .append($('<span class="dashicons dashicons-plus-alt2 kategorie_help_plus"></span>'))
                            .on('click', function () { openCategoryDialog(null); })
                            .appendTo($catRow);

                        if (typeof callback === 'function') {
                            callback();
                        }
                        localStorage.setItem('termin_kalender_kategorien', JSON.stringify(categories));
                    }
                });
        }
        window.TerminKalender.UI.loadCategories = loadCategories;
        //---------------------------------------------------------------------------------
        function loadDashicons() {
            var dashicons = terminKalenderData.TERMIN_KALENDER_ICONS;
            var $iconItems = $('#category-icon-items');
            $iconItems.empty();
            dashicons.forEach(function (icon) {
                var iconName = icon.replace('dashicons-', '').replace(/-/g, ' ');
                $('<div>')
                    .html('<span class="dashicons ' + icon + '"></span> ' + iconName)
                    .attr('data-value', icon)
                    .on('click', function () {
                        $('#category-icon-selected').html('<span class="dashicons ' + icon + '"></span> ' + iconName);
                        $('#category-icon').val(icon);
                        $iconItems.addClass('tk-hidden');
                    })
                    .appendTo($iconItems);
            });
        }
        $('#category-icon-selected').on('click', function () {
            $('#category-icon-items').toggleClass('tk-hidden');
        });
        $(document).on('click', function (e) {
            if (!$(e.target).closest('.custom-select').length) {
                $('#category-icon-items').addClass('tk-hidden');
            }
        });
        loadDashicons();
        //---------------------------------------------------------------------------------
        function openCategoryDialog(category) {
            $('.ui-dialog-content').dialog('close');
            $('#category-dialog').dialog('open');
            if (category) {
                $('#category-form').attr('data-category-label', category.label);
                $('#category-label').val(category.label);
                $('#category-backgroundColor').val(category.backgroundColor);
                $('#category-textColor').val(category.textColor);
                $('#category-icon').val(category.icon);
                $('#category-icon-selected').text(category.icon);
                $('#categoryID').val(category.categoryID);
                applyDialogStyles(category, 'category');
            } else {
                $('#category-form').removeAttr('data-category-label');
                $('#category-label').val(terminKalenderData.strings.new_category);
                $('#category-backgroundColor').val('#0000FF');
                $('#category-textColor').val('#FFFFFF');
                $('#category-icon').val('dashicons-plus');
                $('#categoryID').val(Date.now());
                applyDialogStyles(null, 'category');
            }
        }
        window.TerminKalender.UI.openCategoryDialog = openCategoryDialog;
        //---------------------------------------------------------------------------------
        function show_ter_kal_help() {
            $('.ui-dialog-content').dialog('close');
            $('#help-dialog').dialog('open');
        }
        //---------------------------------------------------------------------------------
        function saveCategoryFromDialog() {
            var categoryLabel = $('#category-label').val().trim();
            if (categoryLabel.toLowerCase() === 'to do') {
                alert('Der Name "To Do" ist für das System reserviert und kann nicht als Kategorie verwendet werden.');
                return;
            }
            var data = {
                categoryID: $('#categoryID').val(),
                label: categoryLabel,
                backgroundColor: $('#category-backgroundColor').val(),
                textColor: $('#category-textColor').val(),
                icon: $('#category-icon').val()
            };
            window.TerminKalender.API.saveCategory(data)
                .then(function (response) {
                    if (response.success) {
                        loadCategories();
                        $('#category-dialog').dialog('close');
                    } else {
                        alert(terminKalenderData.strings.error_saving_category);
                    }
                })
                .catch(function () {
                    alert(terminKalenderData.strings.error_saving_category);
                });
        }
        //---------------------------------------------------------------------------------
        function deleteCategory() {
            var categoryID = $('#categoryID').val();
            if (categoryID && confirm(terminKalenderData.strings.confirm_delete_category)) {
                window.TerminKalender.API.deleteCategory(categoryID)
                    .then(function (response) {
                        if (response.success) {
                            loadCategories();
                            $('#category-dialog').dialog('close');

                            // ter_kal_: Inform admin about orphaned events after deletion.
                            var orphaned = response.orphaned_count || 0;
                            if (orphaned > 0) {
                                ter_kal_show_orphan_notice(orphaned);
                            }
                        } else {
                            alert(terminKalenderData.strings.error_saving_category);
                        }
                    }).catch(function () {
                        alert(terminKalenderData.strings.error_saving_category);
                    });
            }
        }

        //---------------------------------------------------------------------------------
        function getCategoryByID(categoryID) {
            var cats = JSON.parse(localStorage.getItem('termin_kalender_kategorien') || '[]');
            return cats.find(function (cat) { return cat['categoryID'] === categoryID; });
        }
        //---------------------------------------------------------------------------------
        function applyDialogStyles(category, dialogType) {
            if (category) {
                $('.ui-dialog-titlebar').css({ backgroundColor: category.backgroundColor, color: category.textColor });
                if (dialogType === 'event') {
                    $('.ui-dialog-title').html(
                        '<span class="dialog_title_icon dashicons ' + category.icon + '"></span>' +
                        '<span>' + (category.label || terminKalenderData.strings.new_category) + '</span>'
                    );
                } else if (dialogType === 'category') {
                    $('.ui-dialog-title').html(
                        '<span class="dialog_title_icon dashicons ' + category.icon + '"></span>' +
                        '<span>' + (category.label || terminKalenderData.strings.new_category) + '</span>'
                    );
                }
            } else {
                $('.ui-dialog-titlebar, .ui-dialog-buttonpane').css({ backgroundColor: '', color: '' });
                if (dialogType === 'event') {
                    $('.ui-dialog-title').text(terminKalenderData.strings.event_title);
                } else if (dialogType === 'category') {
                    $('.ui-dialog-title').text(terminKalenderData.strings.new_category);
                }
            }
        }
        //---------------------------------------------------------------------------------
        if (typeof flatpickr !== 'undefined' && !/Chrome|Edge/.test(navigator.userAgent)) {
            $(".datetime-picker").flatpickr({
                mode: 'single',
                enableTime: true,
                dateFormat: "Y-m-d H:i",
                time_24hr: true,
                utc: true,
                locale: terminKalenderData.ter_kal_lang,
                monthSelectorType: "static",
            });
        } else {
            var inputs = document.querySelectorAll('#event-start, #event-end, #event-until, #exclude-date-chooser');
            inputs.forEach(function (input) {
                input.addEventListener('click', function () {
                    if (typeof input.showPicker === "function") {
                        input.showPicker();
                    } else {
                        input.focus();
                    }
                });
                input.addEventListener('keydown', function (e) {
                    e.preventDefault();
                });
                input.addEventListener('paste', function (e) {
                    e.preventDefault();
                });
            });
        }
        //---------------------------------------------------------------------------------
        $('#event-start, #event-end, #event-until').on('change', function () {
            if (typeof window.TerminKalender?.check_date === 'function') {
                window.TerminKalender.check_date();
            }
            set_yes_for_post_update();
        });
        //--------------------------------------------------------
        $('#create_event_post').on('click', function () {
            $('#create_post').val('yes');
            $('#create_event_post').hide(700);
            $('#post_info').show(700);
        });
        //-------------------------------------
        $('#back_to_calendar_only').on('click', function () {
            $('#create_post').val('');
            $('#post_link').val('');
            $('#show_event_details').show(700);
            $('#bootstrap_button_line').show(700);
            $('#create_event_post').show(700);
            $('#post_info').hide(700);
        });
        //-------------------------------------
        $('#event-allday, #event-location, #event-freq, #event-byweekday, #event-exdate, #event-interval, #event-bysetpos').on('change', function () {
            set_yes_for_post_update();
        });
        //-------------------------------------
        function set_yes_for_post_update() {
            if ($('#post_link').val().trim() !== '') {
                $('#create_post').val('yes');
                $('#create_event_post').hide(700);
                $('#post_info').hide(700);
            }
        }
        //---------------------------------------------------------------------------------
        function updatePreviewMode() {
            const detailsText = $('#event-details').val().trim();
            const isNewOrEmpty = !$('#event-form').attr('data-event-id') || !detailsText;
            if (isNewOrEmpty) {
                $('#event-details').show();
                $('.bootstrap_button_line').show();
                $('#show_preview').hide();
                $('#event-details-html').html(detailsText).show();
            } else {
                $('#event-details').hide();
                $('.bootstrap_button_line').hide();
                $('#show_preview').show().text(terminKalenderData.strings.edit || 'Edit');
                $('#event-details-html').html(detailsText).show();
            }
        }
        $('#show_preview').on('click', function () {
            const isEditing = $('#event-details').is(':visible');
            if (isEditing) {
                $('#event-details').hide();
                $('.bootstrap_button_line').hide();
                $('#event-details-html').html($('#event-details').val());
                $(this).text(terminKalenderData.strings.edit || 'Edit');
            } else {
                $('#event-details').show();
                $('#event-details').trigger('input');
                $('.bootstrap_button_line').show();
                $(this).text('OK');
            }
        });
        $('#event-details').on('input', function () {
            $('#event-details-html').html($(this).val());
            $('#event-details-html').show();
            $('#show_preview').show(700);
        });
        //---------------------------------------------------------------------------------

        // ter_kal_: Show orphaned-events notice after a category is deleted or replaced.
        // count    = number of newly-orphaned events
        // persistent = true → no auto-dismiss (used when notice arrives via page redirect)
        function ter_kal_show_orphan_notice(count, persistent) {
            var $existing = $('#ter-kal-orphan-notice');
            if ($existing.length) {
                $existing.remove();
            }

            var proLink = '';
            if (terminKalenderData.TERMIN_KALENDER_PRO_ON === 'on') {
                // ter_kal_: Build URL to System → Calendar Data Check (PRO only tab).
                var dataCheckUrl = (terminKalenderData.admin_url || '') +
                    'admin.php?page=termin_kalender_system&tab=auditor';
                proLink = ' <a href="' + dataCheckUrl + '" style="font-weight:600;">' +
                    (terminKalenderData.strings.ter_kal_go_to_data_check ||
                     'System \u2192 Calendar Data Check') +
                    '</a>';
            }

            var msg = count === 1
                ? (terminKalenderData.strings.ter_kal_orphan_notice_singular ||
                   '1 event still references this category. It is preserved as historical data.')
                : ((terminKalenderData.strings.ter_kal_orphan_notice_plural ||
                   '{count} events still reference this category. They are preserved as historical data.')
                   .replace('{count}', count));

            var $notice = $('<div id="ter-kal-orphan-notice" role="alert">' +
                '<span class="dashicons dashicons-info" style="vertical-align:middle;margin-right:6px;color:#72aee6;"></span>' +
                '<span>' + msg + '</span>' + proLink +
                '<button type="button" style="float:right;background:none;border:none;cursor:pointer;font-size:16px;line-height:1;" aria-label="Dismiss">&times;</button>' +
                '</div>').css({
                    background: '#f0f6fc',
                    borderLeft: '4px solid #72aee6',
                    padding: '10px 14px',
                    margin: '12px 0 0 0',
                    fontSize: '13px',
                    lineHeight: '1.5'
                });

            $notice.find('button').on('click', function () { $notice.fadeOut(300, function () { $notice.remove(); }); });

            // ter_kal_: Insert after the category row (or as the first child of the calendar admin wrap).
            var $anchor = $('#kategoriezeile');
            if ($anchor.length) {
                $anchor.after($notice);
            } else {
                $('.ter_kal_calendar_admin').first().prepend($notice);
            }

            // ter_kal_: Auto-dismiss after 12 seconds for same-page notices only.
            // Persistent notices (from page redirects) stay until manually dismissed.
            if (!persistent) {
                setTimeout(function () {
                    $notice.fadeOut(700, function () { $notice.remove(); });
                }, 12000);
            }
        }
        window.TerminKalender.UI.ter_kal_show_orphan_notice = ter_kal_show_orphan_notice;

        // ter_kal_: On page load, check if the setup wizard stored a pending orphan count
        // (written to localStorage before redirecting here). Show it persistently so the
        // admin has time to read and act on it, then clear the stored value immediately.
        (function ter_kal_check_pending_orphan_notice() {
            try {
                var pending = localStorage.getItem('ter_kal_pending_orphan_notice');
                if (pending) {
                    var count = parseInt(pending, 10);
                    localStorage.removeItem('ter_kal_pending_orphan_notice');
                    if (count > 0) {
                        // ter_kal_: Wait for DOM to settle before injecting the notice.
                        setTimeout(function () {
                            ter_kal_show_orphan_notice(count, true /* persistent */);
                        }, 600);
                    }
                }
            } catch (e) { /* Ignore localStorage errors */ }
        })();

        // Initial load
        loadCategories();
    });
});
