(function($){
    // Localized data from PHP
    var simpbookTranslations = window.SimpleBookingEinstellungen && window.SimpleBookingEinstellungen.simpbookTranslations ? window.SimpleBookingEinstellungen.simpbookTranslations : {};
    var simpbookDatepickerTranslations = window.SimpleBookingEinstellungen && window.SimpleBookingEinstellungen.simpbookDatepickerTranslations ? window.SimpleBookingEinstellungen.simpbookDatepickerTranslations : {};
    var wochentagZeitenSettings = window.SimpleBookingEinstellungen && window.SimpleBookingEinstellungen.wochentagZeitenSettings ? window.SimpleBookingEinstellungen.wochentagZeitenSettings : {};
    var wochentagKeysSettings = window.SimpleBookingEinstellungen && window.SimpleBookingEinstellungen.wochentagKeysSettings ? window.SimpleBookingEinstellungen.wochentagKeysSettings : ['sonntag', 'montag', 'dienstag', 'mittwoch', 'donnerstag', 'freitag', 'samstag'];
    var currentLanguage = window.SimpleBookingEinstellungen && window.SimpleBookingEinstellungen.currentLanguage ? window.SimpleBookingEinstellungen.currentLanguage : (simpbookDatepickerTranslations.currentLanguage || 'auto');
    var ajaxUrl = window.SimpleBookingEinstellungen && window.SimpleBookingEinstellungen.ajaxUrl ? window.SimpleBookingEinstellungen.ajaxUrl : '';
    var nonces = window.SimpleBookingEinstellungen && window.SimpleBookingEinstellungen.nonces ? window.SimpleBookingEinstellungen.nonces : {};
    var urlaubDates = window.SimpleBookingEinstellungen && window.SimpleBookingEinstellungen.urlaubDates ? window.SimpleBookingEinstellungen.urlaubDates : [];

    function isRegulaererWochentagDeaktiviert(date) {
        var wochentag = wochentagKeysSettings[date.getDay()];
        if (wochentagZeitenSettings && wochentagZeitenSettings[wochentag]) {
            return wochentagZeitenSettings[wochentag]['aktiv'] !== '1';
        }
        return false;
    }

    jQuery(document).ready(function($) {
        // Ensure datepicker translations reflect language override
        var selectedLanguageDropdown = $('#simpbook_language_override').val();
        if (selectedLanguageDropdown && selectedLanguageDropdown !== 'auto' && selectedLanguageDropdown !== '') {
            simpbookDatepickerTranslations.currentLanguage = selectedLanguageDropdown;
        }

        // re-initialize
        currentLanguage = $('#simpbook_language_override').val();

        function updateActiveTabLabel(tabId) {
            $('.simpbook-tabs-bar label').removeClass('is-active');
            $('.simpbook-tabs-bar label[for="' + tabId + '"]').addClass('is-active');
        }

        function showTab(tabId) {
            $('#' + tabId).prop('checked', true);
            $('#simpbook-active-tab').val(tabId.replace('tab-', ''));
            updateActiveTabLabel(tabId);

            if (simpbookDatepickerTranslations.currentLanguage === 'en_US_AMPM') {
                setTimeout(function() { convertTimeInputsForUS(); }, 100);
            }

            if (tabId === 'tab-opening-hours') {
                setTimeout(function() { initializeDatepicker(); }, 150);
                setTimeout(function() { initializeUrlaubDatepicker(); }, 150);
            }
        }

        $('.simpbook-tabs input[type="radio"]').change(function() {
            var tabId = $(this).attr('id');
            $('#simpbook-active-tab').val(tabId.replace('tab-', ''));
            updateActiveTabLabel(tabId);

            // Close email preview when switching away from emails tab
            if (tabId !== 'tab-emails') {
                $('#simpbook-email-preview-box').removeClass('is-visible');
                $('#content-emails').removeClass('simpbook-email-preview-open');
                $('.simpbook-email-card').removeClass('is-active');
            }

            if (simpbookDatepickerTranslations.currentLanguage === 'en_US_AMPM') {
                setTimeout(function() { convertTimeInputsForUS(); }, 100);
            }

            if (tabId === 'tab-opening-hours') {
                setTimeout(function() { initializeDatepicker(); }, 150);
                setTimeout(function() { initializeUrlaubDatepicker(); }, 150);
            }

            if (typeof(Storage) !== "undefined") {
                localStorage.setItem("simpbookActiveSettingsTab", tabId);
            }
        });

        var initialTab = null;
        if (typeof(Storage) !== "undefined") {
            var savedTab = localStorage.getItem("simpbookActiveSettingsTab");
            if (savedTab && $('#' + savedTab).length) {
                initialTab = savedTab;
            }
        }

        var checkedTab = $('.simpbook-tabs input[type="radio"]:checked');
        if (checkedTab.length > 0) {
            showTab(checkedTab.attr('id'));
        } else if (initialTab) {
            $('#' + initialTab).prop('checked', true);
            showTab(initialTab);
        } else {
            var firstTab = $('.simpbook-tabs input[type="radio"]:first');
            firstTab.prop('checked', true);
            showTab(firstTab.attr('id'));
        }

        $('input[name$="_aktiv"]').change(function() {
            var $zeitenInputs = $(this).closest('.simpbook-setting-card').find('.wochentag-zeiten-inputs');
            if ($(this).is(':checked')) {
                $zeitenInputs.slideDown(function() {
                    if (simpbookDatepickerTranslations.currentLanguage === 'en_US_AMPM') {
                        convertTimeInputsForUS();
                    }
                });
            } else {
                $zeitenInputs.slideUp();
            }
        }).change();

        function convert24to12(time24) {
            if (!time24 || !time24.match(/^\d{2}:\d{2}$/)) return time24;
            var parts = time24.split(':');
            var hours = parseInt(parts[0], 10);
            var minutes = parts[1];
            var ampm = hours >= 12 ? 'PM' : 'AM';
            hours = hours % 12;
            hours = hours ? hours : 12;
            return (hours < 10 ? '0' : '') + hours + ':' + minutes + ' ' + ampm;
        }

        function convert12to24(time12) {
            if (!time12) return '';
            var match = time12.match(/^(\d{1,2}):(\d{2})\s*(AM|PM)$/i);
            if (!match) {
                match = time12.match(/^(\d{1,2}):(\d{2})(AM|PM)$/i);
            }
            if (!match) return time12;

            var hours = parseInt(match[1], 10);
            var minutes = match[2];
            var ampm = match[3].toUpperCase();

            if (ampm === 'PM' && hours !== 12) {
                hours += 12;
            } else if (ampm === 'AM' && hours === 12) {
                hours = 0;
            }

            return (hours < 10 ? '0' : '') + hours + ':' + minutes;
        }

        // --- AM/PM helper: render two toggle buttons (AM / PM) next to the text input ---
        function ensureAmPmToggle($input, ampm) {
            var $wrap = $input.next('.ampm-toggle');
            if ($wrap.length === 0) {
                $wrap = $('<div class="ampm-toggle" role="group" aria-label="AM/PM">' +
                          '<button type="button" class="ampm-btn" data-ampm="AM" aria-pressed="false">AM</button>' +
                          '<button type="button" class="ampm-btn" data-ampm="PM" aria-pressed="false">PM</button>' +
                          '</div>');
                $input.after($wrap);
                $wrap.on('click', '.ampm-btn', function() {
                    var $btn = $(this);
                    $wrap.find('.ampm-btn').removeClass('active').attr('aria-pressed', 'false');
                    $btn.addClass('active').attr('aria-pressed', 'true');
                    // store selection on the input to survive transient DOM updates
                    var val = $btn.data('ampm') || ($btn.attr('data-ampm') || 'AM');
                    val = String(val).toUpperCase();
                    $input.data('ampm', val);
                    // also persist as attribute so it survives serialization and other DOM reads
                    $input.attr('data-ampm', val);

                    // Immediately compute and persist a 24h value when possible so it will be serialized correctly
                    var raw = $input.data('raw-digits') || '';
                    var time12 = '';
                    if (isCompleteRaw(raw)) {
                        var hh = raw.substr(0,2);
                        var mm = raw.substr(2,2);
                        time12 = hh + ':' + mm;
                    } else {
                        var cur = $input.val();
                        if (/^\d{1,2}:\d{2}$/.test(cur)) {
                            time12 = cur;
                        }
                    }
                    if (time12) {
                        var forced24 = convert12to24(time12 + ' ' + val);
                        $input.data('force-24h', forced24);
                        // also set attribute for serialization fallback
                        $input.attr('data-force-24h', forced24);
                    }

                    $input.trigger('input');
                });
            }
            var selected = (ampm || 'AM').toUpperCase();
            $wrap.find('.ampm-btn').removeClass('active').attr('aria-pressed', 'false').filter('[data-ampm="' + selected + '"]').addClass('active').attr('aria-pressed', 'true');
            // ensure input has a stored ampm as a reliable fallback
            selected = String(selected).toUpperCase();
            $input.data('ampm', selected);
            $input.attr('data-ampm', selected);
        }

        function setupAmPmMasking($input) {
            if (typeof $input.data('raw-digits') === 'undefined') $input.data('raw-digits', '');
            var val = $input.attr('value') || $input.val() || '';
            var matches = val.match(/^(\d{1,2}):(\d{2})/);
            if (matches) {
                var raw = matches[1].padStart(2, '0') + matches[2];
                $input.data('raw-digits', raw);
            }
        }

        function formatFromRaw(raw) {
            var digits = raw.split('');
            while (digits.length < 4) digits.push('-');
            var hourStr = (digits[0] === '-' ? '-' : digits[0]) + (digits[1] === '-' ? '-' : digits[1]);
            var minuteStr = (digits[2] === '-' ? '-' : digits[2]) + (digits[3] === '-' ? '-' : digits[3]);
            return hourStr + ':' + minuteStr;
        }

        function isCompleteRaw(raw) {
            return raw && raw.length === 4 && raw.indexOf('-') === -1;
        }

        function convertTimeInputsForUS() {
            if (simpbookDatepickerTranslations.currentLanguage !== 'en_US_AMPM') {
                return;
            }

            $('.time-input').each(function() {
                var $input = $(this);
                
                // Check if we already have a stored 24h value from a previous conversion
                var stored24h = $input.data('original-24h-time');
                var time24 = '';
                
                if (stored24h) {
                    // Use the stored 24h value - this prevents reconversion issues
                    time24 = stored24h;
                } else {
                    // First time conversion - get the 24h value from the input
                    var originalVal = $input.attr('value') || $input.val();
                    
                    if ($input.attr('type') === 'time') {
                        time24 = $input.val();
                    } else {
                        var currentText = $input.val();
                        if (currentText) {
                            // Check if it's already in 24h format (HH:MM without AM/PM)
                            if (/^\d{1,2}:\d{2}$/.test(currentText) && !currentText.match(/AM|PM/i)) {
                                // It's a 24h format, use it directly
                                time24 = currentText;
                            } else {
                                // Has AM/PM, convert to 24h first
                                time24 = convert12to24(currentText);
                            }
                        }
                    }

                    // Try to get from settings if no value found
                    if (!time24) {
                        var name = $input.attr('name') || '';
                        var m = name.match(/^simpbook_([^_]+)_(beginn|ende)$/);
                        if (m && wochentagZeitenSettings && wochentagZeitenSettings[m[1]] && wochentagZeitenSettings[m[1]][m[2]]) {
                            time24 = wochentagZeitenSettings[m[1]][m[2]];
                        } else {
                            var m2 = name.match(/^simpbook_spezielle_tage_daten\[([^\]]+)\]\[(beginn|ende)\]$/);
                            if (m2) {
                                var attrVal = $input.attr('value') || '';
                                if (attrVal) time24 = attrVal;
                            }
                        }
                    }

                    // Last resort - use originalVal
                    if (!time24 && originalVal) {
                        time24 = originalVal;
                    }
                    
                    // Store the original 24h value for future calls
                    if (time24) {
                        $input.data('original-24h-time', time24);
                    }
                }

                $input.data('original-time', time24);
                $input.attr('type', 'text');
                // Avoid setting native pattern validation — it blocks form submit before our JS can convert values.
                // Store the intended pattern for possible JS-based validation/debugging instead.
                $input.data('pattern', '^([0-1]?[0-9]|2[0-3]):[0-5][0-9]\\s*(AM|PM)$');
                $input.attr('placeholder', '--:-- AM/PM');

                var ampm = 'AM';
                if (time24) {
                    var parts = convert24to12(time24).split(' ');
                    var hhmm = parts[0];
                    ampm = parts[1] || 'AM';
                    $input.val(hhmm);
                    $input.attr('value', hhmm);
                } else {
                    $input.val('--:--');
                    $input.removeAttr('value');
                }
                ensureAmPmToggle($input, ampm);
                setupAmPmMasking($input);
            });
        }

        function convertTimeInputsTo24h() {
            // convert back to time inputs and ensure 24h value is set
            $('.time-input').each(function() {
                var $input = $(this);
                var origPreserved = $input.data('original-time') || $input.attr('value') || '';
                var time24 = '';

                if ($input.attr('type') === 'text') {
                    // If we have an AM/PM select, prefer combining raw digits or hh:mm + select
                    var $wrap = $input.next('.ampm-toggle');
                    if ($wrap.length) {
                        var ampm = 'AM';
                        // Prefer explicit attribute (set on click), then active button, then data store
                        if ($input.attr('data-ampm')) {
                            ampm = String($input.attr('data-ampm')).toUpperCase();
                        } else {
                            var $activeBtn = $wrap.find('.ampm-btn.active');
                            if ($activeBtn.length) {
                                ampm = ($activeBtn.data('ampm') || $activeBtn.attr('data-ampm') || 'AM').toUpperCase();
                            } else if ($input.data('ampm')) {
                                ampm = String($input.data('ampm')).toUpperCase();
                            }
                        }
                        var raw = $input.data('raw-digits') || '';
                        var time12 = '';
                        if (isCompleteRaw(raw)) {
                            var hh = raw.substr(0,2);
                            var mm = raw.substr(2,2);
                            time12 = hh + ':' + mm;
                        } else {
                            var val = $input.val();
                            if (/^\d{1,2}:\d{2}$/.test(val)) {
                                time12 = val;
                            }
                        }
                        // Highest priority: explicit forced 24h value set by the toggle handler
                        var forced = $input.data('force-24h') || $input.attr('data-force-24h') || null;
                        if (forced) {
                            time24 = forced;
                        } else if (time12) {
                            time24 = convert12to24(time12 + ' ' + ampm);
                        } else if (!time12 && origPreserved) {
                            // If user only changed AM/PM but didn't type digits, use original preserved value
                            var maybe = origPreserved;
                            if (/^\d{1,2}:\d{2}$/.test(maybe)) {
                                time24 = convert12to24(maybe + ' ' + ampm);
                            }
                        }
                        // remove the AM/PM toggle after conversion
                        $wrap.remove();
                    } else {
                        var time12 = $input.val();
                        if (time12) {
                            time24 = convert12to24(time12);
                        }
                    }
                } else {
                    time24 = $input.val();
                }

                // fallback to localized settings if still empty
                if (!time24) {
                    var name = $input.attr('name') || '';
                    var m = name.match(/^simpbook_([^_]+)_(beginn|ende)$/);
                    if (m && wochentagZeitenSettings && wochentagZeitenSettings[m[1]] && wochentagZeitenSettings[m[1]][m[2]]) {
                        time24 = wochentagZeitenSettings[m[1]][m[2]];
                    } else {
                        var m2 = name.match(/^simpbook_spezielle_tage_daten\[([^\]]+)\]\[(beginn|ende)\]$/);
                        if (m2) {
                            var attrVal = $input.attr('value') || '';
                            if (attrVal) time24 = attrVal;
                        }
                    }
                }

                // final fallback to preserved original
                if (!time24 && origPreserved) {
                    time24 = origPreserved;
                }

                $input.attr('type', 'time');
                $input.removeAttr('pattern');
                $input.removeAttr('placeholder');

                if (time24) {
                    $input.val(time24);
                    $input.attr('value', time24);
                    $input.trigger('input');
                } else {
                    $input.val('');
                    $input.removeAttr('value');
                    $input.trigger('input');
                }
                // cleanup any temporary masking data
                $input.removeData('raw-digits');
            });
        }

        convertTimeInputsForUS();
        setTimeout(initializeDatepicker, 200);
        setTimeout(initializeUrlaubDatepicker, 200);

        $('form').on('submit', function(e) {
            e.preventDefault();
            // Ensure all time inputs are converted to 24h before submit and log the posted values for debugging
            convertTimeInputsTo24h();
            // Small delay to let DOM updates propagate, then log and submit
            var form = this;
            var $form = $(form);
            
            // Ensure submit button value is included in POST data
            var submitButton = $form.find('input[type="submit"][name="simpbook_einstellungen_submit"]');
            if (submitButton.length > 0 && !$form.find('input[name="simpbook_einstellungen_submit"][type="hidden"]').length) {
                $form.append('<input type="hidden" name="simpbook_einstellungen_submit" value="' + submitButton.val() + '">');
            }
            
            setTimeout(function() {
                // Also log specific fields for clarity
                var keys = [];
                $form.find('input[name^="simpbook_"][name$="_beginn"], input[name^="simpbook_"][name$="_ende"], input[name^="simpbook_spezielle_tage_daten"]').each(function() {
                    var $i = $(this);
                    keys.push($i.attr('name') + '=' + ($i.val() || '<empty>'));
                });

                form.submit();
            }, 60);
        });

        function formatDateForDisplay(date) {
            if (!date) return '';
            var day = date.getDate();
            var monthIndex = date.getMonth();
            var year = date.getFullYear();
            var monthName = simpbookDatepickerTranslations.monthNames[monthIndex];

            if (simpbookDatepickerTranslations.currentLanguage === 'en_US_AMPM' || simpbookDatepickerTranslations.currentLanguage === 'en_US') {
                return monthName + ' ' + day + ', ' + year;
            }

            return day + '. ' + monthName + ' ' + year;
        }

        function convertDisplayToDbFormat(displayText) {
            if (!displayText) return '';
            var isUSFormat = simpbookDatepickerTranslations.currentLanguage === 'en_US_AMPM' || simpbookDatepickerTranslations.currentLanguage === 'en_US';

            if ((displayText.indexOf('.') !== -1 || displayText.indexOf('/') !== -1) && displayText.indexOf('-') === -1) {
                var hasMonthName = false;
                for (var i = 0; i < simpbookDatepickerTranslations.monthNames.length; i++) {
                    if (displayText.indexOf(simpbookDatepickerTranslations.monthNames[i]) !== -1) {
                        hasMonthName = true;
                        break;
                    }
                }
                if (!hasMonthName) {
                    if (displayText.indexOf('/') !== -1) {
                        var usParts = displayText.split('/');
                        if (usParts.length === 3) {
                            var month = usParts[0].padStart(2, '0');
                            var day = usParts[1].padStart(2, '0');
                            var year = usParts[2].length === 2 ? '20' + usParts[2] : usParts[2];
                            return day + '.' + month + '.' + year;
                        }
                    }
                    return displayText;
                }
            }

            if (isUSFormat && displayText.indexOf(',') !== -1) {
                var commaIndex = displayText.indexOf(',');
                var monthAndDay = displayText.substring(0, commaIndex).trim();
                var year = displayText.substring(commaIndex + 1).trim();

                var monthIndex = -1;
                var day = '';
                for (var i = 0; i < simpbookDatepickerTranslations.monthNames.length; i++) {
                    if (monthAndDay.indexOf(simpbookDatepickerTranslations.monthNames[i]) !== -1) {
                        monthIndex = i;
                        day = monthAndDay.replace(simpbookDatepickerTranslations.monthNames[i], '').trim();
                        break;
                    }
                }

                if (monthIndex !== -1 && day) {
                    var month = (monthIndex + 1).toString().padStart(2, '0');
                    return day.padStart(2, '0') + '.' + month + '.' + year;
                }
            }

            var parts = displayText.split('. ');
            if (parts.length >= 2) {
                var day = parts[0];
                var monthYear = parts[1].split(' ');
                if (monthYear.length >= 2) {
                    var monthName = monthYear[0];
                    var year = monthYear[1];

                    var monthIndex = simpbookDatepickerTranslations.monthNames.indexOf(monthName);
                    if (monthIndex === -1) {
                        monthIndex = simpbookDatepickerTranslations.monthNamesShort.indexOf(monthName);
                    }
                    if (monthIndex !== -1) {
                        var month = (monthIndex + 1).toString().padStart(2, '0');
                        return day.padStart(2, '0') + '.' + month + '.' + year;
                    }
                }
            }
            return displayText;
        }

        var datepickerIsOpening = false;
        var savedDisplayFormat = null;
        var dateFormat = 'dd.mm.yy';
        var firstDay = 1;
        if (simpbookDatepickerTranslations.currentLanguage === 'en_US_AMPM') {
            dateFormat = 'mm/dd/yy';
            firstDay = 0;
        }

        var datepickerInitialized = false;

        function initializeDatepicker() {
            if (datepickerInitialized) return;
            if ($('#datepicker_speziell').length === 0) return;
            if (typeof($.datepicker) === 'undefined') { setTimeout(initializeDatepicker, 100); return; }

            try {
                $("#datepicker_speziell").datepicker({
                    dateFormat: dateFormat,
                    minDate: 0,
                    firstDay: firstDay,
                    monthNames: simpbookDatepickerTranslations.monthNames,
                    monthNamesShort: simpbookDatepickerTranslations.monthNamesShort,
                    dayNames: simpbookDatepickerTranslations.dayNames,
                    dayNamesShort: simpbookDatepickerTranslations.dayNamesShort,
                    dayNamesMin: simpbookDatepickerTranslations.dayNamesMin,
                    beforeShow: function(input, inst) {
                        datepickerIsOpening = true;
                        setTimeout(function() { datepickerIsOpening = false; }, 100);

                        var displayValue = $(input).val();
                        if (displayValue && displayValue.indexOf('. ') !== -1) {
                            savedDisplayFormat = displayValue;
                            var dbFormat = convertDisplayToDbFormat(displayValue);
                            if (dbFormat && dbFormat !== displayValue) {
                                var dateObj = $.datepicker.parseDate('dd.mm.yy', dbFormat);
                                if (dateObj) {
                                    $(input).datepicker('setDate', dateObj);
                                    $(input).val(dbFormat);
                                }
                            }
                        } else {
                            savedDisplayFormat = null;
                        }
                    },
                    onClose: function(dateText, inst) {
                        var selectedDate = $(this).datepicker('getDate');
                        if (selectedDate) {
                            var displayFormat = formatDateForDisplay(selectedDate);
                            $(this).val(displayFormat);
                        } else if (savedDisplayFormat) {
                            $(this).val(savedDisplayFormat);
                        }
                        savedDisplayFormat = null;
                    },
                    onSelect: function(dateText, inst) {
                        var selectedDate = $(this).datepicker('getDate');
                        if (!selectedDate) return;
                        var $input = $(this);
                        setTimeout(function() {
                            var displayFormat = formatDateForDisplay(selectedDate);
                            $input.val(displayFormat);
                        }, 10);
                    },
                    beforeShowDay: function(date) {
                        var dateStringYMD = $.datepicker.formatDate('yy-mm-dd', date);
                        var istBereitsKonfiguriert = ($('#spezielle-tage-liste .spezieller-tag-eintrag[data-datum="' + dateStringYMD + '"]').length > 0);
                        var istRegulaerDeaktiviert = isRegulaererWochentagDeaktiviert(date);
                        var istUrlaub = (urlaubDates.indexOf(dateStringYMD) !== -1);
                        var cssClass = '';
                        var istAuswaehlbar = true;

                        if (istBereitsKonfiguriert) {
                            istAuswaehlbar = false;
                        }

                        if (istUrlaub) {
                            istAuswaehlbar = false;
                            cssClass = 'urlaub-gesperrt-tag';
                        }

                        if (istRegulaerDeaktiviert) {
                            if (!istBereitsKonfiguriert && !istUrlaub) {
                                cssClass = 'deaktivierter-wochentag';
                            }
                            istAuswaehlbar = false;
                        }

                        return [istAuswaehlbar, cssClass];
                    }
                });

                datepickerInitialized = true;
            } catch (e) {
                console.error('Fehler bei Datepicker-Initialisierung:', e);
            }
        }

        $("#datepicker_speziell").on('change blur', function() {
            if (!datepickerIsOpening) {
                var currentValue = $(this).val();
                if (currentValue && currentValue.indexOf('.') !== -1 && currentValue.indexOf('. ') === -1) {
                    var parts = currentValue.split('.');
                    if (parts.length === 3) {
                        var day = parseInt(parts[0], 10);
                        var month = parseInt(parts[1], 10) - 1;
                        var yearStr = parts[2];
                        var year = (yearStr.length === 2) ? parseInt('20' + yearStr, 10) : parseInt(yearStr, 10);
                        var date = new Date(year, month, day);
                        if (date && !isNaN(date.getTime())) {
                            var displayFormat = formatDateForDisplay(date);
                            $(this).val(displayFormat);
                        }
                    }
                }
            }
        });

        $("#add-speziellen-tag-btn").click(function() {
            var selectedDateInput = $("#datepicker_speziell").val();
            if (selectedDateInput) {
                var dateStringYMD = '';
                var dateObj = null;
                var dateToParse = convertDisplayToDbFormat(selectedDateInput);

                if (dateToParse && dateToParse.indexOf('.') !== -1) {
                    var parts = dateToParse.split('.');
                    if (parts.length === 3) {
                        var day = parseInt(parts[0], 10);
                        var month = parseInt(parts[1], 10) - 1;
                        var yearStr = parts[2];
                        var year = (yearStr.length === 2) ? parseInt('20' + yearStr, 10) : parseInt(yearStr, 10);
                        dateObj = new Date(year, month, day);
                    }
                }

                if (!dateObj || isNaN(dateObj.getTime())) {
                    alert(simpbookTranslations.datum_auswaehlen);
                    return;
                }

                dateStringYMD = $.datepicker.formatDate('yy-mm-dd', dateObj);

                if (isRegulaererWochentagDeaktiviert(dateObj)) {
                    alert(simpbookTranslations.wochentag_geschlossen_warning);
                    $("#datepicker_speziell").val('');
                    return;
                }
                if ($('#spezielle-tage-liste .spezieller-tag-eintrag[data-datum="' + dateStringYMD + '"]').length > 0) {
                    alert(simpbookTranslations.datum_bereits_hinzugefuegt);
                    $("#datepicker_speziell").val('');
                    return;
                }

                var displayDate = formatDateForDisplay(dateObj);

                var newEntryHtml = `
                    <div class="spezieller-tag-eintrag" data-datum="${dateStringYMD}">
                        <strong>${displayDate}</strong>
                        <input type="hidden" name="simpbook_spezielle_tage_daten[${dateStringYMD}][datum_hidden]" value="${dateStringYMD}">
                        <select name="simpbook_spezielle_tage_daten[${dateStringYMD}][status]" class="spezieller-tag-status">
                            <option value="geschlossen" selected>${simpbookTranslations.ganzen_tag_schliessen}</option>
                            <option value="speziell">${simpbookTranslations.spezielle_oeffnungszeiten}</option>
                        </select>
                        <span class="spezielle-zeiten-inputs" style="display:none;">
                            <span class="time-input-group">
                                <span class="time-label">${simpbookTranslations.von}</span>
                                <input type="time" name="simpbook_spezielle_tage_daten[${dateStringYMD}][beginn]" value="10:00" class="spezieller-tag-beginn time-input">
                            </span>
                            <span class="time-input-group">
                                <span class="time-label">${simpbookTranslations.bis}</span>
                                <input type="time" name="simpbook_spezielle_tage_daten[${dateStringYMD}][ende]" value="18:00" class="spezieller-tag-ende time-input">
                            </span>
                        </span>
                        <button type="button" class="button button-link-delete remove-speziellen-tag-btn">${simpbookTranslations.entfernen}</button>
                    </div>`;
                $('#spezielle-tage-liste').append(newEntryHtml);
                $("#datepicker_speziell").val('');
                $("#datepicker_speziell").datepicker("refresh");

                // If current language uses AM/PM, initialize the new inputs with AM/PM defaults/placeholders
                if (simpbookDatepickerTranslations.currentLanguage === 'en_US_AMPM') {
                    var $newEntry = $('#spezielle-tage-liste .spezieller-tag-eintrag').last();
                    var $beg = $newEntry.find('input[name$="[beginn]"]');
                    var $end = $newEntry.find('input[name$="[ende]"]');
                    // take server-rendered value attr (10:00 / 18:00) or fallback
                    var beg24 = $beg.attr('value') || $beg.val() || '10:00';
                    var end24 = $end.attr('value') || $end.val() || '18:00';
                    var beg12 = convert24to12(beg24);
                    var end12 = convert24to12(end24);
                    var begParts = beg12.split(' ');
                    var endParts = end12.split(' ');
                    var begHHMM = begParts[0] || '10:00';
                    var endHHMM = endParts[0] || '18:00';
                    var begAMPM = begParts[1] || 'AM';
                    var endAMPM = endParts[1] || 'PM';

                    $beg.attr('type', 'text').data('pattern', '^([0-1]?[0-9]|2[0-3]):[0-5][0-9]\\s*(AM|PM)$').attr('placeholder', '--:-- AM/PM').val(begHHMM).attr('value', begHHMM).trigger('input');
                    ensureAmPmToggle($beg, begAMPM);
                    $beg.data('raw-digits', (begHHMM || '10:00').replace(':',''));
                    setupAmPmMasking($beg);

                    $end.attr('type', 'text').data('pattern', '^([0-1]?[0-9]|2[0-3]):[0-5][0-9]\\s*(AM|PM)$').attr('placeholder', '--:-- AM/PM').val(endHHMM).attr('value', endHHMM).trigger('input');
                    ensureAmPmToggle($end, endAMPM);
                    $end.data('raw-digits', (endHHMM || '18:00').replace(':',''));
                    setupAmPmMasking($end);
                }

                sortSpecialDays();
            } else {
                alert(simpbookTranslations.datum_auswaehlen);
            }
        });

        $('#spezielle-tage-liste').on('change', '.spezieller-tag-status', function() {
            var $eintrag = $(this).closest('.spezieller-tag-eintrag');
            var datum = $eintrag.data('datum');
            if ($(this).val() === 'speziell') {
                $eintrag.find('.spezielle-zeiten-inputs').slideDown(function() {
                    if (simpbookDatepickerTranslations.currentLanguage === 'en_US_AMPM') {
                        convertTimeInputsForUS();
                    }
                });
            } else {
                $eintrag.find('.spezielle-zeiten-inputs').slideUp();
            }
        });

        $('#spezielle-tage-liste').on('click', '.remove-speziellen-tag-btn', function() {
            $(this).closest('.spezieller-tag-eintrag').remove();
            $("#datepicker_speziell").datepicker("refresh");
            sortSpecialDays();
        });

        $('#spezielle-tage-liste').on('input change', 'input[name$="[beginn]"], input[name$="[ende]"]', function() {
            var $entry = $(this).closest('.spezieller-tag-eintrag');
        });

        // UX: when focusing an AM/PM text time input select all so the user can overwrite directly
        $(document).on('focus', '.time-input[type="text"]', function(e) {
            var $input = $(this);
            // small timeout to ensure selection works on some browsers
            setTimeout(function() { try { $input.select(); } catch (err) {} }, 0);
        });

        // Masked input behavior for AM/PM text time inputs
        $(document).on('keydown', '.time-input[type="text"]', function(e) {
            var $input = $(this);
            if (e.ctrlKey || e.metaKey) return; // allow copy/paste shortcuts
            var key = e.key;

            // If there's a selection, clear the raw-digits so typing replaces cleanly
            try {
                var selStart = this.selectionStart;
                var selEnd = this.selectionEnd;
                if (typeof selStart !== 'undefined' && selEnd > selStart) {
                    $input.data('raw-digits', '');
                }
            } catch (err) {
                // ignore
            }

            if (/^[0-9]$/.test(key)) {
                e.preventDefault();
                var raw = $input.data('raw-digits') || '';
                if (raw.length < 4) {
                    raw += key;
                    $input.data('raw-digits', raw);
                    $input.val(formatFromRaw(raw));
                    $input.attr('value', $input.val()).trigger('input');
                }
            } else if (key === 'Backspace') {
                e.preventDefault();
                var raw = $input.data('raw-digits') || '';
                raw = raw.slice(0, -1);
                $input.data('raw-digits', raw);
                $input.val(formatFromRaw(raw));
                $input.attr('value', $input.val()).trigger('input');
            } else if (key.toLowerCase() === 'a' || key.toLowerCase() === 'p') {
                var $wrap = $input.next('.ampm-toggle');
                if ($wrap.length) {
                    e.preventDefault();
                    var desired = key.toLowerCase() === 'a' ? 'AM' : 'PM';
                    $wrap.find('.ampm-btn').removeClass('active').attr('aria-pressed','false').filter('[data-ampm="' + desired + '"]').addClass('active').attr('aria-pressed','true');
                    // persist selection on the input as well
                    $input.data('ampm', desired);
                    $input.attr('data-ampm', desired);
                    // if we have a forced 24h computed earlier, update it now
                    var rawDigits = $input.data('raw-digits') || '';
                    var time12 = '';
                    if (isCompleteRaw(rawDigits)) {
                        time12 = rawDigits.substr(0,2) + ':' + rawDigits.substr(2,2);
                    } else {
                        var cur = $input.val();
                        if (/^\d{1,2}:\d{2}$/.test(cur)) time12 = cur;
                    }
                    if (time12) {
                        var forced24 = convert12to24(time12 + ' ' + desired);
                        $input.data('force-24h', forced24);
                        $input.attr('data-force-24h', forced24);
                    }
                    $input.trigger('input');
                }
            } else if (key === ':' || key === ' ') {
                e.preventDefault();
            } else if (['ArrowLeft','ArrowRight','Home','End','Tab'].indexOf(key) !== -1) {
                // allow navigation
            } else {
                // block any other input
                e.preventDefault();
            }
        });

        $(document).on('paste', '.time-input[type="text"]', function(e) {
            e.preventDefault();
            var clipboardData = (e.originalEvent || e).clipboardData;
            var text = clipboardData ? clipboardData.getData('text') : '';
            var digits = (text || '').replace(/\D/g, '').substr(0, 4);
            var $input = $(this);
            $input.data('raw-digits', digits);
            $input.val(formatFromRaw(digits));
            $input.attr('value', $input.val()).trigger('input');
            var ampmMatch = text.match(/(AM|PM|am|pm|A|P|a|p)/);
            if (ampmMatch) {
                var $wrap = $input.next('.ampm-toggle');
                if ($wrap.length) {
                    var desired = /p/i.test(ampmMatch[0]) ? 'PM' : 'AM';
                    $wrap.find('.ampm-btn').removeClass('active').attr('aria-pressed','false').filter('[data-ampm="' + desired + '"]').addClass('active').attr('aria-pressed','true');
                    // persist selection
                    $input.data('ampm', desired);
                    $input.trigger('input');
                }
            }
        });

        function sortSpecialDays() {
            var $list = $('#spezielle-tage-liste');
            var $items = $list.children('.spezieller-tag-eintrag');

            $items.sort(function(a, b) {
                var dateA = $(a).data('datum');
                var dateB = $(b).data('datum');
                if (dateA < dateB) return -1;
                if (dateA > dateB) return 1;
                return 0;
            });
            $.each($items, function(idx, itm) { $list.append(itm); });
        }
        sortSpecialDays();

        // COLOR PICKER LOGIC
        $('#container_color_picker').on('input change', function() {
            $('#container_background_input').val($(this).val());
            $(this).attr('name', 'simpbook_container_background');
            $('#container_background_input').attr('name', 'container_background_text_dummy');
        });
        $('#container_background_input').on('input change', function() {
            var colorValue = $(this).val();
            if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(colorValue)) {
                $('#container_color_picker').val(colorValue).attr('name', 'simpbook_container_background');
            }
        });
        $('#apply_container_color_btn').click(function() {
            var colorValue = $('#container_background_input').val();
            if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(colorValue)) {
                $('#container_color_picker').val(colorValue).attr('name', 'simpbook_container_background');
            } else {
                alert(simpbookTranslations.invalid_hex_color);
                $('#container_background_input').val($('#container_color_picker').val());
            }
        });

        // text color
        $('#text_color_picker').on('input change', function() {
            $('#text_color_input').val($(this).val());
            $(this).attr('name', 'simpbook_text_color');
            $('#text_color_input').attr('name', 'text_color_text_dummy');
        });
        $('#text_color_input').on('input change', function() {
            var colorValue = $(this).val();
            if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(colorValue)) {
                $('#text_color_picker').val(colorValue).attr('name', 'simpbook_text_color');
            }
        });
        $('#apply_text_color_btn').click(function() {
            var colorValue = $('#text_color_input').val();
            if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(colorValue)) {
                $('#text_color_picker').val(colorValue).attr('name', 'simpbook_text_color');
            } else {
                alert(simpbookTranslations.invalid_hex_color);
                $('#text_color_input').val($('#text_color_picker').val());
            }
        });

        // button color
        $('#button_color_picker').on('input change', function() {
            $('#button_color_input').val($(this).val());
            $(this).attr('name', 'simpbook_button_color');
            $('#button_color_input').attr('name', 'button_color_text_dummy');
        });
        $('#button_color_input').on('input change', function() {
            var colorValue = $(this).val();
            if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(colorValue)) {
                $('#button_color_picker').val(colorValue).attr('name', 'simpbook_button_color');
            }
        });
        $('#apply_button_color_btn').click(function() {
            var colorValue = $('#button_color_input').val();
            if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(colorValue)) {
                $('#button_color_picker').val(colorValue).attr('name', 'simpbook_button_color');
            } else {
                alert(simpbookTranslations.invalid_hex_color);
                $('#button_color_input').val($('#button_color_picker').val());
            }
        });

        // button text color
        $('#button_text_color_picker').on('input change', function() {
            $('#button_text_color_input').val($(this).val());
            $(this).attr('name', 'simpbook_button_text_color');
            $('#button_text_color_input').attr('name', 'button_text_color_text_dummy');
        });
        $('#button_text_color_input').on('input change', function() {
            var colorValue = $(this).val();
            if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(colorValue)) {
                $('#button_text_color_picker').val(colorValue).attr('name', 'simpbook_button_text_color');
            }
        });
        $('#apply_button_text_color_btn').click(function() {
            var colorValue = $('#button_text_color_input').val();
            if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(colorValue)) {
                $('#button_text_color_picker').val(colorValue).attr('name', 'simpbook_button_text_color');
            } else {
                alert(simpbookTranslations.invalid_hex_color);
                $('#button_text_color_input').val($('#button_text_color_picker').val());
            }
        });

        // tile background
        $('#tile_color_picker').on('input change', function() {
            $('#tile_background_input').val($(this).val());
            $(this).attr('name', 'simpbook_tile_background');
            $('#tile_background_input').attr('name', 'tile_background_text_dummy');
        });
        $('#tile_background_input').on('input change', function() {
            var colorValue = $(this).val();
            if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(colorValue)) {
                $('#tile_color_picker').val(colorValue).attr('name', 'simpbook_tile_background');
            }
        });
        $('#apply_tile_color_btn').click(function() {
            var colorValue = $('#tile_background_input').val();
            if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(colorValue)) {
                $('#tile_color_picker').val(colorValue).attr('name', 'simpbook_tile_background');
            } else {
                alert(simpbookTranslations.invalid_hex_color);
                $('#tile_background_input').val($('#tile_color_picker').val());
            }
        });

        // tile text color
        $('#tile_text_color_picker').on('input change', function() {
            $('#tile_text_color_input').val($(this).val());
            $(this).attr('name', 'simpbook_tile_text_color');
            $('#tile_text_color_input').attr('name', 'tile_text_color_text_dummy');
        });
        $('#tile_text_color_input').on('input change', function() {
            var colorValue = $(this).val();
            if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(colorValue)) {
                $('#tile_text_color_picker').val(colorValue).attr('name', 'simpbook_tile_text_color');
            }
        });
        $('#apply_tile_text_color_btn').click(function() {
            var colorValue = $('#tile_text_color_input').val();
            if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(colorValue)) {
                $('#tile_text_color_picker').val(colorValue).attr('name', 'simpbook_tile_text_color');
            } else {
                alert(simpbookTranslations.invalid_hex_color);
                $('#tile_text_color_input').val($('#tile_text_color_picker').val());
            }
        });

        // Enter to apply
        $('#container_background_input, #text_color_input, #button_color_input, #tile_background_input, #tile_text_color_input').keypress(function(e) {
            if (e.which == 13) {
                e.preventDefault();
                $(this).next('button').click();
            }
        });

        // initial name attributes
        $('#container_color_picker').attr('name', 'simpbook_container_background');
        $('#container_background_input').attr('name', 'container_background_text_dummy');
        $('#text_color_picker').attr('name', 'text_color');
        $('#text_color_input').attr('name', 'text_color_text_dummy');
        $('#button_color_picker').attr('name', 'button_color');
        $('#button_color_input').attr('name', 'button_color_text_dummy');
        $('#button_text_color_picker').attr('name', 'simpbook_button_text_color');
        $('#button_text_color_input').attr('name', 'button_text_color_text_dummy');
        $('#tile_color_picker').attr('name', 'tile_background');
        $('#tile_background_input').attr('name', 'tile_background_text_dummy');
        $('#tile_text_color_picker').attr('name', 'simpbook_tile_text_color');
        $('#tile_text_color_input').attr('name', 'tile_text_color_text_dummy');

        var currentLoadedLanguage = $('#simpbook_language_override').val() || 'auto';

        function loadEmailTemplatesForLanguage(language) {
            var nonce = nonces.simpbook_email_templates_nonce;
            var ajaxUrlLocal = ajaxUrl;

            $.ajax({
                url: ajaxUrlLocal,
                type: 'POST',
                data: {
                    action: 'simpbook_get_email_templates',
                    simpbook_nonce: nonce,
                    simpbook_language: language
                },
                success: function(response) {
                    if (response.success && response.data) {
                        var templates = response.data;

                        $('#email_bestaetigungs_betreff').val(templates.email_bestaetigungs_betreff || '');
                        $('#email_bestaetigungs_nachricht').val(templates.email_bestaetigungs_nachricht || '');
                        $('#email_bestaetigt_betreff').val(templates.email_bestaetigt_betreff || '');
                        $('#email_bestaetigt_nachricht').val(templates.email_bestaetigt_nachricht || '');
                        $('#email_abgelehnt_betreff').val(templates.email_abgelehnt_betreff || '');
                        $('#email_abgelehnt_nachricht').val(templates.email_abgelehnt_nachricht || '');
                        $('#email_erinnerung_betreff').val(templates.email_erinnerung_betreff || '');
                        $('#email_erinnerung_nachricht').val(templates.email_erinnerung_nachricht || '');
                        $('#email_storniert_betreff').val(templates.email_storniert_betreff || '');
                        $('#email_storniert_nachricht').val(templates.email_storniert_nachricht || '');

                        currentLoadedLanguage = language;
                    } else {
                        console.error('Fehler beim Laden der Email-Templates:', response.data);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX-Fehler beim Laden der Email-Templates:', error);
                }
            });
        }

        $('#simpbook_language_override').on('change', function() {
            var selectedLanguage = $(this).val();
            simpbookDatepickerTranslations.currentLanguage = selectedLanguage;

            // Preserve current special-day status & times so we can restore after conversion
            // IMPORTANT: Also capture AM/PM status from toggle buttons or data attributes
            $('#spezielle-tage-liste .spezieller-tag-eintrag').each(function() {
                var $entry = $(this);
                var status = $entry.find('.spezieller-tag-status').val();
                var begInput = $entry.find('input[name$="[beginn]"]');
                var endInput = $entry.find('input[name$="[ende]"]');
                
                // Get the displayed value
                var begVal = begInput.val() || begInput.attr('value') || '';
                var endVal = endInput.val() || endInput.attr('value') || '';
                
                // Check for AM/PM toggle and get the correct 24h value
                var begAmPm = '';
                var endAmPm = '';
                var beg24 = begVal;
                var end24 = endVal;
                
                // Get AM/PM from toggle buttons if they exist
                var $begToggle = begInput.next('.ampm-toggle');
                var $endToggle = endInput.next('.ampm-toggle');
                
                if ($begToggle.length) {
                    var $activeBtn = $begToggle.find('.ampm-btn.active');
                    begAmPm = $activeBtn.length ? ($activeBtn.data('ampm') || $activeBtn.attr('data-ampm') || 'AM') : (begInput.data('ampm') || begInput.attr('data-ampm') || 'AM');
                    begAmPm = String(begAmPm).toUpperCase();
                    // Convert to 24h for storage
                    if (begVal && /^\d{1,2}:\d{2}$/.test(begVal)) {
                        beg24 = convert12to24(begVal + ' ' + begAmPm);
                    }
                } else if (begInput.data('original-24h-time')) {
                    beg24 = begInput.data('original-24h-time');
                }
                
                if ($endToggle.length) {
                    var $activeEndBtn = $endToggle.find('.ampm-btn.active');
                    endAmPm = $activeEndBtn.length ? ($activeEndBtn.data('ampm') || $activeEndBtn.attr('data-ampm') || 'AM') : (endInput.data('ampm') || endInput.attr('data-ampm') || 'AM');
                    endAmPm = String(endAmPm).toUpperCase();
                    // Convert to 24h for storage
                    if (endVal && /^\d{1,2}:\d{2}$/.test(endVal)) {
                        end24 = convert12to24(endVal + ' ' + endAmPm);
                    }
                } else if (endInput.data('original-24h-time')) {
                    end24 = endInput.data('original-24h-time');
                }

                $entry.data('preserve', { status: status, beg: beg24, end: end24 });
            });

            if (selectedLanguage === 'en_US_AMPM') {
                convertTimeInputsForUS();

                // restore special-day times in AM/PM format
                $('#spezielle-tage-liste .spezieller-tag-eintrag').each(function() {
                    var $entry = $(this);
                    var p = $entry.data('preserve') || {};
                    if (p.status === 'speziell') {
                        var $beg = $entry.find('input[name$="[beginn]"]');
                        var $end = $entry.find('input[name$="[ende]"]');
                        var beg24 = p.beg || $beg.attr('value') || $beg.val() || '';
                        var end24 = p.end || $end.attr('value') || $end.val() || '';
                        if (beg24) {
                            var beg12 = convert24to12(beg24);
                            $beg.attr('type', 'text').val(beg12).attr('value', beg12).trigger('input');
                        }
                        if (end24) {
                            var end12 = convert24to12(end24);
                            $end.attr('type', 'text').val(end12).attr('value', end12).trigger('input');
                        }
                        $entry.find('.spezielle-zeiten-inputs').show();
                        $entry.find('.spezieller-tag-status').val('speziell').trigger('change');
                    }
                });
            } else {
                // switching to 24h
                convertTimeInputsTo24h();

                // restore special-day times in 24h format (already stored as 24h in preserve)
                $('#spezielle-tage-liste .spezieller-tag-eintrag').each(function() {
                    var $entry = $(this);
                    var p = $entry.data('preserve') || {};
                    if (p.status === 'speziell') {
                        var $beg = $entry.find('input[name$="[beginn]"]');
                        var $end = $entry.find('input[name$="[ende]"]');
                        // Values are already in 24h format from the preserve logic
                        var beg = p.beg || '';
                        var end = p.end || '';

                        if (beg) { $beg.attr('type', 'time').val(beg).attr('value', beg).trigger('input'); }
                        if (end) { $end.attr('type', 'time').val(end).attr('value', end).trigger('input'); }
                        $entry.find('.spezielle-zeiten-inputs').show();
                        $entry.find('.spezieller-tag-status').val('speziell').trigger('change');
                    }
                });
            }

            loadEmailTemplatesForLanguage(selectedLanguage);
        });

        $('#tab-emails').on('change', function() {
            if ($(this).is(':checked')) {
                var currentLanguageLocal = $('#simpbook_language_override').val();
                loadEmailTemplatesForLanguage(currentLanguageLocal);
            }
        });

        // ==========================================================
        // Design-Tab: Live-Vorschau Funktionalität
        // ==========================================================

        function debounce(func, wait) {
            var timeout;
            return function() {
                var context = this, args = arguments;
                clearTimeout(timeout);
                timeout = setTimeout(function() { func.apply(context, args); }, wait);
            };
        }

        function loadFormPreview() {
            var $iframe = $('#simpbook-form-preview-iframe');
            if ($iframe.length === 0) return;

            var previewUrl = ajaxUrl +
                '?action=simpbook_get_form_preview' +
                '&button_color='          + encodeURIComponent($('#button_color_picker').val()          || '#2271b1') +
                '&button_text_color='     + encodeURIComponent($('#button_text_color_picker').val()     || '#ffffff') +
                '&button_border_radius='  + encodeURIComponent($('#button_border_radius_input').val()   || '8') +
                '&container_background=' + encodeURIComponent($('#container_color_picker').val()       || '#8bbce4') +
                '&text_color='           + encodeURIComponent($('#text_color_picker').val()            || '#000000') +
                '&tile_background='      + encodeURIComponent($('#tile_color_picker').val()            || '#ffffff') +
                '&tile_text_color='      + encodeURIComponent($('#tile_text_color_picker').val()       || '#333333') +
                '&border_radius='        + encodeURIComponent($('#border_radius_input').val()          || '8') +
                '&tile_border_radius='   + encodeURIComponent($('#tile_border_radius_input').val()     || '12') +
                '&form_header_date='     + encodeURIComponent($('#form_header_date_input').val()       || '') +
                '&form_header_service='  + encodeURIComponent($('#form_header_service_input').val()    || '') +
                '&form_header_employee=' + encodeURIComponent($('#form_header_employee_input').val()   || '') +
                '&form_header_time='     + encodeURIComponent($('#form_header_time_input').val()       || '') +
                '&form_header_contact='  + encodeURIComponent($('#form_header_contact_input').val()    || '') +
                '&form_header_booking_option=' + encodeURIComponent($('#form_header_booking_option_input').val() || '');

            $iframe.attr('src', previewUrl);
        }

        var debouncedPreviewUpdate = debounce(loadFormPreview, 500);

        // Initiale Vorschau laden wenn Design-Tab bereits aktiv ist
        if ($('#tab-design').is(':checked')) {
            setTimeout(loadFormPreview, 300);
        }

        // Vorschau laden wenn Design-Tab aktiviert wird
        $('#tab-design').on('change', function() {
            if ($(this).is(':checked')) {
                setTimeout(loadFormPreview, 300);
            }
        });

        // Farb-Picker Änderungen
        $('#button_color_picker, #container_color_picker, #text_color_picker, #tile_color_picker, #tile_text_color_picker, #button_text_color_picker').on('input change', function() {
            debouncedPreviewUpdate();
        });

        // Eckenradius Änderungen
        $('#border_radius_input, #tile_border_radius_input, #button_border_radius_input').on('input change', function() {
            debouncedPreviewUpdate();
        });

        // Überschriften Änderungen
        $('#form_header_date_input, #form_header_service_input, #form_header_employee_input, #form_header_time_input, #form_header_contact_input, #form_header_booking_option_input').on('input keyup', function() {
            debouncedPreviewUpdate();
        });

        // "Übernehmen"-Buttons aktualisieren die Vorschau sofort
        $('#apply_button_color_btn, #apply_container_color_btn, #apply_text_color_btn, #apply_tile_color_btn, #apply_tile_text_color_btn, #apply_button_text_color_btn').on('click', function() {
            setTimeout(loadFormPreview, 50);
        });

        $('form').on('submit', function(e) {
            var checkedTab = $('.simpbook-tabs input[type="radio"]:checked');
            if (checkedTab.length > 0) {
                var currentTabId = checkedTab.attr('id').replace('tab-', '');
                $('#simpbook-active-tab').val(currentTabId);
            }

            var selectedLanguage = $('#simpbook_language_override').val();
            var form = $(this);
            var submitButton = form.find('input[type="submit"][name="simpbook_einstellungen_submit"]');

            // Update currentLanguage tracking variable (but don't re-convert times - 
            // the first submit handler already converted to 24h format)
            if (selectedLanguage !== currentLanguage) {
                currentLanguage = selectedLanguage;
            }

            if ($('#email_bestaetigungs_betreff').length > 0) {
                if (currentLoadedLanguage !== selectedLanguage) {
                    e.preventDefault();
                    submitButton.prop('disabled', true).val(simpbookTranslations.loading_templates || 'Lade Templates...');

                    var nonce = nonces.simpbook_email_templates_nonce;
                    var ajaxUrlLocal = ajaxUrl;

                    $.ajax({
                        url: ajaxUrlLocal,
                        type: 'POST',
                        async: false,
                        data: {
                            action: 'simpbook_get_email_templates',
                            simpbook_nonce: nonce,
                            simpbook_language: selectedLanguage
                        },
                        success: function(response) {
                            if (response.success && response.data) {
                                var templates = response.data;
                                $('#email_bestaetigungs_betreff').val(templates.email_bestaetigungs_betreff || '');
                                $('#email_bestaetigungs_nachricht').val(templates.email_bestaetigungs_nachricht || '');
                                $('#email_bestaetigt_betreff').val(templates.email_bestaetigt_betreff || '');
                                $('#email_bestaetigt_nachricht').val(templates.email_bestaetigt_nachricht || '');
                                $('#email_abgelehnt_betreff').val(templates.email_abgelehnt_betreff || '');
                                $('#email_abgelehnt_nachricht').val(templates.email_abgelehnt_nachricht || '');

                                currentLoadedLanguage = selectedLanguage;
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('AJAX-Fehler beim Laden der Email-Templates:', error);
                        },
                        complete: function() {
                            submitButton.prop('disabled', false).val(simpbookTranslations.save_settings || 'Einstellungen speichern');
                            form.off('submit');
                            form[0].submit();
                        }
                    });

                    return false;
                }
            }
        });

        // === Urlaub & Saison Verwaltung ===
        var urlaubCounter = 1000;
        var urlaubPickersInitialized = false;

        function initializeUrlaubDatepicker() {
            if (urlaubPickersInitialized) return;
            if ($('#urlaub_datepicker_von').length === 0) return;
            if (typeof($.datepicker) === 'undefined') { setTimeout(initializeUrlaubDatepicker, 100); return; }

            var commonOpts = {
                dateFormat: dateFormat,
                minDate: 0,
                firstDay: firstDay,
                monthNames: simpbookDatepickerTranslations.monthNames,
                monthNamesShort: simpbookDatepickerTranslations.monthNamesShort,
                dayNames: simpbookDatepickerTranslations.dayNames,
                dayNamesShort: simpbookDatepickerTranslations.dayNamesShort,
                dayNamesMin: simpbookDatepickerTranslations.dayNamesMin,
                beforeShowDay: function(date) {
                    var ymd = $.datepicker.formatDate('yy-mm-dd', date);
                    // Already-saved vacation ranges → orange
                    if (urlaubDates.indexOf(ymd) !== -1) {
                        return [true, 'urlaub-gesperrt-tag', ''];
                    }
                    // Special closed days from DOM (added but not yet saved counts too)
                    var $eintrag = $('#spezielle-tage-liste .spezieller-tag-eintrag[data-datum="' + ymd + '"]');
                    if ($eintrag.length > 0 && $eintrag.find('select.spezieller-tag-status').val() === 'geschlossen') {
                        return [true, 'speziell-geschlossen-tag', ''];
                    }
                    // Closed weekdays
                    if (isRegulaererWochentagDeaktiviert(date)) {
                        return [true, 'deaktivierter-wochentag', ''];
                    }
                    return [true, '', ''];
                }
            };

            $('#urlaub_datepicker_von').datepicker($.extend({}, commonOpts, {
                beforeShow: function() {
                    $(this).prop('readonly', false);
                },
                onClose: function() {
                    var d = $(this).datepicker('getDate');
                    if (d) {
                        $(this).data('ymd', $.datepicker.formatDate('yy-mm-dd', d));
                        $(this).val(formatDateForDisplay(d));
                        $('#urlaub_datepicker_bis').datepicker('option', 'minDate', d);
                    } else {
                        $(this).data('ymd', '');
                    }
                    $(this).prop('readonly', true);
                },
                onSelect: function() {
                    var d = $(this).datepicker('getDate');
                    if (d) {
                        $(this).data('ymd', $.datepicker.formatDate('yy-mm-dd', d));
                        var that = this;
                        setTimeout(function() {
                            $(that).val(formatDateForDisplay(d));
                            $('#urlaub_datepicker_bis').datepicker('option', 'minDate', d);
                        }, 10);
                    }
                }
            }));

            $('#urlaub_datepicker_bis').datepicker($.extend({}, commonOpts, {
                beforeShow: function() {
                    $(this).prop('readonly', false);
                },
                onClose: function() {
                    var d = $(this).datepicker('getDate');
                    if (d) {
                        $(this).data('ymd', $.datepicker.formatDate('yy-mm-dd', d));
                        $(this).val(formatDateForDisplay(d));
                    } else {
                        $(this).data('ymd', '');
                    }
                    $(this).prop('readonly', true);
                },
                onSelect: function() {
                    var d = $(this).datepicker('getDate');
                    if (d) {
                        $(this).data('ymd', $.datepicker.formatDate('yy-mm-dd', d));
                        var that = this;
                        setTimeout(function() { $(that).val(formatDateForDisplay(d)); }, 10);
                    }
                }
            }));

            urlaubPickersInitialized = true;
        }

        $('#add-urlaub-btn').click(function() {
            var vonYmd = $('#urlaub_datepicker_von').data('ymd') || '';
            var bisYmd = $('#urlaub_datepicker_bis').data('ymd') || '';
            if (!vonYmd || !bisYmd) {
                alert(simpbookTranslations.urlaub_beide_daten_auswaehlen || 'Bitte Start- und Enddatum ausw\u00e4hlen.');
                return;
            }
            if (bisYmd < vonYmd) {
                alert(simpbookTranslations.urlaub_enddatum_nach_startdatum || 'Das Enddatum muss nach dem Startdatum liegen.');
                return;
            }
            var counter = urlaubCounter++;
            var vonParts = vonYmd.split('-');
            var bisParts = bisYmd.split('-');
            var vonDate = new Date(parseInt(vonParts[0]), parseInt(vonParts[1]) - 1, parseInt(vonParts[2]));
            var bisDate = new Date(parseInt(bisParts[0]), parseInt(bisParts[1]) - 1, parseInt(bisParts[2]));
            var vonDisplay = formatDateForDisplay(vonDate);
            var bisDisplay = formatDateForDisplay(bisDate);
            var html = '<div class="spezieller-tag-eintrag urlaub-zeitraum-eintrag" data-von="' + vonYmd + '" data-bis="' + bisYmd + '">' +
                '<strong>' + vonDisplay + ' \u2013 ' + bisDisplay + '</strong>' +
                '<input type="hidden" name="simpbook_urlaub_konfiguration[' + counter + '][von]" value="' + vonYmd + '">' +
                '<input type="hidden" name="simpbook_urlaub_konfiguration[' + counter + '][bis]" value="' + bisYmd + '">' +
                '<button type="button" class="button button-link-delete remove-urlaub-btn">' + (simpbookTranslations.entfernen || 'Entfernen') + '</button>' +
                '</div>';
            $('#urlaub-zeitraeume-liste').append(html);
            $('#urlaub_datepicker_von').val('').data('ymd', '');
            $('#urlaub_datepicker_bis').val('').data('ymd', '').datepicker('option', 'minDate', 0);
        });

        $('#urlaub-zeitraeume-liste').on('click', '.remove-urlaub-btn', function() {
            $(this).closest('.urlaub-zeitraum-eintrag').remove();
        });

        // ========================================================
        // Email Logo Upload
        // ========================================================
        (function() {
            var simpbookLogoFrame;
            $('#simpbook-email-logo-upload').on('click', function(e) {
                e.preventDefault();
                if (simpbookLogoFrame) { simpbookLogoFrame.open(); return; }
                simpbookLogoFrame = wp.media({
                    title: 'Select Email Header Logo',
                    button: { text: 'Use this image' },
                    multiple: false
                });
                simpbookLogoFrame.on('select', function() {
                    var attachment = simpbookLogoFrame.state().get('selection').first().toJSON();
                    $('#simpbook_email_header_logo').val(attachment.url);
                    $('#simpbook-email-logo-preview').attr('src', attachment.url).show();
                    $('#simpbook-email-logo-remove').show();
                    // Refresh active preview if open
                    var $active = $('.simpbook-email-card.is-active');
                    if ($active.length) { simpbookShowEmailPreview($active); }
                });
                simpbookLogoFrame.open();
            });
            $('#simpbook-email-logo-remove').on('click', function() {
                $('#simpbook_email_header_logo').val('');
                $('#simpbook-email-logo-preview').attr('src', '').hide();
                $(this).hide();
                var $active = $('.simpbook-email-card.is-active');
                if ($active.length) { simpbookShowEmailPreview($active); }
            });
        })();

        // ========================================================
        // Email Template Preview
        // ========================================================
        var simpbookShowEmailPreview;
        (function() {
            var sampleData = {
                name: 'Max Mustermann',
                email: 'max@beispiel.at',
                phone: '+43 660 123456',
                date: '15.01.2025',
                time: '14:00',
                service_name: 'Massage 60 Min',
                employee_name: 'Anna M\u00fcller',
                employee_name_label: 'Mitarbeiter',
                booking_option: 'Booking Option: Standard',
                booking_price: '\u20ac 60,00',
                message: 'Bitte Fensterplatz falls m\u00f6glich.',
                company_name: 'Muster GmbH',
                cancellation_link: 'https://beispiel.at/?simpbook_cancel=abc123',
                status: 'BEST\u00c4TIGT'
            };

            var colorSchemes = {
                bestaetigt: { header: '#059669', sub: '#a7f3d0' },
                abgelehnt:  { header: '#dc2626', sub: '#fecaca' },
                storniert:  { header: '#d97706', sub: '#fde68a' },
                'default':  { header: '#1a4a8a', sub: '#c7d2fe' }
            };

            function getScheme(cardId) {
                // Check bestaetigungs BEFORE bestaetigt (bestaetigungs contains bestaetigt as substring)
                if (cardId.indexOf('bestaetigungs') !== -1) {
                    // Booking request — use design settings colors
                    var containerColor = $('#container_color_picker').val() || '#8bbce4';
                    var textColor = $('#text_color_picker').val() || '#000000';
                    return { header: containerColor, sub: '#f0f7ff', headerText: textColor };
                }
                if (cardId.indexOf('bestaetigt') !== -1) return colorSchemes.bestaetigt;
                if (cardId.indexOf('abgelehnt') !== -1 || cardId.indexOf('absage') !== -1) return colorSchemes.abgelehnt;
                if (cardId.indexOf('storniert') !== -1) return colorSchemes.storniert;
                return colorSchemes['default'];
            }

            function escHtml(str) {
                return String(str)
                    .replace(/&/g, '&amp;').replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
            }

            function replacePlaceholders(text, data) {
                var result = text;
                Object.keys(data).forEach(function(k) {
                    result = result.split('{' + k + '}').join(String(data[k]));
                });
                return result;
            }

            function plainToHtml(plain, headerColor) {
                var html = '', paragraph = '';
                plain.split('\n').forEach(function(line) {
                    line = line.trim();
                    if (line === '') {
                        if (paragraph !== '') {
                            html += '<p style="margin:0 0 12px 0;">' + paragraph + '</p>\n';
                            paragraph = '';
                        }
                    } else {
                        var linked = escHtml(line).replace(/(https?:\/\/[^\s<>"]+)/g,
                            '<a href="$1" style="color:' + headerColor + ';">$1</a>');
                        paragraph += (paragraph !== '' ? '<br>' : '') + linked;
                    }
                });
                if (paragraph !== '') {
                    html += '<p style="margin:0 0 12px 0;">' + paragraph + '</p>\n';
                }
                return html;
            }

            function buildPreviewHtml(subject, body, cardId) {
                var scheme      = getScheme(cardId);
                var logoUrl     = $('#simpbook_email_header_logo').val() || '';
                var company     = escHtml($('#simpbook_firmen_name').val() || 'My Company');
                var headerText  = scheme.headerText || '#ffffff';
                var bodyHtml    = plainToHtml(body, scheme.header);
                var headerContent;
                if (logoUrl) {
                    headerContent = '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr>' +
                        '<td style="width:70%;vertical-align:middle;padding-right:16px;">' +
                        '<h1 style="margin:0;font-size:20px;font-weight:700;color:' + headerText + ';line-height:1.3;">' + company + '</h1></td>' +
                        '<td style="width:30%;vertical-align:middle;text-align:right;">' +
                        '<img src="' + escHtml(logoUrl) + '" alt="' + company + '" style="max-height:60px;max-width:100%;display:inline-block;"></td>' +
                        '</tr></table>';
                } else {
                    headerContent = '<h1 style="margin:0;font-size:20px;font-weight:700;color:' + headerText + ';">' + company + '</h1>';
                }
                return '<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>' +
                    '<body style="margin:0;padding:0;background:#f4f4f4;font-family:Arial,sans-serif;">' +
                    '<table width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#f4f4f4;padding:30px;"><tr><td align="center">' +
                    '<table width="600" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;width:100%;background:#fff;border-radius:8px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,.1);">' +
                    '<tr><td style="background:' + scheme.header + ';padding:28px 32px;">' + headerContent + '</td></tr>' +
                    '<tr><td style="background:' + scheme.sub + ';padding:12px 32px;"><p style="margin:0;font-size:14px;font-weight:600;color:#1f2937;">' + escHtml(subject) + '</p></td></tr>' +
                    '<tr><td style="padding:32px;color:#374151;font-size:15px;line-height:1.6;">' + bodyHtml + '</td></tr>' +
                    '<tr><td style="background:#f9fafb;padding:20px 32px;border-top:1px solid #e5e7eb;"><p style="margin:0;font-size:12px;color:#9ca3af;text-align:center;">' + company + '</p></td></tr>' +
                    '</table></td></tr></table></body></html>';
            }

            simpbookShowEmailPreview = function($card) {
                var cardId  = $card.data('card-id') || '';
                // Update company_name dynamically from the settings field
                sampleData.company_name = $('#simpbook_firmen_name').val() || 'My Company';
                var subject = replacePlaceholders($card.find('.simpbook-email-subject').val() || '', sampleData);
                var body    = replacePlaceholders($card.find('.simpbook-email-body').val()    || '', sampleData);
                var html    = buildPreviewHtml(subject, body, cardId);
                var $box    = $('#simpbook-email-preview-box');
                var $body   = $('#simpbook-email-preview-body');
                $body.html('<iframe id="simpbook-email-preview-iframe" style="width:100%;height:600px;border:none;display:block;"></iframe>');
                var iframe  = document.getElementById('simpbook-email-preview-iframe');
                var doc     = iframe.contentDocument || iframe.contentWindow.document;
                doc.open(); doc.write(html); doc.close();
                $box.addClass('is-visible');
                $('#content-emails').addClass('simpbook-email-preview-open');
            };

            // Card click — ignore clicks on interactive elements
            $(document).on('click', '.simpbook-email-card', function(e) {
                if ($(e.target).closest('input, textarea, select, button, label, a').length) return;
                var $card = $(this);
                $('.simpbook-email-card').removeClass('is-active');
                $card.addClass('is-active');
                simpbookShowEmailPreview($card);
            });

            // Close button
            $(document).on('click', '#simpbook-email-preview-close', function() {
                $('#simpbook-email-preview-box').removeClass('is-visible');
                $('#content-emails').removeClass('simpbook-email-preview-open');
                $('.simpbook-email-card').removeClass('is-active');
            });

            // Live update when editing the active card
            $(document).on('input change', '.simpbook-email-card.is-active .simpbook-email-subject, .simpbook-email-card.is-active .simpbook-email-body', function() {
                simpbookShowEmailPreview($(this).closest('.simpbook-email-card'));
            });
        })();

    });
})(jQuery);

