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

const ESPELEOTEMAS = [
  "pa:espeleotema_de_pizarra_profunda",
  "pa:pinaculo_de_hielo",
  "pa:espeleotema_de_piedra_de_end",
  "pa:espeleotema_de_herktom"
];

world.beforeEvents.worldInitialize.subscribe(initEvent => {

  // COMPONENTE DE FORMA / ALTURA
  initEvent.blockComponentRegistry.registerCustomComponent(
    "pa:espeleotema",
    {
      onTick(e) {
        const { block } = e;
        if (!ESPELEOTEMAS.includes(block.typeId)) return;

        const permutation = block.permutation;

        const above = block.above()?.typeId;
        const above2 = block.above(2)?.typeId;
        const below = block.below()?.typeId;

        const sameAbove = ESPELEOTEMAS.includes(above);
        const sameAbove2 = ESPELEOTEMAS.includes(above2);
        const sameBelow = ESPELEOTEMAS.includes(below);

        // Punta inferior
        if (!sameAbove) {
          block.setPermutation(
            permutation.withState("pa:height", 0)
          );
          return;
        }

        // Columna larga
        if (sameAbove && sameAbove2 && !sameBelow) {
          block.setPermutation(
            permutation.withState("pa:height", 3)
          );
          return;
        }

        // Columna corta
        if (sameAbove && !sameAbove2) {
          block.setPermutation(
            permutation.withState("pa:height", 1)
          );
          return;
        }

        // Centro
        if (sameAbove && sameAbove2 && sameBelow) {
          block.setPermutation(
            permutation.withState("pa:height", 2)
          );
          return;
        }
      }
    }
  );

  // COMPONENTE DE DAÑO POR CAÍDA
  initEvent.blockComponentRegistry.registerCustomComponent(
    "pa:espeleotema_caida",
    {
      onEntityFallOn(e) {
        if (!ESPELEOTEMAS.includes(e.block.typeId)) return;

        const damage = Math.ceil((e.fallDistance * 2) - 2);
        if (damage <= 0) return;

        e.entity.applyDamage(damage, {
          cause: "stalagmite"
        });
      }
    }
  );

});