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

const TAG_REGISTERED = "hb_hr_registered_player";
const OBJ_NAME = "hb_hr_WorldFirstLoaded";
const GLOBAL_COUNTER = "var"; // dummy “player” for world-load tracking

export function playerHandler() {
  system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
      if (!player.isValid()) continue;
      if (player.hasTag(TAG_REGISTERED)) continue; // skip those we’ve set up already
      handleFirstJoin(player);
    }
  }, 1);
}

function handleFirstJoin(player) {
  // get or create the “world first loaded” objective (type DUMMY)
  let objective = world.scoreboard.getObjective(OBJ_NAME) || world.scoreboard.addObjective(OBJ_NAME, OBJ_NAME);

  // bump our global “loaded” counter
  player.runCommand("/scoreboard players add var hb_hr_WorldFirstLoaded 0");
  let entry = objective.getScore(GLOBAL_COUNTER);
  let newCount = entry + 1;
  // world.sendMessage("entry: " + entry)
  objective.setScore(GLOBAL_COUNTER, newCount);

  // if this was literally the first time the map loaded
  if (newCount === 1) {
    // …any “map-first-load” logic here…
    // Executing init.mcfunction to initialize scoreboards in the world
  }

  // per-player first-join logic
  if (player.hasTag("hb_hr:jumpscare_movement")) {
    player.runCommand(`/inputpermission set @s movement enabled`);
    player.runCommand(`/inputpermission set @s camera enabled`);
    player.removeTag("hb_hr:jumpscare_movement");
  }
  player.runCommand("/gamerule sendcommandfeedback false");
  player.runCommand("/gamerule commandBlockOutput false");
  player.runCommand("/gamerule showtags false");
  player.runCommand("/give @s hb_hr:guide_book_spawn_egg");
  player.runCommand("/give @s hb_hr:ambient_handler_item");
  player.runCommand('/tellraw @s {"rawtext":[{"text":"§l§4HorrorCraft§r Add-On!"}]}');
  player.addTag("hb_hr:FirstJoined");

  // mark them so we won’t run this again
  player.addTag(TAG_REGISTERED);
}

///////////////////////////////////
export function playerJoins() {
  world.afterEvents.playerSpawn.subscribe((event) => {
    const player = event.player;
    if (!player.isValid()) return;
    else {
      system.runTimeout(() => {
        if (player.hasTag("hb_hr:jumpscare_movement")) {
          player.runCommand(`/inputpermission set @s movement enabled`);
          player.runCommand(`/inputpermission set @s camera enabled`);
          player.removeTag("hb_hr:jumpscare_movement");
        }
      }, 100);
    }
  });
}
