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

// -----------------------------------------------------------
// 1. КОНСТАНТЫ
// -----------------------------------------------------------

const HUGGY_WUGGY_ID = "mebesm:huggy_wuggy";
const HUGGY_WUGGY_VENT_ID = "mebesm:huggy_wuggy_vent";
const ANIMATION_START_NORMAL = "animation.huggy_wuggy.3block";
const WOUNDED_WUGGY_ID = "mebesm:huggy_wuggy_wounded";
const WOUNDED_KISSY_ID = "mebesm:kissy_missy_wounded";
const ANIMATION_START_WOUNDED = "animation.huggy_wuggy_wounded.3block";
const KISSY_MISSY_ID = "mebesm:kissy_missy";
const KISSY_MISSY_VENT_ID = "mebesm:kissy_missy_vent";
const KISSY_ANIMATION_START_NORMAL = "animation.huggy_wuggy.3block";
const KISSY_ANIMATION_START_WOUNDED = "animation.kissy_missy_wounded.3block";
const ANIMATION_STOP = "animation.huggy_wuggy.reset_anim";
const ANIMATION_OPTIONS_LOOP = { loop: true, blendOutTime: 0.1 };
const ANIMATION_OPTIONS_STOP = { duration: 0.1, blendOutTime: 0.1 };

const KISSY_POPPY_ID = "mebesm:kissy_missy_poppy";
const KISSY_POPPY_ANIMATION_START = "animation.kissy_missy_poppy.3block";

// -----------------------------------------------------------
// 2. ЛОГИКА ТРАНСФОРМАЦИИ МОБОВ
// -----------------------------------------------------------

