--------------------------------------------------------------------------------
-- S-Frames: Bag Module Features (Bags/Features.lua)
-- Auto-sell grey + search apply (buttons are now built in Container.lua)
--------------------------------------------------------------------------------

SFrames.Bags.Features = {}

function SFrames.Bags.Features:Initialize()
    self:SetupAutoSell()
    self:SetupAutoOpenBags()
end

-- Auto Sell Grey Items when merchant opens
function SFrames.Bags.Features:SetupAutoSell()
    local f = CreateFrame("Frame")
    f:RegisterEvent("MERCHANT_SHOW")
    f:SetScript("OnEvent", function()
        if not (SFramesDB and SFramesDB.Bags and SFramesDB.Bags.sellGrey) then return end
        for bag = 0, 4 do
            for slot = 1, GetContainerNumSlots(bag) do
                local link = GetContainerItemLink(bag, slot)
                if link then
                    -- Extract item ID from link (format: item:XXXX:...)
                    local _, _, itemString = string.find(link, "item:(%d+)")
                    if itemString then
                        local _, _, _, _, _, _, _, _, _, _, itemSellPrice = GetItemInfo("item:" .. itemString)
                        -- GetItemInfo returns quality as 5th return
                        local _, _, itemRarity = GetItemInfo("item:" .. itemString)
                        -- safer: use a scan tooltip to get quality
                        local scanName, _, scanRarity = GetItemInfo("item:" .. itemString)
                        if scanRarity and scanRarity == 0 then
                            local _, itemCount = GetContainerItemInfo(bag, slot)
                            UseContainerItem(bag, slot)
                            if scanName then
                                SFrames:Print("售出: " .. scanName .. " x" .. (itemCount or 1))
                            end
                        end
                    end
                end
            end
        end
    end)
end

-- Auto open/close bags at Bank, Merchant, Mail, AH, Trade
function SFrames.Bags.Features:SetupAutoOpenBags()
    local f = CreateFrame("Frame")
    f:RegisterEvent("MERCHANT_SHOW")
    f:RegisterEvent("BANKFRAME_OPENED")
    f:RegisterEvent("MAIL_SHOW")
    f:RegisterEvent("AUCTION_HOUSE_SHOW")
    f:RegisterEvent("TRADE_SHOW")

    f:RegisterEvent("MERCHANT_CLOSED")
    f:RegisterEvent("BANKFRAME_CLOSED")
    f:RegisterEvent("MAIL_CLOSED")
    f:RegisterEvent("AUCTION_HOUSE_CLOSED")
    f:RegisterEvent("TRADE_CLOSED")

    local autoOpened = false

    f:SetScript("OnEvent", function()
        if not (SFramesDB and SFramesDB.Bags and SFramesDB.Bags.enable) then return end
        
        -- Shows
        if event == "MERCHANT_SHOW" or event == "BANKFRAME_OPENED" or event == "MAIL_SHOW" or event == "AUCTION_HOUSE_SHOW" or event == "TRADE_SHOW" then
            if SFramesBagFrame and not SFramesBagFrame:IsVisible() then
                autoOpened = true
                SFrames.Bags.Container:Open()
            end
        -- Closes
        elseif event == "MERCHANT_CLOSED" or event == "BANKFRAME_CLOSED" or event == "MAIL_CLOSED" or event == "AUCTION_HOUSE_CLOSED" or event == "TRADE_CLOSED" then
            if autoOpened then
                SFrames.Bags.Container:Close()
                autoOpened = false
            end
        end
    end)
end

-- Search filter - called from the search EditBox OnTextChanged
function SFrames.Bags.Features:ApplySearch(query)
    -- In WoW 1.12 Chinese client, text is GBK encoded. 
    -- using string.lower on GBK strings corrupts Chinese characters because the 2nd byte 
    -- of Chinese characters can hit the ASCII uppercase range (A-Z).
    local safeQuery = query or ""
    safeQuery = string.gsub(safeQuery, "^%s+", "")
    safeQuery = string.gsub(safeQuery, "%s+$", "")
    if not string.find(safeQuery, "%S") then
        safeQuery = ""
    end
    
    local function ProcessSlots(prefix)
        for i = 1, 250 do
            local btn = _G[prefix .. i]
            if not btn then break end
            
            local icon = _G[btn:GetName() .. "IconTexture"]
            
            if btn:IsShown() and icon then
                if safeQuery == "" then
                    icon:SetVertexColor(1, 1, 1)
                    if btn.border then btn.border:SetAlpha(1) end
                    if btn.junkIcon then btn.junkIcon:SetAlpha(1) end
                    if btn.qualGlow then btn.qualGlow:SetAlpha(0.8) end
                elseif btn.bagID ~= nil and btn.slotID ~= nil then
                    local link = GetContainerItemLink(btn.bagID, btn.slotID)
                    if link then
                        local name = GetItemInfo(link)
                        if not name then
                            local _, _, parsedName = string.find(link, "%[(.+)%]")
                            name = parsedName
                        end
                        
                        -- Exact substring match (safe for GBK)
                        if name and string.find(name, safeQuery, 1, true) then
                            icon:SetVertexColor(1, 1, 1)
                            if btn.border then btn.border:SetAlpha(1) end
                            if btn.junkIcon then btn.junkIcon:SetAlpha(1) end
                            if btn.qualGlow then btn.qualGlow:SetAlpha(0.8) end
                        else
                            icon:SetVertexColor(0.45, 0.45, 0.45)
                            if btn.border then btn.border:SetAlpha(0.4) end
                            if btn.junkIcon then btn.junkIcon:SetAlpha(0.4) end
                            if btn.qualGlow then btn.qualGlow:SetAlpha(0.15) end
                        end
                    else
                        icon:SetVertexColor(0.45, 0.45, 0.45)
                        if btn.border then btn.border:SetAlpha(0.4) end
                        if btn.junkIcon then btn.junkIcon:SetAlpha(0.4) end
                        if btn.qualGlow then btn.qualGlow:SetAlpha(0.15) end
                    end
                end
            end
        end
    end

    ProcessSlots("SFramesBagSlot")
end
