import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';

import { GLOBAL_LOG_A_LOT, APP_CONFIG } from './constants.mjs';
import {
    initIbGibStorage,
    initIbGibGlobalThis,
    dynamicallyLoadBootstrapScript,
} from './helpers.web.mjs';

// {{OPTIONAL_ROUTER_IMPORT}}
// import { simpleIbGibRouterSingleton as router } from './ui/router/router-one-file.mjs';

initIbGibGlobalThis(APP_CONFIG);

const logalot = GLOBAL_LOG_A_LOT;

/**
 * Initiates startup without blocking DOMContentLoaded.
 *
 * Sequence:
 *   1. Init IndexedDB storage
 *   2. (Optional) trigger shell / router
 *   3. Dynamically import bootstrap.mjs — the heavy ibgib graph loads here
 */
async function spinOffStartup(): Promise<void> {
    const lc = `[${spinOffStartup.name}]`;
    try {
        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }
        console.time(lc);

        document.addEventListener('DOMContentLoaded', async () => {
            try {
                console.timeLog(lc, 'DOMContentLoaded fired');

                await initIbGibStorage(APP_CONFIG);
                console.timeLog(lc, 'initIbGibStorage complete');

                // {{OPTIONAL_ROUTER_CALL}}
                // router.loadCurrentURLPath();

                await dynamicallyLoadBootstrapScript('./bootstrap.mjs');
                console.timeLog(lc, 'dynamicallyLoadBootstrapScript complete');

                console.timeEnd(lc);
            } catch (error) {
                console.error(`${lc} ${extractErrorMsg(error)}`);
                throw error;
            }
        });

    } catch (error) {
        console.timeEnd(lc);
        debugger; // error in index.mts — investigate immediately
        console.error(`${lc} ${extractErrorMsg(error)}`);
        throw error;
    } finally {
        if (logalot) { console.log(`${lc} complete.`); }
    }
}

spinOffStartup();
