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

// Set up a repeating interval to check for players near the lobby armor stand
let lastCheckTime = 0; // Variable to track the last check time

const checkArmorStandProximity = (armorStandName, teleportCoordinates, distanceThreshold) => {
    const armorStand = world.getDimension("overworld").getEntities({ type: "minecraft:armor_stand", name: armorStandName });

    if (armorStand.length > 0) {
        // Check for all players in the world
        const players = world.getPlayers();
        players.forEach(player => {
            const playerPosition = player.location;
            const armorStandPosition = armorStand[0].location;

            const distance = Math.sqrt(
                Math.pow(playerPosition.x - armorStandPosition.x, 2) +
                Math.pow(playerPosition.y - armorStandPosition.y, 2) +
                Math.pow(playerPosition.z - armorStandPosition.z, 2)
            );

            if (distance <= distanceThreshold) {
                // Teleport the player with facing direction
                try {
                    if (armorStandName === "lobby") {
                        // Teleport to lobby and face towards the shop
                        player.runCommand(`tp @s ${teleportCoordinates.join(' ')} facing 66.38 -61.00 -242.45`);
                    } else if (armorStandName === "shop") {
                        // Teleport to shop and face towards the lobby
                        player.runCommand(`tp @s ${teleportCoordinates.join(' ')} facing 37.50 -58.00 25.22`);
                    }
                } catch (error) {
                    console.error(`Failed to teleport ${player.name}: ${error}`);
                }
            }
        });
    }
};

system.runInterval(() => {
    const currentTime = Date.now();
    if (currentTime - lastCheckTime >= 100) { // Check every 5 ticks (100 milliseconds)
        lastCheckTime = currentTime;

        // Check for players near the lobby armor stand
        checkArmorStandProximity("lobby", [70.43, -61.00, -242.44], 4);
        // Check for players near the shop armor stand
        checkArmorStandProximity("shop", [37.51, -57.84, 33.48], 2);
    }
}, 5); // Run every 5 ticks (approximately 250 milliseconds)