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

import "mythicus/warpstone/modules/devtools.js";
import "mythicus/warpstone/modules/waystone.js";
import "mythicus/warpstone/guidebook.js";
import "mythicus/warpstone/guidebook_update.js";
import "mythicus/warpstone/modules/trader.js";
import { itemLore } from "mythicus/warpstone/modules/lore.js";



world.afterEvents.playerSpawn.subscribe(event => {
    system.runTimeout(() => playerJoin(event.player), 30);
});

const UPDATE_VERSION = 1;

function playerJoin(player) {
    if ((player.getDynamicProperty("mythicus:waystone.updateVersion") || 0) !== UPDATE_VERSION) {
        player.setDynamicProperty("mythicus:waystone.updateVersion", UPDATE_VERSION);

        const dim = player.dimension;
        const pos = player.location;

        dim.spawnItem(new ItemStack("mythicus_ws:waystone.guidebook.update", 1), pos);
    }

    const firstJoin = player.getDynamicProperty("mythicus:waystone.firstJoin") || false;
    if (firstJoin) return;

    player.setDynamicProperty("mythicus:waystone.firstJoin", true);

    const dim = player.dimension;
    const pos = player.location;

    dim.spawnItem(new ItemStack("mythicus_ws:waystone.guidebook", 1), pos);
    dim.spawnItem(new ItemStack("mythicus_ws:waystone.interact", 1), pos);
    dim.spawnItem(new ItemStack("mythicus_ws:waystone.energize.waystone", 1), pos);
    dim.spawnItem(new ItemStack("mythicus_ws:waystone.stone", 1), pos);
}

system.runInterval(() => {
    for (const player of world.getPlayers()) {
      try {
        itemLore(player);
      } catch {
        continue;
      }
    }
}, 10);

const event = world.afterEvents.playerSpawn.subscribe(({ player }) => {
  if (!world.getDynamicProperty("mythicus:waystone.worldInit")) {
    world.setDynamicProperty("mythicus:waystone.worldInit", true);
  }
  world.afterEvents.playerSpawn.unsubscribe(event);
});