/**
 * Kurs Booking Admin JavaScript
 *
 * Professional Admin UI interactions for Kurs meta boxes.
 *
 * @package KursBooking
 * @version 2.0.0
 *
 * PHP 8.4 / WordPress 6.8 compatible
 * Vanilla JS - No jQuery dependency (except for Sortable)
 */

'use strict';

/**
 * Kurs Booking Admin Module
 */
const KursBookingAdmin = {
    /**
     * Initialize all admin functionality
     */
    init() {
        this.initProduktartToggle();
        this.initWorkshopModusToggle();
        this.initKursTypeToggle();
        this.initVariantenRepeater();
        this.initDepositToggle();
        this.initCustomFieldsRepeater();
        this.initLogoUpload();
        this.initAbrechnungToggle();
        this.initBookingToggle();
        this.initSortable();
        this.initSevDesk();
        this.initResendEmail();
        this.initAdminCancel();
        this.initEmailTemplateEditor();
        this.initGoogleMapsGenerator();
        this.initMasterdataRepeaters();
        this.initLocationDropdown();
        this.initHorseDropdown();
        this.initVideoKursFields();
        this.initDienstleistungenEditor();
        this.initGlobalFieldFilter();

        // Trigger initial state update
        this.updateConditionalFields();
        this.updateProduktartDependentFields();
    },

    /**
     * Produktart Dropdown Handler
     * Handles changes between A/B/C/D/D1 product types
     */
    initProduktartToggle() {
        const produktartSelect = document.getElementById('kurs_produktart');
        if (!produktartSelect) return;

        produktartSelect.addEventListener('change', () => {
            this.updateProduktartDependentFields();
        });
    },

    /**
     * Workshop-Modus Toggle Handler
     * Handles vor_ort/online/hybrid toggle for Workshop (B)
     */
    initWorkshopModusToggle() {
        const workshopToggle = document.querySelector('.kb-workshop-toggle');
        if (!workshopToggle) return;

        const options = workshopToggle.querySelectorAll('.kb-type-option');
        const hiddenInput = document.getElementById('kurs_workshop_modus');

        options.forEach(option => {
            option.addEventListener('click', () => {
                // Remove active from all
                options.forEach(o => o.classList.remove('active'));

                // Add active to clicked
                option.classList.add('active');

                // Update hidden input
                if (hiddenInput) {
                    hiddenInput.value = option.dataset.modus;
                }

                // Update conditional fields (Online card visibility)
                this.updateConditionalFields();
            });
        });
    },

    /**
     * Update fields based on Produktart selection
     * - Shows/hides Workshop-Modus row for type B
     * - Shows/hides Zoom fields based on type
     * - Auto-sets Buchungsart for D1 (Einzelcoaching)
     */
    updateProduktartDependentFields() {
        const produktartSelect = document.getElementById('kurs_produktart');
        if (!produktartSelect) return;

        const produktart = produktartSelect.value;

        // Workshop-Modus Row (only for type B)
        const workshopModusRow = document.querySelector('.kb-workshop-modus-row');
        if (workshopModusRow) {
            if (produktart === 'workshop') {
                workshopModusRow.style.display = '';
                workshopModusRow.style.opacity = '0';
                requestAnimationFrame(() => {
                    workshopModusRow.style.transition = 'opacity 0.2s ease';
                    workshopModusRow.style.opacity = '1';
                });
            } else {
                workshopModusRow.style.transition = 'opacity 0.2s ease';
                workshopModusRow.style.opacity = '0';
                setTimeout(() => {
                    workshopModusRow.style.display = 'none';
                }, 200);
            }
        }

        // Auto-set Buchungsart for D1 (Einzelcoaching → Kontaktanfrage)
        const buchungsartSelect = document.getElementById('kurs_buchungsart');
        if (buchungsartSelect && produktart === 'einzelcoaching') {
            buchungsartSelect.value = 'anfrage';
            // Disable the select to prevent changes
            buchungsartSelect.disabled = true;

            // Add info hint
            let hint = buchungsartSelect.parentElement.querySelector('.kb-produktart-hint');
            if (!hint) {
                hint = document.createElement('span');
                hint.className = 'kb-produktart-hint kb-hint';
                hint.textContent = 'Bei Einzel-Coaching immer Kontaktanfrage';
                buchungsartSelect.parentElement.appendChild(hint);
            }
        } else if (buchungsartSelect) {
            // Re-enable if not D1
            buchungsartSelect.disabled = false;

            // Remove hint
            const hint = buchungsartSelect.parentElement.querySelector('.kb-produktart-hint');
            if (hint) {
                hint.remove();
            }
        }

        // Zoom fields visibility
        // Show Zoom for: C (Webinar), D (Gruppencoaching)
        // For B (Workshop): only if modus is 'online' or 'hybrid'
        const onlineCard = document.querySelector('.kb-online-card');
        if (onlineCard) {
            let showZoom = false;

            if (['webinar', 'gruppencoaching'].includes(produktart)) {
                // C and D always show Zoom
                showZoom = true;
            } else if (produktart === 'workshop') {
                // B shows Zoom only if online or hybrid
                const workshopModus = document.getElementById('kurs_workshop_modus')?.value || 'vor_ort';
                showZoom = ['online', 'hybrid'].includes(workshopModus);
            }
            // A (kurs) and D1 (einzelcoaching) do not show Zoom

            onlineCard.classList.toggle('kb-hidden', !showZoom);
            onlineCard.classList.toggle('kb-visible', showZoom);
        }

        // Location card visibility
        // Show for: A (Kurs), D1 (Einzelcoaching)
        // For B (Workshop): only if modus is 'vor_ort' or 'hybrid'
        const locationCard = document.querySelector('.kb-location-card');
        if (locationCard) {
            let showLocation = false;

            if (['kurs', 'einzelcoaching'].includes(produktart)) {
                // A and D1 always show location
                showLocation = true;
            } else if (produktart === 'workshop') {
                // B shows location only if vor_ort or hybrid
                const workshopModus = document.getElementById('kurs_workshop_modus')?.value || 'vor_ort';
                showLocation = ['vor_ort', 'hybrid'].includes(workshopModus);
            }
            // C (Webinar) and D (Gruppencoaching) are online-only

            locationCard.classList.toggle('kb-hidden', !showLocation);
            locationCard.classList.toggle('kb-visible', showLocation);
        }

        // Video-Kurs specific fields
        this.updateVideoKursFields(produktart);
    },

    /**
     * Kurs Type Toggle (vor_ort, online, hybrid) - Button style
     * Note: This is the original kurs_type toggle, not the workshop modus toggle
     */
    initKursTypeToggle() {
        // Only select the kurs_type toggle, not workshop-modus toggle
        const container = document.querySelector('.kb-type-toggle:not(.kb-workshop-toggle)');
        if (!container) return;

        const options = container.querySelectorAll('.kb-type-option');
        const hiddenInput = container.querySelector('input[name="kurs_type"]');

        options.forEach(option => {
            option.addEventListener('click', () => {
                // Remove active from all
                options.forEach(o => o.classList.remove('active'));

                // Add active to clicked
                option.classList.add('active');

                // Update hidden input
                if (hiddenInput) {
                    hiddenInput.value = option.dataset.type;
                }

                // Update conditional fields
                this.updateConditionalFields();
            });
        });

        // Also handle legacy radio inputs if present
        const typeInputs = document.querySelectorAll('input[name="kurs_type"][type="radio"]');
        typeInputs.forEach(input => {
            input.addEventListener('change', () => {
                this.updateConditionalFields();
            });
        });
    },

    /**
     * Update all conditional fields based on current kurs type
     */
    updateConditionalFields() {
        // Get current type from button toggle or radio inputs
        let kursType = 'vor_ort';

        // Only get kurs_type toggle, not workshop-modus toggle
        const kursTypeToggle = document.querySelector('.kb-type-toggle:not(.kb-workshop-toggle)');
        const activeOption = kursTypeToggle?.querySelector('.kb-type-option.active');
        if (activeOption && activeOption.dataset.type) {
            kursType = activeOption.dataset.type;
        } else {
            const checkedRadio = document.querySelector('input[name="kurs_type"]:checked');
            if (checkedRadio) {
                kursType = checkedRadio.value;
            }
        }

        // Location card (vor_ort, hybrid)
        const locationCard = document.querySelector('.kb-location-card');
        if (locationCard) {
            const showLocation = ['vor_ort', 'hybrid'].includes(kursType);
            locationCard.classList.toggle('kb-hidden', !showLocation);
            locationCard.classList.toggle('kb-visible', showLocation);
        }

        // Online card (online, hybrid)
        const onlineCard = document.querySelector('.kb-online-card');
        if (onlineCard) {
            const showOnline = ['online', 'hybrid'].includes(kursType);
            onlineCard.classList.toggle('kb-hidden', !showOnline);
            onlineCard.classList.toggle('kb-visible', showOnline);
        }

        // Generic data-show-for elements
        document.querySelectorAll('[data-show-for]').forEach(field => {
            const showFor = field.dataset.showFor.split(',').map(s => s.trim());
            const shouldShow = showFor.includes(kursType);
            field.classList.toggle('kb-hidden', !shouldShow);
            field.classList.toggle('kb-visible', shouldShow);

            // Also set display for transition support
            if (shouldShow) {
                field.style.display = '';
            }
        });
    },

    /**
     * Initialize price variants repeater with professional UI
     */
    initVariantenRepeater() {
        const container = document.getElementById('kb-variants-container');
        const addButton = document.getElementById('kb-add-variant');

        if (!container || !addButton) return;

        // Initialize auto_invoice toggles for existing variants.
        container.querySelectorAll('.kb-variant').forEach(variantEl => {
            this.initAutoInvoiceToggle(variantEl);
        });

        // Add new variant
        addButton.addEventListener('click', (e) => {
            e.preventDefault();
            this.addVariant(container);
        });

        // Remove variant (event delegation)
        container.addEventListener('click', (e) => {
            const removeBtn = e.target.closest('.kb-variant-remove');
            if (removeBtn) {
                e.preventDefault();
                const variant = removeBtn.closest('.kb-variant');
                const variants = container.querySelectorAll('.kb-variant');

                if (variants.length > 1) {
                    // Animate removal
                    variant.style.overflow = 'hidden';
                    variant.style.transition = 'all 0.2s ease';
                    variant.style.height = variant.offsetHeight + 'px';

                    requestAnimationFrame(() => {
                        variant.style.height = '0';
                        variant.style.opacity = '0';
                        variant.style.marginBottom = '0';
                        variant.style.padding = '0';
                    });

                    setTimeout(() => {
                        variant.remove();
                        this.reindexVariants(container);
                    }, 200);
                } else {
                    this.showNotice('Mindestens ein Ticket ist erforderlich.', 'warning');
                }
            }
        });

        // Update title on name input change
        container.addEventListener('input', (e) => {
            if (e.target.classList.contains('kb-variant-name')) {
                const variant = e.target.closest('.kb-variant');
                const titleEl = variant.querySelector('.kb-variant-title');
                if (titleEl) {
                    titleEl.textContent = e.target.value || 'Neues Ticket';
                }
            }
        });
    },

    /**
     * Add new variant with animation
     */
    addVariant(container) {
        const existingVariants = container.querySelectorAll('.kb-variant');
        const newIndex = existingVariants.length;
        const newId = newIndex + 1;

        // Get default hint from settings (if available via localized data).
        const defaultHint = window.kursBookingAdmin?.defaultManualPaymentHint || 'Wird vor Ort verrechnet';

        const template = `
            <div class="kb-variant" data-index="${newIndex}" style="opacity: 0; transform: translateY(-10px);">
                <div class="kb-variant-header">
                    <div class="kb-variant-handle">
                        <span class="dashicons dashicons-move"></span>
                        <span class="kb-variant-number">${newId}</span>
                        <span class="kb-variant-title">Neues Ticket</span>
                    </div>
                    <button type="button" class="kb-variant-remove">
                        <span class="dashicons dashicons-trash"></span>
                        Entfernen
                    </button>
                </div>
                <div class="kb-variant-body">
                    <input type="hidden" name="kurs_varianten[${newIndex}][id]" value="${newId}">
                    <div class="kb-variant-grid">
                        <div class="kb-field">
                            <label>Ticket-Name</label>
                            <input type="text"
                                   name="kurs_varianten[${newIndex}][name]"
                                   class="kb-variant-name"
                                   value=""
                                   placeholder="z.B. Standardticket, Fruehbucher">
                        </div>
                        <div class="kb-field kb-price-input">
                            <label>Preis</label>
                            <input type="number"
                                   name="kurs_varianten[${newIndex}][preis]"
                                   value="0"
                                   min="0"
                                   step="0.01"
                                   placeholder="0,00">
                        </div>
                        <div class="kb-field">
                            <label>Limit</label>
                            <input type="number"
                                   name="kurs_varianten[${newIndex}][limit]"
                                   value="0"
                                   min="0"
                                   placeholder="0">
                            <span class="kb-hint">0 = unbegrenzt</span>
                        </div>
                    </div>
                    <div class="kb-variant-options">
                        <label class="kb-checkbox-label">
                            <input type="checkbox"
                                   name="kurs_varianten[${newIndex}][per_day]"
                                   value="1">
                            Pro Tag berechnen
                            <span class="kb-hint-inline">(Preis × Kurstage)</span>
                        </label>
                        <label class="kb-checkbox-label">
                            <input type="checkbox"
                                   name="kurs_varianten[${newIndex}][auto_invoice]"
                                   value="1"
                                   checked>
                            Automatisch verrechnen
                            <span class="kb-hint-inline">(sevDesk Rechnung)</span>
                        </label>
                    </div>
                    <div class="kb-variant-hint-row" style="display:none;">
                        <label>Hinweis</label>
                        <input type="text"
                               name="kurs_varianten[${newIndex}][hinweis]"
                               value=""
                               placeholder="${defaultHint}"
                               class="regular-text">
                        <span class="kb-hint">Leer = globaler Standard aus Einstellungen</span>
                    </div>
                    <!-- Sprint 4.11: Placeholder for extra field UI -->
                    <div class="kb-variant-extra-field-container" data-variant-index="${newIndex}"></div>
                </div>
            </div>
        `;

        // eslint-disable-next-line no-unsanitized/method -- Template uses only internally generated index numbers, no user input
        container.insertAdjacentHTML('beforeend', template);

        // Animate in
        const newVariant = container.lastElementChild;
        requestAnimationFrame(() => {
            newVariant.style.transition = 'all 0.2s ease';
            newVariant.style.opacity = '1';
            newVariant.style.transform = 'translateY(0)';
        });

        // Initialize auto_invoice toggle for the new variant.
        this.initAutoInvoiceToggle(newVariant);

        // Sprint 4.11: Dispatch event for custom fields module to add extra field UI.
        const event = new CustomEvent('kurs_booking_variant_added', {
            detail: { variant: newVariant, index: newIndex },
            bubbles: true
        });
        container.dispatchEvent(event);

        // Focus name input
        setTimeout(() => {
            newVariant.querySelector('.kb-variant-name')?.focus();
        }, 200);
    },

    /**
     * Initialize auto_invoice toggle for a variant element.
     */
    initAutoInvoiceToggle(variantEl) {
        const autoInvoiceCheckbox = variantEl.querySelector('input[name$="[auto_invoice]"]');
        const hintRow = variantEl.querySelector('.kb-variant-hint-row');

        if (autoInvoiceCheckbox && hintRow) {
            autoInvoiceCheckbox.addEventListener('change', () => {
                hintRow.style.display = autoInvoiceCheckbox.checked ? 'none' : '';
            });
        }
    },

    /**
     * Reindex variants after removal/reorder
     */
    reindexVariants(container) {
        const variants = container.querySelectorAll('.kb-variant');

        variants.forEach((variant, index) => {
            const newId = index + 1;

            // Update data attribute
            variant.dataset.index = index;

            // Update number badge
            const numberEl = variant.querySelector('.kb-variant-number');
            if (numberEl) {
                numberEl.textContent = newId;
            }

            // Update input names
            variant.querySelectorAll('input, select').forEach(input => {
                const name = input.name;
                if (name) {
                    input.name = name.replace(/\[\d+\]/, `[${index}]`);
                }
            });

            // Update hidden ID
            const idInput = variant.querySelector('input[name$="[id]"]');
            if (idInput) {
                idInput.value = newId;
            }
        });
    },

    /**
     * Initialize Sortable for variants and custom fields (if jQuery UI available)
     */
    initSortable() {
        if (typeof jQuery === 'undefined' || typeof jQuery.fn.sortable === 'undefined') {
            return;
        }

        // Sortable for ticket variants
        const variantsContainer = document.getElementById('kb-variants-container');
        if (variantsContainer) {
            jQuery(variantsContainer).sortable({
                handle: '.kb-variant-handle',
                placeholder: 'kb-variant kb-sortable-placeholder',
                opacity: 0.7,
                tolerance: 'pointer',
                update: () => {
                    this.reindexVariants(variantsContainer);
                }
            });
        }

        // Sortable for custom booking fields
        const fieldsContainer = document.getElementById('kurs-booking-fields-container');
        if (fieldsContainer) {
            jQuery(fieldsContainer).sortable({
                handle: '.kurs-booking-field-header',
                placeholder: 'kurs-booking-field-row kb-sortable-placeholder',
                opacity: 0.7,
                tolerance: 'pointer',
                update: () => {
                    this.reindexFields();
                }
            });
        }
    },

    /**
     * Toggle deposit percentage field based on checkbox
     */
    initDepositToggle() {
        const checkbox = document.getElementById('kurs_deposit_enabled');
        const detailsSection = document.querySelector('.kb-deposit-details');

        if (!checkbox) return;

        const toggle = () => {
            const isEnabled = checkbox.checked;

            if (detailsSection) {
                if (isEnabled) {
                    detailsSection.style.display = '';
                    detailsSection.style.opacity = '0';
                    requestAnimationFrame(() => {
                        detailsSection.style.transition = 'opacity 0.2s ease';
                        detailsSection.style.opacity = '1';
                    });
                } else {
                    detailsSection.style.transition = 'opacity 0.2s ease';
                    detailsSection.style.opacity = '0';
                    setTimeout(() => {
                        detailsSection.style.display = 'none';
                    }, 200);
                }
            }

            // Also handle legacy data-requires
            const percentField = document.querySelector('[data-requires="kurs_deposit_enabled"]');
            if (percentField) {
                percentField.classList.toggle('disabled', !isEnabled);
            }
        };

        checkbox.addEventListener('change', toggle);

        // Initial state
        if (detailsSection && !checkbox.checked) {
            detailsSection.style.display = 'none';
        }
    },

    /**
     * Toggle deposit fields based on abrechnung type
     */
    initAbrechnungToggle() {
        const select = document.getElementById('kurs_abrechnung');
        const depositWrapper = document.querySelector('.kb-deposit-wrapper');
        const depositFields = document.querySelector('.kurs-deposit-fields');

        if (!select) return;

        const toggle = () => {
            const showDeposit = select.value === 'eigen';

            [depositWrapper, depositFields].forEach(el => {
                if (!el) return;

                if (showDeposit) {
                    el.classList.remove('kb-hidden');
                    el.classList.add('kb-visible');
                    el.style.display = '';
                } else {
                    el.classList.add('kb-hidden');
                    el.classList.remove('kb-visible');
                }
            });
        };

        select.addEventListener('change', toggle);
        toggle();
    },

    /**
     * Booking enabled toggle with visual feedback
     */
    initBookingToggle() {
        const toggle = document.getElementById('kb-booking-toggle');
        if (!toggle) return;

        const checkbox = toggle.querySelector('input[type="checkbox"]');
        const statusEl = document.getElementById('kb-booking-status');

        if (!checkbox) return;

        // Make entire toggle clickable
        toggle.addEventListener('click', (e) => {
            if (e.target.type !== 'checkbox') {
                checkbox.checked = !checkbox.checked;
                checkbox.dispatchEvent(new Event('change'));
            }
        });

        // Update status display
        checkbox.addEventListener('change', () => {
            const isEnabled = checkbox.checked;

            if (statusEl) {
                // Clear existing content safely
                while (statusEl.firstChild) {
                    statusEl.removeChild(statusEl.firstChild);
                }

                const icon = document.createElement('span');
                const text = document.createTextNode(isEnabled ? ' Aktiv' : ' Inaktiv');

                if (isEnabled) {
                    statusEl.className = 'kb-status kb-status-active';
                    icon.className = 'dashicons dashicons-yes-alt';
                } else {
                    statusEl.className = 'kb-status kb-status-inactive';
                    icon.className = 'dashicons dashicons-minus';
                }

                statusEl.appendChild(icon);
                statusEl.appendChild(text);
            }
        });
    },

    /**
     * Initialize custom fields repeater on settings page
     */
    initCustomFieldsRepeater() {
        const container = document.getElementById('kurs-booking-fields-container');
        const addButton = document.getElementById('kurs-booking-add-field');
        const template = document.getElementById('kurs-booking-field-template');

        if (!container || !addButton || !template) return;

        // Add new field
        addButton.addEventListener('click', () => {
            const existingFields = container.querySelectorAll('.kurs-booking-field-row');
            const newIndex = existingFields.length;

            const html = template.innerHTML.replace(/__INDEX__/g, newIndex);

            // eslint-disable-next-line no-unsanitized/method -- HTML from script template element, index is array length
            container.insertAdjacentHTML('beforeend', html);

            // Bind events to new field
            const newField = container.lastElementChild;
            this.bindFieldEvents(newField);

            // Focus the label field
            newField.querySelector('.kurs-booking-field-label')?.focus();
        });

        // Bind events to existing fields
        container.querySelectorAll('.kurs-booking-field-row').forEach(field => {
            this.bindFieldEvents(field);
        });
    },

    /**
     * Bind events to a custom field row
     */
    bindFieldEvents(field) {
        // Remove button
        const removeBtn = field.querySelector('.kurs-booking-remove-field');
        removeBtn?.addEventListener('click', () => {
            field.remove();
            this.reindexFields();
        });

        // Insert after button
        const insertBtn = field.querySelector('.kurs-booking-insert-field');
        insertBtn?.addEventListener('click', () => {
            this.insertFieldAfter(field);
        });

        // Active toggle
        const activeCheckbox = field.querySelector('.kurs-booking-field-active-checkbox');
        activeCheckbox?.addEventListener('change', () => {
            if (activeCheckbox.checked) {
                field.classList.remove('kurs-booking-field-inactive');
            } else {
                field.classList.add('kurs-booking-field-inactive');
            }
        });

        // Options popup
        const optionsBtn = field.querySelector('.kurs-booking-options-btn');
        const optionsPopup = field.querySelector('.kurs-booking-options-popup');
        const optionsClose = field.querySelector('.kurs-booking-options-close');

        optionsBtn?.addEventListener('click', (e) => {
            e.stopPropagation();
            // Close all other popups
            document.querySelectorAll('.kurs-booking-options-popup.active').forEach(p => {
                if (p !== optionsPopup) p.classList.remove('active');
            });
            optionsPopup?.classList.toggle('active');
        });

        optionsClose?.addEventListener('click', () => {
            optionsPopup?.classList.remove('active');
        });

        // Close popup on click outside
        document.addEventListener('click', (e) => {
            if (optionsPopup?.classList.contains('active') &&
                !optionsPopup.contains(e.target) &&
                !optionsBtn.contains(e.target)) {
                optionsPopup.classList.remove('active');
            }
        });

        // Type change - show/hide options and page selector
        const typeSelect = field.querySelector('.kurs-booking-field-type');
        const optionsDiv = field.querySelector('.kurs-booking-field-options');
        const pageOptionDiv = field.querySelector('.kurs-booking-field-page-option');

        typeSelect?.addEventListener('change', () => {
            const showOptions = ['select', 'radio'].includes(typeSelect.value);
            const showPage = typeSelect.value === 'agreement';
            if (optionsDiv) {
                optionsDiv.style.display = showOptions ? 'block' : 'none';
            }
            if (pageOptionDiv) {
                pageOptionDiv.style.display = showPage ? 'block' : 'none';
            }
        });

        // Update title on label change
        const labelInput = field.querySelector('.kurs-booking-field-label');
        const titleSpan = field.querySelector('.kurs-booking-field-title');

        labelInput?.addEventListener('input', () => {
            titleSpan.textContent = labelInput.value || 'Neues Feld';
        });

        // Click-to-copy for field name badge
        const nameBadge = field.querySelector('.kurs-booking-field-name-badge');
        if (nameBadge) {
            nameBadge.addEventListener('click', (e) => {
                e.stopPropagation();
                const fieldName = nameBadge.dataset.fieldname || nameBadge.textContent;

                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(fieldName).then(() => {
                        // Visual feedback
                        const originalText = nameBadge.textContent;
                        nameBadge.textContent = '✓ Kopiert!';
                        nameBadge.style.backgroundColor = '#46b450';
                        nameBadge.style.color = '#fff';

                        setTimeout(() => {
                            nameBadge.textContent = originalText;
                            nameBadge.style.backgroundColor = '';
                            nameBadge.style.color = '';
                        }, 1500);
                    }).catch(() => {
                        // Fallback: select text
                        this.selectText(nameBadge);
                    });
                } else {
                    // Fallback for older browsers
                    this.selectText(nameBadge);
                }
            });
        }

        // Sprint 8.2: Basis-Feld toggle - hide/show produktarten matrix
        const basisFieldCheckbox = field.querySelector('.kurs-booking-basis-field-checkbox');
        const produktartenRow = field.querySelector('.kurs-booking-produktarten-row');

        basisFieldCheckbox?.addEventListener('change', () => {
            if (produktartenRow) {
                produktartenRow.style.display = basisFieldCheckbox.checked ? 'none' : 'block';
            }
        });

        // Sprint 8.2: Produktarten Alle/Keine buttons
        const produktartenAllBtn = field.querySelector('.kurs-booking-produktarten-all');
        const produktartenNoneBtn = field.querySelector('.kurs-booking-produktarten-none');
        const produktartenMatrix = field.querySelector('.kurs-booking-produktarten-matrix');

        produktartenAllBtn?.addEventListener('click', () => {
            produktartenMatrix?.querySelectorAll('input[type="checkbox"]').forEach(cb => {
                cb.checked = true;
            });
            this.updateFieldBadges(field);
        });

        produktartenNoneBtn?.addEventListener('click', () => {
            produktartenMatrix?.querySelectorAll('input[type="checkbox"]').forEach(cb => {
                cb.checked = false;
            });
            this.updateFieldBadges(field);
        });

        // Live-Update: Badges aktualisieren wenn Checkbox geändert wird
        produktartenMatrix?.querySelectorAll('input[type="checkbox"]').forEach(cb => {
            cb.addEventListener('change', () => {
                this.updateFieldBadges(field);
            });
        });

        // Live-Update: Basis-Feld Checkbox
        basisFieldCheckbox?.addEventListener('change', () => {
            this.updateFieldBadges(field);
        });
    },

    /**
     * Update header badges based on checked produktarten
     * @param {Element} field - Field row element
     */
    updateFieldBadges(field) {
        const header = field.querySelector('.kurs-booking-field-header-left');
        if (!header) return;

        // Remove existing badges (except title and toggle)
        header.querySelectorAll('.kurs-booking-field-type-badge').forEach(badge => badge.remove());

        const basisCheckbox = field.querySelector('.kurs-booking-basis-field-checkbox');
        const titleSpan = header.querySelector('.kurs-booking-field-title');

        // Basis field badge
        if (basisCheckbox?.checked) {
            const badge = document.createElement('span');
            badge.className = 'kurs-booking-field-type-badge kurs-booking-field-type-basis';
            badge.title = 'Wird bei allen Produktarten angezeigt';
            badge.innerHTML = '<span class="kurs-booking-badge-dot" style="background-color: #666;"></span>Basis';
            titleSpan?.after(badge);
            return;
        }

        // Get checked produktarten
        const checkedBoxes = field.querySelectorAll('.kurs-booking-produktarten-matrix input[type="checkbox"]:checked');

        if (checkedBoxes.length === 0) {
            // No selection = all
            const badge = document.createElement('span');
            badge.className = 'kurs-booking-field-type-badge kurs-booking-field-type-all';
            badge.title = 'Wird bei allen Produktarten angezeigt';
            badge.innerHTML = '<span class="kurs-booking-badge-dot" style="background-color: #4CAF50;"></span>Alle';
            titleSpan?.after(badge);
            return;
        }

        // Create badge for each checked produktart
        const badges = [];
        checkedBoxes.forEach(cb => {
            const name = cb.dataset.name || cb.value;
            const color = cb.dataset.color || '#999';
            const label = cb.dataset.label || '';

            const badge = document.createElement('span');
            badge.className = 'kurs-booking-field-type-badge';
            badge.title = label + ' ' + name;
            badge.innerHTML = `<span class="kurs-booking-badge-dot" style="background-color: ${color};"></span>${name}`;
            badges.push(badge);
        });

        // Insert badges after title
        let insertAfter = titleSpan;
        badges.forEach(badge => {
            insertAfter?.after(badge);
            insertAfter = badge;
        });
    },

    /**
     * Select text in an element (fallback for clipboard)
     */
    selectText(element) {
        const range = document.createRange();
        range.selectNodeContents(element);
        const selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    },

    /**
     * Reindex custom fields after removal
     */
    reindexFields() {
        const container = document.getElementById('kurs-booking-fields-container');
        if (!container) return;

        const fields = container.querySelectorAll('.kurs-booking-field-row');
        fields.forEach((field, index) => {
            field.dataset.index = index;

            // Update input names
            field.querySelectorAll('input, select, textarea').forEach(input => {
                const name = input.name;
                if (name) {
                    input.name = name.replace(/\[\d+\]/, `[${index}]`);
                }
            });
        });
    },

    /**
     * Insert a new field after the specified field row
     */
    insertFieldAfter(afterField) {
        const container = document.getElementById('kurs-booking-fields-container');
        const template = document.getElementById('kurs-booking-field-template');

        if (!container || !template) return;

        // Get temporary index (will be reindexed)
        const tempIndex = Date.now();

        const html = template.innerHTML.replace(/__INDEX__/g, tempIndex);

        // eslint-disable-next-line no-unsanitized/method -- HTML from script template element, index is timestamp
        afterField.insertAdjacentHTML('afterend', html);

        // Reindex all fields
        this.reindexFields();

        // Get the newly inserted field and bind events
        const newField = afterField.nextElementSibling;
        if (newField && newField.classList.contains('kurs-booking-field-row')) {
            this.bindFieldEvents(newField);

            // Focus the label field
            newField.querySelector('.kurs-booking-field-label')?.focus();

            // Scroll into view
            newField.scrollIntoView({ behavior: 'smooth', block: 'center' });

            // Visual highlight
            newField.style.backgroundColor = 'rgba(0, 115, 170, 0.1)';
            setTimeout(() => {
                newField.style.transition = 'background-color 0.5s ease';
                newField.style.backgroundColor = '';
            }, 100);
        }
    },

    /**
     * Initialize logo upload using WordPress media library
     */
    initLogoUpload() {
        const uploadBtn = document.getElementById('kurs-booking-upload-logo');
        const removeBtn = document.getElementById('kurs-booking-remove-logo');
        const input = document.getElementById('kurs_booking_logo');

        if (!uploadBtn || !input) return;

        // Check if wp.media is available
        if (typeof wp === 'undefined' || typeof wp.media === 'undefined') {
            console.warn('WordPress media library not available');
            return;
        }

        let mediaFrame = null;

        uploadBtn.addEventListener('click', (e) => {
            e.preventDefault();

            // Create media frame if not exists
            if (!mediaFrame) {
                mediaFrame = wp.media({
                    title: 'Logo auswählen',
                    button: { text: 'Logo verwenden' },
                    multiple: false,
                    library: { type: 'image' }
                });

                mediaFrame.on('select', () => {
                    const attachment = mediaFrame.state().get('selection').first().toJSON();
                    input.value = attachment.id;

                    // Update preview (DOM-safe)
                    let preview = document.querySelector('.kurs-booking-logo-preview');
                    const imgUrl = attachment.sizes?.medium?.url || attachment.url;

                    // Create img element safely
                    const img = document.createElement('img');
                    img.src = imgUrl;
                    img.alt = '';

                    if (preview) {
                        // Clear and add new image
                        while (preview.firstChild) {
                            preview.removeChild(preview.firstChild);
                        }
                        preview.appendChild(img);
                    } else {
                        preview = document.createElement('div');
                        preview.className = 'kurs-booking-logo-preview';
                        preview.appendChild(img);
                        uploadBtn.parentElement.insertBefore(preview, uploadBtn);
                    }

                    // Show remove button
                    if (removeBtn) {
                        removeBtn.style.display = '';
                    }
                });
            }

            mediaFrame.open();
        });

        // Remove logo
        removeBtn?.addEventListener('click', (e) => {
            e.preventDefault();
            input.value = '0';

            const preview = document.querySelector('.kurs-booking-logo-preview');
            preview?.remove();
            removeBtn.style.display = 'none';
        });
    },

    /**
     * Initialize sevDesk integration functionality
     */
    initSevDesk() {
        this.initSevDeskConnectionTest();
        this.initSevDeskManualInvoice();
    },

    /**
     * sevDesk Connection Test
     */
    initSevDeskConnectionTest() {
        const testButton = document.getElementById('kurs-booking-test-sevdesk');
        const resultSpan = document.getElementById('kurs-booking-sevdesk-result');

        if (!testButton) return;

        testButton.addEventListener('click', (e) => {
            e.preventDefault();

            testButton.disabled = true;
            if (resultSpan) {
                resultSpan.textContent = 'Teste Verbindung...';
                resultSpan.style.color = '';
                resultSpan.className = '';
            }

            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'kurs_booking_test_sevdesk_connection',
                    nonce: window.kursBookingAdmin?.nonce || ''
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (resultSpan) {
                        resultSpan.textContent = '✓ ' + data.data.message;
                        resultSpan.style.color = '#46b450';
                        resultSpan.className = 'success';
                    }

                    // Auto-fill user ID if empty
                    const userIdField = document.getElementById('kurs_booking_sevdesk_user_id');
                    if (userIdField && !userIdField.value && data.data.user_id) {
                        userIdField.value = data.data.user_id;
                    }
                } else {
                    if (resultSpan) {
                        resultSpan.textContent = '✗ ' + (data.data?.message || 'Verbindung fehlgeschlagen');
                        resultSpan.style.color = '#dc3232';
                        resultSpan.className = 'error';
                    }
                }
            })
            .catch(error => {
                if (resultSpan) {
                    resultSpan.textContent = '✗ Verbindungsfehler';
                    resultSpan.style.color = '#dc3232';
                    resultSpan.className = 'error';
                }
                console.error('sevDesk test error:', error);
            })
            .finally(() => {
                testButton.disabled = false;
            });
        });
    },

    /**
     * sevDesk Manual Invoice Creation
     */
    initSevDeskManualInvoice() {
        document.querySelectorAll('.kurs-booking-create-invoice').forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();

                const buchungId = button.dataset.buchungId;
                if (!buchungId) return;

                if (!confirm('Soll eine sevDesk-Rechnung für diese Buchung erstellt werden?')) {
                    return;
                }

                button.disabled = true;
                const originalText = button.textContent;
                button.textContent = 'Erstelle...';

                fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'kurs_booking_create_sevdesk_invoice',
                        nonce: window.kursBookingAdmin?.nonce || '',
                        buchung_id: buchungId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        this.showNotice(data.data.message, 'success');
                        // Reload page to show updated meta box
                        setTimeout(() => window.location.reload(), 1500);
                    } else {
                        this.showNotice('Fehler: ' + (data.data?.message || 'Unbekannter Fehler'), 'error');
                        button.disabled = false;
                        button.textContent = originalText;
                    }
                })
                .catch(error => {
                    this.showNotice('Verbindungsfehler', 'error');
                    button.disabled = false;
                    button.textContent = originalText;
                    console.error('sevDesk invoice error:', error);
                });
            });
        });
    },

    /**
     * Initialize Resend Email functionality
     */
    initResendEmail() {
        const buttons = document.querySelectorAll('.kurs-booking-resend-email');

        buttons.forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();

                const buchungId = button.dataset.buchungId;
                const nonce = button.dataset.nonce;

                // Store original content safely
                const originalContent = [];
                while (button.firstChild) {
                    originalContent.push(button.removeChild(button.firstChild));
                }

                // Disable button and show loading (DOM-safe)
                button.disabled = true;
                const spinner = document.createElement('span');
                spinner.className = 'dashicons dashicons-update spin';
                spinner.style.animation = 'spin 1s linear infinite';
                button.appendChild(spinner);
                button.appendChild(document.createTextNode(' Sende...'));

                // Send AJAX request
                fetch(ajaxurl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'kurs_booking_resend_email',
                        buchung_id: buchungId,
                        nonce: nonce
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        this.showNotice(data.data.message, 'success');

                        // Update last sent time display
                        const lastSentEl = button.nextElementSibling;
                        if (lastSentEl && lastSentEl.tagName === 'SMALL') {
                            const now = new Date();
                            const formatted = now.toLocaleString('de-DE', {
                                day: '2-digit',
                                month: '2-digit',
                                year: 'numeric',
                                hour: '2-digit',
                                minute: '2-digit'
                            });
                            lastSentEl.textContent = 'Zuletzt: ' + formatted;
                        }
                    } else {
                        this.showNotice(data.data?.message || 'Fehler beim Senden', 'error');
                    }
                })
                .catch(error => {
                    this.showNotice('Verbindungsfehler', 'error');
                    console.error('Resend email error:', error);
                })
                .finally(() => {
                    button.disabled = false;
                    // Restore original content safely
                    while (button.firstChild) {
                        button.removeChild(button.firstChild);
                    }
                    originalContent.forEach(node => button.appendChild(node));
                });
            });
        });
    },

    /**
     * Initialize Admin Cancel functionality
     */
    initAdminCancel() {
        const buttons = document.querySelectorAll('.kurs-booking-admin-cancel');
        const dialogEl = document.getElementById('kurs-booking-cancel-dialog');

        if (!dialogEl) return;

        buttons.forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();

                const buchungId = button.dataset.buchungId;
                const nonce = button.dataset.nonce;
                const feePercent = parseInt(button.dataset.feePercent) || 0;
                const canCancel = button.dataset.canCancel === '1';

                // Set fee info
                const feeInfo = dialogEl.querySelector('.cancel-fee-info');
                if (feeInfo) {
                    feeInfo.textContent = `Berechnete Stornogebühr: ${feePercent}%`;
                }

                // Set default fee in override field
                const feeInput = dialogEl.querySelector('#cancel-fee-percent');
                if (feeInput) {
                    feeInput.value = feePercent;
                }

                // Toggle override checkbox
                const overrideCheckbox = dialogEl.querySelector('#cancel-fee-override');
                const overrideFields = dialogEl.querySelector('#cancel-fee-override-fields');

                if (overrideCheckbox && overrideFields) {
                    overrideCheckbox.checked = false;
                    overrideFields.style.display = 'none';

                    overrideCheckbox.addEventListener('change', () => {
                        overrideFields.style.display = overrideCheckbox.checked ? 'block' : 'none';
                    });
                }

                // Show confirmation dialog
                const confirmed = confirm(
                    canCancel
                        ? 'Möchten Sie diese Buchung wirklich stornieren?\n\nStornogebühr: ' + feePercent + '%'
                        : 'ACHTUNG: Stornierung nicht empfohlen!\n\nMöchten Sie dennoch fortfahren?'
                );

                if (!confirmed) return;

                // Check for fee override
                let finalFeePercent = null;
                if (overrideCheckbox?.checked && feeInput) {
                    finalFeePercent = parseInt(feeInput.value) || 0;
                }

                // Check for replacement participant
                const replacementCheckbox = dialogEl.querySelector('#cancel-has-replacement');
                const hasReplacement = replacementCheckbox?.checked || false;

                const notes = dialogEl.querySelector('#cancel-notes')?.value || '';

                // Store original content and disable button (DOM-safe)
                const originalContent = [];
                while (button.firstChild) {
                    originalContent.push(button.removeChild(button.firstChild));
                }
                button.disabled = true;
                const spinner = document.createElement('span');
                spinner.className = 'dashicons dashicons-update spin';
                spinner.style.animation = 'spin 1s linear infinite';
                button.appendChild(spinner);
                button.appendChild(document.createTextNode(' Storniere...'));

                // Build request body
                const body = new URLSearchParams({
                    action: 'kurs_booking_admin_cancel',
                    buchung_id: buchungId,
                    nonce: nonce,
                    notes: notes,
                    has_replacement: hasReplacement ? '1' : '0'
                });

                if (finalFeePercent !== null) {
                    body.append('fee_percent', finalFeePercent);
                }

                // Send AJAX request
                fetch(ajaxurl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: body
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        this.showNotice(data.data.message, 'success');

                        // Reload page to show updated status
                        setTimeout(() => {
                            window.location.reload();
                        }, 1000);
                    } else {
                        this.showNotice(data.data?.message || 'Fehler bei der Stornierung', 'error');
                        button.disabled = false;
                        // Restore original content safely
                        while (button.firstChild) {
                            button.removeChild(button.firstChild);
                        }
                        originalContent.forEach(node => button.appendChild(node));
                    }
                })
                .catch(error => {
                    this.showNotice('Verbindungsfehler', 'error');
                    button.disabled = false;
                    // Restore original content safely
                    while (button.firstChild) {
                        button.removeChild(button.firstChild);
                    }
                    originalContent.forEach(node => button.appendChild(node));
                    console.error('Admin cancel error:', error);
                });
            });
        });
    },

    /**
     * Initialize Email Template Editor functionality
     */
    initEmailTemplateEditor() {
        this.initVariableInsertion();
        this.initEmailPreview();
        this.initEmailReset();
        this.initLoadDefaultTemplate();
        this.initImportMecTemplates();
    },

    /**
     * Variable insertion into wp_editor
     */
    initVariableInsertion() {
        const variableButtons = document.querySelectorAll('.kurs-booking-variable-btn');

        if (!variableButtons.length) return;

        variableButtons.forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();

                const variable = button.dataset.variable;
                if (!variable) return;

                // Find the active editor
                const editorWrapper = document.querySelector('.kurs-booking-email-template-editor');
                if (!editorWrapper) return;

                // Get the editor ID from the textarea
                const textarea = editorWrapper.querySelector('textarea[id^="kurs_booking_email_tpl_"]');
                if (!textarea) return;

                const editorId = textarea.id;

                // Try to insert into TinyMCE visual editor
                if (typeof tinymce !== 'undefined') {
                    const editor = tinymce.get(editorId);
                    if (editor && !editor.isHidden()) {
                        editor.insertContent(variable);
                        editor.focus();
                        return;
                    }
                }

                // Fallback: insert into textarea (text mode)
                this.insertAtCursor(textarea, variable);
                textarea.focus();
            });
        });

        // Also allow insertion into subject field
        const subjectField = document.querySelector('.kurs-booking-email-subject');
        if (subjectField) {
            variableButtons.forEach(button => {
                button.addEventListener('dblclick', (e) => {
                    e.preventDefault();
                    const variable = button.dataset.variable;
                    if (variable) {
                        this.insertAtCursor(subjectField, variable);
                        subjectField.focus();
                    }
                });
            });
        }
    },

    /**
     * Insert text at cursor position in input/textarea
     */
    insertAtCursor(element, text) {
        const start = element.selectionStart;
        const end = element.selectionEnd;
        const value = element.value;

        element.value = value.substring(0, start) + text + value.substring(end);
        element.selectionStart = element.selectionEnd = start + text.length;

        // Trigger change event for WordPress
        element.dispatchEvent(new Event('change', { bubbles: true }));
    },

    /**
     * Email template preview functionality
     */
    initEmailPreview() {
        const previewButtons = document.querySelectorAll('.kurs-booking-preview-email');

        previewButtons.forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();

                const template = button.dataset.template;
                if (!template) return;

                // Get current editor content
                const subjectField = document.querySelector(`input[name="kurs_booking_email_tpl_${template}_subject"]`);
                const editorId = `kurs_booking_email_tpl_${template}_body`;

                let subject = subjectField?.value || '';
                let body = '';

                // Get body from TinyMCE or textarea
                if (typeof tinymce !== 'undefined') {
                    const editor = tinymce.get(editorId);
                    if (editor) {
                        body = editor.getContent();
                    }
                }

                if (!body) {
                    const textarea = document.getElementById(editorId);
                    body = textarea?.value || '';
                }

                // Disable button and show loading
                const originalText = button.textContent;
                button.disabled = true;
                button.textContent = 'Lade Vorschau...';

                // Send AJAX request
                fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'kurs_booking_preview_email_template',
                        nonce: window.kursBookingAdmin?.nonce || '',
                        template: template,
                        subject: subject,
                        body: body
                    })
                })
                .then(response => response.json())
                .then(data => {
    if (data.success) {
                        // Create HTML content for preview
                        const previewHtml = `<!DOCTYPE html>
<html>
<head>
    <title>E-Mail Vorschau</title>
    <style>
        body { margin: 0; padding: 20px; background: #f5f5f5; font-family: sans-serif; }
        .preview-header { background: #0073aa; color: white; padding: 15px; margin: -20px -20px 20px; }
        .preview-subject { font-size: 14px; margin-top: 10px; opacity: 0.9; }
        .preview-body { background: white; padding: 20px; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
    </style>
</head>
<body>
    <div class="preview-header">
        <strong>E-Mail Vorschau</strong>
        <div class="preview-subject">Betreff: ${this.escapeHtml(data.data.subject || '')}</div>
    </div>
    <div class="preview-body">${data.data.body || ''}</div>
</body>
</html>`;
                        // Use Blob URL for secure preview (no document.write)
                        const blob = new Blob([previewHtml], { type: 'text/html; charset=utf-8' });
                        const blobUrl = URL.createObjectURL(blob);
                        const previewWindow = window.open(blobUrl, 'email_preview', 'width=700,height=600,scrollbars=yes');

                        // Revoke blob URL after window loads
                        if (previewWindow) {
                            previewWindow.onload = () => URL.revokeObjectURL(blobUrl);
                        } else {
                            URL.revokeObjectURL(blobUrl);
                        }
                    } else {
                        this.showNotice(data.data?.message || 'Vorschau konnte nicht geladen werden', 'error');
                    }
                })
                .catch(error => {
                    this.showNotice('Verbindungsfehler beim Laden der Vorschau', 'error');
                    console.error('Preview error:', error);
                })
                .finally(() => {
                    button.disabled = false;
                    button.textContent = originalText;
                });
            });
        });
    },

    /**
     * Reset email template to default
     */
    initEmailReset() {
        const resetButtons = document.querySelectorAll('.kurs-booking-reset-template');

        resetButtons.forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();

                const template = button.dataset.template;
                if (!template) return;

                // Confirm reset
                if (!confirm('Möchten Sie dieses Template wirklich auf den Standard zurücksetzen?\n\nAlle Ihre Änderungen gehen verloren!')) {
                    return;
                }

                // Disable button and show loading
                const originalText = button.textContent;
                button.disabled = true;
                button.textContent = 'Zurücksetzen...';

                // Send AJAX request
                fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'kurs_booking_reset_email_template',
                        nonce: window.kursBookingAdmin?.nonce || '',
                        template: template
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        this.showNotice(data.data.message, 'success');

                        // Clear form fields
                        const subjectField = document.querySelector(`input[name="kurs_booking_email_tpl_${template}_subject"]`);
                        if (subjectField) {
                            subjectField.value = '';
                        }

                        const editorId = `kurs_booking_email_tpl_${template}_body`;

                        // Clear TinyMCE
                        if (typeof tinymce !== 'undefined') {
                            const editor = tinymce.get(editorId);
                            if (editor) {
                                editor.setContent('');
                            }
                        }

                        // Also clear textarea
                        const textarea = document.getElementById(editorId);
                        if (textarea) {
                            textarea.value = '';
                        }
                    } else {
                        this.showNotice(data.data?.message || 'Fehler beim Zurücksetzen', 'error');
                    }
                })
                .catch(error => {
                    this.showNotice('Verbindungsfehler', 'error');
                    console.error('Reset error:', error);
                })
                .finally(() => {
                    button.disabled = false;
                    button.textContent = originalText;
                });
            });
        });
    },

    /**
     * Load default template
     */
    initLoadDefaultTemplate() {
        const loadButtons = document.querySelectorAll('.kurs-booking-load-default-template');

        loadButtons.forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();

                const template = button.dataset.template;
                if (!template) return;

                // Confirm load
                if (!confirm('Möchten Sie die Standard-Vorlage laden?\n\nDies ersetzt den aktuellen Inhalt im Editor.')) {
                    return;
                }

                // Disable button and show loading
                const originalText = button.textContent;
                button.disabled = true;
                button.textContent = 'Lade...';

                // Send AJAX request
                fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'kurs_booking_load_default_template',
                        nonce: window.kursBookingAdmin?.nonce || '',
                        template: template
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Update subject field
                        const subjectField = document.querySelector(`input[name="kurs_booking_email_tpl_${template}_subject"]`);
                        if (subjectField && data.data.subject) {
                            subjectField.value = data.data.subject;
                        }

                        // Update editor content
                        const editorId = `kurs_booking_email_tpl_${template}_body`;

                        // Update TinyMCE
                        if (typeof tinymce !== 'undefined') {
                            const editor = tinymce.get(editorId);
                            if (editor) {
                                editor.setContent(data.data.body || '');
                            }
                        }

                        // Also update textarea
                        const textarea = document.getElementById(editorId);
                        if (textarea) {
                            textarea.value = data.data.body || '';
                        }

                        this.showNotice('Standard-Vorlage wurde geladen. Speichern Sie die Einstellungen, um die Änderungen zu übernehmen.', 'success');
                    } else {
                        this.showNotice(data.data?.message || 'Fehler beim Laden der Vorlage', 'error');
                    }
                })
                .catch(error => {
                    this.showNotice('Verbindungsfehler', 'error');
                    console.error('Load default error:', error);
                })
                .finally(() => {
                    button.disabled = false;
                    button.textContent = originalText;
                });
            });
        });
    },

    /**
     * Import templates from MEC
     */
    initImportMecTemplates() {
        const importButton = document.querySelector('.kurs-booking-import-mec-templates');

        if (!importButton) return;

        importButton.addEventListener('click', (e) => {
            e.preventDefault();

            // Confirm import
            if (!confirm('Möchten Sie die E-Mail-Vorlagen aus MEC importieren?\n\nDies überschreibt alle aktuellen Vorlagen mit den MEC-Vorlagen.\nPlatzhalter werden automatisch konvertiert (z.B. %%name%% → {{customer_name}}).\n\nDiese Aktion kann nicht rückgängig gemacht werden!')) {
                return;
            }

            // Disable button and show loading
            const originalText = importButton.textContent;
            importButton.disabled = true;
            importButton.textContent = 'Importiere...';

            // Send AJAX request
            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'kurs_booking_import_mec_templates',
                    nonce: window.kursBookingAdmin?.nonce || ''
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showNotice(data.data.message, 'success');

                    // Reload page to show imported templates
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    this.showNotice(data.data?.message || 'Fehler beim Import', 'error');
                }
            })
            .catch(error => {
                this.showNotice('Verbindungsfehler', 'error');
                console.error('MEC import error:', error);
            })
            .finally(() => {
                importButton.disabled = false;
                importButton.textContent = originalText;
            });
        });
    },

    /**
     * Initialize Google Maps link auto-generation and preview
     */
    initGoogleMapsGenerator() {
        const generateButton = document.getElementById('kb-generate-maps-link');
        const locationField = document.getElementById('kurs_location');
        const mapsField = document.getElementById('kurs_google_maps');
        const previewContainer = document.getElementById('kb-google-maps-preview');

        if (!generateButton || !locationField || !mapsField) return;

        /**
         * Generate Google Maps URL from address
         * Uses Google Maps Search API URL format
         */
        const generateMapsUrl = (address) => {
            if (!address || !address.trim()) return '';
            const encodedAddress = encodeURIComponent(address.trim());
            return `https://www.google.com/maps/search/?api=1&query=${encodedAddress}`;
        };

        /**
         * Generate Google Maps Embed URL for iframe
         */
        const generateEmbedUrl = (address) => {
            if (!address || !address.trim()) return '';
            const encodedAddress = encodeURIComponent(address.trim());
            return `https://www.google.com/maps?q=${encodedAddress}&hl=de&z=14&output=embed`;
        };

        /**
         * Update the map preview iframe
         */
        const updateMapPreview = (address) => {
            if (!previewContainer) return;

            const container = previewContainer.querySelector('.kb-maps-preview-container');
            if (!container) return;

            if (!address || !address.trim()) {
                // Show placeholder
                previewContainer.style.display = 'none';
                return;
            }

            // Show preview container
            previewContainer.style.display = '';

            // Check if iframe exists, if not create it
            let iframe = document.getElementById('kb-google-maps-iframe');
            const placeholder = document.getElementById('kb-maps-placeholder');

            if (placeholder) {
                placeholder.remove();
            }

            if (!iframe) {
                iframe = document.createElement('iframe');
                iframe.id = 'kb-google-maps-iframe';
                iframe.width = '100%';
                iframe.height = '250';
                iframe.style.border = '0';
                iframe.allowFullscreen = true;
                iframe.loading = 'lazy';
                iframe.referrerPolicy = 'no-referrer-when-downgrade';
                container.appendChild(iframe);
            }

            // Update iframe src
            iframe.src = generateEmbedUrl(address);
        };

        // Generate on button click
        generateButton.addEventListener('click', (e) => {
            e.preventDefault();

            const address = locationField.value;

            if (!address || !address.trim()) {
                this.showNotice('Bitte geben Sie zuerst eine Adresse ein.', 'warning');
                locationField.focus();
                return;
            }

            const mapsUrl = generateMapsUrl(address);
            mapsField.value = mapsUrl;

            // Update map preview
            updateMapPreview(address);

            // Visual feedback
            generateButton.classList.add('updated');
            setTimeout(() => generateButton.classList.remove('updated'), 500);

            this.showNotice('Google Maps Link wurde generiert.', 'success');
        });

        // Auto-generate when address field loses focus (if maps field is empty)
        locationField.addEventListener('blur', () => {
            const address = locationField.value;

            // Always update the preview
            updateMapPreview(address);

            // Only auto-fill if maps field is empty
            if (!mapsField.value && address && address.trim()) {
                mapsField.value = generateMapsUrl(address);
            }
        });

        // Debounced input handler for live preview update
        let debounceTimer;
        locationField.addEventListener('input', () => {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => {
                const address = locationField.value;
                if (address && address.trim().length >= 5) {
                    updateMapPreview(address);
                }
            }, 800); // Wait 800ms after typing stops
        });
    },

    /**
     * Initialize masterdata repeaters (Instructors, Horses, Locations)
     */
    initMasterdataRepeaters() {
        // Generic add handler for all masterdata types
        const addButtons = {
            '.kurs-booking-add-instructor': 'kurs-booking-instructor-template',
            '.kurs-booking-add-horse': 'kurs-booking-horse-template',
            '.kurs-booking-add-location': 'kurs-booking-location-template'
        };

        Object.entries(addButtons).forEach(([buttonSelector, templateId]) => {
            const button = document.querySelector(buttonSelector);
            if (!button) return;

            button.addEventListener('click', () => {
                const containerId = button.dataset.container;
                const container = document.getElementById(containerId);
                const template = document.getElementById(templateId);

                if (!container || !template) return;

                const existingRows = container.querySelectorAll('.kurs-booking-repeater-row');
                const newIndex = existingRows.length;

                const html = template.innerHTML.replace(/__INDEX__/g, newIndex);
                // eslint-disable-next-line no-unsanitized/method -- HTML from script template element, index is array length
                container.insertAdjacentHTML('beforeend', html);

                // Focus the first input in the new row
                const newRow = container.lastElementChild;
                newRow.querySelector('input')?.focus();
            });
        });

        // Generic remove handler (event delegation)
        document.querySelectorAll('.kurs-booking-repeater-container').forEach(container => {
            container.addEventListener('click', (e) => {
                const removeBtn = e.target.closest('.kurs-booking-remove-row');
                if (removeBtn) {
                    const row = removeBtn.closest('.kurs-booking-repeater-row');
                    row?.remove();
                }
            });
        });
    },

    /**
     * Initialize location dropdown with website autofill
     */
    initLocationDropdown() {
        const locationSelect = document.getElementById('kurs_location_select');
        const locationInput = document.getElementById('kurs_location');
        const locationUrlInput = document.getElementById('kurs_location_url');
        const locationOtherRow = document.querySelector('.kb-location-other-row');

        if (!locationSelect) return;

        const updateLocationVisibility = () => {
            const selectedOption = locationSelect.options[locationSelect.selectedIndex];
            const value = locationSelect.value;

            if (value === '__other__') {
                // Show custom input fields
                if (locationOtherRow) {
                    locationOtherRow.style.display = 'block';
                    locationOtherRow.style.removeProperty('display');
                    locationOtherRow.classList.remove('kb-hidden');
                }
                if (locationInput) {
                    locationInput.focus();
                }
            } else if (value) {
                // Hide custom input, fill from dropdown
                if (locationOtherRow) {
                    locationOtherRow.style.display = 'none';
                }
                if (locationInput) {
                    locationInput.value = selectedOption.text;
                }
                if (locationUrlInput) {
                    locationUrlInput.value = selectedOption.dataset.url || '';
                }

                // Also update Google Maps link
                const generateMapsBtn = document.getElementById('kb-generate-maps-link');
                if (generateMapsBtn) {
                    generateMapsBtn.click();
                }
            } else {
                // Empty selection - hide custom input
                if (locationOtherRow) {
                    locationOtherRow.style.display = 'none';
                }
            }
        };

        locationSelect.addEventListener('change', updateLocationVisibility);

        // Trigger initial state check
        updateLocationVisibility();
    },

    /**
     * Initialize horse dropdown with "other" option
     */
    initHorseDropdown() {
        const horseSelect = document.getElementById('kurs_horse_select');
        const horseInput = document.getElementById('kurs_horse');
        const horseOtherRow = document.querySelector('.kb-horse-other-row');

        if (!horseSelect) return;

        const updateHorseVisibility = () => {
            const value = horseSelect.value;

            if (value === '__other__') {
                // Show custom input field
                if (horseOtherRow) {
                    horseOtherRow.style.display = 'block';
                    horseOtherRow.style.removeProperty('display');
                    horseOtherRow.classList.remove('kb-hidden');
                }
                if (horseInput) {
                    horseInput.focus();
                }
            } else {
                // Hide custom input
                if (horseOtherRow) {
                    horseOtherRow.style.display = 'none';
                }
            }
        };

        horseSelect.addEventListener('change', updateHorseVisibility);

        // Trigger initial state check
        updateHorseVisibility();
    },

    /**
     * Initialize Video-Kurs specific field handling
     */
    initVideoKursFields() {
        const produktartSelect = document.getElementById('kurs_produktart');
        if (!produktartSelect) return;

        // Initial update
        this.updateVideoKursFields(produktartSelect.value);
    },

    /**
     * Update Video-Kurs related fields based on product type
     *
     * @param {string} produktart Current product type
     */
    updateVideoKursFields(produktart) {
        const isVideoKurs = produktart === 'videokurs';
        const showVideoFields = ['videokurs', 'webinar'].includes(produktart);

        // Video Metabox (show for E and C)
        const videoMetabox = document.getElementById('kurs_video_zuordnung');
        const videoMetaboxContent = document.getElementById('kb-video-metabox');

        if (videoMetabox) {
            if (showVideoFields) {
                videoMetabox.style.display = '';
                videoMetabox.classList.remove('kb-video-metabox-hidden');
                if (videoMetaboxContent) {
                    videoMetaboxContent.classList.remove('kb-video-metabox-hidden');
                }
            } else {
                videoMetabox.style.display = 'none';
                videoMetabox.classList.add('kb-video-metabox-hidden');
                if (videoMetaboxContent) {
                    videoMetaboxContent.classList.add('kb-video-metabox-hidden');
                }
            }
        }

        // Video-Kurs specific settings (only for E)
        const videokursFields = document.getElementById('kb-videokurs-fields');
        if (videokursFields) {
            videokursFields.style.display = isVideoKurs ? '' : 'none';
        }

        // Date/Time section (hide for Video-Kurs)
        const dateTimeSection = document.querySelector('.kb-section:has(#kurs_start_date)');
        if (dateTimeSection) {
            if (isVideoKurs) {
                dateTimeSection.style.display = 'none';
                dateTimeSection.classList.add('kb-hidden');
            } else {
                dateTimeSection.style.display = '';
                dateTimeSection.classList.remove('kb-hidden');
            }
        }

        // Alternative: Find date section by header text
        document.querySelectorAll('.kb-section').forEach(section => {
            const header = section.querySelector('.kb-section-title');
            if (header && header.textContent.includes('Datum')) {
                if (isVideoKurs) {
                    section.style.display = 'none';
                    section.classList.add('kb-videokurs-hidden');
                } else {
                    section.style.display = '';
                    section.classList.remove('kb-videokurs-hidden');
                }
            }
        });

        // Max participants field (hide for Video-Kurs - unlimited)
        const maxParticipantsRow = document.querySelector('#kurs_max_participants')?.closest('.kb-row');
        if (maxParticipantsRow) {
            if (isVideoKurs) {
                maxParticipantsRow.style.display = 'none';
            } else {
                maxParticipantsRow.style.display = '';
            }
        }

        // Capacity section (hide entire section for Video-Kurs)
        document.querySelectorAll('.kb-section').forEach(section => {
            const header = section.querySelector('.kb-section-title');
            if (header && header.textContent.includes('Kapazit')) {
                if (isVideoKurs) {
                    section.style.display = 'none';
                    section.classList.add('kb-videokurs-hidden');
                } else {
                    section.style.display = '';
                    section.classList.remove('kb-videokurs-hidden');
                }
            }
        });

        // Durchfuehrungsart section (hide for Video-Kurs)
        document.querySelectorAll('.kb-section').forEach(section => {
            const header = section.querySelector('.kb-section-title');
            if (header && header.textContent.includes('Durchf')) {
                if (isVideoKurs) {
                    section.style.display = 'none';
                    section.classList.add('kb-videokurs-hidden');
                } else {
                    section.style.display = '';
                    section.classList.remove('kb-videokurs-hidden');
                }
            }
        });

        // Update produktart hint
        const hintEl = document.querySelector('.kb-produktart-hint');
        if (hintEl && isVideoKurs) {
            hintEl.textContent = 'Video-Kurs: Kein Termin, unbegrenzter Zugang';
            hintEl.style.color = '#0073aa';
        } else if (hintEl && !isVideoKurs && hintEl.textContent.includes('Video-Kurs')) {
            hintEl.textContent = '';
            hintEl.style.color = '';
        }
    },

    /**
     * Escape HTML entities
     * @param {string} str - String to escape
     * @returns {string} Escaped string
     */
    escapeHtml(str) {
        if (!str) {
            return '';
        }
        const div = document.createElement('div');
        div.textContent = String(str);
        return div.innerHTML;
    },

    /**
     * Initialize Dienstleistungen (Produktarten) Editor on Settings page
     * Sprint 8.2: CRUD UI for service types
     */
    initDienstleistungenEditor() {
        const editor = document.getElementById('kb-dienstleistungen-editor');
        if (!editor) return;

        const container = document.getElementById('kb-dienstleistungen-list');
        const addButton = document.getElementById('kb-add-dienstleistung');
        const template = document.getElementById('kb-dienstleistung-row-template');

        if (!container || !addButton || !template) return;

        // Add new Dienstleistung
        addButton.addEventListener('click', (e) => {
            e.preventDefault();

            const existingRows = container.querySelectorAll('.kb-dienstleistung-row');
            const newIndex = existingRows.length;

            // Generate unique ID
            const newId = 'custom_' + Date.now();

            let html = template.innerHTML
                .replace(/__INDEX__/g, newIndex)
                .replace(/__ID__/g, newId);

            // eslint-disable-next-line no-unsanitized/method -- HTML from script template, index is array length
            container.insertAdjacentHTML('beforeend', html);

            // Bind events to new row
            const newRow = container.lastElementChild;
            this.bindDienstleistungEvents(newRow);

            // Focus the name input
            newRow.querySelector('input[name$="[name]"]')?.focus();

            // Visual feedback
            newRow.style.backgroundColor = 'rgba(0, 115, 170, 0.1)';
            setTimeout(() => {
                newRow.style.transition = 'background-color 0.5s ease';
                newRow.style.backgroundColor = '';
            }, 100);

            // Update order values
            this.updateDienstleistungenOrder();
        });

        // Bind events to existing rows
        container.querySelectorAll('.kb-dienstleistung-row').forEach(row => {
            this.bindDienstleistungEvents(row);
        });

        // Initialize Sortable for drag & drop
        if (typeof jQuery !== 'undefined' && typeof jQuery.fn.sortable !== 'undefined') {
            jQuery(container).sortable({
                handle: '.kb-drag-handle',
                placeholder: 'kb-dienstleistung-row kb-sortable-placeholder',
                opacity: 0.7,
                tolerance: 'pointer',
                update: () => {
                    this.updateDienstleistungenOrder();
                    this.reindexDienstleistungen();
                }
            });
        }
    },

    /**
     * Bind events to a Dienstleistung row
     */
    bindDienstleistungEvents(row) {
        // Remove button
        const removeBtn = row.querySelector('.kb-delete-dienstleistung');
        removeBtn?.addEventListener('click', (e) => {
            e.preventDefault();

            // Check if this is a system type (cannot be deleted)
            const idInput = row.querySelector('input[name$="[id]"]');
            const systemTypes = ['kurs', 'workshop', 'webinar', 'gruppencoaching', 'einzelcoaching', 'videokurs', 'video_paket'];

            if (idInput && systemTypes.includes(idInput.value)) {
                this.showNotice('Standard-Dienstleistungen können nicht gelöscht werden. Sie können sie deaktivieren.', 'warning');
                return;
            }

            if (!confirm('Möchten Sie diese Dienstleistung wirklich löschen?')) {
                return;
            }

            // Animate removal
            row.style.overflow = 'hidden';
            row.style.transition = 'all 0.2s ease';
            row.style.height = row.offsetHeight + 'px';

            requestAnimationFrame(() => {
                row.style.height = '0';
                row.style.opacity = '0';
                row.style.marginBottom = '0';
                row.style.padding = '0';
            });

            setTimeout(() => {
                row.remove();
                this.reindexDienstleistungen();
            }, 200);
        });

        // Active toggle - visual feedback
        const activeCheckbox = row.querySelector('input[name$="[active]"]');
        activeCheckbox?.addEventListener('change', () => {
            if (activeCheckbox.checked) {
                row.classList.remove('kb-dienstleistung-inactive');
            } else {
                row.classList.add('kb-dienstleistung-inactive');
            }
        });

        // Update preview on name change
        const nameInput = row.querySelector('input[name$="[name]"]');
        const labelInput = row.querySelector('input[name$="[label]"]');
        const preview = row.querySelector('.kb-dienstleistung-preview');

        const updatePreview = () => {
            if (preview) {
                const label = labelInput?.value || '';
                const name = nameInput?.value || 'Neue Dienstleistung';
                preview.textContent = label ? `${label} ${name}` : name;
            }
        };

        nameInput?.addEventListener('input', updatePreview);
        labelInput?.addEventListener('input', updatePreview);

        // Color picker preview
        const colorInput = row.querySelector('input[name$="[badge_color]"]');
        const colorPreview = row.querySelector('.kb-color-preview');

        colorInput?.addEventListener('input', () => {
            if (colorPreview) {
                colorPreview.style.backgroundColor = colorInput.value;
            }
        });
    },

    /**
     * Update order values after sorting
     */
    updateDienstleistungenOrder() {
        const container = document.getElementById('kb-dienstleistungen-list');
        if (!container) return;

        const rows = container.querySelectorAll('.kb-dienstleistung-row');
        rows.forEach((row, index) => {
            const orderInput = row.querySelector('input[name$="[order]"]');
            if (orderInput) {
                orderInput.value = index + 1;
            }
        });
    },

    /**
     * Reindex Dienstleistungen after removal/reorder
     */
    reindexDienstleistungen() {
        const container = document.getElementById('kb-dienstleistungen-list');
        if (!container) return;

        const rows = container.querySelectorAll('.kb-dienstleistung-row');
        rows.forEach((row, index) => {
            row.dataset.index = index;

            // Update input names
            row.querySelectorAll('input, select').forEach(input => {
                const name = input.name;
                if (name) {
                    input.name = name.replace(/dienstleistungen\[\d+\]/, `dienstleistungen[${index}]`);
                }
            });
        });
    },

    /**
     * Initialize Global Field Filter in Sticky Footer
     * Sprint 8.2: Filter all fields by single Dienstleistung (Dropdown)
     */
    initGlobalFieldFilter() {
        const filterSelect = document.getElementById('kurs-booking-field-filter');
        const filterBadge = document.querySelector('.kurs-booking-filter-badge');
        if (!filterSelect) return;

        // Dropdown change handler
        filterSelect.addEventListener('change', () => {
            const filterType = filterSelect.value;
            const selectedOption = filterSelect.options[filterSelect.selectedIndex];
            const color = selectedOption.dataset.color || '#4CAF50';

            // Update badge color dynamically
            if (filterBadge) {
                filterBadge.style.backgroundColor = color;
            }

            // Filter: null for "alle", single ID for specific Dienstleistung
            const allowedIds = filterType === 'alle' ? null : [filterType];
            this.filterFieldRows(allowedIds);
        });
    },

    /**
     * Filter field rows by produktarten
     * @param {Array|null} allowedIds - Array of allowed produktarten IDs, or null for all
     */
    filterFieldRows(allowedIds) {
        const container = document.getElementById('kurs-booking-fields-container');
        if (!container) return;

        const fieldRows = container.querySelectorAll('.kurs-booking-field-row');

        fieldRows.forEach(row => {
            // Check if field should be visible
            const shouldShow = this.shouldShowField(row, allowedIds);

            if (shouldShow) {
                row.classList.remove('filtered-hidden');
            } else {
                row.classList.add('filtered-hidden');
            }
        });

        // Update visible count
        this.updateFilterCount(fieldRows, allowedIds);
    },

    /**
     * Check if a field should be shown for given filter
     * @param {Element} row - Field row element
     * @param {Array|null} allowedIds - Allowed produktarten or null for all
     * @returns {boolean}
     */
    shouldShowField(row, allowedIds) {
        // Show all if no filter
        if (!allowedIds) return true;

        // Get field data
        const basisCheckbox = row.querySelector('input[name$="[basis_field]"]');
        const isBasisField = basisCheckbox?.checked;

        // Basis fields appear everywhere
        if (isBasisField) return true;

        // Check produktarten checkboxes
        const produktartenCheckboxes = row.querySelectorAll('.kurs-booking-produktarten-matrix input[type="checkbox"]:checked');

        // If no produktarten selected, field appears everywhere (backwards compat)
        if (produktartenCheckboxes.length === 0) return true;

        // Check if any checked produktart matches allowed IDs
        for (const checkbox of produktartenCheckboxes) {
            if (allowedIds.includes(checkbox.value)) {
                return true;
            }
        }

        return false;
    },

    /**
     * Update filter count display
     */
    updateFilterCount(fieldRows, allowedIds) {
        const visibleCount = allowedIds
            ? Array.from(fieldRows).filter(r => !r.classList.contains('filtered-hidden')).length
            : fieldRows.length;

        const filterCount = document.querySelector('.kurs-booking-filter-count');
        if (filterCount) {
            filterCount.textContent = allowedIds
                ? `(${visibleCount}/${fieldRows.length})`
                : '';
        }
    },

    /**
     * Show admin notice
     */
    showNotice(message, type = 'info') {
        const notice = document.createElement('div');
        notice.className = `notice notice-${type} is-dismissible`;
        // Create elements safely instead of innerHTML with user message
        const p = document.createElement('p');
        p.textContent = message;
        const dismissBtn = document.createElement('button');
        dismissBtn.type = 'button';
        dismissBtn.className = 'notice-dismiss';
        dismissBtn.innerHTML = '<span class="screen-reader-text">Dismiss this notice.</span>';
        notice.appendChild(p);
        notice.appendChild(dismissBtn);

        const wrap = document.querySelector('.wrap');
        if (wrap) {
            wrap.insertBefore(notice, wrap.firstChild);

            // Auto dismiss
            setTimeout(() => {
                notice.style.transition = 'opacity 0.3s ease';
                notice.style.opacity = '0';
                setTimeout(() => notice.remove(), 300);
            }, 5000);

            // Manual dismiss
            dismissBtn.addEventListener('click', () => {
                notice.remove();
            });
        }
    }
};

/**
 * Initialize on DOM ready
 */
document.addEventListener('DOMContentLoaded', () => {
    KursBookingAdmin.init();
});
