--[[
    Cerebro - UISandbox Progress Tab
    Extracted from UI/UISandbox.lua (Phase 2a decomposition)

    @module UI.Tabs.Progress
    @version 0.12.0
]]--

local AddonName = "Cerebro"
local Cerebro = LibStub("AceAddon-3.0"):GetAddon(AddonName)
local AceGUI = LibStub("AceGUI-3.0")
local UISandbox = Cerebro:GetModule("UISandbox")

--[[=============================================
	Tab: My Progress (Real Player Data)
===============================================]]

function UISandbox:DrawProgressTab(container)
	-- Get actual player data
	local myName = Cerebro:GetFullPlayerName(UnitName("player"))
	local player = Cerebro.Player:New(myName)
	local playerData = Cerebro:GetPlayerData(myName) or {}

	local pr = player:GetPR() or 0
	local ep = playerData.ep or 0
	local gp = playerData.gp or 200

	-- Calculate PR rank (GetAllPlayers returns sorted by PR descending)
	local allPlayers = Cerebro:GetAllPlayers()
	local prRank = #allPlayers
	for i, p in ipairs(allPlayers) do
		if p.name == myName then
			prRank = i
			break
		end
	end

	-- Get M+ history data upfront for total count
	local MPlus = Cerebro:GetModule("MythicPlus", true)
	local totalRuns = 0
	if Cerebro.db.global.mplusRuns then
		totalRuns = #Cerebro.db.global.mplusRuns
	end

	-- ============================================
	-- HERO SECTION (Compact - Fixed, No Scroll)
	-- ============================================
	local heroWrapper = AceGUI:Create("SimpleGroup")
	heroWrapper:SetLayout("Fill")
	heroWrapper:SetFullWidth(true)
	heroWrapper:SetHeight(115)
	container:AddChild(heroWrapper)

	local heroFrame = self:TrackContentFrame(CreateFrame("Frame", nil, heroWrapper.frame, "BackdropTemplate"))
	heroFrame:SetAllPoints()
	heroFrame:SetBackdrop({
		bgFile = "Interface\\AddOns\\Cerebro\\Media\\sandbox_frame_hybrid",
		edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
		edgeSize = 12,
		insets = { left = 3, right = 3, top = 3, bottom = 3 }
	})
	heroFrame:SetBackdropColor(1, 1, 1, 0.95)
	heroFrame:SetBackdropBorderColor(0.3, 0.3, 0.3, 1)

	-- Portrait dimensions
	local PORTRAIT_SIZE = 95
	local PORTRAIT_PADDING = 8

	-- 3D Character Portrait (Far Left with Border)
	local portraitFrame = self:TrackContentFrame(CreateFrame("Frame", nil, heroFrame, "BackdropTemplate"))
	portraitFrame:SetSize(PORTRAIT_SIZE + 6, PORTRAIT_SIZE + 6)  -- +6 for border padding
	portraitFrame:SetPoint("LEFT", PORTRAIT_PADDING, 0)
	portraitFrame:SetBackdrop({
		bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
		edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
		edgeSize = 10,
		insets = { left = 2, right = 2, top = 2, bottom = 2 }
	})
	portraitFrame:SetBackdropColor(0.05, 0.05, 0.05, 1)
	portraitFrame:SetBackdropBorderColor(0.4, 0.4, 0.4, 1)

	local model = self:TrackContentFrame(CreateFrame("PlayerModel", nil, portraitFrame))
	model:SetSize(PORTRAIT_SIZE - 4, PORTRAIT_SIZE - 4)
	model:SetPoint("CENTER", 0, 0)
	model:SetUnit("player")
	model:SetPortraitZoom(0.9)
	model:SetCamDistanceScale(0.8)

	-- Calculate content area (right of portrait, centered in remaining space)
	-- Full width = heroFrame width, portrait takes PORTRAIT_SIZE + PORTRAIT_PADDING*2
	-- Content area starts after portrait and centers in remaining space
	local contentAreaStart = PORTRAIT_SIZE + PORTRAIT_PADDING * 2 + 10  -- 10 = gap after portrait frame

	-- Content block width: EP(70) + div(20) + GP(70) + eq(20) + PR(80) = ~260
	-- Plus readiness bar = 260
	local CONTENT_WIDTH = 280

	-- Create a content container to hold everything (for centering)
	local contentFrame = self:TrackContentFrame(CreateFrame("Frame", nil, heroFrame))
	contentFrame:SetPoint("LEFT", contentAreaStart, 0)
	contentFrame:SetPoint("RIGHT", -10, 0)
	contentFrame:SetPoint("TOP", 0, 0)
	contentFrame:SetPoint("BOTTOM", 0, 0)

	-- Player Name/Rank/Badge - SINGLE LINE at top (centered in content area)
	local nameStr = UnitName("player") or "Player"
	local _, guildRank = GetGuildInfo("player")
	guildRank = guildRank or "No Guild"

	local headerLine = Cerebro:GetClassColorString(nameStr) .. nameStr .. "|r"
	headerLine = headerLine .. " |cff888888·|r " .. guildRank
	if Cerebro:IsOfficer() then
		headerLine = headerLine .. " |cff888888·|r |cffFFD700[Officer]|r"
	end

	local nameFS = contentFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
	nameFS:SetPoint("TOP", 0, -8)
	nameFS:SetText(headerLine)

	-- Stats Block - EP ÷ GP = PR equation (centered)
	-- Tooltip definitions (same as classic UI)
	local tooltipEP = "Effort Points\n\nEarned by raiding, killing bosses,\nand completing Mythic+ dungeons.\n\n|cff00ff00Higher EP = more contribution|r"
	local tooltipGP = "Gear Points\n\nIncreases when you receive loot.\n\n|cffff8800Higher GP = more gear received|r"
	local tooltipPR = "Priority Rating\n\nCalculated as EP ÷ GP.\n\n|cffFFD700Higher PR = higher loot priority|r"

	-- Create tiles anchored to center
	-- EP Tile (anchor point for the row)
	local tileEP = self:CreateDemoTile(contentFrame, "EP", tostring(ep), {1, 1, 1}, false, tooltipEP)

	-- Division Symbol
	local divSymbol = contentFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
	divSymbol:SetPoint("LEFT", tileEP, "RIGHT", 6, 0)
	divSymbol:SetText("|cffFFD700÷|r")

	-- GP Tile
	local tileGP = self:CreateDemoTile(contentFrame, "GP", tostring(gp), {0.5, 0.5, 0.5}, false, tooltipGP)
	tileGP:SetPoint("LEFT", divSymbol, "RIGHT", 6, 0)

	-- Equals Symbol
	local eqSymbol = contentFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
	eqSymbol:SetPoint("LEFT", tileGP, "RIGHT", 6, 0)
	eqSymbol:SetText("|cffFFD700=|r")

	-- PR Tile (Emphasized)
	local tilePR = self:CreateDemoTile(contentFrame, "PR", string.format("%.2f", pr), {1, 0.82, 0}, true, tooltipPR)
	tilePR:SetPoint("LEFT", eqSymbol, "RIGHT", 6, 0)

	-- PR Rank display (right of PR tile)
	-- Huge "Rank" label
	local rankLabel = contentFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
	rankLabel:SetPoint("TOPLEFT", tilePR, "TOPRIGHT", 15, -2)
	rankLabel:SetText("|cffFFD700Rank|r")

	-- Massive Rank Number (1.5x Huge)
	local rankValue = contentFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
	rankValue:SetPoint("TOP", rankLabel, "BOTTOM", 0, -4)
	rankValue:SetText("|cffFFD700" .. prRank .. "|r")

	-- Force larger size (32pt)
	local fontPath = GameFontNormalHuge:GetFont()
	rankValue:SetFont(fontPath, 32, "OUTLINE")

	-- Calculate total equation width and center it
	-- EP(70) + gap(6) + div(20) + gap(6) + GP(70) + gap(6) + eq(20) + gap(6) + PR(80) = 284
	local EQUATION_WIDTH = 284
	tileEP:SetPoint("TOP", -EQUATION_WIDTH/2 + 35, -28)  -- Center the row, offset for tile center

	-- Readiness Bar (below equation, centered)
	local epgp = Cerebro:GetModule("EPGP", true)
	local readyCur = epgp and epgp:GetReadiness(myName) or 0
	local readyCap = (Cerebro.db.global.config and Cerebro.db.global.config.epgp and Cerebro.db.global.config.epgp.readinessCap) or 1000
	local readyPct = (readyCap > 0) and math.min(readyCur / readyCap, 1.0) or 0

	local bar = self:TrackContentFrame(CreateFrame("StatusBar", nil, contentFrame, "BackdropTemplate"))
	bar:SetSize(EQUATION_WIDTH, 20)
	bar:SetPoint("TOP", tileEP, "BOTTOM", EQUATION_WIDTH/2 - 35, -6)  -- Center under equation
	bar:SetStatusBarTexture("Interface\\TargetingFrame\\UI-StatusBar")
	bar:SetStatusBarColor(0.2, 0.8, 0.2)
	bar:SetMinMaxValues(0, 1)
	bar:SetValue(readyPct)

	local barBg = bar:CreateTexture(nil, "BACKGROUND")
	barBg:SetAllPoints()
	barBg:SetColorTexture(0.1, 0.1, 0.1, 0.8)

	bar:SetBackdrop({edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", edgeSize = 8})
	bar:SetBackdropBorderColor(0.4, 0.33, 0.1, 1)

	local barText = bar:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	barText:SetPoint("CENTER")
	barText:SetText(string.format("Readiness: %d%% (%d/%d)", readyPct * 100, readyCur, readyCap))

	-- Readiness bar tooltip
	bar:EnableMouse(true)
	bar:SetScript("OnEnter", function(self)
		GameTooltip:SetOwner(self, "ANCHOR_TOP")
		GameTooltip:AddLine("Readiness", 1, 0.82, 0)
		GameTooltip:AddLine(" ")
		GameTooltip:AddLine("EP earned from Mythic+ and other", 1, 1, 1, true)
		GameTooltip:AddLine("activities outside of raid.", 1, 1, 1, true)
		GameTooltip:AddLine(" ")
		GameTooltip:AddLine("|cffff8800Resets weekly.|r", 1, 1, 1, true)
		GameTooltip:AddLine(" ")
		GameTooltip:AddDoubleLine("Current:", readyCur, 1, 1, 1, 0.2, 1, 0.2)
		GameTooltip:AddDoubleLine("Cap:", readyCap, 1, 1, 1, 1, 0.82, 0)
		GameTooltip:Show()
	end)
	bar:SetScript("OnLeave", function()
		GameTooltip:Hide()
	end)

	-- ============================================
	-- M+ HISTORY SECTION (Exact MyProgress.lua pattern)
	-- ============================================

	-- Determine how many runs to show
	local runLimit = (self.showAllRuns and totalRuns > 5) and 100 or 5
	local history = MPlus and MPlus:GetHistory(runLimit, true) or {}
	local needScroll = self.showAllRuns and #history > 5

	-- Main group (exactly like MyProgress.lua)
	local group = AceGUI:Create("InlineGroup")
	group:SetTitle("Recent Mythic+ Runs" .. (totalRuns > 5 and "  |cffFFD700[Click to " .. (self.showAllRuns and "collapse" or "expand") .. "]|r" or ""))
	group:SetFullWidth(true)
	if needScroll then
		group:SetHeight(250)  -- Explicit height for scroll mode (nested scroll fix)
		group:SetLayout("Fill")
	else
		group:SetLayout("List")
	end
	container:AddChild(group)

	-- Make the group title clickable to toggle show all
	if totalRuns > 5 then
		group.frame:EnableMouse(true)
		group.frame:SetScript("OnMouseUp", function()
			self.showAllRuns = not self.showAllRuns
			self:SelectTab("progress")
		end)
	end

	-- Choose container for rows: scroll or direct
	local rowContainer
	if needScroll then
		local scroll = AceGUI:Create("ScrollFrame")
		scroll:SetLayout("Flow")
		scroll:SetFullWidth(true)
		scroll:SetFullHeight(true)
		group:AddChild(scroll)
		rowContainer = scroll
	else
		rowContainer = group
	end

	-- Column header row
	self:CreateMPlusRow(rowContainer, nil, true, false)

	if #history == 0 then
		local noRuns = AceGUI:Create("Label")
		noRuns:SetText("|cff888888No runs recorded yet. Complete a dungeon to see history.|r")
		noRuns:SetFullWidth(true)
		rowContainer:AddChild(noRuns)
	else
		-- Render runs
		for i, run in ipairs(history) do
			self:CreateMPlusRow(rowContainer, run, false, (i % 2 == 0))
		end
	end
end

-- M+ Row rendering (adapted from MyProgress:CreateRowFrame)
function UISandbox:CreateMPlusRow(container, run, isHeader, isStripe)
	local ROW_HEIGHT = 32  -- Reduced from 40 to fit more rows

	-- AceGUI Wrapper to reserve space in the layout
	local wrapper = AceGUI:Create("SimpleGroup")
	wrapper:SetLayout("Fill")
	wrapper:SetFullWidth(true)
	wrapper:SetHeight(isHeader and 20 or ROW_HEIGHT)
	container:AddChild(wrapper)

	-- Native Frame (tracked for cleanup)
	local f = self:TrackContentFrame(CreateFrame("Frame", nil, wrapper.frame, "BackdropTemplate"))
	f:SetAllPoints()

	-- Background Stripe
	if isStripe and not isHeader then
		local bg = f:CreateTexture(nil, "BACKGROUND")
		bg:SetAllPoints()
		bg:SetColorTexture(1, 1, 1, 0.05)
	end

	if isHeader then
		-- Header Row
		local fsDung = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
		fsDung:SetPoint("LEFT", 10, 0)
		fsDung:SetText("|cffFFD700Level / Dungeon|r")

		local fsGrp = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
		fsGrp:SetPoint("LEFT", 145, 0)  -- Moved left from 180
		fsGrp:SetText("|cffFFD700Party|r")

		local fsRes = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
		fsRes:SetPoint("RIGHT", -10, 0)
		fsRes:SetText("|cffFFD700Result|r")
		return
	end

	-- == DATA ROW ==

	-- A. Level Badge
	local level = run.level or 0
	local levelColor = "|cffFFFFFF"
	if level >= 20 then levelColor = "|cffFF8000" -- Orange
	elseif level >= 15 then levelColor = "|cffA335EE" -- Purple
	elseif level >= 10 then levelColor = "|cff0070DD" -- Blue
	end

	local lvlFS = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")  -- Smaller font
	lvlFS:SetPoint("LEFT", 10, 0)
	lvlFS:SetText(levelColor .. "+" .. level .. "|r")

	-- B. Dungeon Name (with fallback for simulated runs)
	local dungeonNames = {
		[2660] = "Ara-Kara",
		[2662] = "The Dawnbreaker",
		[2651] = "The Stonevault",
		[2649] = "Priory",
		[2669] = "Floodgate",
		[2773] = "Eco-Dome",
		[2287] = "Halls of Atonement",
		[2441] = "Tazavesh: Streets",
		[375] = "Mists",
		[376] = "Necrotic Wake",
		[377] = "De Other Side",
		[378] = "Halls of Atonement",
		[379] = "Plaguefall",
	}

	local mapName = nil
	if run.mapID and run.mapID > 0 then
		if run.mapName and run.mapName ~= "" then
			mapName = run.mapName
		end
		if not mapName or mapName == "" then
			mapName = dungeonNames[run.mapID]
		end
		if not mapName or mapName == "" then
			mapName = C_ChallengeMode.GetMapUIInfo(run.mapID)
		end
	end
	mapName = mapName or "Unknown"

	local nameFS = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")  -- Smaller font
	nameFS:SetPoint("LEFT", lvlFS, "RIGHT", 6, 0)
	nameFS:SetWidth(80)  -- Reduced from 100
	nameFS:SetText(mapName)
	nameFS:SetJustifyH("LEFT")
	nameFS:SetWordWrap(false)

	-- C. Party Icons
	local startX = 145  -- Moved left from 180
	local iconSize = 20  -- Reduced from 22

	-- Sort group: Tank > Healer > Damage
	local roleOrder = { TANK = 1, HEALER = 2, HEALS = 2, DAMAGER = 3, DPS = 3, DMG = 3 }
	local sortedGroup = {}
	for _, m in ipairs(run.group or {}) do table.insert(sortedGroup, m) end
	table.sort(sortedGroup, function(a, b)
		return (roleOrder[a.role] or 4) < (roleOrder[b.role] or 4)
	end)

	for i, member in ipairs(sortedGroup) do
		local iframe = self:TrackContentFrame(CreateFrame("Frame", nil, f))
		iframe:SetSize(iconSize, iconSize)
		iframe:SetPoint("LEFT", startX + ((i - 1) * (iconSize + 3)), 0)

		-- Background circle with class color
		local bgCircle = iframe:CreateTexture(nil, "BACKGROUND")
		bgCircle:SetAllPoints()
		bgCircle:SetTexture("Interface\\CharacterFrame\\TempPortraitAlphaMask")

		local classKey = string.upper(member.class or "PRIEST")
		local cc = RAID_CLASS_COLORS and RAID_CLASS_COLORS[classKey]
		if cc then
			bgCircle:SetVertexColor(cc.r, cc.g, cc.b, 1)
		else
			bgCircle:SetVertexColor(0.5, 0.5, 0.5, 1)
		end

		-- Role icon overlay
		local roleIcon = iframe:CreateTexture(nil, "ARTWORK")
		roleIcon:SetSize(13, 13)
		roleIcon:SetPoint("CENTER")

		local role = member.role
		if role == "TANK" then
			roleIcon:SetAtlas("roleicon-tiny-tank")
		elseif role == "HEALER" or role == "HEALS" then
			roleIcon:SetAtlas("roleicon-tiny-healer")
		else
			roleIcon:SetAtlas("roleicon-tiny-dps")
		end

		-- Tooltip (with role normalization matching MyProgress.lua)
		iframe:EnableMouse(true)
		iframe:SetScript("OnEnter", function(self)
			GameTooltip:SetOwner(self, "ANCHOR_TOP")
			local colorStr = member.class and RAID_CLASS_COLORS and RAID_CLASS_COLORS[string.upper(member.class)]
				and "|c" .. RAID_CLASS_COLORS[string.upper(member.class)].colorStr or "|cffFFFFFF"
			GameTooltip:AddLine(colorStr .. (member.name or "Unknown") .. "|r")

			-- Role normalization (exact match with MyProgress.lua)
			local roleDisplay = member.role or "DPS"
			if roleDisplay == "DAMAGER" or roleDisplay == "DMG" then roleDisplay = "DPS" end
			if roleDisplay == "HEALER" then roleDisplay = "HEALS" end

			GameTooltip:AddLine(roleDisplay, 1, 1, 1)
			if member.mplusRating then
				GameTooltip:AddLine("M+ Rating: " .. member.mplusRating, 0.5, 0.5, 0.5)
			end
			GameTooltip:Show()
		end)
		iframe:SetScript("OnLeave", function() GameTooltip:Hide() end)
	end

	-- D. Result (Right Aligned) - EP Award only, no status icon (time +upgrade shows completion)
	local epBtn = self:TrackContentFrame(CreateFrame("Button", nil, f))
	epBtn:SetSize(80, 20)
	epBtn:SetPoint("RIGHT", -5, 0)  -- Pushed further right

	local epFS = epBtn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
	epFS:SetAllPoints()
	epFS:SetText("|cff00ff00+" .. (run.totalEP or 0) .. " EP|r")

	-- EP Breakdown Tooltip (exact match with MyProgress.lua)
	epBtn:SetScript("OnEnter", function(self)
		GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
		GameTooltip:AddLine("EP Breakdown", 1, 1, 1)
		GameTooltip:AddLine(" ")
		GameTooltip:AddDoubleLine("Base Reward:", run.baseEP or 0, 1, 1, 1, 1, 1, 1)
		GameTooltip:AddDoubleLine("Keystone Level (+" .. (run.level or 0) .. "):", run.levelEP or 0, 1, 1, 1, 0.2, 1, 0.2)
		GameTooltip:AddDoubleLine("Time/Guild Bonus:", run.bonusEP or 0, 1, 1, 1, 1, 0.82, 0)
		GameTooltip:AddLine(" ")
		GameTooltip:AddDoubleLine("Total:", (run.totalEP or 0) .. " EP", 1, 1, 1, 0.2, 1, 0.2)
		GameTooltip:AddLine(" ")
		GameTooltip:AddDoubleLine("Status:", run.status or "Pending", 0.5, 0.5, 0.5, 0.5, 0.5, 0.5)
		GameTooltip:Show()
	end)
	epBtn:SetScript("OnLeave", function() GameTooltip:Hide() end)

	-- Time
	local mins = math.floor((run.duration or 0) / 60)
	local secs = (run.duration or 0) % 60
	local timeStr = string.format("%d:%02d", mins, secs)
	if run.upgrade and run.upgrade > 0 then
		timeStr = timeStr .. " (+" .. run.upgrade .. ")"
	end

	local timeFS = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	timeFS:SetPoint("RIGHT", epFS, "LEFT", -10, 0)
	timeFS:SetText(timeStr)
end
