let params = new URLSearchParams(window.location.search);
if (params.get("delete")) {
    if (confirm("Are you sure you want to clear all game data?")) {
        localStorage.clear();
        window.location = "./";
    }
}

var timeoutId;

var previousState;
var errorMessage;

var states = [];
var rooms = [];

var selectedItems = [];

var userData = {
    version: 1,
    position: "begin-pickup",
    fuel: 40,
    energy: 50,
    money: 0,
    debrisInSpace: [],
    inCargoHold: [],
    maxCargoCapacity: 20,
    energyRegenRate: 10,
    maxBattery: 100,
    energyRegenAmount: 1,
    ramscoop: 25,
    energyRegen: 10,
    enabled: [],
    id: 1,
    name: "FR-LNC-3R",
    sprite: "playerShip1_red.png",
};

var templateLoader;
var messageQueue = [];

document.addEventListener("DOMContentLoaded", event => {
    errorMessage = "";

    document.getElementById("delete-game").addEventListener("click", () => {
        if (confirm("Are you sure you want to delete your game? This cannot be undone.")) {
            localStorage.clear();
            window.location = "./";
        }
    });

    templateLoader = new TemplateLoader();

    load();

    setInterval(gameTick, 1000);

    var settingsButton = document.getElementsByClassName('dropdown-toggle')[0];
    settingsButton.addEventListener('click', event => {
        event.stopPropagation();
        let dropdownTarget = settingsButton.getAttribute("data-target");
        let dropdownContainer = document.getElementById(dropdownTarget);
        if(dropdownContainer.style.display == "block") {
            dropdownContainer.style.display = "none";
        } else {
            dropdownContainer.style.display = "block";
            dropdownContainer.style.top = settingsButton.offsetTop + settingsButton.clientHeight + 4 + "px";
            dropdownContainer.style.left = settingsButton.offsetRight + dropdownContainer.clientWidth + "px";
        }
    });

    window.addEventListener("click", event => {
        var settingsButton = document.getElementsByClassName('dropdown-toggle')[0];
        let dropdownTarget = settingsButton.getAttribute("data-target");
        let dropdownContainer = document.getElementById(dropdownTarget);
        dropdownContainer.style.display = "none";

    });
});

function updateError() {
    let errorElement = document.getElementById("error");
    if (errorMessage != "") {
        toastMessage(`<span class="error">${errorMessage}</span>`);
    }
    errorElement.innerHTML = errorMessage;
}

function toastMessage(message, style) {
    messageQueue.push({message: message, style: style});
    processToasts();
}

function processToasts() {
    let message = messageQueue.pop();
    if(!message) {
        return;
    }
    let messageElement = document.createElement('div');
    messageElement.innerHTML = message.message;
    messageElement.className = "toast";
    if(message.style) {
        messageElement.className += " " + message.style;
    }
    let messageLength = message.message.split(" ").length;
    let timeoutId = setTimeout(() => hideToast(messageElement), Math.max(5000, messageLength * 500));

    let closeButton = document.createElement('i');
    closeButton.className = "toast-close fas fa-times";
    closeButton.addEventListener("click", event => {
        hideToast(messageElement);
        clearTimeout(timeoutId);
    });
    messageElement.appendChild(closeButton);
    document.body.appendChild(messageElement);
    updateToastPosition();
}

function updateToastPosition() {
    let activeToasts = document.body.getElementsByClassName("toast");
    let lastTop = 30;
    for(let i = activeToasts.length - 1; i >= 0; i--) {
        let toastElement = activeToasts[i];
        
        toastElement.style.right = "5%";
        toastElement.style.bottom = lastTop + "px";
        let bounds = toastElement.getBoundingClientRect();
        lastTop += bounds.height + 16;
    }
}

function hideToast(messageElement) {
    document.body.removeChild(messageElement);
    updateToastPosition();
}

function updateEnergy() {
    let batteryClass = "fa-battery-full";
    if(userData.energy/ userData.maxBattery < 0.75) {
        batteryClass = "fa-battery-three-quarters";
    }
    if(userData.energy/ userData.maxBattery < 0.5) {
        batteryClass = "fa-battery-half";
    }
    if(userData.energy/ userData.maxBattery < 0.25) {
        batteryClass = "fa-battery-quarter";
    }
    if(userData.energy/ userData.maxBattery < 0.05) {
        batteryClass = "fa-battery-empty";
    }
    document.getElementById("energy").innerHTML = `<i class="fas ${batteryClass}"></i> <span>${userData.energy} / ${userData.maxBattery}</span>`;
}
function updateMoney() {
    document.getElementById("money").innerHTML = `<i class="fas fa-won-sign"></i> ${userData.money}`;
}
function updateFuel() {
    document.getElementById("fuel").innerHTML = `<i class="fas fa-gas-pump"></i>  ${userData.fuel}`;
}

function groupByType(dataset) {
    let reducedDataset = dataset.reduce((accumulator, value) => {
        accumulator[value.type] = accumulator[value.type] || [];
        accumulator[value.type].push(value);
        return accumulator;
    }, {});
    return Object.values(reducedDataset);
}

function updateActivity(newActivityText) {
    document.getElementById("activity").innerHTML = newActivityText;
}

function delayLoop(callback = () => { }, duration = 3000, step = 10) {
    var delay = duration / step;
    timeoutId = setTimeout(() => {
        let progress = document.getElementById("progress");
        progress.value += (delay / duration) * 100;
        if (progress.value >= 100) {
            progress.value = 100;
            callback();
        } else {
            delayLoop(callback, duration, step);
        }
    }, delay);
}

function gameTick() {
    processToasts();
    userData.energyRegen--;
    if (userData.energyRegen < 0) {
        userData.energy = Math.min(userData.maxBattery, userData.energy + userData.energyRegenAmount);
        updateEnergy();
        userData.energyRegen = userData.energyRegenRate;
        save();
    }
    if (userData.energy > 0 && isFlagEnabled('ion-engine-enabled')) {
        userData.energy--;
        if (isFlagEnabled('ramjet-enabled')) {
            userData.ramscoop--;
            if (userData.ramscoop < 0) {
                userData.ramscoop = 25;
                userData.fuel++;
                updateFuel();
                save();
            }
        }
        updateEnergy();
        save();
    }
}

function pickRandomItem(probabilityTable) {
    let roll = Math.floor(100 * Math.random()) + 1;

    let totalProbability = 0;
    let selectedItem = probabilityTable[0];
    for (let i = 0; i < probabilityTable.length; i++) {
        let item = probabilityTable[i];
        totalProbability += item.probability;
        if (roll < totalProbability) {
            selectedItem = item;
            break;
        }
    };
    return selectedItem;
}