local ADDON_NAME, ns = ...
local WF = ns.WF

WF.UI = WF.UI or {}
WF.UI.HelpPages = WF.UI.HelpPages or {}
WF.UI.HelpPages.OverviewSections = WF.UI.HelpPages.OverviewSections or {}

local Sections = WF.UI.HelpPages.OverviewSections

local RF_EXPANSION_DISPLAY = {
  ["BfA"] = "Battle for Azeroth",
  ["TWW"] = "The War Within",
  ["MoP"] = "Mists of Pandaria",
  ["WoD"] = "Warlords of Draenor",
  ["WotLK"] = "Wrath of the Lich King",
  ["Wrath"] = "Wrath of the Lich King",
  ["Cata"] = "Cataclysm",
  ["DF"] = "Dragonflight",
  ["SL"] = "Shadowlands",
  ["TBC"] = "The Burning Crusade",
  ["BC"] = "The Burning Crusade",
}

local function RF_Trim(v)
  v = tostring(v or "")
  return (v:gsub("^%s+", ""):gsub("%s+$", ""))
end

local function RF_HumanizeLabel(v)
  v = RF_Trim(v)
  if v == "" then return v end
  v = v:gsub("_", " ")
  v = v:gsub("%-", " ")
  v = v:gsub("(%l)(%u)", "%1 %2")
  v = v:gsub("(%a)(%d)", "%1 %2")
  v = v:gsub("(%d)(%a)", "%1 %2")
  v = v:gsub("%s+", " ")
  return v
end

local function RF_AimLabel(Util, v)
  local value = RF_Trim(v)
  if value == "" then value = "Unknown" end
  if Util and Util.PrettyToken then
    return Util:PrettyToken(value)
  end
  return tostring(value)
end

local function RF_ExpansionLabel(v)
  local value = RF_Trim(v)
  if value == "" then value = "Unknown" end
  return RF_EXPANSION_DISPLAY[value] or RF_HumanizeLabel(value)
end

