import {
  BlockPermutation,
  EquipmentSlot,
  ItemStack,
  system,
  world,
  TicksPerSecond,
} from "@minecraft/server";
import { updateWallsAround } from "./wall";
import "./slab/destroy";
import "./slab/interact";
import { armorEffect } from "./armorEffect";
import { handleEntity, removeEntity } from "./jumpscare";
const nonSpread = [
  "minecraft:air",
  "minecraft:water",
  "minecraft:lava",
  "minecraft:grass",
  "lore_hrc:dark_matter_vine",
  "lore_hrc:dark_matter_vine_over",
  "lore_hrc:lumen_blossom",
  "lore_hrc:dark_matter_liquid",
  "lore_hrc:dark_matter_liquid_flow",
  "lore_hrc:dark_matter_undervine",
  "minecraft:short_grass",
  "minecraft:tall_grass",
  "minecraft:short_dry_grass",
  "minecraft:tall_dry_grass",
  "minecraft:allium",
  "minecraft:azure_bluet",
  "minecraft:blue_orchid",
  "minecraft:cornflower",
  "minecraft:dandelion",
  "minecraft:lilac",
  "minecraft:lily_of_the_valley",
  "minecraft:orange_tulip",
  "minecraft:oxeye_daisy",
  "minecraft:peony",
  "minecraft:pink_tulip",
  "minecraft:poppy",
  "minecraft:red_tulip",
  "minecraft:rose_bush",
  "minecraft:sunflower",
  "minecraft:white_tulip",
  "minecraft:wither_rose",
];

const nonAllowed = [
  "minecraft:air",
  "minecraft:coal_ore",
  "minecraft:deepslate_coal_ore",
  "minecraft:deepslate_diamond_ore",
  "minecraft:deepslate_emerald_ore",
  "minecraft:deepslate_gold_ore",
  "minecraft:deepslate_iron_ore",
  "minecraft:deepslate_redstone_ore",
  "minecraft:diamond_ore",
  "minecraft:emerald_ore",
  "minecraft:gold_ore",
  "minecraft:iron_ore",
  "minecraft:lapis_ore",
  "minecraft:lit_deepslate_redstone_ore",
  "minecraft:lit_redstone_ore",
  "minecraft:obsidian",
  "minecraft:raw_gold_block",
  "minecraft:raw_iron_block",
  "minecraft:redstone_ore",
  "minecraft:bedrock",
  "minecraft:redstone_wire",
  "minecraft:piston",
  "minecraft:sticky_piston",
  "minecraft:repeater",
  "minecraft:comparator",
  "minecraft:unpowered_comparator",
  "minecraft:powered_comparator",
  "minecraft:unpowered_repeater",
  "minecraft:powered_repeater",
  "minecraft:redstone_block",
  "minecraft:redstone_torch",
  "minecraft:redstone_lamp",
  "minecraft:lit_redstone_lamp",
];

const effectedList = [
  "minecraft:bogged",
  "minecraft:husk",
  "minecraft:creeper",
  "minecraft:skeleton",
  "minecraft:zombie",
  "minecraft:spider",
  "minecraft:stray",
  "minecraft:zoglin",
  "minecraft:zombie_pigman",
  "minecraft:blaze",
];
const spreadBlock = [
  "lore_hrc:dark_matter_block",
  "lore_hrc:dark_matter_mud",
  "lore_hrc:dark_matter_liquid",
];

const darkMatter = [
  "lore_hrc:dark_matter_block",
  "lore_hrc:dark_matter_mud",
  "lore_hrc:dark_matter_liquid",
  "lore_hrc:dark_matter_liquid_flow",
  "lore_hrc:dark_matter_vine",
  "lore_hrc:dark_matter_vine_over",
  "lore_hrc:dark_matter_undervine",
];

const mudCapable = [
  "minecraft:grass_block",
  "minecraft:grass_path",
  "minecraft:dirt",
  "minecraft:coarse_dirt",
  "minecraft:dirt_with_roots",
  "minecraft:mud",
  "minecraft:mud_bricks",
  "minecraft:muddy_mangrove_roots",
  "minecraft:packed_mud",
  "minecraft:sand",
  "minecraft:sandstone",
  "minecraft:chiseled_sandstone",
  "minecraft:cut_sandstone",
  "minecraft:smooth_sandstone",
  "minecraft:red_sand",
  "minecraft:red_sandstone",
  "minecraft:chiseled_red_sandstone",
  "minecraft:cut_red_sandstone",
  "minecraft:smooth_red_sandstone",
  "minecraft:clay",
  "minecraft:hardened_clay",
];

