document.addEventListener('DOMContentLoaded', function () {
    window.quill = new Quill('#quill-editor', {
        modules: {
            toolbar: [
                [{ 'size': [] }],
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'color': [] }, { 'background': [] }],
                [{ 'header': 1 }, { 'header': 2 }, 'blockquote'],
                [{ 'list': 'ordered' }, { 'list': 'bullet' }, { 'indent': '-1' }, { 'indent': '+1' }],
                [{ 'direction': 'rtl' }, { 'align': [] }],
            ]
        },
        placeholder: 'Compose your prompt...',
        theme: 'snow'
    });

    const hiddenInput = document.getElementById('editor_prompt_aiapp');
   
    const wordCountDisplay = document.getElementById('word-count');

    function updateWordCount() {
        const text = quill.getText().trim();
        const maxToken = parseInt(document.getElementById("prompt-max-token-value").innerHTML ?? 3000 , 10);
        const words = text.length > 0 ? text.split(/\s+/).length : 0;
        const estimatedTokens = Math.ceil(words * 1.33);
        const percentage = Math.ceil((estimatedTokens / maxToken) * 100);


        if (wordCountDisplay) {
            wordCountDisplay.textContent = `${estimatedTokens} / ${maxToken} Est. Tokens Used`;
            wordCountDisplay.style.color = percentage < 50 ? 'green' : percentage < 80 ? 'orange' : 'red';
            wordCountDisplay.style.fontWeight = '600';
            wordCountDisplay.style.fontSize = '13px';
            wordCountDisplay.style.marginBottom = '10px';
        }
    }

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

    window.quill.root.style.minHeight = '250px';

    window.quill.on('text-change', updateWordCount);

    const promptMaxTokenValue = document.getElementById("prompt-max-token-value");
    if (promptMaxTokenValue) {
        const observer = new MutationObserver(updateWordCount);
        observer.observe(promptMaxTokenValue, { childList: true });
    }
});
