--[[
	Cerebro - Onboarding Wizard
	5-screen tutorial for new raiders, triggered after guild lock
	
	See docs/proposals/ONBOARDING_FLOW.md for full specification.
]]--

local AddonName, PrivateTable = ...
local Cerebro = LibStub("AceAddon-3.0"):GetAddon(AddonName)
local AceGUI = LibStub("AceGUI-3.0")

local Onboarding = Cerebro:NewModule("Onboarding", "AceEvent-3.0")

-- Constants
local FRAME_WIDTH = 500
local FRAME_HEIGHT = 400
local TOTAL_SCREENS = 5

-- Module State
Onboarding.currentScreen = 1
Onboarding.frame = nil
Onboarding.pausedForCombat = false
Onboarding.nativeFrames = {}  -- Track native frames for cleanup

function Onboarding:OnInitialize()
	-- Register combat events for pause/resume
	self:RegisterEvent("PLAYER_REGEN_DISABLED", "OnCombatStart")
	self:RegisterEvent("PLAYER_REGEN_ENABLED", "OnCombatEnd")
end

function Onboarding:OnEnable()
	-- Module enabled
end

-- Clean up native frames when switching screens
function Onboarding:CleanupNativeFrames()
	for _, frame in ipairs(self.nativeFrames) do
		if frame then
			frame:Hide()
			frame:SetParent(nil)
			frame:ClearAllPoints()
		end
	end
	self.nativeFrames = {}
end

-- Track a frame for later cleanup
function Onboarding:TrackFrame(frame)
	if frame then
		table.insert(self.nativeFrames, frame)
	end
	return frame
end

--[[=============================================
	Combat Pause/Resume
===============================================]]

function Onboarding:OnCombatStart()
	if self.frame and self.frame:IsShown() then
		self.pausedForCombat = true
		self.frame:Hide()
		Cerebro:Debug("Onboarding paused for combat")
	end
end

function Onboarding:OnCombatEnd()
	if self.pausedForCombat then
		self.pausedForCombat = false
		-- Delay slightly to avoid UI conflicts
		Cerebro:ScheduleTimer(function()
			if not InCombatLockdown() then
				self:ShowFrame()
				Cerebro:Debug("Onboarding resumed after combat")
			end
		end, 0.5)
	end
end

--[[=============================================
	Main Entry Point
===============================================]]

function Onboarding:Show(force)
	-- Check if already completed (unless forced via /cb intro)
	if not force and Cerebro.db.global.config.onboardingCompleted then
		return
	end
	
	self.currentScreen = 1
	self:ShowFrame()
end

function Onboarding:ShowFrame()
	if InCombatLockdown() then
		self.pausedForCombat = true
		Cerebro:Debug("Onboarding deferred: in combat")
		return
	end
	
	if not self.frame then
		self:CreateFrame()
	end
	
	self:DrawCurrentScreen()
	self.frame:Show()
end

function Onboarding:Hide()
	if self.frame then
		self.frame:Hide()
	end
end

function Onboarding:Complete()
	Cerebro.db.global.config.onboardingCompleted = true
	self:Hide()
	
	-- Check if season notice should be shown
	self:CheckSeasonNotice()
end

--[[=============================================
	Frame Creation
===============================================]]

function Onboarding:CreateFrame()
	local frame = AceGUI:Create("Frame")
	frame:SetTitle("Cerebro")
	frame:SetWidth(FRAME_WIDTH)
	frame:SetHeight(FRAME_HEIGHT)
	frame:SetLayout("Flow")
	frame:EnableResize(false)
	
	-- Center on screen
	frame:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
	
	-- ESC key closes and marks complete
	_G["CerebroOnboardingFrame"] = frame.frame
	tinsert(UISpecialFrames, "CerebroOnboardingFrame")
	
	frame:SetCallback("OnClose", function()
		Onboarding:Complete()
	end)
	
	-- Hide the status bar footer completely (including Close button)
	frame:SetStatusText(nil)
	if frame.statustext then
		frame.statustext:GetParent():Hide()
	end
	-- Hide the status bar background and close/resize corner
	if frame.statusbg then
		frame.statusbg:Hide()
	end
	if frame.sizer_se then
		frame.sizer_se:Hide()
	end
	if frame.sizer_s then
		frame.sizer_s:Hide()
	end
	if frame.sizer_e then
		frame.sizer_e:Hide()
	end
	-- Hide the close button in the status bar area
	if frame.closebutton then
		frame.closebutton:Hide()
	end
	
	-- Iterate through the native frame's children to find and hide the Close button
	local nativeFrame = frame.frame
	for _, child in ipairs({nativeFrame:GetChildren()}) do
		if child:GetObjectType() == "Button" then
			local point, _, _, _, y = child:GetPoint()
			-- If button is at the bottom of the frame (low y offset), hide it
			if point and (point == "BOTTOMRIGHT" or (y and y < 50)) then
				local text = child:GetText()
				if text and text:lower():find("close") then
					child:Hide()
				end
			end
		end
	end
	
	self.frame = frame
