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

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

-- =========================================================================
-- 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 C_GuildInfo.CanEditOfficerNote() 
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 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 (Enhanced Logic)
    local motdFrame = CreateFrame("Frame", nil, parent)
    motdFrame:RegisterEvent("GUILD_MOTD")
    motdFrame:RegisterEvent("GUILD_ROSTER_UPDATE") -- Added Roster Update as fallback trigger
    
    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()
        C_GuildInfo.GuildRoster() -- Request fresh data from server
        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
    local btnRecruit = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    btnRecruit:SetSize(btnWidth, btnHeight)
    btnRecruit:SetPoint("LEFT", btnSettings, "RIGHT", 10, 0)
    btnRecruit:SetText("Recruitment")
    SkinButton(btnRecruit)
    if GR:IsOfficer() or GR:IsGM() then btnRecruit:Show() else btnRecruit:Hide() end
    
    btnRecruit:SetScript("OnClick", function() 
        if not InCombatLockdown() then
            C_AddOns.LoadAddOn("Blizzard_Communities")
            local dialog = CommunitiesFrame and CommunitiesFrame.RecruitmentDialog
            if dialog then
                dialog:SetParent(UIParent)
                dialog:SetFrameStrata("DIALOG")
                dialog:Show()
                local clubId = C_Club.GetGuildClubId()
                if clubId and CommunitiesFrame.SelectClub then
                    CommunitiesFrame:SelectClub(clubId)
                end
            else
                print("|cffff0000GRS:|r Recruitment Dialog not found.")
            end
        end
    end)

    -- D. REPLACE NATIVE FRAME
    local chkReplace = CreateFrame("CheckButton", nil, parent, "ChatConfigCheckButtonTemplate")
    chkReplace:SetPoint("BOTTOMRIGHT", -200, 10)
    chkReplace.Text:SetText("Replace Native Frame")
    if GRS_DB and GRS_DB.ReplaceGuildFrame then chkReplace:SetChecked(true) else chkReplace:SetChecked(false) end
    
    chkReplace:SetScript("OnClick", function(self)
        if not GRS_DB then GRS_DB = {} end
        GRS_DB.ReplaceGuildFrame = self:GetChecked()
        print("|cff00ff00GRS:|r Native Frame Replacement: " .. (GRS_DB.ReplaceGuildFrame and "ON" or "OFF"))
    end)
    
    if not GR.hookedToggle then
        hooksecurefunc("ToggleGuildFrame", function()
            if GRS_DB and GRS_DB.ReplaceGuildFrame then
                if CommunitiesFrame and CommunitiesFrame:IsShown() then HideUIPanel(CommunitiesFrame) end
                if GR:IsShown() then GR:Hide() else GR:Show() end
            end
        end)
        GR.hookedToggle = true
    end
    
    -- 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)
    -- 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)