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

-- =========================================================================
-- UI: CENTER PANE (RESULTS)
-- =========================================================================

function GR:BuildCenterPane(parent)
    self.ResultsHeader = parent:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    self.ResultsHeader:SetPoint("TOPLEFT", 15, -15); self.ResultsHeader:SetText("Unguilded Players - Current Filter: Default (All)")
    
    local sBtn = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    sBtn:SetSize(140, 30); sBtn:SetPoint("TOPRIGHT", -15, -10); sBtn:SetText("Search Players")
    self.SearchBtn = sBtn 
    sBtn:SetScript("OnClick", function() self:StartSearch() end)
    NS.SkinButton(sBtn) 
    
    local rListBtn = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    rListBtn:SetSize(100, 30)
    rListBtn:SetPoint("RIGHT", sBtn, "LEFT", -5, 0)
    rListBtn:SetText("Reset List")
    rListBtn:SetScript("OnClick", function()
        GR.foundPlayers = {}
        GR:UpdateScrollFrame()
        if GR.StatusText then GR.StatusText:SetText("List Discarded.") end
    end)
    NS.SkinButton(rListBtn)

    local headF = CreateFrame("Frame", nil, parent); headF:SetSize(750, 20); headF:SetPoint("TOPLEFT", 21, -45) 

    local selectAll = CreateFrame("CheckButton", nil, headF, "UICheckButtonTemplate")
    selectAll:SetSize(20, 20)
    selectAll:SetPoint("LEFT", 0, 0)
    selectAll:SetScript("OnClick", function(self)
        local state = self:GetChecked()
        if GR.foundPlayers then
            for _, p in ipairs(GR.foundPlayers) do
                p.selected = state
            end
            GR:UpdateScrollFrame()
        end
    end)
    
    local headers = {
        {text="Name", key="name", width=110}, 
        {text="Race", key="race", width=90},  
        {text="Class", key="fullClass", width=100},
        {text="Level", key="level", width=40}, 
        {text="Max Key", key="maxKey", width=70}, 
        {text="Zone", key="zone", width=110}, 
        {text="Score", key="rio", width=70},  
        {text="Heroic", key="heroic", width=70}, 
        {text="Mythic", key="mythic", width=70}  
    }
    
    local lastH = nil
    for i, data in ipairs(headers) do
        local btn = CreateFrame("Button", nil, headF)
        btn:SetSize(data.width, 20)
        
        if i==1 then 
            btn:SetPoint("LEFT", 30, 0) 
        else 
            btn:SetPoint("LEFT", lastH, "RIGHT", 0, 0) 
        end
        
        local txt = btn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        txt:SetPoint("LEFT", 0, 0)
        txt:SetText(data.text)
        btn:SetFontString(txt)
        
        btn:SetScript("OnEnter", function(s) 
            s:GetFontString():SetTextColor(1, 1, 1) 
        end)
        btn:SetScript("OnLeave", function(s) 
            s:GetFontString():SetTextColor(1, 0.82, 0) 
        end)
        
        btn:SetScript("OnClick", function() 
            GR:SortPlayers(data.key) 
        end)
        
        lastH = btn
    end
    
    local bot = CreateFrame("Frame", nil, parent); bot:SetHeight(40)
    bot:SetPoint("BOTTOMLEFT", 15, 5)
    bot:SetPoint("BOTTOMRIGHT", -15, 5)
    
    local slL = bot:CreateFontString(nil,"OVERLAY","GameFontHighlightSmall"); slL:SetPoint("LEFT", 0, 0); slL:SetText("Msg Delay: 0.8s")
    local sl = CreateFrame("Slider", nil, bot, "OptionsSliderTemplate")
    sl:SetPoint("LEFT", slL, "RIGHT", 10, 0); sl:SetWidth(150); sl:SetMinMaxValues(0.5, 1.0); sl:SetValue(0.8); sl:SetValueStep(0.1); sl:SetObeyStepOnDrag(true)
    sl:SetScript("OnValueChanged", function(s,v) v=math.floor(v*10)/10; self.db.scanDelay=v; slL:SetText("Msg Delay: "..v.."s") end)
    
    local snd = CreateFrame("Button", nil, bot, "UIPanelButtonTemplate"); snd:SetSize(120, 30); snd:SetPoint("RIGHT", -10, 0); snd:SetText("Send Batch")
    snd:SetScript("OnClick", function() self:SendMessageSequence() end)
    NS.SkinButton(snd) 

    local btnBL = CreateFrame("Button", nil, bot, "UIPanelButtonTemplate")
    btnBL:SetSize(130, 30)
    btnBL:SetPoint("RIGHT", snd, "LEFT", -10, 0)
    btnBL:SetText("Blacklist Selected")
    btnBL:SetScript("OnClick", function() self:ManualBlacklist() end)
    NS.SkinButton(btnBL)

    self.StatusText = bot:CreateFontString(nil,"OVERLAY","GameFontNormal"); 
    self.StatusText:SetPoint("RIGHT", btnBL, "LEFT", -20, 0); 
    self.StatusText:SetText("Ready.")
    
    -- =========================================================================
    -- LAYERING FIX: Separate Backdrop from Scroll Logic
    -- =========================================================================
    
    -- 1. Create the Backdrop "Slab" first
    -- This frame sits at the bottom and holds the black background texture
    local listBackdrop = CreateFrame("Frame", nil, parent)
    listBackdrop:SetPoint("TOPLEFT", headF, "BOTTOMLEFT", 0, -5)
    listBackdrop:SetPoint("BOTTOMRIGHT", bot, "TOPRIGHT", -5, 5)
    listBackdrop:SetFrameLevel(parent:GetFrameLevel() + 1) -- Just above parent
    
    -- Apply background to THIS frame, not the scroll frame
    NS.CreateBg(listBackdrop, 0, 0, 0, 0.8) 
    self.listBackdrop = listBackdrop

    -- 2. Create the Logical ScrollFrame
    self.scroll = CreateFrame("ScrollFrame", "GRS_S", parent, "FauxScrollFrameTemplate")
    parent.scrollFrame = self.scroll
    parent.scroll = self.scroll 
    local scrollFrame = self.scroll 
    
    -- Anchor scrollframe to the backdrop
    scrollFrame:SetAllPoints(listBackdrop)
    
    -- Ensure scroll logic sits ABOVE the backdrop
    scrollFrame:SetFrameLevel(listBackdrop:GetFrameLevel() + 5)
    
    -- ScrollBar Styling
    local scrollBar = _G["GRS_SScrollBar"]
    if scrollBar then
        NS.CreateBg(scrollBar, 0.1, 0.1, 0.1, 0.8) 
    end

    scrollFrame:SetScript("OnVerticalScroll", function(s, offset)
        FauxScrollFrame_OnVerticalScroll(s, offset, 20, function() self:UpdateScrollFrame() end)
    end)
    
    scrollFrame:EnableMouseWheel(true)
    
    parent:SetScript("OnSizeChanged", function(frame, w, h)
        local sFrame = scrollFrame or frame.scrollFrame or frame.scroll
        if not sFrame then return end

        local availableW = w - 30 
        local MAX_WIDTH = 760 
        
        if availableW > MAX_WIDTH then
            bot:ClearAllPoints()
            bot:SetPoint("BOTTOMLEFT", 15, 5)
            bot:SetWidth(MAX_WIDTH)
            
            -- Update Backdrop
            if self.listBackdrop then
                self.listBackdrop:ClearAllPoints()
                self.listBackdrop:SetPoint("TOPLEFT", headF, "BOTTOMLEFT", 0, -5)
                self.listBackdrop:SetPoint("BOTTOMLEFT", bot, "TOPLEFT", 0, 5)
                self.listBackdrop:SetWidth(MAX_WIDTH)
            end
            
            -- Snap Scroll to Backdrop
            sFrame:ClearAllPoints()
            sFrame:SetAllPoints(self.listBackdrop)
        else
            bot:ClearAllPoints()
            bot:SetPoint("BOTTOMLEFT", 15, 5)
            bot:SetPoint("BOTTOMRIGHT", -15, 5)
            
            -- Update Backdrop
            if self.listBackdrop then
                self.listBackdrop:ClearAllPoints()
                self.listBackdrop:SetPoint("TOPLEFT", headF, "BOTTOMLEFT", 0, -5)
                self.listBackdrop:SetPoint("BOTTOMRIGHT", bot, "TOPRIGHT", -5, 5)
            end
            
            -- Snap Scroll to Backdrop
            sFrame:ClearAllPoints()
            sFrame:SetAllPoints(self.listBackdrop)
        end
    end)
    
    self.rows = {}
    
    function GR:UpdateResultsLayout(height)
        if not height then height = self.scroll:GetHeight() end
        local numRows = math.floor(height / 20)
        self.visibleRows = numRows 
        
        for i = 1, numRows do
            if not self.rows[i] then
                local r = CreateFrame("Button", nil, parent)
                -- Force rows to sit above the backdrop (ScrollFrame level + 1)
                r:SetFrameLevel(self.scroll:GetFrameLevel() + 1)
                
                r:SetHeight(20); 
                r:SetPoint("LEFT", 41, 0); 
                r:SetPoint("RIGHT", -25, 0)
                if i==1 then r:SetPoint("TOP", self.scroll, "TOP") else r:SetPoint("TOP", self.rows[i-1], "BOTTOM") end
                
                r.c = CreateFrame("CheckButton", nil, r, "UICheckButtonTemplate"); r.c:SetSize(20,20); r.c:SetPoint("LEFT", -20, 0)
                r.c:SetScript("OnClick", function(b) if r.d then r.d.selected=b:GetChecked() end end)
                
                r.n = r:CreateFontString(nil,"OVERLAY","GameFontHighlightSmall"); r.n:SetPoint("LEFT",10,0); r.n:SetWidth(110); r.n:SetJustifyH("LEFT")
                r.ra = r:CreateFontString(nil,"OVERLAY","GameFontHighlightSmall"); r.ra:SetPoint("LEFT",r.n,"RIGHT"); r.ra:SetWidth(90); r.ra:SetJustifyH("LEFT")
                r.cl = r:CreateFontString(nil,"OVERLAY","GameFontHighlightSmall"); r.cl:SetPoint("LEFT",r.ra,"RIGHT"); r.cl:SetWidth(100); r.cl:SetJustifyH("LEFT")
                
                r.lvl = r:CreateFontString(nil,"OVERLAY","GameFontHighlightSmall"); r.lvl:SetPoint("LEFT",r.cl,"RIGHT"); r.lvl:SetWidth(40); r.lvl:SetJustifyH("LEFT")
                r.mk = r:CreateFontString(nil,"OVERLAY","GameFontHighlightSmall"); r.mk:SetPoint("LEFT",r.lvl,"RIGHT"); r.mk:SetWidth(50); r.mk:SetJustifyH("LEFT") 

                r.z = r:CreateFontString(nil,"OVERLAY","GameFontHighlightSmall"); r.z:SetPoint("LEFT",r.mk,"RIGHT", 20, 0); r.z:SetWidth(110); r.z:SetJustifyH("LEFT")
                r.s = r:CreateFontString(nil,"OVERLAY","GameFontHighlightSmall"); r.s:SetPoint("LEFT",r.z,"RIGHT", 10, 0); r.s:SetWidth(70); r.s:SetJustifyH("LEFT")
                r.h = r:CreateFontString(nil,"OVERLAY","GameFontHighlightSmall"); r.h:SetPoint("LEFT",r.s,"RIGHT", 5, 0); r.h:SetWidth(70); r.h:SetJustifyH("LEFT")
                r.m = r:CreateFontString(nil,"OVERLAY","GameFontHighlightSmall"); r.m:SetPoint("LEFT",r.h,"RIGHT", 5, 0); r.m:SetWidth(70); r.m:SetJustifyH("LEFT")
                self.rows[i] = r
            end
        end
        self:UpdateScrollFrame() 
    end
