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"

  -- 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"))

  -- Enabled
  local secGeneral = container:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  secGeneral:SetPoint("TOPLEFT", subtitle, "BOTTOMLEFT", 0, -12)
  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: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: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: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: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: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 = 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)
    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, container, "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:", PvPScout_L("BRACKET_ORDER_UPDATED"))
    end)
  local down = CreateFrame("Button", nil, container, "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:", 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")
  staleLabel:SetPoint("TOPLEFT", cr, "BOTTOMLEFT", 0, -12)
  staleLabel:SetText(PvPScout_L("STALE_HOURS"))

  local slider = CreateFrame("Slider", nil, container, "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 = 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:SetSize(120, 22)
  reloadBtn:SetText(PvPScout_L("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 = 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"))

  -- Legend section
  local legendTitle = container:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  legendTitle:SetPoint("TOPLEFT", staleExplain, "BOTTOMLEFT", 0, -12)
  legendTitle:SetText(PvPScout_L("LEGEND_TITLE"))

  local function addLegendRow(anchor, offsetY, r, g, b, text)
    local swatch = container:CreateTexture(nil, "ARTWORK")
    swatch:SetSize(12, 12)
    swatch:SetColorTexture(r, g, b, 1)
    swatch:SetPoint("TOPLEFT", anchor, "BOTTOMLEFT", 0, offsetY)
  local lbl = container:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
    lbl:SetPoint("LEFT", swatch, "RIGHT", 6, 0)
    lbl:SetText(text)
    return lbl
  end

  local legend1 = addLegendRow(legendTitle, -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"))
  local legend6 = addLegendRow(legend5, -6, 0.8, 0.8, 0.8, PvPScout_L("LEGEND_DISABLED_GRAY"))

  -- 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(420, 110)
  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:SetSize(130, 22)
  refreshBtn:SetText(PvPScout_L("PREVIEW_REFRESH"))
  refreshBtn:SetPoint("LEFT", previewBox, "RIGHT", 8, 0)
  refreshBtn:SetScript("OnClick", refreshPreview)

  -- Prominent info: When no data is shown
  local infoTitle = container:CreateFontString(nil, "ARTWORK", "GameFontNormal")
  infoTitle:SetPoint("TOPLEFT", previewBox, "BOTTOMLEFT", 0, -12)
  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(640)

  -- Reset buttons
  local resetBtn = CreateFrame("Button", nil, container, "UIPanelButtonTemplate")
  resetBtn:SetSize(140, 22)
  resetBtn:SetText(PvPScout_L("RESET_DEFAULTS"))
  resetBtn:SetPoint("TOPLEFT", infoText, "BOTTOMLEFT", 0, -12)
  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:SetSize(140, 22)
  clearBtn:SetText(PvPScout_L("CLEAR_HISTORY"))
  clearBtn:SetPoint("LEFT", resetBtn, "RIGHT", 8, 0)
  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)
    specSensitive:SetChecked(PvPScoutDB.specSensitiveShuffle ~= false)
    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()
  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)
