local addonName, NS = ...
local GR = NS.GR

-- =========================================================================
-- UI: POPUPS (TBC Port)
-- =========================================================================

function GR:BuildWelcomePopup()
    local f = CreateFrame("Frame", "GRS_WelcomePopup", UIParent)
    f:SetSize(300, 350)
    f:SetPoint("CENTER")
    f:SetFrameStrata("FULLSCREEN_DIALOG")
    f:Hide()
    
    NS.CreateBg(f, 0, 0, 0, 0.95)
    NS.CreateBorder(f, 0.5, 0.5, 0.5, 1)
    GR.WelcomeFrame = f
    
    local title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOP", 0, -15)
    title:SetText(NS.L["CONFIGURE_WELCOME"] or "Configure Welcome Messages")
    
    -- 1. Checkbox for Automation
    local chkWelcome = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
    chkWelcome:SetSize(24, 24)
    chkWelcome:SetPoint("TOPLEFT", 20, -50)
    
    chkWelcome.text = chkWelcome:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    chkWelcome.text:SetPoint("LEFT", chkWelcome, "RIGHT", 5, 0)
    chkWelcome.text:SetText(NS.L["AUTOMATE_WELCOME"] or "Automate Welcome message")
    f.chk = chkWelcome
    
    -- 2. Five EditBoxes for Random Rotation
    local wY = -10 -- Offset relative to Checkbox
    f.inputs = {}
    
    for i = 1, 5 do
        local wb = CreateFrame("EditBox", nil, f, "InputBoxTemplate")
        wb:SetSize(260, 20) 
        wb:SetPoint("TOPLEFT", chkWelcome, "BOTTOMLEFT", 5, wY)
        wb:SetAutoFocus(false)
        wb:SetScript("OnEscapePressed", function(s) s:ClearFocus() end)
        wb:SetScript("OnEnterPressed", function(s) s:ClearFocus() end)
        
        f.inputs[i] = wb
        wY = wY - 25 -- Stack them downwards
    end
    
    -- 3. Test G Message Button
    local btnTestG = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    btnTestG:SetSize(120, 22)
    btnTestG:SetPoint("TOPLEFT", f.inputs[5], "BOTTOMLEFT", 0, -15)
    btnTestG:SetText(NS.L["TEST_G_MESSAGE"] or "Test G message")
    NS.SkinButton(btnTestG)
    
    btnTestG:SetScript("OnClick", function()
        -- Gather candidates from CURRENT INPUTS (so user can test before saving)
        local candidates = {}
        for i=1, 5 do
            local txt = f.inputs[i]:GetText()
            if txt and txt ~= "" then
                table.insert(candidates, txt)
            end
        end
        
        if #candidates == 0 then
            print("GRS: No welcome messages configured.")
            return
        end
        
        -- Logic: No same message > 3 times back-to-back
        if not GR.welcomeState then GR.welcomeState = {lastIdx = 0, repeatCount = 0} end
        
        local idx
        if #candidates > 1 then
             idx = math.random(1, #candidates)
             if idx == GR.welcomeState.lastIdx then
                 GR.welcomeState.repeatCount = GR.welcomeState.repeatCount + 1
             else
                 GR.welcomeState.repeatCount = 0
             end
             
             if GR.welcomeState.repeatCount >= 3 then
                 local safety = 0
                 repeat
                     idx = math.random(1, #candidates)
                     safety = safety + 1
                 until idx ~= GR.welcomeState.lastIdx or safety > 10
                 GR.welcomeState.repeatCount = 0
             end
        else
             idx = 1
        end
        
        GR.welcomeState.lastIdx = idx
        local raw = candidates[idx]
        
        -- Placeholder replacement
        local myName = UnitName("player")
        local myGuild = GetGuildInfo("player") or "Guild"
        local myClass = UnitClass("player")
        
        local msg = raw
        msg = msg:gsub("%[player%]", myName)
        msg = msg:gsub("%[Player%]", myName)
        msg = msg:gsub("%[ownname%]", myName)
        msg = msg:gsub("%[OwnName%]", myName)
        msg = msg:gsub("%[guild%]", myGuild)
        msg = msg:gsub("%[Guild%]", myGuild)
        msg = msg:gsub("%[playerclass%]", myClass)
        msg = msg:gsub("%[PlayerClass%]", myClass)
        
        SendChatMessage(msg, "WHISPER", nil, myName)
        print("GRS: Test Guild Welcome sent to self: " .. msg)
    end)
    
    -- 4. Save Button
    local btnSave = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    btnSave:SetSize(80, 22)
    btnSave:SetPoint("BOTTOMLEFT", 20, 20)
    btnSave:SetText(NS.L["SAVE"] or "Save")
    NS.SkinButton(btnSave)
    
    btnSave:SetScript("OnClick", function()
        -- Commit changes to DB
        GR.db.automateWelcome = chkWelcome:GetChecked()
        if not GR.db.welcomeMessages then GR.db.welcomeMessages = {} end
        
        for i = 1, 5 do
            local rawMsg = f.inputs[i]:GetText()
            if rawMsg ~= "" then
                -- Worst-Case Simulation Validation
                local sim = rawMsg:gsub("[\n\r]", " ")
                sim = sim:gsub("%[player%]", "Deathknight-BoreanTundra")
                sim = sim:gsub("%[Player%]", "Deathknight-BoreanTundra")
                sim = sim:gsub("%[ownname%]", "YourPlayerName")
                sim = sim:gsub("%[OwnName%]", "YourPlayerName")
                sim = sim:gsub("%[guild%]", "<Order of the Silent Nexus>")
                sim = sim:gsub("%[Guild%]", "<Order of the Silent Nexus>")
                sim = sim:gsub("%[playerclass%]", "Demon Hunter")
                sim = sim:gsub("%[PlayerClass%]", "Demon Hunter")
                
                local len = string.len(sim)
                if len > 255 then
                    if GR.ShowTemplateValidationPopup then
                        GR:ShowTemplateValidationPopup("Welcome MSG " .. i, rawMsg, sim, len)
                    end
                    return -- Block all saving visually if ANY fail
                end
            end
            GR.db.welcomeMessages[i] = rawMsg
        end
        
        print("GRS: Welcome messages saved.")
        f:Hide()
    end)
    
    -- 5. Cancel Button
    local btnCancel = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    btnCancel:SetSize(80, 22)
    btnCancel:SetPoint("BOTTOMRIGHT", -20, 20)
    btnCancel:SetText(NS.L["CANCEL"] or "Cancel")
    NS.SkinButton(btnCancel)
    
    btnCancel:SetScript("OnClick", function()
        f:Hide()
    end)
end

function GR:OpenWelcomePopup()
    if not GR.WelcomeFrame then GR:BuildWelcomePopup() end
    
    -- Populate from DB
    if not GR.db.welcomeMessages then GR.db.welcomeMessages = {} end
    
    GR.WelcomeFrame.chk:SetChecked(GR.db.automateWelcome or false)
    for i = 1, 5 do
        GR.WelcomeFrame.inputs[i]:SetText(GR.db.welcomeMessages[i] or "")
    end
    
    GR.WelcomeFrame:Show()
end

function GR:BuildHelpPopup()
    local f = CreateFrame("Frame", "GRS_HelpPopup", UIParent)
    f:SetSize(400, 300)
    f:SetPoint("CENTER")
    f:SetFrameStrata("FULLSCREEN_DIALOG")
    NS.CreateBg(f, 0, 0, 0, 0.95)
    NS.CreateBorder(f, 0.5, 0.5, 0.5, 1)
    
    local close = CreateFrame("Button", nil, f, "UIPanelCloseButton")
    close:SetPoint("TOPRIGHT", -5, -5)
    
    local title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOP", 0, -15)
    title:SetText(NS.L["TEMPLATE_HELP"] or "Template Help")
    
    local content = f:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    content:SetPoint("TOPLEFT", 20, -50)
    content:SetPoint("BOTTOMRIGHT", -20, 20)
    content:SetJustifyH("LEFT")
    content:SetJustifyV("TOP")
    
    local helpText = 
        "Extra functionalities for the message template:\n\n" ..
        "|cff00ffff[player]|r - Scans and mentions the players name.\n" ..
        "|cff00ffff[ownname]|r - Scans and mentions YOUR name.\n" ..
        "|cff00ffff[Guild]|r - Scans and mentions your guilds name.\n" ..
        "|cff00ffff[playerclass]|r - Scans and mentions players class.\n"
    
    content:SetText(helpText)
    
    GR.HelpFrame = f
end

function GR:ShowTemplateValidationPopup(templateName, originalBody, simulatedBody, len)
    if not GR.ValidationPopup then
        local f = CreateFrame("Frame", "GRS_ValidationPopup", UIParent)
        f:SetSize(400, 380)
        f:SetPoint("CENTER")
        f:SetFrameStrata("FULLSCREEN_DIALOG")
        NS.CreateBg(f, 0, 0, 0, 0.95)
        NS.CreateBorder(f, 0.5, 0.5, 0.5, 1)
        
        local title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        title:SetPoint("TOP", 0, -15)
        title:SetText("Template Exceeds Safe API Limits")
        title:SetTextColor(1, 0.2, 0.2)
        
        local desc1 = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
        desc1:SetPoint("TOPLEFT", 20, -45)
        desc1:SetText("Your Input:")
        
        local box1 = CreateFrame("Frame", nil, f)
        box1:SetSize(360, 90)
        box1:SetPoint("TOPLEFT", 20, -60)
        NS.CreateBg(box1, 0.1, 0.1, 0.1, 0.8)
        NS.CreateBorder(box1, 0.3, 0.3, 0.3, 1)
        local text1 = box1:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
        text1:SetPoint("TOPLEFT", 5, -5)
        text1:SetPoint("BOTTOMRIGHT", -5, 5)
        text1:SetJustifyH("LEFT")
        text1:SetJustifyV("TOP")
        text1:SetWordWrap(true)
        f.text1 = text1
        
        local desc2 = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
        desc2:SetPoint("TOPLEFT", 20, -165)
        desc2:SetText("Example of Exceeding (Worst-Case Expansion):")
        
        local box2 = CreateFrame("Frame", nil, f)
        box2:SetSize(360, 110)
        box2:SetPoint("TOPLEFT", 20, -180)
        NS.CreateBg(box2, 0.1, 0.1, 0.1, 0.8)
        NS.CreateBorder(box2, 0.3, 0.3, 0.3, 1)
        local text2 = box2:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
        text2:SetPoint("TOPLEFT", 5, -5)
        text2:SetPoint("BOTTOMRIGHT", -5, 5)
        text2:SetJustifyH("LEFT")
        text2:SetJustifyV("TOP")
        text2:SetWordWrap(true)
        f.text2 = text2
        
        local lblTotal = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        lblTotal:SetPoint("BOTTOMLEFT", 20, 55)
        f.lblTotal = lblTotal
        
        local lblExceed = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        lblExceed:SetPoint("BOTTOMRIGHT", -20, 55)
        f.lblExceed = lblExceed
        
        local btnBack = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
        btnBack:SetSize(120, 25)
        btnBack:SetPoint("BOTTOM", 0, 15)
        btnBack:SetText("Back to Edit")
        if NS.SkinButton then NS.SkinButton(btnBack) end
        btnBack:SetScript("OnClick", function() f:Hide() end)
        
        GR.ValidationPopup = f
    end
    
    local f = GR.ValidationPopup
    f.text1:SetText(originalBody)
    
    -- Colorize the dummy variables in simulated body (Gold/Orange)
    local coloredSim = simulatedBody
    coloredSim = coloredSim:gsub("Deathknight%-BoreanTundra", "|cffffa500Deathknight-BoreanTundra|r")
    coloredSim = coloredSim:gsub("<Order of the Silent Nexus>", "|cffffa500<Order of the Silent Nexus>|r")
    coloredSim = coloredSim:gsub("YourPlayerName", "|cffffa500YourPlayerName|r")
    coloredSim = coloredSim:gsub("Demon Hunter", "|cffffa500Demon Hunter|r")
    
    f.text2:SetText(coloredSim)
    
    f.lblTotal:SetText("Total Characters: " .. len .. " / 255")
    f.lblExceed:SetText("Exceeding by: |cffff0000" .. (len - 255) .. "|r")
    
    f:Show()
end
