document.addEventListener('DOMContentLoaded', function () {
    const textareas = document.querySelectorAll('textarea.tinymce, textarea.richtext, textarea.rtf-editor');
    if (!textareas.length || typeof Quill === 'undefined') return;

    textareas.forEach((textarea, index) => {
        textarea.style.display = 'none';

        const wrapper = document.createElement('div');
        wrapper.className = 'quill-wrapper mb-3';

        const editor = document.createElement('div');
        editor.id = 'quill-editor-' + index;
        editor.style.minHeight = '220px';
        editor.innerHTML = textarea.value || '';

        wrapper.appendChild(editor);
        textarea.parentNode.insertBefore(wrapper, textarea.nextSibling);

        const quill = new Quill(editor, {
            theme: 'snow',
            modules: {
                toolbar: [
                    [{ header: [1, 2, 3, false] }],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ list: 'ordered' }, { list: 'bullet' }],
                    [{ direction: 'rtl' }, { align: [] }],
                    ['link', 'blockquote', 'code-block'],
                    ['clean']
                ]
            }
        });

        quill.root.innerHTML = textarea.value || '';

        const form = textarea.closest('form');
        if (form) {
            form.addEventListener('submit', function () {
                textarea.value = quill.root.innerHTML;
            });
        }
    });
});
