local _ = ... -- addon name unused

local function normalizeRealm(realm)
  if not realm or realm == "" then return realm end
  return realm:gsub("[%'%-%s]", "")
end

local function unitKey(name, realm)
  if not name or name == "" then return nil end
  realm = realm and realm ~= "" and normalizeRealm(realm) or GetNormalizedRealmName()
  if not realm or realm == "" then return nil end
  return name .. "-" .. realm
end

local function getRegion()
  local region = PvPScoutDB and PvPScoutDB.region
  if region and region ~= "" then return region end
  local portal = GetCVar("portal")
  return portal and string.lower(portal) or "eu"
end

local function ratingColor(r)
  if not (PvPScoutDB and PvPScoutDB.colorByRating) then
    local c = (PvPScoutDB and PvPScoutDB.color) or { r = 1, g = 0.82, b = 0 }
    return c.r, c.g, c.b
  end
  r = tonumber(r) or 0
  if r >= 2400 then return 1.00, 0.80, 0.00 end -- gold
  if r >= 2100 then return 1.00, 0.50, 0.00 end -- orange
  if r >= 1800 then return 0.64, 0.21, 0.93 end -- purple
  if r >= 1600 then return 0.00, 0.44, 0.87 end -- blue
  if r >= 1400 then return 0.12, 1.00, 0.00 end -- green
  return 1, 1, 1 -- white
end

local function secondsToHuman(secs)
  secs = math.max(0, math.floor(secs or 0))
  local d = math.floor(secs / 86400); secs = secs % 86400
  local h = math.floor(secs / 3600); secs = secs % 3600
  local m = math.floor(secs / 60)
  if d > 0 then return string.format("%dd %dh", d, h) end
  if h > 0 then return string.format("%dh %dm", h, m) end
  return string.format("%dm", m)
end

local function addRatingLines(tooltip, key)
  if not key then return end
  local region = getRegion()
  local data = PvPScoutData and PvPScoutData.data and PvPScoutData.data[region]
  local noDataMode = not data

  local selected = PvPScoutDB and PvPScoutDB.brackets or { "2v2", "3v3", "shuffle", "rbg", "blitz" }
  local order = (PvPScoutDB and PvPScoutDB.bracketOrder) or selected
  local inSet = {}
  for _, k in ipairs(selected) do inSet[k] = true end
  local brackets = {}
  for _, k in ipairs(order) do if inSet[k] then table.insert(brackets, k) end end
  if #brackets == 0 then brackets = selected end

  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 added = false

  if PvPScoutDB and PvPScoutDB.showHeader then
    local season = PvPScoutData and PvPScoutData.season or 0
    local header = string.format("PvPScout — %s — S%s", string.upper(region), season)
    if PvPScoutDB.showUpdatedAt then
      local updatedAt = (PvPScoutData and PvPScoutData.updatedAt) or 0
      if updatedAt > 0 then
    local age = secondsToHuman(time() - updatedAt)
    header = header .. string.format(" — %s", string.format(PvPScout_L("UPDATED_AGO"), age))
      end
    end
    tooltip:AddLine(header, 1, 0.82, 0)
    added = true
    local staleH = (PvPScoutDB and PvPScoutDB.staleHours) or 24
    local updatedAt = (PvPScoutData and PvPScoutData.updatedAt) or 0
    if updatedAt > 0 and staleH and staleH > 0 then
      local ageSecs = time() - updatedAt
      if ageSecs > staleH * 3600 then
        tooltip:AddLine(PvPScout_L("STALE_NOTICE"), 1, 0.2, 0.2)
      end
    end
  end

  for _, bracket in ipairs(brackets) do
    local v = (not noDataMode) and (data[bracket] and data[bracket][key]) or nil
    if v then
      local label = labels[bracket] or bracket
      local value = tostring(v.rating or 0)
      if PvPScoutDB and PvPScoutDB.showRank and v.rank then
        value = value .. string.format(" (Rank %s)", v.rank)
      end
      local vr, vg, vb = ratingColor(v.rating)
      tooltip:AddDoubleLine(label, value, 1, 1, 1, vr, vg, vb)
      added = true
    else
      -- Placeholder when no ladder data is loaded yet
      local label = labels[bracket] or bracket
      local placeholder = PvPScout_L("NO_DATA")
      tooltip:AddDoubleLine(label, placeholder, 1, 1, 1, 0.8, 0.8, 0.8)
      added = true
    end
  end
  if not added then
    tooltip:AddLine(PvPScout_L("NO_DATA"), 0.8, 0.8, 0.8)
    added = true
  end
  if added then tooltip:Show() end
