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

-- =========================================================================
-- UI: POPUPS
-- =========================================================================

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
            GR.db.welcomeMessages[i] = f.inputs[i]:GetText()
        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