function seconds() {
  const players = world.getAllPlayers();

  for (const player of players) {
    const effected = player.getDynamicProperty("lore_hrc:effected");
    const block = player.dimension.getBlock(player.location);
    const lumenSet = player.getDynamicProperty("lore_hrc:lumen_set");
    for (let i = 0; i < player.getComponent("inventory").container.size; i++) {
      if (!player.getComponent("inventory").container.getItem(i)) continue
      if (player.getComponent("inventory").container.getItem(i).typeId === "lore_hrc:guidebook") {
      player.getComponent("inventory").container.setItem(i, undefined);
      player.runCommand("structure load \"lore_hrc:guide_book\" ~~~");
    }
    }
    if (player.getGameMode() === "creative" || lumenSet) return;
    if (darkMatter.includes(block?.typeId)) {
      if (!effected) {
        player.setDynamicProperty("lore_hrc:effected", 0);
      }
      player.setDynamicProperty("lore_hrc:effected", effected + 1);
      player.setDynamicProperty("lore_hrc:effected_cd", 0);
    }
    const effected_cd = player.getDynamicProperty("lore_hrc:effected_cd");
    const jumpscare_rate = Math.random();
    if (effected_cd >= 20) {
      player.setDynamicProperty("lore_hrc:effected", 0);
      player.setDynamicProperty("lore_hrc:effected_cd", 0);
    }
    if (effected > 0) {
      if (!effected_cd) {
        player.setDynamicProperty("lore_hrc:effected_cd", 0);
      }
      player.setDynamicProperty("lore_hrc:effected_cd", effected_cd + 1);
    }

    const jumpscare = player.dimension.getEntities({
      location: player.location,
      families: ["dark_matter"],
      maxDistance: 25,
    });
    const jumpscare_cd = player.getDynamicProperty(
      "lore_hrc:jumpscare_cooldown"
    );
    player.setDynamicProperty("lore_hrc:jumpscare_died", false);
    if (jumpscare.length != 0 && !jumpscare_cd && jumpscare_rate < 0.025) {
      let duration = 0;
      player.addEffect("blindness", 20 * 7, {
        showParticles: false,
        amplifier: 3,
      });
      const jumpscareEvent = system.runInterval(() => {
        duration += 1;
        handleEntity(player);
        if (
          duration == 20 * 6 ||
          player.getDynamicProperty("lore_hrc:jumpscare_died")
        ) {
          removeEntity(player);
          return system.clearRun(jumpscareEvent);
        }
      });
      const soundrand = Math.floor(Math.random() * (3 + 1)) + 1;
      player.setDynamicProperty("lore_hrc:jumpscare_cooldown", true);
      player.runCommand(`playsound mob.jumpscare${soundrand}`);
      system.runTimeout(() => {
        player.setDynamicProperty("lore_hrc:jumpscare_cooldown", false);
      }, 20 * 5 * 60);
    }
  }
}

system.runInterval(() => {
  const players = world.getAllPlayers();
  for (const player of players) {
    const block = player.dimension.getBlock(player.location);
    armorEffect(player);
    if (player.getGameMode() === "creative") return;
    if (
      darkMatter.includes(block?.typeId) ||
      darkMatter.includes(block.below(1)?.typeId)
    ) {
      if (block.typeId.includes("dark_matter_liquid")) {
        if (block.above(1).typeId.includes("dark_matter_liquid")) {
          player.runCommand(`fog @s push lore_hrc:dark_liquid_fog liquidFog`);
          player.addEffect("darkness", 20 * 3, {
            showParticles: false,
            amplifier: 3,
          });
        }
        player.addEffect("slow_falling", 20 * 3, {
          showParticles: false,
          amplifier: 3,
        });
      } else {
        player.runCommand(`fog @s remove liquidFog`);
      }
      player.addEffect("wither", 20 * 3, {
        showParticles: false,
        amplifier: 1,
      });
    } else {
      player.runCommand(`fog @s remove liquidFog`);
    }
    const entities = player.dimension.getEntities({
      maxDistance: 5,
      minDistance: 0,
      location: player.location,
      families: ["dark_matter"],
    });
    if (entities) {
      player.setDynamicProperty("lore_hrc:jumpscared", true);
    }
    if (player.getDynamicProperty("lore_hrc:jumpscared")) return;
  }
});

system.runInterval(() => {
  seconds();
}, TicksPerSecond);

world.afterEvents.playerSpawn.subscribe(({ initialSpawn, player }) => {
  player.setDynamicProperty("lore_hrc:jumpscare_cooldown", false);
  player.runCommand("event entity @e[family=jumpscare] lore_hrc:despawn");
  player.setDynamicProperty("lore_hrc:effected_cd", 0);
  player.setDynamicProperty("lore_hrc:effected", 0);
  if (!initialSpawn || player.hasTag("member")) return;
  player.runCommand("structure load \"lore_hrc:guide_book\" ~~~");
  player.addTag("member");
});

