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

const decayTickCounter = new Map(); // Switch to Map

function getBlockKey(block) {
  const loc = block.location;
  return `${block.dimension.id}:${loc.x},${loc.y},${loc.z}`;
}

world.beforeEvents.worldInitialize.subscribe((data) => {
  // === Light Block Component ===
  const lightTagRegex = /^pb_gat_trinket_light_.+/;

  data.blockComponentRegistry.registerCustomComponent("pb_gat:light_block", {
    onTick: ({ block }) => {
      const centeredLocation = {
        x: block.location.x + 0.5,
        y: block.location.y - 0.2,
        z: block.location.z + 0.5,
      };

      const playersNearby = block.dimension.getPlayers({
        location: centeredLocation,
        maxDistance: 1.5,
      });

      const hasTaggedPlayer = playersNearby.some((player) =>
        player.getTags().some((tag) => lightTagRegex.test(tag))
      );

      if (!hasTaggedPlayer) {
        block.setType("air");
      }
    },
  });

  // === Bridge Builder Component ===
  data.blockComponentRegistry.registerCustomComponent("pb_gat:bridge_block", {
    onTick: ({ block }) => {
      const decayState = block.permutation.getState("pb_gat:decay");

      if (decayState === 3) {
        block.setType("air");
      } else if (typeof decayState === "number") {
        const newDecay = decayState + 1; // Progress toward 3
        const updatedPermutation = block.permutation.withState(
          "pb_gat:decay",
          newDecay
        );
        block.setPermutation(updatedPermutation);
      }
    },
  });

  // === Ember Bridge Builder Component ===
  data.blockComponentRegistry.registerCustomComponent(
    "pb_gat:ember_bridge_block",
    {
      onTick: ({ block }) => {
        // === DAMAGE: Every tick ===
        const { x, y, z } = block.location;
        const dimension = block.dimension;

        const entities = dimension.getEntities({
          location: { x: x + 0.5, y: y + 1, z: z + 0.5 },
          maxDistance: 0.8,
        });

        for (const entity of entities) {
          if (
            entity.isValid() &&
            !entity.getComponent("minecraft:fire_immune") &&
            !entity.getEffect("fire_resistance")
          ) {
            try {
              entity.applyDamage(1);
            } catch (e) {
            }
          }
        }

        // === DECAY: Every 60 ticks ===
        const key = getBlockKey(block);
        let counter = decayTickCounter.get(key) ?? 0;

        if (counter >= 60) {
          const decayState = block.permutation.getState("pb_gat:decay");

          if (decayState === 3) {
            block.setType("air");
          } else if (typeof decayState === "number") {
            const newDecay = decayState + 1;
            const updatedPermutation = block.permutation.withState(
              "pb_gat:decay",
              newDecay
            );
            block.setPermutation(updatedPermutation);
          }

          decayTickCounter.set(key, 0);
        } else {
          decayTickCounter.set(key, counter + 1);
        }
      },
    }
  );

  // === Ember Bridge Life Builder Component ===
  data.blockComponentRegistry.registerCustomComponent(
    "pb_gat:ember_bridge_block_life",
    {
      onTick: ({ block }) => {
        // === DAMAGE: Every tick ===
        const { x, y, z } = block.location;
        const dimension = block.dimension;

        const entities = dimension.getEntities({
          location: { x: x + 0.5, y: y + 1, z: z + 0.5 },
          maxDistance: 0.8,
        });

        for (const entity of entities) {
          if (
            entity.isValid() &&
            !entity.getComponent("minecraft:fire_immune") &&
            !entity.getEffect("fire_resistance")
          ) {
            try {
              entity.applyDamage(1);
            } catch (e) {
            }
          }
        }

        // === DECAY: Every 60 ticks ===
        const key = getBlockKey(block);
        let counter = decayTickCounter.get(key) ?? 0;

        if (counter >= 120) {
          const decayState = block.permutation.getState("pb_gat:decay");

          if (decayState === 3) {
            block.setType("air");
          } else if (typeof decayState === "number") {
            const newDecay = decayState + 1;
            const updatedPermutation = block.permutation.withState(
              "pb_gat:decay",
              newDecay
            );
            block.setPermutation(updatedPermutation);
          }

          decayTickCounter.set(key, 0);
        } else {
          decayTickCounter.set(key, counter + 1);
        }
      },
    }
  );

  // === Bridge Builder Component ===
  data.blockComponentRegistry.registerCustomComponent("pb_gat:ember_block", {
    onTick: ({ block }) => {
      const { x, y, z } = block.location;
      const dimension = block.dimension;

      // Get all entities standing directly on the block
      const entities = dimension.getEntities({
        location: { x: x + 0.5, y: y + 1, z: z + 0.5 },
        maxDistance: 0.8,
      });

      for (const entity of entities) {
        if (
          entity.isValid() &&
          !entity.getComponent("minecraft:fire_immune") &&
          !entity.getEffect("fire_resistance")
        ) {
          try {
            entity.applyDamage(1);
          } catch (e) {
          }
        }
      }
    },
  });
});
