ServerEvents.commandRegistry(event => {
    const { commands: Commands } = event

    const spawnLogic = (ctx, cmdName) => {
        const player = ctx.source.player
        if (!player) return 0

        const now = Date.now()
        const cooldown = 3000
        const lastUsed = player.persistentData.lastSpawnTime || 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.lastSpawnTime = now
        const server = ctx.source.server
        const pName = player.username

        server.runCommandSilent(`tp ${pName} 0 101 0 facing 0 101 -1`)
        server.runCommandSilent(`gamemode survival ${pName}`)
        server.runCommandSilent(`spawnpoint ${pName} 0 101 0`)

        const niceName = cmdName.charAt(0).toUpperCase() + cmdName.slice(1)
        
        const messageJson = `{"text":"Teleported to ${niceName}!","color":"green"}`
        server.runCommandSilent(`title ${pName} actionbar ${messageJson}`)

        return 1
    }

    ['spawn', 'hub', 'lobby'].forEach(cmd => {
        event.register(
            Commands.literal(cmd)
            .requires(src => src.hasPermission(0))
            .executes(ctx => spawnLogic(ctx, cmd))
        )
    })
})