local _ = ... -- addon name unused

local BUTTON_SIZE = 28

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

local function ColorRingByDataAge(btn)
  if not btn or not btn.ring then return end
  local staleH = (PvPScoutDB and PvPScoutDB.staleHours) or 24
  local updatedAt = (PvPScoutData and PvPScoutData.updatedAt) or 0
  if not updatedAt or updatedAt == 0 then
    btn.ring:SetVertexColor(0, 0, 0, 1)
    return
  end
  local now = type(_G.time) == "function" and _G.time() or 0
  local age = now - updatedAt
  local warn = staleH * 3600 * 0.8
  local crit = staleH * 3600
  if age < warn then
    -- fresh: greenish ring
    btn.ring:SetVertexColor(0.1, 0.8, 0.1, 1)
  elseif age < crit then
    -- warning: yellow/orange
    btn.ring:SetVertexColor(1.0, 0.7, 0.0, 1)
  else
    -- stale: red
    btn.ring:SetVertexColor(1.0, 0.2, 0.2, 1)
  end
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

  -- Black circular ring behind the icon for a clean, centered border
  local ring = btn:CreateTexture(nil, "BACKGROUND")
  ring:SetTexture("Interface\\CHARACTERFRAME\\TempPortraitAlphaMask")
  ring:SetVertexColor(0, 0, 0, 1)
  ring:SetSize(BUTTON_SIZE + 2, BUTTON_SIZE + 2) -- subtle 1px rim around
  ring:SetPoint("CENTER", btn, "CENTER", 0, 0)
  btn.ring = ring

  local tex = btn:CreateTexture(nil, "ARTWORK")
  tex:SetAllPoints()
  -- 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 portrait alpha mask)
  if tex.AddMaskTexture then
    local mask = btn:CreateMaskTexture(nil, "BACKGROUND")
    mask:SetAllPoints(btn)
    mask:SetTexture("Interface\\CHARACTERFRAME\\TempPortraitAlphaMask")
    tex:AddMaskTexture(mask)
  end

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

  -- Hover highlight glow
  local highlight = btn:CreateTexture(nil, "HIGHLIGHT")
  highlight:SetTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight")
  highlight:SetAllPoints(btn)
  highlight:SetBlendMode("ADD")
  highlight:Hide()
  btn.highlight = highlight

  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)
    if self.highlight then self.highlight:Show() end
    ColorRingByDataAge(self)
    showHoverTooltip(self)
  end)
  btn:SetScript("OnLeave", function(self)
    if self.highlight then self.highlight:Hide() end
    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: menu unavailable on this client")
  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 "enabled" or "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"] = "2v2", ["3v3"] = "3v3", ["shuffle"] = "Solo Shuffle", ["rbg"] = "RBG 10v10", ["blitz"] = "Blitz RBG" }
      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)
