import React, { useEffect, useRef } from "react";

const LoaderJs = ({ pack, serverSeed, clientSeed, nonce, brand, getResult }) => {
    const setDataRef = useRef(null);

    const gameModules = {
        packwheel: () => import("./js/packwheel"),
        sv_151: () => import("./js/151-calculator"),
        azurite_sea: () => import("./js/azurite-sea-calculator"),
        into_the_inklands: () => import("./js/into-the-inklands-calculator"),
        reign_of_jafar: () => import("./js/reign-of-jafar-calculator"),
        rise_of_the_floodborn: () => import("./js/rise-of-the-floodborn-calculator"),
        shimmering_skies: () => import("./js/shimmering-skies-calculator"),
        the_first_chapter: () => import("./js/the-first-chapter-calculator"),
        ursulas_return: () => import("./js/ursula-return-calculator"),
        archazias_island: () => import("./js/archazia-island-calculator"),
        aetherdrift: () => import("./js/aetherdrift-calculator"),
        assassins: () => import("./js/assassins-calculator"),
        bloomburrow: () => import("./js/bloomburrow-calculator"),
        duskmourn_house_of_horror: () => import("./js/duskmourn-calculator"),
        innistrad_remastered: () => import("./js/innistrad-calculator"),
        march_of_the_machine: () => import("./js/march-calculator"),
        outlaws_of_thunder_junction: () => import("./js/outlaws-calculator"),
        phyrexia_all_will_be_one: () => import("./js/phyrexia-calculator"),
        ravnica_remastered: () => import("./js/ravnica-calculator"),
        chilling_reign: () => import("./js/chilling-reign-calculator"),
        destined_rivals: () => import("./js/destined-rivals-calculator"),
        evolving_skies: () => import("./js/evolving-calculator"),
        journey_together: () => import("./js/journey-together-calculator"),
        paldea_evolved: () => import("./js/paldea-evolved-calculator"),
        surging_sparks: () => import("./js/surging-sparks-calculator"),
        prismatic_evolutions: () => import("./js/prismatic-evolutions-calculator"),
        paldean_fates: () => import("./js/paldean-fates-calculator"),
        fusion_strike: () => import("./js/fusion-strike-calculator"),
        wilds_of_eldraine: () => import("./js/wilds-calculator"),
        commander_masters: () => import("./js/commander-calculator"),
        mega_evolutions: () => import("./js/mega-evolutions-calculator"),
        white_flare: () => import("./js/white-flare-calcualtor"),
        black_bolt: () => import("./js/black-bolt-calculator"),
    };

    // Load and assign the correct module
    useEffect(() => {
        if (!pack) return;

        // Reset current setData to prevent premature execution
        setDataRef.current = null;

        const loadModule = async () => {
            try {
                let key = pack.toLowerCase().replace(/ /g, "_");
                if (!gameModules[key]) return;

                const module = await gameModules[key]();
                if (module.setData) {
                    setDataRef.current = module.setData;
                    // Run immediately only after it's set
                    runSetData();
                } else {
                    console.warn("⚠️ setData not found in:", key);
                }
            } catch (err) {
                console.error("❌ Module load failed:", err);
            }
        };

        loadModule();
    }, [pack]);

    // Only run after valid inputs and module loaded
    const runSetData = async () => {
        if (
            typeof setDataRef.current === "function" &&
            serverSeed &&
            clientSeed &&
            nonce &&
            pack
        ) {
            try {
                const result = await setDataRef.current(serverSeed, clientSeed, nonce);
                getResult(result.result);
            } catch (err) {
                console.error("❌ Error calling setData:", err);
            }
        }
    };

    useEffect(() => {
        runSetData();
    }, [serverSeed, clientSeed, nonce, brand]); // ✅ add brand here

    return null;
};

export default LoaderJs;
