
  --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

  -- oUF_Diablo "low Health Warning" – 1:1 port.
  -- A step color curve over the health percentage drives the red glow's alpha:
  -- full red (alpha 0.85) at 0% HP, fading to alpha 0 at 31% HP. The texture stays
  -- shown; the curve-driven alpha makes it appear/disappear smoothly.
  -- C-side curve evaluation (UnitHealthPercent(unit, true, curve)) is secret-safe.
  local _lowHealthCurve
  local function GetLowHealthCurve()
    if _lowHealthCurve ~= nil then return _lowHealthCurve or nil end
    if not (C_CurveUtil and C_CurveUtil.CreateColorCurve and Enum and Enum.LuaCurveType and CreateColor) then
      _lowHealthCurve = false
      return nil
    end
    local curve = C_CurveUtil.CreateColorCurve()
    curve:SetType(Enum.LuaCurveType.Step)
    curve:AddPoint(0.0,  CreateColor(1, 0, 0, 0.85))
    curve:AddPoint(0.31, CreateColor(1, 0, 0, 0))
    _lowHealthCurve = curve
    return curve
  end
  ns.GetLowHealthCurve = GetLowHealthCurve

  function ns.UpdateLowHPGlow(orb, unit)
    if not orb or not orb.lowHP then return end
    if type(UnitHealthPercent) ~= "function" then
      orb.lowHP:SetVertexColor(1, 0, 0, 0)
      orb.lowHP:Show()
      return
    end

    -- Preferred path: oUF_Diablo color-curve (smooth red fade as HP drops).
    local curve = GetLowHealthCurve()
    if curve then
      local color = UnitHealthPercent(unit, true, curve)
      if color then
        orb.lowHP:SetVertexColor(color:GetRGBA())
        orb.lowHP:Show()
        return
      end
    end

    -- Fallback (no color-curve API): alpha 0 above 25%, full red below.
    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:SetVertexColor(1, 0, 0, 0)
      orb.lowHP:Show()
      return
    end
    scratch:SetFormattedText("%.1f", pct)
    local pctStr = scratch:GetText()
    local pctNum = pctStr and tonumber(pctStr)
    if pctNum and pctNum <= 25 then
      orb.lowHP:SetVertexColor(1, 0, 0, 1)
    else
      orb.lowHP:SetVertexColor(1, 0, 0, 0)
    end
    orb.lowHP:Show()
  end

  -- oUF_Diablo "debuff type glow" – 1:1 port.
  -- Colors the orb's glow texture by the dispel type of the first dispel-typed
  -- harmful aura on the unit (Magic/Curse/Disease/Poison/Enrage etc.), using the
  -- same Blizzard API oUF_Diablo uses: C_UnitAuras.GetAuraDispelTypeColor.
  -- No dispel-typed debuff -> alpha 0 (invisible). Secret-safe: we never read the
  -- secret dispelName value, only its truthiness, and pass auraInstanceID to C.
  function ns.UpdateDebuffTypeGlow(orb, unit)
    if not orb or not orb.glow then return end
    if not (unit and UnitExists(unit)) then
      orb.glow:SetVertexColor(0.8, 0, 0, 0)
      return
    end
    local found = false
    if C_UnitAuras and C_UnitAuras.GetAuraSlots and C_UnitAuras.GetAuraDataBySlot and C_UnitAuras.GetAuraDispelTypeColor then
      local slots = { C_UnitAuras.GetAuraSlots(unit, "HARMFUL") }
      for i = 2, #slots do
        local data = C_UnitAuras.GetAuraDataBySlot(unit, slots[i])
        if data and data.dispelName and data.auraInstanceID then
          local ok, color = pcall(C_UnitAuras.GetAuraDispelTypeColor, unit, data.auraInstanceID, orb._dispelColorCurve)
          if ok and color then
            orb.glow:SetVertexColor(color:GetRGBA())
            found = true
            break
          end
        end
      end
    end
    if not found then
      orb.glow:SetVertexColor(0.8, 0, 0, 0)
    end
  end

  -- Directly render a health/power percentage onto a FontString.
  -- Uses SetFormattedText (C-side) so the secret number never
  -- touches Lua arithmetic.
  -- noSign: if true, omit the %% symbol (controlled by rOrbsDB["hidePercentSign_<cfgKey>"])
  function ns.RenderPercent(fontString, unit, isHealth, noSign)
    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
    local fmt = noSign and "%.0f" or "%.0f%%"

    -- 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(fmt, 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(fmt, 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, noSign)
    if not fontString then return end
    if not UnitExists(unit) or UnitIsDeadOrGhost(unit) then
      fontString:SetText("")
      return
    end
    -- Always show % on top (consistent with Health orb) for all power types
    ns.RenderPercent(fontString, unit, false, noSign)
  end

  -- Render Power Orb bottom text:
  -- Always show abbreviated value on bottom (consistent with Health orb)
  function ns.RenderPowerBottom(fontString, unit)
    if not fontString then return end
    if not UnitExists(unit) or UnitIsDeadOrGhost(unit) then
      fontString:SetText("")
      return
    end
    ns.RenderAbbreviated(fontString, unit, false)
  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

  -- Party frame health tag: abbreviated HP (secret-safe via AbbreviateLargeNumbers)
  oUF.Tags.Methods["diablo:curhp"] = function(unit)
    if not UnitExists(unit) then return "" end
    if UnitIsDeadOrGhost(unit) then return "|cffaaaaaa Dead|r" end
    if not UnitIsConnected(unit) then return "|cffaaaaaa Offline|r" end
    local abbr = _G.ShortenNumber or _G.AbbreviateLargeNumbers or _G.AbbreviateNumbers
    if not abbr then return "" end
    local hp = UnitHealth(unit)
    if type(hp) == "number" then
      return abbr(hp) or ""
    end
    return ""
  end
  oUF.Tags.Events["diablo:curhp"] = "UNIT_HEALTH UNIT_MAXHEALTH UNIT_CONNECTION"

  -- Legacy tags
  -- SECRET-SAFE: UnitPower/UnitPowerMax may return secrets for non-player units.
  -- All math in pcall; on failure (secret) tag returns nil — better than a 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"

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