// ======================================
// WITHER STORM TIMER + HORDE (FIXED)
// ======================================

// CONFIG
const OVERWORLD_REQUIRED = 1200               
const STORM_TIMER = 216000                  
const WAVE_INTERVAL = 600                    
const NORMAL_WAVE_SIZE = 15
const ELITE_WAVE_INTERVAL = 5
const DARKNESS_DURATION = 3                  

const NORMAL_MOBS = [
  "bygonenether:corpor",
  "bygonenether:wither_skeleton_knight",
  "witherstormmod:sickened_iron_golem"
]

const ELITE_MOBS = [
  "legendary_monsters:withered_abomination",
  "mutantmore:mutant_wither_skeleton"
]

const BOWELS_DIMENSION = "witherstormmod:bowels"

// MAIN TICK LOOP
ServerEvents.tick(event => {
  const server = event.server
  const data = server.persistentData
  if (server.players.length == 0) return
  let player = server.players[0]

  // ENTERING BOWELS STOPS WAVES
  if (player.level.dimension == BOWELS_DIMENSION) {
    if (data.stormActive) {
      data.stormActive = false
      server.tell("§7The storm cannot reach this place...")
    }
    // permanent betrayed effect
    player.runCommandSilent(
      `effect give ${player.username} netherexp:betrayed 999999 0 true`
    )
    return
  }

  // REMOVE BETRAYED WHEN LEAVING BOWELS
  if (player.hasEffect('netherexp:betrayed')) {
    player.potionEffects.remove('netherexp:betrayed')
  }

  // MUST BE IN OVERWORLD
  if (player.level.dimension != "minecraft:overworld") {
    data.overworldTime = 0
    return
  }

  // START TIMER
  data.overworldTime = (data.overworldTime || 0) + 1
  if (data.overworldTime < OVERWORLD_REQUIRED) return

  if (!data.timerStarted) {
    data.timerStarted = true
    data.timer = STORM_TIMER
    data.waveCount = 0
    server.tell("§7The world feels... wrong.")
  }

  // COUNTDOWN
  if (!data.stormSpawned) {
    data.timer--

    // Calculate thresholds based on total timer
    const halfwayThreshold = Math.floor(STORM_TIMER / 2)          
    const finalWarningThreshold = Math.floor(STORM_TIMER * 0.2)  

    if (data.timer === halfwayThreshold) {
      server.tell("§5The sky begins to distort...")
    }
    if (data.timer === finalWarningThreshold) {
      server.tell("§cSomething terrible is coming...")
    }

    if (data.timer <= 0) {
      data.stormSpawned = true
      data.stormActive = true
      player.runCommandSilent(
        `execute at ${player.username} run summon witherstormmod:wither_storm ~ ~100 ~`
      )
      server.tell("§4THE WITHER STORM HAS AWAKENED")
    }
    return
  }

  // HORDE SYSTEM
  if (!data.stormActive) return

  data.waveTimer = (data.waveTimer || 0) + 1
  if (data.waveTimer < WAVE_INTERVAL) return

  data.waveTimer = 0
  data.waveCount = (data.waveCount || 0) + 1

  // APPLY DARKNESS EFFECT (seconds, not ticks)
  player.runCommandSilent(
    `effect give ${player.username} minecraft:darkness ${DARKNESS_DURATION} 0 true`
  )

  // ELITE WAVE
  if (data.waveCount % ELITE_WAVE_INTERVAL == 0) {
    for (let i = 0; i < 2; i++) {
      let mob = ELITE_MOBS[Math.floor(Math.random() * ELITE_MOBS.length)]
      let dx = Math.floor(Math.random() * 20 - 10)
      let dz = Math.floor(Math.random() * 20 - 10)
      player.runCommandSilent(
        `execute at ${player.username} run summon ${mob} ~${dx} ~1 ~${dz}`
      )
    }
    server.tell("§5Elite enemies descend from the storm!")
    return
  }

  // NORMAL WAVE
  for (let i = 0; i < NORMAL_WAVE_SIZE; i++) {
    let mob = NORMAL_MOBS[Math.floor(Math.random() * NORMAL_MOBS.length)]
    let dx = Math.floor(Math.random() * 20 - 10)
    let dz = Math.floor(Math.random() * 20 - 10)
    player.runCommandSilent(
      `execute at ${player.username} run summon ${mob} ~${dx} ~1 ~${dz}`
    )
  }
  server.tell("§aA wave of enemies emerges from the storm!")
})

// HIT COMMAND BLOCK START WAVES
EntityEvents.hurt(event => {
  if (!event.entity.isType('witherstormmod:command_block')) return
  const server = event.server
  const data = server.persistentData
  data.stormActive = true
  server.tell("§4The command block pulses... the storm returns.")
})

// KILL COMMAND BLOCK STOP WAVES
EntityEvents.death(event => {
  if (!event.entity.isType('witherstormmod:command_block')) return
  const server = event.server
  const data = server.persistentData
  data.stormActive = false
  server.tell("§7The storm weakens...")
})