---@class addonTablePlatynator
local addonTable = select(2, ...)

local LSM = LibStub("LibSharedMedia-3.0")

local pandemicCurve
local pandemicPercentage = 0.3
local dispelCurve
local dispelColorMap = {
  ["Magic"] = CreateColorFromHexString("ff007ffb"),
  ["Curse"] = CreateColorFromHexString("ffb534ed"),
  ["Disease"] = CreateColorFromHexString("fffc982f"),
  ["Poison"] = CreateColorFromHexString("ffe5fb00"),
  [""] = CreateColorFromHexString("ffff0000"),
  ["Bleed"] = CreateColorFromHexString("fffc0318"),
}
if C_CurveUtil then
  pandemicCurve = C_CurveUtil.CreateCurve()
  pandemicCurve:SetType(Enum.LuaCurveType.Step)
  pandemicCurve:AddPoint(0, 1)
  pandemicCurve:AddPoint(pandemicPercentage, 0)

  dispelCurve = C_CurveUtil.CreateColorCurve()
  dispelCurve:SetType(Enum.LuaCurveType.Step)
  dispelCurve:AddPoint(0, CreateColor(0, 0, 0, 0))
  dispelCurve:AddPoint(1, dispelColorMap["Magic"])
  dispelCurve:AddPoint(2, dispelColorMap["Curse"])
  dispelCurve:AddPoint(3, dispelColorMap["Disease"])
  dispelCurve:AddPoint(4, dispelColorMap["Poison"])
  dispelCurve:AddPoint(5, CreateColor(0, 0, 0, 0))
  dispelCurve:AddPoint(9, dispelColorMap[""])
  dispelCurve:AddPoint(10, CreateColor(0, 0, 0, 0))
  dispelCurve:AddPoint(11, dispelColorMap["Bleed"])
end

