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
    -- Default is visible when unset (nil); only hide when explicitly false
    if PvPScoutDB["bracket_"..b.key] ~= false then table.insert(selected, b.key) end
  end
  if #selected == 0 then
    -- If user hid everything, keep it empty: tooltip will show header only
    selected = {}
  end
  PvPScoutDB.brackets = selected
end

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

  -- Scroll container to avoid content running off-screen
  local scroll = CreateFrame("ScrollFrame", ADDON_NAME.."OptionsScroll", panel, "UIPanelScrollFrameTemplate")
  scroll:SetPoint("TOPLEFT", 0, -8)
  scroll:SetPoint("BOTTOMRIGHT", -28, 8) -- leave room for scrollbar
  local container = CreateFrame("Frame", nil, scroll)
  container:SetSize(680, 1) -- width constrained, height will grow with content
  scroll:SetScrollChild(container)

  -- Title
  local icon = container:CreateTexture(nil, "ARTWORK")
  icon:SetPoint("TOPLEFT", 16, -12)
  icon:SetSize(24, 24)
  icon:SetTexture("Interface\\AddOns\\PvPScout\\Media\\pvp_scout_icon_final.blp")

  local title = container:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
  title:SetPoint("LEFT", icon, "RIGHT", 8, 0)
  title:SetText(PvPScout_L("SETTINGS_TITLE"))

  local subtitle = container:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
  subtitle:SetPoint("TOPLEFT", icon, "BOTTOMLEFT", 0, -6)
  subtitle:SetWidth(640)
  subtitle:SetJustifyH("LEFT")
  subtitle:SetText(PvPScout_L("SETTINGS_SUBTITLE"))

  -- Helper: autosize buttons to their text so labels don't overflow
  local function AutosizeButton(btn, minWidth)
    if not (btn and btn.SetWidth and btn.GetText) then return end
    local text = btn:GetText() or ""
    btn:SetWidth(math.max(minWidth or 80, (btn.Text and btn.Text:GetStringWidth() or btn:GetFontString() and btn:GetFontString():GetStringWidth() or #text * 6) + 24))
  end

  -- Create single-column layout; informational section will be appended at the bottom
  local leftAnchor = CreateFrame("Frame", nil, container)
  leftAnchor:SetSize(640, 1)
  leftAnchor:SetPoint("TOPLEFT", subtitle, "BOTTOMLEFT", 0, -12)

  local secGeneral = container:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  secGeneral:SetPoint("TOPLEFT", leftAnchor, "TOPLEFT", 0, 0)
  secGeneral:SetText(PvPScout_L("SECTION_GENERAL"))

  local enabled = CreateFrame("CheckButton", nil, container, "InterfaceOptionsCheckButtonTemplate")
  enabled.Text:SetText(PvPScout_L("ENABLE"))
  enabled:SetPoint("TOPLEFT", secGeneral, "BOTTOMLEFT", 0, -8)
  enabled:SetChecked(PvPScoutDB.enabled)
  enabled.Text:SetJustifyH("LEFT")
  enabled.Text:SetWidth(600)
  enabled:SetScript("OnClick", function(self)
    PvPScoutDB.enabled = self:GetChecked()
  end)

  -- Show rank
  local secDisplay = container:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  secDisplay:SetPoint("TOPLEFT", enabled, "BOTTOMLEFT", 0, -12)
  secDisplay:SetText(PvPScout_L("SECTION_DISPLAY"))

  local showRank = CreateFrame("CheckButton", nil, container, "InterfaceOptionsCheckButtonTemplate")
  showRank.Text:SetText(PvPScout_L("SHOW_RANK"))
  showRank:SetPoint("TOPLEFT", secDisplay, "BOTTOMLEFT", 0, -8)
  showRank:SetChecked(PvPScoutDB.showRank)
  showRank.Text:SetJustifyH("LEFT")
  showRank.Text:SetWidth(600)
  showRank:SetScript("OnClick", function(self)
    PvPScoutDB.showRank = self:GetChecked()
  end)

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

  -- Minimap icon visibility
  local showMinimap = CreateFrame("CheckButton", nil, container, "InterfaceOptionsCheckButtonTemplate")
  showMinimap.Text:SetText(PvPScout_L("SHOW_MINIMAP"))
  showMinimap:SetPoint("TOPLEFT", showTrend, "BOTTOMLEFT", 0, -8)
  showMinimap:SetChecked(PvPScoutDB.showMinimap ~= false)
  showMinimap.Text:SetJustifyH("LEFT")
  showMinimap.Text:SetWidth(600)
  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, container, "UIPanelButtonTemplate")
  resetMinimap:SetText(PvPScout_L("RESET_MINIMAP"))
  -- Place the action button to the right of the long label so it doesn't cover text
  resetMinimap:ClearAllPoints()
  resetMinimap:SetPoint("LEFT", showMinimap.Text, "RIGHT", 16, 0)
  AutosizeButton(resetMinimap, 120)
  resetMinimap:SetScript("OnClick", function()
    PvPScoutDB.minimapPos = 45
    if type(_G.PvPScout_UpdateMinimapButtonPosition) == "function" then _G.PvPScout_UpdateMinimapButtonPosition() end
  end)

  -- Bracket toggles
  local header = container: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, container, "InterfaceOptionsCheckButtonTemplate")
    cb.Text:SetText(b.label)
    cb:SetPoint("TOPLEFT", last, "BOTTOMLEFT", 0, -6)
    cb.Text:SetJustifyH("LEFT")
  cb.Text:SetWidth(560)
    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]
    -- Default visible when unset
    cb:SetChecked(stored ~= false and (initial or stored ~= false))
    cb:SetScript("OnClick", function(self)
      PvPScoutDB["bracket_"..b.key] = self:GetChecked()
      SaveSelectedBrackets()
    end)
    -- Up/Down buttons for order (use standard scroll button templates for professional look)
    local up = CreateFrame("Button", nil, container, "UIPanelScrollUpButtonTemplate")
    up:SetSize(20, 20)
    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:", PvPScout_L("BRACKET_ORDER_UPDATED"))
    end)
    local down = CreateFrame("Button", nil, container, "UIPanelScrollDownButtonTemplate")
    down:SetSize(20, 20)
    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:", PvPScout_L("BRACKET_ORDER_UPDATED"))
    end)
    last = cb
  end

  -- Footer hint
  -- Header/Updated/Color toggles and staleHours slider
  local secData = container:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  secData:SetPoint("TOPLEFT", last, "BOTTOMLEFT", 0, -16)
  secData:SetText(PvPScout_L("SECTION_DATA"))

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

  local su = CreateFrame("CheckButton", nil, container, "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)

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

  local staleLabel = container:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  -- Add a bit more spacing so the label/value never overlap
  staleLabel:SetPoint("TOPLEFT", cr, "BOTTOMLEFT", 0, -16)
  staleLabel:SetText(PvPScout_L("STALE_HOURS"))

  local slider = CreateFrame("Slider", nil, container, "OptionsSliderTemplate")
  -- Increase gap to avoid the value text touching the label
  slider:SetPoint("TOPLEFT", staleLabel, "BOTTOMLEFT", 0, -12)
  slider:SetMinMaxValues(1, 72)
  slider:SetValueStep(1)
  slider:SetObeyStepOnDrag(true)
  slider:SetWidth(260)
  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')
    -- Move the numeric value to the right of the slider to prevent any overlap with the label above
    slider.Text:ClearAllPoints()
    slider.Text:SetPoint("LEFT", slider, "RIGHT", 8, 0)
  end

  local hint = container: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, container, "UIPanelButtonTemplate")
  reloadBtn:SetText(PvPScout_L("RELOAD_UI"))
  -- Place it next to the slider/value instead of far on the right of the hint text
  reloadBtn:ClearAllPoints()
  reloadBtn:SetPoint("LEFT", slider.Text or slider, "RIGHT", 12, 0)
  AutosizeButton(reloadBtn, 120)
  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 = container: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 = container:CreateFontString(nil, "ARTWORK", "GameFontDisableSmall")
  staleExplain:SetPoint("TOPLEFT", updatedText, "BOTTOMLEFT", 0, -6)
  staleExplain:SetText(PvPScout_L("STALE_EXPLAIN"))

  -- Informational section (bottom): Legend, Preview, Visibility notes
  local infoSectionTitle = container:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  infoSectionTitle:SetPoint("TOPLEFT", staleExplain, "BOTTOMLEFT", 0, -16)
  infoSectionTitle:SetText(PvPScout_L("LEGEND_TITLE"))

  local function addLegendRow(anchor, offsetY, r, g, b, text)
    local yAnchor = anchor
    local leftOffset = 0
    if r and g and b then
      local swatch = container:CreateTexture(nil, "ARTWORK")
      swatch:SetSize(12, 12)
      swatch:SetColorTexture(r, g, b, 1)
      swatch:SetPoint("TOPLEFT", anchor, "BOTTOMLEFT", 0, offsetY)
      yAnchor = swatch
      leftOffset = 6
    end
    local lbl = container:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
    lbl:SetPoint("LEFT", yAnchor, "RIGHT", leftOffset, r and 0 or offsetY)
    if not r then
      -- when no swatch is provided, also anchor TOPLEFT for vertical placement
      lbl:ClearAllPoints()
      lbl:SetPoint("TOPLEFT", anchor, "BOTTOMLEFT", 0, offsetY)
    end
    lbl:SetText(text)
    return lbl
  end

  local legend1 = addLegendRow(infoSectionTitle, -8, 1.00, 0.50, 0.00, PvPScout_L("LEGEND_TOP001"))
  local legend2 = addLegendRow(legend1, -6, 0.64, 0.21, 0.93, PvPScout_L("LEGEND_GE_2400"))
  local legend3 = addLegendRow(legend2, -6, 0.78, 0.78, 0.78, PvPScout_L("LEGEND_GE_2100"))
  local legend4 = addLegendRow(legend3, -6, 0.00, 0.44, 0.87, PvPScout_L("LEGEND_GE_1800"))
  local legend5 = addLegendRow(legend4, -6, 0.12, 1.00, 0.00, PvPScout_L("LEGEND_LT_1800"))
  -- Final legend entry: use the dash placeholder to indicate no data available (no color swatch)
  local legend6 = addLegendRow(legend5, -6, nil, nil, nil, PvPScout_L("LEGEND_NO_DATA_DASH"))

  -- Preview section: show a small mock tooltip using current settings
  local previewTitle = container:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  previewTitle:SetPoint("TOPLEFT", legend6, "BOTTOMLEFT", 0, -12)
  previewTitle:SetText(PvPScout_L("PREVIEW_TITLE"))

  local previewBox = CreateFrame("Frame", nil, container, "TooltipBackdropTemplate")
  previewBox:SetPoint("TOPLEFT", previewTitle, "BOTTOMLEFT", 0, -6)
  previewBox:SetSize(320, 120)
  if previewBox.SetBackdrop then
    previewBox:SetBackdrop({ bgFile = "Interface/Tooltips/UI-Tooltip-Background", edgeFile = "Interface/Tooltips/UI-Tooltip-Border", tile = true, tileSize = 16, edgeSize = 16, insets = { left = 4, right = 4, top = 4, bottom = 4 } })
    previewBox:SetBackdropColor(0, 0, 0, 0.8)
  end

  local rowLeft, rowRight = {}, {}
  local function ensureRow(i)
    if rowLeft[i] then return end
  rowLeft[i] = previewBox:CreateFontString(nil, "ARTWORK", "GameFontHighlight")
  rowRight[i] = previewBox:CreateFontString(nil, "ARTWORK", "GameFontHighlight")
    local y = -8 - (i - 1) * 18
    rowLeft[i]:SetPoint("TOPLEFT", previewBox, "TOPLEFT", 10, y)
    rowRight[i]:SetPoint("TOPRIGHT", previewBox, "TOPRIGHT", -10, y)
  end

  local function colorForPreview(r, isTop)
    if not (PvPScoutDB and PvPScoutDB.colorByRating) then return 0.8, 0.8, 0.8 end
    if isTop then return 1.00, 0.50, 0.00 end
    r = tonumber(r) or 0
    if r >= 2400 then return 0.64, 0.21, 0.93 end
    if r >= 2100 then return 0.78, 0.78, 0.78 end
    if r >= 1800 then return 0.00, 0.44, 0.87 end
    return 0.12, 1.00, 0.00
  end

  local function refreshPreview()
    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 samples = {
      { key = "blitz", rating = 2501, rank = 5, isTop = true, trend = "+12" },
      { key = "shuffle", rating = 2410, rank = 200, isTop = false, trend = "+3" },
      { key = "3v3", rating = 2150, rank = 1200, isTop = false, trend = "-8" },
      { key = "2v2", rating = 1830, rank = 3200, isTop = false, trend = "+0" },
      { key = "rbg", rating = 1550, rank = nil, isTop = false, trend = "—" },
    }
    for i = 1, #samples do ensureRow(i) end
    for i, s in ipairs(samples) do
      local left = labels[s.key] or s.key
      local right = tostring(s.rating)
      if PvPScoutDB.showRank then
        if s.rank and s.rank > 0 then right = right .. string.format(" (%s %s)", PvPScout_L("RANK"), s.rank) else right = right .. string.format(" (%s %s)", PvPScout_L("RANK"), PvPScout_L("PLACEHOLDER")) end
      end
      if PvPScoutDB.showTrend then right = right .. string.format("  [%s %s]", PvPScout_L("TREND"), s.trend) end
      rowLeft[i]:SetText(left)
      rowRight[i]:SetText(right)
      local r, g, b = colorForPreview(s.rating, s.isTop)
      rowRight[i]:SetTextColor(r, g, b)
    end
  end
  refreshPreview()

  local refreshBtn = CreateFrame("Button", nil, container, "UIPanelButtonTemplate")
  refreshBtn:SetText(PvPScout_L("PREVIEW_REFRESH"))
  refreshBtn:ClearAllPoints()
  -- Move the button beside the preview box to keep the area below free for explanatory texts
  refreshBtn:SetPoint("LEFT", previewBox, "RIGHT", 12, 0)
  AutosizeButton(refreshBtn, 120)
  refreshBtn:SetScript("OnClick", refreshPreview)

  -- Prominent info: When no data is shown
  local infoTitle = container:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  -- Place safely below the preview box with extra spacing so no text is obscured
  infoTitle:SetPoint("TOPLEFT", previewBox, "BOTTOMLEFT", 0, -16)
  infoTitle:SetText(PvPScout_L("DATA_VISIBILITY_TITLE"))

  local infoText = container:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
  infoText:SetPoint("TOPLEFT", infoTitle, "BOTTOMLEFT", 0, -6)
  infoText:SetText(PvPScout_L("DATA_VISIBILITY_BODY"))
  infoText:SetWidth(380)

  -- Reset buttons
  local resetBtn = CreateFrame("Button", nil, container, "UIPanelButtonTemplate")
  resetBtn:SetText(PvPScout_L("RESET_DEFAULTS"))
  resetBtn:SetPoint("TOPLEFT", infoText, "BOTTOMLEFT", 0, -12)
  AutosizeButton(resetBtn, 140)
  resetBtn:SetScript("OnClick", function()
    -- Reset core settings, keep history
    PvPScoutDB.enabled = true
    PvPScoutDB.region = PvPScoutDB.region -- leave as is or autodetect on login
    PvPScoutDB.brackets = { "2v2", "3v3", "shuffle", "rbg", "blitz" }
    PvPScoutDB.bracketOrder = { "2v2", "3v3", "shuffle", "rbg", "blitz" }
    PvPScoutDB.showRank = true
    PvPScoutDB.showHeader = true
    PvPScoutDB.showUpdatedAt = true
    PvPScoutDB.colorByRating = true
    PvPScoutDB.staleHours = 24
    PvPScoutDB.showTrend = false
    PvPScoutDB.showMinimap = true
    PvPScoutDB.minimapPos = 45
    for _, b in ipairs({"2v2","3v3","shuffle","rbg","blitz"}) do PvPScoutDB["bracket_"..b] = nil end
    if type(_G.PvPScout_UpdateMinimapButtonPosition) == "function" then _G.PvPScout_UpdateMinimapButtonPosition() end
    panel.refresh()
    print("PvPScout:", PvPScout_L("RESET_DONE"))
  end)

  local clearBtn = CreateFrame("Button", nil, container, "UIPanelButtonTemplate")
  clearBtn:SetText(PvPScout_L("CLEAR_HISTORY"))
  clearBtn:SetPoint("LEFT", resetBtn, "RIGHT", 8, 0)
  AutosizeButton(clearBtn, 140)
  clearBtn:SetScript("OnClick", function()
    PvPScoutDB.history = {}
    print("PvPScout:", PvPScout_L("CLEARED_HISTORY"))
  end)

  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)
    cr:SetChecked(PvPScoutDB.colorByRating ~= false)
    slider:SetValue(PvPScoutDB.staleHours or 24)
    refreshUpdated()
    -- refresh bracket checkboxes to reflect DB state
    for _, b in ipairs(BRACKETS_LIST) do
      local checked = (PvPScoutDB["bracket_"..b.key] ~= false)
      for _, child in ipairs({container:GetChildren()}) do
        if child.Text and child.Text.GetText and child.Text:GetText() == b.label and child.SetChecked then
          child:SetChecked(checked)
        end
      end
    end
  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 _G.InCombatLockdown and _G.InCombatLockdown() then
    f:RegisterEvent("PLAYER_REGEN_ENABLED")
    return
  end
  BuildPanel()
end)