function decrementStack(source, itemStack) {
  system.run(() => {
    source
      .getComponent("minecraft:inventory")
      .container.setItem(
        source.selectedSlotIndex,
        itemStack.amount > 1
          ? new ItemStack(itemStack.typeId, itemStack.amount - 1)
          : undefined
      );
  });
}

world.afterEvents.projectileHitBlock.subscribe((event) => {
  const { projectile, dimension, location } = event;
  const block = event.getBlockHit().block;
  const blockLoc = block.location;
  if (projectile.typeId === "lore_hrc:lumen_potion_projectile") {
    dimension.spawnParticle("lore_hrc:lumen_potion_splash", location);
    createCirclePotion(blockLoc, 4, 16, dimension, "air");
    createCirclePotion(blockLoc, 3, 14, dimension, "air");
    createCirclePotion(blockLoc, 2, 12, dimension, "air");
    createCirclePotion(blockLoc, 1, 10, dimension, "air");
    const entities = dimension.getEntities({
      maxDistance: 5,
      minDistance: 0,
      location: location,
    });
    for (const entity of entities) {
      if (entity.typeId.includes("dark_matter")) {
        entity.applyDamage(40);
      } else if (entity.typeId === "minecraft:player") {
        entity.setDynamicProperty("lore_hrc:effected", 0);
      }
    }
  } else if (projectile.typeId === "lore_hrc:dark_matter_potion_projectile") {
    dimension.spawnParticle("lore_hrc:dark_matter_potion_splash", location);
    createCirclePotion(blockLoc, 4, 16, dimension, "dark");
    createCirclePotion(blockLoc, 3, 14, dimension, "dark");
    createCirclePotion(blockLoc, 2, 12, dimension, "dark");
    createCirclePotion(blockLoc, 1, 10, dimension, "dark");
  }
});

world.afterEvents.entityHitEntity.subscribe((event) => {
  const { hitEntity, damagingEntity } = event;
  if (!hitEntity || !hitEntity.isValid()) return;
  if (!damagingEntity || !damagingEntity.isValid()) return;

  const lumenSet = hitEntity.getDynamicProperty("lore_hrc:lumen_set");
  const lumenSetDmg = damagingEntity.getDynamicProperty("lore_hrc:lumen_set");
  const darkSet = hitEntity.getDynamicProperty("lore_hrc:dark_set");
  let type = "";
  const equip =
    damagingEntity.typeId === "minecraft:player"
      ? damagingEntity.getComponent("minecraft:equippable")
      : false;

  const equipment = equip ? equip?.getEquipment(EquipmentSlot.Mainhand) : false;
  if (equipment === undefined) return;

  if (
    damagingEntity.typeId.includes("dark_matter") ||
    damagingEntity.typeId.includes("effected") ||
    equipment.typeId === "lore_hrc:dark_matter_battleaxe"
  ) {
    if (hitEntity.typeId === "minecraft:player" && !lumenSet) {
      const effected = hitEntity.getDynamicProperty("lore_hrc:effected");
      effected
        ? hitEntity.setDynamicProperty("lore_hrc:effected", effected + 1)
        : hitEntity.setDynamicProperty("lore_hrc:effected", 0);
      hitEntity.setDynamicProperty("lore_hrc:effected_cd", 0);
    } else if (effectedList.includes(hitEntity.typeId)) {
      type = hitEntity.typeId.split(":");
      hitEntity.setDynamicProperty("lore_hrc:effected", true);
      system.runTimeout(() => {
        if (!hitEntity.isValid()) return;
        hitEntity.dimension.spawnEntity(
          `lore_hrc:effected_${type[1]}`,
          hitEntity.location
        );
        hitEntity.dimension.playSound(
          "mob.dark_matter_form1.angry",
          hitEntity.location
        );
        hitEntity.remove();
      }, 20 * 5);
    }
    hitEntity.addEffect("slowness", 20 * 3, {
      showParticles: false,
      amplifier: 3,
    });
    hitEntity.addEffect("wither", 20 * 3, {
      showParticles: false,
      amplifier: 1,
    });
  } else if (hitEntity.typeId === "minecraft:player" && darkSet) {
    if (damagingEntity.typeId === "minecraft:player" && !lumenSetDmg) {
      const effected = damagingEntity.getDynamicProperty("lore_hrc:effected");
      effected
        ? damagingEntity.setDynamicProperty("lore_hrc:effected", effected + 1)
        : damagingEntity.setDynamicProperty("lore_hrc:effected", 0);
      damagingEntity.setDynamicProperty("lore_hrc:effected_cd", 0);
    } else if (effectedList.includes(damagingEntity.typeId)) {
      type = damagingEntity.typeId.split(":");
      damagingEntity.setDynamicProperty("lore_hrc:effected", true);
      system.runTimeout(() => {
        if (!damagingEntity.isValid()) return;
        damagingEntity.dimension.spawnEntity(
          `lore_hrc:effected_${type[1]}`,
          damagingEntity.location
        );
        damagingEntity.dimension.playSound(
          "mob.dark_matter_form1.angry",
          damagingEntity.location
        );
        damagingEntity.remove();
      }, 20 * 5);
    }
    damagingEntity.addEffect("slowness", 20 * 3, {
      showParticles: false,
      amplifier: 3,
    });
    damagingEntity.addEffect("wither", 20 * 3, {
      showParticles: false,
      amplifier: 1,
    });
  } else if (
    equipment.typeId === "lore_hrc:lumen_longsword" &&
    hitEntity.typeId.includes("dark_matter")
  ) {
    hitEntity.applyDamage(5);
  }
});

