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

world.afterEvents.playerSpawn.subscribe((event) => {
  const player = event.player;
  if (!player) {
    console.warn("[Admin] No player found in playerSpawn event!");
    return;
  }

  const admins = world.getPlayers({ tags: ["admin"] });
  if (admins.length === 0) {
    try {
      player.runCommand(`tag @s add admin`);
      player.sendMessage("You are the first player and have been granted admin!");
      console.log(`[Admin] Given admin to ${player.name}`);

      // ✅ Give book and set dynamic property
      if (!player.getDynamicProperty("hasReceivedAddonBook")) {
        const bookItem = new ItemStack("just:addon_book", 1);
        player.getComponent("inventory")?.container?.addItem(bookItem);
        player.setDynamicProperty("hasReceivedAddonBook", true);
      }
    } catch (e) {
      console.warn("[Admin] Failed to give admin tag or item:", e);
    }
  }
});

