function getMiniName(name) {
    let parts = name.split(" ");

    if (parts[0].length > 3 && !parts[0].endsWith("e") && parts[0] !== "Filly" && parts[0] !== "Windy" && parts[1] !== "Brightdawn") {
        if (parts[0].includes("/")) {
            return parts[0].split("/")[0];
        } else {
            return parts[0];
        }
    } else {
        return name;
    }
}

let lastStartTime = null;
let responseTimes = [];

defaultConfigSlot = localStorage.getItem("default-slot") ? parseInt(localStorage.getItem("default-slot")) : (JSON.parse(localStorage.getItem("identity"))['pluralkit'] === "gdapd" ? 0 : 1);

let configSlot = defaultConfigSlot;

if (isNaN(configSlot) || configSlot < 0 || configSlot >= WiafConfig.length) {
    console.log("reset slot");
    configSlot = defaultConfigSlot;
} else {
    localStorage.setItem("default-slot", configSlot);
}

function sleep(ms) {
    let start = new Date().getTime(), expire = start + ms;
    while (new Date().getTime() < expire) { }
}

console.log(configSlot);

async function fetchPlus(resource, options = {}) {
    const { timeout = 8000 } = options;

    const controller = new AbortController();
    const id = setTimeout(() => controller.abort(), timeout);
    const response = await fetch(resource, {
        ...options,
        signal: controller.signal
    });
    clearTimeout(id);
    return response;
}

window.onload = async () => {
    if (navigator.onLine) {
        loadApp();
    } else {
        showOffline();
        loadApp();
    }
}

function showOffline() {
    document.getElementById("online").style.display = "none";
    document.getElementById("offline").style.display = "";
}

responses = {
    step1: null,
    step2: null,
    step3: null,
    step4: null,
    step5: null
}

