local addonName, TC = ...
TC.Mail = CreateFrame("Frame")

-- Listen for the mailbox opening and closing
TC.Mail:RegisterEvent("MAIL_SHOW")
TC.Mail:RegisterEvent("MAIL_CLOSED")

-- Create the Auto-Fill Button on the Blizzard SendMail frame
local mailBtn = CreateFrame("Button", "TCMailButton", SendMailFrame, "UIPanelButtonTemplate")
mailBtn:SetSize(160, 25)
mailBtn:SetPoint("TOPLEFT", SendMailFrame, "TOPRIGHT", 5, -50) 
mailBtn:SetText("TownCrier: Fill Payout")
mailBtn:Hide()

TC.Mail:SetScript("OnEvent", function(self, event)
    if event == "MAIL_SHOW" then
        mailBtn:Show()
    elseif event == "MAIL_CLOSED" then
        mailBtn:Hide()
    end
end)

mailBtn:SetScript("OnClick", function()
    local payouts = TC.db.profile.pendingPayouts
    local nextPlayer, amount = nil, 0
    
    -- Grab the first person in the ledger who is owed gold
    for name, goldOwed in pairs(payouts) do
        nextPlayer = name
        amount = goldOwed
        break
    end
    
    if not nextPlayer then
        print("|cFFFFD100TownCrier:|r Your Purse is empty. No payouts pending!")
        return
    end
    
    -- Fill the Blizzard UI Boxes
    SendMailNameEditBox:SetText(nextPlayer)
    SendMailSubjectEditBox:SetText("TownCrier Trivia Winnings!")
    
    -- Convert copper to Gold/Silver/Copper
    local gold = math.floor(amount / 10000)
    local silver = math.floor((amount - (gold * 10000)) / 100)
    local copper = amount % 100
    
    SendMailMoneyGold:SetText(gold)
    SendMailMoneySilver:SetText(silver)
    SendMailMoneyCopper:SetText(copper)
    
    -- Remove them from the pending list so the next click grabs the next winner!
    TC.db.profile.pendingPayouts[nextPlayer] = nil
    if TC.UI and TC.UI.UpdatePurse then TC.UI:UpdatePurse() end
    
    print("|cFFFFD100TownCrier:|r Filled payout for " .. nextPlayer .. ". Press Send!")
    if TC.LogToLedger then
        TC:LogToLedger("|cFFFFFF00[Mailbox]|r Pre-filled " .. gold .. "g payout for " .. nextPlayer)
    end
end)