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

const TICK_INTERVAL = 40;
const FREEZE_START = 50;
const MAX_WARMTH = 300;
const FIRE_IDS = ["minecraft:fire", "minecraft:soul_fire"];
const CAMPFIRE_IDS = ["minecraft:campfire", "minecraft:soul_campfire"];

function getWarmth(player) {
  const obj = world.scoreboard.getObjective("warmth");
  if (!obj) return 0;
  const score = obj.getScore(player);
  return score ?? 0;
}

system.runTimeout(() => {
  const overworld = world.getDimension("overworld");

  overworld.runCommand(`scoreboard objectives add warmth dummy`);
  overworld.runCommand(`scoreboard objectives setdisplay sidebar warmth`);
  overworld.runCommand(`scoreboard players set @a warmth ${MAX_WARMTH}`);

  system.runInterval(() => {
    const obj = world.scoreboard.getObjective("warmth");

    for (const player of world.getPlayers()) {
      obj.setScore(player, getWarmth(player) - 1);

      let heatGain = 0;

      const armor = player.getComponent("minecraft:equippable");
      if (armor) {
        const slots = [
          EquipmentSlot.Head,
          EquipmentSlot.Chest,
          EquipmentSlot.Legs,
          EquipmentSlot.Feet
        ];
        for (const slot of slots) {
          const item = armor.getEquipment(slot);
          if (item && item.typeId.startsWith("minecraft:leather_"))
            heatGain += 5;
        }
      }
      let hasHeatSource = false;

      const px = Math.floor(player.location.x);
      const py = Math.floor(player.location.y);
      const pz = Math.floor(player.location.z);

      for (let x = -4; x <= 4; x++) {
        for (let y = -2; y <= 2; y++) {
          for (let z = -4; z <= 4; z++) {
            const block = player.dimension.getBlock({ x: px + x, y: py + y, z: pz + z });
            if (!block) continue;
            const id = block.typeId;
            if (FIRE_IDS.includes(id) || CAMPFIRE_IDS.includes(id)) {
              hasHeatSource = true;
            }
          }
        }
      }

      if (hasHeatSource) heatGain += 3;
      if (player.dimension.id === "nether") {
        heatGain += 8
      }
      if (heatGain > 0) {
        obj.setScore(player, getWarmth(player) + heatGain);
      }

      let warmth = getWarmth(player);

      if (warmth > MAX_WARMTH) {
        warmth = MAX_WARMTH;
        obj.setScore(player, MAX_WARMTH);
      }

      if (warmth <= FREEZE_START) {
        player.runCommand("title @s title jumpscare1")
        player.applyDamage(1, { cause: "freezing" });
      }
    }
  }, TICK_INTERVAL);
}, 5);

world.afterEvents.playerSpawn.subscribe(ev => {
  if (ev.initialSpawn) {
    const obj = world.scoreboard.getObjective("warmth");
    if (obj) obj.setScore(ev.player, MAX_WARMTH);
  }
});