end

--[[=============================================
	Screen Drawing
===============================================]]

function Onboarding:DrawCurrentScreen()
	if not self.frame then return end
	
	self.frame:ReleaseChildren()
	
	-- Clean up native frames from previous screen
	self:CleanupNativeFrames()
	
	-- Content area
	local content = AceGUI:Create("SimpleGroup")
	content:SetLayout("Flow")
	content:SetFullWidth(true)
	content:SetHeight(FRAME_HEIGHT - 80)
	self.frame:AddChild(content)
	
	-- Draw the appropriate screen
	if self.currentScreen == 1 then
		self:DrawScreen1_Welcome(content)
	elseif self.currentScreen == 2 then
		self:DrawScreen2_EarnEP(content)
	elseif self.currentScreen == 3 then
		self:DrawScreen3_Readiness(content)
	elseif self.currentScreen == 4 then
		self:DrawScreen4_Loot(content)
	elseif self.currentScreen == 5 then
		self:DrawScreen5_ThankYou(content)
	end
	
	-- Navigation bar
	self:DrawNavigation()
end

function Onboarding:DrawNavigation()
	-- Clean up existing nav bar if present
	if self.navBar then
		self.navBar:Hide()
		self.navBar:SetParent(nil)
		self.navBar = nil
	end
	
	-- Create a native frame for navigation, anchored to the bottom
	local navBar = self:TrackFrame(CreateFrame("Frame", nil, self.frame.frame))
	navBar:SetSize(FRAME_WIDTH - 40, 40)
	navBar:SetPoint("BOTTOMLEFT", self.frame.frame, "BOTTOMLEFT", 20, 15)
	self.navBar = navBar
	
	-- Back button
	local backBtn = CreateFrame("Button", nil, navBar, "UIPanelButtonTemplate")
	backBtn:SetSize(80, 24)
	backBtn:SetPoint("LEFT", 0, 0)
	backBtn:SetText("< Back")
	if self.currentScreen == 1 then
		backBtn:Disable()
	else
		backBtn:Enable()
	end
	backBtn:SetScript("OnClick", function()
		if self.currentScreen > 1 then
			self.currentScreen = self.currentScreen - 1
			self:DrawCurrentScreen()
		end
	end)
	
	-- Next/Finish button
	local nextBtn = CreateFrame("Button", nil, navBar, "UIPanelButtonTemplate")
	nextBtn:SetSize(80, 24)
	nextBtn:SetPoint("RIGHT", 0, 0)
	if self.currentScreen == TOTAL_SCREENS then
		nextBtn:SetText("Finish")
	else
		nextBtn:SetText("Next >")
	end
	nextBtn:SetScript("OnClick", function()
		if self.currentScreen < TOTAL_SCREENS then
			self.currentScreen = self.currentScreen + 1
			self:DrawCurrentScreen()
		else
			self:Complete()
		end
	end)
	
	-- Progress dots (centered)
	local dotsFS = navBar:CreateFontString(nil, "OVERLAY", "GameFontNormal")
	dotsFS:SetPoint("CENTER", 0, 0)
	local dots = ""
	for i = 1, TOTAL_SCREENS do
		if i == self.currentScreen then
			dots = dots .. "|cffFFD700[*]|r "
		else
			dots = dots .. "|cff888888[ ]|r "
		end
	end
	dotsFS:SetText(dots)
	
	navBar:Show()
end

--[[=============================================
	Screen 1: Welcome
===============================================]]

