(function () {
    function syncEditor(editor, hiddenInput) {
        const html = editor.innerHTML.trim();
        hiddenInput.value = html;
    }

    function setupEditor(root) {
        const editor = root.querySelector('[data-blog-editor]');
        const hiddenInput = root.querySelector('[data-blog-editor-value]');
        const publishedToggle = root.querySelector('[data-blog-published-toggle]');
        const publishedValue = root.querySelector('[data-blog-published-value]');
        const form = root.querySelector('form');
        const preview = root.querySelector('[data-blog-preview]');
        const buttons = root.querySelectorAll('[data-blog-command]');

        if (!editor || !hiddenInput) return;

        const renderPreview = () => {
            if (preview) preview.innerHTML = editor.innerHTML;
        };

        editor.addEventListener('input', () => {
            syncEditor(editor, hiddenInput);
            renderPreview();
        });

        buttons.forEach(button => {
            button.addEventListener('click', () => {
                const command = button.getAttribute('data-blog-command');
                const value = button.getAttribute('data-blog-value');
                editor.focus();
                document.execCommand(command, false, value);
                syncEditor(editor, hiddenInput);
                renderPreview();
            });
        });

        const syncPublishedState = () => {
            if (publishedValue && publishedToggle) {
                publishedValue.value = publishedToggle.checked ? 'true' : 'false';
            }
        };

        if (publishedToggle) {
            publishedToggle.addEventListener('change', syncPublishedState);
            syncPublishedState();
        }

        if (form) {
            form.addEventListener('submit', syncPublishedState);
        }

        syncEditor(editor, hiddenInput);
        renderPreview();
    }

    document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('[data-blog-editor-root]').forEach(setupEditor);
    });
})();
