-- =========================================================================
-- FILE: UI_Home_Controls.lua (TBC)
-- PURPOSE: Left pane controls - filters, templates, scan settings
-- =========================================================================
local addonName, NS = ...
local GR = NS.GR
local CreateBg = NS.CreateBg
local CreateBorder = NS.CreateBorder
local SkinButton = NS.SkinButton

-- =========================================================================
-- UI: LEFT PANE (CONTROLS)
-- =========================================================================

function GR:BuildLeftPane(parent)
    local y = -15
    local function AddText(txt, font, dy)
        local t = parent:CreateFontString(nil, "OVERLAY", font)
        t:SetPoint("TOPLEFT", 15, y + (dy or 0)); t:SetText(txt)
    end
    
    AddText("SEARCH FILTERS", "GameFontNormal", 0); y = y - 30
    
    local dFilt = CreateFrame("Button", nil, parent); CreateBg(dFilt, 0.2, 0.2, 0.2, 1)
    dFilt:SetSize(180, 24); dFilt:SetPoint("TOPLEFT", 15, y)
    local dFiltTxt = dFilt:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall"); dFiltTxt:SetPoint("LEFT", 5, 0); dFiltTxt:SetText("Filter: Default (All)")
    self.dFiltTxt = dFiltTxt
    
    local dFiltArrow = dFilt:CreateTexture(nil, "ARTWORK")
    dFiltArrow:SetTexture("Interface\\Buttons\\UI-ScrollBar-ScrollDownButton-Up")
    dFiltArrow:SetSize(20, 20)
    dFiltArrow:SetPoint("RIGHT", -2, 0)
    
    local dFiltList = CreateFrame("Frame", nil, dFilt); CreateBg(dFiltList, 0.1, 0.1, 0.1, 1); CreateBorder(dFiltList, 0.5, 0.5, 0.5, 1)
    dFiltList:SetSize(180, 50); dFiltList:SetPoint("TOPLEFT", dFilt, "BOTTOMLEFT", 0, -2); dFiltList:SetFrameStrata("FULLSCREEN_DIALOG"); dFiltList:Hide()
    self.dFiltList = dFiltList; 
    if GR.RefreshMainFilterList then GR:RefreshMainFilterList() end
    
    dFilt:SetScript("OnClick", function() 
        if GR.RefreshMainFilterList then GR:RefreshMainFilterList() end
        dFiltList:SetShown(not dFiltList:IsShown()) 
    end)
    
    local cIcon = CreateFrame("Button", nil, parent); cIcon:SetSize(24, 24); cIcon:SetPoint("LEFT", dFilt, "RIGHT", 5, 0)
    cIcon:SetNormalTexture("Interface\\Buttons\\UI-OptionsButton")
    cIcon:SetScript("OnClick", function() if GR.FilterFrame then GR.FilterFrame.OpenCreate() end end)

    local eIcon = CreateFrame("Button", nil, parent); eIcon:SetSize(24, 24); eIcon:SetPoint("LEFT", cIcon, "RIGHT", 2, 0)
    eIcon:SetNormalTexture("Interface\\Buttons\\UI-GuildButton-PublicNote-Up") 
    eIcon:SetHighlightTexture("Interface\\Buttons\\UI-Common-MouseHilight")
    eIcon:SetScript("OnClick", function() 
        if GR.selectedFilterData then 
            GR.FilterFrame.OpenEdit(GR.selectedFilterData)
        else
            print("|cffff0000GRS: Cannot edit Default filter. Select a custom filter first.|r")
        end
    end)
    
    y = y - 40; AddText("Level Range", "GameFontHighlightSmall", 0); y = y - 20
    
    -- Container frame for level range row
    local lvlFrame = CreateFrame("Frame", nil, parent)
    lvlFrame:SetSize(130, 24); lvlFrame:SetPoint("TOPLEFT", 15, y)
    
    -- Min input container
    local minBox = CreateFrame("Frame", nil, lvlFrame)
    minBox:SetSize(45, 20); minBox:SetPoint("LEFT", 0, 0)
    CreateBg(minBox, 0.1, 0.1, 0.1, 0.8); CreateBorder(minBox, 0.3, 0.3, 0.3, 1)
    
    local lvlMin = CreateFrame("EditBox", nil, minBox)
    lvlMin:SetPoint("TOPLEFT", 4, -2); lvlMin:SetPoint("BOTTOMRIGHT", -4, 2)
    lvlMin:SetFontObject(GameFontHighlightSmall); lvlMin:SetAutoFocus(false)
    lvlMin:SetMaxLetters(3); lvlMin:SetJustifyH("LEFT")
    lvlMin:SetText(tostring(self.db.minLevel or 1))
    lvlMin:SetCursorPosition(0)
    lvlMin:SetScript("OnEscapePressed", function(s) s:ClearFocus() end)
    lvlMin:SetScript("OnEnterPressed", function(s) s:ClearFocus() end)
    lvlMin:SetScript("OnEditFocusLost", function(s)
        local v = tonumber((s:GetText():gsub("%D", ""))) or 1
        if v < 1 then v = 1 end; if v > 70 then v = 70 end
        s:SetText(tostring(v)); s:SetCursorPosition(0); self.db.minLevel = v
    end)
    minBox:SetScript("OnMouseDown", function() lvlMin:SetFocus() end)
    self.LevelMinInput = lvlMin
    
    -- Dash
    local dash = lvlFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    dash:SetPoint("LEFT", minBox, "RIGHT", 5, 0); dash:SetText("-")
    
    -- Max input container
    local maxBox = CreateFrame("Frame", nil, lvlFrame)
    maxBox:SetSize(45, 20); maxBox:SetPoint("LEFT", dash, "RIGHT", 5, 0)
    CreateBg(maxBox, 0.1, 0.1, 0.1, 0.8); CreateBorder(maxBox, 0.3, 0.3, 0.3, 1)
    
    local lvlMax = CreateFrame("EditBox", nil, maxBox)
    lvlMax:SetPoint("TOPLEFT", 4, -2); lvlMax:SetPoint("BOTTOMRIGHT", -4, 2)
    lvlMax:SetFontObject(GameFontHighlightSmall); lvlMax:SetAutoFocus(false)
    lvlMax:SetMaxLetters(3); lvlMax:SetJustifyH("LEFT")
    lvlMax:SetText(tostring(self.db.maxLevel or 70))
    lvlMax:SetCursorPosition(0)
    lvlMax:SetScript("OnEscapePressed", function(s) s:ClearFocus() end)
    lvlMax:SetScript("OnEnterPressed", function(s) s:ClearFocus() end)
    lvlMax:SetScript("OnEditFocusLost", function(s)
        local v = tonumber((s:GetText():gsub("%D", ""))) or 70
        if v < 1 then v = 1 end; if v > 70 then v = 70 end
        s:SetText(tostring(v)); s:SetCursorPosition(0); self.db.maxLevel = v
    end)
    maxBox:SetScript("OnMouseDown", function() lvlMax:SetFocus() end)
    self.LevelMaxInput = lvlMax
    
    y = y - 50; AddText("Scan Scope", "GameFontHighlightSmall", 0); y = y - 20
    
    local function MkScanBtn(text, mode, x, tooltipText)
        local b = CreateFrame("Button", nil, parent); CreateBg(b, 0.2, 0.2, 0.2, 1); b:SetSize(80, 20); b:SetPoint("TOPLEFT", 15 + x, y)
        local t = b:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall"); t:SetPoint("CENTER"); t:SetText(text)
        b.bg = b.bg
        b:SetScript("OnClick", function() self.db.remixMode = mode; self:UpdateRemixVisuals() end)
        
        b:SetScript("OnEnter", function(self) 
            if self.bg then self.bg:SetColorTexture(0.3, 0.3, 0.3, 1) end
            GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
            GameTooltip:SetText(tooltipText, nil, nil, nil, nil, true)
            GameTooltip:Show()
        end)
        b:SetScript("OnLeave", function(self) 
            GameTooltip:Hide()
            GR:UpdateRemixVisuals()
        end)
        
        return b
    end
    
    self.btnWorld = MkScanBtn("World Only", "OFF", 0, "Excludes players currently inside Raid or Dungeon instances for a safer, non-intrusive scan.")
    self.btnAllow = MkScanBtn("All", "ALLOW", 85, "Searches ALL zones, including instances.\n\n|cffff0000WARNING:|r Sending unsolicited whispers to players in high-stress content carries a risk of reports.")
    
    function GR:UpdateRemixVisuals()
        self.btnWorld.bg:SetColorTexture(0.2,0.2,0.2,1); self.btnAllow.bg:SetColorTexture(0.2,0.2,0.2,1); 
        if self.db.remixMode=="OFF" then self.btnWorld.bg:SetColorTexture(0,0.6,0,1) end
        if self.db.remixMode=="ALLOW" then self.btnAllow.bg:SetColorTexture(0,0.6,0,1) end
    end
    self:UpdateRemixVisuals()
    
    y = y - 40; AddText("MESSAGE TEMPLATES", "GameFontNormal", 0); y = y - 30
    local dTemp = CreateFrame("Button", nil, parent); CreateBg(dTemp, 0.2, 0.2, 0.2, 1); dTemp:SetSize(200, 24); dTemp:SetPoint("TOPLEFT", 15, y)
    local dTempTxt = dTemp:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall"); dTempTxt:SetPoint("LEFT", 5, 0); dTempTxt:SetText(self.db.messageTemplate)
    
    local dTempArrow = dTemp:CreateTexture(nil, "ARTWORK")
    dTempArrow:SetTexture("Interface\\Buttons\\UI-ScrollBar-ScrollDownButton-Up")
    dTempArrow:SetSize(20, 20)
    dTempArrow:SetPoint("RIGHT", -2, 0)
    
    local dTempList = CreateFrame("Frame", nil, dTemp); CreateBg(dTempList, 0.1, 0.1, 0.1, 1); CreateBorder(dTempList, 0.5, 0.5, 0.5, 1)
    dTempList:SetSize(200, 100); dTempList:SetPoint("TOPLEFT", dTemp, "BOTTOMLEFT", 0, -2); dTempList:SetFrameStrata("FULLSCREEN_DIALOG"); dTempList:Hide()
    
    dTemp:SetScript("OnClick", function() 
        local kids = {dTempList:GetChildren()}; for _, k in ipairs(kids) do k:Hide() end
        local ty = -5
        for k, v in pairs(GR.db.templates) do
            local b = CreateFrame("Button", nil, dTempList); b:SetSize(190, 20); b:SetPoint("TOPLEFT", 5, ty)
            local t = b:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall"); t:SetPoint("LEFT"); t:SetText(k)
            b:SetScript("OnClick", function() 
                GR.db.messageTemplate = k; dTempTxt:SetText(k); GR.InputBody:SetText(v); GR.InputName:SetText(k); dTempList:Hide() 
                if GR.InputBody:GetScript("OnTextChanged") then
                     GR.InputBody:GetScript("OnTextChanged")(GR.InputBody)
                end
                if GR.InputName:GetScript("OnTextChanged") then
                     GR.InputName:GetScript("OnTextChanged")(GR.InputName)
                end
            end)
            ty = ty - 20
        end
        dTempList:SetHeight(math.abs(ty) + 5)
        dTempList:SetShown(not dTempList:IsShown()) 
    end)
    
    local btnNew = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    btnNew:SetSize(50, 22); btnNew:SetPoint("LEFT", dTemp, "RIGHT", 5, 0); btnNew:SetText("New")
    btnNew:SetScript("OnClick", function() GR.InputName:SetText(""); GR.InputBody:SetText(""); GR.InputName:SetFocus() end)
    SkinButton(btnNew)

    y = y - 30
    local nameBox = CreateFrame("Frame", nil, parent)
    nameBox:SetSize(250, 22); nameBox:SetPoint("TOPLEFT", 15, y)
    CreateBg(nameBox, 0.1, 0.1, 0.1, 0.8); CreateBorder(nameBox, 0.3, 0.3, 0.3, 1)
    
    local nameIn = CreateFrame("EditBox", nil, nameBox)
    nameIn:SetPoint("TOPLEFT", 4, -2); nameIn:SetPoint("BOTTOMRIGHT", -4, 2)
    nameIn:SetFontObject(GameFontHighlightSmall); nameIn:SetAutoFocus(false)
    nameIn:SetScript("OnEscapePressed", function(s) s:ClearFocus() end)
    self.InputName = nameIn
    local ph = nameBox:CreateFontString(nil, "ARTWORK", "GameFontDisable"); ph:SetPoint("LEFT", 6, 0); ph:SetText("Template Name...")
    
    nameIn:SetScript("OnTextChanged", function(s) 
        if s:GetText() ~= "" then ph:Hide() else ph:Show() end 
    end)
    
    nameIn:SetScript("OnEditFocusGained", function() ph:Hide() end)
    nameIn:SetScript("OnEditFocusLost", function(s) if s:GetText()=="" then ph:Show() end end)
    nameBox:SetScript("OnMouseDown", function() nameIn:SetFocus() end)
    
    y = y - 30
    local bodyF = CreateFrame("Frame", nil, parent); CreateBg(bodyF, 0.1, 0.1, 0.1, 0.5); bodyF:SetSize(290, 100); bodyF:SetPoint("TOPLEFT", 15, y)
    local scrollM = CreateFrame("ScrollFrame", nil, bodyF, "UIPanelScrollFrameTemplate"); scrollM:SetPoint("TOPLEFT", 5, -5); scrollM:SetPoint("BOTTOMRIGHT", -25, 5)
    if NS.StyleScrollBar then NS.StyleScrollBar(scrollM) end
    local editM = CreateFrame("EditBox", nil, scrollM); editM:SetSize(265, 100); editM:SetMultiLine(true); editM:SetFontObject(ChatFontNormal); 
    editM:SetMaxLetters(255); 
    editM:SetAutoFocus(false) 
    editM:SetScript("OnEscapePressed", function(self) self:ClearFocus() end)
    editM:SetText(self.db.templates[self.db.messageTemplate] or ""); scrollM:SetScrollChild(editM); self.InputBody = editM

    local charCount = bodyF:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall")
    charCount:SetPoint("BOTTOMRIGHT", -30, 2)
    local function UpdateCharCount()
        local len = string.len(editM:GetText() or "")
        charCount:SetText(len .. " / 255")
        if len >= 255 then charCount:SetTextColor(1, 0.2, 0.2) else charCount:SetTextColor(0.5, 0.5, 0.5) end
    end
    editM:SetScript("OnTextChanged", function(self)
        UpdateCharCount()
    end)
    editM:SetScript("OnEditFocusGained", function(self) UpdateCharCount() end) 
    UpdateCharCount() 
    
    y = y - 110
    local btnSave = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate"); btnSave:SetSize(80, 22); btnSave:SetPoint("TOPLEFT", 15, y); btnSave:SetText("Save")
    btnSave:SetScript("OnClick", function()
        local n, b = self.InputName:GetText(), self.InputBody:GetText()
        if n ~= "" and b ~= "" then
            self.db.templates[n] = b; self.db.messageTemplate = n; dTempTxt:SetText(n); print("Saved Template: " .. n)
        end
    end)
    SkinButton(btnSave)

    -- HELP BUTTON
    local btnHelp = CreateFrame("Button", nil, parent)
    btnHelp:SetSize(80, 22)
    btnHelp:SetPoint("LEFT", btnSave, "RIGHT", 5, 0)
    
    btnHelp:SetNormalTexture("")
    btnHelp:SetHighlightTexture("")
    btnHelp:SetPushedTexture("")
    btnHelp:SetDisabledTexture("")
    CreateBg(btnHelp, 0.4, 0.0, 0.0, 1)
    CreateBorder(btnHelp, 0, 0, 0, 1)
    
    local hText = btnHelp:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    hText:SetPoint("CENTER"); hText:SetText("HELP"); hText:SetTextColor(1, 1, 1) 
    btnHelp:SetFontString(hText)
    
    btnHelp:SetScript("OnClick", function()
        if GR.HelpFrame then GR.HelpFrame:SetShown(not GR.HelpFrame:IsShown()) else GR:BuildHelpPopup() end
    end)
    
    btnHelp:SetScript("OnEnter", function(s) if s.bg then s.bg:SetColorTexture(0.6, 0.1, 0.1, 1) end end)
    btnHelp:SetScript("OnLeave", function(s) if s.bg then s.bg:SetColorTexture(0.4, 0.0, 0.0, 1) end end)
    btnHelp:SetScript("OnMouseDown", function(s) if s.bg then s.bg:SetColorTexture(0.2, 0.0, 0.0, 1) end end)
    btnHelp:SetScript("OnMouseUp", function(s) if s.bg then s.bg:SetColorTexture(0.6, 0.1, 0.1, 1) end end)

    -- TEST BUTTON
    local btnTest = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    btnTest:SetSize(165, 22)
    btnTest:SetPoint("TOPLEFT", btnSave, "BOTTOMLEFT", 0, -5)
    btnTest:SetText("TEST ME")
    btnTest:SetScript("OnClick", function()
        if not GR.InputBody then return end
        local msg = GR.InputBody:GetText()
        if not msg or msg == "" then print("Template is empty."); return end
        
        local myName = UnitName("player")
        local myClass = UnitClass("player")
        local myGuild = GetGuildInfo("player") or "Guild"
        
        -- Placeholder replacements
        msg = msg:gsub("%[player%]", myName)
        msg = msg:gsub("%[Player%]", myName)
        msg = msg:gsub("%[PLAYER%]", myName)
        msg = msg:gsub("%[ player %]", myName)
        msg = msg:gsub("%[ Player %]", myName)
        msg = msg:gsub("%[ PLAYER %]", myName)
        msg = msg:gsub("%[ownname%]", myName)
        msg = msg:gsub("%[OwnName%]", myName)
        msg = msg:gsub("%[Ownname%]", myName)
        msg = msg:gsub("%[OWNNAME%]", myName)
        msg = msg:gsub("%[own name%]", myName)
        msg = msg:gsub("%[Own Name%]", myName)
        msg = msg:gsub("%[OWN NAME%]", myName)
        msg = msg:gsub("%[guild%]", myGuild)
        msg = msg:gsub("%[Guild%]", myGuild)
        msg = msg:gsub("%[GUILD%]", myGuild)
        msg = msg:gsub("%[playerclass%]", myClass)
        msg = msg:gsub("%[PlayerClass%]", myClass)
        msg = msg:gsub("%[Playerclass%]", myClass)
        msg = msg:gsub("%[PLAYERCLASS%]", myClass)
        msg = msg:gsub("%[player class%]", myClass)
        msg = msg:gsub("%[Player Class%]", myClass)
        msg = msg:gsub("%[Player class%]", myClass)
        msg = msg:gsub("%[class%]", myClass)
        msg = msg:gsub("%[Class%]", myClass)
        msg = msg:gsub("%[CLASS%]", myClass)
        
        if GR.recruitedPlayers then GR.recruitedPlayers[Ambiguate(myName, "none")] = true end
        
        SendChatMessage(msg, "WHISPER", nil, myName)
        print("GRS: Test message sent to self.")
    end)
    SkinButton(btnTest)
    GR.TestBtn = btnTest -- Expose for Compact Mode Anchor

    -- =========================================================================
    -- WELCOME MESSAGES POPUP BUTTON
    -- =========================================================================
    local btnWelcomePopup = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    btnWelcomePopup:SetSize(165, 30)
    btnWelcomePopup:SetPoint("TOPLEFT", btnTest, "BOTTOMLEFT", 0, -20)
    btnWelcomePopup:SetText("Welcome Messages")
    
    btnWelcomePopup:SetScript("OnClick", function()
        GR:OpenWelcomePopup()
    end)
    SkinButton(btnWelcomePopup)
    GR.WelcomeBtn = btnWelcomePopup -- Expose for Compact Mode Reparenting
end

function GR:BuildHelpPopup()
    local f = CreateFrame("Frame", "GRS_HelpPopup", UIParent)
    f:SetSize(400, 300)
    f:SetPoint("CENTER")
    f:SetFrameStrata("FULLSCREEN_DIALOG")
    CreateBg(f, 0, 0, 0, 0.95)
    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("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
