local ADDON_NAME = ...
local PvPScout = CreateFrame("Frame")
PvPScout:SetScript("OnEvent", function(self, event, ...)
  if self[event] then
    self[event](self, ...)
  end
end)

PvPScout:RegisterEvent("ADDON_LOADED")
PvPScout:RegisterEvent("PLAYER_LOGIN")

local function InitSavedVariables()
  if not PvPScoutDB then
    PvPScoutDB = {
      enabled = true,
      region = nil, -- auto-detect from client
      brackets = { "2v2", "3v3", "shuffle", "rbg", "blitz" },
      bracketOrder = { "2v2", "3v3", "shuffle", "rbg", "blitz" },
      showRank = true,
      color = { r = 1, g = 0.82, b = 0 }, -- gold
        -- UI/tooltip options
        showHeader = true,
        showUpdatedAt = true,
        colorByRating = true,
        staleHours = 24,
        showTrend = false,
    -- compatibility
    compatTooltipHook = false,
        -- minimap
        showMinimap = true,
        minimapPos = 45,
        -- local history for simple trend calculations (per character key and bracket)
        history = {}, -- [key][bracket] = { {ts=unix, rating=number}, ... }
    }
  else
    -- Migrations: ensure new fields exist
    PvPScoutDB.bracketOrder = PvPScoutDB.bracketOrder or { "2v2", "3v3", "shuffle", "rbg", "blitz" }
    if PvPScoutDB.showHeader == nil then PvPScoutDB.showHeader = true end
    if PvPScoutDB.showUpdatedAt == nil then PvPScoutDB.showUpdatedAt = true end
    if PvPScoutDB.colorByRating == nil then PvPScoutDB.colorByRating = true end
    if not PvPScoutDB.staleHours then PvPScoutDB.staleHours = 24 end
    if PvPScoutDB.showTrend == nil then PvPScoutDB.showTrend = false end
  if PvPScoutDB.compatTooltipHook == nil then PvPScoutDB.compatTooltipHook = false end
    if PvPScoutDB.showMinimap == nil then PvPScoutDB.showMinimap = true end
    if not PvPScoutDB.minimapPos then PvPScoutDB.minimapPos = 45 end
    PvPScoutDB.history = PvPScoutDB.history or {}
  end
end

function PvPScout:ADDON_LOADED(name)
  local _ = self -- silence luacheck: unused self
  if name ~= ADDON_NAME then return end
  InitSavedVariables()
end

function PvPScout:PLAYER_LOGIN()
  local _ = self -- silence luacheck: unused self
  -- Determine region by realm list
  local realmList = GetCVar("portal")
  -- Possible values: US, EU, KR, TW, CN (CN unsupported for BNet API)
  if realmList and realmList ~= "" then
    PvPScoutDB.region = PvPScoutDB.region or string.lower(realmList)
  end

  -- Apply minimap visibility if button exists
  if PvPScout_MinimapButton then
    if PvPScoutDB.showMinimap == false then PvPScout_MinimapButton:Hide() else PvPScout_MinimapButton:Show() end
  end

  -- Startup message (English)
  local ver = tostring((GetAddOnMetadata and GetAddOnMetadata(ADDON_NAME, "Version")) or "")
  local brackets = PvPScoutDB.brackets or {"2v2","3v3"}
  local bracketStr = table.concat(brackets, ", ")
  local mini = (PvPScoutDB.showMinimap ~= false) and "shown" or "hidden"
  print(string.format("PvPScout %s loaded — settings via /pvpscout — minimap: %s — brackets: %s", ver, mini, bracketStr))

  -- Make sure slash to open AddOns pane exists as alternative navigation
  _G.SLASH_PVPSCOUTADDONS1 = "/pvpscoutaddons"
  SlashCmdList["PVPSCOUTADDONS"] = function()
    if Settings and SettingsPanel and SettingsPanel.OpenToCategory then
      SettingsPanel.OpenToCategory("AddOns")
    elseif InterfaceOptionsFrame_OpenToCategory then
      InterfaceOptionsFrame_OpenToCategory("InterfaceOptionsFrameAddOnsList")
    end
  end

  -- Snapshot current player's ratings once per login (for local 7-day trend)
  local function normalizeRealm(realm)
    if not realm or realm == "" then return realm end
    return realm:gsub("[%'%-%s]", "")
  end
  local function makeKey(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 name, realm = UnitName("player")
  local key = makeKey(name, realm)
  local region = PvPScoutDB and PvPScoutDB.region
  local data = PvPScoutData and PvPScoutData.data and region and PvPScoutData.data[region]
  if key and data then
    PvPScoutDB.history[key] = PvPScoutDB.history[key] or {}
    local now = type(_G.time) == "function" and _G.time() or 0
    for _, bracket in ipairs({"2v2","3v3","shuffle","rbg","blitz"}) do
      local v = data[bracket] and data[bracket][key]
      if v and v.rating then
        local list = PvPScoutDB.history[key][bracket] or {}
        table.insert(list, { ts = now, rating = tonumber(v.rating) or 0 })
        -- prune entries older than ~14 days and cap length to 50
        local cutoff = now - (14 * 86400)
        local j = 1
        while j <= #list do
          if (list[j].ts or 0) < cutoff then table.remove(list, j) else j = j + 1 end
        end
        while #list > 50 do table.remove(list, 1) end
        PvPScoutDB.history[key][bracket] = list
      end
    end
  end
end

-- Public API
_G.PvPScout = PvPScout
