ServerEvents.commandRegistry(event => {
    const { commands: Commands } = event
    const COOLDOWN_KEY = "lastEndTime"
    const COOLDOWN = 5000
    const DEATH_OBJECTIVE = 'Deaths' 
    const displayDeathStats = (server) => {
        server.runCommandSilent(`tellraw @a ["",{"text":"--- GAME SUMMARY ---","color":"dark_red","bold":true}]`)
        server.players.forEach(player => {
            const pName = player.username
            server.runCommandSilent(`tellraw @a ["",{"text":"\u25b8 "},{"selector":"${pName}"},{"text":": "},{"score":{"name":"${pName}","objective":"${DEATH_OBJECTIVE}"},"color":"red","bold":true},{"text":" deaths","color":"gray"}]`)
        })
        server.runCommandSilent(`tellraw @a ["",{"text":"-------------------","color":"dark_red","bold":true}]`)
    }
    event.register(
        Commands.literal('end')
        .requires(src => src.hasPermission(0))
        .executes(ctx => {
            const player = ctx.source.player
            if (!player) return 0
            const now = Date.now()
            const lastUsed = player.persistentData[COOLDOWN_KEY] || 0
            if (now - lastUsed < COOLDOWN) {
                const remaining = ((COOLDOWN - (now - lastUsed)) / 1000).toFixed(1)
                player.tell(`§cYou must wait §e${remaining}s §cbefore using this command again!`)
                return 0
            }
            player.persistentData[COOLDOWN_KEY] = now
            const server = ctx.source.server
            const pName = player.username
            server.runCommandSilent(`clear ${pName}`)
            server.runCommandSilent(`tp ${pName} 0 101 0 facing 0 101 -1`)
            server.runCommandSilent(`gamemode survival ${pName}`)
            server.runCommandSilent(`spawnpoint ${pName} 0 101 0`)
            const messageJson = `{"text":"Game ended!","color":"green"}`
            server.runCommandSilent(`title ${pName} times 10 70 20`)
            server.runCommandSilent(`title ${pName} title ${messageJson}`)
            displayDeathStats(server)
            server.runCommandSilent(`scoreboard players set @a Deaths 0`) 
            return 1
        })
    )
})