end

function GR:UpdateScrollFrame()
    local d = self.foundPlayers or {}
    local rowCount = self.visibleRows or 15
    if rowCount > #self.rows then rowCount = #self.rows end
    
    FauxScrollFrame_Update(self.scroll, #d, rowCount, 20)
    
    local scrollBar = _G["GRS_SScrollBar"]
    if scrollBar then
        scrollBar:Show() 
        
        local _, maxVal = scrollBar:GetMinMaxValues()
        local thumb = scrollBar:GetThumbTexture()
        
        if not maxVal or maxVal == 0 then
             if thumb then thumb:Hide() end
             
             local up = _G["GRS_SScrollBarScrollUpButton"]
             local down = _G["GRS_SScrollBarScrollDownButton"]
             if up then up:Disable() end
             if down then down:Disable() end
        else
             if thumb then thumb:Show() end
             
             local up = _G["GRS_SScrollBarScrollUpButton"]
             local down = _G["GRS_SScrollBarScrollUpButton"]
             if up then up:Enable() end
             if down then down:Enable() end
        end
    end
    
    local offset = FauxScrollFrame_GetOffset(self.scroll)
    
    for i=1, #self.rows do
        local r = self.rows[i]
        if i > rowCount then
            r:Hide()
        else
            local idx = offset + i
            if idx <= #d then
                local p = d[idx]
                r.d = p; r:Show()
                r.n:SetText(p.name); 
                r.lvl:SetText(p.level);
                r.mk:SetText(p.maxKey); 
                
                r.z:SetText(p.zone); r.ra:SetText(p.race or "Unknown")
                local cc = C_ClassColor.GetClassColor(p.classFile or "PRIEST")
                r.cl:SetText(cc and cc:WrapTextInColorCode(p.fullClass) or p.fullClass)
                
                local sc = p.rio or 0; local col = "|cffffffff"
                if sc>=2500 then col="|cffff8000" 
                elseif sc>=2000 then col="|cffa335ee" 
                elseif sc>=1000 then col="|cff0070dd" 
                end
                r.s:SetText(col..sc.."|r")
                
                local function Col(str)
                    if not str or str == "-" then return "|cff808080"..str.."|r" end
                    local k = tonumber(str:match("^(%d+)")) or 0
                    if k >= 8 then return "|cffff8000"..str.."|r"
                    elseif k >= 4 then return "|cffa335ee"..str.."|r"
                    else return "|cff00ff00"..str.."|r" end
                end
                
                r.h:SetText(Col(p.heroic)); r.m:SetText(Col(p.mythic))
                r.c:SetChecked(p.selected)
            else 
                r:Hide() 
            end
        end
    end
end

-- MISSING FUNCTION IMPLEMENTATION: SORT PLAYERS
function GR:SortPlayers(key)
    if not self.foundPlayers or #self.foundPlayers == 0 then return end
    
    -- Toggle sort direction state if needed, or default to ASC
    if not self.sortState then self.sortState = {} end
    if self.sortState.key == key then
        self.sortState.asc = not self.sortState.asc
    else
        self.sortState.key = key
        self.sortState.asc = true
    end
    
    table.sort(self.foundPlayers, function(a, b)
        local v1, v2 = a[key], b[key]
        -- Handle nils
        if v1 == v2 then return false end
        if v1 == nil then return false end
        if v2 == nil then return true end
        
        -- Compare
        if self.sortState.asc then
            return v1 < v2
        else
            return v1 > v2
        end
    end)
    
    self:UpdateScrollFrame()
end