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

// --- define first (prevents ReferenceError) ---
const dynamicLight = new Map([
  ["compycraft_alien:flashlight",           { amount: 15, slot: "Mainhand" }],
  ["compycraft_alien:night_ops_helmet",     { amount: 15, slot: "Head"     }],
  ["minecraft:beacon",                      { amount: 13, slot: "Mainhand" }],
  ["minecraft:ochre_froglight",             { amount: 13, slot: "Mainhand" }],
  ["minecraft:pearlescent_froglight",       { amount: 13, slot: "Mainhand" }],
  ["minecraft:verdant_froglight",           { amount: 13, slot: "Mainhand" }],
  ["minecraft:glowstone",                   { amount: 13, slot: "Mainhand" }],
  ["minecraft:lantern",                     { amount: 13, slot: "Mainhand" }],
  ["minecraft:shroomlight",                 { amount: 13, slot: "Mainhand" }],
  ["minecraft:sea_lantern",                 { amount: 13, slot: "Mainhand" }],
  ["minecraft:lit_pumpkin",                 { amount: 13, slot: "Mainhand" }],
  ["minecraft:soul_lantern",                { amount: 8,  slot: "Mainhand" }],
  ["minecraft:torch",                       { amount: 12, slot: "Mainhand" }],
  ["minecraft:soul_torch",                  { amount: 8,  slot: "Mainhand" }],
  ["minecraft:redstone_torch",              { amount: 5,  slot: "Mainhand" }],
]);

// only store blocks we actually placed as light
const placedBlocks = new Map(); // playerId -> Array<{x,y,z}>

const isAnyLightBlock = (block) => {
  if (!block) return false;
  const id = block.typeId || "";
  return id === "minecraft:light_block" ||
         id.startsWith("minecraft:light_block_") ||
         id === "light_block" ||
         id.startsWith("light_block_");
};

const sameLoc = (a, b) => a && b && a.x === b.x && a.y === b.y && a.z === b.z;

system.runInterval(() => {
  for (const player of world.getAllPlayers()) {
    const eq = player.getComponent("equippable");
    if (!eq) continue;

    // choose the brightest valid equipped item (mainhand/head)
    const candidates = [
      eq.getEquipment(EquipmentSlot.Mainhand),
      eq.getEquipment(EquipmentSlot.Head),
    ].filter(s => s && dynamicLight.has(s.typeId))
     .filter(s => eq.getEquipment(dynamicLight.get(s.typeId).slot)?.typeId === s.typeId)
     .sort((a, b) => dynamicLight.get(b.typeId).amount - dynamicLight.get(a.typeId).amount);

    const best = candidates[0];
    const level = best ? dynamicLight.get(best.typeId).amount : undefined;

    const dim = player.dimension;
    const feet = dim.getBlock(player.location);
    const head = feet?.above?.();

    if (!feet || !head) continue;

    const prev = placedBlocks.get(player.id) || [];
    const keep = [];

    // 1) clear our previous light blocks we are not reusing
    for (const loc of prev) {
      const reuse = (level !== undefined) &&
                    (sameLoc(loc, feet.location) || sameLoc(loc, head.location));
      if (reuse) continue;

      const blk = dim.getBlock(loc);
      if (isAnyLightBlock(blk)) blk.setType("minecraft:air");
    }

    // 2) if we have a light item now, place/update only in air (or update existing light)
    if (level !== undefined) {
      // modern stateful light_block (block state is 'block_light_level')
      const perm = BlockPermutation.resolve("minecraft:light_block", { block_light_level: level }); // :contentReference[oaicite:1]{index=1}

      const tryPlace = (b) => {
        if (!b) return;
        if (isAnyLightBlock(b)) {
          // standardize/update to current level
          b.setPermutation(perm);
          keep.push(b.location);
        } else if (b.isAir) { // only empty air gets replaced (prevents clashing with buttons/frames) :contentReference[oaicite:2]{index=2}
          b.setPermutation(perm);
          keep.push(b.location);
        }
      };

      tryPlace(feet);
      tryPlace(head);
    }

    placedBlocks.set(player.id, keep);
  }
});

// extra safety: clear lights if a player leaves
world.afterEvents.playerLeave.subscribe((ev) => {
  const prev = placedBlocks.get(ev.playerId) || [];
  const overworld = world.getDimension("overworld");
  for (const loc of prev) {
    const blk = overworld.getBlock(loc);
    if (isAnyLightBlock(blk)) blk.setType("minecraft:air");
  }
  placedBlocks.delete(ev.playerId);
});