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

// Bug fix for player spawning in air
world.afterEvents.playerSpawn.subscribe(e => {
    if (!e.initialSpawn) return;
    const p = e.player;
    const d = p.dimension;

    const getBlockAtYOffsetPlayerPos = (y = 0) => d.getBlock({ ...p.location, y: p.location.y + y });

    let yOffset = 0;
    let blockType = getBlockAtYOffsetPlayerPos(yOffset)?.typeId;

    while (yOffset > -5 && (blockType === 'ecbl_bc:fake_air' || blockType === 'minecraft:air')) {
        yOffset--;
        blockType = getBlockAtYOffsetPlayerPos(yOffset)?.typeId;
    }

    if (yOffset <= -5) {
        let foundFakeAir = false;

        // move down until solid ground while determining if the spawn is due to world gen, i.e., spawning ontop of fake air
        while (blockType === 'ecbl_bc:fake_air' || blockType === 'minecraft:air') {
            if (blockType === 'ecbl_bc:fake_air') foundFakeAir = true;
            yOffset--;
            blockType = getBlockAtYOffsetPlayerPos(yOffset)?.typeId;
        }

        if (!foundFakeAir) return;
        if (yOffset < 0) p.teleport({ ...p.location, y: p.location.y + yOffset });
    }

});