local addonName, TC = ...
TC.UI = TC.UI or {}

local TABS = {"Trivia", "Leaderboard", "Proclamations", "Purse", "The Ledger"}

function TC.UI:CreateMainFrame()
    if self.MainFrame then return end
    
    local f = CreateFrame("Frame", "TownCrierMain", UIParent, "PortraitFrameTemplate")
    f:SetSize(460, 600)
    f:SetPoint("CENTER")
    f:SetClampedToScreen(true)
    f:SetMovable(true)
    f:EnableMouse(true)
    f:RegisterForDrag("LeftButton")
    f:SetScript("OnDragStart", f.StartMoving)
    f:SetScript("OnDragStop", f.StopMovingOrSizing)
    f:Hide()
    tinsert(UISpecialFrames, "TownCrierMain")
    
    local getVersion = C_AddOns and C_AddOns.GetAddOnMetadata or GetAddOnMetadata
    local version = getVersion(addonName, "Version") or "1.2.5"
    f:SetTitle("TownCrier by ForgeDMC v" .. version)
    
    if f.SetPortraitToAsset then f:SetPortraitToAsset("Interface\\Icons\\INV_Misc_Bell_01") end
    local portraitTex = f.portrait or (f.PortraitContainer and f.PortraitContainer.portrait)
    if portraitTex then
        portraitTex:SetTexture("Interface\\Icons\\INV_Misc_Bell_01")
        portraitTex:SetTexCoord(0.05, 0.95, 0.05, 0.95)
    end

    -- [[ TOP HEADER BUTTONS ]]
    local btnChannel = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    btnChannel:SetSize(80, 22)
    btnChannel:SetPoint("TOPRIGHT", f, "TOPRIGHT", -10, -30)
    if not TC.db.profile.channel then TC.db.profile.channel = "GUILD" end
    btnChannel:SetText("Ch: " .. TC.db.profile.channel)
    btnChannel:SetScript("OnClick", function(btn)
        if TC.db.profile.channel == "GUILD" then TC.db.profile.channel = "SAY"
        elseif TC.db.profile.channel == "SAY" then TC.db.profile.channel = "PARTY"
        else TC.db.profile.channel = "GUILD" end
        btn:SetText("Ch: " .. TC.db.profile.channel)
        print("|cFFFFD100TownCrier:|r Output changed to /" .. TC.db.profile.channel)
    end)

    -- NEW: TEST CONNECTION BUTTON
    local btnTest = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    btnTest:SetSize(60, 22)
    btnTest:SetPoint("RIGHT", btnChannel, "LEFT", -5, 0)
    btnTest:SetText("📡 Test")
    btnTest:SetScript("OnClick", function()
        local chan = TC.db.profile.channel or "GUILD"
        SendChatMessage("TownCrier: Connection Test... Loud and Clear!", chan)
    end)

    local btnHowTo = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    btnHowTo:SetSize(80, 22)
    btnHowTo:SetPoint("RIGHT", btnTest, "LEFT", -5, 0)
    btnHowTo:SetText("❓ HowTo")
    btnHowTo:SetScript("OnClick", function()
        LibStub("AceConfigDialog-3.0"):Open("TownCrier")
    end)

    f.Tabs = {}
    for i, name in ipairs(TABS) do
        local content = CreateFrame("Frame", nil, f)
        content:SetSize(420, 500)
        content:SetPoint("TOP", f, "TOP", 0, -65)
        content:Hide()
        f.Tabs[name] = content
        
        local tab = CreateFrame("Button", "TownCrierMainTab"..i, f, "PanelTabButtonTemplate")
        tab:SetID(i)
        tab:SetText(name)
        if i == 1 then tab:SetPoint("TOPLEFT", f, "BOTTOMLEFT", 15, 2)
        else tab:SetPoint("LEFT", _G["TownCrierMainTab"..(i-1)], "RIGHT", 2, 0) end
        tab:SetScript("OnClick", function() TC.UI:SelectTab(name) end)
        f["TabBtn"..name] = tab
    end

    self:PopulateTrivia(f.Tabs["Trivia"])
    self:PopulateLeaderboard(f.Tabs["Leaderboard"])
    self:PopulateProclamations(f.Tabs["Proclamations"])
    self:PopulatePurse(f.Tabs["Purse"])
    self:PopulateTheLedger(f.Tabs["The Ledger"])

    self.MainFrame = f
    TC.UI:SelectTab("Proclamations")