local function RF_BuildExpansionItems(expansions)
  local items = {}
  local src = expansions or {}
  for i = 1, #src do
    local v = tostring(src[i] or "")
    if v ~= "" then
      local display = RF_ExpansionLabel(v)
      local body
      if v == "Any" then
        body = "Show farms from every expansion in the Random Farm pool."
      elseif v == "Unknown" then
        body = "Only show farms that do not have an expansion assigned yet."
      else
        body = "Only show farms from " .. display .. "."
      end
      items[#items + 1] = { text = display, value = v, tooltipTitle = "Expansion", tooltipBody = body }
    end
  end
  return items
end

local function RF_BuildAimItems(WF, Util, farmAims)
  local items = {}
  local seen = {}

  local function add(value, body)
    value = RF_Trim(value)
    if value == "" then value = "Unknown" end
    local key = value:lower()
    if seen[key] then return end
    seen[key] = true
    items[#items + 1] = {
      text = RF_AimLabel(Util, value),
      value = value,
      tooltipTitle = "Aim",
      tooltipBody = body,
    }
  end

  add("Any", "Show every farm aim in the Random Farm pool.")
  add("Unknown", "Only show farms that do not have an aim assigned yet.")

  for i = 1, #(farmAims or {}) do
    local v = tostring(farmAims[i] or "")
    if v ~= "" and v ~= "Any" then
      add(v, "Only show farms aimed at " .. RF_AimLabel(Util, v) .. ".")
    end
  end

  local db = (WF and WF.DB and WF.DB.Get and WF.DB:Get()) or nil
  local farms = (db and db.farms) or nil
  if farms then
    local dynamic = {}
    for _, farm in pairs(farms) do
      if type(farm) == "table" then
        local aim = RF_Trim(farm.aim)
        if aim ~= "" and aim ~= "Any" then
          dynamic[#dynamic + 1] = aim
        end
      end
    end

    table.sort(dynamic, function(a, b)
      return RF_AimLabel(Util, a):lower() < RF_AimLabel(Util, b):lower()
    end)

    for i = 1, #dynamic do
      local v = dynamic[i]
      add(v, "Only show farms aimed at " .. RF_AimLabel(Util, v) .. ".")
    end
  end

  return items
end

function Sections.BuildRandomFarm(ctx, env)
  local UI = env.UI
  local WF = env.WF
  local Widgets = env.Widgets
  local Util = env.Util
  local C4 = env.C4
  local TEXT = env.TEXT
  local MUTED = env.MUTED
  local ACCENT = env.ACCENT
  local rSC = env.rSC
  local MakeSectionTitle = env.MakeSectionTitle
  local MakeMutedText = env.MakeMutedText
  local MakeDivider = env.MakeDivider
  local EnsureSettingsDefaults = env.EnsureSettingsDefaults
  local _WF_ApplyGearOptionButton = env.ApplyGearOptionButton
  local _WF_GearOpt_SetHover = env.GearOptionSetHover
  local _WF_TooltipFlipAboveIfNeeded = env.TooltipFlipAboveIfNeeded
  local _WF_TooltipFollow_Stop = env.TooltipFollowStop
  local self = env.self

    -- Random Farm
    local rfHeader = CreateFrame("Frame", nil, rSC)
    rfHeader:SetPoint("TOPLEFT", 12, -10)
    rfHeader:SetPoint("TOPRIGHT", rSC, "TOPRIGHT", -12, -10)
    rfHeader:SetHeight(20)

    local rTitle = MakeSectionTitle(rfHeader, "Random Farm")
    rTitle:SetPoint("LEFT", 0, 0)

    -- Match Farm Timer options style (small text toggle)
    local rfOptBtn = CreateFrame("Button", nil, rfHeader)
    rfOptBtn:SetSize(64, 18)
    rfOptBtn:SetPoint("RIGHT", 0, 0)

    rfOptBtn.bg = rfOptBtn:CreateTexture(nil, "BACKGROUND")
    rfOptBtn.bg:SetAllPoints(rfOptBtn)
    rfOptBtn.bg:SetTexture("Interface\\Buttons\\WHITE8x8")
    rfOptBtn.bg:SetVertexColor(1, 1, 1, 1)
    rfOptBtn.bg:SetAlpha(0)

    rfOptBtn.txt = rfOptBtn:CreateFontString(nil, "OVERLAY", "WF_GameFontDisableSmall")
    rfOptBtn.txt:SetPoint("CENTER", 0, 0)
    rfOptBtn.txt:SetText("Options")
    do
      local mr, mg, mb = C4(MUTED, MUTED)
      if rfOptBtn.txt then rfOptBtn.txt:SetTextColor(mr, mg, mb, 1) end
    end


    _WF_ApplyGearOptionButton(rfOptBtn)
    rfOptBtn:SetScript("OnEnter", function()
      _WF_GearOpt_SetHover(rfOptBtn, true)
      if GameTooltip then
        if Widgets and Widgets.EnsureTooltipSkin then Widgets:EnsureTooltipSkin() end
        GameTooltip:SetOwner(rfOptBtn, "ANCHOR_RIGHT")
        if GameTooltip.ClearLines then GameTooltip:ClearLines() end
        local ar, ag, ab = C4(ACCENT, ACCENT)
        GameTooltip:AddLine("Random Farm Options", ar, ag, ab)
        GameTooltip:AddLine("Adjust the pool filters used by Random Farm.", TEXT[1], TEXT[2], TEXT[3], true)
        GameTooltip:AddLine("Notification style and sound live in Settings > Notifications.", 0.75, 0.75, 0.75, true)
        GameTooltip:Show()
        _WF_TooltipFlipAboveIfNeeded(self)
      end
    end)
    rfOptBtn:SetScript("OnLeave", function()
      _WF_GearOpt_SetHover(rfOptBtn, false)
      if GameTooltip then GameTooltip:Hide() end
        _WF_TooltipFollow_Stop()
    end)

    local rMeta = MakeMutedText(rSC, "")
    rMeta:SetPoint("TOPLEFT", rfHeader, "BOTTOMLEFT", 0, -8)
    rMeta:SetJustifyH("LEFT")

    local rfOptPanel = CreateFrame("Frame", nil, rSC, "BackdropTemplate")
    rfOptPanel:SetPoint("TOPLEFT", rMeta, "BOTTOMLEFT", 0, -10)
    rfOptPanel:SetPoint("RIGHT", rSC, "RIGHT", -12, 0)
    rfOptPanel:Hide()
    rfOptPanel:SetBackdrop({
      bgFile = "Interface/Buttons/WHITE8x8",
      edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
      edgeSize = 10,
      insets = { left = 3, right = 3, top = 3, bottom = 3 },
    })
    rfOptPanel:SetBackdropColor(0, 0, 0, 0.16)
    rfOptPanel:SetBackdropBorderColor(1, 1, 1, 0.10)

    local function _RF_Ensure()
      if EnsureSettingsDefaults then EnsureSettingsDefaults() end
    end

    local function _RF_Set(key, v)
      _RF_Ensure()
      if WF and WF.DB and WF.DB.SetSetting then
        WF.DB:SetSetting(key, v)
      end
      if UI and UI.RefreshOverview then
        UI:RefreshOverview()
      end
      if UI and UI._UpdateOverviewRightScroll then
        UI:_UpdateOverviewRightScroll()
      end
    end

    local comboAim = ctx.MakeCombo(
      rfOptPanel,
      "Aim",
      function() _RF_Ensure(); if WF and WF.DB and WF.DB.GetSetting then return WF.DB:GetSetting("randomAim") or "Any" end return "Any" end,
      function(v) _RF_Set("randomAim", v) end,
      function() return RF_BuildAimItems(WF, Util, ctx.FARM_AIMS) end
    )

    local comboExp = ctx.MakeCombo(
      rfOptPanel,
      "Expansion",
      function() _RF_Ensure(); if WF and WF.DB and WF.DB.GetSetting then return WF.DB:GetSetting("randomExpansion") or "Any" end return "Any" end,
      function(v) _RF_Set("randomExpansion", v) end,
      function() return RF_BuildExpansionItems(ctx.EXPANSIONS) end
    )

    local comboType = ctx.MakeCombo(
      rfOptPanel,
      "Type",
      function() _RF_Ensure(); if WF and WF.DB and WF.DB.GetSetting then return WF.DB:GetSetting("randomFarmType") or "Any" end return "Any" end,
      function(v) _RF_Set("randomFarmType", v) end,
      function() return ctx.FARM_TYPES end
    )

    comboExp._refresh = function()
      if comboExp and comboExp._txt then
        local value = "Any"
        if WF and WF.DB and WF.DB.GetSetting then
          value = WF.DB:GetSetting("randomExpansion") or "Any"
        end
        comboExp._txt:SetText(RF_ExpansionLabel(value))
      end
    end

    local chkZone = ctx.MakeCheck(
      rfOptPanel,
      "Current zone only",
      function() _RF_Ensure(); if WF and WF.DB and WF.DB.GetSetting then return WF.DB:GetSetting("randomCurrentZoneOnly") end return false end,
      function(v) _RF_Set("randomCurrentZoneOnly", v) end
    )

    local chkUnknown = ctx.MakeCheck(
      rfOptPanel,
      "Include uncategorized farms",
      function() _RF_Ensure(); if WF and WF.DB and WF.DB.GetSetting then return WF.DB:GetSetting("randomIncludeUnknown") end return false end,
      function(v) _RF_Set("randomIncludeUnknown", v) end
    )

    local function _RF_SetComboWidth(combo, w)
      if not combo then return end
      w = tonumber(w) or 240
      if combo.SetWidth then combo:SetWidth(w) end
      if combo._btn and combo._btn.SetWidth then combo._btn:SetWidth(w) end
    end

    local function _RF_Layout()
      local w = rfOptPanel:GetWidth() or 0
      local pad = 12
      local gap = 12
      local fullW = (w > 0) and (w - (pad * 2)) or 240
      if fullW < 140 then fullW = 140 end
      local colW = math.floor((fullW - gap) / 2)

      comboAim:ClearAllPoints()
      comboExp:ClearAllPoints()
      comboType:ClearAllPoints()
      chkZone:ClearAllPoints()
      chkUnknown:ClearAllPoints()

      if colW >= 150 then
        _RF_SetComboWidth(comboAim, colW)
        _RF_SetComboWidth(comboExp, colW)
        _RF_SetComboWidth(comboType, fullW)

        comboAim:SetPoint("TOPLEFT", rfOptPanel, "TOPLEFT", pad, -10)
        comboExp:SetPoint("TOPLEFT", comboAim, "TOPRIGHT", gap, 0)
        comboType:SetPoint("TOPLEFT", comboAim, "BOTTOMLEFT", 0, -10)


        chkZone:SetPoint("TOPLEFT", comboType, "BOTTOMLEFT", 0, -8)
        chkUnknown:SetPoint("TOPLEFT", comboType, "BOTTOMLEFT", colW + gap, -8)

        rfOptPanel:SetHeight(10 + 44 + 10 + 44 + 8 + 26 + 12)
      else
        _RF_SetComboWidth(comboAim, fullW)
        _RF_SetComboWidth(comboExp, fullW)
        _RF_SetComboWidth(comboType, fullW)

        comboAim:SetPoint("TOPLEFT", rfOptPanel, "TOPLEFT", pad, -10)
        comboExp:SetPoint("TOPLEFT", comboAim, "BOTTOMLEFT", 0, -10)
        comboType:SetPoint("TOPLEFT", comboExp, "BOTTOMLEFT", 0, -10)


        chkZone:SetPoint("TOPLEFT", comboType, "BOTTOMLEFT", 0, -8)
        chkUnknown:SetPoint("TOPLEFT", chkZone, "BOTTOMLEFT", 0, -8)

        rfOptPanel:SetHeight(10 + 44 + 10 + 44 + 10 + 44 + 8 + 26 + 8 + 26 + 12)
      end
    end

    rfOptPanel:SetScript("OnShow", function()
      -- Defer one frame so rSC has its real width before backdrop renders
      C_Timer.After(0, function()
        if not rfOptPanel:IsShown() then return end
        rfOptPanel:ClearAllPoints()
        rfOptPanel:SetPoint("TOPLEFT", rMeta, "BOTTOMLEFT", 0, -10)
        rfOptPanel:SetPoint("RIGHT", rSC, "RIGHT", -12, 0)
        _RF_Layout()
        if comboAim and comboAim._refresh then comboAim._refresh() end
        if comboExp and comboExp._refresh then comboExp._refresh() end
        if comboType and comboType._refresh then comboType._refresh() end
      end)
    end)
    rfOptPanel:SetScript("OnSizeChanged", function()
      if rfOptPanel:IsShown() then _RF_Layout() end
    end)

    local bRoll = Widgets:Button(rSC, "Roll + Waypoint", 160, 26)

    -- Tooltip for the Random Farm roll button
    if bRoll and bRoll.HookScript then
      bRoll:HookScript("OnEnter", function()
        if not GameTooltip then return end
        if Widgets and Widgets.EnsureTooltipSkin then Widgets:EnsureTooltipSkin() end
        GameTooltip:SetOwner(bRoll, "ANCHOR_RIGHT")
        if GameTooltip.ClearLines then GameTooltip:ClearLines() end
        local ar, ag, ab = C4(ACCENT, ACCENT)
        GameTooltip:AddLine("Roll + Waypoint", ar, ag, ab)
        GameTooltip:AddLine("Rolls a random farm from your current filters.", TEXT[1], TEXT[2], TEXT[3], true)
        GameTooltip:AddLine("Sets a map waypoint to the selected farm.", 0.75, 0.75, 0.75, true)
        GameTooltip:AddLine("Tip: tweak the pool via Options.", 0.65, 0.65, 0.65, true)
        GameTooltip:Show()
        _WF_TooltipFlipAboveIfNeeded(self)
      end)
      bRoll:HookScript("OnLeave", function()
        if GameTooltip then GameTooltip:Hide() end
        _WF_TooltipFollow_Stop()
      end)
    end

    local rDiv = MakeDivider(rSC)
    rDiv:SetPoint("LEFT", rSC, "LEFT", 12, 0)
    rDiv:SetPoint("RIGHT", rSC, "RIGHT", -12, 0)
    rDiv:SetDrawLayer("OVERLAY", 7)
    if rDiv.SetHeight then rDiv:SetHeight(2) end
    rDiv:SetAlpha(0.30)

    local function _RF_Reflow()
      bRoll:ClearAllPoints()
      if rfOptPanel:IsShown() then
        bRoll:SetPoint("TOPLEFT", rfOptPanel, "BOTTOMLEFT", 0, -10)
      else
        bRoll:SetPoint("TOPLEFT", rMeta, "BOTTOMLEFT", 0, -10)
      end

      rDiv:ClearAllPoints()
      rDiv:SetPoint("LEFT", rSC, "LEFT", 12, 0)
      rDiv:SetPoint("RIGHT", rSC, "RIGHT", -12, 0)
      rDiv:SetPoint("TOP", bRoll, "BOTTOM", 0, -14)

      if UI and UI._UpdateOverviewRightScroll then
        UI:_UpdateOverviewRightScroll()
      end
    end

    rfOptBtn:SetScript("OnClick", function()
      if rfOptPanel:IsShown() then
        rfOptPanel:Hide()
      else
        rfOptPanel:Show()
      end
      _RF_Reflow()
    end)

    -- initial layout (panel collapsed)
    _RF_Reflow()



    return {
      rTitle = rTitle,
      rMeta = rMeta,
      bRoll = bRoll,
      rDiv = rDiv,
    }
end