function updateTransformationLogic() {
  const dimension = world.getDimension("overworld");

  // --- Huggy Wuggy Logic ---
  const huggyWuggies = dimension.getEntities({ type: HUGGY_WUGGY_ID });
  for (const huggy of huggyWuggies) {
    if (!huggy.isValid) continue;
    const { x, y, z } = huggy.location;
    const headBlock = dimension.getBlock({ x: Math.floor(x), y: Math.floor(y + 2), z: Math.floor(z) });
    const animationCheckBlock = dimension.getBlock({ x: Math.floor(x), y: Math.floor(y + 3), z: Math.floor(z) });
    let blockIdAtAnimCheck = animationCheckBlock?.isValid() ? animationCheckBlock.permutation.type.id : "minecraft:air";
    const isAnimationConditionMet = blockIdAtAnimCheck !== "minecraft:air";
    const isHeadBlocked = headBlock?.isValid() && headBlock.permutation.type.id !== "minecraft:air";
    
    try {
      if (isAnimationConditionMet) {
        huggy.playAnimation(ANIMATION_START_NORMAL, ANIMATION_OPTIONS_LOOP);
      } else {
        huggy.playAnimation(ANIMATION_STOP, ANIMATION_OPTIONS_STOP);
      }
    } catch (e) { }

    if (isHeadBlocked) {
      try {
        dimension.spawnEntity(HUGGY_WUGGY_VENT_ID, huggy.location);
        huggy.remove();
      } catch (e) { }
    }
  }

  // --- Wounded Huggy Logic ---
  const woundedWuggies = dimension.getEntities({ type: WOUNDED_WUGGY_ID });
  for (const woundedHuggy of woundedWuggies) {
    if (!woundedHuggy.isValid) continue;
    const { x, y, z } = woundedHuggy.location;
    const animationCheckBlock = dimension.getBlock({ x: Math.floor(x), y: Math.floor(y + 3), z: Math.floor(z) });
    let blockIdAtAnimCheck = animationCheckBlock?.isValid() ? animationCheckBlock.permutation.type.id : "minecraft:air";
    const isAnimationConditionMet = blockIdAtAnimCheck !== "minecraft:air";
    try {
      if (isAnimationConditionMet) {
        woundedHuggy.playAnimation(ANIMATION_START_WOUNDED, ANIMATION_OPTIONS_LOOP);
      } else {
        woundedHuggy.playAnimation(ANIMATION_STOP, ANIMATION_OPTIONS_STOP);
      }
    } catch (e) { }
  }

  // --- Huggy Vent Logic ---
  const huggyVents = dimension.getEntities({ type: HUGGY_WUGGY_VENT_ID });
  for (const vent of huggyVents) {
    if (!vent.isValid) continue;
    const { x, y, z } = vent.location;
    const blockY1 = dimension.getBlock({ x: Math.floor(x), y: Math.floor(y + 1), z: Math.floor(z) });
    const blockY2 = dimension.getBlock({ x: Math.floor(x), y: Math.floor(y + 2), z: Math.floor(z) });
    const isY1Air = blockY1?.isValid() && blockY1.permutation.type.id === "minecraft:air";
    const isY2Air = blockY2?.isValid() && blockY2.permutation.type.id === "minecraft:air";
    if (isY1Air && isY2Air) {
      system.runTimeout(() => {
        if (vent.isValid) {
          try {
            dimension.spawnEntity(HUGGY_WUGGY_ID, vent.location);
            vent.remove();
          } catch (e) { }
        }
      }, 2);
    }
  }

  // --- Kissy Missy Logic ---
  const kissyMissies = dimension.getEntities({ type: KISSY_MISSY_ID });
  for (const kissy of kissyMissies) {
    if (!kissy.isValid) continue;
    const { x, y, z } = kissy.location;
    const headBlock = dimension.getBlock({ x: Math.floor(x), y: Math.floor(y + 2), z: Math.floor(z) });
    const animationCheckBlock = dimension.getBlock({ x: Math.floor(x), y: Math.floor(y + 3), z: Math.floor(z) });
    let blockIdAtAnimCheck = animationCheckBlock?.isValid() ? animationCheckBlock.permutation.type.id : "minecraft:air";
    const isAnimationConditionMet = blockIdAtAnimCheck !== "minecraft:air";
    const isHeadBlocked = headBlock?.isValid() && headBlock.permutation.type.id !== "minecraft:air";
    try {
      if (isAnimationConditionMet) {
        kissy.playAnimation(KISSY_ANIMATION_START_NORMAL, ANIMATION_OPTIONS_LOOP);
      } else {
        kissy.playAnimation(ANIMATION_STOP, ANIMATION_OPTIONS_STOP);
      }
    } catch (e) { }

    if (isHeadBlocked) {
      try {
        dimension.spawnEntity(KISSY_MISSY_VENT_ID, kissy.location);
        kissy.remove();
      } catch (e) { }
    }
  }

  // --- Wounded Kissy Logic ---
  const woundedKissies = dimension.getEntities({ type: WOUNDED_KISSY_ID });
  for (const woundedKissy of woundedKissies) {
    if (!woundedKissy.isValid) continue;
    const { x, y, z } = woundedKissy.location;
    const animationCheckBlock = dimension.getBlock({ x: Math.floor(x), y: Math.floor(y + 3), z: Math.floor(z) });
    let blockIdAtAnimCheck = animationCheckBlock?.isValid() ? animationCheckBlock.permutation.type.id : "minecraft:air";
    const isAnimationConditionMet = blockIdAtAnimCheck !== "minecraft:air";
    try {
      if (isAnimationConditionMet) {
        woundedKissy.playAnimation(KISSY_ANIMATION_START_WOUNDED, ANIMATION_OPTIONS_LOOP);
      } else {
        woundedKissy.playAnimation(ANIMATION_STOP, ANIMATION_OPTIONS_STOP);
      }
    } catch (e) { }
  }

  // --- Kissy Poppy Logic ---
  const kissyPoppies = dimension.getEntities({ type: KISSY_POPPY_ID });
  for (const kissyPoppy of kissyPoppies) {
    if (!kissyPoppy.isValid) continue;
    const animationCheckBlock = dimension.getBlock({ x: Math.floor(kissyPoppy.location.x), y: Math.floor(kissyPoppy.location.y + 3), z: Math.floor(kissyPoppy.location.z) });
    let isBlocked = animationCheckBlock?.isValid() && animationCheckBlock.permutation.type.id !== "minecraft:air";

    try {
      if (isBlocked) {
        kissyPoppy.playAnimation(KISSY_POPPY_ANIMATION_START, ANIMATION_OPTIONS_LOOP);
      } else {
        kissyPoppy.playAnimation(ANIMATION_STOP, ANIMATION_OPTIONS_STOP);
      }
    } catch (e) { }
  }

  // --- Kissy Vent Logic ---
  const kissyVents = dimension.getEntities({ type: KISSY_MISSY_VENT_ID });
  for (const vent of kissyVents) {
    if (!vent.isValid) continue;
    const { x, y, z } = vent.location;
    const isY1Air = dimension.getBlock({ x: Math.floor(x), y: Math.floor(y + 1), z: Math.floor(z) })?.permutation.type.id === "minecraft:air";
    const isY2Air = dimension.getBlock({ x: Math.floor(x), y: Math.floor(y + 2), z: Math.floor(z) })?.permutation.type.id === "minecraft:air";
    if (isY1Air && isY2Air) {
      system.runTimeout(() => {
        if (vent.isValid) {
          try {
            dimension.spawnEntity(KISSY_MISSY_ID, vent.location);
            vent.remove();
          } catch (e) { }
        }
      }, 2);
    }
  }
}

// -----------------------------------------------------------
// 3. ИНИЦИАЛИЗАЦИЯ КОМПОНЕНТОВ БЛОКОВ
// -----------------------------------------------------------

world.beforeEvents.worldInitialize.subscribe(initEvent => {
  const registry = initEvent.blockComponentRegistry;

  registry.registerCustomComponent('besmc_poppy_box:trigger', {
    onPlayerDestroy: e => { e.dimension.runCommand("function clearPopyBox"); },
    onPlace: e => { e.dimension.runCommand("function a"); },
    onPlayerInteract: e => { e.player.runCommand("function VzaemPopyBox"); },
  });

  registry.registerCustomComponent('besmc_horizontal_bar:trigger', {
    onPlayerInteract: e => { e.player.runCommand("function flylever1"); },
  });
});

// -----------------------------------------------------------
// 4. ЗАПУСК
// -----------------------------------------------------------

world.beforeEvents.worldInitialize.subscribe(() => {
  system.runInterval(updateTransformationLogic, 5);
  console.warn("✅ [MEBESM MAIN] Логіка мобів та блоків активована.");
});