import {Controller} from '@hotwired/stimulus';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
//import { ClassicEditor, Bold, Italic, Link, Undo } from 'ckeditor5'; // Im

export default class extends Controller {
    static values = {
        config: String,
        maxlength: Number,
        language: String
    }

    connect() {
        const config = this.getConfig();
        ClassicEditor
            .create(this.element, {
                ...config,
                licenseKey: 'GPL'
            })
            .then(editor => {
                this.editor = editor;
                const charCountWrapper = this.element.parentElement.querySelector('.ck-editor-char');
                const charCountEl = this.element.parentElement.querySelector('[data-char-count]');
                const updateCounts = () => {
                    const data = editor.getData();
                    // Crée un élément temporaire pour extraire le texte pur
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = data;

                    const text = tempDiv.textContent || '';
                    charCountEl.textContent = text.length;

                    return text.length;
                };

                updateCounts(); // Init à 0 ou contenu initial
                editor.model.document.on('change:data', updateCounts);

                // Récupère le wrapper DOM généré par CKEditor
                const ckEditorWrapper = editor.ui.view.editable.element.closest('.ck-editor');
                if (this.element.classList.contains('is-invalid')) {
                    ckEditorWrapper.classList.add('is-invalid');
                }
                if (ckEditorWrapper) {
                    ckEditorWrapper.id = this.element.id + '_textarea'; // Ton ID personnalisé ici
                }

                // Synchroniser la data
                editor.editing.view.document.on('blur', (e) => {
                    this.element.value = editor.getData();
                    //ne lance pas le re-render car cela empêche de bien faire fonctionner la toolbar avec le undo/redo
                    this.element.dispatchEvent(new Event('change', {bubbles: true}));
                });

                editor.model.document.on('change:data', () => {
                    if (charCountWrapper) {
                        charCountWrapper.classList.toggle('is-text-error', updateCounts() > this.maxlengthValue);
                    }
                });
            })
            .catch(error => {
                console.error('Erreur CKEditor:', error);
            });
    }

    disconnect() {
        if (this.editor) {
            this.editor.destroy().catch(error => console.error('Erreur destroy:', error));
        }
    }

    getConfig() {
        const configs = {
            minimal: {
                toolbar: ['bold', 'italic', 'link', 'undo', 'redo'],
                language: this.hasConfigValue ? this.configValue : 'en'
            },
            full: {
                toolbar: [
                    'heading', '|',
                    'bold', 'italic', 'underline', 'link', '|',
                    'bulletedList', 'numberedList', '|',
                    'blockQuote', 'codeBlock', '|',
                    'undo', 'redo'
                ],
                language: this.hasConfigValue ? this.configValue : 'en'
            },
            clean: {
                toolbar: [],
                language: this.hasConfigValue ? this.configValue : 'en'
            }
        };

        const name = this.hasConfigValue ? this.configValue : 'minimal';

        return configs[name];
    }
}
