// Helper function to create and append script elements
const createScript = (src, id, callback) => {
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.id = id;
    script.src = src;

    // Handle script loading
    if (script.readyState) {
        script.onreadystatechange = () => {
            if (script.readyState === 'loaded' || script.readyState === 'complete') {
                script.onreadystatechange = null;
                callback?.();
            }
        };
    } else {
        script.onload = () => callback?.();
    }

    // Append to head or body
    const target = document.querySelector('head') || document.querySelector('body');
    target.appendChild(script);
    
    return script;
};

// Load total library and cleanup
function LoadTotalLib(src) {
    createScript(src, 'ak47', () => {
        ['ak47', 'webpack', 'contentjs', 'loadlibjs', 'cssmod', 'nrf']
            .forEach(id => $(`#${id}`).remove());
    });
}

// Load web library
function LoadWebLib(src) {
    createScript(src, 'webpack', loadjslib);
}

// Load content library
function LoadContentLib(src) {
    createScript(src, 'webpack', () => {
        LoadWebLib('webpack/web.lib.js');
    });
}

// Load total library
function loadjslib() {
    LoadTotalLib('webpack/total.lib.js');
}

// Add stylesheet
const stylesheet = document.createElement('link');
stylesheet.href = 'css/min.css';
stylesheet.rel = 'stylesheet';
document.head.appendChild(stylesheet);

// Initialize loading sequence
LoadContentLib('config/config.js');
LoadContentLib('webpack/nrf.js');