-- ============================================================
-- RealNibba.Farm.lua  - Farming Window
-- Layout: WoW-native internal title bar, consistent spacing
-- WIN_W=320, WIN_H=440  MINI_H=195
-- ============================================================
local P  = RNPack

-- Layout constants from Core
local BPAD     = P.BPAD  or 14
local GAP      = P.GAP   or 6
local GAP_S    = P.GAP_S or 3
local BTN_H    = P.BTN_H or 22
local LBL_H    = P.LBL_H or 14
local DIV_H    = 1

local WIN_W  = P.WIN_W or 320
local WIN_H  = 418
local MINI_H = 148   -- minimized height: title + zone + gph + nodes + buttons + padding

-- Shared frames / labels
local farmFrame, farmFrameLbl
local farmScrollChild
local farmItems  = {}
local itemDropdown
local lblZone, lblStatus, lblDuration
local lblCash

-- Minimize state
local farmMinimized = false
local collapseGroup = {}   -- frames to hide when minimized
local btnMinimize           -- the [-]/[+] title-bar button
-- forward-declared so SetFarmMinimized (defined before the rows) can reference them
local btnStart, lblGPH, lblTotalRight, lblNodes

-- ============================================================
-- REFRESH FUNCTIONS
-- ============================================================
local function RefreshFarmStats()
    if not P.session then return end
    local s   = P.session
    local dur = P.GetSessionDuration()
    local tot = P.GetTotalMoney()
    local gph = P.GetGoldPerHour()
    local z   = (s.zoneName and s.zoneName ~= "" and s.zoneName)
             or (P.curZone   and P.curZone   ~= "" and P.curZone)
             or "Unknown"

    if lblZone     then lblZone:SetText("Zone: "..z) end
    if lblStatus   then
        if P.sessionActive and not P.sessionPaused then
            lblStatus:SetText("|cff00FF44ACTIVE|r")
        elseif P.sessionPaused then
            lblStatus:SetText("|cffFF8800PAUSED|r")
        else
            lblStatus:SetText("|cff888888STOPPED|r")
        end
    end
    if lblDuration   then lblDuration:SetText(P.FormatTime(dur)) end
    if lblGPH        then
        local gphGold = gph / 10000
        local col = gphGold < 500 and "|cffFF4444"
                 or gphGold < 1000 and "|cffFFD700"
                 or "|cff00FF44"
        lblGPH:SetText("Gold/hr: "..col..P.FormatMoneyShort(gph).."|r")
    end
    if lblTotalRight then lblTotalRight:SetText("Total: "..P.FormatMoneyShort(tot)) end
    if lblCash       then
        lblCash:SetText(
            "Cash: "  ..P.FormatMoneyShort(s.moneyCash   or 0)..
            "  Items: "..P.FormatMoneyShort(s.moneyItems  or 0)..
            "  Quests: "..P.FormatMoneyShort(s.moneyQuests or 0)
        )
    end
    if lblNodes then
        lblNodes:SetText(
            "|cff00CC00Herbs: "..tostring(s.countHerbs or 0).."|r  "..
            "|cff4488FFMines: "..tostring(s.countMines or 0).."|r  "..
            "Items: "..tostring(s.countItems or 0)
        )
    end
    if P.gphBox then
        local gphGold = gph/10000
        local col = gphGold<500 and "|cffFF4444" or gphGold<1000 and "|cffFFD700" or "|cff00FF44"
        P.gphBox:SetText(col..P.FormatMoneyShort(gph).."|r")
    end
    if P.hnBox then
        P.hnBox:SetText("|cff00CC00"..tostring(s.countHerbs or 0)..
                        "|r / |cff4488FF"..tostring(s.countMines or 0).."|r")
    end
    if P.cashBox then
        local cashGold = (s.moneyCash or 0)/10000
        local col = cashGold<30 and "|cffFF4444" or cashGold<50 and "|cffFFD700" or "|cff00FF44"
        P.cashBox:SetText(col..P.FormatMoneyShort(s.moneyCash or 0).."|r")
    end
end