function Onboarding:DrawScreen1_Welcome(container)
	-- Title
	local title = AceGUI:Create("Label")
	title:SetText("  |cffFFD700Welcome to Cerebro|r")
	title:SetFullWidth(true)
	title:SetFont(GameFontNormalHuge:GetFont())
	container:AddChild(title)
	
	local subtitle = AceGUI:Create("Label")
	subtitle:SetText("|cffffffff  |rYour guild's effort and loot tracking system.\n ")
	subtitle:SetFullWidth(true)
	container:AddChild(subtitle)
	
	-- Native tile row: EP ÷ GP = PR
	local tileWrapper = AceGUI:Create("SimpleGroup")
	tileWrapper:SetLayout("Fill")
	tileWrapper:SetFullWidth(true)
	tileWrapper:SetHeight(80)
	container:AddChild(tileWrapper)
	
	-- Create a native frame to hold the tiles
	local tileHost = self:TrackFrame(CreateFrame("Frame", nil, tileWrapper.frame))
	tileHost:SetAllPoints()
	
	-- Helper function to create a stat tile
	local function CreateTile(parent, label, borderColor, x)
		local f = self:TrackFrame(CreateFrame("Frame", nil, parent, "BackdropTemplate"))
		f:SetSize(70, 55)
		f:SetPoint("LEFT", x, 0)
		f:SetBackdrop({
			bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
			edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
			edgeSize = 12,
			insets = { left = 2, right = 2, top = 2, bottom = 2 }
		})
		f:SetBackdropColor(0.1, 0.1, 0.1, 0.8)
		f:SetBackdropBorderColor(borderColor[1], borderColor[2], borderColor[3], 1)
		
		local v = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
		v:SetPoint("CENTER", 0, 0)
		v:SetText(label)
		v:SetTextColor(borderColor[1], borderColor[2], borderColor[3])
		
		return f
	end
	
	-- Create tiles: EP ÷ GP = PR centered
	local startX = 80  -- Centered positioning
	
	-- EP tile (white border)
	CreateTile(tileHost, "EP", {1, 1, 1}, startX)
	
	-- Division symbol
	local div1 = tileHost:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
	div1:SetPoint("LEFT", startX + 85, 0)
	div1:SetText("|cffFFD700÷|r")
	
	-- GP tile (gray border)
	CreateTile(tileHost, "GP", {0.5, 0.5, 0.5}, startX + 110)
	
	-- Equals symbol
	local eq = tileHost:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
	eq:SetPoint("LEFT", startX + 195, 0)
	eq:SetText("|cffFFD700=|r")
	
	-- PR tile (gold border, emphasized)
	local prTile = self:TrackFrame(CreateFrame("Frame", nil, tileHost, "BackdropTemplate"))
	prTile:SetSize(85, 60)
	prTile:SetPoint("LEFT", startX + 220, 0)
	prTile:SetBackdrop({
		bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
		edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
		edgeSize = 12,
		insets = { left = 2, right = 2, top = 2, bottom = 2 }
	})
	prTile:SetBackdropColor(0.1, 0.1, 0.1, 0.8)
	prTile:SetBackdropBorderColor(1, 0.82, 0, 1)  -- Gold border
	
	local prV = prTile:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
	prV:SetPoint("CENTER", 0, 0)
	prV:SetText("PR")
	prV:SetTextColor(1, 0.82, 0)
	
	-- Spacer
	local spacer = AceGUI:Create("Label")
	spacer:SetText("\n")
	spacer:SetFullWidth(true)
	container:AddChild(spacer)
	
	-- Bullet points with better descriptions
	local bullet1 = AceGUI:Create("Label")
	bullet1:SetText("|cffffffff  |r|cffFFD700*|r |cffFFFFFFEP|r (Effort Points)\n|cffffffff      |rEarned through raids, M+, and preparation")
	bullet1:SetFullWidth(true)
	container:AddChild(bullet1)
	
	local spacer2 = AceGUI:Create("Label")
	spacer2:SetText(" ")
	spacer2:SetFullWidth(true)
	container:AddChild(spacer2)
	
	local bullet2 = AceGUI:Create("Label")
	bullet2:SetText("|cffffffff  |r|cff888888*|r |cff888888GP|r (Gear Points)\n|cffffffff      |rCharged when you win loot from Raid")
	bullet2:SetFullWidth(true)
	container:AddChild(bullet2)
	
	local spacer3 = AceGUI:Create("Label")
	spacer3:SetText(" ")
	spacer3:SetFullWidth(true)
	container:AddChild(spacer3)
	
	local bullet3 = AceGUI:Create("Label")
	bullet3:SetText("|cffffffff  |r|cffFFD700*|r |cffFFD700PR|r (Priority Rating)\n|cffffffff      |rEP / GP = your loot priority")
	bullet3:SetFullWidth(true)
	container:AddChild(bullet3)
	
	-- Spacer
	local spacer4 = AceGUI:Create("Label")
	spacer4:SetText("\n")
	spacer4:SetFullWidth(true)
	container:AddChild(spacer4)
	
	-- Conclusion with emphasis
	local conclusion = AceGUI:Create("Label")
	conclusion:SetText("|cffffffff  |r|cff00ff00The higher your PR, the greater your chance at upgrades!|r")
	conclusion:SetFullWidth(true)
	container:AddChild(conclusion)