world.afterEvents.itemStopUse.subscribe((event) => {
  const { itemStack, source } = event;
  if (!itemStack) return;
  if (itemStack?.typeId === "lore_hrc:lumen_potion") {
    const projectile = source.dimension.spawnEntity(
      "lore_hrc:lumen_potion_projectile",
      source.getHeadLocation()
    );
    projectile
      .getComponent("minecraft:projectile")
      .shoot(source.getViewDirection());
    decrementStack(source, itemStack);
  }
  if (itemStack?.typeId === "lore_hrc:dark_matter_potion") {
    const projectile = source.dimension.spawnEntity(
      "lore_hrc:dark_matter_potion_projectile",
      source.getHeadLocation()
    );
    projectile
      .getComponent("minecraft:projectile")
      .shoot(source.getViewDirection());
    decrementStack(source, itemStack);
  }
});

function height(yAxis, amount, location, particles, radius) {
  for (let i = 0; i < amount; i++) {
    const angle = (i / amount) * 2 * Math.PI;
    const offsetX = Math.cos(angle) * radius;
    const offsetZ = Math.sin(angle) * radius;
    const particlePos = {
      x: location.x + offsetX,
      y: location.y - yAxis,
      z: location.z + offsetZ,
    };
    particles.push(particlePos);
  }
}

function createCircleMob(location, radius, amount, source) {
  const particles = [];
  height(-1, amount, location, particles, radius);
  height(0, amount, location, particles, radius);
  height(1, amount, location, particles, radius);

  particles.forEach((pos) => {
    const block = source?.dimension.getBlock(pos);
    if (!block) return;
    if (
      block?.typeId != "minecraft:air" &&
      !nonAllowed.includes(block.typeId)
    ) {
      block?.setPermutation(
        BlockPermutation.resolve("lore_hrc:dark_matter_block")
      );
    }
  });
}
function createCirclePotion(location, radius, amount, dimension, blocks) {
  const particles = [];
  let replace = "";
  height(-1, amount, location, particles, radius);
  height(0, amount, location, particles, radius);
  height(1, amount, location, particles, radius);
  if (blocks === "dark") {
    replace = "lore_hrc:dark_matter_block";
    particles.forEach((pos) => {
      const block = dimension.getBlock(pos);
      if (!block) return;
      if (
        block?.typeId != "minecraft:air" &&
        !nonAllowed.includes(block.typeId)
      ) {
        block?.setPermutation(BlockPermutation.resolve(replace));
      }
    });
  } else if (blocks === "air") {
    replace = "minecraft:air";
    particles.forEach((pos) => {
      const block = dimension.getBlock(pos);
      if (!block) return;
      if (
        block?.typeId != "minecraft:air" &&
        darkMatter.includes(block.typeId)
      ) {
        block?.setPermutation(BlockPermutation.resolve(replace));
      }
    });
  }
}

system.afterEvents.scriptEventReceive.subscribe((event) => {
  const { sourceEntity, id } = event;
  if (!sourceEntity && !sourceEntity.isValid()) return;
  if (id === "lore_hrc:dead_trigger") {
    const blockLoc = {
      x: sourceEntity?.location.x,
      y: sourceEntity?.location.y,
      z: sourceEntity?.location.z,
    };
    const health = sourceEntity.getComponent("minecraft:health");
    sourceEntity.runCommand(
      "/particle minecraft:huge_explosion_lab_misc_emitter ~~~"
    );
    sourceEntity.runCommand(
      "/playsound mob.dark_matter_form2.death @p[r=5] ~~~"
    );
    createCircleMob(sourceEntity.location, 4, 16, sourceEntity);
    createCircleMob(sourceEntity.location, 3, 14, sourceEntity);
    createCircleMob(sourceEntity.location, 2, 12, sourceEntity);
    createCircleMob(sourceEntity.location, 1, 10, sourceEntity);
    const block = sourceEntity?.dimension.getBlock(sourceEntity.location);
    block?.setPermutation(
      BlockPermutation.resolve("lore_hrc:dark_matter_block")
    );
    // for (let x = blockLoc.x - 2; x <= blockLoc.x + 2; x++) {
    //   for (let y = blockLoc.y - 1; y <= blockLoc.y + 1; y++) {
    //     for (let z = blockLoc.z - 2; z <= blockLoc.z + 2; z++) {
    //       const block = sourceEntity?.dimension.getBlock({ x, y, z });
    //       if (
    //         block?.typeId != "minecraft:air" &&
    //         !nonAllowed.includes(block.typeId)
    //       ) {
    //         block?.setPermutation(
    //           BlockPermutation.resolve("lore_hrc:dark_matter_block")
    //         );
    //       }
    //     }
    //   }
    // }
    const entities = sourceEntity.dimension.getEntities({
      location: sourceEntity.location,
      maxDistance: 5,
      families: ["player"],
    });
    entities.forEach((element) => {
      const effected = element.getDynamicProperty("lore_hrc:effected");
      if (!effected) {
        element.setDynamicProperty("lore_hrc:effected", 0);
      }

      element.setDynamicProperty("lore_hrc:effected", effected + 1);
    });
    if (health.currentValue == 1) {
      sourceEntity.remove();
      return;
    }
  } else if (id === "lore_hrc:jumpscare_reset") {
    sourceEntity.setDynamicProperty("lore_hrc:jumpscare_cooldown", false);
  }
});

