// priority: 993

const tierRequirement = 4;
const layers = [
  "ftbevolution:pyramid_top",
  "ftbevolution:pyra_mid_upper",
  "ftbevolution:pyra_mid_lower",
  "ftbevolution:pyramid_base",
];
const catalystItem = "minecraft:nether_star";
const rewardItem = "ftbevolution:creative_ascension"; // Define the specific reward item here
const gamestageRequired = "completed_pyramid";


BlockEvents.rightClicked("minecraft:beacon", function (event) {
  const { player, hand, item, level, block, server } = event;

  if (hand != "MAIN_HAND") event.cancel()

  // Check if the player meets requirements
  if (!player.stages.has(gamestageRequired)) return player.tell(Component.translate("kubejs.pyramid.gamestage"))
  if (item.id !== catalystItem) return;
  if (block.getEntityData().Levels < tierRequirement) {
    return player.tell(Component.translate("kubejs.pyramid.below_tier", [`${tierRequirement.toString()}`, `${block.getEntityData().Levels.toString()}`]));
  }

  // Validate each layer of the pyramid
  for (let i = 0; i < layers.length; i++) {
    let layerSize = 1 + i; // Increase pyramid size by layer
    let yOffset = -i - 1; // Calculate the vertical offset for each layer

    for (let x = -layerSize; x <= layerSize; x++) {
      for (let z = -layerSize; z <= layerSize; z++) {
        let currentBlock = level.getBlock(
          block.x + x,
          block.y + yOffset,
          block.z + z
        );

        if (currentBlock.id !== layers[i]) {
          return player.tell(
            Component.translate('kubejs.pyramid.wrong_layer', 
              [
                `${(i+1)}`, 
                Text.green(Component.translate(Item.of(layers[i]).getDescriptionId())), 
                Text.red(Component.translate(currentBlock.item.getDescriptionId()))
              ]
            )
          )
        }
      }
    }
  }


  player.sendSystemMessage({ translate: 'kubejs.pyramid.success', color: "green" }, true);
  let soundCommand = `execute as ${player.name.string} run playsound ars_nouveau:ea_channel ambient ${player.name.string} ~ ~ ~ 0.5 2 0.5`
  server.runCommandSilent(soundCommand)

  let iterations = 10

  // Fireworks for first time completion
  if(!player.stages.has('received_pyramid_reward')) {
    iterations = 40
    player.stages.add('received_pyramid_reward');
    server.scheduleInTicks(170, (_) => {
      server.runCommandSilent(`execute in ${player.level.dimension} positioned ${block.x} ${block.y + 1} ${block.z} run summon firework_rocket ~ ~1 ~ {LifeTime:20,FireworksItem:{id:firework_rocket,components:{fireworks:{flight_duration:1.5,explosions:[{shape:creeper,has_twinkle:1b,has_trail:1b,colors:[I;11546150,8439583]}]}}}}`)
      })
    server.scheduleInTicks(180, (_) => {
      server.runCommandSilent(`execute in ${player.level.dimension} positioned ${block.x+3} ${block.y-1} ${block.z+3} run summon firework_rocket ~ ~1 ~ {LifeTime:15,FireworksItem:{id:firework_rocket,components:{fireworks:{flight_duration:1.5,explosions:[{shape:star,has_twinkle:1b,has_trail:1b,colors:[I;11546150,8439583],fade_colors:[I;16351261,16701501]}]}}}}`)
      server.runCommandSilent(`execute in ${player.level.dimension} positioned ${block.x+3} ${block.y-1} ${block.z-3} run summon firework_rocket ~ ~1 ~ {LifeTime:15,FireworksItem:{id:firework_rocket,components:{fireworks:{flight_duration:1.5,explosions:[{shape:star,has_twinkle:1b,has_trail:1b,colors:[I;11546150,8439583],fade_colors:[I;16351261,16701501]}]}}}}`)
      server.runCommandSilent(`execute in ${player.level.dimension} positioned ${block.x-3} ${block.y-1} ${block.z+3} run summon firework_rocket ~ ~1 ~ {LifeTime:15,FireworksItem:{id:firework_rocket,components:{fireworks:{flight_duration:1.5,explosions:[{shape:star,has_twinkle:1b,has_trail:1b,colors:[I;11546150,8439583],fade_colors:[I;16351261,16701501]}]}}}}`)
      server.runCommandSilent(`execute in ${player.level.dimension} positioned ${block.x-3} ${block.y-1} ${block.z-3} run summon firework_rocket ~ ~1 ~ {LifeTime:15,FireworksItem:{id:firework_rocket,components:{fireworks:{flight_duration:1.5,explosions:[{shape:star,has_twinkle:1b,has_trail:1b,colors:[I;11546150,8439583],fade_colors:[I;16351261,16701501]}]}}}}`)
    })
  }

  // Particle effects for the pyramid
  for (let i = 0; i < iterations; i++) {
    let red = Math.random() * 0.5 + 0.5;
    let green = Math.random() * 0.5 + 0.5;
    let blue = Math.random() * 0.5 + 0.5;
    server.scheduleInTicks((i * 5), (_) => server.runCommandSilent(`execute at ${player.username} run particle minecraft:entity_effect{color:[${red},${green},${blue},1.0]} ${block.x + 0.5} ${block.y + 1} ${block.z + 0.5} 0 0 0 0.5 100 force`))
  }

  // Spawn the reward item
  server.scheduleInTicks(iterations*5, (_) => {
    if(item.count < 1) {
      return player.sendSystemMessage({ translate: 'kubejs.pyramid.no_catalyst', color: "red" }, true);
    }
    server.runCommandSilent(`execute at ${player.username} run summon item ${block.x} ${block.y + 1} ${block.z} {Item:{id:"${rewardItem}",Count:1b},NoGravity:1b, Glowing:1b, Motion:[0d,0.02d]}`)
    if (!player.isCreative()) item.count--; // Consume catalyst if player is not in Creative mode
  })

  event.cancel(); // Prevent beacon GUI from opening
});

