local ADDON_NAME = ...

local BRACKETS_LIST = {
  { key = "2v2", label = PvPScout_L("B2V2") },
  { key = "3v3", label = PvPScout_L("B3V3") },
  { key = "shuffle", label = PvPScout_L("B_SHUFFLE") },
  { key = "rbg", label = PvPScout_L("B_RBG") },
  { key = "blitz", label = PvPScout_L("B_BLITZ") },
}

local function SaveSelectedBrackets()
  local selected = {}
  for _, b in ipairs(BRACKETS_LIST) do
    if PvPScoutDB["bracket_"..b.key] then table.insert(selected, b.key) end
  end
  if #selected == 0 then
    selected = { "2v2", "3v3" } -- enforce at least something visible
  end
  PvPScoutDB.brackets = selected
end

local function BuildPanel()
  local panel = CreateFrame("Frame", ADDON_NAME.."OptionsPanel", InterfaceOptionsFramePanelContainer)
  panel.name = "PvPScout"

  -- Title
  local title = panel:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
  title:SetPoint("TOPLEFT", 16, -16)
  title:SetText(PvPScout_L("SETTINGS_TITLE"))

  -- Enabled
  local enabled = CreateFrame("CheckButton", nil, panel, "InterfaceOptionsCheckButtonTemplate")
  enabled.Text:SetText(PvPScout_L("ENABLE"))
  enabled:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -12)
  enabled:SetChecked(PvPScoutDB.enabled)
  enabled:SetScript("OnClick", function(self)
    PvPScoutDB.enabled = self:GetChecked()
  end)

  -- Show rank
  local showRank = CreateFrame("CheckButton", nil, panel, "InterfaceOptionsCheckButtonTemplate")
  showRank.Text:SetText(PvPScout_L("SHOW_RANK"))
  showRank:SetPoint("TOPLEFT", enabled, "BOTTOMLEFT", 0, -8)
  showRank:SetChecked(PvPScoutDB.showRank)
  showRank:SetScript("OnClick", function(self)
    PvPScoutDB.showRank = self:GetChecked()
  end)

  -- Show trend (7-day delta)
  local showTrend = CreateFrame("CheckButton", nil, panel, "InterfaceOptionsCheckButtonTemplate")
  showTrend.Text:SetText(PvPScout_L("TREND"))
  showTrend:SetPoint("TOPLEFT", showRank, "BOTTOMLEFT", 0, -8)
  showTrend:SetChecked(PvPScoutDB.showTrend)
  showTrend:SetScript("OnClick", function(self)
    PvPScoutDB.showTrend = self:GetChecked()
  end)

  -- Minimap icon visibility
  local showMinimap = CreateFrame("CheckButton", nil, panel, "InterfaceOptionsCheckButtonTemplate")
  showMinimap.Text:SetText(PvPScout_L("SHOW_MINIMAP"))
  showMinimap:SetPoint("TOPLEFT", showTrend, "BOTTOMLEFT", 0, -8)
  showMinimap:SetChecked(PvPScoutDB.showMinimap ~= false)
  showMinimap:SetScript("OnClick", function(self)
    PvPScoutDB.showMinimap = self:GetChecked()
    if PvPScout_MinimapButton then
      if PvPScoutDB.showMinimap then PvPScout_MinimapButton:Show() else PvPScout_MinimapButton:Hide() end
    end
  end)

  -- Reset minimap button position
  local resetMinimap = CreateFrame("Button", nil, panel, "UIPanelButtonTemplate")
  resetMinimap:SetSize(180, 22)
  resetMinimap:SetText(PvPScout_L("RESET_MINIMAP"))
  resetMinimap:SetPoint("LEFT", showMinimap.Text, "RIGHT", 12, 0)
  resetMinimap:SetScript("OnClick", function()
    PvPScoutDB.minimapPos = 45
    if type(_G.PvPScout_UpdateMinimapButtonPosition) == "function" then _G.PvPScout_UpdateMinimapButtonPosition() end
  end)

  -- Bracket toggles
  local header = panel:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  header:SetPoint("TOPLEFT", showMinimap, "BOTTOMLEFT", 0, -14)
  header:SetText(PvPScout_L("BRACKETS_HEADER"))

  local last = header
  for _, b in ipairs(BRACKETS_LIST) do
    local cb = CreateFrame("CheckButton", nil, panel, "InterfaceOptionsCheckButtonTemplate")
    cb.Text:SetText(b.label)
    cb:SetPoint("TOPLEFT", last, "BOTTOMLEFT", 0, -6)
    local initial = false
    if PvPScoutDB.brackets then
      for _, k in ipairs(PvPScoutDB.brackets) do if k == b.key then initial = true break end end
    end
    -- also persist individual checks for UX
    local stored = PvPScoutDB["bracket_"..b.key]
    cb:SetChecked(stored == nil and initial or stored)
    cb:SetScript("OnClick", function(self)
      PvPScoutDB["bracket_"..b.key] = self:GetChecked()
      SaveSelectedBrackets()
    end)
    -- Up/Down buttons for order
    local up = CreateFrame("Button", nil, panel, "UIPanelButtonTemplate")
    up:SetSize(22, 20); up:SetText("^")
    up:SetPoint("LEFT", cb.Text, "RIGHT", 8, 0)
    up:SetScript("OnClick", function()
      local order = PvPScoutDB.bracketOrder or { "2v2","3v3","shuffle","rbg","blitz" }
      local idx
      for i2, k in ipairs(order) do if k == b.key then idx = i2 break end end
      if idx and idx > 1 then
        order[idx], order[idx-1] = order[idx-1], order[idx]
      end
      PvPScoutDB.bracketOrder = order
      -- Recompute selected order used by tooltip rendering
      local selected = {}
      for _, bb in ipairs(BRACKETS_LIST) do if PvPScoutDB["bracket_"..bb.key] ~= false then table.insert(selected, bb.key) end end
      if #selected == 0 then selected = { "2v2","3v3" } end
      PvPScoutDB.brackets = selected
      print("PvPScout: bracket order updated")
    end)
    local down = CreateFrame("Button", nil, panel, "UIPanelButtonTemplate")
    down:SetSize(22, 20); down:SetText("v")
    down:SetPoint("LEFT", up, "RIGHT", 4, 0)
    down:SetScript("OnClick", function()
      local order = PvPScoutDB.bracketOrder or { "2v2","3v3","shuffle","rbg","blitz" }
      local idx
      for i2, k in ipairs(order) do if k == b.key then idx = i2 break end end
      if idx and idx < #order then
        order[idx], order[idx+1] = order[idx+1], order[idx]
      end
      PvPScoutDB.bracketOrder = order
      local selected = {}
      for _, bb in ipairs(BRACKETS_LIST) do if PvPScoutDB["bracket_"..bb.key] ~= false then table.insert(selected, bb.key) end end
      if #selected == 0 then selected = { "2v2","3v3" } end
      PvPScoutDB.brackets = selected
      print("PvPScout: bracket order updated")
    end)
    last = cb
  end

  -- Footer hint
  -- Header/Updated/Color toggles and staleHours slider
  local hc = CreateFrame("CheckButton", nil, panel, "InterfaceOptionsCheckButtonTemplate")
  hc.Text:SetText(PvPScout_L("SHOW_HEADER"))
  hc:SetPoint("TOPLEFT", last, "BOTTOMLEFT", 0, -12)
  hc:SetChecked(PvPScoutDB.showHeader ~= false)
  hc:SetScript("OnClick", function(self) PvPScoutDB.showHeader = self:GetChecked() end)

  local su = CreateFrame("CheckButton", nil, panel, "InterfaceOptionsCheckButtonTemplate")
  su.Text:SetText(PvPScout_L("SHOW_UPDATED"))
  su:SetPoint("TOPLEFT", hc, "BOTTOMLEFT", 0, -8)
  su:SetChecked(PvPScoutDB.showUpdatedAt ~= false)
  su:SetScript("OnClick", function(self) PvPScoutDB.showUpdatedAt = self:GetChecked() end)

  -- Compatible tooltip hook (ElvUI/TipTac)
  local compat = CreateFrame("CheckButton", nil, panel, "InterfaceOptionsCheckButtonTemplate")
  compat.Text:SetText(PvPScout_L("COMPAT_HOOK"))
  compat:SetPoint("TOPLEFT", su, "BOTTOMLEFT", 0, -8)
  compat:SetChecked(PvPScoutDB.compatTooltipHook == true)
  compat:SetScript("OnClick", function(self)
    PvPScoutDB.compatTooltipHook = self:GetChecked()
    print("PvPScout:", PvPScout_L("COMPAT_HOOK_DESC"))
  end)

  local cr = CreateFrame("CheckButton", nil, panel, "InterfaceOptionsCheckButtonTemplate")
  cr.Text:SetText(PvPScout_L("COLOR_BY_RATING"))
  cr:SetPoint("TOPLEFT", compat, "BOTTOMLEFT", 0, -8)
  cr:SetChecked(PvPScoutDB.colorByRating ~= false)
  cr:SetScript("OnClick", function(self) PvPScoutDB.colorByRating = self:GetChecked() end)

  local staleLabel = panel:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  staleLabel:SetPoint("TOPLEFT", cr, "BOTTOMLEFT", 0, -12)
  staleLabel:SetText(PvPScout_L("STALE_HOURS"))

  local slider = CreateFrame("Slider", nil, panel, "OptionsSliderTemplate")
  slider:SetPoint("TOPLEFT", staleLabel, "BOTTOMLEFT", 0, -8)
  slider:SetMinMaxValues(1, 72)
  slider:SetValueStep(1)
  slider:SetObeyStepOnDrag(true)
  slider:SetWidth(200)
  slider:SetValue(PvPScoutDB.staleHours or 24)
  slider:SetScript("OnValueChanged", function(self, value)
    PvPScoutDB.staleHours = math.floor(value)
    if self.Text then self.Text:SetText(PvPScoutDB.staleHours .. 'h') end
  end)
  if slider.Low then slider.Low:SetText('1h') end
  if slider.High then slider.High:SetText('72h') end
  if slider.Text then slider.Text:SetText((PvPScoutDB.staleHours or 24) .. 'h') end

  local hint = panel:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
  hint:SetPoint("TOPLEFT", slider, "BOTTOMLEFT", 0, -10)
  hint:SetText(PvPScout_L("TIP_SLASH"))

  -- Reload UI button for quick apply
  local reloadBtn = CreateFrame("Button", nil, panel, "UIPanelButtonTemplate")
  reloadBtn:SetSize(120, 22)
  reloadBtn:SetText("Reload UI")
  reloadBtn:SetPoint("LEFT", hint, "RIGHT", 12, 0)
  reloadBtn:SetScript("OnClick", function()
    if type(_G.ReloadUI) == "function" then _G.ReloadUI() end
  end)

  -- Last updated and stale explain
  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 updatedText = panel:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
  updatedText:SetPoint("TOPLEFT", hint, "BOTTOMLEFT", 0, -12)
  local function refreshUpdated()
    local updatedAt = (PvPScoutData and PvPScoutData.updatedAt) or 0
    if updatedAt and updatedAt > 0 then
  -- Use WoW globals via _G to satisfy luacheck and avoid bare globals
  local now = type(_G.time) == "function" and _G.time() or 0
  local age = secondsToHuman(now - updatedAt)
  local fmtDate = type(_G.date) == "function" and _G.date or nil
  local abs = fmtDate and fmtDate("%Y-%m-%d %H:%M", updatedAt) or ""
      updatedText:SetText(string.format(PvPScout_L("LAST_UPDATED_LINE"), age, abs))
    else
      updatedText:SetText(PvPScout_L("NO_DATA_YET"))
    end
  end
  refreshUpdated()

  local staleExplain = panel:CreateFontString(nil, "ARTWORK", "GameFontDisableSmall")
  staleExplain:SetPoint("TOPLEFT", updatedText, "BOTTOMLEFT", 0, -6)
  staleExplain:SetText(PvPScout_L("STALE_EXPLAIN"))

  panel.refresh = function()
    enabled:SetChecked(PvPScoutDB.enabled)
    showRank:SetChecked(PvPScoutDB.showRank)
    showTrend:SetChecked(PvPScoutDB.showTrend)
    showMinimap:SetChecked(PvPScoutDB.showMinimap ~= false)
    -- nothing dynamic for reset button
    hc:SetChecked(PvPScoutDB.showHeader ~= false)
    su:SetChecked(PvPScoutDB.showUpdatedAt ~= false)
  compat:SetChecked(PvPScoutDB.compatTooltipHook == true)
    cr:SetChecked(PvPScoutDB.colorByRating ~= false)
    slider:SetValue(PvPScoutDB.staleHours or 24)
    refreshUpdated()
  end

  -- Register options in AddOns category (Dragonflight+), fallback to classic Interface Options
  if Settings and Settings.RegisterCanvasLayoutCategory and Settings.RegisterAddOnCategory then
    local category = Settings.RegisterCanvasLayoutCategory(panel, panel.name)
    Settings.RegisterAddOnCategory(category)
    panel.categoryID = category.ID
  else
    InterfaceOptions_AddCategory(panel)
  end

  _G.PvPScout_OpenOptions = function()
    if Settings and Settings.OpenToCategory then
      Settings.OpenToCategory(panel.categoryID or panel.name)
    elseif InterfaceOptionsFrame_OpenToCategory then
      InterfaceOptionsFrame_OpenToCategory(panel.name)
      InterfaceOptionsFrame_OpenToCategory(panel.name)
    end
  end
end

-- Build panel on login
local f = CreateFrame("Frame")
f:RegisterEvent("PLAYER_LOGIN")
f:SetScript("OnEvent", function()
  if InCombatLockdown() then
    f:RegisterEvent("PLAYER_REGEN_ENABLED")
    return
  end
  BuildPanel()
end)