world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
  const { block, player, itemStack, isFirstEvent, blockFace } = event;
  if (
    !isFirstEvent ||
    !itemStack ||
    itemStack.typeId === "lore_hrc:lumen_potion"
  )
    return;
  const itemhand = player.getComponent("minecraft:equippable");
  const getItemHand = itemhand.getEquipment(EquipmentSlot.Mainhand);
  // world.sendMessage(`${blockFace}`)
  if (
    itemStack?.typeId === "minecraft:bucket" &&
    block.typeId === "lore_hrc:dark_matter_liquid"
  ) {
    system.run(() => {
      if (getItemHand.amount == 1) {
        itemhand.setEquipment(
          EquipmentSlot.Mainhand,
          new ItemStack("lore_hrc:dark_matter_bucket")
        );
      } else {
        itemhand.setEquipment(
          EquipmentSlot.Mainhand,
          new ItemStack("minecraft:bucket", getItemHand.amount - 1)
        );
        player.runCommand(
          `loot spawn ${player.location.x} ${player.location.y} ${player.location.z} loot "lore/hrc/blocks/dark_matter_bucket"`
        );
      }
      block.setPermutation(BlockPermutation.resolve("minecraft:air"));
    });
  } else if (itemStack.typeId === "lore_hrc:dark_matter_bucket") {
    system.run(() => {
      switch (blockFace) {
        case "North":
          block
            .north()
            .setPermutation(
              BlockPermutation.resolve("lore_hrc:dark_matter_liquid")
            );
          break;
        case "East":
          block
            .east()
            .setPermutation(
              BlockPermutation.resolve("lore_hrc:dark_matter_liquid")
            );
          break;
        case "South":
          block
            .south()
            .setPermutation(
              BlockPermutation.resolve("lore_hrc:dark_matter_liquid")
            );
          break;
        case "West":
          block
            .west()
            .setPermutation(
              BlockPermutation.resolve("lore_hrc:dark_matter_liquid")
            );
          break;
        case "Up":
          block
            .above()
            .setPermutation(
              BlockPermutation.resolve("lore_hrc:dark_matter_liquid")
            );
          break;
        case "Down":
          block
            .below()
            .setPermutation(
              BlockPermutation.resolve("lore_hrc:dark_matter_liquid")
            );
          break;
      }
      itemhand.setEquipment(
        EquipmentSlot.Mainhand,
        new ItemStack("minecraft:bucket")
      );
    });
  }
});

const effectStep = {
  onStepOn(event) {
    const { block, dimension, entity } = event;
    if (!entity) return;
    if (effectedList.includes(entity.typeId)) {
      const type = entity.typeId.split(":");
      system.runTimeout(() => {
        if (!entity.isValid()) return;
        entity.dimension.spawnEntity(
          `lore_hrc:effected_${type[1]}`,
          entity.location
        );
        entity.dimension.playSound(
          "mob.dark_matter_form1.angry",
          entity.location
        );
        entity.remove();
      }, 20 * 5);
    }
    if (
      entity.typeId.includes("effected") ||
      entity.typeId.includes("dark_matter")
    )
      return;
    entity.addEffect("slowness", 20 * 3, {
      showParticles: false,
      amplifier: 3,
    });
    entity.addEffect("wither", 20 * 3, {
      showParticles: false,
      amplifier: 1,
    });
  },
};

