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

const CHECK_INTERVAL = 200;

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    handleBurningBase(player);
    handleReplaceTorch(player);
    handleReplaceLantern(player);
    handleCreepingHerobrine(player);
    handleNightmare(player);
    handleGlassSpotted(player);
  }
}, CHECK_INTERVAL);

function handleBurningBase(player) {
  const homePos = player.getSpawnPoint();
  if (!homePos) return;
  const playerPos = player.location;
  const dist = distance(playerPos, homePos);
  if (dist > 50 && Math.random() < 0.001) {
    const dim = player.dimension;
    for (let x = -3; x <= 3; x++) {
      for (let z = -3; z <= 3; z++) {
        const tx = Math.floor(homePos.x + x);
        const ty = Math.floor(homePos.y);
        const tz = Math.floor(homePos.z + z);
        const targetPos = new BlockLocation(tx, ty, tz);
        const block = dim.getBlock(targetPos);
        if (block && block.typeId === "minecraft:air" && Math.random() < 0.3) {
          const under = dim.getBlock(new BlockLocation(tx, ty - 1, tz));
          if (
            under &&
            (under.typeId.includes("wood") ||
             under.typeId.includes("planks") ||
             under.typeId.includes("log") ||
             under.typeId.includes("leaves"))
          ) {
            try {
              dim.runCommand(`setblock ${tx} ${ty} ${tz} fire`);
            } catch (e) {
              console.warn("BurningBase setblock failed:", e);
            }
          }
        }
      }
    }
  }
}

function handleReplaceTorch(player) {
  if (Math.random() < 0.1) {
    const pos = player.location;
    const radius = 6;
    const dim = player.dimension;
    for (let dx = -radius; dx <= radius; dx++) {
      for (let dy = -2; dy <= 2; dy++) {
        for (let dz = -radius; dz <= radius; dz++) {
          const bx = Math.floor(pos.x + dx);
          const by = Math.floor(pos.y + dy);
          const bz = Math.floor(pos.z + dz);
          const block = dim.getBlock(new BlockLocation(bx, by, bz));
          if (block && block.typeId === "minecraft:torch") {
            try {
              dim.runCommand(`setblock ${bx} ${by} ${bz} redstone_torch`);
            } catch (e) {
              console.warn("ReplaceTorch setblock failed:", e);
            }
            return;
          }
        }
      }
    }
  }
}

function handleReplaceLantern(player) {
  if (Math.random() < 0.05) {
    const pos = player.location;
    const radius = 6;
    const dim = player.dimension;
    for (let dx = -radius; dx <= radius; dx++) {
      for (let dy = -2; dy <= 2; dy++) {
        for (let dz = -radius; dz <= radius; dz++) {
          const bx = Math.floor(pos.x + dx);
          const by = Math.floor(pos.y + dy);
          const bz = Math.floor(pos.z + dz);
          const block = dim.getBlock(new BlockLocation(bx, by, bz));
          if (block && block.typeId === "minecraft:lantern") {
            try {
              dim.runCommand(`setblock ${bx} ${by} ${bz} soul_lantern`);
            } catch (e) {
              console.warn("ReplaceLantern setblock failed:", e);
            }
            return;
          }
        }
      }
    }
  }
}

function handleCreepingHerobrine(player) {
  if (Math.random() < 0.03) {
    const dim = player.dimension;
    const pos = player.location;
    const hx = pos.x + (Math.random() * 10 - 5);
    const hy = pos.y;
    const hz = pos.z + (Math.random() * 10 - 5);
    try {
      dim.runCommand(`summon gl:herobrine ${hx} ${hy} ${hz}`);
    } catch (e) {
      console.warn("CreepingHerobrine summon failed:", e);
    }
    system.runTimeout(() => {
      try {
        dim.runCommand(`execute as @e[type=gl:herobrine, distance=..3] run event entity @s despawn`);
      } catch (e) {
        console.warn("CreepingHerobrine despawn failed:", e);
      }
    }, 60);
  }
}

function handleNightmare(player) {
  if (Math.random() < 0.02) {
    if (player.hasComponent && player.hasComponent("minecraft:player_sleep")) {
      try {
        player.runCommandAsync(`tp @s ~ ~ ~1`);
      } catch (e) {
        console.warn("Nightmare tp failed:", e);
      }
    }
  }
}

function handleGlassSpotted(player) {
  if (Math.random() < 0.02) {
    const pos = player.location;
    const dim = player.dimension;
    let rot;
    try {
      rot = player.getRotation();
    } catch (e) {
      console.warn("getRotation failed:", e);
      rot = { x: 0, y: 0 };
    }
    const yaw = rot.x;
    const fx = Math.floor(pos.x + Math.sin((yaw * Math.PI) / 180) * 2);
    const fy = Math.floor(pos.y);
    const fz = Math.floor(pos.z + Math.cos((yaw * Math.PI) / 180) * 2);
    const block = dim.getBlock(new BlockLocation(fx, fy, fz));
    if (block && block.typeId.includes("glass")) {
      try {
        dim.runCommand(`summon gl:herobrine ${fx} ${fy} ${fz}`);
      } catch (e) {
        console.warn("GlassSpotted summon failed:", e);
      }
      system.runTimeout(() => {
        try {
          dim.runCommand(`execute as @e[type=gl:herobrine, distance=..5] run event entity @s despawn`);
        } catch (e) {
          console.warn("GlassSpotted despawn failed:", e);
        }
      }, 80);
    }
  }
}

function distance(a, b) {
  const dx = a.x - b.x;
  const dy = a.y - b.y;
  const dz = a.z - b.z;
  return Math.sqrt(dx * dx + dy * dy + dz * dz);
}