let loadedApp = false;
function loadApp() {
    if (loadedApp) return;
    loadedApp = true;

    document.getElementById("step1").innerHTML = "";
    document.getElementById("step2").innerHTML = "";
    document.getElementById("step3").innerHTML = "";
    document.getElementById("step4").innerHTML = "";
    document.getElementById("step5").innerHTML = "";
    document.getElementById("step5").innerHTML = "";
    document.getElementById("selector-profiles").innerHTML = "";

    for (let slot in WiafConfig) {
        let slotData = WiafConfig[slot];
        document.getElementById("selector-profiles").innerHTML += "<li><a href='#" + slot + "' onclick='localStorage.setItem(`default-slot`, slot);location.reload();'>" + slotData["name"] + "</a></li>";
    }

    window.members = JSON.parse(localStorage.getItem("pluralkit-" + configSlot)).filter(i => i.name !== "unknown" && i.name !== "fusion" && i.name !== "smolscoots" && i.name !== "smoltwi" && !i.name.endsWith("-travelling")).sort(() => Math.random() - 0.5);
    document.getElementById("loader").innerHTML = "Starting application...";

    let dc;
    let dcName;

    // Step 1
    window.members = JSON.parse(localStorage.getItem("pluralkit-" + configSlot)).filter(i => i.name !== "unknown" && i.name !== "fusion" && i.name !== "smolscoots" && i.name !== "smoltwi" && !i.name.endsWith("-travelling")).sort(() => Math.random() - 0.5);
    dc = document.getElementById("s1-default-card");
    dcName = document.getElementById("s1-default-card-name");

    for (let member of window.members) {
        dc.id = "s1-" + member.id;
        dcName.id = "s1-" + member.id + "-name";

        dcName.innerText = member.display_name ?? member.name;

        dc.style.display = "";
        document.getElementById("step1").appendChild(dc.cloneNode(true));

        dc.style.display = "none";
        dc.id = "s1-default-card";
        dcName.id = "s1-default-card-name";
        dcName.innerText = "Member name";
    }

    for (let member of window.members) {
        document.getElementById("s1-" + member.id).addEventListener("click",() => {
            responses.step1 = member.id;
            switchToStep(2);
        });
    }

    // Step 2
    window.members = JSON.parse(localStorage.getItem("pluralkit-" + configSlot)).filter(i => i.name !== "unknown" && i.name !== "fusion" && i.name !== "smolscoots" && i.name !== "smoltwi" && !i.name.endsWith("-travelling")).sort(() => Math.random() - 0.5);
    dc = document.getElementById("s2-default-card");
    dcName = document.getElementById("s2-default-card-name");

    for (let member of window.members) {
        dc.id = "s2-" + member.id;
        dcName.id = "s2-" + member.id + "-name";

        dcName.innerText = member.display_name ?? member.name;

        dc.style.display = "";
        document.getElementById("step2").appendChild(dc.cloneNode(true));

        dc.style.display = "none";
        dc.id = "s2-default-card";
        dcName.id = "s2-default-card-name";
        dcName.innerText = "Member name";
    }

    for (let member of window.members) {
        document.getElementById("s2-" + member.id).addEventListener("click",() => {
            responses.step2 = member.id;
            switchToStep(3);
        });
    }

    // Step 3
    window.members = JSON.parse(localStorage.getItem("pluralkit-" + configSlot)).filter(i => i.name !== "unknown" && i.name !== "fusion" && i.name !== "smolscoots" && i.name !== "smoltwi" && !i.name.endsWith("-travelling")).sort(() => Math.random() - 0.5);
    dc = document.getElementById("s3-default-card");
    dcName = document.getElementById("s3-default-card-img");

    for (let member of window.members) {
        dc.id = "s3-" + member.id;
        dcName.id = "s3-" + member.id + "-img";

        dcName.src = "ponies/" + member.id + ".png";

        dc.style.display = "";
        document.getElementById("step3").appendChild(dc.cloneNode(true));

        dc.style.display = "none";
        dc.id = "s3-default-card";
        dcName.id = "s3-default-card-img";
        dcName.src = "";
    }

    for (let member of window.members) {
        document.getElementById("s3-" + member.id).addEventListener("click",() => {
            responses.step3 = member.id;
            switchToStep(4);
        });
    }

    // Step 4
    window.members = JSON.parse(localStorage.getItem("pluralkit-" + configSlot)).filter(i => i.name !== "unknown" && i.name !== "fusion" && i.name !== "smolscoots" && i.name !== "smoltwi" && !i.name.endsWith("-travelling")).sort(() => Math.random() - 0.5);
    dc = document.getElementById("s4-default-card");
    dcName = document.getElementById("s4-default-card-img");

    for (let member of window.members) {
        dc.id = "s4-" + member.id;
        dcName.id = "s4-" + member.id + "-img";

        dcName.src = "profiles/" + member.id + ".png";

        dc.style.display = "";
        document.getElementById("step4").appendChild(dc.cloneNode(true));

        dc.style.display = "none";
        dc.id = "s4-default-card";
        dcName.id = "s4-default-card-img";
        dcName.src = "";
    }

    for (let member of window.members) {
        document.getElementById("s4-" + member.id).addEventListener("click",() => {
            responses.step4 = member.id;
            switchToStep(5);
        });
    }

    // Step 5
    window.members = JSON.parse(localStorage.getItem("pluralkit-" + configSlot)).filter(i => i.name !== "unknown" && i.name !== "fusion" && i.name !== "smolscoots" && i.name !== "smoltwi" && !i.name.endsWith("-travelling")).sort(() => Math.random() - 0.5);
    dc = document.getElementById("s5-default-card");
    dcName = document.getElementById("s5-default-card-name");

    for (let member of window.members) {
        dc.id = "s5-" + member.id;
        dcName.id = "s5-" + member.id + "-name";

        dcName.innerText = WiafConfig[configSlot]["samples"][member.id] ?? member.proxy_tags[0].prefix;

        dc.style.display = "";
        document.getElementById("step5").appendChild(dc.cloneNode(true));

        dc.style.display = "none";
        dc.id = "s5-default-card";
        dcName.id = "s5-default-card-name";
        dcName.innerText = "Member name";
    }

    for (let member of window.members) {
        document.getElementById("s5-" + member.id).addEventListener("click",async () => {
            responses.step5 = member.id;
            switchToStep(6);
            await compute();
        });
    }

    document.getElementById("loader").style.display = "none";
    document.getElementById("step1-outer").style.display = "";
}

function switchToStep(step) {
    if (lastStartTime !== null) {
        responseTimes.push(new Date().getTime() - lastStartTime);
    }

    document.getElementById("step" + (step - 1) + "-outer").style.pointerEvents = "none";
    if (step === 6) document.getElementById("progress").style.pointerEvents = "none";
    document.getElementById("step" + step + "-outer").style.pointerEvents = "none";
    document.getElementById("wiaf-progress").style.width = ((step - 1) * 20) + "%";
    setTimeout(() => {
        document.getElementById("step" + (step - 1) + "-outer").style.opacity = "0";
        if (step === 6) document.getElementById("progress").style.opacity = "0";
        document.getElementById("step" + step + "-outer").style.opacity = "0";
        setTimeout(() => {
            lastStartTime = new Date().getTime();

            document.getElementById("step" + (step - 1) + "-outer").style.display = "none";
            if (step === 6) document.getElementById("progress").style.display = "none";
            document.getElementById("step" + step + "-outer").style.display = "";
            setTimeout(() => {
                document.getElementById("step" + step + "-outer").style.opacity = "1";
                setTimeout(() => {
                    document.getElementById("step" + step + "-outer").style.pointerEvents = "";
                }, 200)
            }, 100)
        }, 200)
    }, 500)
}

