import { world, system } from "@minecraft/server";

const CHECK_INTERVAL = 20 * 60 * 3; 
const RETRY_INTERVAL = 20 * 60 * 2; 
const MESSAGE = "§bCheckpoint... Done";


const playerTimers = new Map();


world.afterEvents.playerSpawn.subscribe(ev => {
    const player = ev.player;

    if (!playerTimers.has(player.id)) {
        player.sendMessage(MESSAGE);

        playerTimers.set(player.id, {
            nextCheck: system.currentTick + CHECK_INTERVAL
        });
    }
});


system.runInterval(() => {
    const tick = system.currentTick;

    for (const player of world.getPlayers()) {
        const data = playerTimers.get(player.id);
        if (!data) continue;

        if (tick < data.nextCheck) continue;

        if (player.dimension.id !== "minecraft:overworld") {
            data.nextCheck = tick + RETRY_INTERVAL;
            continue;
        }
        
        if (player.isInWater) {
            data.nextCheck = tick + RETRY_INTERVAL;
            continue;
        }

        const health = player.getComponent("minecraft:health");
        if (!health || health.current !== health.value) {
            data.nextCheck = tick + RETRY_INTERVAL;
            continue;
        }

        const loc = player.location;

        player.dimension.runCommandAsync(
            `spawnpoint ${player.name} ${loc.x.toFixed(2)} ${loc.y.toFixed(2)} ${loc.z.toFixed(2)}`
        );

        player.sendMessage(MESSAGE);

        data.nextCheck = tick + CHECK_INTERVAL;
    }
}, 20);
