-- ============================================================
-- RealNibba.Bags.lua  - Bag Scanner
-- BOE items only (soulbound excluded)
-- Item list with quality colors, counts, values
-- ============================================================
local P = RNPack

local bagPopup, bagTotal, bagBreak, bagScroll, bagChild
local bagRows    = {}
local bagQualRows= {}

bagPopup = CreateFrame("Frame","RNPackBagPopup",UIParent)
bagPopup:SetSize(360,460)
bagPopup:SetFrameStrata("DIALOG"); bagPopup:SetFrameLevel(100)
bagPopup:SetToplevel(true)
bagPopup:SetBackdrop(P.BACKDROP_DARK)
bagPopup:SetBackdropBorderColor(0.4,0.35,0.25,0.9)
P.ApplyBG(bagPopup)
bagPopup:SetScript("OnMouseDown",function() bagPopup:Raise() end)
bagPopup:SetMovable(true); bagPopup:EnableMouse(true)
bagPopup:RegisterForDrag("LeftButton")
bagPopup:SetScript("OnDragStart",function() bagPopup:StartMoving() end)
bagPopup:SetScript("OnDragStop", function() bagPopup:StopMovingOrSizing() end)
bagPopup:SetClampedToScreen(true)
bagPopup:Hide()
if P.RegisterScalableFrame then P.RegisterScalableFrame(bagPopup) end

-- Title
local bagTitleLbl=bagPopup:CreateFontString(nil,"OVERLAY","GameFontNormal")
bagTitleLbl:SetPoint("TOP",bagPopup,"TOP",0,-10)
bagTitleLbl:SetText("|cffCC2222Bag|r Scanner")
-- Close button
local bagX=CreateFrame("Button",nil,bagPopup,"UIPanelCloseButton")
bagX.isCloseBtn=true
bagX:SetPoint("TOPRIGHT",bagPopup,"TOPRIGHT",-4,-4)
bagX:SetScript("OnClick",function() bagPopup:Hide() end)

-- Total value label
bagTotal = bagPopup:CreateFontString(nil,"OVERLAY","GameFontNormal")
bagTotal:SetPoint("TOPLEFT",bagPopup,"TOPLEFT",14,-28)
bagTotal:SetPoint("TOPRIGHT",bagPopup,"TOPRIGHT",-14,-28)
bagTotal:SetJustifyH("LEFT")
bagTotal:SetTextColor(1,0.82,0,1); bagTotal:SetText("Scan Bags to see value")

-- Quality breakdown label
bagBreak = bagPopup:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
bagBreak:SetPoint("TOPLEFT",bagPopup,"TOPLEFT",14,-46)
bagBreak:SetPoint("TOPRIGHT",bagPopup,"TOPRIGHT",-14,-46)
bagBreak:SetTextColor(0.8,0.8,0.8,1); bagBreak:SetText("")

-- Scroll frame (fixed position, starts at -70, goes to bottom)
bagScroll = CreateFrame("ScrollFrame","RNPackBagScroll",bagPopup,"UIPanelScrollFrameTemplate")
bagScroll:SetPoint("TOPLEFT",  bagPopup,"TOPLEFT",  14,-70)
bagScroll:SetPoint("BOTTOMRIGHT",bagPopup,"BOTTOMRIGHT",-34,14)
bagChild = CreateFrame("Frame",nil,bagScroll)
bagChild:SetWidth(300)
bagChild:SetHeight(1)
bagScroll:SetScrollChild(bagChild)

-- ── Soulbound detection via tooltip scan (created lazily) ───
local _bagTT = nil
local function GetBagTT()
    if not _bagTT then
        _bagTT = CreateFrame("GameTooltip","RNPackBagTT",UIParent,"GameTooltipTemplate")
    end
    return _bagTT
end

local function IsSlotSoulbound(bag, slot)
    local tt = GetBagTT()
    tt:SetOwner(UIParent, "ANCHOR_NONE")
    tt:ClearLines()
    tt:SetBagItem(bag, slot)
    for i = 1, tt:NumLines() do
        local left = _G["RNPackBagTTTextLeft"..i]
        if left then
            local txt = left:GetText() or ""
            if txt == ITEM_SOULBOUND or txt == "Soulbound" then
                tt:Hide(); return true
            end
        end
    end
    tt:Hide(); return false
end

-- ── Scan ────────────────────────────────────────────────────
local QUAL_NAMES = {[0]="Grey",[1]="White",[2]="Green",[3]="Blue",[4]="Purple",[5]="Orange"}
local QUAL_HEX   = {[0]="ff999999",[1]="ffffffff",[2]="ff1eff00",
                    [3]="ff0070dd",[4]="ffa335ee",[5]="ffff8000"}
local QUAL_COLORS= {[0]={0.62,0.62,0.62},[1]={1,1,1},[2]={0.12,1,0},
                    [3]={0,0.44,0.87},[4]={0.64,0.21,0.93},[5]={1,0.5,0}}

