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

print("|cff00ff00GRS:|r Guild Roster Module Loaded (View 5).")

-- =========================================================================
-- 0. COMPATIBILITY WRAPPERS (Universal Fix)
-- =========================================================================
local function RequestGuildRoster()
    if C_GuildInfo and C_GuildInfo.GuildRoster then
        C_GuildInfo.GuildRoster()
    elseif _G.GuildRoster then
        _G.GuildRoster()
    end
end

local function CanEditOfficerNoteSafe()
    if C_GuildInfo and C_GuildInfo.CanEditOfficerNote then
        return C_GuildInfo.CanEditOfficerNote()
    elseif _G.CanEditOfficerNote then
        return _G.CanEditOfficerNote()
    end
    return false
end

-- =========================================================================
-- 1. STYLING HELPERS
-- =========================================================================
local function SkinButton(btn)
    if not btn then return end
    btn:SetNormalTexture("")
    btn:SetHighlightTexture("")
    btn:SetPushedTexture("")
    btn:SetDisabledTexture("")
    if btn.Left then btn.Left:SetAlpha(0) end
    if btn.Middle then btn.Middle:SetAlpha(0) end
    if btn.Right then btn.Right:SetAlpha(0) end
    if btn.Top then btn.Top:SetAlpha(0) end
    if btn.Bottom then btn.Bottom:SetAlpha(0) end
    local t = btn:CreateTexture(nil, "BACKGROUND")
    t:SetAllPoints(); t:SetColorTexture(0.2, 0.2, 0.2, 1); btn.bg = t
    local b = btn:CreateTexture(nil, "BORDER")
    b:SetPoint("TOPLEFT", -1, 1); b:SetPoint("BOTTOMRIGHT", 1, -1); b:SetColorTexture(0, 0, 0, 1); btn.border = b
    btn:HookScript("OnEnter", function(s) if s.bg then s.bg:SetColorTexture(0.3, 0.3, 0.3, 1) end end)
    btn:HookScript("OnLeave", function(s) if s.bg then s.bg:SetColorTexture(0.2, 0.2, 0.2, 1) end end)
    btn:HookScript("OnMouseDown", function(s) if s.bg then s.bg:SetColorTexture(0.1, 0.1, 0.1, 1) end end)
    btn:HookScript("OnMouseUp", function(s) if s.bg then s.bg:SetColorTexture(0.3, 0.3, 0.3, 1) end end)
    local fs = btn:GetFontString(); if fs then fs:SetTextColor(1, 1, 1) end
end

-- =========================================================================
-- 2. HELPER: OFFICER CHECK
-- =========================================================================
function GR:IsOfficer()
    if not IsInGuild() then return false end
    return CanEditOfficerNoteSafe()
end

function GR:IsGM()
    if not IsInGuild() then return false end
    return IsGuildLeader()
end