const darkLiquidSpread = {
  onRandomTick(event) {
    const spread = event.block.below(1);
    if (
      !spread ||
      !spread.north(1) ||
      !spread.east(1) ||
      !spread.south(1) ||
      !spread.west(1)
    )
      return;
    if (
      spread.typeId === "minecraft:water" ||
      spread.typeId === "minecraft:lava"
    ) {
      spread.setPermutation(
        BlockPermutation.resolve("lore_hrc:dark_matter_liquid_flow")
      );
      spread
        .north(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_liquid")
        );
      spread
        .south(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_liquid")
        );
      spread
        .west(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_liquid")
        );
      spread
        .east(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_liquid")
        );
    }
  },
};

const darkMatterDrip = {
  onRandomTick(event) {
    const liquid = event.block;
    if (liquid.below(1).typeId === "minecraft:air") {
      liquid
        .below(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_liquid_flow")
        );
    }
  },
};

const changeFlow = {
  onTick(event) {
    const liquid = event.block;
    if (liquid.below(1).typeId === "lore_hrc:dark_matter_liquid") {
      liquid
        .below(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_liquid_flow")
        );
    } else if (
      liquid.above(1).typeId === "minecraft:air" &&
      liquid.typeId === "lore_hrc:dark_matter_liquid_flow"
    ) {
      liquid.setPermutation(
        BlockPermutation.resolve("lore_hrc:dark_matter_liquid")
      );
    }
  },
};
// world.sendMessage(`${spread.north(1).above(1).typeId}`)

const darkUndervineSpread = {
  onRandomTick(event) {
    const spread = event.block;
    if (
      spread.below(1).typeId === "minecraft:air" &&
      spread.below(2).typeId === "minecraft:air" &&
      !spread.typeId.includes("liquid")
    ) {
      spread
        .below(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_undervine")
        );
    }
  },
};

const effectedSink = {
  onRandomTick(event) {
    const entities = event.dimension.getEntities({
      location: event.block.location,
      families: ["mob"],
      maxDistance: 1,
    });
    entities.forEach((element) => {
      if (effectedList.includes(element.typeId)) {
        const type = element.typeId.split(":");
        system.runTimeout(() => {
          if (!element.isValid()) return;
          element.dimension.spawnEntity(
            `lore_hrc:effected_${type[1]}`,
            element.location
          );
          element.dimension.playSound(
            "mob.dark_matter_form1.angry",
            element.location
          );
          element.remove();
        }, 20 * 5);
      }
      if (
        element.typeId.includes("effected") ||
        element.typeId.includes("dark_matter")
      )
        return;
      element.addEffect("slowness", 20 * 3, {
        showParticles: false,
        amplifier: 3,
      });
      element.addEffect("wither", 20 * 3, {
        showParticles: false,
        amplifier: 1,
      });
    });
  },
};

const darkVineSpread = {
  onRandomTick(event) {
    const spread = event.block;
    if (
      !spread.north(1) ||
      !spread.south(1) ||
      !spread.east(1) ||
      !spread.west(1)
    )
      return;
    if (
      !nonSpread.includes(spread.north(1).typeId) &&
      spread.north(1).above(1).typeId === "minecraft:air"
    ) {
      spread
        .north(1)
        .above(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_vine_over", {
            "minecraft:cardinal_direction": "south",
          })
        );
    } else if (
      !nonSpread.includes(spread.south(1).typeId) &&
      spread.south(1).above(1).typeId === "minecraft:air"
    ) {
      spread
        .south(1)
        .above(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_vine_over", {
            "minecraft:cardinal_direction": "north",
          })
        );
    } else if (
      !nonSpread.includes(spread.east(1).typeId) &&
      spread.east(1).above(1).typeId === "minecraft:air"
    ) {
      spread
        .east(1)
        .above(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_vine_over", {
            "minecraft:cardinal_direction": "west",
          })
        );
    } else if (
      !nonSpread.includes(spread.west(1).typeId) &&
      spread.west(1).above(1).typeId === "minecraft:air"
    ) {
      spread
        .west(1)
        .above(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_vine_over", {
            "minecraft:cardinal_direction": "east",
          })
        );
    }
  },
};

const darkVineSpreadDown = {
  onRandomTick(event) {
    const spread = event.block.below(1);
    if (
      !spread.north(1) ||
      !spread.south(1) ||
      !spread.east(1) ||
      !spread.west(1)
    )
      return;
    if (
      !nonSpread.includes(spread.north(1).typeId) &&
      spread.north(1).above(1).typeId === "minecraft:air"
    ) {
      spread
        .north(1)
        .above(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_vine_over", {
            "minecraft:cardinal_direction": "south",
          })
        );
    } else if (
      !nonSpread.includes(spread.south(1).typeId) &&
      spread.south(1).above(1).typeId === "minecraft:air"
    ) {
      spread
        .south(1)
        .above(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_vine_over", {
            "minecraft:cardinal_direction": "north",
          })
        );
    } else if (
      !nonSpread.includes(spread.east(1).typeId) &&
      spread.east(1).above(1).typeId === "minecraft:air"
    ) {
      spread
        .east(1)
        .above(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_vine_over", {
            "minecraft:cardinal_direction": "west",
          })
        );
    } else if (
      !nonSpread.includes(spread.west(1).typeId) &&
      spread.west(1).above(1).typeId === "minecraft:air"
    ) {
      spread
        .west(1)
        .above(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_vine_over", {
            "minecraft:cardinal_direction": "east",
          })
        );
    }
  },
};

