import { game, socket, ID } from "./main.js";
import { Region } from "./map.js";
import { Packet } from "./packet.js";

export function unlockMapDom() {
    Object.values(Region.getAllRegions()).forEach((region) => {
        if (!Region.allRegionsClaimed() && region.owner === null) {
            document
                .querySelector(`.node[data-name=${region.name}] .actions`)
                .classList.remove("hidden");
        } else if (region.owner === game.us) {
            document
                .querySelector(`.node[data-name=${region.name}] .actions`)
                .classList.remove("hidden");
        }
    });
}

export function lockMapDom() {
    document.querySelectorAll(".actions").forEach((e) => e.classList.add("hidden"));
}

function updateMapDom() {
    if (game.us.isPlaying) {
        unlockMapDom();
    } else {
        lockMapDom();
    }

    if (game.isPregame()) {
        document.querySelectorAll(".fortify, .attack").forEach((e) => {
            e.classList.add("hidden");
        });

        if (Region.allRegionsClaimed()) {
            document.querySelectorAll(".claim").forEach((e) => {
                e.classList.add("hidden");
            });
            document.querySelectorAll(".reinforce").forEach((e) => {
                e.classList.remove("hidden");
            });
        } else {
            document.querySelectorAll(".reinforce").forEach((e) => {
                e.classList.add("hidden");
            });
        }
    } else if (game.isPlaying()) {
        document.querySelectorAll(".node button:not(.claim)").forEach((e) => {
            e.classList.remove("hidden");
        });

        if (game.us.isPlaying) {
            document.querySelector("#end-turn").classList.remove("hidden");
        } else {
            document.querySelector("#end-turn").classList.add("hidden");
        }
    }

    showStrengths();
    showRemainingReinforcements();
}

function showStrengths() {
    for (let region of Region.getAllRegions()) {
        const element = document.querySelector(`.node[data-name=${region.name}]`);
        element.querySelector(".strength").textContent = region.displayStrength();
        element.style.backgroundColor =
            region.owner === null ? "white" : region.owner.getColor();
    }
}

document.addEventListener("updateStrengths", showStrengths);
document.addEventListener("gameStateUpdate", () => {
    if (!game.isWaiting()) {
        document.querySelector("#ready-button").style.display = "none";
    }
});
document.addEventListener("gameStateUpdate", updateMapDom);
document.addEventListener("playerChange", updateMapDom);
document.addEventListener("turnProgress", updateMapDom);

function updatePlayerDom() {
    let list = document.querySelector("#playerList");
    list.replaceChildren();

    for (let playerId of Object.keys(game.players).sort()) {
        let player = game.players[playerId];

        let statusSpan = document.createElement("div");
        statusSpan.classList.add("status-span");
        if (game.isWaiting()) {
            if (player.ready) {
                statusSpan.textContent = "R";
                statusSpan.classList.add("ready");
            } else {
                statusSpan.textContent = "N";
                statusSpan.classList.add("not-ready");
            }
        } else {
            if (player.isPlaying) {
                statusSpan.textContent = "P";
            }
        }

        let idSpan = document.createElement("span");
        idSpan.style.color = player.getColor();
        if (playerId === ID) {
            idSpan.textContent = `${playerId} (you)`;
        } else {
            idSpan.textContent = playerId;
        }

        let newDom = document.createElement("li");
        newDom.appendChild(statusSpan);
        newDom.appendChild(idSpan);
        list.appendChild(newDom);
    }
}

document.addEventListener("addPlayer", updatePlayerDom);
document.addEventListener("removePlayer", updatePlayerDom);
document.addEventListener("updatePlayer", updatePlayerDom);
document.addEventListener("playerChange", updatePlayerDom);

document.addEventListener("DOMContentLoaded", () => {
    document.querySelector("#ready-button").addEventListener("click", async (ev) => {
        let nowReady = ev.target.textContent === "Not ready";

        ev.target.classList.toggle("active");
        ev.target.textContent = nowReady ? "Ready" : "Not ready";

        socket.emit("message", Packet.createSetReady(nowReady));
    });

    document.querySelector("#end-turn").addEventListener("click", async (ev) => {
        socket.emit("message", Packet.createEndTurn());
    });

    document.querySelectorAll(".claim").forEach((el) =>
        el.addEventListener("click", (ev) => {
            let region = ev.target.closest(".node").dataset.name;
            game.us.sendClaim(region);
        })
    );

    document.querySelectorAll(".reinforce").forEach((el) =>
        el.addEventListener("click", (ev) => {
            let region = ev.target.closest(".node").dataset.name;
            game.us.sendReinforce(region);
        })
    );

    document.querySelectorAll(".attack").forEach((el) =>
        el.addEventListener("click", (ev) => {
            let modal = document.querySelector("#modal");

            let region = ev.target.closest(".node").dataset["name"];

            modal.dataset["region"] = ev.target.closest(".node").dataset.name;
            modal.dataset["action"] = "ATTACK";

            let selector = modal.querySelector(".target");
            selector.replaceChildren("");
            for (let neighbour of Region.getRegion(region).neighbours) {
                let opt = document.createElement("option");
                opt.value = neighbour.name;
                opt.textContent = neighbour.name;
                selector.appendChild(opt);
            }

            modal.classList.remove("hidden");
        })
    );

    document.querySelectorAll(".fortify").forEach((el) =>
        el.addEventListener("click", (ev) => {
            let modal = document.querySelector("#modal");

            let region = ev.target.closest(".node").dataset["name"];

            modal.dataset["region"] = region;
            modal.dataset["action"] = "FORTIFY";

            let selector = modal.querySelector(".target");
            selector.replaceChildren("");
            for (let neighbour of Region.getRegion(region).neighbours) {
                let opt = document.createElement("option");
                opt.value = neighbour.name;
                opt.textContent = neighbour.name;
                selector.appendChild(opt);
            }

            modal.classList.remove("hidden");
        })
    );

    document.querySelector("#modal .submit-modal").addEventListener("click", () => {
        let modal = document.querySelector("#modal");

        let startRegion = modal.dataset["region"];
        let action = modal.dataset["action"];

        let amount = modal.querySelector(".amount").value;
        let endRegion = modal.querySelector(".target").value;

        socket.emit(
            "message",
            Packet.createAction(action, startRegion, endRegion, amount)
        );
    });

    document
        .querySelector("#defense-modal .submit-modal")
        .addEventListener("click", () => {
            let modal = document.querySelector("#defense-modal");
            let amount = modal.querySelector(".amount").value;
            socket.emit("message", Packet.createDefense(amount));
        });

    document.querySelectorAll(".submit-modal, .cancel-modal").forEach((el) => {
        el.addEventListener("click", () => {
            el.closest(".modal").classList.add("hidden");
        });
    });

    document.querySelector("#shuffleColors").addEventListener("click", () => {
        Object.values(game.players).forEach((player) => {
            player.resetColor();
        });
        updatePlayerDom();
    });
});

function showRemainingReinforcements() {
    if (game.isPregame()) {
        document.querySelector(
            "#remaining-reinforcements"
        ).innerHTML = `<span>Remaining placements: ${game.reinforcementsRemaining()}</span>`;
    } else if (game.isPlaying()) {
        document.querySelector(
            "#remaining-reinforcements"
        ).innerHTML = `<span>Remaining placements: ${
            game.currentPlayer().reinforcementsAvailable -
            game.currentPlayer().reinforcementsPlaced
        }</span>`;
    }
}

export function showDefenseDom(region) {
    const modal = document.querySelector("#defense-modal");
    modal.querySelector("span").textContent = region;
    modal.classList.remove("hidden");
}
