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 parts = { PvPScout_L("TITLE_BRACKET_RATING"), string.upper(region) }
    if season and season > 0 then table.insert(parts, "S"..tostring(season)) end
    local header = table.concat(parts, " — ")
    if PvPScoutDB.showUpdatedAt then
      local updatedAt = (PvPScoutData and PvPScoutData.updatedAt) or 0
      if updatedAt > 0 then
        local now = type(_G.time) == "function" and _G.time() or 0
        local age = secondsToHuman(now - 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 now2 = type(_G.time) == "function" and _G.time() or 0
      local ageSecs = now2 - updatedAt
      if ageSecs > staleH * 3600 then
        tooltip:AddLine(PvPScout_L("STALE_NOTICE"), 1, 0.2, 0.2)
      end
    end
  end

  local function computeTrendDelta(bracket, currentRating)
    if not (PvPScoutDB and PvPScoutDB.showTrend) then return nil end
    if not PvPScoutDB.history or not key then return PvPScout_L("TREND_PLACEHOLDER") end
    local list = PvPScoutDB.history[key] and PvPScoutDB.history[key][bracket]
    if not list or #list == 0 then return PvPScout_L("TREND_PLACEHOLDER") end
    local now = type(_G.time) == "function" and _G.time() or 0
    local cutoff = now - (7 * 86400)
    local oldest
    for i = 1, #list do
      if (list[i].ts or 0) >= cutoff then oldest = list[i]; break end
    end
    if not oldest then oldest = list[1] end
    local base = tonumber(oldest.rating) or 0
    local delta = (tonumber(currentRating) or 0) - base
    if delta == 0 then return "+0" end
    if delta > 0 then return "+" .. tostring(delta) end
    return tostring(delta) -- negative already has '-'
  end

  for _, bracket in ipairs(brackets) do
    local v = (not noDataMode) and (data[bracket] and data[bracket][key]) or nil
    local label = labels[bracket] or bracket
    if v then
      local rating = tonumber(v.rating) or 0
      local value = tostring(rating)
      if PvPScoutDB and PvPScoutDB.showRank then
        local rankNum = tonumber(v.rank)
        if rankNum and rankNum > 0 then
          value = value .. string.format(" (%s %s)", PvPScout_L("RANK"), rankNum)
        else
          -- Rank placeholder when rating exists but rank is missing/non-positive
          value = value .. string.format(" (%s %s)", PvPScout_L("RANK"), PvPScout_L("PLACEHOLDER"))
        end
      end
      local trend = computeTrendDelta(bracket, rating)
      if trend then
        value = value .. string.format("  [%s %s]", PvPScout_L("TREND"), trend)
      end
      local vr, vg, vb = ratingColor(rating)
      tooltip:AddDoubleLine(label, value, 1, 1, 1, vr, vg, vb)
      added = true
    else
      -- No ladder data for this bracket: still honor placeholder parity for rank/trend when toggled
      local value = PvPScout_L("PLACEHOLDER")
      if PvPScoutDB and PvPScoutDB.showRank then
        value = value .. string.format(" (%s %s)", PvPScout_L("RANK"), PvPScout_L("PLACEHOLDER"))
      end
      if PvPScoutDB and PvPScoutDB.showTrend then
        value = value .. string.format("  [%s %s]", PvPScout_L("TREND"), PvPScout_L("TREND_PLACEHOLDER"))
      end
      tooltip:AddDoubleLine(label, value, 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

local function SetupTooltipHook()
  if _G.PvPScout_TooltipHooked then return end
  local compat = PvPScoutDB and PvPScoutDB.compatTooltipHook
  if compat and _G.hooksecurefunc and GameTooltip then
    _G.hooksecurefunc(GameTooltip, "SetUnit", function(self)
      OnTooltipSetUnit(self)
    end)
    _G.PvPScout_TooltipHooked = true
    return
  end
  -- Default: Dragonflight API or classic fallback
  if TooltipDataProcessor and TooltipDataProcessor.AddTooltipPostCall and Enum and Enum.TooltipDataType then
    TooltipDataProcessor.AddTooltipPostCall(Enum.TooltipDataType.Unit, function(tooltip)
      OnTooltipSetUnit(tooltip)
    end)
    _G.PvPScout_TooltipHooked = true
  elseif GameTooltip and GameTooltip.HookScript and GameTooltip:HasScript("OnTooltipSetUnit") then
    GameTooltip:HookScript("OnTooltipSetUnit", OnTooltipSetUnit)
    _G.PvPScout_TooltipHooked = true
  end
end

-- Defer hook until login to ensure SavedVariables are ready
local hookFrame = CreateFrame("Frame")
hookFrame:RegisterEvent("PLAYER_LOGIN")
hookFrame:SetScript("OnEvent", function()
  SetupTooltipHook()
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 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
        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
