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

world.afterEvents.playerJoin.subscribe((event) => {

    system.runTimeout(() => {

        try {
            const player = world.getEntity(event.playerId);
            if (!player) return;

            if (player.hasTag("useSkill")) player.removeTag("useSkill");

            if (!player.hasTag("Joined")) {
                const location = player.location;

                player.runCommandAsync(`titleraw @s times 30 100 30`);
                player.runCommandAsync(`title @s title title_tutorial`);
                player.runCommandAsync(`titleraw @s times 0 0 0`);
                player.addTag("Joined");

                if (world.getDynamicProperty("structure_spawned")) return;
                player.runCommandAsync("gamerule commandblockoutput false");
                world.structureManager.place(
                    "msf_bc:spawn", player.dimension,
                    { x: location.x, y: location.y - 11, z: location.z },
                    { includeBlocks: true, rotation: StructureRotation.Rotate90 }
                );
                world.setDefaultSpawnLocation({ x: location.x + 22, y: location.y + 48, z: location.z + 18 });
                player.setSpawnPoint({ dimension: player.dimension, x: location.x + 22, y: location.y + 48, z: location.z + 18 });
                player.tryTeleport(
                    { x: location.x + 22, y: location.y + 48, z: location.z + 18 },
                    { dimension: player.dimension }
                );
                player.addEffect("minecraft:mining_fatigue", 9999, { showParticles: false });
                world.setDynamicProperty("structure_spawned", true);
                player.playSound("msft:ambient:welcome");
                player.getComponent("inventory").container.addItem(new ItemStack("msft:item_guide_book"))
            }
        } catch (error) {
        }
    }, 120);
})