end

--[[=============================================
	Screen 2: How to Earn EP (Cards)
===============================================]]

function Onboarding:DrawScreen2_EarnEP(container)
	-- Title
	local title = AceGUI:Create("Label")
	title:SetText("  |cffFFD700How to Earn EP|r\n ")
	title:SetFullWidth(true)
	title:SetFont(GameFontNormalHuge:GetFont())
	container:AddChild(title)
	
	-- Get dynamic config values
	local cfg = Cerebro.db.global.config.epgp
	local prepCfg = Cerebro.db.global.config.prep
	
	local mplusBase = cfg.mplusBase or 20
	local mplusPerLevel = cfg.mplusPerLevel or 5
	local epFarmBoss = cfg.epFarmBoss or 15
	local epProgBoss = cfg.epProgBoss or 50
	local epOnTime = cfg.epOnTime or 50
	local gracePeriod = cfg.onTimeGracePeriod or 5
	local epFullAttendance = cfg.epFullAttendance or 100
	
	local mplusCard = AceGUI:Create("InlineGroup")
	mplusCard:SetTitle("MYTHIC+ DUNGEONS")
	mplusCard:SetFullWidth(true)
	container:AddChild(mplusCard)
	
	local mplusText = AceGUI:Create("Label")
	local example15 = mplusBase + (15 * mplusPerLevel)
	mplusText:SetText(string.format(
		"Complete keys with guildmates. Higher keys = more EP.\n" ..
		"Example: +15 earns |cffFFD700%d|r + 15×|cffFFD700%d|r = |cff00ff00%d EP|r",
		mplusBase, mplusPerLevel, example15
	))
	mplusText:SetFullWidth(true)
	mplusCard:AddChild(mplusText)
	
	local raidCard = AceGUI:Create("InlineGroup")
	raidCard:SetTitle("RAID ATTENDANCE")
	raidCard:SetFullWidth(true)
	container:AddChild(raidCard)
	
	local raidText = AceGUI:Create("Label")
	raidText:SetText(string.format(
		"• Farm Boss: |cffFFD700%d|r EP each\n" ..
		"• Prog Boss: |cffFFD700%d|r EP each\n" ..
		"• Raid Start: |cffFFD700%d|r EP (arrive within |cffFFD700%d|r min)\n" ..
		"• Raid End: |cffFFD700%d|r EP",
		epFarmBoss, epProgBoss, epOnTime, gracePeriod, epFullAttendance
	))
	raidText:SetFullWidth(true)
	raidCard:AddChild(raidText)
	
	local prepCard = AceGUI:Create("InlineGroup")
	prepCard:SetTitle("RAID PREPARATION")
	prepCard:SetFullWidth(true)
	container:AddChild(prepCard)
	
	-- Build per-category prep EP display from config
	local prepLines = {}
	if prepCfg.requireGems then
		table.insert(prepLines, string.format("• Gems: |cffFFD700%d|r EP per socket", prepCfg.gemEPPerSocket or 1))
	end
	if prepCfg.requireEnchants then
		table.insert(prepLines, string.format("• Enchants: |cffFFD700%d|r EP per slot", prepCfg.enchantEPPerSlot or 1))
	end
	if prepCfg.requireFood then
		table.insert(prepLines, string.format("• Food: |cffFFD700%d|r EP", prepCfg.foodEP or 1))
	end
	if prepCfg.requireFlask then
		table.insert(prepLines, string.format("• Flask: |cffFFD700%d|r EP", prepCfg.flaskEP or 1))
	end
	if prepCfg.requireAugmentRune then
		table.insert(prepLines, string.format("• Augment Rune: |cffFFD700%d|r EP", prepCfg.augmentRuneEP or 1))
	end
	if prepCfg.requireVantusRune then
		table.insert(prepLines, string.format("• Vantus Rune: |cffFFD700%d|r EP", prepCfg.vantusRuneEP or 1))
	end
	if prepCfg.requireWeaponEnhancement then
		table.insert(prepLines, string.format("• Weapon Buff: |cffFFD700%d|r EP", prepCfg.weaponEnhancementEP or 1))
	end
	
	local prepText = AceGUI:Create("Label")
	if #prepLines > 0 then
		prepText:SetText(table.concat(prepLines, "\n"))
	else
		prepText:SetText("|cff888888No prep categories currently enabled.|r")
	end
	prepText:SetFullWidth(true)
	prepCard:AddChild(prepText)
	
	-- Disclaimer
	local disclaimer = AceGUI:Create("Label")
	disclaimer:SetText("\n|cff888888Note: Values shown are your guild's current settings.\n   Officers may adjust these during the season.|r")
	disclaimer:SetFullWidth(true)
	container:AddChild(disclaimer)