end

local function OnTooltipSetUnit(tooltip)
  if not PvPScoutDB or not PvPScoutDB.enabled then return end
  local _, unit = tooltip:GetUnit()
  if not unit or not UnitIsPlayer(unit) then return end
  local name, realm = UnitName(unit)
  local key = unitKey(name, realm and realm ~= "" and realm or GetNormalizedRealmName())
  addRatingLines(tooltip, key)
end

-- Hook tooltip for unit data (Dragonflight+ uses TooltipDataProcessor; fallback for older clients)
if TooltipDataProcessor and TooltipDataProcessor.AddTooltipPostCall and Enum and Enum.TooltipDataType then
  TooltipDataProcessor.AddTooltipPostCall(Enum.TooltipDataType.Unit, function(tooltip)
    OnTooltipSetUnit(tooltip)
  end)
elseif GameTooltip and GameTooltip.HookScript and GameTooltip:HasScript("OnTooltipSetUnit") then
  GameTooltip:HookScript("OnTooltipSetUnit", OnTooltipSetUnit)
end

-- Slash command: /pvpscout [enable|disable|options]
SLASH_PVPSCOUT1 = "/pvpscout"
SlashCmdList["PVPSCOUT"] = function(msg)
  msg = msg and msg:lower() or ""
  if msg:find("disable") then
    PvPScoutDB.enabled = false
    print("PvPScout: disabled")
    return
  elseif msg:find("enable") then
    PvPScoutDB.enabled = true
    print("PvPScout: enabled")
    return
  elseif msg == "" or msg:find("option") then
    if type(PvPScout_OpenOptions) == "function" then
      PvPScout_OpenOptions()
    elseif Settings and Settings.OpenToCategory then
      Settings.OpenToCategory("PvPScout")
    else
      InterfaceOptionsFrame_OpenToCategory("PvPScout"); InterfaceOptionsFrame_OpenToCategory("PvPScout")
    end
    return
  end

  local unit = "target"
  if not UnitExists(unit) or not UnitIsPlayer(unit) then
    print("PvPScout: No player target.")
    return
  end
  local name, realm = UnitName(unit)
  local key = unitKey(name, realm and realm ~= "" and realm or GetNormalizedRealmName())
  local tip = CreateFrame("GameTooltip", "PvPScoutTooltipTemp", UIParent, "GameTooltipTemplate")
  tip:SetOwner(UIParent, "ANCHOR_NONE")
  addRatingLines(tip, key)
  -- Print to chat as well
  local region = getRegion()
  local data = PvPScoutData and PvPScoutData.data and PvPScoutData.data[region]
  if data then
    local labels = { ["2v2"] = "2v2", ["3v3"] = "3v3", ["shuffle"] = "Solo Shuffle", ["rbg"] = "RBG 10v10", ["blitz"] = "Blitz RBG" }
    local function p(bracket)
      local v = data[bracket] and data[bracket][key]
      if v then
        local label = labels[bracket] or bracket
        local s = label..": "..v.rating
        if PvPScoutDB.showRank and v.rank then s = s.." (Rank "..v.rank..")" end
        print("PvPScout:", name, s)
      end
    end
    local selected = PvPScoutDB and PvPScoutDB.brackets or { "2v2", "3v3", "shuffle", "rbg", "blitz" }
    for _, k in ipairs(selected) do p(k) end
  end
end
