-- ============================================================
-- RealNibba.AHMail.lua  - AH Popup + Mail Popup
-- Clamped to AuctionFrame/MailFrame, appear automatically
-- ============================================================
local P = RNPack

local function MakePopupWindow(name, title, w, h)
    local f = CreateFrame("Frame", name, UIParent)
    f:SetSize(w, h)
    f:SetBackdrop({
        bgFile="Interface/DialogFrame/UI-DialogBox-Background",
        edgeFile="Interface/DialogFrame/UI-DialogBox-Border",
        tile=true,tileSize=32,edgeSize=32,
        insets={left=11,right=12,top=12,bottom=11}
    })
    P.ApplyBG(f, true)
    f:SetToplevel(true)
    f:SetClampedToScreen(true)
    f:SetScript("OnMouseDown",function() f:Raise() end)
    f:Hide()
    -- Internal title bar (WoW native style, no external parchment)
    local lbl=f:CreateFontString(nil,"OVERLAY","GameFontNormal")
    lbl:SetPoint("TOP",f,"TOP",0,-14); lbl:SetText(title)
    local div=f:CreateTexture(nil,"ARTWORK"); div:SetHeight(1)
    div:SetPoint("TOPLEFT", f,"TOPLEFT", 10,-24)
    div:SetPoint("TOPRIGHT",f,"TOPRIGHT",-10,-24)
    div:SetTexture(0.4,0.35,0.25,0.9)
    -- Close
    local x=CreateFrame("Button",nil,f,"UIPanelCloseButton")
    x.isCloseBtn=true
    x:SetPoint("TOPRIGHT",f,"TOPRIGHT",-6,-6)
    x:SetScript("OnClick",function() f:Hide() end)
    return f
end

-- ============================================================
-- AH POPUP  (clamped to right side of AuctionFrame + 5px gap)
-- ============================================================
local ahPopup = MakePopupWindow("RNPackAHPopup","Auction House",180,150)
if P.RegisterScalableFrame then P.RegisterScalableFrame(ahPopup) end

local ahPostedLbl = ahPopup:CreateFontString(nil,"OVERLAY","GameFontNormal")
ahPostedLbl:SetPoint("TOPLEFT",ahPopup,"TOPLEFT",14,-30)
ahPostedLbl:SetTextColor(0.8,0.8,0.8,1); ahPostedLbl:SetText("Posted Auctions:")
local ahPostedVal = ahPopup:CreateFontString(nil,"OVERLAY","GameFontNormal")
ahPostedVal:SetPoint("TOPLEFT",ahPopup,"TOPLEFT",14,-46)
ahPostedVal:SetTextColor(1,0.82,0,1); ahPostedVal:SetText("--")

local ahIncomeLbl = ahPopup:CreateFontString(nil,"OVERLAY","GameFontNormal")
ahIncomeLbl:SetPoint("TOPLEFT",ahPopup,"TOPLEFT",14,-68)
ahIncomeLbl:SetTextColor(0.8,0.8,0.8,1); ahIncomeLbl:SetText("Incoming Gold:")
local ahIncomeVal = ahPopup:CreateFontString(nil,"OVERLAY","GameFontNormal")
ahIncomeVal:SetPoint("TOPLEFT",ahPopup,"TOPLEFT",14,-84)
ahIncomeVal:SetTextColor(0.2,1,0.3,1); ahIncomeVal:SetText("--")

local btnScanAH2 = CreateFrame("Button",nil,ahPopup,"UIPanelButtonTemplate")
btnScanAH2:SetSize(160,22)
btnScanAH2:SetPoint("BOTTOM",ahPopup,"BOTTOM",0,12)
btnScanAH2:SetText("Scan Auctions")

local function DoAHScan()
    if not AuctionFrame or not AuctionFrame:IsShown() then return end
    local total,incoming = 0,0
    local num = GetNumAuctionItems("owner")
    for i=1,num do
        local count,_,_,_,_,_,buyout = select(3, GetAuctionItemInfo("owner",i))
        if buyout and buyout>0 then
            total = total+buyout
            if count==0 then incoming=incoming+buyout end
        end
    end
    ahPostedVal:SetText(total>0 and P.FormatMoney(total) or "0g")
    ahIncomeVal:SetText(incoming>0 and P.FormatMoney(incoming) or "0g")
    P.ahPosted   = total
    P.ahIncoming = incoming
end

btnScanAH2:SetScript("OnClick", DoAHScan)

function P.OpenAHPopup()
    if not AuctionFrame or not AuctionFrame:IsShown() then
        P.prt("Open the Auction House first!"); return
    end
    -- Clamp to right side of AH with 5px gap
    ahPopup:ClearAllPoints()
    ahPopup:SetPoint("TOPLEFT", AuctionFrame, "TOPRIGHT", 2, -12)
    ahPopup:Show(); ahPopup:Raise()
    DoAHScan()
end

-- ============================================================
-- MAIL POPUP  (clamped to right side of MailFrame + 5px gap)
-- Auto-shows on MAIL_SHOW, auto-hides on MAIL_CLOSED
-- ============================================================
local mailPopup = MakePopupWindow("RNPackMailPopup","Mailbox Gold",220,200)
if P.RegisterScalableFrame then P.RegisterScalableFrame(mailPopup) end

