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

let isFormBeingProcessed = false;

export default async function showfirsttime(sourcePlayer) {
  if (isFormBeingProcessed) {
    return;
  }

  isFormBeingProcessed = true;

  try {
    const form = new ActionFormData()
      .title({ translate: "warning.float_fc:firsttime.title" })
      .body({ translate: "warning.float_fc:firsttime.body" })
      .button({ translate: "warning.float_fc:firsttime.treespawning" }, "textures/float/f/ui/treespawn")
      .button({ translate: "warning.float_fc:firsttime.notreespawning" }, "textures/float/f/ui/notreespawn");
    const response = await form.show(sourcePlayer);

    if (!response.isCanceled && response.selection !== undefined) {
      console.log("Form response:", JSON.stringify(response));
      const treeSpawnTag = `no_tree_spawning`;
      if (response.selection === 0) {
        world.setDynamicProperty(treeSpawnTag, true);
      } else if (response.selection === 1) {
        world.setDynamicProperty(treeSpawnTag, false);
      }
    }
  } catch (error) {
    console.error("Failed to show form:", error);
  } finally {
    isFormBeingProcessed = false;
  }
}

world.afterEvents.playerSpawn.subscribe((event) => {
  const player = event.player;

  if (!player.hasTag("has_float_fc_book")) {
    showfirsttime(player);
    player.runCommandAsync("function fs/f/init");

    let spawnLocation = player.location;
    let blockAbove;
    let yOffset = 2;

    do {
      blockAbove = player.dimension.getBlock({
        x: Math.floor(spawnLocation.x),
        y: Math.floor(spawnLocation.y) + yOffset,
        z: Math.floor(spawnLocation.z) - 5,
      });
      yOffset++;
    } while (blockAbove.typeId !== "minecraft:air");

    player.runCommand(`summon float_fc:sapling_trader ^ ^${yOffset - 1} ^-5`);
  }
});
