/**
 * Monaco loader for Import tab custom field scripts.
 */
(function (global) {
    'use strict';

    var monacoReady = null;
    var MONACO_VS = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.45.0/min/vs';

    function ensureMonaco() {
        if (monacoReady) return monacoReady;
        monacoReady = new Promise(function (resolve, reject) {
            if (global.monaco && global.monaco.editor) {
                resolve(global.monaco);
                return;
            }
            if (typeof global.require !== 'function') {
                reject(new Error('Monaco loader (require.js) is not on the page. Include monaco-editor min/vs/loader.js.'));
                return;
            }
            global.require.config({ paths: { vs: MONACO_VS } });
            global.require(
                ['vs/editor/editor.main'],
                function () { resolve(global.monaco); },
                function (err) { reject(err || new Error('Monaco failed to load')); }
            );
        });
        return monacoReady;
    }

    function create(container, initialValue, onChange) {
        if (!container || !global.monaco)
            return null;
        var editor = global.monaco.editor.create(container, {
            value: initialValue || '',
            language: 'csharp',
            theme: 'vs-dark',
            automaticLayout: true,
            minimap: { enabled: false },
            fontSize: 13,
            scrollBeyondLastLine: false,
            wordWrap: 'on'
        });
        if (typeof onChange === 'function') {
            editor.onDidChangeModelContent(function () {
                onChange(editor.getValue());
            });
        }
        return editor;
    }

    function dispose(editor) {
        if (editor && typeof editor.dispose === 'function')
            editor.dispose();
    }

    global.ChameleonImportScriptEditor = {
        ensureMonaco: ensureMonaco,
        create: create,
        dispose: dispose,
        getValue: function (editor) {
            return editor ? editor.getValue() : '';
        }
    };
})(typeof window !== 'undefined' ? window : globalThis);
