// priority: 0

ServerEvents.loaded(event => {
  if (event.server.persistentData.gameRules) return
  event.server.gameRules.set("doTraderSpawning", false)
  event.server.persistentData.gameRules = true
})

// === BLOCK EVENTS === //

// Nether Bedrock
BlockEvents.broken(event => {
  if (event.level.isClientSide()) return;

  let curios = event.player.nbt.ForgeCaps['curios:inventory']

  if (event.level.dimension == "minecraft:the_nether" && event.player.y < 10) {
    if (!curios.toString().contains("submerged:nether_bedrock_breaker")) {
      event.player.displayClientMessage(Text.of("You need a Nether Bedrock Breaker Curio to break this!"), true)
      event.cancel()
    }
  }
})

// Ender Eyes
BlockEvents.rightClicked("minecraft:end_portal_frame", event => {
  let curios = event.player.nbt.ForgeCaps['curios:inventory']

  if (!curios.toString().contains('submerged:ender_eye_curio')) {
    event.player.displayClientMessage(Text.of("You need an Ender Eye Curio to activate this!"), true)
    event.cancel()
  }
})

// Grass Seed
BlockEvents.rightClicked("minecraft:dirt", event => {
  if (event.item.id === "submerged:grass_seed") {
    event.block.set('minecraft:grass_block')
    event.server.runCommandSilent(`particle dust 0 0.65 0 1 ${event.block.x} ${event.block.y + 1.2} ${event.block.z} 0.25 0.2 0.25 1 100 force`)
    event.item.count--
    event.success()
  }
})

// Set loot table neptune's chest
BlockEvents.placed("aquaculture:neptunes_bounty", event => {
  event.block.mergeEntityData({ LootTable: "aquaculture:box/neptunes_bounty" });
})


// === ITEM EVENTS === //

// Nether roof item
ItemEvents.rightClicked("submerged:nether_roof", event => {
  if (event.level.dimension == "minecraft:the_nether") {
    event.player.teleportTo(event.server.getLevel("minecraft:the_nether"), event.player.x, 258, event.player.z, [], event.player.yaw, event.player.pitch)
  }
})

// Colored Caves roof item
ItemEvents.rightClicked("submerged:colored_caves_roof", event => {
  if (event.level.dimension == "caveopolis:colored_caves") {
    event.player.teleportTo(event.server.getLevel("caveopolis:colored_caves"), event.player.x, 130, event.player.z, [], event.player.yaw, event.player.pitch)
  }
})

// Apple of ascent going up in dimensions
ItemEvents.foodEaten("submerged:apple_of_ascent", event => {

  let xPos = Math.floor(event.player.x);
  let zPos = Math.floor(event.player.z);

  // Nether to Overworld
  if (event.level.dimension == "minecraft:the_nether") {
    event.player.teleportTo(event.server.getLevel("minecraft:overworld"), event.player.x, -62, event.player.z, [], event.player.yaw, event.player.pitch)

    for (let xOffset = -1; xOffset <= 1; xOffset++) {
      for (let zOffset = -1; zOffset <= 1; zOffset++) {
        let xCoord = xPos + xOffset;
        let zCoord = zPos + zOffset;

        event.server.getLevel("minecraft:overworld").getBlock(xCoord, -64, zCoord).set('minecraft:bedrock');
        event.server.getLevel("minecraft:overworld").getBlock(xCoord, -63, zCoord).set('minecraft:air');
        event.server.getLevel("minecraft:overworld").getBlock(xCoord, -62, zCoord).set('minecraft:air');
        event.server.getLevel("minecraft:overworld").getBlock(xCoord, -61, zCoord).set('minecraft:air');
      }
    }
    event.player.displayClientMessage(Text.of("Clearing area (for your safety)"), true);
  }

  // Colored Caves to Nether
  if (event.level.dimension == "caveopolis:colored_caves") {
    event.player.teleportTo(event.server.getLevel("minecraft:the_nether"), event.player.x, 1, event.player.z, [], event.player.yaw, event.player.pitch)

    for (let xOffset = -1; xOffset <= 1; xOffset++) {
      for (let zOffset = -1; zOffset <= 1; zOffset++) {
        let xCoord = xPos + xOffset;
        let zCoord = zPos + zOffset;

        event.server.getLevel("minecraft:the_nether").getBlock(xCoord, 0, zCoord).set('minecraft:bedrock');
        event.server.getLevel("minecraft:the_nether").getBlock(xCoord, 1, zCoord).set('minecraft:air');
        event.server.getLevel("minecraft:the_nether").getBlock(xCoord, 2, zCoord).set('minecraft:air');
        event.server.getLevel("minecraft:the_nether").getBlock(xCoord, 3, zCoord).set('minecraft:air');
      }
    }
    event.player.displayClientMessage(Text.of("Clearing area (for your safety)"), true);
  }
})

