const _injectedWiiShopSoundUrls = window._wiiShopSoundUrls_ || [];

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;

// Define the trace function
const trace = function(...args) {
    extensionStorage.slog(...args)
    console.log(...args);
    //console.trace(...args);
};
// content-script.js
const storageCache = {};
const STORAGE_ENDPOINT = '/_extension_storage';


const extensionStorage = {
    set: (key, value) => {
      storageCache[key] = value;
      fetch(`${STORAGE_ENDPOINT}?set_key=${encodeURIComponent(key)}&set_value=${encodeURIComponent(value)}`)
        .catch(() => {});
    },
    
    get: (key) => {
      if (key in storageCache) return storageCache[key];
      
      const request = new XMLHttpRequest();
      request.open('GET', `${STORAGE_ENDPOINT}?get=${encodeURIComponent(key)}`, false);
      request.send(null);
      
      if (request.status === 0) {
        try {
          const data = JSON.parse(request.responseText);
          storageCache[key] = data.value;
          return data.value;
        } catch {
          return null;
        }
      }
      return null;
    },
    
    slog: (message) => {
      fetch(`${STORAGE_ENDPOINT}?set_key=slogs&set_value=${encodeURIComponent(message)}`)
        .catch(() => {});
    },
    
    getLogs: () => {
      return extensionStorage.get('logs') || [];
    },
    
    clearLogs: () => {
      fetch(`${STORAGE_ENDPOINT}?clogs=true`)
        .catch(() => {});
      storageCache.logs = [];
    },

    spts: (points) => {
        const pointsToAdd = parseInt(points) || 0;
        if (pointsToAdd > 0) {
            fetch(`${STORAGE_ENDPOINT}?set_key=spts&set_value=${pointsToAdd}`)
                .catch(() => {});
        }
    },
    
    getpts: () => {
        const points = extensionStorage.get('pts');
        return parseInt(points) || 0;
    },
    
    clearpts: () => {
        fetch(`${STORAGE_ENDPOINT}?cpts=true`)
            .catch(() => {});
        storageCache.pts = 0;
    }
  };

console.log("Current points:", extensionStorage.getpts());
console.log("Trace loaded:", extensionStorage.getLogs());

// 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
    }

    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 extensionStorage.getLogs() || ""; // Return the stored trace or an empty string
    }

    getPoints() {
        return extensionStorage.getpts() || 0; // 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;
        }

        extensionStorage.spts(newPoints);
        trace("Points updated to: " + extensionStorage.getpts()); 
    }

    loadPoints() {
        console.log("nah i dont load points, they alr loaded");
    }

    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 {
            status: 0,
            operation: "checkDeviceStatus",
            description: "",
            phase: 17,
            isCancelRequested: "false",
            downloadedSize: 888,
            totalSize: 888,
            errCode: "",
            errInfo: "",
        };
    }

    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",
            accountCountry: "CA",
            deviceCode: "N/A",
            accountDeviceCode: "N/A",
        };
    }
    setSessionValue(key, value) {
        extensionStorage.set(key, value);
    }
    getSessionValue(key) {
        return extensionStorage.get(key);
    }
    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
        return "isok";
    }
    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 {
    // === THIS IS THE CRUCIAL CHANGE ===
    // Use a static property to store the sound URLs, accessible by all instances
    static audioUrls = _injectedWiiShopSoundUrls;

    constructor() {
        trace("wiiSound initialized"); // Use the trace function
    }
    playSE(snd) {
        const soundIndex = parseInt(snd, 10);
        // Access the URLs via the static property
        if (isNaN(soundIndex) || soundIndex < 1 || soundIndex >= wiiSound.audioUrls.length) {
            console.warn("Invalid sound index for wiiSound.playSE:", snd);
            return;
        }

        // Access the URLs via the static property
        const audioUrl = wiiSound.audioUrls[soundIndex];
        if (!audioUrl) {
            console.warn("No audio URL found for sound index:", soundIndex);
            return;
        }

        const audio = new Audio(audioUrl);
        audio.style.display = 'none'; // Keep it hidden
        audio.play()
            .then(() => {
                console.log('Wii Shop Sound played:', soundIndex, audioUrl);
            })
            .catch(error => {
                console.error('Error playing Wii Shop Sound:', soundIndex, audioUrl, error);
                // Common error: Autoplay policy blocked.
                // Consider a fallback, like playing on user interaction.
            });
    }
}

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 == 0) {
                return "User1";
            } else if (fnm == 1) {
                return "User2";
            } else if (fnm == 2) {
                return "User3";
            } else if (fnm == 3) {
                return "User4";
            } else if (fnm == 4) {
                return "User5";
            }
        }
        if (data == "userId") {
            if (fnm == 0) {
                return "3630753603591712";
            } else if (fnm == 1) {
                return "3630753603591712";
            } else if (fnm == 2) {
                return "3630753603591712";
            } else if (fnm == 3) {
                return "3630753603591712";
            } else if (fnm == 4) {
                return "3630753603591712";
            }
        }
        if (data == "miiImage") {
            return "111"
        }  
    }
}
class wiiDlTask {
    constructor() {
        trace("WiiDlTask init");
    }
    addDownloadTask(url, interval){
        trace("yes i got it dw i will download it :tro:");
    }
}
class wiiMii {
    constructor() {
        trace("wiiMii init");
    }
}
window.ECommerceInterface = ECommerceInterface;
window.ECCreditCardEncryptedPayment = ECCreditCardEncryptedPayment;
window.ECPrice = ECPrice;
window.wiiKeyboard = wiiKeyboard;
window.wiiShop = wiiShop;
window.wiiSound = wiiSound;
window.wiiMii = wiiMii;