const darkVineSpreadUp = {
  onRandomTick(event) {
    const spread = event.block.above(1);
    if (
      !spread.north(1) ||
      !spread.south(1) ||
      !spread.east(1) ||
      !spread.west(1)
    )
      return;
    if (
      !nonSpread.includes(spread.north(1).typeId) &&
      spread.north(1).above(1).typeId === "minecraft:air"
    ) {
      spread
        .north(1)
        .above(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_vine_over", {
            "minecraft:cardinal_direction": "south",
          })
        );
    } else if (
      !nonSpread.includes(spread.south(1).typeId) &&
      spread.south(1).above(1).typeId === "minecraft:air"
    ) {
      spread
        .south(1)
        .above(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_vine_over", {
            "minecraft:cardinal_direction": "north",
          })
        );
    } else if (
      !nonSpread.includes(spread.east(1).typeId) &&
      spread.east(1).above(1).typeId === "minecraft:air"
    ) {
      spread
        .east(1)
        .above(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_vine_over", {
            "minecraft:cardinal_direction": "west",
          })
        );
    } else if (
      !nonSpread.includes(spread.west(1).typeId) &&
      spread.west(1).above(1).typeId === "minecraft:air"
    ) {
      spread
        .west(1)
        .above(1)
        .setPermutation(
          BlockPermutation.resolve("lore_hrc:dark_matter_vine_over", {
            "minecraft:cardinal_direction": "east",
          })
        );
    }
  },
};

const darkVineReplace = {
  onRandomTick(event) {
    const darkBlock = event.block;
    if (darkBlock.above(1).typeId === "lore_hrc:dark_matter_vine_over") {
      darkBlock
        .above(1)
        .setPermutation(BlockPermutation.resolve("lore_hrc:dark_matter_vine"));
    }
  },
};

// const lumenBright = {
//     onTick(event) {
//         console.warn("halo");
//         system.run(()=>{
//             event.dimension.runCommand("fill ~-10~-2~-10 ~10~2~10 minecraft:air replace lore_hrc:dark_matter_block")
//             event.dimension.runCommand("fill ~-10~-2~-10 ~10~2~10 minecraft:air replace lore_hrc:dark_matter_vine")
//             event.dimension.runCommand("msg @a halo")
//             event.dimension.runCommand("fill ~-10~-2~-10 ~10~2~10 minecraft:air replace lore_hrc:dark_matter_mud")
//         })
//     }
// }

const darkMatterSpread = {
  onRandomTick(event) {
    const spread = event.block;
    if (!spreadBlock.includes(spread.below(1).typeId)) {
      if (mudCapable.includes(spread.below(1).typeId)) {
        spread
          .below(1)
          .setPermutation(BlockPermutation.resolve("lore_hrc:dark_matter_mud"));
      } else {
        spread
          .below(1)
          .setPermutation(
            BlockPermutation.resolve("lore_hrc:dark_matter_block")
          );
      }
    }
  },
};

