let isEndSequenceRunning = false;
ServerEvents.commandRegistry(event => {
    const { commands: Commands } = event;
    const DEATH_OBJECTIVE = 'Deaths';
    event.register(
        Commands.literal('cancelen')
        .requires(src => src.hasPermission(0))
        .executes(ctx => {
            if (isEndSequenceRunning) {
                isEndSequenceRunning = false;
                const pName = ctx.source.player ? ctx.source.player.username : "Admin";
                ctx.source.server.tell(Text.of(`§e${pName} §fcancelled the countdown!`));
            }
            return 1;
        })
    );
    event.register(
        Commands.literal('end')
        .requires(src => src.hasPermission(2))
        .executes(ctx => {
            const server = ctx.source.server;
            if (isEndSequenceRunning) {
                ctx.source.sendFailure("Game reset already in progress.");
                return 0;
            }
            isEndSequenceRunning = true;
            let cancelRaw = `["",{"text":"\\n \u26a0 WARNING: Game reset initiated! \u26a0\\n","color":"red","bold":true},{"text":"CLICK HERE TO CANCEL","color":"green","bold":true,"underlined":true,"clickEvent":{"action":"run_command","value":"/cancelen"},"hoverEvent":{"action":"show_text","value":"Stop the reset!"}},{"text":"\\n"}]`;
            server.runCommandSilent(`tellraw @a ${cancelRaw}`);
            server.tell(Text.of("§cGame will reset in 10 seconds..."));
            let countdown = 10;
            const timer = (time) => {
                server.scheduleInTicks(20, () => {
                    if (!isEndSequenceRunning) return;

                    if (time > 1) {
                        let next = time - 1;
                        if (next <= 5) {
                            server.runCommandSilent(`title @a title {"text":"${next}","color":"red","bold":true}`);
                            server.runCommandSilent(`playsound minecraft:block.note_block.bit master @a ~ ~ ~ 1 1`);
                        }
                        timer(next);
                    } else {
                        performReset(server, DEATH_OBJECTIVE);
                        isEndSequenceRunning = false;
                    }
                });
            };
            timer(countdown);
            return 1;
        })
    );
});
function performReset(server, objectiveName) {
    server.tell(Text.of("§6\u2560\u2550\u2550\u2563 §5§lGAME SUMMARY§r §6\u2560\u2550\u2550\u2563"));
    server.tell(Text.of(""));
    server.players.forEach(p => {
        try {
            server.runCommandSilent(`tellraw @a ["",{"text":"▸ ","color":"white"},{"selector":"${p.username}","bold":false},{"text":": ","color":"white"},{"score":{"name":"${p.username}","objective":"${objectiveName}"},"color":"red","bold":true},{"text":" deaths","color":"gray"}]`);
        } catch (e) {
            console.error("Error displaying score: " + e);
        }
    });
    server.tell(Text.of(""));
    server.tell(Text.of("§6\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"));
    server.players.forEach(p => {
        try {
            p.setXpLevel(0);
            p.setXp(0);
            p.inventory.clear();
            p.enderChestInventory.clear();
            p.health = 20;
            p.foodLevel = 20;
            p.teleportTo(p.level.id, 0.5, 101, 0.5, 180, 0);
            server.runCommandSilent(`spawnpoint ${p.username} 0 101 0`);
        } catch (e) {
            server.runCommandSilent(`tp ${p.username} 0.5 101 0.5 180 0`);
        }
    });
    server.runCommandSilent(`team leave @a`);
    server.scheduleInTicks(5, () => {
        server.runCommandSilent(`scoreboard players set @a ${objectiveName} 0`);
        server.runCommandSilent(`gamemode survival @a`);
        server.runCommandSilent(`title @a title {"text":"RESET COMPLETE","color":"green"}`);
    });
}