local _ = ... -- addon name unused

-- Use Blizzard tracking button proportions precisely to ensure perfect centering
local BUTTON_SIZE = 32 -- default button frame size

-- Compute cursor angle around the minimap center in degrees (WoW-safe)
local function computeAngleDeg(dy, dx)
  -- Prefer WoW's global atan(y, x) if present
  if _G.atan then
    return math.deg(_G.atan(dy, dx))
  end
  if math.atan then
    -- Fallback approximation: atan(y/x) with quadrant correction
    local a = math.deg(math.atan(dy / (dx ~= 0 and dx or 0.0001)))
    if dx < 0 then a = a + 180 end
    return a
  end
  return 0
end

local function UpdateButtonPosition(btn)
  local angle = PvPScoutDB.minimapPos or 45
  local radius = Minimap:GetWidth() / 2 + 5
  local x = math.cos(math.rad(angle)) * radius
  local y = math.sin(math.rad(angle)) * radius
  btn:SetPoint("CENTER", Minimap, "CENTER", x, y)
end

-- Match Blizzard's standard: static tracking border, no dynamic recolor
local function ColorRingByDataAge(btn)
  if not btn or not btn.ring then return end
  btn.ring:SetVertexColor(1, 1, 1, 1)
end

-- Expose a tiny helper so other modules (options) can request a reposition
_G.PvPScout_UpdateMinimapButtonPosition = function()
  if PvPScout_MinimapButton then
    UpdateButtonPosition(PvPScout_MinimapButton)
  end
end

