<script type="module">

window.EveAI = window.EveAI || {};
window.EveAI.JsonEditors = {
    instances: {},
    initialize: function(containerId, data, options = {}) {
        console.log('Initializing JSONEditor for', containerId, 'with data', data, 'and options', options);
        const container = document.getElementById(containerId);
        if (!container || typeof container !== 'object' || !('classList' in container)) {
            console.error(`Container met ID ${containerId} niet gevonden of geen geldig element:`, container);
            return null;
        }

        if (!container) {
            console.error(`Container with ID ${containerId} not found`);
            return null;
        }
        if (this.instances[containerId]) return this.instances[containerId];

        if (typeof window.createJSONEditor !== 'function') {
            console.error('vanilla-jsoneditor not loaded (window.createJSONEditor missing).');
            container.innerHTML = `<div class="alert alert-danger p-3">
                <strong>Error:</strong> vanilla-jsoneditor not loaded
            </div>`;
            return null;
        }

        const isReadOnly = options.readOnly === true;

        let content = {
            {#text: undefined,#}
            json: data
        }

        // props voor vanilla-jsoneditor
        const editorProps = {
            content: content,
            mode: options.mode || (isReadOnly ? "text" : "tree"),
            readOnly: isReadOnly,
            mainMenuBar: options.mainMenuBar !== undefined ? options.mainMenuBar : true,
            navigationBar: options.navigationBar !== undefined ? options.navigationBar : false,
            statusBar: options.statusBar !== undefined ? options.statusBar : !isReadOnly,
            onChange: options.onChange || ((updatedContent, previousContent, { contentErrors, patchResult }) => {
                // Default onChange behavior - alleen loggen
                console.log('onChange', { updatedContent, previousContent, contentErrors, patchResult });
            })
        };
        console.log('EditorProps', editorProps);

        let editor;
        try {
            console.log('Creating JSONEditor for', containerId);
            editor = window.createJSONEditor({
                    target: container,
                    props: editorProps
                }
            );
            console.log('JSONEditor created for ', containerId);
            container.classList.add('jsoneditor-initialized', isReadOnly ? 'jsoneditor-readonly-mode' : 'jsoneditor-edit-mode');
            console.log('Container class set for ', containerId);
            this.instances[containerId] = editor;
            console.log('JSONEditor instance stored for ', containerId);
            return editor;
        } catch (e) {
            console.error(`Error initializing JSONEditor for ${containerId}:`, e);
            container.innerHTML = `<div class="alert alert-danger p-3">
                <strong>Error loading JSON data:</strong><br>${e.message}
            </div>`;
            return null;
        }
    },
    initializeReadOnly: function(containerId, data, additionalOptions = {}) {
        const options = Object.assign({ readOnly: true, mode: 'text' }, additionalOptions);
        const editor = this.initialize(containerId, data, options);
        if (editor && additionalOptions.expandAll && typeof editor.expand === "function") {
            try { editor.expand(() => true); } catch {}
        }
        return editor;
    },
    get: function(containerId) {
        return this.instances[containerId] || null;
    },
    destroy: function(containerId) {
        if (this.instances[containerId]) {
            if (typeof this.instances[containerId].destroy === 'function') this.instances[containerId].destroy();
            delete this.instances[containerId];
        }
        const container = document.getElementById(containerId);
        if (container) {
            container.classList.remove('jsoneditor-initialized', 'jsoneditor-readonly-mode', 'jsoneditor-edit-mode');
            container.innerHTML = '';
        }
    }
};

document.addEventListener('DOMContentLoaded', function() {
    // Tooltips
    document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(trigger => new bootstrap.Tooltip(trigger));
    // Textarea->json editor conversies
    document.querySelectorAll('.json-editor').forEach(function(textarea) {
        const containerId = textarea.id + '-editor';
        const container = document.getElementById(containerId);
        if (!container) return;
        try {
            const data = textarea.value ? JSON.parse(textarea.value) : {};
            const isReadOnly = textarea.readOnly || textarea.hasAttribute('readonly') || textarea.classList.contains('readonly');
            window.EveAI.JsonEditors.initialize(containerId, data, {
                mode: isReadOnly ? 'preview' : 'tree',
                readOnly: isReadOnly,
                onChange: isReadOnly ? undefined : (updatedContent, previousContent, { contentErrors, patchResult }) => {
                    // Automatische synchronisatie naar textarea bij elke wijziging
                    if (updatedContent.json !== undefined) {
                        textarea.value = JSON.stringify(updatedContent.json, null, 2);
                    } else if (updatedContent.text !== undefined) {
                        textarea.value = updatedContent.text;
                    }
                    console.log('Textarea automatisch bijgewerkt via onChange');
                }
            });
        } catch (e) {
            console.error('Error parsing initial JSON for .json-editor:', e);
            container.innerHTML = `<div class="alert alert-danger p-3"><strong>Error loading JSON data:</strong><br>${e.message}</div>`;
        }
    });
    
    // Real-time synchronisatie als extra beveiliging
    setInterval(function() {
        document.querySelectorAll('.json-editor').forEach(function(textarea) {
            if (textarea.style.display === 'none') { // Alleen voor verborgen textareas (zoals in edit forms)
                const containerId = textarea.id + '-editor';
                const editor = window.EveAI?.JsonEditors?.get(containerId);
                if (editor && editor.get) {
                    try {
                        const content = editor.get();
                        let newValue = '';
                        if (content.json !== undefined) {
                            newValue = JSON.stringify(content.json, null, 2);
                        } else if (content.text !== undefined) {
                            newValue = content.text;
                        }
                        
                        // Alleen updaten als de waarde daadwerkelijk is veranderd
                        if (textarea.value !== newValue) {
                            textarea.value = newValue;
                            console.log('Real-time sync uitgevoerd voor', textarea.id);
                        }
                    } catch (e) {
                        // Stil falen - geen console spam
                    }
                }
            }
        });
    }, 1000); // Elke seconde controleren
    
    // Alleen-lezen containers
    document.querySelectorAll('.json-viewer').forEach(function(container) {
        const dataElement = document.getElementById(container.id + '-data');
        if (!dataElement) return;
        try {
            const data = dataElement.textContent ? JSON.parse(dataElement.textContent) : {};
            window.EveAI.JsonEditors.initializeReadOnly(container.id, data, { expandAll: true });
        } catch (e) {
            console.error('Error parsing JSON for .json-viewer:', e);
            container.innerHTML = `<div class="alert alert-danger p-3"><strong>Error loading JSON data:</strong><br>${e.message}</div>`;
        }
    });
});
</script>