#======================================================
#              Adds the Lure Metadata
#======================================================
class PokemonGlobalMetadata # For Global Metadata
  attr_accessor :lure
 
  alias initialize_Lure initialize
  def initialize
    initialize_Lure
    @lure = 0
  end
end
class GameStats             # For Stats Count
  attr_accessor :lure_count
 
  alias initialize_Lure_stats initialize
  def initialize
    initialize_Lure_stats
    @lure_count = 0
  end
end
#============================================================
#    Makes it unable to use repels when a lure is active
#===========================================================
def pbRepel(item, steps)
  # Ujistěte se, že $PokemonGlobal.repel není nil a je inicializováno
  $PokemonGlobal.repel ||= 0
  if $PokemonGlobal.repel > 0
    pbMessage(_INTL("But a repellent's effect still lingers from earlier."))
    return false
  end
  # Ujistěte se, že $PokemonGlobal.lure není nil a je inicializováno
  $PokemonGlobal.lure ||= 0
  if $PokemonGlobal.lure > 0
    pbMessage(_INTL("You can't use a repel and a lure at the same time."))
    return false
  end
  pbSEPlay("Repel")
  $stats.repel_count += 1 if $stats.repel_count
  pbUseItemMessage(item)
  $PokemonGlobal.repel = steps
  return true
end
#============================================================
#            Adds the lure and Item Handlers
#============================================================
def pbLure(item, steps)
  # Zajisti, že lure je inicializováno na 0, pokud je nil
  $PokemonGlobal.lure ||= 0
  if $PokemonGlobal.lure > 0
    pbMessage(_INTL("But a lure's effect still lingers from earlier."))
    return false
  end
  # Ujistěte se, že $PokemonGlobal.repel není nil a je inicializováno
  $PokemonGlobal.repel ||= 0
  if $PokemonGlobal.repel > 0
    pbMessage(_INTL("You can't use a lure and a repel at the same time."))
    return false
  end
  pbSEPlay("Repel")
  $stats.lure_count += 1 if $stats.lure_count
  pbUseItemMessage(item)
  $PokemonGlobal.lure = steps
  return true