// Strainers Upgrade Uncraft
ItemEvents.rightClicked(event => {
  if (!event.player.crouching) return;

  const giveUpgrades = (prefix) => {
    event.player.give(`strainers:${prefix}_mesh_upgrade`)
    event.player.give(`strainers:${prefix}_input_upgrade`)
    event.player.give(`strainers:${prefix}_output_upgrade`)
    event.player.give(`strainers:${prefix}_duration_upgrade`)
    event.item.count--
  }

  if (event.item.id === 'strainers:improved_everything_upgrade') giveUpgrades('improved');
  else if (event.item.id === 'strainers:sturdy_everything_upgrade') giveUpgrades('sturdy');
  else if (event.item.id === 'strainers:everlasting_everything_upgrade') giveUpgrades('everlasting');
  else if (event.item.id === 'strainers:reinforced_everything_upgrade') giveUpgrades('reinforced');
})


// === ENTITY EVENTS === //

EntityEvents.death("minecraft:wither_skeleton", event => {
  if (event.source.actual && event.source.actual.isPlayer()) {
    let killer = event.source.actual;
    let curios = killer.nbt.ForgeCaps['curios:inventory'];

    if (curios.toString().contains('submerged:wither_skull_curio')) {
      killer.give("minecraft:wither_skeleton_skull")
    }
  }
})


// === PLAYER TICK EVENTS === //

PlayerEvents.tick(event => {
  // 1. Creative/Spectator Bypass
  if (event.player.isCreative() || event.player.isSpectator()) {
    event.player.removeTag("in_water_poisoned");
    event.player.removeTag("in_toxic_air_poisoned");
    return;
  }

  // 2. Throttle the tick event. 
  // Forces logic to calculate once per second (every 20 ticks)
  if (event.player.age % 20 !== 0) return;

  let curios = event.player.nbt.ForgeCaps['curios:inventory']

  // --- Dimension Teleporting ---

  // Overworld to Nether 
  if (event.level.dimension == "minecraft:overworld" && event.player.y < -125) {
    event.player.teleportTo(event.server.getLevel("minecraft:the_nether"), event.player.x, 270, event.player.z, [], event.player.yaw, event.player.pitch)
    event.player.potionEffects.add("minecraft:slow_falling", 20 * 5)
    event.player.displayClientMessage(Text.of("You have entered The Nether"), true)
  }

  // Nether to Colored Caves
  if (event.level.dimension == "minecraft:the_nether" && event.player.y < -60 && event.player.y > -110) {
    event.player.teleportTo(event.server.getLevel("caveopolis:colored_caves"), event.player.x, 140, event.player.z, [], event.player.yaw, event.player.pitch)
    event.player.potionEffects.add("minecraft:slow_falling", 20 * 5)
    event.player.displayClientMessage(Text.of("You have entered the Colored Caves"), true)
  }

  // --- Poison Logic ---

  // Toxic Air Curio
  if (curios.toString().contains('submerged:toxic_air_curio')) {
    event.player.addTag("wearing_toxic_air_curio");
  } else {
    event.player.removeTag("wearing_toxic_air_curio");
  }

  // Diving Suit Check
  let wearingDivingSuit = (event.player.feetArmorItem == "thermal:diving_boots" &&
    event.player.legsArmorItem == "thermal:diving_leggings" &&
    event.player.chestArmorItem == "thermal:diving_chestplate" &&
    event.player.headArmorItem == "thermal:diving_helmet");

  if (wearingDivingSuit || curios.toString().contains('submerged:water_curio')) {
    event.player.addTag("wearing_diving_suit");
  } else {
    event.player.removeTag("wearing_diving_suit");
  }

  // Apply Poison in Overworld
  if (event.level.dimension == "minecraft:overworld") {

    // Water Poison
    if (event.player.isInWater() && !event.player.getTags().contains("wearing_diving_suit")) {
      event.player.addTag("in_water_poisoned");
    } else {
      event.player.removeTag("in_water_poisoned");
    }

    // Toxic Air Poison
    if (event.player.y > 150 && !event.player.getTags().contains("wearing_toxic_air_curio")) {
      event.player.potionEffects.add("minecraft:poison", 20 * 1, 10); // 20 ticks (1 sec)
      event.player.addTag("in_toxic_air_poisoned");
    } else {
      event.player.removeTag("in_toxic_air_poisoned");
    }

    // Apply Damage
    if (event.player.getTags().contains("in_water_poisoned") || event.player.getTags().contains("in_toxic_air_poisoned")) {
      event.player.potionEffects.add("minecraft:poison", 20 * 1, 1);
      event.player.attack(1);
    }
  }
})