(function($){
    $(document).ready(function(){

        const fonts = window.MM_Announcement_Fonts || {};
        const current = window.MM_Announcement_Current || {};
        const fontSelect = $('#mm-announcement-font');
        const sizeInput = $('#mm-announcement-size');
        const bgInput = $('#mm-announcement-bg');
        const colorInput = $('#mm-announcement-color');
        const previewText = $('#mm-announcement-preview-text');
        const previewWrap = $('#mm-announcement-preview');
        const positionSelect = $('#mm-announcement-position');

        // Helper: lädt Google-Font-Link oder updatet existing
        function ensureGoogleFont(googleName) {
            if (!googleName) return;
            const id = 'mm-admin-google-font';
            const href = 'https://fonts.googleapis.com/css2?family=' + encodeURIComponent(googleName) + ':wght@400;700&display=swap';
            let link = document.getElementById(id);
            if (link) {
                if (link.getAttribute('href') !== href) link.setAttribute('href', href);
            } else {
                link = document.createElement('link');
                link.id = id;
                link.rel = 'stylesheet';
                link.href = href;
                document.head.appendChild(link);
            }
        }

        // Update preview appearance based on font key
        function updatePreviewForFontKey(key) {
            const meta = fonts[key];
            if (!meta) {
                previewText.css('font-family', '');
                return;
            }
            previewText.css('font-family', meta.css);
            if (meta.google && meta.google_name) {
                ensureGoogleFont(meta.google_name);
            }
        }

        // Update size/colors/position UI
        function updateSizeAndColors() {
            const size = parseInt(sizeInput.val(), 10) || 16;
            previewText.css('font-size', size + 'px');
            previewWrap.css('background', bgInput.val());
            previewWrap.css('color', colorInput.val());
        }

        // Read content from wp_editor (TinyMCE) or textarea
        function getEditorText() {
            // Try TinyMCE first
            if ( typeof tinymce !== 'undefined' ) {
                try {
                    const ed = tinymce.get('mm_announcement_text');
                    if (ed && !ed.isHidden()) {
                        // getContent then strip tags
                        const html = ed.getContent({format: 'html'});
                        const tmp = document.createElement('div');
                        tmp.innerHTML = html;
                        return tmp.textContent || tmp.innerText || '';
                    }
                } catch (e) {
                    // ignore
                }
            }
            // Fallback to textarea
            const ta = $('#mm_announcement_text');
            if (ta.length) {
                const tmp = document.createElement('div');
                tmp.innerHTML = ta.val();
                return tmp.textContent || tmp.innerText || '';
            }
            return '';
        }

        // Update preview text from editor content
        function updatePreviewTextFromEditor() {
            const text = getEditorText();
            if (text && text.trim().length) {
                previewText.text(text.trim());
            } else {
                previewText.text(current.text || 'Das ist eine Vorschau: Wie sieht die Schrift aus?');
            }
        }

        // Initialize controls with current settings
        if (current.font) {
            updatePreviewForFontKey(current.font);
            fontSelect.val(current.font);
        } else {
            updatePreviewForFontKey(fontSelect.val());
        }
        if (current.size) sizeInput.val(current.size);
        if (current.bg) bgInput.val(current.bg);
        if (current.color) colorInput.val(current.color);

        updateSizeAndColors();
        updatePreviewTextFromEditor();

        // Attach events --------------------------------------------------

        // font change
        fontSelect.on('change', function(){
            const key = $(this).val();
            updatePreviewForFontKey(key);
        });

        // size/color/position change
        sizeInput.on('input change', updateSizeAndColors );
        bgInput.on('input change', updateSizeAndColors );
        colorInput.on('input change', updateSizeAndColors );

        // Editor changes:
        // - TinyMCE: listen for keyup / change events when editor is ready
        // - Textarea: listen for input
        function attachEditorListeners() {
            // TinyMCE
            if ( typeof tinymce !== 'undefined' ) {
                const ed = tinymce.get('mm_announcement_text');
                if (ed) {
                    ed.on('keyup change NodeChange', function(){
                        updatePreviewTextFromEditor();
                    });
                }
            }

            // Textarea fallback
            $('#mm_announcement_text').on('input change', function(){
                updatePreviewTextFromEditor();
            });
        }

        // TinyMCE initialisation might be async — poll short time then attach
        let tries = 0;
        const waitForEditor = setInterval(function(){
            tries++;
            if ( (typeof tinymce !== 'undefined' && tinymce.get('mm_announcement_text')) || $('#mm_announcement_text').length ) {
                clearInterval(waitForEditor);
                attachEditorListeners();
            } else if (tries > 30) { // about 3s
                clearInterval(waitForEditor);
                // still attach textarea event just in case
                $('#mm_announcement_text').on('input change', updatePreviewTextFromEditor);
            }
        }, 100);

        // Also update preview when the form is programmatically changed (e.g., quicktags)
        $(document).on('change', '#mm-announcement-font, #mm-announcement-size, #mm-announcement-bg, #mm-announcement-color', function(){
            updateSizeAndColors();
            updatePreviewForFontKey($('#mm-announcement-font').val());
            updatePreviewTextFromEditor();
        });

    });
})(jQuery);
