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 TargetFrame then
    TargetFrame:UnregisterAllEvents()
    TargetFrame:Hide()
    TargetFrame:SetAlpha(0)
    TargetFrame:HookScript("OnShow", function(self)
      if not InCombatLockdown() then
        self:Hide()
      end
    end)
  end
end

---------------------------------------------
-- FUNCTIONS
---------------------------------------------

local initUnitParameters = function(self)
  self:SetFrameStrata("LOW")
  self:SetFrameLevel(1)
  self:SetSize(self.cfg.size, self.cfg.size)
  self:SetScale(self.cfg.scale)
  self:SetPoint(self.cfg.pos.a1, self.cfg.pos.af, self.cfg.pos.a2, self.cfg.pos.x, self.cfg.pos.y)
  
  -- SecureUnitButton for click functionality (left-click only = target)
  -- Right-click (togglemenu) is handled by the Target Health Orb
  self:SetAttribute("unit", "target")
  self:SetAttribute("*type1", "target")
  self:RegisterForClicks("AnyUp")
  
  -- Custom Tooltip Handler for Target
  self:SetScript("OnEnter", function(frame)
    if UnitExists("target") then
      GameTooltip:SetOwner(frame, "ANCHOR_RIGHT")
      GameTooltip:SetUnit("target")
      GameTooltip:Show()
    end
  end)
  
  self:SetScript("OnLeave", function(frame)
    GameTooltip:Hide()
  end)
  
  -- Dragging
  func.applyDragFunctionality(self, "target")
end

---------------------------------------------
-- CREATE TARGET ICON (NO oUF)
---------------------------------------------

local function CreateTargetIcon()
  cfg = ns.cfg
  if not cfg.units.target or not cfg.units.target.show then return end
  
  -- Create main frame as SecureUnitButton
  local frame = CreateFrame("Button", "rOrbsTargetFrame", UIParent, "SecureUnitButtonTemplate")
  frame.cfg = cfg.units.target
  
  -- Apply settings
  initUnitParameters(frame)
  
  -- Load saved position and scale from rOrbsDB (after applyDragFunctionality)
  C_Timer.After(0, function()
    local frameName = frame:GetName()
    
    -- Load saved position
    if frameName and rOrbsDB and 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
    
    -- Load saved scale
    if frameName and rOrbsDB and rOrbsDB.frameScales and rOrbsDB.frameScales[frameName] then
      frame:SetScale(rOrbsDB.frameScales[frameName])
    end
  end)
  
  -- Background (transparent)
  frame.bg = frame:CreateTexture(nil, "BACKGROUND", nil, -8)
  frame.bg:SetAllPoints()
  frame.bg:SetColorTexture(0, 0, 0, 0)
  
  -- Portrait holder
  local portraitHolder = CreateFrame("Frame", nil, frame)
  portraitHolder:SetAllPoints()
  portraitHolder:SetFrameLevel(frame:GetFrameLevel() + 2)
  
  -- 3D Portrait Model
  local portrait = CreateFrame("PlayerModel", nil, portraitHolder)
  portrait:SetAllPoints()
  portrait:SetFrameLevel(portraitHolder:GetFrameLevel() + 1)
  portrait:EnableMouse(false)
  
  -- Apply circular mask
  if portrait.SetMask then
    portrait:SetMask(ns.mediapath .. "orb_inverse_mask")
  end
  
  -- Portrait update function
  function portrait:Update()
    if UnitExists("target") then
      self:ClearModel()
      self:SetUnit("target")
      self:SetCamDistanceScale(1)
      self:SetPosition(0, 0, 0)
      self:SetRotation(0)
      self:SetPortraitZoom(0)
      frame:SetAlpha(1)
    else
      self:ClearModel()
      frame:SetAlpha(0.3)
    end
  end
  
  -- Events
  frame:RegisterEvent("PLAYER_TARGET_CHANGED")
  frame:RegisterEvent("PLAYER_ENTERING_WORLD")
  
  frame:SetScript("OnEvent", function(self, event)
    portrait:Update()
  end)
  
  frame:SetScript("OnShow", function(self)
    portrait:Update()
  end)
  
  -- Store portrait reference
  frame.Portrait = portrait
  
  -- Initial update
  C_Timer.After(0.1, function()
    if portrait then
      portrait:Update()
    end
    -- Apply saved visibility setting
    if rOrbsDB and rOrbsDB.targetPortraitShow == false then
      frame:Hide()
    end
  end)
  
  return frame
end

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

local function Init()
  cfg = ns.cfg
  if cfg.units.target and cfg.units.target.show then
    -- Check if target orb is enabled in settings
    if rOrbsDB and rOrbsDB.targetOrbEnabled == false then return end
    ns:RegisterInit(function()
      -- Hide Blizzard Target Frame
      HideBlizzardTargetFrame()
      
      -- Clean up old frame if exists
      local f = _G["rOrbsTargetFrame"]
      if f then
        f:UnregisterAllEvents()
        f:Hide()
        f:SetParent(nil)
        _G["rOrbsTargetFrame"] = nil
      end
      
      -- Create new target icon
      local targetFrame = CreateTargetIcon()
      
      -- Force update after short delay
      C_Timer.After(0.5, function()
        if targetFrame and targetFrame.Portrait then
          targetFrame.Portrait:Update()
        end
      end)
    end)
  end
end

ns:RegisterInit(Init)

