local addon, ns = ...

local cfg
local db = ns.db
local func = ns.func
local unit = ns.unit

---------------------------------------------
-- HIDE BLIZZARD TARGET FRAME
---------------------------------------------

local function HideBlizzardTargetFrame()
  if rOrbsDB and (rOrbsDB.showBlizzardUnitFrames == true or ns._blizzTempVisible == true) then
    return
  end
  if TargetFrame then
    TargetFrame:Hide()
    TargetFrame:SetAlpha(0)
    if not TargetFrame._rOrbsHideHooked then
      TargetFrame:HookScript("OnShow", function(self)
        if (rOrbsDB and rOrbsDB.showBlizzardUnitFrames == true) or ns._blizzTempVisible == true then return end
        if not InCombatLockdown() then self:Hide() end
      end)
      TargetFrame._rOrbsHideHooked = true
    end
  end
end

---------------------------------------------
-- CREATE TARGET ICON
---------------------------------------------

local function CreateTargetIcon()
  cfg = ns.cfg
  if not cfg.units.target or not cfg.units.target.show then return end

  local pcfg = cfg.units.target

  local frame = CreateFrame("Button", "rOrbsTargetFrame", UIParent, "SecureUnitButtonTemplate")
  frame.cfg = pcfg
  frame:SetFrameStrata("LOW")
  frame:SetFrameLevel(1)
  frame:SetSize(pcfg.size, pcfg.size)
  frame:SetScale(pcfg.scale)
  frame:SetPoint(pcfg.pos.a1, pcfg.pos.af, pcfg.pos.a2, pcfg.pos.x, pcfg.pos.y)

  frame:SetAttribute("unit",   "target")
  frame:SetAttribute("*type1", "target")
  frame:SetAttribute("*type2", "togglemenu")
  frame:RegisterForClicks("AnyDown")
  frame:EnableMouse(true)

  frame:SetScript("OnEnter", function(self)
    if UnitExists("target") then
      GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
      GameTooltip:SetUnit("target")
      GameTooltip:Show()
    end
  end)
  frame:SetScript("OnLeave", function() GameTooltip:Hide() end)

  -- DRAG
  func.applyDragFunctionality(frame, "target")

  -- Den Drag-Overlay-Frame des Portraits permanent verstecken und deaktivieren.
  -- Er liegt auf HIGH-Strata und wuerde sonst alle Mausklicks auf dem Portrait abfangen.
  -- Das Portrait wird stattdessen per SHIFT+Drag auf dem Orb mitbewegt (gleiche Position).
  if frame.dragframe then
    frame.dragframe:Hide()
    frame.dragframe:EnableMouse(false)
    frame.dragframe:SetScript("OnUpdate", nil)
    frame.dragframe:SetScript("OnMouseDown", nil)
    frame.dragframe:SetScript("OnMouseUp", nil)
    frame.dragframe:SetScript("OnEnter", nil)
    frame.dragframe:SetScript("OnLeave", nil)
  end

  -- Frame muss sichtbar sein damit Mausevents ankommen
  frame:Show()

  C_Timer.After(0, function()
    local frameName = frame:GetName()
    if frameName and rOrbsDB then
      if rOrbsDB.framePositions and rOrbsDB.framePositions[frameName] then
        local pos = rOrbsDB.framePositions[frameName]
        frame:ClearAllPoints()
        local relFrame = _G[pos.relativeTo] or UIParent
        frame:SetPoint(pos.point, relFrame, pos.relativePoint, pos.x, pos.y)
      end
      if rOrbsDB.frameScales and rOrbsDB.frameScales[frameName] then
        frame:SetScale(rOrbsDB.frameScales[frameName])
      end
    end
  end)

  -- DEBUG: Rotes Overlay zeigt wo die Hitbox des Portrait-Buttons liegt
  -- Dunkler Hintergrund
  local portraitBg = frame:CreateTexture(nil, "BACKGROUND", nil, -1)
  portraitBg:SetAllPoints()
  portraitBg:SetColorTexture(0, 0, 0, 0.85)

  -- 2D Portrait-Textur (kein PlayerModel-Viewport = keine Klick-Blocker)
  -- PlayerModel-Frames in WoW 12.0 routen alle Mausevents an WorldFrame,
  -- wodurch kein SecureButton-Click mehr durchkommt.
  local portraitTex = frame:CreateTexture(nil, "ARTWORK", nil, 2)
  portraitTex:SetAllPoints()
  if portraitTex.SetMask then
    portraitTex:SetMask(ns.mediapath .. "orb_inverse_mask")
  end

  -- Gloss-Overlay
  local portraitGloss = frame:CreateTexture(nil, "OVERLAY", nil, 1)
  portraitGloss:SetAllPoints()
  portraitGloss:SetTexture(ns.mediapath .. "orb_gloss_new")

  local function UpdatePortrait()
    if UnitExists("target") then
      SetPortraitTexture(portraitTex, "target")
      frame:SetAlpha(1)
    else
      portraitTex:SetTexture(nil)
      frame:SetAlpha(0)
    end
  end
  frame.Portrait = { Update = UpdatePortrait }

  frame:RegisterEvent("PLAYER_TARGET_CHANGED")
  frame:RegisterEvent("PLAYER_ENTERING_WORLD")
  frame:SetScript("OnEvent", function(self, event) UpdatePortrait() end)

  C_Timer.After(0.1, function()
    UpdatePortrait()
    if rOrbsDB and rOrbsDB.targetPortraitShow == false then
      frame:Hide()
    end
  end)

  return frame
end

---------------------------------------------
-- INIT
---------------------------------------------

local function Init()
  -- Portrait-Orb deaktiviert: der Ziel-Orb (rOrbsTargetHealthFrame) ersetzt diese Funktion.
  -- HideBlizzardTargetFrame() wird weiterhin aufgerufen damit Blizzards Standard-Frame weg bleibt.
  cfg = ns.cfg
  ns:RegisterInit(function()
    HideBlizzardTargetFrame()
    -- rOrbsTargetFrame wird nicht mehr erstellt.
    local f = _G["rOrbsTargetFrame"]
    if f then
      f:UnregisterAllEvents()
      f:Hide()
      f:SetParent(nil)
      _G["rOrbsTargetFrame"] = nil
    end
  end)
end

ns:RegisterInit(Init)
