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

system.runInterval(() => {
  // Define mappings: entityId → valid block types
  const entityBlockMap = {
    "pb_gat:mb_tinker_table_entity": [
      "pb_gat:mb_tinker_table_bottom",
      "pb_gat:mb_tinker_table_top",
    ],
    "pb_gat:mb_upgrade_puncher_entity": [
      "pb_gat:mb_upgrade_puncher_bottom",
      "pb_gat:mb_upgrade_puncher_top",
    ],
  };

  // Get all players
  const players = world.getAllPlayers();

  players.forEach((player) => {
    const dimension = player.dimension;
    const playerLoc = player.location;

    // For each entity type we care about
    for (const [entityId, validBlocks] of Object.entries(entityBlockMap)) {
      const entities = dimension.getEntities({
        type: entityId,
        location: playerLoc,
        maxDistance: 12, // Only within 12 blocks of this player
      });

      entities.forEach((entity) => {
        const blockLoc = entity.location;
        const block = dimension.getBlock(blockLoc);

        if (!block || !validBlocks.includes(block.typeId)) {
          entity.remove(); // Despawn invalid entity
        }
      });
    }
  });
}, 5);
