--@name Status widget
--@version 1.0.0
--@author wolfhack docs
--@api 1.0
--@description A small widget showing your health as a bar and a number, with an optional enemy count. Everything about it is configurable on its tab.
-- No permissions needed. The enemy count only sees the teams whose ESP is switched on in the overlay menu.

local W, H = 200, 56
local shown = 100          -- the health that is drawn, easing toward the real value

local STYLES = { "Bar", "Number", "Bar and number" }

ui.tab("Status widget", function()
  ui.card("Widget", function()
    ui.toggle("visible", "Show the widget", true)
    ui.dropdown("style", "Style", STYLES, 3)
    ui.toggle("enemies", "Count enemies alive", true)
    ui.slider("opacity", "Background opacity", 0, 1, 0.86)
  end, { width = 0.5 })

  ui.card("Colours", function()
    ui.color("good", "Healthy", 0x5EC27AFF)
    ui.color("low", "Low health", 0xEC5454FF)
    ui.slider("low_below", "Low health below", 5, 60, 30, { int = true })
  end, { width = 0.5 })
end)

-- The widget is registered once; hiding it is done with ui.widget_visible.
ui.widget{
  id = "status", name = "Status widget", size = { W, H }, pos = { 0.02, 0.55 },
  draw = function(w)
    local snap = data.snapshot()
    local me = snap["local"]                      -- "local" is a Lua keyword, so index it as a string
    local health = me and me.health or 0
    shown = anim.approach(shown, health, 10, w.dt)

    draw.rect(0, 0, w.w, w.h, color.alpha(0x101418FF, store.get("opacity", 0.86)), 6)

    if not me then
      draw.text(w.w / 2, w.h / 2 - 8, 0x808890FF, "no player", { align = "center", size = 14 })
      return
    end

    local style = store.get("style", 3)
    local low = shown <= store.get("low_below", 30)
    local col = low and store.get("low", 0xEC5454FF) or store.get("good", 0x5EC27AFF)

    if style ~= 2 then                           -- the bar
      local frac = math.clamp(shown / 100, 0, 1)
      draw.rect(12, 34, w.w - 24, 8, 0xFFFFFF22, 4)
      if frac > 0 then draw.rect(12, 34, (w.w - 24) * frac, 8, col, 4) end
    end
    if style ~= 1 then                           -- the number
      draw.text(12, 8, col, tostring(math.floor(shown + 0.5)), { size = 20 })
    end

    if store.get("enemies", true) then
      local alive = 0
      for _, p in ipairs(snap.players) do
        if not p.teammate and not p["local"] and p.health > 0 then alive = alive + 1 end
      end
      draw.text(w.w - 12, 12, 0xA8B0B8FF, alive .. " enemies", { align = "right", size = 13 })
    end
  end,
}

local function apply_visibility()
  ui.widget_visible("status", store.get("visible", true))
end
apply_visibility()
events.on("settings", function(key)
  if key == "visible" then apply_visibility() end
end)