local function ScanBags()
    local total = 0
    local byQ   = {[0]=0,[1]=0,[2]=0,[3]=0,[4]=0,[5]=0}
    local items = {}

    for bag = 0,4 do
        for slot = 1, GetContainerNumSlots(bag) do
            local link = GetContainerItemLink(bag, slot)
            if link then
                -- Skip soulbound items
                if not IsSlotSoulbound(bag, slot) then
                    local _, count = GetContainerItemInfo(bag, slot)
                    count = count or 1
                    local price, rarity, name = P.GetItemPrice(link)
                    rarity = rarity or 1
                    local val = (price or 0) * count
                    total = total + val
                    byQ[rarity] = (byQ[rarity] or 0) + val
                    -- Merge stacks
                    local merged = false
                    for _, it in ipairs(items) do
                        if it.link == link then
                            it.count = it.count + count
                            it.value = it.value + val
                            merged = true; break
                        end
                    end
                    if not merged then
                        local iname = name or (GetItemInfo(link)) or "Unknown"
                        items[#items+1] = {link=link, name=iname,
                                           count=count, value=val, rarity=rarity}
                    end
                end
            end
        end
    end

    table.sort(items, function(a,b) return a.value > b.value end)

    -- ── Total label ──────────────────────────────────────────
    bagTotal:SetText("BOE Value: |cffFFD700"..P.FormatMoney(total)..
                     "|r  |cff666666(soulbound excluded)|r")

    -- ── Quality breakdown (compact single line) ──────────────
    for _,r in ipairs(bagQualRows) do r:Hide() end; bagQualRows = {}
    local parts = {}
    for qi = 5,0,-1 do
        if byQ[qi] and byQ[qi] > 0 then
            parts[#parts+1] = string.format("|c%s%s|r: %s",
                QUAL_HEX[qi], QUAL_NAMES[qi], P.FormatMoneyShort(byQ[qi]))
        end
    end
    bagBreak:SetText(table.concat(parts, "  "))

    -- ── Item rows ────────────────────────────────────────────
    for _,r in ipairs(bagRows) do r:Hide() end; bagRows = {}

    local W   = (bagChild:GetWidth() or 300)
    local rowH = 22

    bagChild:SetHeight(math.max(1, #items * rowH + 4))

    if #items == 0 then
        local nl = bagChild:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
        nl:SetPoint("TOPLEFT",bagChild,"TOPLEFT",4,-4)
        nl:SetTextColor(0.5,0.5,0.5,1)
        nl:SetText("No sellable (BOE) items found in bags.")
        bagRows[1] = nl
        return
    end

    for i, item in ipairs(items) do
        local row = CreateFrame("Frame",nil,bagChild)
        row:SetHeight(rowH)
        row:SetPoint("TOPLEFT",  bagChild,"TOPLEFT",  0,-(i-1)*rowH-2)
        row:SetPoint("TOPRIGHT", bagChild,"TOPRIGHT",  0,-(i-1)*rowH-2)

        -- Alternating bg
        local rbg = row:CreateTexture(nil,"BACKGROUND"); rbg:SetAllPoints()
        rbg:SetTexture(i%2==0 and 0.10 or 0.07, 0.04, 0.04, i%2==0 and 0.6 or 0.4)

        -- Icon
        local _,_,_,_,_,_,_,_,_,tex = GetItemInfo(item.link)
        local ico = row:CreateTexture(nil,"ARTWORK")
        ico:SetSize(16,16); ico:SetPoint("LEFT",row,"LEFT",2,0)
        ico:SetTexture(tex or "Interface/Icons/INV_Misc_QuestionMark")

        -- Name x count
        local qc = QUAL_COLORS[item.rarity] or QUAL_COLORS[1]
        local nm = row:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
        local nmW = W - 80
        nm:SetPoint("LEFT",ico,"RIGHT",3,0)
        nm:SetWidth(nmW)
        nm:SetJustifyH("LEFT")
        -- Truncate name to fit column (6.3px/char estimate for GameFontNormalSmall)
        local maxC = math.floor(nmW / 6.3)
        local dispName = item.name
        if #dispName > maxC then dispName = string.sub(dispName,1,maxC-3).."..." end
        nm:SetText(dispName.." x"..item.count)
        nm:SetTextColor(qc[1],qc[2],qc[3],1)
        -- Tooltip on hover shows full name
        local fullLink = item.link
        row:EnableMouse(true)
        row:SetScript("OnEnter", function(self)
            GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
            GameTooltip:SetHyperlink(fullLink)
            GameTooltip:Show()
        end)
        row:SetScript("OnLeave", function() GameTooltip:Hide() end)

        -- Value
        local vl = row:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
        vl:SetPoint("RIGHT",row,"RIGHT",-4,0)
        vl:SetWidth(70); vl:SetJustifyH("RIGHT")
        vl:SetTextColor(1,0.82,0,1)
        vl:SetText(P.FormatMoneyShort(item.value))

        bagRows[#bagRows+1] = row; row:Show()
        if _G.RNPackSkinFrame then _G.RNPackSkinFrame(row) end
    end
end

function P.OpenBagScanner()
    if bagPopup:IsShown() then bagPopup:Hide(); return end
    bagTotal:SetText("|cff888888Scanning...|r")
    bagBreak:SetText("")
    bagPopup:ClearAllPoints()
    bagPopup:SetPoint("CENTER",UIParent,"CENTER",0,0)
    bagPopup:Show(); bagPopup:Raise()
    ScanBags()
end