world.afterEvents.entityDie.subscribe(({ deadEntity }) => {
  // if (
  //   deadEntity.typeId === "minecraft:bogged" &&
  //   deadEntity.getDynamicProperty("lore_hrc:effected")
  // ) {
  //   deadEntity.dimension.spawnEntity(
  //     "lore_hrc:effected_bogged",
  //     deadEntity.location
  //   );
  //   deadEntity.dimension.playSound(
  //     "mob.dark_matter_form1.angry",
  //     deadEntity.location
  //   );
  // } else if (
  //   deadEntity.typeId === "minecraft:creeper" &&
  //   deadEntity.getDynamicProperty("lore_hrc:effected")
  // ) {
  //   deadEntity.dimension.spawnEntity(
  //     "lore_hrc:effected_creeper",
  //     deadEntity.location
  //   );
  //   deadEntity.dimension.playSound(
  //     "mob.dark_matter_form1.angry",
  //     deadEntity.location
  //   );
  // } else if (
  //   deadEntity.typeId === "minecraft:husk" &&
  //   deadEntity.getDynamicProperty("lore_hrc:effected")
  // ) {
  //   deadEntity.dimension.spawnEntity(
  //     "lore_hrc:effected_husk",
  //     deadEntity.location
  //   );
  //   deadEntity.dimension.playSound(
  //     "mob.dark_matter_form1.angry",
  //     deadEntity.location
  //   );
  // } else if (
  //   deadEntity.typeId === "minecraft:skeleton" &&
  //   deadEntity.getDynamicProperty("lore_hrc:effected")
  // ) {
  //   deadEntity.dimension.spawnEntity(
  //     "lore_hrc:effected_skeleton",
  //     deadEntity.location
  //   );
  //   deadEntity.dimension.playSound(
  //     "mob.dark_matter_form1.angry",
  //     deadEntity.location
  //   );
  // } else if (
  //   deadEntity.typeId === "minecraft:spider" &&
  //   deadEntity.getDynamicProperty("lore_hrc:effected")
  // ) {
  //   deadEntity.dimension.spawnEntity(
  //     "lore_hrc:effected_spider",
  //     deadEntity.location
  //   );
  //   deadEntity.dimension.playSound(
  //     "mob.dark_matter_form1.angry",
  //     deadEntity.location
  //   );
  // } else if (
  //   deadEntity.typeId === "minecraft:stray" &&
  //   deadEntity.getDynamicProperty("lore_hrc:effected")
  // ) {
  //   deadEntity.dimension.spawnEntity(
  //     "lore_hrc:effected_stray",
  //     deadEntity.location
  //   );
  //   deadEntity.dimension.playSound(
  //     "mob.dark_matter_form1.angry",
  //     deadEntity.location
  //   );
  // } else if (
  //   deadEntity.typeId === "minecraft:zoglin" &&
  //   deadEntity.getDynamicProperty("lore_hrc:effected")
  // ) {
  //   deadEntity.dimension.spawnEntity(
  //     "lore_hrc:effected_zoglin",
  //     deadEntity.location
  //   );
  //   deadEntity.dimension.playSound(
  //     "mob.dark_matter_form1.angry",
  //     deadEntity.location
  //   );
  // } else if (
  //   deadEntity.typeId === "minecraft:zombie" &&
  //   deadEntity.getDynamicProperty("lore_hrc:effected")
  // ) {
  //   deadEntity.dimension.spawnEntity(
  //     "lore_hrc:effected_zombie",
  //     deadEntity.location
  //   );
  //   deadEntity.dimension.playSound(
  //     "mob.dark_matter_form1.angry",
  //     deadEntity.location
  //   );
  // } else if (
  //   deadEntity.typeId === "minecraft:zombie_pigman" &&
  //   deadEntity.getDynamicProperty("lore_hrc:effected")
  // ) {
  //   deadEntity.dimension.spawnEntity(
  //     "lore_hrc:effected_zombie_piglin",
  //     deadEntity.location
  //   );
  //   deadEntity.dimension.playSound(
  //     "mob.dark_matter_form1.angry",
  //     deadEntity.location
  //   );
  // }
  if (deadEntity.typeId === "minecraft:player") {
    deadEntity.setDynamicProperty("lore_hrc:jumpscare_died", true);
  }
});

world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
  // LIQUID

  blockComponentRegistry.registerCustomComponent(
    "lore_hrc:dark_matter_drip",
    darkMatterDrip
  );

  blockComponentRegistry.registerCustomComponent(
    "lore_hrc:dark_liquid_spread",
    darkLiquidSpread
  );

  blockComponentRegistry.registerCustomComponent(
    "lore_hrc:change_flow",
    changeFlow
  );

  // VINE

  blockComponentRegistry.registerCustomComponent(
    "lore_hrc:dark_matter_spread",
    darkMatterSpread
  );

  // MUD, LIQUID, BLOCK

  blockComponentRegistry.registerCustomComponent(
    "lore_hrc:dark_vine_spread",
    darkVineSpread
  );

  blockComponentRegistry.registerCustomComponent(
    "lore_hrc:effected_sink",
    effectedSink
  );

  blockComponentRegistry.registerCustomComponent(
    "lore_hrc:effect_step",
    effectStep
  );

  blockComponentRegistry.registerCustomComponent(
    "lore_hrc:dark_vine_spread_down",
    darkVineSpreadDown
  );

  blockComponentRegistry.registerCustomComponent(
    "lore_hrc:dark_vine_spread_up",
    darkVineSpreadUp
  );

  blockComponentRegistry.registerCustomComponent(
    "lore_hrc:dark_undervine_spread",
    darkUndervineSpread
  );

  blockComponentRegistry.registerCustomComponent(
    "lore_hrc:dark_vine_replace",
    darkVineReplace
  );

  // LUMEN

  // blockComponentRegistry.registerCustomComponent(
  //     "lore_hrc:lumen_bright",
  //     lumenBright
  // );
});

for (const eventName of [
  "playerBreakBlock",
  "playerPlaceBlock",
  "playerInteractWithBlock",
]) {
  world.afterEvents[eventName].subscribe(({ block }) => {
    updateWallsAround(block);
  });
}

// world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
//     blockComponentRegistry.registerCustomComponent(
//         "lore_hrc:dark_matter_spread",
//         darkMatterSpread
//     );
// });
