import { world } from "@minecraft/server"
import { ActionFormData, ModalFormData } from "@minecraft/server-ui"

let counter
let pn
world.events.tick.subscribe(() => { // death event stuff
    let players = Array.from(world.getPlayers());
    for (let player of players) {
        if (player.getComponent("minecraft:health").current != 0 && counter == "died" && !player.hasTag(`dead`) && player.name == pn) {
            player.addTag(`dead`)
            player.runCommand(`titleraw ${pn} times 0 100 0`)
            player.onScreenDisplay.setTitle(`§4You Died`)
            player.onScreenDisplay.updateSubtitle(`§fThanks for Playing!`)
            player.runCommand(`tellraw ${pn} {"rawtext":[{"text":"\n§7[You can now use §a.ui§7 in chat to teleport to other alive players.]"}]}`)
            player.runCommand(`gamemode spectator ${pn}`)
            counter = " "
        }
        if (player.getComponent("minecraft:health").current == 0 && counter != "died") {
            pn = player.name
            player.runCommandAsync(`tellraw @a {"rawtext":[{"text":"${player.name} died §4permanently"}]}`)
            counter = "died"
        }
        if (player.hasTag("rebirth")) { player.runCommandAsync(`function hardcore(/).rebirth`) }
        if (player.hasTag("reborn")) { player.runCommandAsync(`function hardcore(/).rebirth`) }
        if (player.hasTag("alive")) { player.runCommandAsync(`function hardcore(/).rebirth`) }
        player.runCommandAsync(`tag @a[m=s,tag=dead] add hardcore-modeswitch`)
        player.runCommandAsync(`tag @a[m=c,tag=dead] add hardcore-modeswitch`)
        player.runCommandAsync(`tag @a[m=a,tag=dead] add hardcore-modeswitch`)
        if (player.hasTag(`hardcore-modeswitch`)) {
            player.runCommand(`function hardcore(/).rebirth`)
            player.runCommand(`tag @s remove hardcore-modeswitch`)
        }


    }
})
world.events.beforeChat.subscribe((event) => { //chat
    let player = event.sender
    let msg = event.message
    if (msg == `.ui` && player.hasTag(`dead`)) {
        player.addTag(`open-ui-cooldown`)
        event.cancel = true
        return;
    }
    if (msg == `.ui` && !player.hasTag(`dead`)) {
        player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§4Sorry, §cyou cannot use this feature when you're alive!"}]}`)
        event.cancel = true
        return;
    }
    if (!player.hasTag(`dead`)) { return; }
    event.cancel = true
    if (msg.includes("\"")) { msg = msg.replace(/\"/gi, `f510ba94-bb61-42f2-b982-0dcd623cf54c`) }
    if (msg.includes("\\")) { msg = msg.replace(/\\/gi, `fa232ee6-7ac9-4c91-8167-cff363d857db`) }
    msg = msg.replace(/f510ba94-bb61-42f2-b982-0dcd623cf54c/gi, `\\\"`).replace(/fa232ee6-7ac9-4c91-8167-cff363d857db/gi, `\\\\`)
    player.runCommandAsync(`tellraw @a {"rawtext":[{"text":"§4Dead§f <${player.name}> ${msg}"}]}`)
})

import { Player } from "@minecraft/server";//also helpful
// by JaylyDev, ScriptAPI \/
function getScore(player, objectiveId, rNull = false) { try { return world.scoreboard.getObjective(objectiveId).getScore(player.scoreboard); } catch (error) { return rNull ? null : 0; } }
// by JaylyDev, ScriptAPI /\

let playersArray = ["none"]//start of wat i needs
world.events.tick.subscribe(() => {
    let players = Array.from(world.getPlayers())
    for (let player of players) {
        if (player.hasTag(`open-ui-cooldown`)) {
            player.runCommandAsync(`scoreboard players add @s cooldown 1`)
        }
        if (getScore(player, "cooldown") == 1) {
            player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"\n§7Please §4exit§7 the chat in §a2§7 seconds"}]}`)
        }
        if (getScore(player, "cooldown") == 20) {
            player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"\n§7Please §4exit§7 the chat in §a1§7 second"}]}`)
        }
        if (getScore(player, "cooldown") > 45) {
            playersArray = ["none"]//HERE IT IS!
            players.forEach(myFunction)
            function myFunction(e) { if (!e.hasTag(`dead`)) { playersArray.push(e.name) } }
            const ui = new ModalFormData()
                .title(`Teleport to a Player §cBETA`)
                .dropdown(`Select a Player`, playersArray)
            ui.show(player).then(promise => {
                // if(promise.formValues[0] == 0){return;}
                player.runCommand(`tp @s ${playersArray[promise.formValues[0]]}`)
                player.runCommand(`tellraw @s {"rawtext":[{"text":"§7Teleported to §a${playersArray[promise.formValues[0]]}"}]}`)
            })
            player.runCommandAsync(`scoreboard players reset @s "cooldown"`)
            player.removeTag(`open-ui-cooldown`)
        }
    }
})

