local addonName, NS = ...
local GR = _G["GRS_MainFrame"]

-- Import Helpers
local CreateBg = GR.RR.CreateBg
local CreateBorder = GR.RR.CreateBorder
local SkinButton = GR.RR.SkinButton
local CreateCustomScrollbar = GR.RR.CreateCustomScrollbar

-- =========================================================================
-- LITE ROSTER MODULE (Member Popup with Class Data)
-- =========================================================================

GR.RR.Lite = {}
local Lite = GR.RR.Lite

Lite.RosterData = {}
Lite.Rows = {} 
Lite.ViewList = {}
Lite.SortKey = "rankIndex"
Lite.SortAsc = true
Lite.CurrentFilter = nil 
Lite.ShowOffline = false 

local LITE_ROW_HEIGHT = 24
-- TBC: Removed Key, Score, RaidN, RaidH, RaidM columns
local LITE_COL_DEF = {
    { name = "Name", width = 160, key = "name", sort = "name" },
    { name = "Rank", width = 100, key = "rank", sort = "rankIndex" }, 
    { name = "Lvl", width = 50, key = "level", sort = "level" },
    { name = "ilvl", width = 50, key = "ilvl", sort = "ilvl" },
}

function Lite:Init()
    if not self.Frame then
        local f = CreateFrame("Frame", "GRS_RR_PopupFrame", UIParent)
        f:SetSize(400, 500); f:SetPoint("CENTER"); f:Hide()
        f:SetFrameStrata("FULLSCREEN_DIALOG") 
        f:EnableMouse(true); f:SetMovable(true)
        f:RegisterForDrag("LeftButton")
        f:SetScript("OnDragStart", f.StartMoving)
        f:SetScript("OnDragStop", f.StopMovingOrSizing)
        
        CreateBg(f, 0, 0, 0, 0.95)
        CreateBorder(f, 0.5, 0.5, 0.5, 1)
        
        local t = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        t:SetPoint("TOP", 0, -15); t:SetText("Available Members")
        f.title = t
        
        local c = CreateFrame("Button", nil, f)
        c:SetSize(24, 24); c:SetPoint("TOPRIGHT", -5, -5)
        SkinButton(c)
        local cfs = c:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
        cfs:SetPoint("CENTER"); cfs:SetText("X")
        c:SetFontString(cfs)
        c:SetScript("OnClick", function() f:Hide() end)
        
        local sf = CreateFrame("ScrollFrame", "GRS_RR_LiteScroll", f)
        sf:SetPoint("TOPLEFT", 10, -50); sf:SetPoint("BOTTOMRIGHT", -30, 40)
        
        local slider = CreateCustomScrollbar(sf, sf)
        slider:SetPoint("TOPRIGHT", f, "TOPRIGHT", -10, -50)
        slider:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", -10, 40)
        sf.slider = slider
        
        local content = CreateFrame("Frame", nil, sf); content:SetSize(350, 500)
        sf:SetScrollChild(content)
        sf:EnableMouseWheel(true)
        sf:SetScript("OnMouseWheel", function(s, d) 
            local cur = slider:GetValue()
            slider:SetValue(cur - (d * 20)) 
        end)
        
        self.Frame = f
        self.Content = content
        
        local h = CreateFrame("Frame", nil, f)
        h:SetHeight(20); h:SetPoint("TOPLEFT", 10, -30); h:SetPoint("RIGHT", -10, 0)
        local x = 0
        for _, col in ipairs(LITE_COL_DEF) do
            local b = CreateFrame("Button", nil, h)
            b:SetSize(col.width, 20); b:SetPoint("LEFT", x, 0)
            local txt = b:CreateFontString(nil,"OVERLAY","GameFontNormalSmall"); txt:SetPoint("LEFT",5,0); txt:SetText(col.name)
            if col.sort then b:SetScript("OnClick", function() Lite:Sort(col.sort) end) end
            x = x + col.width
        end
        
        local chk = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
        chk:SetPoint("BOTTOMLEFT", 10, 10)
        chk.text:SetText("Show Offline Members")
        chk:SetScript("OnClick", function(s) 
            Lite.ShowOffline = s:GetChecked()
            Lite:FetchData()
        end)
        chk:SetChecked(Lite.ShowOffline)
        self.OfflineChk = chk
    end