end
ItemHandlers::UseInField.add(:LURE, proc { |item|
  next pbLure(item, 100)
})
ItemHandlers::UseInField.add(:SUPERLURE, proc { |item|
  next pbLure(item, 200)
})
ItemHandlers::UseInField.add(:MAXLURE, proc { |item|
  next pbLure(item, 250)
})
#============================================================
#            Adds the lure counter + use in field
#============================================================
EventHandlers.add(:on_player_step_taken, :lure_counter,
  proc {
    # Kontrola, zda existuje $PokemonGlobal a jestli je lure inicializováno
    next if !$PokemonGlobal || $PokemonGlobal.lure.nil? || $PokemonGlobal.lure <= 0 || $game_player.terrain_tag.ice   # Shouldn't count down if on ice
    $PokemonGlobal.lure -= 1
    # Pokud lure dosáhne nuly, informuj hráče a zjisti, jestli chce použít další lure
    next if $PokemonGlobal.lure > 0
    lures = []
    GameData::Item.each { |itm| lures.push(itm.id) if itm.has_flag?("Lure") }
    if lures.none? { |item| $bag.has?(item) }
      pbMessage(_INTL("The lure's effect wore off!"))
      next
    end
    next if !pbConfirmMessage(_INTL("The lure's effect wore off! Would you like to use another one?"))
    ret = nil
    pbFadeOutIn do
      scene = PokemonBag_Scene.new
      screen = PokemonBagScreen.new(scene, $bag)
      ret = screen.pbChooseItemScreen(proc { |item| lures.include?(item) })
    end
    pbUseItem($bag, ret) if ret
  }
)
#============================================================
#            Lure Function to the field
#============================================================
class PokemonEncounters
  # Returns whether a wild encounter should happen, based on its encounter
  # chance. Called when taking a step and by Rock Smash.
  def encounter_triggered?(enc_type, repel_active = false, triggered_by_step = true)
    if !enc_type || !GameData::EncounterType.exists?(enc_type)
      raise ArgumentError.new(_INTL("Encounter type {1} does not exist", enc_type))
    end
    return false if $game_system.encounter_disabled
    return false if !$player
    return false if $DEBUG && Input.press?(Input::CTRL)
    # Check if enc_type has a defined step chance/encounter table
    return false if !@step_chances[enc_type] || @step_chances[enc_type] == 0
    return false if !has_encounter_type?(enc_type)
    # Poké Radar encounters always happen, ignoring the minimum step period and
    # trigger probabilities
    return true if pbPokeRadarOnShakingGrass
    # Get base encounter chance and minimum steps grace period
    encounter_chance = @step_chances[enc_type].to_f
    min_steps_needed = (8 - (encounter_chance / 10)).clamp(0, 8).to_f
    # Apply modifiers to the encounter chance and the minimum steps amount
    if triggered_by_step
      encounter_chance += @chance_accumulator / 200
      encounter_chance *= 0.8 if $PokemonGlobal.bicycle
    end
    if $PokemonGlobal.lure && $PokemonGlobal.lure > 0 # Opravená podmínka
      encounter_chance *= 2.75
      min_steps_needed /= 3
    end
    if $PokemonMap.lower_encounter_rate
      encounter_chance /= 2
      min_steps_needed *= 2
    elsif $PokemonMap.higher_encounter_rate
      encounter_chance *= 1.5
      min_steps_needed /= 2
    end
    first_pkmn = $player.first_pokemon
    if first_pkmn
      case first_pkmn.item_id
      when :CLEANSETAG
        encounter_chance *= 2.0 / 3
        min_steps_needed *= 4 / 3.0
      when :PUREINCENSE
        encounter_chance *= 2.0 / 3
        min_steps_needed *= 4 / 3.0
      else   # Ignore ability effects if an item effect applies
        case first_pkmn.ability_id
        when :STENCH, :WHITESMOKE, :QUICKFEET
          encounter_chance /= 2
          min_steps_needed *= 2
        when :INFILTRATOR
          if Settings::MORE_ABILITIES_AFFECT_WILD_ENCOUNTERS
            encounter_chance /= 2
            min_steps_needed *= 2
          end
        when :SNOWCLOAK
          if GameData::Weather.get($game_screen.weather_type).category == :Hail
            encounter_chance /= 2
            min_steps_needed *= 2
          end
        when :SANDVEIL
          if GameData::Weather.get($game_screen.weather_type).category == :Sandstorm
            encounter_chance /= 2
            min_steps_needed *= 2
          end
        when :SWARM
          encounter_chance *= 1.5
          min_steps_needed /= 2
        when :ILLUMINATE, :ARENATRAP, :NOGUARD
          encounter_chance *= 2
          min_steps_needed /= 2
        end
      end
    end
    # Wild encounters are much less likely to happen for the first few steps
    # after a previous wild encounter
    if triggered_by_step && @step_count < min_steps_needed
      @step_count += 1
      return false if rand(100) >= encounter_chance * 5 / (@step_chances[enc_type] + (@chance_accumulator / 200))
    end
    # Decide whether the wild encounter should actually happen
    return true if rand(100) < encounter_chance
    # If encounter didn't happen, make the next step more likely to produce one
    if triggered_by_step
      @chance_accumulator += @step_chances[enc_type]
      @chance_accumulator = 0 if repel_active
    end
    return false
  end
end
EventHandlers.add(:on_wild_pokemon_created, :make_shiny,
  proc { |pokemon, map, encounter_type|
    if $PokemonGlobal.lure && $PokemonGlobal.lure > 0 # Opravená podmínka
      if rand(100) < 50
        pokemon.shiny = true
      end
    end
  }
)
#============================================================
#            Counts down the lure while on the field
#============================================================
EventHandlers.add(:on_player_step_taken, :lure_counter,
  proc {
    # Kontrola, zda existuje $PokemonGlobal a jestli je lure inicializováno
    next if !$PokemonGlobal || $PokemonGlobal.lure.nil? || $PokemonGlobal.lure <= 0 || $game_player.terrain_tag.ice   # Shouldn't count down if on ice
    $PokemonGlobal.lure -= 1
    # Pokud lure dosáhne nuly, informuj hráče a zjisti, jestli chce použít další lure
    next if $PokemonGlobal.lure > 0
    lures = []
    GameData::Item.each { |itm| lures.push(itm.id) if itm.has_flag?("Lure") }
    if lures.none? { |item| $bag.has?(item) }
      pbMessage(_INTL("The lure's effect wore off!"))
      next
    end
    next if !pbConfirmMessage(_INTL("The lure's effect wore off! Would you like to use another one?"))
    ret = nil
    pbFadeOutIn do
      scene = PokemonBag_Scene.new
      screen = PokemonBagScreen.new(scene, $bag)
      ret = screen.pbChooseItemScreen(proc { |item| lures.include?(item) })
    end
    pbUseItem($bag, ret) if ret
  }
)
#============================================================
#            Generate Wild Pokemon
#============================================================
EventHandlers.add(:on_wild_encounter, :generate_wild_pokemon,
  proc { |encounter_type|
    next if !$PokemonGlobal || !$PokemonGlobal.lure || $PokemonGlobal.lure <= 0 # Opravená podmínka
    wild_pokemon = pbGenerateWildPokemon(encounter_type)
    next wild_pokemon if wild_pokemon
  }
)