async function compute() {
    let seen = {};

    Object.keys(responses).map((i) => {
        return responses[i];
    }).filter((i) => {
        return i !== null;
    }).map((i) => {
        if (!seen[i]) seen[i] = 0;
        seen[i]++;
        return i;
    });

    console.log(seen);
    let implied = Object.keys(seen);

    if (implied.length === 0) {
        document.getElementById("final-load").style.display = "none";
        document.getElementById("final-newpony").style.display = "";
    } else if (implied.length === 1) {
        document.getElementById("final-load").style.display = "none";
        document.getElementById("final-precise").style.display = "";
        document.getElementById("final-precise-member").innerText = getMiniName(getMember(implied[0]).display_name ?? getMember(implied[0]).name);
        document.getElementById("final-precise-proxy").innerText = getMember(implied[0]).proxy_tags[0].prefix ?? "<n/a>";
        document.getElementById("final-precise-pluralkit").innerText = getMember(implied[0]).name;
        document.getElementById("final-precise-link1").href = "https://ponies.equestria.horse/" + WiafConfig[configSlot]["name"] + "/" + (getMember(implied[0]).name);
        document.getElementById("final-precise-link2").href = "https://dash.pluralkit.me/profile/m/" + getMember(implied[0]).id;

        setTimeout(async () => {
            await checkPluralKit(implied[0]);
        }, 2000)
    } else if (implied.length === 2) {
        document.getElementById("final-load").style.display = "none";
        document.getElementById("final-blur").style.display = "";
        document.getElementById("final-blur-m1").innerText = document.getElementById("final-blur-m1-link2").innerText = document.getElementById("final-blur-m1-link1").innerText = getMiniName(getMember(implied[0]).display_name ?? getMember(implied[0]).name);
        document.getElementById("final-blur-m2").innerText = document.getElementById("final-blur-m2-link2").innerText = document.getElementById("final-blur-m2-link1").innerText = getMiniName(getMember(implied[1]).display_name ?? getMember(implied[1]).name);
        document.getElementById("final-blur-m1-link1").href = "https://ponies.equestria.horse/" + WiafConfig[configSlot]["name"] + "/" + (getMember(implied[0]).name);
        document.getElementById("final-blur-m1-link2").href = "https://dash.pluralkit.me/profile/m/" + getMember(implied[0]).id;
        document.getElementById("final-blur-m2-link1").href = "https://ponies.equestria.horse/" + WiafConfig[configSlot]["name"] + "/" + (getMember(implied[1]).name);
        document.getElementById("final-blur-m2-link2").href = "https://dash.pluralkit.me/profile/m/" + getMember(implied[1]).id;
    } else if (implied.length > 2) {
        document.getElementById("final-load").style.display = "none";
        document.getElementById("final-unclear").style.display = "";
        document.getElementById("final-unclear-count").innerText = implied.length.toString();
    }

    let avgCompleteTime = responseTimes.reduce((a, b) => a + b, 0) / responseTimes.length;
    console.log(avgCompleteTime);

    if (avgCompleteTime < 5000) {
        document.getElementById("final-speed-error").style.display = "none";
        document.getElementById("final-speed-fast").style.display = "";
    } else if (avgCompleteTime < 10000) {
        document.getElementById("final-speed-error").style.display = "none";
        document.getElementById("final-speed-medium").style.display = "";
    } else {
        document.getElementById("final-speed-error").style.display = "none";
        document.getElementById("final-speed-slow").style.display = "";
    }
}

async function checkPluralKit(id) {
    try {
        let data = JSON.parse(await (await fetchPlus("https://api.pluralkit.me/v2/systems/" + WiafConfig[configSlot]["system"] + "/fronters", { timeout: 3000 })).text());
        let frontersID = data.members.map((i) => { return i.id; });
        if (frontersID.includes(id)) {
            document.getElementById("final-precise-pk-already").style.display = "";
            document.getElementById("final-precise-pk-waiting").style.display = "none";
        } else {
            document.getElementById("final-precise-pk-register").style.display = "";
            document.getElementById("final-precise-pk-waiting").style.display = "none";
        }
    } catch (e) {
        console.error(e);
        document.getElementById("final-precise-pk-register").style.display = "";
        document.getElementById("final-precise-pk-failed").style.display = "";
        document.getElementById("final-precise-pk-asterisk").style.display = "";
        document.getElementById("final-precise-pk-waiting").style.display = "none";
    }
}

function getMember(id) {
    return window.members.find((i) => i.id === id);
}