(function () {
    function escapeHtml(value) {
        return String(value ?? '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function normalizeColor(value, fallback) {
        const color = String(value || '').trim();
        return /^#[0-9a-fA-F]{6}$/.test(color) ? color.toUpperCase() : fallback;
    }

    function clamp(value, min, max, fallback) {
        const parsed = parseInt(value, 10);
        if (Number.isNaN(parsed)) {
            return fallback;
        }
        return Math.min(max, Math.max(min, parsed));
    }

    function normalizeAlign(value) {
        return ['left', 'center', 'right'].includes(value) ? value : 'center';
    }

    function normalizeTextPosition(value) {
        return ['below', 'side'].includes(value) ? value : 'below';
    }

    function marginStyle(align) {
        if (align === 'left') {
            return 'margin:0 auto 0 0;';
        }
        if (align === 'right') {
            return 'margin:0 0 0 auto;';
        }
        return 'margin:0 auto;';
    }


    function defaultState() {
        return {
            header: {
                background_color: '#F8FAFC',
                text_color: '#243B53',
                logo_url: '',
                logo_alt: '',
                logo_width: 180,
                align: 'center',
                text_position: 'below',
                headline: '',
                text: '',
                show_online_view: true,
                online_view_text: 'E-Mail im Browser ansehen'
            },
            footer: {
                background_color: '#F8FAFC',
                text_color: '#486581',
                text: '',
                show_social: false,
                facebook_url: '',
                instagram_url: '',
                linkedin_url: '',
                youtube_url: '',
                show_unsubscribe: true,
                unsubscribe_text: 'Abmelden',
                show_online_view: false,
                online_view_text: 'Im Browser ansehen',
                show_pause: true,
                pause_text: 'Versand pausieren'
            }
        };
    }

    function normalizeState(rawValue) {
        let parsed = defaultState();
        try {
            const incoming = JSON.parse(rawValue || '{}');
            parsed = {
                header: { ...parsed.header, ...(incoming && incoming.header ? incoming.header : {}) },
                footer: { ...parsed.footer, ...(incoming && incoming.footer ? incoming.footer : {}) }
            };
        } catch (error) {
            parsed = defaultState();
        }

        parsed.header.background_color = normalizeColor(parsed.header.background_color, '#F8FAFC');
        parsed.header.text_color = normalizeColor(parsed.header.text_color, '#243B53');
        parsed.header.logo_width = clamp(parsed.header.logo_width, 80, 320, 180);
        parsed.header.align = normalizeAlign(parsed.header.align);
        parsed.header.text_position = normalizeTextPosition(parsed.header.text_position);
        parsed.header.show_online_view = !!parsed.header.show_online_view;

        parsed.footer.background_color = normalizeColor(parsed.footer.background_color, '#F8FAFC');
        parsed.footer.text_color = normalizeColor(parsed.footer.text_color, '#486581');
        parsed.footer.show_social = !!parsed.footer.show_social;
        parsed.footer.show_unsubscribe = !Object.prototype.hasOwnProperty.call(parsed.footer, 'show_unsubscribe') || !!parsed.footer.show_unsubscribe;
        parsed.footer.show_online_view = !!parsed.footer.show_online_view;
        parsed.footer.show_pause = !!parsed.footer.show_pause;

        return parsed;
    }

    function renderHeaderHtml(state) {
        const header = state.header;
        const rows = [];
        if (header.show_online_view && header.online_view_text) {
            rows.push(`<tr><td align="center" style="padding:0 0 12px 0;font-family:Arial,Helvetica,sans-serif;font-size:12px;line-height:1.5;color:${escapeHtml(header.text_color)};"><a href="[online_view_url]" style="color:${escapeHtml(header.text_color)};text-decoration:underline;">${escapeHtml(header.online_view_text)}</a></td></tr>`);
        }
        const hasTextBlock = !!(header.headline || header.text);
        if (header.logo_url && hasTextBlock && header.text_position === 'side') {
            const textParts = [];
            if (header.headline) {
                textParts.push(`<div style="padding:0 0 10px 0;font-family:Arial,Helvetica,sans-serif;font-size:28px;line-height:1.2;font-weight:700;color:${escapeHtml(header.text_color)};text-align:center;">${escapeHtml(header.headline)}</div>`);
            }
            if (header.text) {
                textParts.push(`<div style="font-family:Arial,Helvetica,sans-serif;font-size:15px;line-height:1.6;color:${escapeHtml(header.text_color)};text-align:center;">${escapeHtml(header.text).replace(/\n/g, '<br>')}</div>`);
            }
            rows.push(`<tr><td align="${escapeHtml(header.align)}" style="padding:0 0 24px 0;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;max-width:100%;${marginStyle(header.align)}"><tr><td valign="middle" style="padding:0 18px 0 0;"><img src="${escapeHtml(header.logo_url)}" alt="${escapeHtml(header.logo_alt)}" width="${header.logo_width}" style="display:block;max-width:100%;height:auto;border:0;"></td><td valign="middle" align="center" style="text-align:center;">${textParts.join('')}</td></tr></table></td></tr>`);
        } else {
            if (header.logo_url) {
                rows.push(`<tr><td align="${escapeHtml(header.align)}" style="padding:0 0 16px 0;"><img src="${escapeHtml(header.logo_url)}" alt="${escapeHtml(header.logo_alt)}" width="${header.logo_width}" style="display:inline-block;max-width:100%;height:auto;border:0;"></td></tr>`);
            }
            if (header.headline) {
                rows.push(`<tr><td align="${escapeHtml(header.align)}" style="padding:0 0 12px 0;font-family:Arial,Helvetica,sans-serif;font-size:28px;line-height:1.2;font-weight:700;color:${escapeHtml(header.text_color)};">${escapeHtml(header.headline)}</td></tr>`);
            }
            if (header.text) {
                rows.push(`<tr><td align="${escapeHtml(header.align)}" style="padding:0 0 24px 0;font-family:Arial,Helvetica,sans-serif;font-size:15px;line-height:1.6;color:${escapeHtml(header.text_color)};">${escapeHtml(header.text).replace(/\n/g, '<br>')}</td></tr>`);
            }
        }
        const headerSection = rows.length
            ? `<tr><td style="padding:28px 24px 8px 24px;background:${escapeHtml(header.background_color)};"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">${rows.join('')}</table></td></tr>`
            : '';
        return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#FFFFFF;">${headerSection}<tr><td style="padding:0;">`;
    }

    function renderFooterHtml(state) {
        const footer = state.footer;
        const rows = [];
        if (footer.text) {
            rows.push(`<tr><td align="center" style="padding:0 0 14px 0;font-family:Arial,Helvetica,sans-serif;font-size:13px;line-height:1.6;color:${escapeHtml(footer.text_color)};">${escapeHtml(footer.text).replace(/\n/g, '<br>')}</td></tr>`);
        }
        const socialLinks = [];
        if (footer.show_social) {
            [
                ['facebook_url', 'Facebook'],
                ['instagram_url', 'Instagram'],
                ['linkedin_url', 'LinkedIn'],
                ['youtube_url', 'YouTube']
            ].forEach(([field, label]) => {
                if (footer[field]) {
                    socialLinks.push(`<a href="${escapeHtml(footer[field])}" style="color:${escapeHtml(footer.text_color)};text-decoration:underline;">${escapeHtml(label)}</a>`);
                }
            });
        }
        if (socialLinks.length) {
            rows.push(`<tr><td align="center" style="padding:0 0 14px 0;font-family:Arial,Helvetica,sans-serif;font-size:13px;line-height:1.6;color:${escapeHtml(footer.text_color)};">${socialLinks.join(' &nbsp;&middot;&nbsp; ')}</td></tr>`);
        }

        const systemLinks = [];
        if (footer.show_unsubscribe && footer.unsubscribe_text) {
            systemLinks.push(`<a href="[unsubscribe_url]" style="color:${escapeHtml(footer.text_color)};text-decoration:underline;">${escapeHtml(footer.unsubscribe_text)}</a>`);
        }
        if (footer.show_online_view && footer.online_view_text) {
            systemLinks.push(`<a href="[online_view_url]" style="color:${escapeHtml(footer.text_color)};text-decoration:underline;">${escapeHtml(footer.online_view_text)}</a>`);
        }
        if (footer.show_pause && footer.pause_text) {
            systemLinks.push(`<a href="[pause_url]" style="color:${escapeHtml(footer.text_color)};text-decoration:underline;">${escapeHtml(footer.pause_text)}</a>`);
        }
        if (systemLinks.length) {
            rows.push(`<tr><td align="center" style="padding:0 0 8px 0;font-family:Arial,Helvetica,sans-serif;font-size:12px;line-height:1.6;color:${escapeHtml(footer.text_color)};">${systemLinks.join(' &nbsp;&middot;&nbsp; ')}</td></tr>`);
        }

        const footerSection = rows.length
            ? `<tr><td style="padding:20px 24px 28px 24px;background:${escapeHtml(footer.background_color)};"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">${rows.join('')}</table></td></tr>`
            : '';
        return `</td></tr>${footerSection}</table>`;
    }

    function initLayoutEditor(form) {
        const modeField = form.querySelector('[data-role="layout-editor-mode"]');
        const sourceInput = form.querySelector('[data-role="layout-source-content"]');
        const headerHtmlInput = form.querySelector('[data-role="layout-header-html"]');
        const footerHtmlInput = form.querySelector('[data-role="layout-footer-html"]');
        const preview = form.querySelector('[data-role="layout-builder-preview"]');
        const panels = Array.from(form.querySelectorAll('[data-layout-editor-panel]'));
        const builderFields = Array.from(form.querySelectorAll('[data-layout-field]'));
        const builderCheckboxes = Array.from(form.querySelectorAll('[data-layout-checkbox]'));
        const state = normalizeState(sourceInput ? sourceInput.value : '');

        function syncHiddenFields() {
            if (!sourceInput || !headerHtmlInput || !footerHtmlInput || !modeField) {
                return;
            }
            if (modeField.value === 'layout_builder') {
                sourceInput.value = JSON.stringify(state);
                headerHtmlInput.value = renderHeaderHtml(state);
                footerHtmlInput.value = renderFooterHtml(state);
            }
        }

        function renderPreview() {
            if (!preview) {
                return;
            }
            preview.innerHTML = `${renderHeaderHtml(state)}<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#ffffff;"><tr><td style="padding:24px;font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:1.6;color:#243B53;text-align:center;">Inhalt der Vorlage erscheint hier.</td></tr></table>${renderFooterHtml(state)}`;
            syncHiddenFields();
        }

        function togglePanels() {
            if (!modeField) {
                return;
            }
            panels.forEach((panel) => {
                panel.classList.toggle('is-active', panel.getAttribute('data-layout-editor-panel') === modeField.value);
            });
            syncHiddenFields();
        }

        builderFields.forEach((field) => {
            const path = String(field.getAttribute('data-layout-field') || '').split('.');
            field.value = state[path[0]][path[1]] ?? '';
            field.addEventListener('input', () => {
                if (path[1].endsWith('color')) {
                    state[path[0]][path[1]] = normalizeColor(field.value, state[path[0]][path[1]]);
                } else if (path[1] === 'logo_width') {
                    state[path[0]][path[1]] = clamp(field.value, 80, 320, 180);
                } else if (path[1] === 'align') {
                    state[path[0]][path[1]] = normalizeAlign(field.value);
                } else {
                    state[path[0]][path[1]] = field.value;
                }
                renderPreview();
            });
        });

        builderCheckboxes.forEach((checkbox) => {
            const path = String(checkbox.getAttribute('data-layout-checkbox') || '').split('.');
            checkbox.checked = !!state[path[0]][path[1]];
            checkbox.addEventListener('change', () => {
                state[path[0]][path[1]] = checkbox.checked;
                renderPreview();
            });
        });

        if (modeField) {
            modeField.addEventListener('change', togglePanels);
        }

        renderPreview();
        togglePanels();
    }

    document.querySelectorAll('[data-layout-editor-form]').forEach(initLayoutEditor);
})();
