function handleErrors(response) {
    if (!response.ok) {
        document.getElementById("serverStatus").innerHTML = "";
        document.getElementById("serverStatusM").innerHTML = "";
        document.getElementById("serverLogoName").classList.remove("hidden");
    }
    return response;
}

function createPlayerCard(playerName, uuid) {
    const card = document.createElement("div");
    card.className = "px-4 py-4 w-40 text-center flex flex-col items-center gap-2";

    const avatar = document.createElement("img");
    avatar.src = `https://map.tuxworld.nl/maps/world/assets/playerheads/${uuid}.png`;
    avatar.alt = playerName;
    avatar.className = "w-16 h-16 shadow-md";

    const name = document.createElement("p");
    name.textContent = playerName;
    name.className = "font-mono text-sm break-words";

    card.appendChild(avatar);
    card.appendChild(name);
    return card;
}

async function getUUID(playerName) {
    try {
        const res = await fetch(`https://api.ashcon.app/mojang/v2/user/${playerName}`);
        if (!res.ok) throw new Error();
        const data = await res.json();
        return data.uuid;
    } catch {
        return "00000000000000000000000000000000";
    }
}

function formatServerType(type) {
    if (!type) return "";
    return type.split("-").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
}

function parsePlayers(input) {
    if (!input) return [];
    try {
        return JSON.parse(input);
    } catch {
        try {
            const fixed = input.replace(/'/g, '"');
            return JSON.parse(fixed);
        } catch {
            return [];
        }
    }
}

fetch("/api")
    .then(handleErrors)
    .then(r => r.json())
    .then(async res => {
        const data = res.data;

        const container = document.getElementById("playerCards");
        container.innerHTML = "";

        if (data.online === undefined) throw new Error();

        const serverType = formatServerType(data.server_id?.type || data.type);
        const version = data.version || "";

        document.getElementById("serverVer").textContent =
            `${serverType} ${version}`.trim() || "Minecraft Server";

        const onlineText = `<p class="font-bold select-none">
            <span class="text-green-600">&#11044;</span>&emsp;
            Online, ${data.online} / ${data.max} playing
        </p>`;

        document.getElementById("serverStatus").innerHTML = onlineText;
        document.getElementById("serverStatusM").innerHTML = onlineText;

        document.getElementById("serverPlaynow").innerHTML =
            `<span class="inline-block bg-yellow-500 rounded-full px-3 py-1 text-sm font-thin uppercase text-gray-900 mr-2 shadow-lg">Play Now</span>`;

        document.getElementById("serverIP").classList.remove("bg-orange-800");
        document.getElementById("serverIP").classList.add("bg-green-900");

        const players = parsePlayers(data.players);

        if (players.length > 0) {
            for (const player of players) {
                const name = player.name || player;
                const uuid = await getUUID(name);
                container.appendChild(createPlayerCard(name, uuid));
            }
        } else {
            const msg = document.createElement("p");
            msg.textContent = "No players online";
            msg.className = "text-gray-400";
            container.appendChild(msg);
        }
    })
    .catch(() => {
        document.getElementById("serverStatus").innerHTML =
            `<p class="text-red-600 font-bold">Error loading server status</p>`;

        document.getElementById("serverStatusM").innerHTML =
            `<p class="text-red-600 font-bold">Error</p>`;

        document.getElementById("playerCards").innerHTML =
            `<p class="text-gray-400">Cannot load players</p>`;
    });