local mailLbl = mailPopup:CreateFontString(nil,"OVERLAY","GameFontNormal")
mailLbl:SetPoint("TOPLEFT",mailPopup,"TOPLEFT",14,-30)
mailLbl:SetTextColor(0.8,0.8,0.8,1); mailLbl:SetText("AH Mail Gold:")
local mailVal = mailPopup:CreateFontString(nil,"OVERLAY","GameFontNormal")
mailVal:SetPoint("TOPLEFT",mailPopup,"TOPLEFT",14,-46)
mailVal:SetTextColor(1,0.82,0,1); mailVal:SetText("--")

-- Two-line info label (word wrap via two stacked FontStrings)
local mailInfoLbl = mailPopup:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
mailInfoLbl:SetPoint("TOPLEFT",mailPopup,"TOPLEFT",14,-68)
mailInfoLbl:SetWidth(192)
mailInfoLbl:SetWordWrap(true)
mailInfoLbl:SetNonSpaceWrap(false)
mailInfoLbl:SetJustifyH("LEFT")
mailInfoLbl:SetTextColor(0.6,0.6,0.6,1)
mailInfoLbl:SetText("Showing up to 50 mails.")

local mailInfoLbl2 = mailPopup:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
mailInfoLbl2:SetPoint("TOPLEFT",mailPopup,"TOPLEFT",14,-106)
mailInfoLbl2:SetWidth(192)
mailInfoLbl2:SetWordWrap(true)
mailInfoLbl2:SetNonSpaceWrap(false)
mailInfoLbl2:SetJustifyH("LEFT")
mailInfoLbl2:SetTextColor(0.6,0.6,0.6,1)
mailInfoLbl2:SetText("Collect mails to see more.")

local btnQueryMail = CreateFrame("Button",nil,mailPopup,"UIPanelButtonTemplate")
btnQueryMail:SetSize(180,22)
btnQueryMail:SetPoint("BOTTOM",mailPopup,"BOTTOM",0,12)
btnQueryMail:SetText("Reload Mail")

local function DoMailScan()
    local total=0; local ahCount=0; local totalMails=GetInboxNumItems()
    for i=1,totalMails do
        local _,_,sender,subject,money=GetInboxHeaderInfo(i)
        if money and money>0 and sender then
            local s=string.lower(sender)
            local sub=subject and string.lower(subject) or ""
            if string.find(s,"auction") or string.find(sub,"sold") or string.find(sub,"auction") then
                total=total+money; ahCount=ahCount+1
            end
        end
    end
    mailVal:SetText(total>0 and P.FormatMoney(total) or "0g")
    -- Line 1: counts
    mailInfoLbl:SetText("From "..ahCount.." AH mails / "..totalMails.." total loaded.")
    -- Line 2: cap warning or all-clear
    if totalMails>=50 then
        mailInfoLbl2:SetText("|cffFF4444Cap reached - some mail not shown.|r") 
    else
        mailInfoLbl2:SetText("|cff00CC00All "..totalMails.." mails scanned.|r")
    end
    P.mailGold=total
end

btnQueryMail:SetScript("OnClick",function()
    -- ReloadUI gets completely fresh mail data from server
    ReloadUI()
end)

-- Auto-show/hide on AH open/close (same pattern as mailbox)
local ahEvFrame=CreateFrame("Frame")
ahEvFrame:RegisterEvent("AUCTION_HOUSE_SHOW")
ahEvFrame:RegisterEvent("AUCTION_HOUSE_CLOSED")
ahEvFrame:SetScript("OnEvent",function(self,event)
    if event=="AUCTION_HOUSE_SHOW" then
        ahPopup:ClearAllPoints()
        ahPopup:SetPoint("TOPLEFT",AuctionFrame,"TOPRIGHT",2,-12)
        ahPopup:Show(); ahPopup:Raise()
        -- Scan after 1.5s for AH data to load
        local t=0
        ahEvFrame:SetScript("OnUpdate",function(s,e)
            t=t+e; if t>=1.5 then
                s:SetScript("OnUpdate",nil); DoAHScan()
            end
        end)
    elseif event=="AUCTION_HOUSE_CLOSED" then
        ahPopup:Hide()
        ahEvFrame:SetScript("OnUpdate",nil)
    end
end)

-- Auto-show/hide on mailbox open/close
local mailEvFrame=CreateFrame("Frame")
mailEvFrame:RegisterEvent("MAIL_SHOW")
mailEvFrame:RegisterEvent("MAIL_CLOSED")
mailEvFrame:SetScript("OnEvent",function(self,event)
    if event=="MAIL_SHOW" then
        mailPopup:ClearAllPoints()
        mailPopup:SetPoint("TOPLEFT",MailFrame,"TOPRIGHT",2,-12)
        mailPopup:Show(); mailPopup:Raise()
        -- Scan after 0.5s for data to load
        local t=0
        mailEvFrame:SetScript("OnUpdate",function(s,e)
            t=t+e; if t>=0.5 then
                s:SetScript("OnUpdate",nil); DoMailScan()
            end
        end)
    elseif event=="MAIL_CLOSED" then
        mailPopup:Hide()
        mailEvFrame:SetScript("OnUpdate",nil)
    end
end)