end

function Lite:ShowPopup(classFilter)
    if not self.Frame then self:Init() end
    self.CurrentFilter = classFilter
    self.Frame.title:SetText(classFilter .. " - Available")
    self.Frame:Show()
    self:FetchData() 
end

function Lite:FetchData()
    if not IsInGuild() then return {} end
    if C_GuildInfo and C_GuildInfo.GuildRoster then C_GuildInfo.GuildRoster() elseif _G.GuildRoster then _G.GuildRoster() end
    local num = GetNumGuildMembers()
    local temp = {}
    
    for i=1, num do
        local fullName, rank, rankIndex, level, class, zone, note, onote, online, status, classFile = GetGuildRosterInfo(i)
        
        if fullName and (online or self.ShowOffline) then
            local ilvl = 0
            table.insert(temp, {
                name = fullName, rank = rank, rankIndex = rankIndex, level = level,
                class = classFile, online = online, ilvl = ilvl
            })
        end
    end
    self.RosterData = temp
    self:BuildView()
    return temp
end

function Lite:Sort(key)
    if self.SortKey == key then self.SortAsc = not self.SortAsc else self.SortKey = key; self.SortAsc = true end
    self:BuildView()
end

function Lite:BuildView()
    if not self.Content then return end

    local data = {}
    for _, d in ipairs(self.RosterData) do
        if not self.CurrentFilter or d.class == self.CurrentFilter then
            table.insert(data, d)
        end
    end
    
    table.sort(data, function(a, b)
        local valA, valB = a[self.SortKey], b[self.SortKey]
        if self.SortAsc then return valA < valB else return valA > valB end
    end)
    
    for _, r in ipairs(self.Rows) do r:Hide() end
    local y = 0
    
    for i, d in ipairs(data) do
        local r = self.Rows[i]
        if not r then
            r = CreateFrame("Button", nil, self.Content)
            r:SetSize(350, LITE_ROW_HEIGHT)
            
            local bg = r:CreateTexture(nil, "BACKGROUND")
            bg:SetAllPoints()
            r.bg = bg
            
            local hl = r:CreateTexture(nil,"HIGHLIGHT"); hl:SetAllPoints(); hl:SetColorTexture(1,1,1,0.1)
            
            r.cols = {}
            local x = 0
            for _, def in ipairs(LITE_COL_DEF) do
                local t = r:CreateFontString(nil,"OVERLAY","GameFontHighlightSmall")
                t:SetPoint("LEFT", x+5, 0); t:SetWidth(def.width-10); t:SetJustifyH("LEFT")
                r.cols[def.key] = t
                x = x + def.width
            end
            self.Rows[i] = r
        end
        
        r:SetPoint("TOPLEFT", 0, -y); r:Show()
        
        if (i % 2 == 0) then r.bg:SetColorTexture(0.1, 0.1, 0.1, 0.6) 
        else r.bg:SetColorTexture(0.15, 0.15, 0.15, 0.6) end
        
        local cColor = C_ClassColor.GetClassColor(d.class) or C_ClassColor.GetClassColor("PRIEST")
        local nameText = cColor:WrapTextInColorCode(d.name)
        if not d.online then nameText = "|cff808080" .. d.name .. "|r" end
        
        r.cols["name"]:SetText(nameText)
        r.cols["rank"]:SetText(d.rank)
        r.cols["level"]:SetText(d.level)
        r.cols["ilvl"]:SetText(d.ilvl > 0 and math.floor(d.ilvl) or "-")
        
        y = y + LITE_ROW_HEIGHT
    end
    self.Content:SetHeight(math.max(y, 10))
    if self.Frame and self.Frame.title then 
        local scrollFrame = _G["GRS_RR_LiteScroll"]
        if scrollFrame and scrollFrame.slider then
            local maxScroll = math.max(0, self.Content:GetHeight() - scrollFrame:GetHeight())
            scrollFrame.slider:SetMinMaxValues(0, maxScroll)
        end
    end
end
