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

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

initEvent.blockComponentRegistry.registerCustomComponent('we:maple_leaves', {
    onRandomTick: e => {
      const block = e.block.below();

      if(block?.typeId !== 'minecraft:air') return;

      block.dimension.spawnParticle('we:autumn_leaves',{
        x: block.center().x,
        y: e.block.y - 0.2,
        z: block.center().z
      }); 
    }
  });


  initEvent.blockComponentRegistry.registerCustomComponent('we:leaves_place', {
    beforeOnPlayerPlace: e => {
      e.permutationToPlace = e.permutationToPlace.withState('we:persistent_bit', true);
    }
  });
  initEvent.blockComponentRegistry.registerCustomComponent('we:leaves_random_tick', {
    onRandomTick: e => {
      const validLogBlocks = ["minecraft:warped_stem", "minecraft:crimson_stem", "minecraft:cherry_log", "minecraft:mangrove_log", "minecraft:jungle_log", "we:palm_log", "we:baobab_log", "we:azalea_log", "we:banana_log", "we:willow_log", "we:pine_log", "we:maple_log" ];
      const loc = e.block.location;
      const radius = 5;

      function isWithinSphere(blockLoc, center, radius) {
        const dx = blockLoc.x - center.x;
        const dy = blockLoc.y - center.y;
        const dz = blockLoc.z - center.z;
        const distanceSquared = dx * dx + dy * dy + dz * dz;
        return distanceSquared <= radius * radius;
      }

      let foundLog = false;

      for (let xOffset = -radius; xOffset <= radius; xOffset++) {
        for (let yOffset = -radius; yOffset <= radius; yOffset++) {
          for (let zOffset = -radius; zOffset <= radius; zOffset++) {
            const blockLoc = {
              x: loc.x + xOffset,
              y: loc.y + yOffset,
              z: loc.z + zOffset,
            };

            if (isWithinSphere(blockLoc, loc, radius)) {
              const block = e.block.dimension.getBlock(getMaterial(blockLoc));
              const foundValidLog = validLogBlocks.find(logType => logType === block?.typeId);

              if (foundValidLog) {
                foundLog = true;

                break;
              }
              if (block?.hasTag('log')) {

                foundLog = true;
                break;
              }
            }
          }
        }
        if (foundLog) {
          break;
        }
      }

      if (!foundLog) {
        if (!e.block.permutation.getState('we:persistent_bit')) {
          e.block.dimension.runCommandAsync(`/setblock ${loc.x} ${loc.y} ${loc.z} air destroy`);
        }
      }

      function getMaterial(blockLoc) {
        return blockLoc;
      }
    }

  });

  initEvent.blockComponentRegistry.registerCustomComponent('we:leaves_opaque_tick', {
    onRandomTick(e) {
      const validLogBlocks = ["minecraft:warped_stem", "minecraft:crimson_stem", "minecraft:cherry_log", "minecraft:mangrove_log", "minecraft:jungle_log"]

      const {
        block
      } = e;
      const {
        x,
        y,
        z
      } = block.location;

      const adjacentBlocks = [
        block.above(),
        block.below(),
        block.north(),
        block.south(),
        block.east(),
        block.west()
      ];

      for (const adjacentBlock of adjacentBlocks) {
        if (!validLogBlocks.includes(adjacentBlock.typeId) && !adjacentBlock.hasTag('log') && !adjacentBlock.typeId.includes('leaves')) {
          const currentStates = block.permutation.getAllStates();

          const newStates = {
            ...currentStates,
            'we:opaque_bit': false
          };
          const newPermutation = BlockPermutation.resolve(block.typeId, newStates);
          block.setPermutation(newPermutation);
          return;
        }
      }

      const currentStates = block.permutation.getAllStates();

      const newStates = {
        ...currentStates,
        'we:opaque_bit': true
      };
      const newPermutation = BlockPermutation.resolve(block.typeId, newStates);
      block.setPermutation(newPermutation);

    }
  });
});