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 function fallbackTrim(s)
  s = tostring(s or "")
  return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end

function Sections.BuildTopFarms(ctx, env)
  local UI = env.UI
  local WF = env.WF
  local Widgets = env.Widgets
  local Util = env.Util
  local Money = env.Money
  local C4 = env.C4
  local TEXT = env.TEXT
  local MUTED = env.MUTED
  local ACCENT = env.ACCENT
  local rSC = env.rSC
  local rDiv = env.rDiv
  local MakeSectionTitle = env.MakeSectionTitle
  local MakeMutedText = env.MakeMutedText
  local MakeDivider = env.MakeDivider
  local _Trim = env.Trim or fallbackTrim
  local _SessDuration = env.SessDuration
  local _SessDurationText = env.SessDurationText
  local _DurationLongText = env.DurationLongText
  local _SessTotals = env.SessTotals
  local _WF_ApplyBlueQuestHighlight = env.ApplyBlueQuestHighlight
  local _WF_TooltipAnchorRow = env.TooltipAnchorRow
  local _WF_TooltipFlipAboveIfNeeded = env.TooltipFlipAboveIfNeeded
  local _WF_TooltipFollow_Stop = env.TooltipFollowStop

-- Top Farms (clean rows + hover details)
    local tTitle = MakeSectionTitle(rSC, "Top Farms")
    tTitle:SetPoint("TOPLEFT", rDiv, "BOTTOMLEFT", 0, -18)

    -- Stored for metric refresh (we render "Top Farms • <metric>")
    UI._ovTopTitle = tTitle

    local tMetric = MakeMutedText(rSC, "")
    tMetric:SetPoint("TOPRIGHT", rDiv, "BOTTOMRIGHT", 0, -18)
    tMetric:SetJustifyH("RIGHT")

    local TOP_FARMS_LIMIT = 5

    local tList = CreateFrame("Frame", nil, rSC)
    tList:SetPoint("TOPLEFT", tTitle, "BOTTOMLEFT", 0, -8)
    tList:SetPoint("TOPRIGHT", rSC, "TOPRIGHT", -12, 0)
    tList:SetHeight(108)

    -- Empty state (Top Farms)
    local emptyTop = tList:CreateFontString(nil, "OVERLAY", "WF_GameFontDisable")
    emptyTop:SetPoint("CENTER", tList, "CENTER", 0, 0)
    emptyTop:SetJustifyH("CENTER")
    emptyTop:SetTextColor(C4(MUTED, MUTED))
    emptyTop:SetText("No farm data yet.\nComplete a session to populate Top Farms.")
    emptyTop:Hide()
    UI._ovEmptyTopFarms = emptyTop

    local tRows = {}
    local function EnsureTopRow(i)
      if tRows[i] then return tRows[i] end

      local b = CreateFrame("Button", nil, tList)
      b:SetHeight(18)
      b:SetPoint("LEFT", 0, 0)
      b:SetPoint("RIGHT", 0, 0)
      _WF_ApplyBlueQuestHighlight(b, 0.20)

      b.rank = b:CreateFontString(nil, "OVERLAY", "WF_GameFontDisableSmall")
      b.rank:SetPoint("LEFT", 0, 0)
      b.rank:SetTextColor(C4(MUTED, MUTED))
      b.rank:SetText(i .. ".")

      b.name = b:CreateFontString(nil, "OVERLAY", "WF_GameFontHighlightSmall")
      b.name:SetPoint("LEFT", b.rank, "RIGHT", 6, 0)
      b.name:SetTextColor(C4(TEXT, TEXT))
      b.name:SetJustifyH("LEFT")

      b.value = b:CreateFontString(nil, "OVERLAY", "WF_GameFontHighlightSmall")
      b.value:SetPoint("RIGHT", 0, 0)
      b.value:SetTextColor(C4(TEXT, TEXT))
      b.value:SetJustifyH("RIGHT")

      b.sep = b:CreateTexture(nil, "BACKGROUND")
      b.sep:SetHeight((Widgets and Widgets.PixelSize) and Widgets:PixelSize(b) or 1)
  if Widgets and Widgets.MakePixelPerfect then Widgets:MakePixelPerfect(b.sep, b) end
      b.sep:SetPoint("BOTTOMLEFT", 0, -2)
      b.sep:SetPoint("BOTTOMRIGHT", 0, -2)
      b.sep:SetColorTexture(1, 1, 1, 0.06)

      b:RegisterForClicks("LeftButtonUp")
      b:SetScript("OnMouseUp", function(self, button)
        if button ~= "LeftButton" then return end
        local d = self._data
        if not d or not d.bestSess then return end

        UI._pendingSelectSession = d.bestSess
        UI:Show("History")
        if UI.RefreshHistory then UI:RefreshHistory() end
      end)

      b:SetScript("OnEnter", function(self)
        local d = self._data
        if not d or not GameTooltip then return end

        _WF_TooltipAnchorRow(self)
        GameTooltip:AddLine(d.label or "Farm", ACCENT[1], ACCENT[2], ACCENT[3], true)
        local bestSess = d.bestSess
        if bestSess and _Trim(bestSess._wfCustomFarmName or "") ~= "" then
          local z = _Trim(bestSess.zone or "")
          if z == "" and WF and WF.DB and WF.DB.GetFarm and bestSess.farmId then
            local f = WF.DB:GetFarm(bestSess.farmId)
            if f then z = _Trim(f.zone or "") end
          end
          GameTooltip:AddLine("Zone: " .. (z ~= "" and z or "—"), 0.95, 0.95, 0.95)
        end
        GameTooltip:AddLine((d.metricLabel or "GPH") .. ": " .. Money(Util:Round(d.metricValue or 0)), 0.95, 0.95, 0.95)
        if bestSess then
          local modeText = _Trim(bestSess.mode or bestSess.profile or bestSess.profileName or bestSess.modeName or "")
          if modeText == "" then modeText = "—" end
          GameTooltip:AddDoubleLine("Mode:", modeText, 0.75, 0.75, 0.75, 1, 1, 1)
        end

        GameTooltip:AddLine(" ", 1, 1, 1)

        if d.bestRunText and d.bestRunText ~= "" then
          GameTooltip:AddDoubleLine("Best run:", tostring(d.bestRunText), 0.75, 0.75, 0.75, 1, 1, 1)
        end

        if d.durationText and d.durationText ~= "" then
          GameTooltip:AddDoubleLine("Duration:", tostring(d.durationText), 0.75, 0.75, 0.75, 1, 1, 1)
        end

        if d.itemValue then
          GameTooltip:AddDoubleLine("Looted Item Value:", Money(Util:Round(d.itemValue)), 0.75, 0.75, 0.75, 1, 1, 1)
        end
        if d.goldValue then
          GameTooltip:AddDoubleLine("Looted Gold:", Money(Util:Round(d.goldValue)), 0.75, 0.75, 0.75, 1, 1, 1)
        end
        if d.totalValue then
          GameTooltip:AddDoubleLine("Total Value:", Money(Util:Round(d.totalValue)), 0.75, 0.75, 0.75, 1, 1, 1)
        end
        if d.runsCount then
          GameTooltip:AddLine(" ", 1, 1, 1)
          GameTooltip:AddDoubleLine("Runs:", tostring(d.runsCount), 0.75, 0.75, 0.75, 1, 1, 1)
        end

        local note = bestSess and _Trim(bestSess.note or "") or ""
        local isPinned = bestSess and bestSess.pinned and true or false

        if isPinned or note ~= "" then
          GameTooltip:AddLine(" ", 1, 1, 1)
          if isPinned then
            GameTooltip:AddLine("Pinned", ACCENT[1], ACCENT[2], ACCENT[3], true)
          end
          if note ~= "" then
            GameTooltip:AddLine(note, TEXT[1], TEXT[2], TEXT[3], true)
          end
        else
          -- Keep the CTA separated even when there's no note/pin.
          GameTooltip:AddLine(" ", 1, 1, 1)
        end

        GameTooltip:AddLine("Click to view in History", 0.65, 0.65, 0.65)
        GameTooltip:Show()
        _WF_TooltipFlipAboveIfNeeded(self)
      end)

      b:SetScript("OnLeave", function()
        if GameTooltip then GameTooltip:Hide() end
        _WF_TooltipFollow_Stop()
      end)

      tRows[i] = b
      return b
    end

    for i = 1, TOP_FARMS_LIMIT do
      local r = EnsureTopRow(i)
      r:SetPoint("TOPLEFT", 0, -((i - 1) * 22))
      r:SetPoint("TOPRIGHT", 0, -((i - 1) * 22))
      r.name:SetPoint("RIGHT", r.value, "LEFT", -10, 0) -- prevents wrapping into value
    end

    local tDiv = MakeDivider(rSC)
    tDiv:SetPoint("LEFT", rSC, "LEFT", 12, 0)
    tDiv:SetPoint("RIGHT", rSC, "RIGHT", -12, 0)
    tDiv:SetPoint("TOP", tList, "BOTTOM", 0, -14)



    return {
      tTitle = tTitle,
      tMetric = tMetric,
      limit = TOP_FARMS_LIMIT,
      tList = tList,
      tRows = tRows,
      tDiv = tDiv,
    }
end
