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

const GUIDE_BOOK_ID = "msft:guide_book";
const DESPAWN_DISTANCE = 20;
const DESPAWN_DISTANCE_SQUARED = DESPAWN_DISTANCE * DESPAWN_DISTANCE;
const DESPAWN_DELAY_SECONDS = 1;

const despawningEntities = new Set();

function distanceSquared(loc1, loc2) {
    const dx = loc1.x - loc2.x;
    const dy = loc1.y - loc2.y;
    const dz = loc1.z - loc2.z;
    return dx * dx + dy * dy + dz * dz;
}

system.runInterval(() => {
    const players = world.getAllPlayers();
    if (players.length === 0) return;

    const dimension = players[0].dimension;
    const guideBooks = dimension.getEntities({ type: GUIDE_BOOK_ID });

    for (const book of guideBooks) {
        if (despawningEntities.has(book.id)) {
            continue;
        }

        const playerIsFar = players.some(
            player => player.dimension.id === dimension.id &&
            distanceSquared(player.location, book.location) > DESPAWN_DISTANCE_SQUARED
        );
        
        if (playerIsFar) {
            despawningEntities.add(book.id);
            book.playAnimation("close");

            system.runTimeout(() => {
                despawningEntities.delete(book.id);

                const entityExists = world.getEntity(book.id);
                if (!entityExists) return;

                const itemToDrop = new ItemStack("msft:item_guide_book", 1);
                dimension.spawnItem(itemToDrop, book.location);
                
                book.remove();

            }, DESPAWN_DELAY_SECONDS * 20);
        }
    }
}, 40);