addonTable.Display.NameplateMixin = {}
function addonTable.Display.NameplateMixin:OnLoad()
  self:SetFlattensRenderLayers(true)
  self:SetCollapsesLayout(true)

  self.widgets = {}

  self.SoftTargetIcon = self:CreateTexture(nil, "OVERLAY")
  self.SoftTargetIcon:SetSize(34, 34)
  self.SoftTargetIcon:SetPoint("BOTTOM", self, "TOP", 0, 24)
  self.SoftTargetIcon:Hide()

  self.BuffDisplay = CreateFrame("Frame", nil, self)
  self.BuffDisplay:SetSize(10, 10)
  self.BuffDisplay:SetFlattensRenderLayers(true)
  self.DebuffDisplay = CreateFrame("Frame", nil, self)
  self.DebuffDisplay:SetSize(10, 10)
  self.DebuffDisplay:SetFlattensRenderLayers(true)
  self.CrowdControlDisplay = CreateFrame("Frame", nil, self)
  self.CrowdControlDisplay:SetSize(10, 10)
  self.CrowdControlDisplay:SetFlattensRenderLayers(true)

  self.AurasManager = addonTable.Utilities.InitFrameWithMixin(self, addonTable.Display.AurasManagerMixin)
  local borderAsset = LSM:Fetch("nineslice", "Platy: 1px")
  local dispelAsset = LSM:Fetch("nineslice", "Platy: 4px")
  self.AurasPool = CreateFramePool("Frame", self, "PlatynatorNameplateBuffButtonTemplate", nil, false, function(frame)
    frame.Border = frame:CreateTexture(nil, "OVERLAY")
    frame.Border:SetAllPoints(true)
    frame.Border:SetScale(borderAsset.scaleModifier)
    frame.Border:SetTexture(borderAsset.file)
    frame.Border:SetTextureSliceMargins(borderAsset.margins.left, borderAsset.margins.top, borderAsset.margins.right, borderAsset.margins.bottom)
    frame.Border:SetVertexColor(0, 0, 0)
    frame.Cooldown:SetCountdownAbbrevThreshold(20)
    frame.Cooldown.Text = frame.Cooldown:GetRegions()
    frame.Pandemic = CreateFrame("Frame", nil, frame)
    frame.Pandemic:SetAllPoints()
    frame.Pandemic.Animation = frame.Pandemic:CreateAnimationGroup()
    frame.Pandemic:SetFrameLevel(frame.Cooldown:GetFrameLevel() + 5)
    do
      frame.Pandemic.Top = frame.Pandemic:CreateTexture()
      frame.Pandemic.Top:SetPoint("TOPLEFT")
      frame.Pandemic.Top:SetPoint("TOPRIGHT")
      frame.Pandemic.Top:SetTexture("Interface/AddOns/Platynator/Assets/Special/pandemic.png")
      frame.Pandemic.Bottom = frame.Pandemic:CreateTexture()
      frame.Pandemic.Bottom:SetPoint("BOTTOMLEFT")
      frame.Pandemic.Bottom:SetPoint("BOTTOMRIGHT")
      frame.Pandemic.Bottom:SetTexture("Interface/AddOns/Platynator/Assets/Special/pandemic.png")
      frame.Pandemic.Bottom:SetRotation(math.pi)
      frame.Pandemic.Left = frame.Pandemic:CreateTexture()
      frame.Pandemic.Left:SetPoint("TOPLEFT")
      frame.Pandemic.Left:SetPoint("BOTTOMLEFT")
      frame.Pandemic.Left:SetTexture("Interface/AddOns/Platynator/Assets/Special/pandemic-90.png")
      frame.Pandemic.Right = frame.Pandemic:CreateTexture()
      frame.Pandemic.Right:SetPoint("TOPRIGHT")
      frame.Pandemic.Right:SetPoint("BOTTOMRIGHT")
      frame.Pandemic.Right:SetTexture("Interface/AddOns/Platynator/Assets/Special/pandemic-90.png")
      frame.Pandemic.Right:SetRotation(math.pi)
      local fb = frame.Pandemic.Animation:CreateAnimation("Flipbook")
      fb:SetFlipBookColumns(1)
      fb:SetFlipBookRows(11)
      fb:SetDuration(0.5)
      fb:SetTarget(frame.Pandemic.Top)
      local fb = frame.Pandemic.Animation:CreateAnimation("Flipbook")
      fb:SetFlipBookColumns(1)
      fb:SetFlipBookRows(11)
      fb:SetDuration(0.5)
      fb:SetTarget(frame.Pandemic.Bottom)
      local fb = frame.Pandemic.Animation:CreateAnimation("Flipbook")
      fb:SetFlipBookColumns(11)
      fb:SetFlipBookRows(1)
      fb:SetDuration(0.5)
      fb:SetTarget(frame.Pandemic.Left)
      local fb = frame.Pandemic.Animation:CreateAnimation("Flipbook")
      fb:SetFlipBookColumns(11)
      fb:SetFlipBookRows(1)
      fb:SetDuration(0.5)
      fb:SetTarget(frame.Pandemic.Right)
      frame.Pandemic.Animation:SetLooping("REPEAT")
      frame.Pandemic.Animation:Play()
      function frame.Pandemic:SetVertexColor(...)
        frame.Pandemic.Top:SetVertexColor(...)
        frame.Pandemic.Bottom:SetVertexColor(...)
        frame.Pandemic.Left:SetVertexColor(...)
        frame.Pandemic.Right:SetVertexColor(...)
      end
    end
    frame.Dispel = CreateFrame("Frame", nil, frame)
    frame.Dispel:SetAllPoints()
    do
      local dispelTexture = frame.Dispel:CreateTexture()
      dispelTexture:SetAllPoints()
      dispelTexture:SetScale(dispelAsset.scaleModifier)
      dispelTexture:SetTexture(dispelAsset.file)
      dispelTexture:SetTextureSliceMargins(dispelAsset.margins.left, dispelAsset.margins.top, dispelAsset.margins.right, dispelAsset.margins.bottom)
      dispelTexture:SetVertexColor(1, 0, 0)
      frame.Dispel.Border = dispelTexture
    end
    frame:SetScript("OnEnter", function()
      GameTooltip_SetDefaultAnchor(GameTooltip, frame)
      if GameTooltip.SetUnitAuraByAuraInstanceID then
        GameTooltip:SetUnitAuraByAuraInstanceID(self.unit, frame.auraInstanceID)
      elseif frame.auraIndex then
        if frame.auraIndex ~= -1 then
          GameTooltip:SetUnitAura(self.unit, frame.auraIndex, frame.auraFilter)
          GameTooltip:Show()
        end
      else
        local index = 1
        while true do
          local aura = C_UnitAuras.GetAuraDataByIndex(self.unit, index, frame.auraFilter)
          if not aura then
            break
          end
          if aura.auraInstanceID == frame.auraInstanceID then
            frame.auraIndex = index
            break
          end
          index = index + 1
        end

        if frame.auraIndex then
          GameTooltip:SetUnitAura(self.unit, frame.auraIndex, frame.auraFilter)
          GameTooltip:Show()
        else
          frame.auraIndex = -1
        end
      end
    end)
    frame:SetScript("OnLeave", function()
      GameTooltip:Hide()
    end)
  end)

  local function GetCallback(frame)
    return function(data, auraFilter)
      if frame.items then
        for _, item in ipairs(frame.items) do
          self.AurasPool:Release(item)
        end
        frame.items = nil
      end

      if not frame:GetParent():IsShown() then
        return
      end

      local pandemicDim = PixelUtil.ConvertPixelsToUIForRegion(1, frame)

      local step = PixelUtil.ConvertPixelsToUIForRegion(22, frame)
      local currentX = 0
      local currentY = 0
      local xOffset = 0
      local yOffset = 0
      local details = frame:GetParent().details
      if details.direction == "LEFT" then
        xOffset = -step
      elseif details.direction == "RIGHT" then
        xOffset = step
      else -- CENTER
        xOffset = step
        currentX = -(#data - 1) * step / 2
      end
      local anchor = details.anchor[1]
      if type(anchor) ~= "string" then
        anchor = "CENTER"
      end

      frame.items = {}
      local texBase = 0.95 * (1 - details.height) / 2
      for index, auraInstanceID in ipairs(data) do
        if index > details.limit then
          break
        end

        local aura = self.AurasManager:GetByInstanceID(auraInstanceID)
        local auraFrame = self.AurasPool:Acquire()
        table.insert(frame.items, auraFrame)
        auraFrame:SetParent(frame)

        auraFrame.auraInstanceID = auraInstanceID
        auraFrame.auraIndex = nil
        auraFrame.auraFilter = auraFilter
        auraFrame.durationSecret = aura.durationSecret
        if not C_Secrets then
          auraFrame.duration = aura.duration
          auraFrame.expirationTime = aura.expirationTime
        end

        auraFrame.Icon:SetTexture(aura.icon);
        auraFrame.CountFrame.Count:SetText(aura.applicationsString)

        if auraFrame.styleIndex ~= self.styleIndex or auraFrame.kind ~= details.kind then
          auraFrame.kind = details.kind
          auraFrame.styleIndex = self.styleIndex

          auraFrame:EnableMouse(details.showTooltips)

          auraFrame.CountFrame.Count:SetFontObject(addonTable.CurrentFont)
          auraFrame.CountFrame.Count:ClearAllPoints()
          addonTable.Display.ApplyAnchor(auraFrame.CountFrame.Count, details.texts.stacks.anchor, addonTable.CurrentFontUsesSmoothing and 1/details.texts.stacks.scale or 1)
          if addonTable.CurrentFontUsesSmoothing then
            auraFrame.CountFrame.Count:SetTextScale(1)
            auraFrame.CountFrame.Count:SetScale(details.texts.stacks.scale)
          else
            auraFrame.CountFrame.Count:SetTextScale(details.texts.stacks.scale)
            auraFrame.CountFrame.Count:SetScale(1)
          end
          local c1 = details.texts.stacks.color
          auraFrame.CountFrame.Count:SetTextColor(c1.r, c1.g, c1.b)
          auraFrame.CountFrame.Count:SetShown(details.texts.stacks.visible);

          auraFrame.Cooldown:SetHideCountdownNumbers(not details.texts.countdown.visible)

          if details.texts.countdown.visible then
            auraFrame.Cooldown.Text:SetFontObject(addonTable.CurrentFont)
            auraFrame.Cooldown.Text:ClearAllPoints()
            addonTable.Display.ApplyAnchor(auraFrame.Cooldown.Text, details.texts.countdown.anchor, addonTable.CurrentFontUsesSmoothing and 1/details.texts.countdown.scale or 1)
            if addonTable.CurrentFontUsesSmoothing then
              auraFrame.Cooldown.Text:SetTextScale(1)
              auraFrame.Cooldown.Text:SetScale(details.texts.countdown.scale)
            else
              auraFrame.Cooldown.Text:SetTextScale(details.texts.countdown.scale)
              auraFrame.Cooldown.Text:SetScale(1)
            end
            local c2 = details.texts.countdown.color
            auraFrame.Cooldown.Text:SetTextColor(c2.r, c2.g, c2.b)
          end

          if auraFrame.CountFrame.Count.SetSmoothScaling then
            auraFrame.CountFrame.Count:SetSmoothScaling(addonTable.CurrentFontUsesSmoothing)
            auraFrame.Cooldown.Text:SetSmoothScaling(addonTable.CurrentFontUsesSmoothing)
          end

          auraFrame.Cooldown:SetDrawEdge(details.showSwipe)
          auraFrame.Cooldown:SetDrawSwipe(details.showSwipe)

          PixelUtil.SetSize(auraFrame, 20, 20 * details.height)
          PixelUtil.SetSize(auraFrame.Border, 20, 20 * details.height)
          PixelUtil.SetSize(auraFrame.Icon, 20, 20 * details.height)
          auraFrame.Icon:SetTexCoord(0.05, 0.95, 0.05 + texBase, 0.95 - texBase)

          auraFrame.Dispel:SetShown(details.showType)

          if details.showStealable then
            auraFrame.Pandemic:SetVertexColor(1, 171/255, 26/255)
          elseif details.showPandemic then
            auraFrame.Pandemic:SetVertexColor(1, 1, 1)
          end

          auraFrame.Pandemic:SetShown(details.showPandemic or details.showStealable)
          if auraFrame.Pandemic:IsShown() then
            auraFrame.Pandemic.Top:SetHeight(pandemicDim)
            auraFrame.Pandemic.Bottom:SetHeight(pandemicDim)
            auraFrame.Pandemic.Left:SetWidth(pandemicDim)
            auraFrame.Pandemic.Right:SetWidth(pandemicDim)
          end
        end

        if aura.durationSecret then
          auraFrame.Cooldown:SetCooldownFromDurationObject(aura.durationSecret)
          if details.showPandemic then
            auraFrame.Pandemic:SetAlpha(C_CurveUtil.EvaluateColorValueFromBoolean(auraFrame.durationSecret:IsZero(), 0, auraFrame.durationSecret:EvaluateRemainingPercent(pandemicCurve)))
          end
          if details.showType then
            local color = C_UnitAuras.GetAuraDispelTypeColor(self.unit, aura.auraInstanceID, dispelCurve)
            auraFrame.Dispel.Border:SetVertexColor(color:GetRGBA())
          end
          if details.showStealable then
            auraFrame.Pandemic:SetAlphaFromBoolean(aura.isStealable)
          end
        elseif auraFrame.expirationTime then
          CooldownFrame_Set(auraFrame.Cooldown, aura.expirationTime - aura.duration, aura.duration, aura.duration > 0, true);
          if details.showPandemic then
            auraFrame.Pandemic:SetAlpha(aura.duration > 0 and aura.expirationTime - GetTime() <= aura.duration * pandemicPercentage and 1 or 0)
          end
          if details.showType then
            local color = dispelColorMap[aura.dispelName]
            if color then
              auraFrame.Dispel:SetAlpha(1)
              auraFrame.Dispel.Border:SetVertexColor(color.r, color.g, color.b)
            else
              auraFrame.Dispel:SetAlpha(0)
            end
          end
          if details.showStealable then
            auraFrame.Pandemic:SetShown(aura.isStealable)
          end
        else
          auraFrame.Cooldown:Clear()
          auraFrame.Pandemic:SetAlpha(0)
          auraFrame.Dispel:SetAlpha(0)
        end

        auraFrame:Show();

        PixelUtil.SetPoint(auraFrame, anchor, frame, anchor, currentX, currentY)
        currentX = currentX + xOffset
      end
    end
  end

  self.BuffDisplay.Wrapped = CreateFrame("Frame", nil, self.BuffDisplay)
  self.BuffDisplay.Wrapped:SetSize(10, 10)
  self.DebuffDisplay.Wrapped = CreateFrame("Frame", nil, self.DebuffDisplay)
  self.DebuffDisplay.Wrapped:SetSize(10, 10)
  self.CrowdControlDisplay.Wrapped = CreateFrame("Frame", nil, self.CrowdControlDisplay)
  self.CrowdControlDisplay.Wrapped:SetSize(10, 10)

  self.DebuffDisplay:Hide()
  self.BuffDisplay:Hide()
  self.CrowdControlDisplay:Hide()

  self.AurasManager:SetDebuffsCallback(GetCallback(self.DebuffDisplay.Wrapped))
  self.AurasManager:SetBuffsCallback(GetCallback(self.BuffDisplay.Wrapped))
  self.AurasManager:SetCrowdControlCallback(GetCallback(self.CrowdControlDisplay.Wrapped))

  self:SetSize(10, 10)

  self.casting = false

  self.sizeChangeCount = -1
end

function addonTable.Display.NameplateMixin:OnSizeChanged()
  -- Optimisation to avoid recalculating anchors/sizes while nameplate scales up/down
  self.sizeChangeCount = 0
  self:SetScript("OnUpdate", function()
    self.sizeChangeCount = self.sizeChangeCount + 1
    if self.sizeChangeCount >= 2 then
      self:ApplyPixelPerfectSizing()
      self:SetScript("OnUpdate", nil)
    end
  end)
end

-- Avoid pixel-perfecting the alignment if the scale hasn't changed, or its
-- shrinking cause the nameplate is disappearing
function addonTable.Display.NameplateMixin:ShouldNotSize()
  -- Detect sizing down, which we should ignore
  if not self.unit or not self:IsVisible() then
    return true
  end
  local scale = self:GetEffectiveScale()
  return scale == self.lastScale or scale < self.offsetScale
end

function addonTable.Display.NameplateMixin:ApplyPixelPerfectSizing()
  if self:ShouldNotSize() then
    return
  end
  for _, w in ipairs(self.widgets) do
    w:ApplyAnchor()
    w:ApplySize()
  end
  self.lastScale = self:GetEffectiveScale()
end

function addonTable.Display.NameplateMixin:InitializeWidgets(design, scaleOffset, scaleMod)
  self.offsetScale = (scaleOffset or 1) * UIParent:GetEffectiveScale() * addonTable.Config.Get(addonTable.Config.Options.GLOBAL_SCALE)
  self.scale = design.scale * scaleMod

  self.lastScale = self:GetEffectiveScale()

  self.unit = nil
  self:UpdateVisual()

  if self.widgets then
    addonTable.Display.ReleaseWidgets(self.widgets)
    self.widgets = nil
  end
  self.widgets = addonTable.Display.GetWidgets(design, self)

  local auras = design.auras
  local designInfo = {}
  for _, a in ipairs(auras) do
    designInfo[a.kind] = a
  end
  self.DebuffDisplay.enabled = false
  self.BuffDisplay.enabled = false
  self.CrowdControlDisplay.enabled = false
  local defaultSize = 20
  if designInfo.debuffs then
    self.DebuffDisplay.enabled = true
    self.DebuffDisplay:ClearAllPoints()
    self.DebuffDisplay:SetFrameStrata("MEDIUM")
    self.DebuffDisplay:SetFrameLevel(addonTable.Constants.LayerFrameLevelStep * designInfo.debuffs.layer + 450)
    self.DebuffDisplay.details = designInfo.debuffs
    if self.DebuffDisplay.Wrapped then
      self.DebuffDisplay.Wrapped:ClearAllPoints()
      self.DebuffDisplay.Wrapped:SetPoint(designInfo.debuffs.anchor[1] or "CENTER")
      self.DebuffDisplay.Wrapped:SetScale(designInfo.debuffs.scale)
    end
    PixelUtil.SetSize(self.DebuffDisplay, defaultSize * designInfo.debuffs.scale, defaultSize * designInfo.debuffs.scale)
    addonTable.Display.ApplyAnchor(self.DebuffDisplay, designInfo.debuffs.anchor)
  end
  if designInfo.buffs then
    self.BuffDisplay.enabled = true
    self.BuffDisplay:ClearAllPoints()
    self.BuffDisplay:SetFrameStrata("MEDIUM")
    self.BuffDisplay:SetFrameLevel(addonTable.Constants.LayerFrameLevelStep * designInfo.buffs.layer + 450 + 10)
    self.BuffDisplay.details = designInfo.buffs
    if self.BuffDisplay.Wrapped then
      self.BuffDisplay.Wrapped:ClearAllPoints()
      self.BuffDisplay.Wrapped:SetScale(designInfo.buffs.scale)
      self.BuffDisplay.Wrapped:SetPoint(designInfo.buffs.anchor[1] or "CENTER")
    end
    PixelUtil.SetSize(self.BuffDisplay, defaultSize * designInfo.buffs.scale, defaultSize * designInfo.buffs.scale)
    addonTable.Display.ApplyAnchor(self.BuffDisplay, designInfo.buffs.anchor)
  end
  if designInfo.crowdControl then
    self.CrowdControlDisplay.enabled = true
    self.CrowdControlDisplay:ClearAllPoints()
    self.CrowdControlDisplay:SetFrameStrata("MEDIUM")
    self.CrowdControlDisplay:SetFrameLevel(addonTable.Constants.LayerFrameLevelStep * designInfo.crowdControl.layer + 450 + 20)
    self.CrowdControlDisplay.details = designInfo.crowdControl
    if self.CrowdControlDisplay.Wrapped then
      self.CrowdControlDisplay.Wrapped:ClearAllPoints()
      self.CrowdControlDisplay.Wrapped:SetScale(designInfo.crowdControl.scale)
      self.CrowdControlDisplay.Wrapped:SetPoint(designInfo.crowdControl.anchor[1] or "CENTER")
    end
    PixelUtil.SetSize(self.CrowdControlDisplay, defaultSize * designInfo.crowdControl.scale, defaultSize * designInfo.crowdControl.scale)
    addonTable.Display.ApplyAnchor(self.CrowdControlDisplay, designInfo.crowdControl.anchor)
  end

  self.AurasManager:PostInit(designInfo.buffs, designInfo.debuffs, designInfo.crowdControl)

  if self:GetScript("OnSizeChanged") == nil then
    self:SetScript("OnSizeChanged", self.OnSizeChanged)
  end
  self:SetScript("OnUpdate", nil)
end

function addonTable.Display.NameplateMixin:Install(nameplate, offsetY)
  self:Show()
  self:SetFrameStrata("BACKGROUND")
  self:SetPoint("CENTER", nameplate, "CENTER", 0, offsetY)
  self:SetSize(10, 10)

  -- We force a sizing immediately to avoid 0 size widgets breaking the textures from the Blizz animations
  self:ApplyPixelPerfectSizing()
  self:SetScript("OnUpdate", nil)
end

function addonTable.Display.NameplateMixin:SetUnit(unit)
  if self.unit then
    addonTable.Display.Cache:RemoveUnit(self.unit)
  end

  self.SoftTargetIcon:Hide()

  self.interactUnit = unit
  if unit and (not UnitNameplateShowsWidgetsOnly or not UnitNameplateShowsWidgetsOnly(unit)) and not UnitIsGameObject(unit) then
    self.unit = unit
    addonTable.Display.Cache:AddUnit(unit)

    if UnitCanAttack("player", self.unit) and addonTable.Config.Get(addonTable.Config.Options.OUT_OF_RANGE_ALPHA) ~= 1 then
      addonTable.Display.Cache:RegisterCallback(self.unit, "range", function(state)
        self.inRange = state
        self:UpdateVisual()
      end)
      self.inRange = addonTable.Display.Cache:Get(self.unit, "range")
    else
      self.inRange = true
    end

    if UnitCanAttack("player", self.unit) and addonTable.Config.Get(addonTable.Config.Options.NOT_IN_PULL_ALPHA) ~= 1 then
      self.inCombat = addonTable.Display.Utilities.IsInCombatWith(self.unit)
      addonTable.CallbackRegistry:RegisterCallback("CombatStatusChange", function(_, unit2)
        if unit2 == self.unit then
          self.inCombat = addonTable.Display.Utilities.IsInCombatWith(self.unit)
          self:UpdateVisual()
        end
      end, self)
    else
      self.inCombat = true
    end

    for _, w in ipairs(self.widgets) do
      w:Show()
      w:SetUnit(self.unit)
      if w.ApplyTarget then
        w:ApplyTarget()
      end
      if w.ApplyMouseover then
        w:ApplyMouseover()
      end
      if w.ApplyFocus then
        w:ApplyFocus()
      end
      if addonTable.API.TextOverrides.isActive and w.ApplyTextOverride then
        w:ApplyTextOverride()
      end
    end

    self.BuffDisplay:SetShown(self.BuffDisplay.enabled)
    self.DebuffDisplay:SetShown(self.DebuffDisplay.enabled)
    self.CrowdControlDisplay:SetShown(self.CrowdControlDisplay.enabled)

    self.AurasManager:SetUnit(self.unit)

    addonTable.Display.Cache:RegisterCallback(self.unit, "cast", function(state)
      local old = self.casting
      self:UpdateCastingState(state)
      if old ~= self.casting then
        self:UpdateVisual()
      end
    end)

    addonTable.CallbackRegistry:RegisterCallback("TextOverrideUpdated", function(_, unit)
      if unit ~= self.unit then
        return
      end
      for _, w in ipairs(self.widgets) do
        if w.ApplyTextOverride then
          w:ApplyTextOverride()
        end
      end
    end, self)
  else
    self.unit = nil
    for _, w in ipairs(self.widgets) do
      w:SetUnit(nil)
      w:Hide()
    end

    self.BuffDisplay:Hide()
    self.DebuffDisplay:Hide()
    self.CrowdControlDisplay:Hide()

    self.AurasManager:SetUnit()

    self:UnregisterAllEvents()
    self.casting = false

    addonTable.CallbackRegistry:UnregisterCallback("TextOverrideUpdated", self)
    addonTable.CallbackRegistry:UnregisterCallback("CombatStatusChange", self)
  end

  self:UpdateVisual()
end

function addonTable.Display.NameplateMixin:UpdateCastingState(state)
  state = state or addonTable.Display.Cache:Get(self.unit, "cast")
  self.casting = state.cast[1] ~= nil or state.channel[1] ~= nil
end

function addonTable.Display.NameplateMixin:UpdateForTarget()
  if self.unit then
    for _, w in ipairs(self.widgets) do
      if w.ApplyTarget then
        w:ApplyTarget()
      end
    end
  end

  self:UpdateVisual()
end

function addonTable.Display.NameplateMixin:UpdateForMouseover()
  if self.unit then
    for _, w in ipairs(self.widgets) do
      if w.ApplyMouseover then
        w:ApplyMouseover()
      end
    end
  end

  self:UpdateVisual()
end

function addonTable.Display.NameplateMixin:UpdateForFocus()
  if self.unit then
    for _, w in ipairs(self.widgets) do
      if w.ApplyFocus then
        w:ApplyFocus()
      end
    end
  end

  self:UpdateVisual()
end

function addonTable.Display.NameplateMixin:UpdateVisual()
  local scaleMod = addonTable.Constants.IsRetail and 1 or UIParent:GetEffectiveScale()
  if not self.unit then
    self:SetAlpha(1)
    self:SetScale(self.scale * addonTable.Config.Get(addonTable.Config.Options.GLOBAL_SCALE) * scaleMod)
    return
  end

  local scale = 1
  local alpha = 0
  local isTarget = UnitIsUnit("target", self.unit) or UnitIsUnit("softenemy", self.unit) or UnitIsUnit("softfriend", self.unit)
  if isTarget then
    alpha = 1
  else
    local isMouseover = UnitIsUnit("mouseover", self.unit)
    if isMouseover then
      alpha = math.max(alpha, addonTable.Config.Get(addonTable.Config.Options.MOUSEOVER_ALPHA))
    end
    if self.casting then
      scale = addonTable.Config.Get(addonTable.Config.Options.CAST_SCALE)
      alpha = math.max(alpha, addonTable.Config.Get(addonTable.Config.Options.CAST_ALPHA))
    end
    if not isMouseover and not self.casting then
      alpha = addonTable.Config.Get(addonTable.Config.Options.NOT_TARGET_ALPHA)
    end
  end
  if not self.inRange then
    alpha = alpha * addonTable.Config.Get(addonTable.Config.Options.OUT_OF_RANGE_ALPHA)
  end
  if not self.inCombat and UnitAffectingCombat("player") then
    alpha = alpha * addonTable.Config.Get(addonTable.Config.Options.NOT_IN_PULL_ALPHA)
  end
  self:SetScale(self.scale * scale * addonTable.Config.Get(addonTable.Config.Options.GLOBAL_SCALE) * scaleMod)
  self:SetAlpha(alpha)
end

function addonTable.Display.NameplateMixin:UpdateSoftInteract()
  -- From Blizzard code, modified
  local doEnemyIcon = GetCVarBool("SoftTargetIconEnemy")
  local doFriendIcon = GetCVarBool("SoftTargetIconFriend")
  local doInteractIcon = GetCVarBool("SoftTargetIconInteract")
  local hasCursorTexture = false
  if ((doEnemyIcon and UnitIsUnit(self.interactUnit, "softenemy")) or
    (doFriendIcon and UnitIsUnit(self.interactUnit, "softfriend")) or
    (doInteractIcon and UnitIsUnit(self.interactUnit, "softinteract"))
    ) then
    hasCursorTexture = SetUnitCursorTexture(self.SoftTargetIcon, self.interactUnit)
  end
  self.SoftTargetIcon:SetShown(hasCursorTexture)
end

function addonTable.Display.NameplateMixin:UpdateAurasForPandemic()
  local time = GetTime()
  if self.DebuffDisplay.details and self.DebuffDisplay.details.showPandemic and self.DebuffDisplay.Wrapped.items then
    for _, item in ipairs(self.DebuffDisplay.Wrapped.items) do
      if item.durationSecret then
        item.Pandemic:SetAlpha(C_CurveUtil.EvaluateColorValueFromBoolean(item.durationSecret:IsZero(), 0, item.durationSecret:EvaluateRemainingPercent(pandemicCurve)))
      elseif item.expirationTime then
        item.Pandemic:SetAlpha(item.duration > 0 and item.expirationTime - time <= item.duration * pandemicPercentage and 1 or 0)
      end
    end
  end
end
