import * as SERVER from '@minecraft/server';

//abrrir cerrar
SERVER.world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent('xaierg:abrir', {
           onPlayerInteract: e => {
        if (!e.player) return;
          const abierto = e.block.permutation.withState("xaierg:abierto", true);
          e.block.setPermutation(abierto);
          const effectLocation = e.block.center();
          e.dimension.playSound("polvo.amb", effectLocation);
        
      }
         
  });
  
  }); 
  SERVER.world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent('xaierg:cerrar', {
     onPlayerInteract: e => {
        if (!e.player) return;
          const abierto = e.block.permutation.withState("xaierg:abierto", false);
          e.block.setPermutation(abierto);
          const effectLocation = e.block.center();
          e.dimension.playSound("polvo.amb", effectLocation);
        
      }
  });
  
  }); 



const IGNITE_ITEMS = [
  "minecraft:flint_and_steel",
  "minecraft:fire_charge",
  // agrega más si quieres
];

const burningBlocks = new Map();

SERVER.world.beforeEvents.worldInitialize.subscribe(initEvent => {
  initEvent.blockComponentRegistry.registerCustomComponent('xaierg:explode', {
    onTick: e => {
      const key = `${e.block.location.x},${e.block.location.y},${e.block.location.z}`;
      let burn = burningBlocks.get(key);

      // Si el bloque está quemándose, inicia el contador si no existe
      if (e.block.isBurning && !burn) {
        burningBlocks.set(key, { timer: 1, block: e.block });
        burn = burningBlocks.get(key);
      }

      // Si está en proceso de quemarse
      if (burn) {
        burn.timer--;  
      
            
if (burn.timer >= 5) {
         e.dimension.runCommand(
              `execute positioned ${e.block.center().x} ${e.block.center().y} ${e.block.center().z} run playsound gas_1 @a[r=16]`,
            ); 
        }
        // Partícula de humo cada tick
         e.dimension.spawnParticle("minecraft:fog_white", {
          x: e.block.center().x,
          y: e.block.center().y + 0.5,
          z: e.block.center().z
        });
                e.dimension.spawnParticle("minecraft:fog_white", {
          x: e.block.center().x,
          y: e.block.center().y + 0,
          z: e.block.center().z
        }); e.dimension.spawnParticle("xaierg:fog_white", {
          x: e.block.center().x,
          y: e.block.center().y + 0,
          z: e.block.center().z
        }); 

        // Cuando termina el contador
         if (burn.timer <= 1) {
          e.dimension.spawnEntity("xaierg:explode_p", e.block.center());
                       e.dimension.runCommand(
              `execute positioned ${e.block.center().x} ${e.block.center().y} ${e.block.center().z} run damage @e[r=8,family=!player,family=!inanimate] 50`,
            );  e.dimension.runCommand(
               `execute positioned ${e.block.center().x} ${e.block.center().y} ${e.block.center().z} run damage @e[r=8,family=player] 30`
            );
        }
        
               if (burn.timer <= 0) {
              
  e.block.setType('minecraft:air');
  // Daño a entidades que no sean player ni inanimate usando comando
 
  burningBlocks.delete(key);
}
else {
          burningBlocks.set(key, burn);
        }
      }
    },

    onPlayerInteract: e => {
      if (!e.player) return;
      const equippable = e.player.getComponent("minecraft:equippable");
      if (!equippable) return;
      const mainhand = equippable.getEquipmentSlot("Mainhand");
      if (!mainhand.hasItem()) return;
      const heldItem = mainhand.typeId;

      if (IGNITE_ITEMS.includes(heldItem)) {
        let growth = e.block.permutation.getState("xaierg:growth");
        
        if (growth >= 1) return;
        
        growth += 1;
        e.block.setPermutation(
            e.block.permutation.withState("xaierg:growth", growth)
        );
        const key = `${e.block.location.x},${e.block.location.y},${e.block.location.z}`;
        if (!burningBlocks.has(key)) {
          burningBlocks.set(key, { timer: 6, block: e.block });
        }
      }
    }
  });
}); // cada segundo