-- =========================================================================
-- 3. MAIN BUILD FUNCTION
-- =========================================================================
function GR:BuildRosterView(parent)
    if not parent then return end
    
    -- Prevent Duplicate Builds
    if parent.isRosterBuilt then return end
    parent.isRosterBuilt = true

    -- Cleanup Placeholders
    for _, region in ipairs({parent:GetRegions()}) do
        if region:GetObjectType() == "FontString" then region:Hide() end
    end
    
    -- A. GUILD HEADER & MOTD
    
    -- 1. Guild Name Label (Gold, Title Size)
    local guildNameLabel = parent:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
    guildNameLabel:SetPoint("TOPLEFT", 20, -35)
    guildNameLabel:SetTextColor(1, 0.82, 0, 1) 
    guildNameLabel:SetText(GetGuildInfo("player") or "Guild Name")

    -- 2. Message of the Day
    local gmotdLabel = parent:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    gmotdLabel:SetPoint("TOPLEFT", 20, -50)
    gmotdLabel:SetPoint("TOPRIGHT", -20, -50)
    gmotdLabel:SetJustifyH("CENTER")
    gmotdLabel:SetTextColor(0, 1, 0, 1)
    
    -- INITIAL FETCH ATTEMPT
    gmotdLabel:SetText(GetGuildRosterMOTD() or "No Message of the Day")
    parent.gmotdLabel = gmotdLabel
    
    -- Event for MOTD updates
    local motdFrame = CreateFrame("Frame", nil, parent)
    motdFrame:RegisterEvent("GUILD_MOTD")
    motdFrame:RegisterEvent("GUILD_ROSTER_UPDATE")
    
    local function UpdateMOTD()
        local msg = GetGuildRosterMOTD()
        if msg and msg ~= "" then
            gmotdLabel:SetText(msg)
        else
            gmotdLabel:SetText("No Message of the Day")
        end
    end

    motdFrame:SetScript("OnEvent", function() 
        if parent:IsVisible() then UpdateMOTD() end 
    end)
    
    -- Force Update on Show
    parent:HookScript("OnShow", function()
        local gName = GetGuildInfo("player")
        if gName then guildNameLabel:SetText(gName) end
        RequestGuildRoster() -- Safe Call
        UpdateMOTD()
    end)

    -- B. ROSTER LIST CONTAINER
    local listContainer = CreateFrame("Frame", "GRS_RosterListFrame", parent, "BackdropTemplate")
    listContainer:SetPoint("TOPLEFT", 10, -80)
    listContainer:SetPoint("BOTTOMRIGHT", -10, 50)
    listContainer:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        tile = true, tileSize = 16, edgeSize = 16,
        insets = { left = 4, right = 4, top = 4, bottom = 4 }
    })
    listContainer:SetBackdropColor(0, 0, 0, 0.8)
    GR.rosterListContainer = listContainer

    -- C. BOTTOM BUTTONS
    local btnHeight = 22
    local btnWidth = 120

    -- 1. Invite Member
    local btnInvite = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    btnInvite:SetSize(btnWidth, btnHeight)
    btnInvite:SetPoint("BOTTOMLEFT", 10, 10)
    btnInvite:SetText("Invite Member")
    SkinButton(btnInvite)
    if CanGuildInvite() then btnInvite:Enable() else btnInvite:Disable() end
    btnInvite:SetScript("OnClick", function() StaticPopup_Show("ADD_GUILDMEMBER") end)

    -- 2. Guild Settings
    local btnSettings = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    btnSettings:SetSize(btnWidth, btnHeight)
    btnSettings:SetPoint("LEFT", btnInvite, "RIGHT", 10, 0)
    btnSettings:SetText("Guild Settings")
    SkinButton(btnSettings)
    if GR:IsGM() then btnSettings:Show() else btnSettings:Hide() end
    btnSettings:SetScript("OnClick", function() 
        if not InCombatLockdown() then
            if not GuildControlUI then GuildControlUI_LoadUI() end
            if GuildControlUI then GuildControlUI:Show() end
        end
    end)

    -- 3. Recruitment (Hidden for TBC/Classic Compatibility)
    local btnRecruit = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    btnRecruit:SetSize(btnWidth, btnHeight)
    btnRecruit:SetPoint("LEFT", btnSettings, "RIGHT", 10, 0)
    btnRecruit:SetText("Recruitment")
    SkinButton(btnRecruit)
    btnRecruit:Hide()
    
    -- E. TRIGGER MEMBERS LIST
    if GR.UpdateRosterList then GR:UpdateRosterList() end
    
    print("|cff00ff00GRS:|r Roster UI Built.")
end

-- 4. ROBUST INITIALIZATION
local loader = CreateFrame("Frame")
loader:RegisterEvent("PLAYER_ENTERING_WORLD")
loader:RegisterEvent("ADDON_LOADED")
loader:SetScript("OnEvent", function(self, event, arg1)
    if event == "PLAYER_ENTERING_WORLD" then
        RequestGuildRoster() -- Safe Pre-fetch
    end
    
    -- Try to build immediately if GR is ready
    if GR and GR.views and GR.views[5] then
        GR:BuildRosterView(GR.views[5])
        self:UnregisterAllEvents() -- Stop once done
    end
end)