end

-- ==========================================
-- TAB 3: PROCLAMATIONS
-- ==========================================
function TC.UI:PopulateProclamations(frame)
    local bg = CreateFrame("Frame", nil, frame, "BackdropTemplate")
    bg:SetSize(400, 70)
    bg:SetPoint("TOP", 0, -5)
    bg:SetBackdrop({bgFile = "Interface\\ChatFrame\\ChatFrameBackground", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", edgeSize = 14, insets = {4,4,4,4}})
    bg:SetBackdropColor(0,0,0,0.8)

    -- The Timer text object
    TC.UI.timerText = bg:CreateFontString(nil, "OVERLAY", "GameFontHighlightHuge")
    TC.UI.timerText:SetPoint("CENTER", 0, 0)
    TC.UI.timerText:SetText("00:00")
    TC.UI.timerText:SetScale(1.5)

    local btnBroadcast = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    btnBroadcast:SetSize(195, 30)
    btnBroadcast:SetPoint("TOPLEFT", bg, "BOTTOMLEFT", 0, -5)
    btnBroadcast:SetText("Manual Broadcast")
    btnBroadcast:SetScript("OnClick", function() TC.Broadcaster:Execute() end)

    local btnPause = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    btnPause:SetSize(195, 30)
    btnPause:SetPoint("TOPRIGHT", bg, "BOTTOMRIGHT", 0, -5)
    btnPause:SetText(TC.db.profile.enabled and "Pause Automation" or "Resume Automation")
    btnPause:SetScript("OnClick", function(btn)
        TC.db.profile.enabled = not TC.db.profile.enabled
        btn:SetText(TC.db.profile.enabled and "Pause Automation" or "Resume Automation")
    end)

    local btnFunFact = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    btnFunFact:SetSize(195, 30)
    btnFunFact:SetPoint("TOPLEFT", btnBroadcast, "BOTTOMLEFT", 0, -5)
    btnFunFact:SetText("Post Fun Fact")
    btnFunFact:SetScript("OnClick", function() TC.Broadcaster:BroadcastFunFact() end)

    local autoFactToggle = CreateFrame("CheckButton", "TCAutoFactCheck", frame, "UICheckButtonTemplate")
    autoFactToggle:SetPoint("TOPLEFT", btnPause, "BOTTOMLEFT", 5, -5)
    autoFactToggle:SetSize(26, 26)
    autoFactToggle:SetChecked(TC.db.profile.autoFunFacts)
    _G["TCAutoFactCheckText"]:SetText("Mix Auto-Facts")
    autoFactToggle:SetScript("OnClick", function(check)
        TC.db.profile.autoFunFacts = check:GetChecked()
    end)

    local intervalSlider = CreateFrame("Slider", "TCIntervalSlider", frame, "OptionsSliderTemplate")
    intervalSlider:SetPoint("TOP", frame, "TOP", 0, -170)
    intervalSlider:SetMinMaxValues(1, 60)
    intervalSlider:SetValueStep(1)
    intervalSlider:SetObeyStepOnDrag(true)
    intervalSlider:SetWidth(380)
    intervalSlider:SetValue(TC.db.profile.interval or 15)
    _G[intervalSlider:GetName() .. "Text"]:SetText("Broadcast Interval: " .. (TC.db.profile.interval or 15) .. " min")
    intervalSlider:SetScript("OnValueChanged", function(s, val)
        TC.db.profile.interval = val
        _G[s:GetName() .. "Text"]:SetText("Broadcast Interval: " .. val .. " min")
        TC.Broadcaster:UpdateInterval(val)
    end)

    -- Message Editor
    local editBG = CreateFrame("Frame", nil, frame, "BackdropTemplate")
    editBG:SetSize(400, 110)
    editBG:SetPoint("TOP", frame, "TOP", 0, -210)
    editBG:SetBackdrop({bgFile = "Interface\\ChatFrame\\ChatFrameBackground", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", edgeSize = 14, insets = {4,4,4,4}})
    editBG:SetBackdropColor(0,0,0,0.8)

    local scrollFrame = CreateFrame("ScrollFrame", "TCMessageScroll", editBG, "UIPanelScrollFrameTemplate")
    scrollFrame:SetPoint("TOPLEFT", 10, -10)
    scrollFrame:SetPoint("BOTTOMRIGHT", -30, 10)

    local editBox = CreateFrame("EditBox", "TCMessageEdit", scrollFrame)
    editBox:SetMultiLine(true)
    editBox:SetFontObject(ChatFontNormal)
    editBox:SetWidth(350)
    editBox:SetAutoFocus(false)
    editBox:SetScript("OnEscapePressed", function(eb) eb:ClearFocus() end)
    scrollFrame:SetScrollChild(editBox)

    local currentMsgs = TC.db.profile.messages or {}
    editBox:SetText(table.concat(currentMsgs, "\n"))

    local btnSaveMsgs = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    btnSaveMsgs:SetSize(180, 25)
    btnSaveMsgs:SetPoint("TOP", editBG, "BOTTOM", 0, -5)
    btnSaveMsgs:SetText("Save Messages")
    btnSaveMsgs:SetScript("OnClick", function()
        editBox:ClearFocus()
        local text = editBox:GetText()
        local newMsgs = {}
        for line in text:gmatch("[^\r\n]+") do table.insert(newMsgs, line) end
        TC.db.profile.messages = newMsgs
        print("|cFFFFD100TownCrier:|r Proclamation messages saved!")
    end)
    
    -- Auto-Welcome Logic
    local welcomeTitle = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    welcomeTitle:SetPoint("TOPLEFT", frame, "TOPLEFT", 15, -370)
    welcomeTitle:SetText("|cFFFFD100Auto-Welcome New Members|r")

    local welcomeToggle = CreateFrame("CheckButton", "TCWelcomeCheck", frame, "UICheckButtonTemplate")
    welcomeToggle:SetPoint("LEFT", welcomeTitle, "RIGHT", 10, 0)
    welcomeToggle:SetSize(24, 24)
    welcomeToggle:SetChecked(TC.db.profile.welcomeEnabled)
    _G["TCWelcomeCheckText"]:SetText("Enable")
    welcomeToggle:SetScript("OnClick", function(check)
        TC.db.profile.welcomeEnabled = check:GetChecked()
    end)

    local welcomeInputBG = CreateFrame("Frame", nil, frame, "BackdropTemplate")
    welcomeInputBG:SetSize(400, 30)
    welcomeInputBG:SetPoint("TOP", frame, "TOP", 0, -395)
    welcomeInputBG:SetBackdrop({bgFile = "Interface\\ChatFrame\\ChatFrameBackground", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", edgeSize = 14, insets = {4,4,4,4}})
    welcomeInputBG:SetBackdropColor(0,0,0,0.8)

    local welcomeInput = CreateFrame("EditBox", "TCWelcomeInput", welcomeInputBG)
    welcomeInput:SetFontObject(ChatFontNormal)
    welcomeInput:SetPoint("TOPLEFT", 10, -5)
    welcomeInput:SetPoint("BOTTOMRIGHT", -10, 5)
    welcomeInput:SetAutoFocus(false)
    welcomeInput:SetText(TC.db.profile.welcomeMessage or "")
    welcomeInput:SetScript("OnEscapePressed", function(eb) eb:ClearFocus() end)

    local btnSaveWelcome = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    btnSaveWelcome:SetSize(180, 25)
    btnSaveWelcome:SetPoint("TOP", welcomeInputBG, "BOTTOM", 0, -5)
    btnSaveWelcome:SetText("Save Welcome Message")
    btnSaveWelcome:SetScript("OnClick", function()
        welcomeInput:ClearFocus()
        TC.db.profile.welcomeMessage = welcomeInput:GetText()
        print("|cFFFFD100TownCrier:|r Welcome message saved!")
    end)
end

-- ==========================================
-- POPULATE OTHER TABS
-- ==========================================
function TC.UI:PopulateTrivia(frame)
    local btnStart = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    btnStart:SetSize(240, 45)
    btnStart:SetPoint("TOP", 0, -10)
    btnStart:SetText("Start Trivia Round")
    btnStart:SetScript("OnClick", function() TC.Trivia:StartRound() end)

    local btnHint = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    btnHint:SetSize(110, 30)
    btnHint:SetPoint("TOPLEFT", btnStart, "BOTTOMLEFT", -10, -5)
    btnHint:SetText("Send Hint")
    btnHint:SetScript("OnClick", function() TC.Trivia:SendHint() end)

    local btnReset = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    btnReset:SetSize(110, 30)
    btnReset:SetPoint("TOPRIGHT", btnStart, "BOTTOMRIGHT", 10, -5)
    btnReset:SetText("Reset Streak")
    btnReset:SetScript("OnClick", function() TC.Trivia:ResetStreaks() end)

    local histBG = CreateFrame("Frame", nil, frame, "BackdropTemplate")
    histBG:SetSize(400, 360)
    histBG:SetPoint("TOP", btnStart, "BOTTOM", 0, -45)
    histBG:SetBackdrop({bgFile = "Interface\\ChatFrame\\ChatFrameBackground", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", edgeSize = 14, insets = {4,4,4,4}})
    histBG:SetBackdropColor(0,0,0,0.8)
    
    frame.historyText = histBG:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    frame.historyText:SetPoint("TOPLEFT", 15, -15)
    frame.historyText:SetJustifyH("LEFT")
end

function TC.UI:PopulateLeaderboard(frame)
    local lbBG = CreateFrame("Frame", nil, frame, "BackdropTemplate")
    lbBG:SetSize(400, 400)
    lbBG:SetPoint("TOP", 0, -10)
    lbBG:SetBackdrop({bgFile = "Interface\\ChatFrame\\ChatFrameBackground", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", edgeSize = 14, insets = {4,4,4,4}})
    lbBG:SetBackdropColor(0,0,0,0.8)

    frame.lbText = lbBG:CreateFontString(nil, "OVERLAY", "GameFontHighlightLarge")
    frame.lbText:SetPoint("TOPLEFT", 15, -15)
    frame.lbText:SetJustifyH("LEFT")

    local btnAnnounce = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    btnAnnounce:SetSize(220, 40)
    btnAnnounce:SetPoint("TOP", lbBG, "BOTTOM", 0, -10)
    btnAnnounce:SetText("Post Standings to Guild")
    btnAnnounce:SetScript("OnClick", function() 
        if TC.Leaderboard then TC.Leaderboard:AnnounceTopScholars() end 
    end)
end

function TC.UI:PopulatePurse(frame)
    local rewardSlider = CreateFrame("Slider", "TCRewardSlider", frame, "OptionsSliderTemplate")
    rewardSlider:SetPoint("TOP", 0, -25)
    rewardSlider:SetMinMaxValues(10, 500)
    rewardSlider:SetValueStep(10)
    rewardSlider:SetWidth(280)
    rewardSlider:SetValue((TC.db.profile.rewardAmount or 50000) / 10000)
    
    _G[rewardSlider:GetName() .. "Text"]:SetText("Trivia Base Reward: " .. rewardSlider:GetValue() .. "g")
    rewardSlider:SetScript("OnValueChanged", function(s, val)
        TC.db.profile.rewardAmount = val * 10000
        _G[s:GetName() .. "Text"]:SetText("Trivia Base Reward: " .. val .. "g")
    end)

    local purseBG = CreateFrame("Frame", nil, frame, "BackdropTemplate")
    purseBG:SetSize(400, 340)
    purseBG:SetPoint("TOP", rewardSlider, "BOTTOM", 0, -20)
    purseBG:SetBackdrop({bgFile = "Interface\\ChatFrame\\ChatFrameBackground", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", edgeSize = 14, insets = {4,4,4,4}})
    purseBG:SetBackdropColor(0,0,0,0.8)

    frame.purseText = purseBG:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    frame.purseText:SetPoint("TOPLEFT", 15, -15)
    frame.purseText:SetJustifyH("LEFT")

    local btnClear = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    btnClear:SetSize(180, 40)
    btnClear:SetPoint("TOP", purseBG, "BOTTOM", 0, -10)
    btnClear:SetText("Clear Purse Data")
    btnClear:SetScript("OnClick", function() 
        TC.db.profile.pendingPayouts = {}
        TC.UI:UpdatePurse() 
    end)
end

function TC.UI:PopulateTheLedger(frame)
    local bg = CreateFrame("Frame", nil, frame, "BackdropTemplate")
    bg:SetSize(400, 390) 
    bg:SetPoint("TOP", 0, -10)
    bg:SetBackdrop({bgFile = "Interface\\ChatFrame\\ChatFrameBackground", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", edgeSize = 14, insets = {4,4,4,4}})
    bg:SetBackdropColor(0,0,0,0.8)

    local sf = CreateFrame("ScrollingMessageFrame", "TownCrierLedgerLog", bg)
    sf:SetPoint("TOPLEFT", 10, -10)
    sf:SetPoint("BOTTOMRIGHT", -25, 10) 
    sf:SetFontObject(ChatFontNormal)
    sf:SetFading(false)
    sf:SetMaxLines(500)
    sf:SetInsertMode("BOTTOM")
    TC.UI.LedgerText = sf

    sf:EnableMouseWheel(true)
    sf:SetScript("OnMouseWheel", function(self, delta)
        if delta > 0 then self:ScrollUp() else self:ScrollDown() end
    end)

    sf:AddMessage("|cFFFFD100--- Live Chat Ledger Started ---|r")
end

-- ==========================================
-- LIVE UPDATES
-- ==========================================
function TC.UI:UpdateHistory()
    if not self.MainFrame then return end
    local frame = self.MainFrame.Tabs["Trivia"]
    if not frame or not TC.Trivia.History then return end
    local str = "|cFFFFD100Session History:|r\n\n"
    for i = #TC.Trivia.History, math.max(1, #TC.Trivia.History - 12), -1 do
        local h = TC.Trivia.History[i]
        str = str .. "|cFF00FF00" .. (h.winner or "None") .. "|r: " .. (h.question or ""):sub(1,35) .. "...\n"
    end
    frame.historyText:SetText(str)
end

function TC.UI:UpdateLeaderboard()
    if not self.MainFrame then return end
    local frame = self.MainFrame.Tabs["Leaderboard"]
    if not frame or not TC.Leaderboard then return end
    local players = TC.Leaderboard:GetTopPlayers(15)
    local str = "|cFFFFD100Season Leaderboard:|r\n\n"
    for i, p in ipairs(players) do str = str .. i .. ". " .. p.name .. " - " .. p.score .. " wins\n" end
    frame.lbText:SetText(str)
end

function TC.UI:UpdatePurse()
    if not self.MainFrame then return end
    local frame = self.MainFrame.Tabs["Purse"]
    if not frame then return end
    local payouts = TC.db.profile.pendingPayouts or {}
    local str = "|cFFFFD100Purse Ledger:|r\n\n"
    for name, amt in pairs(payouts) do str = str .. name .. ": " .. (amt/10000) .. "g\n" end
    frame.purseText:SetText(str)
end

function TC.UI:SelectTab(name)
    if not self.MainFrame then self:CreateMainFrame() end
    for i, tabName in ipairs(TABS) do
        local f = self.MainFrame.Tabs[tabName]
        local btn = self.MainFrame["TabBtn"..tabName]
        if tabName == name then f:Show(); PanelTemplates_SelectTab(btn)
        else f:Hide(); PanelTemplates_DeselectTab(btn) end
    end
    if name == "Trivia" then self:UpdateHistory() end
    if name == "Leaderboard" then self:UpdateLeaderboard() end
    if name == "Purse" then self:UpdatePurse() end
end

function TC.UI:Toggle()
    if not self.MainFrame then self:CreateMainFrame() end
    if self.MainFrame:IsShown() then self.MainFrame:Hide() else self.MainFrame:Show() end
end