
  --get the addon namespace
  local addon, ns = ...

  --get oUF namespace (just in case needed)
  local oUF = ns.oUF or oUF

  --get the config
  local cfg = ns.cfg
  --get the database
  local db = ns.db
  --get the functions
  local func = ns.func

  local format, floor = format, floor

  ---------------------------------------------
  -- SECRET-SAFE HELPER FUNCTIONS (WoW 12.0+)
  --
  -- CRITICAL RULES FOR SECRET VALUES:
  -- 1) NEVER do Lua arithmetic (floor, +, -, *, /) on them
  -- 2) NEVER do Lua comparisons (<, >, ==) on them
  -- 3) NEVER pass them to string.format / format()
  -- 4) ONLY pass them to C-side functions:
  --    - FontString:SetFormattedText(fmt, secretVal)
  --    - AbbreviateLargeNumbers(secretVal)
  --    - StatusBar:SetValue(secretVal)
  --    - StatusBar:SetMinMaxValues(0, secretVal)
  ---------------------------------------------

  -- Low HP glow threshold check (secret-safe).
  -- Uses a hidden scratch FontString + SetFormattedText to render the pct to a string,
  -- then reads it back as plain Lua text for the <= 25 comparison.
  -- This is safe because GetText() returns a plain (non-secret) Lua string.
  local _lowHPScratch
  local function getLowHPScratch()
    if _lowHPScratch then return _lowHPScratch end
    local f = CreateFrame("Frame", nil, UIParent)
    f:SetSize(1, 1)
    f:Hide()
    local fs = f:CreateFontString(nil, "ARTWORK")
    fs:SetFont("Fonts\\FRIZQT__.TTF", 10)
    _lowHPScratch = fs
    return fs
  end

  function ns.UpdateLowHPGlow(orb, unit)
    if not orb or not orb.lowHP then return end
    if type(UnitHealthPercent) ~= "function" then
      orb.lowHP:Hide()
      return
    end
    local scratch = getLowHPScratch()
    local pct
    if CurveConstants and CurveConstants.ScaleTo100 then
      pct = UnitHealthPercent(unit, true, CurveConstants.ScaleTo100)
    else
      pct = UnitHealthPercent(unit, true, true)
    end
    if type(pct) ~= "number" then
      orb.lowHP:Hide()
      return
    end
    -- Render to string via C-side, read back as plain text (non-secret)
    scratch:SetFormattedText("%.1f", pct)
    local pctStr = scratch:GetText()
    local pctNum = pctStr and tonumber(pctStr)
    if pctNum and pctNum <= 25 then
      orb.lowHP:Show()
    else
      orb.lowHP:Hide()
    end
  end

  -- Directly render a health/power percentage onto a FontString.
  -- Uses SetFormattedText (C-side) so the secret number never
  -- touches Lua arithmetic.
  function ns.RenderPercent(fontString, unit, isHealth)
    if not fontString then return end
    if not UnitExists(unit) then
      fontString:SetText("")
      return
    end
    if UnitIsDeadOrGhost(unit) then
      fontString:SetText("Dead")
      return
    end
    if not UnitIsConnected(unit) then
      fontString:SetText("Offline")
      return
    end

    -- SECRET-SAFE: use type() to validate secret values, never ~= nil or comparisons.
    if isHealth then
      if type(UnitHealthPercent) == "function" then
        local pct
        if CurveConstants and CurveConstants.ScaleTo100 then
          pct = UnitHealthPercent(unit, true, CurveConstants.ScaleTo100)
        else
          pct = UnitHealthPercent(unit, true, true)
        end
        if type(pct) == "number" then
          fontString:SetFormattedText("%.0f", pct)
          return
        end
      end
    else
      if type(UnitPowerPercent) == "function" then
        local pType
        if type(UnitPowerType) == "function" then
          pType = UnitPowerType(unit)
        end
        local pct
        if CurveConstants and CurveConstants.ScaleTo100 then
          pct = UnitPowerPercent(unit, pType, false, CurveConstants.ScaleTo100)
        else
          pct = UnitPowerPercent(unit, pType, false, true)
        end
        if type(pct) == "number" then
          fontString:SetFormattedText("%.0f", pct)
          return
        end
      end
    end
    fontString:SetText("")
  end

  -- Directly render an abbreviated value (e.g. "4K", "1.2M") onto a FontString.
  -- AbbreviateLargeNumbers is C-side and converts secret numbers to clean strings.
  function ns.RenderAbbreviated(fontString, unit, isHealth)
    if not fontString then return end
    if not UnitExists(unit) then
      fontString:SetText("")
      return
    end
    if UnitIsDeadOrGhost(unit) then
      fontString:SetText("")
      return
    end
    if not UnitIsConnected(unit) then
      fontString:SetText("")
      return
    end

    -- Prefer ShortenNumber ("58.4k") over AbbreviateLargeNumbers ("58,360" for small numbers).
    -- Call abbr WITHOUT pcall — pcall wrapping suppresses tainted return values.
    -- Use type() to check secret values, never compare with ~= nil (also blocked).
    local abbr = _G.ShortenNumber or _G.AbbreviateLargeNumbers or _G.AbbreviateNumbers
    if not abbr then
      fontString:SetText("")
      return
    end

    local value
    if isHealth then
      value = UnitHealth(unit)
    else
      value = UnitPower(unit)
    end

    -- type() on a secret value is safe (returns "number"), ~= nil comparison is NOT safe.
    if type(value) == "number" then
      local text = abbr(value)
      if text ~= nil then
        fontString:SetText(text)
        return
      end
    end
    fontString:SetText("")
  end

  -- Render Power Orb top text:
  -- MANA users: percentage | Non-MANA: abbreviated current value
  function ns.RenderPowerTop(fontString, unit)
    if not fontString then return end
    if not UnitExists(unit) or UnitIsDeadOrGhost(unit) then
      fontString:SetText("")
      return
    end
    local _, powerToken = UnitPowerType(unit)
    if powerToken == "MANA" then
      ns.RenderPercent(fontString, unit, false)
    else
      ns.RenderAbbreviated(fontString, unit, false)
    end
  end

  -- Render Power Orb bottom text:
  -- MANA users: abbreviated current value | Non-MANA: percentage
  function ns.RenderPowerBottom(fontString, unit)
    if not fontString then return end
    if not UnitExists(unit) or UnitIsDeadOrGhost(unit) then
      fontString:SetText("")
      return
    end
    local _, powerToken = UnitPowerType(unit)
    if powerToken == "MANA" then
      ns.RenderAbbreviated(fontString, unit, false)
    else
      ns.RenderPercent(fontString, unit, false)
    end
  end

  -- Get a CLEAN percentage from StatusBar fill height ratio.
  -- This is pixel-based (not a secret value) and safe for Lua
  -- arithmetic and threshold comparisons (e.g. low HP glow).
  function ns.GetFillPercent(bar)
    if not bar then return 0 end
    local fillTex = bar:GetStatusBarTexture()
    local barH = bar:GetHeight()
    local fillH = fillTex and fillTex:GetHeight() or 0
    local ok, per = pcall(function()
      if barH > 0 then return fillH / barH * 100 end
      return 0
    end)
    if not ok then return 0 end
    return per
  end

  ---------------------------------------------
  -- TAGS (non-secret, kept for oUF compat)
  ---------------------------------------------

  local function RGBPercToHex(r, g, b)
    r = r <= 1 and r >= 0 and r or 1
    g = g <= 1 and g >= 0 and g or 1
    b = b <= 1 and b >= 0 and b or 1
    return format("%02x%02x%02x", r*255, g*255, b*255)
  end

  oUF.Tags.Methods["diablo:color"] = function(unit)
    local color = { r=1, g=1, b=1, }
    if UnitIsDeadOrGhost(unit) or not UnitIsConnected(unit) then
      color = {r = 0.5, g = 0.5, b = 0.5}
    elseif UnitIsPlayer(unit) then
      color = RAID_CLASS_COLORS[select(2, UnitClass(unit))]
    elseif UnitIsUnit(unit, "target") and UnitIsTapDenied("target") then
      color = {r = 0.5, g = 0.5, b = 0.5}
    else
      color = FACTION_BAR_COLORS[UnitReaction(unit, "player")]
    end
    if color then
      return RGBPercToHex(color.r,color.g,color.b)
    else
      return "ffffff"
    end
  end

  oUF.Tags.Methods["diablo:colorsimple"] = function(unit)
    local color = { r=1, g=1, b=1, }
    if UnitIsDeadOrGhost(unit) or not UnitIsConnected(unit) then
      color = {r = 0.5, g = 0.5, b = 0.5}
    end
    if color then
      return RGBPercToHex(color.r,color.g,color.b)
    else
      return "ffffff"
    end
  end

  oUF.Tags.Methods["diablo:name"] = function(unit)
    local cc = ("|cff%s%%s|r"):format(oUF.Tags.Methods["diablo:color"](unit))
    local fullName
    if C_AddOns and C_AddOns.IsAddOnLoaded and C_AddOns.IsAddOnLoaded("Totalrp3") and TRP3_API then
      local unitID = TRP3_API.utils.str.getUnitID(unit)
      fullName = unitID and TRP3_API.chat.getFullnameForUnitUsingChatMethod(unitID)
    end
    return cc:format(fullName or UnitName(unit) or "")
  end
  oUF.Tags.Events["diablo:name"] = "UNIT_NAME_UPDATE UNIT_HEALTH UNIT_MAXHEALTH UNIT_CONNECTION"

  oUF.Tags.Methods["diablo:status"] = function(unit, rolf)
    local color = oUF.Tags.Methods["diablo:colorsimple"](unit)
    local status
    if UnitIsDeadOrGhost(unit) then
      status = "Dead"
    elseif not UnitIsConnected(unit) then
      status = "Offline"
    end
    return "|cff"..color..(status or "").."|r"
  end
  oUF.Tags.Events["diablo:status"] = "UNIT_HEALTH UNIT_MAXHEALTH UNIT_CONNECTION"

  -- Dummy tag methods (return empty, actual rendering is done via ns.Render* in PostUpdate)
  -- These exist so oUF tag system doesn't error when referencing them.
  oUF.Tags.Methods["diablo:HealthOrbTop"] = function(unit) return "" end
  oUF.Tags.Methods["diablo:HealthOrbBottom"] = function(unit) return "" end
  oUF.Tags.Methods["diablo:PowerOrbTop"] = function(unit) return "" end
  oUF.Tags.Methods["diablo:PowerOrbBottom"] = function(unit) return "" end
  oUF.Tags.Methods["diablo:TargetHealthOrbTop"] = function(unit) return "" end
  oUF.Tags.Methods["diablo:TargetHealthOrbBottom"] = function(unit) return "" end

  -- Legacy tags
  -- SECRET-SAFE: UnitPower/UnitPowerMax können für Nicht-Player-Units secret values
  -- zurückgeben. Alle Arithmetik läuft deshalb in einem pcall. Schlägt er fehl
  -- (secret value), gibt der Tag nil zurück — besser als ein UI-Error.
  oUF.Tags.Methods["diablo:altbosspower"] = function(unit)
    if UnitIsDeadOrGhost(unit) then return end
    local ok, result = pcall(function()
      local cur = UnitPower(unit, ALTERNATE_POWER_INDEX) or 0
      local max = UnitPowerMax(unit, ALTERNATE_POWER_INDEX) or 0
      if max <= 0 then return nil end
      return floor(cur / max * 100)
    end)
    if not ok or not result then return end
    return "|cff0099ff"..result.."%|cff666666 / |r"
  end
  oUF.Tags.Events["diablo:altbosspower"] = "UNIT_POWER_UPDATE"

  oUF.Tags.Methods["diablo:altpower"] = function(unit)
    local ok, result = pcall(function()
      local cur = UnitPower(unit, ALTERNATE_POWER_INDEX) or 0
      local max = UnitPowerMax(unit, ALTERNATE_POWER_INDEX) or 0
      if cur <= 0 or max <= 0 then return nil end
      return floor(cur).." / "..floor(max)
    end)
    if not ok or not result then return end
    return result
  end
  oUF.Tags.Events["diablo:altpower"] = "UNIT_POWER_UPDATE"

  ---------------------------------------------
