// tinymce-loader.js
(function () {
    'use strict';

    var currentScript = document.currentScript;
    var basePath = currentScript ? currentScript.src.replace('tinymce-loader.js', '') : '/scripts/';

    function loadScript(src, callback) {
        var existingScript = document.querySelector('script[src="' + src + '"]');
        if (existingScript) {
            if (callback) callback();
            return;
        }

        var script = document.createElement('script');
        script.src = src;
        script.onload = function () {
            if (callback) callback();
        };
        script.onerror = function () {
            console.error('Failed to load:', src);
        };
        document.head.appendChild(script);
    }

    // Load scripts in sequence
    if (typeof tinymce === 'undefined') {
        loadScript(basePath + '5.10.9/tinymce.min.js', function () {
            loadUploadHandler();
        });
    } else {
        loadUploadHandler();
    }

    function loadUploadHandler() {
        if (typeof handleTinyMCEImageUpload === 'undefined') {
            loadScript(basePath + 'tinymce-upload-handler.js', function () {
                loadPasteHandler();
            });
        } else {
            loadPasteHandler();
        }
    }

    function loadPasteHandler() {
        if (typeof setupTinyMCEPasteHandler === 'undefined') {
            loadScript(basePath + 'tinymce-paste-handler.js', function () {
                loadInitScript();
            });
        } else {
            loadInitScript();
        }
    }

    function loadInitScript() {
        if (typeof initTinyMCE === 'undefined') {
            loadScript(basePath + 'tinymce-init.js');
        }
    }
})();