(function(window, document) {
    function loadScript(src, done) {
        var existing = document.querySelector('script[src="' + src + '"]');
        if (existing) {
            existing.addEventListener('load', done);
            if (existing.dataset.loaded === '1') {
                done();
            }
            return;
        }

        var script = document.createElement('script');
        script.src = src;
        script.onload = function() {
            script.dataset.loaded = '1';
            done();
        };
        document.head.appendChild(script);
    }

    function loadStyle(href) {
        if (document.querySelector('link[href="' + href + '"]')) {
            return;
        }

        var link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = href;
        document.head.appendChild(link);
    }

    function init(container, options) {
        var rootUrl = typeof ROOT_URL !== 'undefined' ? ROOT_URL : (window.ROOT_URL || '');
        var base = rootUrl + '/packages/spellcheck';
        loadStyle(base + '/enrep-spellcheck.css?v=20260723c');

        loadScript(base + '/typo.js?v=1.3.2', function() {
            loadScript(base + '/enrep-spellcheck.js?v=20260724f', function() {
                if (window.EnrepInHouseSpellcheck) {
                    options = options || {};
                    options.packageUrl = base;
                    options.addWordUrl = options.addWordUrl || rootUrl + '/includes/dictionary/dictionary_actions.php';
                    options.customWordsUrl = options.customWordsUrl || options.addWordUrl + '?action=custom_words&tenant=' + encodeURIComponent(options.tenant || (typeof TENANT_URL !== 'undefined' ? TENANT_URL : ''));
                    window.EnrepInHouseSpellcheck.init(container, options);
                }
            });
        });
    }

    window.EnrepReportSpellcheck = {
        init: init
    };
})(window, document);
