/**
 * CKEDITOR RTE
 */
import IGDATAPOOLFE from '@dp/ig_datapool_fe.js';

import {
    ClassicEditor,
    Essentials,
    Paragraph,
    Bold,
    Italic,
    Underline,
    Strikethrough,
    Subscript,
    Superscript,
    SpecialCharacters,
    SpecialCharactersEssentials,
    
    Font,
    Heading,
    List,
    Table,
    Link,
    Alignment,
    Indent,
    HorizontalLine,
    Clipboard,
    GeneralHtmlSupport,
    PastePlainText,
    PasteFromOffice,
    RemoveFormat,
    SourceEditing,
} from 'ckeditor5';
const ckeditorPlugin = {
    ckPlugins: [ 
        Essentials, Paragraph, Bold, Italic, Underline, Strikethrough, 
        Subscript, Superscript, SpecialCharacters, SpecialCharactersEssentials, 
        Font, Heading, List, Table, Link, Alignment, Indent, 
        HorizontalLine, Clipboard, GeneralHtmlSupport, PastePlainText, 
        PasteFromOffice, RemoveFormat, SourceEditing 
    ],
    form: null,
    initFields(form) {
        this.init(form);
    },
    init(form) {
	form.querySelectorAll('.dp-ckeditor textarea').forEach(el => {
	    if (el.closest('.dp-inlinerecord-container-new')) return;
	    const container = el.closest('.dp-ckeditor');
            const language = container.getAttribute('data-language') || 'en';
            let config = {};

            try {
                const dataConfig = container.getAttribute('data-config');
                config = dataConfig ? JSON.parse(dataConfig) : {};
            } catch (e) {
                console.error("CKEditor config parse error", e);
            }
	    
            config.plugins = this.ckPlugins;

            // Dynamic translation import
            import(`ckeditor5/translations/${language}.js`).then(coreTranslations => {
                config.translations = [coreTranslations.default || coreTranslations];
                
                ClassicEditor.create(el, config).then(editor => {
                    // Store reference by ID
                    IGDATAPOOLFE.ckeditors[el.id] = editor;
                });
            });
        });

        // Initialize markers for this form
        this.initMarkers(form);
    },

    initMarkers(form) {
        // Handle List Markers
        form.querySelectorAll(".dp-marker-list").forEach(list => {
            const inputId = list.getAttribute('data-input-id');
            list.querySelectorAll("[data-marker],[data-html]").forEach(item => {
                item.addEventListener("click", () => {
                    const marker = item.getAttribute('data-marker');
                    const html = marker ? `{${marker}}` : item.getAttribute('data-html');
                    this.insertContent(inputId, html);
                });
            });
        });

        // Handle Select Markers
        form.querySelectorAll(".dp-marker-select").forEach(select => {
            const inputId = select.getAttribute('data-input-id');
            select.addEventListener("change", (e) => {
                const opt = e.target.options[e.target.selectedIndex];
                if (!opt.value) return; // Ignore placeholder
                
                const marker = opt.getAttribute('data-marker');
                const html = marker ? `{${marker}}` : opt.getAttribute('data-html');
                
                this.insertContent(inputId, html);
                e.target.selectedIndex = 0; // Reset select
            });
        });
    },

    insertContent(inputId, html) {
        const editor = IGDATAPOOLFE.ckeditors[inputId];
        if (editor) {
            // Logic for CKEditor
            editor.model.change(writer => {
                writer.insertText(html, editor.model.document.selection.getFirstPosition());
            });
        } else {
            // Fallback for standard Textarea
            const textarea = document.getElementById(inputId);
            if (!textarea) return;

            const start = textarea.selectionStart;
            const end = textarea.selectionEnd;
            textarea.value = textarea.value.substring(0, start) + html + textarea.value.substring(end);
            textarea.selectionStart = textarea.selectionEnd = start + html.length;
            textarea.focus();
        }
    }
};

IGDATAPOOLFE.addPlugin('ckeditor', ckeditorPlugin);
export default ckeditorPlugin;