var ecsUrl = "";
var iasUrl = "";
var ccsUrl = "";
var ucsUrl = "";
var tid = "";
var tsz = "";
var ttmdsz = "";
var lv = "";

// Expose the URLs to the global scope
window.ecsUrl = ecsUrl;
window.iasUrl = iasUrl;
window.ccsUrl = ccsUrl;
window.ucsUrl = ucsUrl;
window.tid = tid;
window.tsz = tsz;
window.ttmdsz = ttmdsz;
window.lv = lv;

var thetrace = "";
var points = 0; // Initialize points

// Load the existing trace and points from localStorage
const loadData = () => {
    const storedTrace = window.localStorage.getItem('thetrace');
    if (storedTrace) {
        thetrace = storedTrace; // Set thetrace to the stored value
    }
    window.thetrace = thetrace; // Make it available globally

    const storedPoints = window.localStorage.getItem('points');
    if (storedPoints) {
        points = parseInt(storedPoints, 10); // Set points to the stored value
    }
};

// Define the trace function
const trace = function(...args) {
    // Join the arguments into a single string
    const message = args.join(" "); // You can customize the separator if needed
    // Append the message to the thetrace variable with a newline
    thetrace += message + "\n";
    
    // Update the global window.thetrace variable
    window.thetrace = thetrace;

    // Save the updated trace to localStorage
    window.localStorage.setItem('thetrace', window.thetrace);
    console.log(...args);
    console.trace(...args);
};

loadData();
console.log("Trace loaded:", window.thetrace);
console.log("Current points:", points);


// Define the ECommerceInterface class
class ECommerceInterface {
    constructor() {
        const unwantedPath = "/oss/serv/CheckRegistered.jsp";
        if (window.location.pathname === unwantedPath) {
            //window.location.pathname = "/oss/serv/W_01.jsp";
            console.log("Do nothing...");
        }
        this._titlesMap = new Map([
            ["0001000248414241", { 
                name: 'Wii Shop Channel', 
                version: '21',
                isTmdPresent: true,
            }],
            ['0001000248414242', { 
                name: 'idk', 
                version: '1',
                isTmdPresent: true,
            }],
        ]);
        trace("ECommerceInterface initialized"); // Use the trace function
        this.loadPoints(); // Load data when the class is instantiated
    }

    getTicketInfos(titleId) {
        // Return a mock object that simulates an unlimited license
        return {
            length: 1, // Simulate the length property
            get: function(index) {
                if (index === 0) {
                    return {
                        deviceId: 222222, // Simulate a personalized ticket
                        limits: null // No limits, indicating an unlimited license
                    };
                }
                return null; // Return null for any other index
            }
        };
    }

    getTitleInfo(shopAppTitleId) {
        const title = this._titlesMap.get(shopAppTitleId);
        if (!title || typeof title !== 'object' || !title.isTmdPresent || title.version == null) {
            return null;
        }
    }
    getTitleInfo(titleid) {
        return {
            isOnDevice: false,
            version: 0,
            isTmdPresent: false,
        }
    }
    getLog() {
        return window.localStorage.getItem('thetrace') || ""; // Return the stored trace or an empty string
    }

    getPoints() {
        return points; // Return the current points
    }

    setPoints(newPoints) {
        if (!Number.isInteger(newPoints)) {
            newPoints = parseInt(newPoints, 10); // Convert to integer if not
        }

        if (isNaN(newPoints)) {
            console.error("Invalid points value provided:", newPoints);
            return;
        }

        const currentPoints = parseInt(window.localStorage.getItem('points'), 10) || 0;
        points = currentPoints + newPoints; 
        window.localStorage.setItem('points', points); 
        trace("Points updated to: " + points); 
    }

    loadPoints() {
        const storedPoints = window.localStorage.getItem('points');
        if (storedPoints) {
            points = parseInt(storedPoints, 10); // Set points to the stored value
        }
    }

    cancelOperation() {
        console.log("bro what do you want me to cancel");
    }

    setWebSvcUrls(ecsuri, iasuri) {
        window.ecsUrl = ecsuri; 
        window.iasUrl = iasuri;
    }

    setContentUrls(ccsuri, ucsuri) {
        window.ccsUrl = ccsuri;
        window.ucsUrl = ucsuri;
    }

    getCachedBalance() {
        const storedPoints = window.localStorage.getItem('points');
        if (storedPoints) {
            return parseInt(storedPoints, 10);
        }
        else {
            return 0;
        }
    }

    refreshCachedBalance() {
        const storedPoints = window.localStorage.getItem('points');
        if (storedPoints) {
            return parseInt(storedPoints, 10);
        }
        else {
            return 0;
        }
    }

    checkDeviceStatus() {
        return 1;
    }

