import Quill from 'quill';
import htmlEditButton from 'quill-html-edit-button';

export function initQuill(selector = '.quill-editor', options = {}) {
    document.querySelectorAll(selector).forEach(function (editorContainer) {
        const hiddenInput = editorContainer.parentElement.querySelector('input[type=hidden]');

        const isRTL = editorContainer.dataset.direction === 'rtl';
        const fontFamily = editorContainer.dataset.font || 'inherit';

        Quill.register('modules/htmlEditButton', htmlEditButton);

        const quill = new Quill(editorContainer, {
            theme: 'snow',
            placeholder: editorContainer.dataset.placeholder || 'Type your content...',
            modules: {
                toolbar: [
                    [{ header: [1, 2, 3, 4, 5, 6, false] }],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ list: 'ordered' }, { list: 'bullet' }],
                    [{ align: [] }],
                    ['link', 'image', 'code-block'],
                    ['clean'],
                ],
                htmlEditButton: {
                    debug: true,
                    msg: "Edit the HTML below",
                    okText: "Ok",
                    cancelText: "Cancel",
                    buttonHTML: "&lt;/&gt;",
                    buttonTitle: "Show HTML source",
                    syntax: false
                }
            },
            ...options
        });

        // Set initial value from hidden input
        quill.root.innerHTML = hiddenInput.value;

        // Apply RTL direction and custom font
        if (isRTL) {
            quill.root.setAttribute('dir', 'rtl');
            quill.root.style.textAlign = 'right';
        }
        quill.root.style.fontFamily = fontFamily;

        // Update hidden input when content changes
        quill.on('text-change', function () {
            hiddenInput.value = quill.root.innerHTML;
        });
    });
}