end

--[[=============================================
	Screen 3: Readiness & Weekly Cap
===============================================]]

function Onboarding:DrawScreen3_Readiness(container)
	-- Title
	local title = AceGUI:Create("Label")
	title:SetText("  |cffFFD700Your Weekly Target|r\n ")
	title:SetFullWidth(true)
	title:SetFont(GameFontNormalHuge:GetFont())
	container:AddChild(title)
	
	-- Intro text
	local intro = AceGUI:Create("Label")
	intro:SetText("|cffffffff  |rThe Readiness Bar tracks your EP from M+ and other activities.\n ")
	intro:SetFullWidth(true)
	container:AddChild(intro)
	
	-- Get current readiness
	local myName = Cerebro:GetFullPlayerName(UnitName("player"))
	local epgp = Cerebro:GetModule("EPGP")
	local readyCur = epgp:GetReadiness(myName)
	local readyCap = Cerebro.db.global.config.epgp.readinessCap or 1000
	local readyPct = (readyCap > 0) and math.min(readyCur / readyCap, 1.0) or 0
	
	-- Current readiness label
	local currentLabel = AceGUI:Create("Label")
	currentLabel:SetText(string.format(
		"|cffffffff  |r> Your current readiness: |cffFFD700%d|r / |cffFFD700%d|r (|cff00ff00%d%%|r)",
		readyCur, readyCap, math.floor(readyPct * 100)
	))
	currentLabel:SetFullWidth(true)
	container:AddChild(currentLabel)
	
	-- Native StatusBar widget (same as My Progress tab)
	local barWrapper = AceGUI:Create("SimpleGroup")
	barWrapper:SetLayout("Fill")
	barWrapper:SetFullWidth(true)
	barWrapper:SetHeight(32)
	container:AddChild(barWrapper)
	
	local bar = self:TrackFrame(CreateFrame("StatusBar", nil, barWrapper.frame, "BackdropTemplate"))
	bar:SetSize(400, 24)
	bar:SetPoint("TOPLEFT", 20, -4)
	bar:SetStatusBarTexture("Interface\\TargetingFrame\\UI-StatusBar")
	bar:SetStatusBarColor(0, 1, 0)
	bar:SetMinMaxValues(0, 1)
	bar:SetValue(readyPct)
	
	-- Bar BG
	local barBg = bar:CreateTexture(nil, "BACKGROUND")
	barBg:SetAllPoints()
	barBg:SetColorTexture(0.2, 0.2, 0.2, 0.5)
	
	-- Bar Border
	bar:SetBackdrop({edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", edgeSize = 8})
	
	-- Bar text overlay
	local barText = bar:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	barText:SetPoint("CENTER", 0, 0)
	barText:SetText(string.format("Readiness: %d%% (%d/%d)", math.floor(readyPct * 100), readyCur, readyCap))
	
	-- Spacer after bar
	local spacer = AceGUI:Create("Label")
	spacer:SetText(" ")
	spacer:SetFullWidth(true)
	container:AddChild(spacer)
	
	-- Explanation
	local explanation = AceGUI:Create("Label")
	explanation:SetText(string.format(
		"|cffffffff  |rOnce you reach |cffFFD700%d|r EP, you've maxed your weekly contribution.\n" ..
		"|cffffffff  |rThis encourages balance -- stay active, but don't burn out!\n ",
		readyCap
	))
	explanation:SetFullWidth(true)
	container:AddChild(explanation)
	
	-- Tip
	local tip = AceGUI:Create("Label")
	tip:SetText("|cffffffff  |r|cff00ff00Tip:|r Raid boss EP is separate and never capped.\n ")
	tip:SetFullWidth(true)
	container:AddChild(tip)
	
	-- Disclaimer
	local disclaimer = AceGUI:Create("Label")
	disclaimer:SetText(string.format(
		"|cffffffff  |r|cff888888Note: Resets every Tuesday. Current cap: %d EP (officers may adjust).|r",
		readyCap
	))
	disclaimer:SetFullWidth(true)
	container:AddChild(disclaimer)
end

--[[=============================================
	Screen 4: Loot & Priority
===============================================]]

function Onboarding:DrawScreen4_Loot(container)
	-- Title
	local title = AceGUI:Create("Label")
	title:SetText("  |cffFFD700Loot & Priority|r\n ")
	title:SetFullWidth(true)
	title:SetFont(GameFontNormalHuge:GetFont())
	container:AddChild(title)
	
	-- Intro
	local intro = AceGUI:Create("Label")
	intro:SetText("|cffffffff  |rWhen loot drops in raid, Cerebro works with RCLootCouncil:\n ")
	intro:SetFullWidth(true)
	container:AddChild(intro)
	
	-- Spacer
	local spacer1 = AceGUI:Create("Label")
	spacer1:SetText(" ")
	spacer1:SetFullWidth(true)
	container:AddChild(spacer1)
	
	-- Steps
	local step1 = AceGUI:Create("Label")
	step1:SetText("|cffffffff    |r|cffFFD7001.|r Your |cffFFD700PR|r appears in the voting frame\n ")
	step1:SetFullWidth(true)
	container:AddChild(step1)
	
	local step2 = AceGUI:Create("Label")
	step2:SetText("|cffffffff    |r|cffFFD7002.|r Officers use PR to guide fair distribution\n ")
	step2:SetFullWidth(true)
	container:AddChild(step2)
	
	local step3 = AceGUI:Create("Label")
	step3:SetText("|cffffffff    |r|cffFFD7003.|r If you win, GP is charged and your PR adjusts\n ")
	step3:SetFullWidth(true)
	container:AddChild(step3)
	
	-- Spacer
	local spacer2 = AceGUI:Create("Label")
	spacer2:SetText("\n")
	spacer2:SetFullWidth(true)
	container:AddChild(spacer2)
	
	-- Emphasis
	local emphasis = AceGUI:Create("Label")
	emphasis:SetText("|cffffffff  |r|cff00ff00Higher PR = higher priority for upgrades.|r\n ")
	emphasis:SetFullWidth(true)
	container:AddChild(emphasis)
	
	-- Spacer
	local spacer3 = AceGUI:Create("Label")
	spacer3:SetText("\n")
	spacer3:SetFullWidth(true)
	container:AddChild(spacer3)
	
	-- Officer caveat
	local caveat = AceGUI:Create("Label")
	caveat:SetText("|cffffffff  |r|cffFF8800Note: Officers reserve the right to call an audible when\n|cffffffff      |rtwo or more players' PRs are too close.|r")
	caveat:SetFullWidth(true)
	container:AddChild(caveat)
end

--[[=============================================
	Screen 5: Thank You (Role-based)
===============================================]]

function Onboarding:DrawScreen5_ThankYou(container)
	-- Title
	local title = AceGUI:Create("Label")
	title:SetText("  |cffFFD700Thank You!|r\n ")
	title:SetFullWidth(true)
	title:SetFont(GameFontNormalHuge:GetFont())
	container:AddChild(title)
	
	-- Instructions
	local instructions = AceGUI:Create("Label")
	instructions:SetText("|cffffffff  |rTo open Cerebro at any time:\n ")
	instructions:SetFullWidth(true)
	container:AddChild(instructions)
	
	-- Spacer
	local spacer1 = AceGUI:Create("Label")
	spacer1:SetText(" ")
	spacer1:SetFullWidth(true)
	container:AddChild(spacer1)
	
	local bullet1 = AceGUI:Create("Label")
	bullet1:SetText("|cffffffff    |r|cffFFD700*|r Click the minimap icon, or\n ")
	bullet1:SetFullWidth(true)
	container:AddChild(bullet1)
	
	local bullet2 = AceGUI:Create("Label")
	bullet2:SetText("|cffffffff    |r|cffFFD700*|r Type |cff00ff00/cb|r in chat\n ")
	bullet2:SetFullWidth(true)
	container:AddChild(bullet2)
	
	-- Spacer
	local spacer2 = AceGUI:Create("Label")
	spacer2:SetText("\n")
	spacer2:SetFullWidth(true)
	container:AddChild(spacer2)
	
	-- Divider
	local divider = AceGUI:Create("Label")
	divider:SetText("|cffffffff  |r|cff444444-----------------------------------------------------|r\n ")
	divider:SetFullWidth(true)
	container:AddChild(divider)
	
	-- Spacer
	local spacer3 = AceGUI:Create("Label")
	spacer3:SetText(" ")
	spacer3:SetFullWidth(true)
	container:AddChild(spacer3)
	
	-- Role-based message
	local myName = Cerebro:GetFullPlayerName(UnitName("player"))
	local playerData = Cerebro:GetPlayerData(myName)
	local isOfficer = Cerebro:IsOfficer()
	local status = playerData.status or "Pending"
	
	local roleMessage = AceGUI:Create("Label")
	
	if isOfficer then
		roleMessage:SetText("|cffffffff  |r|cffFFD700* Officer responsibility assigned.|r\n\n" ..
			"|cffffffff  |rYou can now:\n" ..
			"|cffffffff    |r* Award or adjust EP/GP\n" ..
			"|cffffffff    |r* Admit pending raiders\n" ..
			"|cffffffff    |r* Configure guild settings")
	elseif status == "Core" then
		roleMessage:SetText("|cffffffff  |r|cff00ff00* You're part of the team -- go start earning EP!|r")
	else
		-- Pending
		roleMessage:SetText("|cffffffff  |r|cffFF8800You're awaiting officer approval.|r\n\n" ..
			"|cffffffff  |rIn the meantime, feel free to start earning EP!\n" ..
			"|cffffffff  |rYour progress is being tracked.")
	end
	
	roleMessage:SetFullWidth(true)
	container:AddChild(roleMessage)
	
	-- Officer Configuration Button
	if isOfficer then
		local spacer = AceGUI:Create("Label")
		spacer:SetText("\n")
		spacer:SetFullWidth(true)
		container:AddChild(spacer)
		
		local configBtn = AceGUI:Create("Button")
		configBtn:SetText("Configure Guild Settings")
		configBtn:SetWidth(200)
		configBtn:SetCallback("OnClick", function()
			Onboarding:Complete()
			if Cerebro.modules.UI and Cerebro.modules.UI.ShowConfig then
				Cerebro.modules.UI:ShowConfig()
			end
		end)
		
		-- Center the button
		local btnGroup = AceGUI:Create("SimpleGroup")
		btnGroup:SetLayout("Flow")
		btnGroup:SetFullWidth(true)
		btnGroup:AddChild(configBtn)
		
		-- Manual centering hack with spacers (AceGUI flow layout limitation)
		-- We use a full-width container and align simplistic content
		container:AddChild(btnGroup)
	end
end

--[[=============================================
	New Season Notice
===============================================]]

function Onboarding:CheckSeasonNotice()
	local seasonInfo = Cerebro:GetSeasonInfo()
	if not seasonInfo or not seasonInfo.seasonID then return end
	
	local lastShown = Cerebro.db.global.config.lastSeasonNoticeShown or 0
	
	if seasonInfo.seasonID > lastShown then
		self:ShowSeasonNotice(seasonInfo.seasonID)
	end
end

function Onboarding:ShowSeasonNotice(seasonID)
	local baseGP = Cerebro.db.global.config.epgp.baseGP or 200
	
	StaticPopupDialogs["CEREBRO_NEW_SEASON_NOTICE"] = {
		text = string.format(
			"|cffFFD700New Season Detected!|r\n\n" ..
			"All standings have been reset:\n" ..
			"  • EP → 0\n" ..
			"  • GP → Base (%d)\n" ..
			"  • M+ History → Cleared\n\n" ..
			"|cff00ff00Good luck this season!|r",
			baseGP
		),
		button1 = "Got It",
		OnAccept = function()
			Cerebro.db.global.config.lastSeasonNoticeShown = seasonID
		end,
		timeout = 0,
		whileDead = true,
		hideOnEscape = true,
		preferredIndex = 3,
	}
	
	StaticPopup_Show("CEREBRO_NEW_SEASON_NOTICE")
end