local function CreateMinimapButton()
  if PvPScout_MinimapButton then return PvPScout_MinimapButton end
  local btn = CreateFrame("Button", "PvPScout_MinimapButton", Minimap)
  btn:SetSize(BUTTON_SIZE, BUTTON_SIZE)
  btn:SetFrameStrata("MEDIUM")
  if Minimap.GetFrameLevel then btn:SetFrameLevel(Minimap:GetFrameLevel() + 5) end

  -- Standard circular border using Blizzard's tracking border (perfectly centered)
  local ring = btn:CreateTexture(nil, "BACKGROUND")
  ring:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")
  -- Blizzard uses a 54px tracking border around a 32px button; keep exact dimensions
  ring:SetSize(54, 54)
  ring:SetPoint("CENTER", btn, "CENTER", 0, 0)
  btn.ring = ring

  local tex = btn:CreateTexture(nil, "ARTWORK")
  -- Center the icon precisely; 22px gives a proportion close to Blizzard's tracking icon
  tex:SetPoint("CENTER", btn, "CENTER", 0, 0)
  tex:SetSize(22, 22)
  -- Prefer WoW-native formats (.blp/.tga); fallback to png and finally a fileID
  local base = "Interface\\AddOns\\PvPScout\\Media\\pvp_scout_icon_final"
  tex:SetTexture(base .. ".blp")
  if not tex:GetTexture() then tex:SetTexture(base .. ".tga") end
  if not tex:GetTexture() then tex:SetTexture("Interface\\AddOns\\PvPScout\\Media\\PVPScout_Icon.png") end
  if not tex:GetTexture() then tex:SetTexture(136243) end
  btn.icon = tex

  -- Circular mask like other minimap buttons (reliable alpha mask)
  if tex.AddMaskTexture then
    local mask = btn:CreateMaskTexture(nil, "BACKGROUND")
    mask:SetPoint("CENTER", btn, "CENTER", 0, 0)
    -- Match the icon size so the visible area is perfectly circular within the border
    mask:SetSize(22, 22)
    mask:SetTexture("Interface\\Minimap\\UI-Minimap-Background")
    tex:AddMaskTexture(mask)
  end

  -- No default tracking border; the black ring above provides a centered, neutral frame

  -- Native circular hover highlight
  btn:SetHighlightTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight", "ADD")
  local hl = btn:GetHighlightTexture()
  if hl then hl:ClearAllPoints(); hl:SetPoint("CENTER", btn, "CENTER", 0, 0); hl:SetSize(54, 54) end

  btn:RegisterForClicks("LeftButtonUp", "RightButtonUp")
  btn:RegisterForDrag("LeftButton")

  btn:SetScript("OnDragStart", function(self)
    self:SetScript("OnUpdate", function()
      local mx, my = Minimap:GetCenter()
      local px, py = GetCursorPosition()
      local scale = UIParent:GetEffectiveScale()
      px, py = px / scale, py / scale
      local dy, dx = (py - my), (px - mx)
      local angle = computeAngleDeg(dy, dx)
      PvPScoutDB.minimapPos = angle
      UpdateButtonPosition(self)
    end)
  end)
  btn:SetScript("OnDragStop", function(self)
    self:SetScript("OnUpdate", nil)
  end)
  btn:SetScript("OnShow", function(self)
    UpdateButtonPosition(self)
    ColorRingByDataAge(self)
  end)

  local function showHoverTooltip(self)
    if not GameTooltip then return end
    GameTooltip:SetOwner(self, "ANCHOR_LEFT")
    -- Title
    GameTooltip:AddLine(PvPScout_L("MENU_TITLE"), 1, 0.82, 0)
    -- Action hint
    GameTooltip:AddLine(PvPScout_L("MINIMAP_TIP_LEFT"), 1, 1, 1)
    local order = PvPScoutDB and PvPScoutDB.brackets or { "2v2", "3v3", "shuffle", "rbg", "blitz" }
    local labels = { ["2v2"] = PvPScout_L("B2V2"), ["3v3"] = PvPScout_L("B3V3"), ["shuffle"] = PvPScout_L("B_SHUFFLE"), ["rbg"] = PvPScout_L("B_RBG"), ["blitz"] = PvPScout_L("B_BLITZ") }
    local parts = {}
    for _, k in ipairs(order) do table.insert(parts, labels[k] or k) end
    GameTooltip:AddLine(string.format(PvPScout_L("MINIMAP_TIP_BRACKETS_SETTINGS"), table.concat(parts, ", ")), 0.9, 0.9, 0.9)
    GameTooltip:Show()
  end

  btn:SetScript("OnEnter", function(self)
    ColorRingByDataAge(self)
    showHoverTooltip(self)
  end)
  btn:SetScript("OnLeave", function(_)
    if GameTooltip then GameTooltip:Hide() end
  end)

  local menuFrame = CreateFrame("Frame", "PvPScout_MinimapMenu", UIParent, "UIDropDownMenuTemplate")
  local function showContextMenu(anchor, menu)
    -- Prefer EasyMenu when available
    if type(_G.EasyMenu) == "function" then
      _G.EasyMenu(menu, menuFrame, anchor, 0, 0, "MENU", 2)
      return
    end
    -- Fallback to UIDropDownMenu_* API when EasyMenu isn't present
    if _G.UIDropDownMenu_Initialize and _G.ToggleDropDownMenu and _G.UIDropDownMenu_AddButton then
      -- underscore-prefixed arg marks it intentionally unused for luacheck
      local function initialize(_dropdown, level)
        if not level then return end
        for _, item in ipairs(menu) do
          local info = _G.UIDropDownMenu_CreateInfo and _G.UIDropDownMenu_CreateInfo() or {}
          info.text = item.text
          info.isTitle = item.isTitle
          info.notCheckable = item.notCheckable or item.isTitle or item.isNotRadio
          info.checked = item.checked
          info.func = item.func
          info.isNotRadio = item.isNotRadio
          _G.UIDropDownMenu_AddButton(info, level)
        end
      end
      _G.UIDropDownMenu_Initialize(menuFrame, initialize, "MENU")
      _G.ToggleDropDownMenu(1, nil, menuFrame, anchor, 0, 0)
      return
    end
  -- Last resort: print a simple hint
  print("PvPScout:", PvPScout_L("MENU_UNAVAILABLE"))
  end
  local function toggleBracket(key)
    local checked = PvPScoutDB["bracket_"..key]
    PvPScoutDB["bracket_"..key] = not checked
    -- rebuild selection set for tooltip usage
    local order = PvPScoutDB.bracketOrder or { "2v2", "3v3", "shuffle", "rbg", "blitz" }
    local selected = {}
    for _, k in ipairs(order) do if PvPScoutDB["bracket_"..k] ~= false then table.insert(selected, k) end end
    if #selected == 0 then selected = { "2v2", "3v3" } end
    PvPScoutDB.brackets = selected
  end
  local function openMenu(anchor)
    local menu = {}
    table.insert(menu, { text = PvPScout_L("MENU_TITLE"), isTitle = true, notCheckable = true })
    table.insert(menu, { text = PvPScoutDB.enabled and PvPScout_L("MENU_DISABLE") or PvPScout_L("MENU_ENABLE"), notCheckable = true, func = function()
      PvPScoutDB.enabled = not PvPScoutDB.enabled
      print("PvPScout:", PvPScoutDB.enabled and PvPScout_L("ENABLED") or PvPScout_L("DISABLED"))
    end })
    -- Show/Hide minimap icon
    table.insert(menu, { text = PvPScout_L("MENU_SHOW_MINIMAP"), isNotRadio = true, checked = (PvPScoutDB.showMinimap ~= false), func = function()
      local newVal = (PvPScoutDB.showMinimap == false)
      PvPScoutDB.showMinimap = newVal
      if newVal then anchor:Show() else anchor:Hide() end
    end })
    -- Reset minimap button position
    table.insert(menu, { text = PvPScout_L("MENU_RESET_MINIMAP"), notCheckable = true, func = function()
      PvPScoutDB.minimapPos = 45
      UpdateButtonPosition(anchor)
    end })
    table.insert(menu, { text = PvPScout_L("MENU_SHOW_RANK"), isNotRadio = true, checked = PvPScoutDB.showRank, func = function()
      PvPScoutDB.showRank = not PvPScoutDB.showRank
    end })
    table.insert(menu, { text = PvPScout_L("MENU_SHOW_HEADER"), isNotRadio = true, checked = PvPScoutDB.showHeader, func = function()
      PvPScoutDB.showHeader = not PvPScoutDB.showHeader
    end })
    table.insert(menu, { text = PvPScout_L("MENU_SHOW_UPDATED"), isNotRadio = true, checked = PvPScoutDB.showUpdatedAt, func = function()
      PvPScoutDB.showUpdatedAt = not PvPScoutDB.showUpdatedAt
    end })
    table.insert(menu, { text = PvPScout_L("MENU_BRACKETS"), isTitle = true, notCheckable = true })
    local order = PvPScoutDB.bracketOrder or { "2v2", "3v3", "shuffle", "rbg", "blitz" }
    local labels = { ["2v2"] = PvPScout_L("B2V2"), ["3v3"] = PvPScout_L("B3V3"), ["shuffle"] = PvPScout_L("B_SHUFFLE"), ["rbg"] = PvPScout_L("B_RBG"), ["blitz"] = PvPScout_L("B_BLITZ") }
    for _, k in ipairs(order) do
      table.insert(menu, {
        text = labels[k] or k,
        isNotRadio = true,
        checked = (PvPScoutDB["bracket_"..k] ~= false),
        func = function() toggleBracket(k) end
      })
    end
    table.insert(menu, { text = PvPScout_L("MENU_OPEN_SETTINGS"), notCheckable = true, func = function()
      if type(PvPScout_OpenOptions) == "function" then PvPScout_OpenOptions() end
    end })
    -- Share to chat (compact bracket lines)
    table.insert(menu, { text = PvPScout_L("MENU_SHARE_CHAT"), notCheckable = true, func = function()
      local region = PvPScoutDB and PvPScoutDB.region
      local data = PvPScoutData and PvPScoutData.data and region and PvPScoutData.data[region]
      if not data then return end
      local selected = PvPScoutDB and PvPScoutDB.brackets or { "2v2", "3v3", "shuffle", "rbg", "blitz" }
  local shareLabels = { ["2v2"] = PvPScout_L("B2V2"), ["3v3"] = PvPScout_L("B3V3"), ["shuffle"] = PvPScout_L("B_SHUFFLE"), ["rbg"] = PvPScout_L("B_RBG"), ["blitz"] = PvPScout_L("B_BLITZ") }
      local function unitKeyFromTarget()
        local unit = "target"
        if not UnitExists(unit) or not UnitIsPlayer(unit) then return nil, nil end
        local name, realm = UnitName(unit)
        if not name or name == "" then return nil, nil end
        local r = realm and realm ~= "" and realm or GetNormalizedRealmName()
        if not r or r == "" then return nil, nil end
        r = r:gsub("[%'%-%s]", "")
        return name.."-"..r, name
      end
      local key, disp = unitKeyFromTarget()
      if not key then return end
      local parts = {}
      for _, k in ipairs(selected) do
        local v = data[k] and data[k][key]
        if v then
          local s = (shareLabels[k] or k)..": "..tostring(v.rating)
          if PvPScoutDB.showRank then
            local rankNum = tonumber(v.rank)
            if rankNum and rankNum > 0 then
              s = s .. " ("..PvPScout_L("RANK").." "..rankNum..")"
            else
              s = s .. " ("..PvPScout_L("RANK").." "..PvPScout_L("PLACEHOLDER")..")"
            end
          end
          table.insert(parts, s)
        end
      end
      if #parts > 0 then
        local msg = string.format("PvPScout %s  %s", disp or "", table.concat(parts, " | "))
        if _G.ChatEdit_InsertLink and _G.ChatEdit_ChooseBoxForSend then
          local editBox = _G.ChatEdit_ChooseBoxForSend()
          if editBox then _G.ChatEdit_InsertLink(msg) end
        else
          print(msg)
        end
      end
    end })
    showContextMenu(anchor, menu)
  end

  btn:SetScript("OnClick", function(self, button)
    if button == "RightButton" then
      openMenu(self)
    else
      if type(PvPScout_OpenOptions) == "function" then
        PvPScout_OpenOptions()
      elseif Settings and SettingsPanel and SettingsPanel.OpenToCategory then
        SettingsPanel.OpenToCategory("AddOns")
      elseif Settings and Settings.OpenToCategory then
        Settings.OpenToCategory("PvPScout")
      elseif InterfaceOptionsFrame_OpenToCategory then
        InterfaceOptionsFrame_OpenToCategory("PvPScout"); InterfaceOptionsFrame_OpenToCategory("PvPScout")
      end
    end
  end)

  UpdateButtonPosition(btn)
  if PvPScoutDB.showMinimap == false then btn:Hide() else btn:Show() end
  return btn
end

local f = CreateFrame("Frame")
f:RegisterEvent("PLAYER_LOGIN")
f:SetScript("OnEvent", function() CreateMinimapButton() end)