    getDeviceInfo() {
        return {
            country: "CA", // Example value
            region: "USA", // Example value
            isParentalControlEnabled: false, // Example value
            userAge: 20, // Example value
            language: "fr", // Example value
            accountId: "659247", // Example value
            deviceId: "458757", // Example value
            serial: "PC156494873", // Example value
            maxUserInodes: 200000,
            usedUserInodes: 100000,
            freeChannelAppCount: 41,
            freeChannelAppCount: 41,
            blockSize: 536870912,
            totalBlocks: 65536,
            usedBlocks: 0,
            totalSysBlocks: 65536,
            usedSysBlocks: 0,
            titleId: "0001000248414241",
        };
    }
    setSessionValue(idk, idk2) {
        
        console.log("tbh idk ill just log: " + idk + " log2: " + idk2);
    }
    getSessionValue(avalue) {
        if (avalue == "nTitlesDownloaded"){
            return 0;
        } else {
            console.log("thy omighty value: " + avalue);
            return;
        }
    }
    pubKeyEncrypt(nah) {
        console.log("behonest this is not required: " + nah)
        return nah;
    }
    purchasePoints(pointsToBuy, itemId, price, payment, taxes, purchaseInfo, discount) {
        this.setPoints(pointsToBuy);
        return 100;
    }
    getProgress() {
        console.log("idk what to return its a progress?");
        return 100;
    }
    checkRegistration() {
        return true;
    }
    getWeakToken() {
        return "iamaweaktoken";
    }
}

class wiiShop {
    constructor() {
        trace("wiiShop initialized"); // Use the trace function
    }
    retry() {
        window.location.pathname = "/oss/serv/W_01.jsp";
    }
    endWaiting() {
        console.log("Currently does nothing endwaiting");
    }
    enableHRP() {
        console.log("Does Jack shit homebuttonenabler");
    }
    sleep(duration) {
        return new Promise(resolve => setTimeout(resolve, duration)); // duration is in milliseconds
    }
    async beginWaiting(seconds) {
        // Check if the input is a string and convert to integer if so
        if (seconds == null) {
            seconds = 3;
        }
        if (typeof seconds === 'string') {
            const parsedValue = parseInt(seconds, 10);
            if (isNaN(parsedValue) || parsedValue.toString() !== seconds) {
                console.error("Invalid input: Please provide a valid integer value.");
                return; // Exit the function if the string is not a valid integer
            }
            seconds = parsedValue; // Convert string to integer
        }

        // Check if the input is a valid integer
        if (!Number.isInteger(seconds)) {
            console.error("Invalid input: Please provide an integer value.");
            return; // Exit the function if the input is not an integer
        }

        let duration;

        // Convert single-digit seconds to milliseconds
        duration = (seconds < 10) ? seconds * 1000 : seconds; // Convert to ms if single digit

        await this.sleep(duration);
        console.log("Wait complete!");
    }
    isCompatibleMode() {
        return true;
    }
}

class wiiSound {
    constructor() {
        trace("wiiSound initialized"); // Use the trace function
    }
    playSE(snd) {
        console.log("i play this sound hehehehe (it dont exist lol): " + snd);
    }
}

class wiiKeyboard {
    constructor() {
        trace("wiiKeyboard initialized");
    }
}

class ECCreditCardEncryptedPayment {
    constructor(smth) {
        this.smth = smth;
    }
}

class ECPrice {
    constructor(uhh, ahh) {
        return uhh;
    }
}

class wiiSDCard {
    constructor() {
        return;
    }
}

class wiiNwc24 {
    constructor() {
        return;
    }
    sendable() {
        return true;
    }
    mailErrNo() {
        return null;
    }
    errMsg() {
        return null;
    }
    getFriendNum() {
        return 5;
    }
    getFriendInfo(fnm, data) {
        if (typeof fnm === 'string') {
            const parsedValue = parseInt(fnm, 10);
            if (isNaN(parsedValue) || parsedValue.toString() !== fnm) {
                console.error("Invalid input: Please provide a valid integer value.");
                return; // Exit the function if the string is not a valid integer
            }
            fnm = parsedValue; // Convert string to integer
        }
        if (data == "name") {
            if (fnm == 1) {
                return "User1";
            } else if (fnm == 2) {
                return "User2";
            } else if (fnm == 3) {
                return "User3";
            } else if (fnm == 4) {
                return "User4";
            } else if (fnm == 5) {
                return "User5";
            }
        }
        if (data == "userId") {
            if (fnm == 1) {
                return "3630753603591712";
            } else if (fnm == 2) {
                return "3630753603591712";
            } else if (fnm == 3) {
                return "3630753603591712";
            } else if (fnm == 4) {
                return "3630753603591712";
            } else if (fnm == 5) {
                return "3630753603591712";
            }
        }
        if (data == "miiImage") {
            return "111"
        }  
    }
}

window.ECommerceInterface = ECommerceInterface;
window.ECCreditCardEncryptedPayment = ECCreditCardEncryptedPayment;
window.ECPrice = ECPrice;
window.wiiKeyboard = wiiKeyboard;
window.wiiShop = wiiShop;
window.wiiSound = wiiSound;
