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

-- =========================================================================
-- 1. CORE INITIALIZATION & CONSTANTS
-- =========================================================================

-- Ensure Module Namespace exists
if not GR.RR then GR.RR = {} end

-- CONSTANTS CONTAINER
GR.RR.CONST = {}

GR.RR.CONST.ROSTER_BG_PATH = "Interface\\AddOns\\GuildRecruiterManagement\\Media\\RaidRosterBackground.tga"
GR.RR.CONST.INSPECT_BG_PATH = "Interface\\AddOns\\GuildRecruiterManagement\\Media\\Inspection.tga"
GR.RR.CONST.COMM_PREFIX = "GRS_RR"
GR.RR.CONST.SYNC_INTERVAL = 900 
GR.RR.CONST.MAX_ROWS_PER_COLUMN = 10
GR.RR.CONST.COMM_DELIM = "^"
GR.RR.CONST.MAX_COMM_CHUNK = 200

GR.RR.CONST.ROLE_TEX = {
    ["TANK"] = "Interface\\Icons\\Ul_70_tank_icon",
    ["HEALER"] = "Interface\\Icons\\Ul_70_healer_icon",
    ["DPS"] = "Interface\\Icons\\Ul_70_dps_icon",
    ["BENCH"] = "Interface\\Icons\\Spell_ChargePositive",
    ["ABSENT"] = "Interface\\Icons\\Spell_ChargeNegative"
}

-- Colors for Attendance Blocks
GR.RR.CONST.STATUS_COLORS = {
    Present = {0, 1, 0, 1},
    TANK    = {0, 1, 0, 1},
    HEALER  = {0, 1, 0, 1},
    DPS     = {0, 1, 0, 1},
    BENCH   = {0, 0.6, 1, 1},
    TENTATIVE = {1, 0.5, 0, 1},
    ABSENT  = {0.5, 0.5, 0.5, 1},
    NOSHOW  = {0.8, 0, 0, 1},
    NULL    = {0.2, 0.2, 0.2, 1}
}

-- TBC Classes Only (No DK, Monk, DH, Evoker)
GR.RR.CONST.CLASS_ICON_TCOORDS = {
    ["WARRIOR"] = {0, 0.25, 0, 0.25}, ["MAGE"] = {0.25, 0.5, 0, 0.25},
    ["ROGUE"] = {0.5, 0.75, 0, 0.25}, ["DRUID"] = {0.75, 1, 0, 0.25},
    ["HUNTER"] = {0, 0.25, 0.25, 0.5}, ["SHAMAN"] = {0.25, 0.5, 0.25, 0.5},
    ["PRIEST"] = {0.5, 0.75, 0.25, 0.5}, ["WARLOCK"] = {0.75, 1, 0.25, 0.5},
    ["PALADIN"] = {0, 0.25, 0.5, 0.75}
}

-- Module State Defaults
GR.RR.selectedEvent = nil
GR.RR.viewMode = "MEMBER" 
GR.RR.cache = {}
GR.RR.lastSync = 0
GR.RR.multiSelect = {}
GR.RR.inspectSelection = nil
GR.RR.inviteSelection = {}
GR.RR.trackingPanels = {} 
GR.RR.Initialized = false

-- =========================================================================
-- 2. INITIALIZATION (Split: Early Network + Deferred UI)
-- =========================================================================

-- Standalone comm frame (not tied to any UI view)
local rrCommFrame = CreateFrame("Frame")

function GR:RR_EarlyInit()
    -- DB Bootstrap (needed before any sync data arrives)
    if not GRS_RaidRosterDB then GRS_RaidRosterDB = {} end
    if not GRS_RaidRosterDB.events then GRS_RaidRosterDB.events = {} end
    if not GRS_RaidRosterDB.attendanceHistory then GRS_RaidRosterDB.attendanceHistory = {} end
    if not GRS_RaidRosterDB.logs then GRS_RaidRosterDB.logs = {} end
    
    if not GRS_RaidRosterDB.settings then 
        GRS_RaidRosterDB.settings = {
            panelA = { title = "Raiders", ranks = {}, limit = 10 },
            panelB = { title = "Trialists", ranks = {}, limit = 10 },
            showOffline = false
        }
    end
    if not GRS_RaidRosterDB.settings.panelA then GRS_RaidRosterDB.settings.panelA = { title = "Raiders", ranks = {}, limit = 10 } end
    if not GRS_RaidRosterDB.settings.panelB then GRS_RaidRosterDB.settings.panelB = { title = "Trialists", ranks = {}, limit = 10 } end
    if GRS_RaidRosterDB.settings.showOffline == nil then GRS_RaidRosterDB.settings.showOffline = false end

    -- Register Network on standalone frame (not tied to UI tab)
    C_ChatInfo.RegisterAddonMessagePrefix(GR.RR.CONST.COMM_PREFIX)
    rrCommFrame:RegisterEvent("CHAT_MSG_ADDON")
    rrCommFrame:SetScript("OnEvent", function(s, event, ...)
        if event == "CHAT_MSG_ADDON" then GR:RR_OnComm(...) end
    end)
    
    -- Periodic Sync (15min)
    C_Timer.NewTicker(GR.RR.CONST.SYNC_INTERVAL, function() GR:RR_RequestSync() end)
    
    -- Initial sync with 8s delay (wait for guild roster cache to populate)
    C_Timer.After(8, function() if IsInGuild() then GR:RR_RequestSync() end end)
end

function GR:RR_Init()
    GR.RR.Frame = GR.views[6]
    
    if GR.RR.Lite and GR.RR.Lite.Init then GR.RR.Lite:Init() end

    -- GUILD_ROSTER_UPDATE stays on the UI frame (visual-only)
    GR.RR.Frame:RegisterEvent("GUILD_ROSTER_UPDATE")
    GR.RR.Frame:SetScript("OnEvent", function(s, event, ...)
        if event == "GUILD_ROSTER_UPDATE" then
            if GR.RR.viewMode == "OFFICER" and s:IsVisible() then GR:RR_UpdateOfficerRightPane() end
        end
    end)
    
    -- TBC: DevOfficerMode + CanEditOfficerNote/CanGuildInvite fallback
    if (IsInGuild() and (CanEditOfficerNote and CanEditOfficerNote() or CanGuildInvite and CanGuildInvite() or IsGuildLeader())) or GR.devOfficerMode then
        GR.RR.viewMode = "OFFICER"
    else
        GR.RR.viewMode = "MEMBER"
    end
    
    GR:RR_BuildUI()
    GR:RR_ScanDB()
end

hooksecurefunc(GR, "SwitchView", function(self, id) 
    if id == 6 and not GR.RR.Initialized then 
        GR:RR_Init()
        GR.RR.Initialized = true 
    end 
end)