world.events.worldInitialize.subscribe(() => {
    world.getDimension("overworld").runCommand(`function hardcore(/).wi`)
    console.error("§aworldInitialize §c[Simple Hardcore]")
})














//myu testsd
player.forEach(newPlayer)

world.events.playerJoin.subscribe(newPlayer)












let testActionForm = new ActionFormData();
form.title("Test Form");
form.body("clik");
form.button("button1", "textures/items/diamond");
form.button("button2", "textures/items/diamond_sword");

let testMessageForm = new MessageFormData();
form.title("Message form");
form.body("body");
form.button1("ye");
form.button2("noh");



world.events.beforeItemUse.subscribe(event => {
    if (event.item.typeId === "minecraft:stick" && event.item.nameTag === "Form Opener") {
        let testModalForm = new ModalFormData()
        let testlist = ["leaf", "shoe", "foo", "Hello World"]
            .title("title")
            .textField("TextTitle", "Type Here")
            .dropdown("dropdown", testlist)
            .slider("slider", 0, 400, 2)
            .toggle("toggle", true)
        testModalForm.show(event.source).then(r => {

        }).catch((e) => {
            console.error(e, e.stack);
        });
    };
});



let playersArray = ["none"]//start of wat i needs
world.events.tick.subscribe(() => {
    let players = Array.from(world.getPlayers())
    for (let player of players) {
        if (player.hasTag(`open-ui-cooldown`)) {
            player.runCommandAsync(`scoreboard players add @s cooldown 1`)
        }
        if (getScore(player, "cooldown") == 1) {
            player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"\n§7Please §4exit§7 the chat in §a2§7 seconds"}]}`)
        }
        if (getScore(player, "cooldown") == 20) {
            player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"\n§7Please §4exit§7 the chat in §a1§7 second"}]}`)
        }
        if (getScore(player, "cooldown") > 45) {
            playersArray = ["none"]//HERE IT IS!
            players.forEach(myFunction)
            function myFunction(e) { if (!e.hasTag(`dead`)) { playersArray.push(e.name) } }
            const ui = new ModalFormData()
                .title(`Teleport to a Player §cBETA`)
                .dropdown(`Select a Player`, playersArray)
            ui.show(player).then(promise => {
                // if(promise.formValues[0] == 0){return;}
                player.runCommand(`tp @s ${playersArray[promise.formValues[0]]}`)
                player.runCommand(`tellraw @s {"rawtext":[{"text":"§7Teleported to §a${playersArray[promise.formValues[0]]}"}]}`)
            })
            player.runCommandAsync(`scoreboard players reset @s "cooldown"`)
            player.removeTag(`open-ui-cooldown`)
        }
    }
})




if (!lastTick) {
    lastTick = tick.currentTick
}




let lastTick = undefined




lastTick = tick.currentTick