local function RefreshItemList()
    if not farmScrollChild or not P.session then return end
    local s     = P.session
    local items = {}
    for link, data in pairs(s.lootedItems or {}) do
        items[#items+1] = {link=link, value=data[1], count=data[2]}
    end
    table.sort(items, function(a,b) return a.value > b.value end)
    local rowH = 20
    farmScrollChild:SetHeight(math.max(1, #items*rowH))
    for i, item in ipairs(items) do
        local row = farmItems[i]
        if not row then
            row = CreateFrame("Frame",nil,farmScrollChild)
            row:SetHeight(rowH)
            local rbg=row:CreateTexture(nil,"BACKGROUND"); rbg:SetAllPoints()
            rbg:SetTexture(i%2==0 and 0.12 or 0.07, i%2==0 and 0.12 or 0.07,
                           i%2==0 and 0.14 or 0.09, 0.6)
            local ico=row:CreateTexture(nil,"ARTWORK")
            ico:SetSize(16,16); ico:SetPoint("LEFT",row,"LEFT",2,0); row.icon=ico
            local nm=row:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
            nm:SetPoint("LEFT",ico,"RIGHT",3,0); nm:SetWidth(150)
            nm:SetJustifyH("LEFT"); row.name=nm
            local cnt=row:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
            cnt:SetPoint("RIGHT",row,"RIGHT",-60,0); cnt:SetWidth(36)
            cnt:SetJustifyH("RIGHT"); cnt:SetTextColor(0.7,0.7,0.7,1); row.cnt=cnt
            local val=row:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
            val:SetPoint("RIGHT",row,"RIGHT",-2,0); val:SetWidth(56)
            val:SetJustifyH("RIGHT"); val:SetTextColor(1,0.82,0,1); row.val=val
            row:EnableMouse(true)
            farmItems[i]=row
        end
        row:SetPoint("TOPLEFT",  farmScrollChild,"TOPLEFT",  0,-(i-1)*rowH)
        row:SetPoint("TOPRIGHT", farmScrollChild,"TOPRIGHT",  0,-(i-1)*rowH)
        local name,_,rarity,_,_,_,_,_,_,tex = GetItemInfo(item.link)
        row.icon:SetTexture(tex or "Interface/Icons/INV_Misc_QuestionMark")
        local qc = P.QUALITY_COLORS[rarity or 1] or P.QUALITY_COLORS[1]
        local dn = name or "Unknown"
        -- Compute max chars that fit in the name column (150px, ~6.5px/char for small font)
        local nmW = row.name:GetWidth()
        local maxChars = nmW > 0 and math.floor(nmW / 6.3) or 22
        if #dn > maxChars then dn = string.sub(dn,1,maxChars-3).."..." end
        row.name:SetText(dn); row.name:SetTextColor(qc[1],qc[2],qc[3],1)
        row.cnt:SetText("x"..item.count)
        local isCustom = P.DB and P.DB.customPrices and P.DB.customPrices[item.link]
        row.val:SetText((isCustom and "|cffFFAA00" or "")..
                        P.FormatMoneyShort(item.value)..(isCustom and "|r" or ""))
        local ilink = item.link
        row:SetScript("OnEnter", function()
            GameTooltip:SetOwner(row,"ANCHOR_RIGHT")
            GameTooltip:SetHyperlink(ilink)
            GameTooltip:AddLine(" ")
            GameTooltip:AddLine("Right-click for options",0.6,0.6,0.6)
            GameTooltip:Show()
        end)
        row:SetScript("OnLeave", function() GameTooltip:Hide() end)
        row:SetScript("OnMouseUp", function(self,btn)
            if btn=="RightButton" then
                if P.ShowItemDropdown then P.ShowItemDropdown(ilink) end
            end
        end)
        row:Show()
        if _G.RNPackSkinFrame then _G.RNPackSkinFrame(row) end
    end
    for i=#items+1, #farmItems do farmItems[i]:Hide() end
end

P.RefreshFarmStats = RefreshFarmStats
P.RefreshItemList  = RefreshItemList
P.UpdateAHDisplay  = RefreshFarmStats

-- ============================================================
-- RIGHT-CLICK DROPDOWN
-- ============================================================
-- Item right-click context menu using EasyMenu (native WoW API)
local _rnEasyMenuFrame = CreateFrame("Frame","RNPackEasyMenuFrame",UIParent,"UIDropDownMenuTemplate")
local ddCurrentLink = nil

function P.ShowItemDropdown(link)
    ddCurrentLink = link
    local name = GetItemInfo(link) or "Item"
    local menuList = {
        {text=name, isTitle=true, notCheckable=true},
        {
            text = "Set Custom Price",
            notCheckable = true,
            func = function()
                if P.ShowPriceEdit then P.ShowPriceEdit(ddCurrentLink) end
            end,
        },
        {
            text = "Remove Custom Price",
            notCheckable = true,
            func = function()
                if P.DB and P.DB.customPrices then
                    P.DB.customPrices[ddCurrentLink] = nil
                    if P.RefreshItemList then P.RefreshItemList() end
                    P.prt("Custom price removed.")
                end
            end,
        },
        {text="", disabled=true, notCheckable=true},  -- separator
        {
            text = "Delete from List",
            notCheckable = true,
            func = function()
                local s = P.session
                if s and s.lootedItems and ddCurrentLink then
                    local d = s.lootedItems[ddCurrentLink]
                    if d then
                        s.moneyItems = math.max(0,(s.moneyItems or 0)-d[1])
                        s.countItems = math.max(0,(s.countItems or 0)-d[2])
                    end
                    s.lootedItems[ddCurrentLink] = nil
                    if P.RefreshItemList  then P.RefreshItemList() end
                    if P.RefreshFarmStats then P.RefreshFarmStats() end
                end
            end,
        },
        {
            text = "Blacklist Item",
            notCheckable = true,
            func = function()
                if P.DB and ddCurrentLink then
                    P.DB.blacklist = P.DB.blacklist or {}
                    P.DB.blacklist[ddCurrentLink] = true
                    local s = P.session
                    if s and s.lootedItems then s.lootedItems[ddCurrentLink] = nil end
                    if P.RefreshItemList  then P.RefreshItemList() end
                    if P.RefreshFarmStats then P.RefreshFarmStats() end
                    local n = GetItemInfo(ddCurrentLink)
                    P.prt("Blacklisted: "..(n or ddCurrentLink))
                end
            end,
        },
    }
    EasyMenu(menuList, _rnEasyMenuFrame, "cursor", 0, 0, "MENU", 2)
end

-- ============================================================
-- FARM WINDOW  320 x 440
-- Layout (all Y from frame top, negative = down):
--   Title bar + divider: 0 to -24
--   Content starts:      -30
-- ============================================================
farmFrame, farmFrameLbl = P.MakeWindow("RNPackFarmFrame","RealNibba.Pack",WIN_W,WIN_H)
farmFrame:SetToplevel(true)
farmFrame:SetScript("OnMouseDown",function() farmFrame:Raise() end)
P.farmFrame = farmFrame
if P.RegisterScalableFrame then P.RegisterScalableFrame(farmFrame) end

-- ── MINIMIZE button in title bar  (sits left of the X close button)
-- UIPanelCloseButton is 32px wide anchored at TOPRIGHT -4,-4; place [-] just left of it
btnMinimize = P.MakeBtn("[-]", farmFrame, 28, 18)
btnMinimize:SetPoint("TOPRIGHT", farmFrame, "TOPRIGHT", -36, -6)

-- ── SetFarmMinimized: collapses/expands the farm window
local function SetFarmMinimized(mini)
    farmMinimized = mini
    if P.DB then P.DB.farmMinimized = mini end
    farmFrame:SetHeight(mini and MINI_H or WIN_H)
    btnMinimize:SetText(mini and "[+]" or "[-]")
    for _, f in ipairs(collapseGroup) do
        if mini then f:Hide() else f:Show() end
    end
    -- Re-anchor all rows; always ClearAllPoints first to avoid accumulation
    if mini then
        -- Zone/Status/Duration just below title
        lblZone:ClearAllPoints();     lblZone:SetPoint("TOPLEFT",      farmFrame, "TOPLEFT",  BPAD,  -30)
        lblStatus:ClearAllPoints();   lblStatus:SetPoint("TOP",         farmFrame, "TOP",       0,     -30)
        lblDuration:ClearAllPoints(); lblDuration:SetPoint("TOPRIGHT",  farmFrame, "TOPRIGHT", -BPAD, -30)
        -- Stats below zone row
        lblGPH:ClearAllPoints();        lblGPH:SetPoint("TOPLEFT",        farmFrame, "TOPLEFT",  BPAD,  -66)
        lblTotalRight:ClearAllPoints(); lblTotalRight:SetPoint("TOPRIGHT", farmFrame, "TOPRIGHT", -BPAD, -66)
        lblNodes:ClearAllPoints();      lblNodes:SetPoint("TOPLEFT",       farmFrame, "TOPLEFT",  BPAD,  -86)
        -- Control buttons pinned to the bottom of the mini frame
        btnStart:ClearAllPoints();    btnStart:SetPoint("BOTTOMLEFT",   farmFrame, "BOTTOMLEFT", BPAD, 8)
    else
        -- Restore expanded positions
        lblZone:ClearAllPoints();     lblZone:SetPoint("TOPLEFT",      farmFrame, "TOPLEFT",  BPAD,  -65)
        lblStatus:ClearAllPoints();   lblStatus:SetPoint("TOP",         farmFrame, "TOP",       0,     -65)
        lblDuration:ClearAllPoints(); lblDuration:SetPoint("TOPRIGHT",  farmFrame, "TOPRIGHT", -BPAD, -65)
        lblGPH:ClearAllPoints();       lblGPH:SetPoint("TOPLEFT",       farmFrame, "TOPLEFT",  BPAD, -135)
        lblTotalRight:ClearAllPoints(); lblTotalRight:SetPoint("TOPRIGHT",farmFrame,"TOPRIGHT", -BPAD,-135)
        lblNodes:ClearAllPoints();     lblNodes:SetPoint("TOPLEFT",      farmFrame, "TOPLEFT",  BPAD, -168)
        btnStart:ClearAllPoints();    btnStart:SetPoint("TOPLEFT",      farmFrame, "TOPLEFT",   BPAD, -100)
    end
end
P.SetFarmMinimized = SetFarmMinimized

btnMinimize:SetScript("OnClick", function()
    SetFarmMinimized(not farmMinimized)
end)

farmFrame:SetScript("OnMouseDown", function(self) self:Raise() end)

-- ── ROW 0: Title-area nav buttons  y=-30  h=22  end=-52
-- 4 buttons: Routes | Sessions | Config | Scan Bags  (Scan AH removed - auto)
local _navCount = 4
local navW = math.floor((WIN_W - BPAD*2 - (_navCount-1)*GAP_S) / _navCount)
local routesTopBtn = P.MakeBtn("Routes",   farmFrame, navW, BTN_H)
local btnSessions  = P.MakeBtn("Sessions", farmFrame, navW, BTN_H)
local configTopBtn = P.MakeBtn("Config",   farmFrame, navW, BTN_H)
local btnBagScan   = P.MakeBtn("Scan Bags",farmFrame, navW, BTN_H)
-- Centered positioning
local _navTotalW = _navCount*navW + (_navCount-1)*GAP_S
local _navStartX = math.floor((WIN_W - _navTotalW) / 2)
routesTopBtn:SetPoint("TOPLEFT",farmFrame,"TOPLEFT",_navStartX,-30)
btnSessions:SetPoint( "LEFT",routesTopBtn,"RIGHT",GAP_S,0)
configTopBtn:SetPoint("LEFT",btnSessions, "RIGHT",GAP_S,0)
btnBagScan:SetPoint(  "LEFT",configTopBtn,"RIGHT",GAP_S,0)
P.routesTopBtn = routesTopBtn
P.configTopBtn = configTopBtn
P.btnBagScan   = btnBagScan

-- ── DIVIDER  y=-58

-- ── ROW 1: Zone | Status | Duration  y=-65  h=14  end=-79
lblZone = farmFrame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
lblZone:SetPoint("TOPLEFT",farmFrame,"TOPLEFT",BPAD,-65)
lblZone:SetWidth(110); lblZone:SetJustifyH("LEFT")
lblZone:SetText("Zone: -")

P.UpdateZoneLabel = function()
    local z = (P.session and P.session.zoneName and P.session.zoneName ~= "" and P.session.zoneName)
           or (P.curZone and P.curZone ~= "" and P.curZone)
           or ""
    if z ~= "" and lblZone then lblZone:SetText("Zone: "..z) end
end

lblStatus = farmFrame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
lblStatus:SetPoint("TOP",farmFrame,"TOP",0,-65)
lblStatus:SetText("|cff888888STOPPED|r")

lblDuration = farmFrame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
lblDuration:SetPoint("TOPRIGHT",farmFrame,"TOPRIGHT",-BPAD,-65)
lblDuration:SetJustifyH("RIGHT"); lblDuration:SetText("0m 00s")

-- ── ROW 2: Start/Stop/Pause/Finish  y=-82  h=22  end=-104
local bW = math.floor((WIN_W - BPAD*2 - 3*GAP_S) / 4)
btnStart        = P.MakeBtn("Start",  farmFrame, bW, BTN_H)
local btnStop   = P.MakeBtn("Stop",   farmFrame, bW, BTN_H)
local btnPause  = P.MakeBtn("Pause",  farmFrame, bW, BTN_H)
local btnFinish = P.MakeBtn("Finish", farmFrame, bW, BTN_H)
btnStart:SetPoint("TOPLEFT",farmFrame,"TOPLEFT", BPAD, -100)
btnStop:SetPoint( "LEFT",   btnStart, "RIGHT",   GAP_S, 0)
btnPause:SetPoint("LEFT",   btnStop,  "RIGHT",   GAP_S, 0)
btnFinish:SetPoint("LEFT",  btnPause, "RIGHT",   GAP_S, 0)

btnStart:SetScript("OnClick",  function() P.SessionStart() end)
btnStop:SetScript("OnClick",   function() P.SessionStop() end)
btnPause:SetScript("OnClick",  function()
    if P.sessionPaused then P.SessionStart() else P.SessionPause() end
end)
btnFinish:SetScript("OnClick", function()
    P.SessionStop(); P.ResetSession(); RefreshFarmStats(); RefreshItemList()
end)

-- ── DIVIDER  y=-110

-- ── ROW 3: Gold/hr (left) | Total (right)  y=-135
lblGPH = farmFrame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
lblGPH:SetPoint("TOPLEFT",farmFrame,"TOPLEFT",BPAD,-135)
lblGPH:SetText("Gold/hr: --")

lblTotalRight = farmFrame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
lblTotalRight:SetPoint("TOPRIGHT",farmFrame,"TOPRIGHT",-BPAD,-135)
lblTotalRight:SetJustifyH("RIGHT"); lblTotalRight:SetText("Total: --")

-- ── ROW 4: Cash/Items/Quests  y=-152
lblCash = farmFrame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
lblCash:SetPoint("TOPLEFT",farmFrame,"TOPLEFT",BPAD,-152)
lblCash:SetText("Cash: 0g  Items: 0g  Quests: 0g")

-- ── ROW 5: Herbs/Mines/Items  y=-168
lblNodes = farmFrame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
lblNodes:SetPoint("TOPLEFT",farmFrame,"TOPLEFT",BPAD,-168)
lblNodes:SetText("|cff00CC00Herbs: 0|r  |cff4488FFMines: 0|r  Items: 0")

-- ── DIVIDER  y=-169

-- ── ROW 6: AUTO-TRACK toggle button  y=-186  h=22
local btnAutoTrack = P.MakeBtn("Auto-Track: OFF", farmFrame, WIN_W - BPAD*2, BTN_H)
btnAutoTrack:SetPoint("TOPLEFT", farmFrame, "TOPLEFT", BPAD, -186)

-- ── AUTO-TRACK TICKER
local atFrame = CreateFrame("Frame", "RNPackAutoTrackFrame", UIParent)
atFrame._t    = 0
atFrame._slot = 1   -- 1 = Herbs, 2 = Minerals

local function UpdateAutoTrackBtn()
    if not atFrame:IsShown() then
        btnAutoTrack:SetText("Auto-Track: OFF")
        btnAutoTrack:GetNormalTexture():SetVertexColor(1, 1, 1)
    elseif atFrame._slot == 1 then
        btnAutoTrack:SetText("|cff00CC00Auto-Track: Herbs|r")
        btnAutoTrack:GetNormalTexture():SetVertexColor(0.6, 1, 0.6)
    else
        btnAutoTrack:SetText("|cff4488FFAuto-Track: Mines|r")
        btnAutoTrack:GetNormalTexture():SetVertexColor(0.6, 0.8, 1)
    end
end

atFrame:SetScript("OnUpdate", function(self, elapsed)
    self._t = self._t + elapsed
    local db = P.DB and P.DB.autoTrack
    if not db then return end
    if self._t < db.interval then return end
    self._t = 0
    self._slot = self._slot == 1 and 2 or 1
    SetTracking(self._slot)
    UpdateAutoTrackBtn()
end)
atFrame:Hide()

local function SetAutoTrack(enable)
    if enable then
        atFrame._t = 0
        atFrame:Show()
        SetTracking(atFrame._slot)
    else
        atFrame:Hide()
    end
    if P.DB and P.DB.autoTrack then P.DB.autoTrack.enabled = enable end
    UpdateAutoTrackBtn()
end
P.SetAutoTrack = SetAutoTrack

btnAutoTrack:SetScript("OnClick", function()
    SetAutoTrack(not atFrame:IsShown())
end)

-- ── ROW 7: LOOTED ITEMS header + [-] button  y=-218
local lblItemsHdr = farmFrame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
lblItemsHdr:SetPoint("TOPLEFT",farmFrame,"TOPLEFT",BPAD,-218)
lblItemsHdr:SetTextColor(1,0.82,0,1); lblItemsHdr:SetText("LOOTED ITEMS")

local btnHideItems = P.MakeBtn("[-]",farmFrame,28,16)
btnHideItems:SetPoint("LEFT",lblItemsHdr,"RIGHT",GAP_S,0)

-- ── ITEM SCROLL  y=-240  to  BOTTOMRIGHT+64
local farmScroll = CreateFrame("ScrollFrame","RNPackFarmScroll",farmFrame,"UIPanelScrollFrameTemplate")
farmScroll:SetPoint("TOPLEFT",  farmFrame,"TOPLEFT",  BPAD,      -240)
farmScroll:SetPoint("BOTTOMRIGHT",farmFrame,"BOTTOMRIGHT",-BPAD-18, 64)

farmScrollChild = CreateFrame("Frame",nil,farmScroll)
farmScrollChild:SetSize(farmScroll:GetWidth() or 260, 1)
farmScroll:SetScrollChild(farmScrollChild)

local itemsVisible = true
btnHideItems:SetScript("OnClick",function()
    itemsVisible = not itemsVisible
    if itemsVisible then farmScroll:Show(); btnHideItems:SetText("[-]")
    else farmScroll:Hide(); btnHideItems:SetText("[+]") end
end)

-- ── DIVIDER above bottom bar
local bbH   = 50
local bbDivY= -(WIN_H - bbH - 1)   -- = -389

-- ── BOTTOM BAR: 3 equal panels  (y from bottom = 0 to bbH)
local bBW = math.floor((WIN_W - BPAD*2 - GAP_S*2) / 3)

local function MakeGoldPanel(title, xOff)
    local f=CreateFrame("Frame",nil,farmFrame)
    f:SetSize(bBW, bbH-6)
    f:SetPoint("BOTTOMLEFT",farmFrame,"BOTTOMLEFT",xOff,14)
    f:SetBackdrop(P.BACKDROP_DARK)
    f:SetBackdropColor(0.05,0.05,0.05,0.9)
    f:SetBackdropBorderColor(0.35,0.30,0.20,0.8)
    local top=f:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
    top:SetPoint("TOP",f,"TOP",0,-4); top:SetTextColor(0.7,0.7,0.7,1); top:SetText(title)
    local val=f:CreateFontString(nil,"OVERLAY","GameFontNormal")
    val:SetPoint("CENTER",f,"CENTER",0,-5); val:SetTextColor(1,0.82,0,1); val:SetText("0g")
    return val
end

P.gphBox  = MakeGoldPanel("GOLD / HR",    BPAD)
P.hnBox   = MakeGoldPanel("HERBS / MINES",BPAD + bBW + GAP_S)
P.cashBox = MakeGoldPanel("CASH EARNED",  BPAD + bBW*2 + GAP_S*2)

-- ── BUTTON SCRIPTS
routesTopBtn:SetScript("OnClick",function()
    local rf = P.routesFrame
    if rf then
        if rf:IsShown() then rf:Hide()
        else rf:Show(); if P.UI_Routes then P.UI_Routes.RefreshList() end end
    end
end)
-- Sessions button
btnSessions:SetScript("OnClick",function()
    if P.OpenSessions then P.OpenSessions() end
end)

-- Recursively find all WoW Slider frames under a parent
local function FindSliders(parent, result)
    result = result or {}
    for _, child in ipairs({parent:GetChildren()}) do
        if child:GetObjectType() == "Slider" then
            result[#result+1] = child
        end
        FindSliders(child, result)
    end
    return result
end

-- Config → AceConfigDialog (full Ace3 options window)
local _cfgHookTick = CreateFrame("Frame")
_cfgHookTick:SetScript("OnUpdate", nil)

configTopBtn:SetScript("OnClick",function()
    local ACD=LibStub("AceConfigDialog-3.0",true)
    if ACD then
        if ACD.OpenFrames and ACD.OpenFrames["RealNibba.Pack"] then
            ACD:Close("RealNibba.Pack")
        else
            ACD:Open("RealNibba.Pack")
            -- Apply saved scale + backdrop immediately on open
            local cf = ACD.OpenFrames and ACD.OpenFrames["RealNibba.Pack"]
            if cf and cf.frame then
                local scale = P.DB and P.DB.addonScale or 1.0
                cf.frame:SetScale(scale)
                if not cf.frame._rnBgApplied then
                    cf.frame._rnBgApplied = true
                    P.ApplyBG(cf, true)
                end
            end
            -- After each click inside the config window, sweep for any new
            -- slider frames (tab switches create new ones) and hook OnMouseUp
            -- so scale is applied only once on release, not during drag.
            local function SweepAndHookSliders()
                local acdf = ACD.OpenFrames and ACD.OpenFrames["RealNibba.Pack"]
                if not (acdf and acdf.frame) then return end
                local sliders = FindSliders(acdf.frame)
                for _, s in ipairs(sliders) do
                    if not s._rnScaleHooked then
                        s._rnScaleHooked = true
                        s:HookScript("OnMouseUp", function()
                            if P.DB and P.DB.addonScale then
                                P.ApplyAddonScale(P.DB.addonScale)
                            end
                        end)
                    end
                end
            end
            -- Recurring sweep: re-check every ~0.3s while config is open.
            -- Tab clicks don't bubble to the parent frame, so we can't rely on
            -- OnMouseDown. Instead we sweep periodically so newly rendered tab
            -- content (including the Interface tab scale slider) gets hooked.
            local _sweepElapsed = 0
            _cfgHookTick:SetScript("OnUpdate", function(self, elapsed)
                _sweepElapsed = _sweepElapsed + elapsed
                if _sweepElapsed < 0.3 then return end
                _sweepElapsed = 0
                local acdf = ACD.OpenFrames and ACD.OpenFrames["RealNibba.Pack"]
                if not (acdf and acdf.frame and acdf.frame:IsShown()) then
                    self:SetScript("OnUpdate", nil)
                    return
                end
                SweepAndHookSliders()
            end)
        end
    end
end)
btnBagScan:SetScript("OnClick",function()
    if P.OpenBagScanner then P.OpenBagScanner() end
end)

-- ── COLLAPSE GROUP: everything hidden in minimized mode
-- Nav row
collapseGroup[#collapseGroup+1] = routesTopBtn
collapseGroup[#collapseGroup+1] = btnSessions
collapseGroup[#collapseGroup+1] = configTopBtn
collapseGroup[#collapseGroup+1] = btnBagScan
-- Cash breakdown row (less critical — hidden in mini)
collapseGroup[#collapseGroup+1] = lblCash
-- Auto-track button and items section
collapseGroup[#collapseGroup+1] = btnAutoTrack
collapseGroup[#collapseGroup+1] = lblItemsHdr
collapseGroup[#collapseGroup+1] = btnHideItems
collapseGroup[#collapseGroup+1] = farmScroll
-- Bottom gold panels (parent frames)
collapseGroup[#collapseGroup+1] = P.gphBox:GetParent()
collapseGroup[#collapseGroup+1] = P.hnBox:GetParent()
collapseGroup[#collapseGroup+1] = P.cashBox:GetParent()

-- Restore minimized state from DB when the farm window is first shown
farmFrame:HookScript("OnShow", function()
    if P.DB and P.DB.farmMinimized ~= farmMinimized then
        SetFarmMinimized(P.DB.farmMinimized)
    end
end)

-- ── MINIMAP BUTTON
local MINIMAP_ICON = [[Interface\Icons\Trade_Herbalism]]

local minimapShapes_Pack = {
    ["ROUND"]                  = {true, true, true, true},
    ["SQUARE"]                 = {false, false, false, false},
    ["CORNER-TOPLEFT"]         = {true, false, false, false},
    ["CORNER-TOPRIGHT"]        = {false, false, true, false},
    ["CORNER-BOTTOMLEFT"]      = {false, true, false, false},
    ["CORNER-BOTTOMRIGHT"]     = {false, false, false, true},
    ["SIDE-LEFT"]              = {true, true, false, false},
    ["SIDE-RIGHT"]             = {false, false, true, true},
    ["SIDE-TOP"]               = {true, false, true, false},
    ["SIDE-BOTTOM"]            = {false, true, false, true},
    ["TRICORNER-TOPLEFT"]      = {true, true, true, false},
    ["TRICORNER-TOPRIGHT"]     = {true, false, true, true},
    ["TRICORNER-BOTTOMLEFT"]   = {true, true, false, true},
    ["TRICORNER-BOTTOMRIGHT"]  = {false, true, true, true},
}

local function RNPack_UpdateMinimapPos(btn)
    local angle = math.rad(RNPackMinimapAngle or 195)
    local x, y, q = math.cos(angle), math.sin(angle), 1
    if x < 0 then q = q + 1 end
    if y > 0 then q = q + 2 end
    local shape = GetMinimapShape and GetMinimapShape() or "ROUND"
    local quad = minimapShapes_Pack[shape]
    if quad[q] then
        x, y = x * 80, y * 80
    else
        local r = 103.13708498985
        x = math.max(-80, math.min(x * r, 80))
        y = math.max(-80, math.min(y * r, 80))
    end
    btn:SetPoint("CENTER", Minimap, "CENTER", x, y)
end

local function OnMinimapDragUpdate(self)
    local mx, my = Minimap:GetCenter()
    local px, py = GetCursorPosition()
    local scale  = Minimap:GetEffectiveScale()
    px, py = px / scale, py / scale
    RNPackMinimapAngle = math.deg(math.atan2(py - my, px - mx)) % 360
    RNPack_UpdateMinimapPos(self)
end

local function OnMinimapDragStart(self)
    self:LockHighlight()
    self.icon:SetTexCoord(0, 1, 0, 1)
    self:SetScript("OnUpdate", OnMinimapDragUpdate)
    GameTooltip:Hide()
end

local function OnMinimapDragStop(self)
    self:SetScript("OnUpdate", nil)
    self.icon:SetTexCoord(0.05, 0.95, 0.05, 0.95)
    self:UnlockHighlight()
end

local function OnMinimapClick(self,btn)
    if btn=="LeftButton" then
        if farmFrame:IsShown() then farmFrame:Hide()
        else farmFrame:Show(); RefreshFarmStats(); RefreshItemList() end
    end
end
local function OnMinimapEnter(self)
    GameTooltip:SetOwner(self,"ANCHOR_LEFT")
    GameTooltip:AddLine("|cffCC2222RealNibba|r.Pack",1,0.82,0)
    GameTooltip:AddLine("by RealNibba",0.7,0.7,0.7)
    GameTooltip:AddLine(" ")
    GameTooltip:AddLine("Left Click:",0,1,0)
    GameTooltip:AddLine("  Open / Close Addon UI",1,1,1)
    GameTooltip:Show()
end
local function OnMinimapLeave() GameTooltip:Hide() end

local function CreateMinimapButton()
    local btn = CreateFrame("Button", "RNPackMinimapBtn", Minimap)
    btn:SetFrameStrata("MEDIUM")
    btn:SetWidth(31); btn:SetHeight(31)
    btn:SetFrameLevel(8)
    btn:RegisterForClicks("anyUp")
    btn:RegisterForDrag("LeftButton")
    btn:SetHighlightTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight")

    local overlay = btn:CreateTexture(nil, "OVERLAY")
    overlay:SetWidth(53); overlay:SetHeight(53)
    overlay:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")
    overlay:SetPoint("TOPLEFT")

    local icon = btn:CreateTexture(nil, "BACKGROUND")
    icon:SetWidth(20); icon:SetHeight(20)
    icon:SetTexture(MINIMAP_ICON)
    icon:SetTexCoord(0.05, 0.95, 0.05, 0.95)
    icon:SetPoint("TOPLEFT", 7, -5)
    btn.icon = icon

    btn:SetScript("OnDragStart", OnMinimapDragStart)
    btn:SetScript("OnDragStop",  OnMinimapDragStop)
    btn:SetScript("OnClick",     OnMinimapClick)
    btn:SetScript("OnEnter",     OnMinimapEnter)
    btn:SetScript("OnLeave",     OnMinimapLeave)

    RNPack_UpdateMinimapPos(btn)
    P.CreateMinimapButton = nil
end
P.CreateMinimapButton = CreateMinimapButton
farmFrame:Hide()