// Helper for registering block components
function registerCustomComponent(id, handlers) {
  SERVER.world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent(id, handlers);
  });
}
// Helper to run a command for every nearby player within maxDistance
function forEachNearbyPlayer(block, maxDistance, commandCallback) {
  block.dimension.getEntities({ location: block.location, maxDistance })
    .forEach(entity => {
      if (entity.typeId === 'minecraft:player') {
        block.dimension.getPlayers().forEach(player => {
          commandCallback(player, block);
        });
      }
    });
}
//tramp_1X
registerCustomComponent('xaierg:tramp_1X', {
  onStepOn: e => {
    e.dimension.runCommand(
      `structure load celda_1 ${e.block.location.x-1} ${e.block.location.y} ${e.block.location.z-1}`
    );
  }
});
//tramp_1X
registerCustomComponent('xaierg:tramp_2X', {
  onStepOn: e => {
    if (e.entity ) {
      // Solo ejecuta si es un jugador
      forEachNearbyPlayer(e.block, 16, (player, block) => {
        player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run structure load celda_2 ~-1 ~ ~-1`);
      });
    }
  }
});
//tramp_1X
registerCustomComponent('xaierg:tramp_3X', {
  onStepOn: e => {
    if (e.entity ) {
      // Solo ejecuta si es un jugador
      forEachNearbyPlayer(e.block, 16, (player, block) => {
        player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run structure load celda_3 ~-1 ~ ~-1`);
      });
    }
  }
});
//damage
SERVER.world.beforeEvents.worldInitialize.subscribe(initEvent => {
  initEvent.blockComponentRegistry.registerCustomComponent('xaierg:damage', {
    onStepOn: e => {
      // Activa el daño
      e.block.setPermutation(e.block.permutation.withState("xaierg:damage", true));
    },
    onTick: e => {
      // Solo aplica daño si el state está activo
      if (e.block.permutation.getState("xaierg:damage")) {
        const entities = e.dimension.getEntities({
          location: e.block.center(),
          maxDistance: 0.7
        });
        entities.forEach(entity => {
          entity.applyDamage(2);
          if (entity.addEffect) {
            entity.addEffect("slowness", 20, { amplifier: 1, showParticles: false });
          }
        });
      }
    },
    onStepOff: e => {
      // Desactiva el daño
      e.block.setPermutation(e.block.permutation.withState("xaierg:damage", false));
    }
  });
});
  //radio_emisora//
  SERVER.world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent('xaierg:radio_emisora', {
      onPlayerInteract: e => {if (!e.player) return;

        const equippable = e.player.getComponent("minecraft:equippable");
        if (!equippable) return;

        const mainhand = equippable.getEquipmentSlot("Mainhand");
        if (!mainhand.hasItem() || mainhand.typeId !== "minecraft:paper")
            return;

        const abierto = e.block.permutation.withState("xaierg:encendido", true)
        e.block.setPermutation(
            abierto
        );
         e.player.runCommand(`particle xaierg:polvo ${e.block.location.x} ${e.block.location.y+1} ${e.block.location.z}`);
         
         },
         onTick: e => playEmmison(e.block), 
         
  });
  
  }); 
  function playEmmison(block) {
    const musicPlay=[
      'playsound radio.transmision.all @a[r=8]  ~ ~ ~'
    ];
    const randommusicPlay = musicPlay[Math.floor(Math.random() * musicPlay.length)];     
block.dimension.getEntities({ location: block.location, maxDistance: 16 })
    .forEach(entity => {
        if (entity.typeId == 'minecraft:player') {
            block.dimension.getPlayers().forEach(player => {    
              player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run ${randommusicPlay}`);   
  
            });
              
        } 
    });  
  }
  //radio_encendido//
  SERVER.world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent('xaierg:radio_encendido', {
           onPlayerInteract: e => {
        if (!e.player) return;
      
       
          // Lógica normal
          const abierto = e.block.permutation.withState("xaierg:encendido", true);
          e.block.setPermutation(abierto);
          const effectLocation = e.block.center();
          e.dimension.playSound("polvo.amb", effectLocation);
        
      },
         onTick: e => playMusic(e.block), 
         
  });
  
  }); 
  function playMusic(block) {
    
    const musicPlay=[
      'playsound radio.more_music.all @a[r=16]  ~ ~ ~',
      'playsound radio.music.all @a[r=16]  ~ ~ ~',
      'playsound radio.music.all @a[r=16]  ~ ~ ~',
      'playsound radio.transmision.all @a[r=8]  ~ ~ ~'
    ];
    const randommusicPlay = musicPlay[Math.floor(Math.random() * musicPlay.length)];     
block.dimension.getEntities({ location: block.location, maxDistance: 16 })
    .forEach(entity => {
        if (entity.typeId == 'minecraft:player') {
            block.dimension.getPlayers().forEach(player => {    
              player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run ${randommusicPlay}`);   
  
            });
              
        } 
    });  
  }
  //radio_apagado//
  SERVER.world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent('xaierg:radio_apagado', {
      onPlayerInteract: e => {
        if (!e.player) return;
// Detecta si el jugador está agachado
        if (e.player.isSneaking) {
          // Detiene el sonido actual y reproduce otro
          // Ejemplo: para detener, reproduce el mismo sonido con volumen 0 o usa otro sonido de "apagado"
          e.player.runCommand(`stopsound @s radio.music.all`);
          e.player.runCommand(`stopsound @s radio.more_music.all`);
          e.player.runCommand(`stopsound @s radio.transmision.all`);
        SERVER.system.runTimeout(() => {
  playMusic(e.block);
}, 40);
       } 
        else{
          const equippable = e.player.getComponent("minecraft:equippable");
        if (!equippable) return;

        e.player.runCommand(`stopsound @s radio.music.all`);
          e.player.runCommand(`stopsound @s radio.more_music.all`);
          e.player.runCommand(`stopsound @s radio.transmision.all`);

        const abierto = e.block.permutation.withState("xaierg:encendido", false)
        e.block.setPermutation(
            abierto
        );}
  e.player.runCommand(`particle xaierg:polvo ${e.block.location.x} ${e.block.location.y+1} ${e.block.location.z}`);
  const effectLocation = e.block.center();
  e.dimension.playSound("polvo.amb", effectLocation);
         }
  });
  
  }); 

  
  //event_hunterX//
  SERVER.world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent('xaierg:event_hunterX', {
      onTick: e => event_hunterX(e.block)
  });
  
  });
  function event_hunterX(block) {   
    block.dimension.getEntities({ location: block.location, maxDistance: 128 })
    .forEach(entity => {
        if (entity.typeId == 'minecraft:player') {
            block.dimension.getPlayers().forEach(player => {   
              player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function event_hunter`);    
          
            });
              
        } 
    });  
        
     }
  //event_hunter2X//
  SERVER.world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent('xaierg:event_hunter2X', {
      onTick: e => event_hunter2X(e.block)
  });
  
  });
  function event_hunter2X(block) {   
    block.dimension.getEntities({ location: block.location, maxDistance: 128 })
    .forEach(entity => {
        if (entity.typeId == 'minecraft:player') {
            block.dimension.getPlayers().forEach(player => {   
              player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function event_hunter2`);    
            
            });
              
        } 
    });  
        
     }
  //event_hunter3X//
  SERVER.world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent('xaierg:event_hunter3X', {
      onTick: e => event_hunter3X(e.block)
  });
  
  });
  function event_hunter3X(block) {   
    block.dimension.getEntities({ location: block.location, maxDistance: 128 })
    .forEach(entity => {
        if (entity.typeId == 'minecraft:player') {
            block.dimension.getPlayers().forEach(player => {   
              player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function event_hunter3`);    
          
            });
              
        } 
    });  
        
     }
  //event_hunter4X//
  SERVER.world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent('xaierg:event_hunter4X', {
      onTick: e => event_hunter4X(e.block)
  });
  
  });
  function event_hunter4X(block) {   
    block.dimension.getEntities({ location: block.location, maxDistance: 128 })
    .forEach(entity => {
        if (entity.typeId == 'minecraft:player') {
            block.dimension.getPlayers().forEach(player => {   
              player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function event_hunter4`);    
              
            });
              
        } 
    });  
        
     }
     
     //ola_cordycepsX//
     SERVER.world.beforeEvents.worldInitialize.subscribe(initEvent => {
       initEvent.blockComponentRegistry.registerCustomComponent('xaierg:ola_cordycepsX', {
           onTick: e => ola_cordycepsX(e.block),
       });
     });
     
     function ola_cordycepsX(block) {
       const genstructuresB2 = [
         'function horda_c1',
         'function horda_c2',
         'function horda_c3',
         'function horda_c4'
       ];
       const horda = genstructuresB2[Math.floor(Math.random() * genstructuresB2.length)];
       
       block.dimension.getEntities({ location: block.location, maxDistance: 32 })
       .forEach(entity => {
           if (entity.typeId == 'minecraft:player') {
               block.dimension.getPlayers().forEach(player => {
                 player.runCommand(Math.random() < 0.5 ? `execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run ${horda}`: `execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run setblock ~~~ xaierg:cordy`);
                 player.runCommand(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run title @a[r=32] title §4CORDYCEPS HORDE`);
                 
               });
                 
           } 
       });
     }
  SERVER.system.runInterval(()=>
  {
  
      var entities = SERVER.world.getDimension("overworld").getEntities({excludeTypes: ["minecraft:item"]})
      var dimension = SERVER.world.getDimension("overworld")
      
      for (let i = 0; i < entities.length; i++)
      {
          if (entities[i].isValid && entities[i].typeId != "minecraft:item")
          {
              let block = dimension.getBlock({x: entities[i].location.x, y: entities[i].location.y, z: entities[i].location.z})
              if ((block != undefined))
              {
                  if (block.typeId == "xaierg:barbedwire" || block.typeId == "xaierg:reinforcedbarb")
                  {
                      if (SERVER.system.currentTick % 10 == 0 || !entities[i].hasTag("in_barbedwire"))
                      {
                          if (entities[i].applyDamage(2))
                          {
                              dimension.playSound('dig.chain', entities[i].location)
                          }
                          
                      }
                      if (entities[i].getComponent("minecraft:movement") != undefined)
                      {
                          entities[i].getComponent("minecraft:movement").setCurrentValue(entities[i].getComponent("minecraft:movement").defaultValue / 3)
                      }
                      entities[i].addTag("in_barbedwire")
                      
                      
                  }
                  else {
                      if (entities[i].getComponent("minecraft:movement") != undefined && entities[i].hasTag("in_barbedwire"))
                      {
                          entities[i].getComponent("minecraft:movement").resetToDefaultValue()
                          entities[i].removeTag("in_barbedwire")
                      }
                      
                  }
              }
          }
          
      }
  },
  1)

