local _, _ns = ...
local AC = _G.ArenaCore
if not AC then return end

-- =============================================================================
-- Core/TalentReminder.lua - Talent Reminder overlay for arena/BG prep rooms
-- because forgetting to swap talents before gates open is a feelsbad moment
-- =============================================================================

local TR = {}
AC.TalentReminder = TR

local frame = nil
local eventFrame = nil
local bgHideTimer = nil
local rosterUpdateTimer = nil
local dismissed = false

------------------------------------------------------------------------
-- helpers
------------------------------------------------------------------------
local function GetDB()
    if not AC.DB or not AC.DB.profile then
        return { enabled = true }
    end
    AC.DB.profile.talentReminder = AC.DB.profile.talentReminder or {}
    local db = AC.DB.profile.talentReminder
    if db.enabled == nil then db.enabled = true end
    return db
end

local function IsInPvPInstance()
    local _, instanceType = IsInInstance()
    return instanceType == "arena" or instanceType == "pvp"
end

local function IsArenaPrep()
    -- Prep room: arena opponent specs are available but match hasn't started yet
    local numSpecs = GetNumArenaOpponentSpecs and GetNumArenaOpponentSpecs() or 0
    local numOpps = GetNumArenaOpponents and GetNumArenaOpponents() or 0
    return numSpecs > 0 and numOpps == 0
end

local function IsBattlegroundStarting()
    local _, instanceType = IsInInstance()
    if instanceType ~= "pvp" then return false end
    -- Not an arena
    local isArena = IsActiveBattlefieldArena and IsActiveBattlefieldArena()
    if isArena then return false end
    -- BG is in starting phase if match hasn't been going long
    -- C_PvP.GetActiveMatchDuration returns seconds since match start, 0 during prep
    local duration = 0
    if C_PvP and C_PvP.GetActiveMatchDuration then
        duration = C_PvP.GetActiveMatchDuration() or 0
    end
    return duration < 5
end

------------------------------------------------------------------------
-- frame creation
------------------------------------------------------------------------
local function CreateReminderFrame()
    if frame then return frame end

    local f = CreateFrame("Frame", "ArenaCoreTalentReminder", UIParent)
    f:SetSize(360, 110)
    f:SetPoint("TOP", UIParent, "TOP", 0, -180)
    f:SetFrameStrata("HIGH")
    f:SetFrameLevel(200)
    f:Hide()
    f:EnableMouse(true)

    -- ===================================================================
    -- BACKDROP - very dark with subtle green tint
    -- ===================================================================
    local bg = f:CreateTexture(nil, "BACKGROUND")
    bg:SetAllPoints()
    bg:SetColorTexture(0.01, 0.03, 0.01, 0.96)
    f.bg = bg

    -- ===================================================================
    -- SCAN LINES - horizontal subtle stripes for that CRT / alert vibe
    -- ===================================================================
    local scanGroup = CreateFrame("Frame", nil, f)
    scanGroup:SetAllPoints()
    local spacing = 6
    local maxLines = math.floor(f:GetHeight() / spacing)
    for i = 1, maxLines do
        local line = scanGroup:CreateTexture(nil, "BORDER", nil, -1)
        line:SetHeight(1)
        line:SetColorTexture(0, 0, 0, 0.25)
        line:SetPoint("TOPLEFT", scanGroup, "TOPLEFT", 2, -(i * spacing))
        line:SetPoint("TOPRIGHT", scanGroup, "TOPRIGHT", -2, -(i * spacing))
    end
    f.scanGroup = scanGroup

    -- ===================================================================
    -- OUTER EMERALD BORDER (2px)
    -- ===================================================================
    local borderOuter = f:CreateTexture(nil, "BORDER")
    borderOuter:SetPoint("TOPLEFT", f, "TOPLEFT", 0, 0)
    borderOuter:SetPoint("TOPRIGHT", f, "TOPRIGHT", 0, 0)
    borderOuter:SetHeight(2)
    borderOuter:SetColorTexture(0.05, 0.75, 0.05, 1)
    f.borderTop = borderOuter

    local borderBot = f:CreateTexture(nil, "BORDER")
    borderBot:SetPoint("BOTTOMLEFT", f, "BOTTOMLEFT", 0, 0)
    borderBot:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", 0, 0)
    borderBot:SetHeight(2)
    borderBot:SetColorTexture(0.05, 0.75, 0.05, 1)
    f.borderBot = borderBot

    local borderLeft = f:CreateTexture(nil, "BORDER")
    borderLeft:SetPoint("TOPLEFT", f, "TOPLEFT", 0, -2)
    borderLeft:SetPoint("BOTTOMLEFT", f, "BOTTOMLEFT", 0, 2)
    borderLeft:SetWidth(2)
    borderLeft:SetColorTexture(0.05, 0.75, 0.05, 1)
    f.borderLeft = borderLeft

    local borderRight = f:CreateTexture(nil, "BORDER")
    borderRight:SetPoint("TOPRIGHT", f, "TOPRIGHT", 0, -2)
    borderRight:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", 0, 2)
    borderRight:SetWidth(2)
    borderRight:SetColorTexture(0.05, 0.75, 0.05, 1)
    f.borderRight = borderRight

    -- ===================================================================
    -- INNER GLOW / ACCENT
    -- ===================================================================
    local innerGlow = f:CreateTexture(nil, "BACKGROUND", nil, 1)
    innerGlow:SetPoint("TOPLEFT", f, "TOPLEFT", 4, -4)
    innerGlow:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", -4, 4)
    innerGlow:SetColorTexture(0.02, 0.15, 0.02, 0.15)
    f.innerGlow = innerGlow

    -- ===================================================================
    -- TITLE - bold emerald green
    -- ===================================================================
    local title = f:CreateFontString(nil, "OVERLAY")
    title:SetPoint("TOP", f, "TOP", 0, -12)
    title:SetJustifyH("CENTER")
    title:SetTextColor(0.15, 1, 0.15, 1)
    if title.SetFont then
        title:SetFont(AC.FONT_PATH or "Interface\\AddOns\\ArenaCore\\Media\\Fonts\\arenacore.ttf", 16, "OUTLINE")
    end
    title:SetText("TALENT REMINDER")
    f.title = title

    -- ===================================================================
    -- BODY TEXT
    -- ===================================================================
    local body = f:CreateFontString(nil, "OVERLAY")
    body:SetPoint("TOP", title, "BOTTOM", 0, -6)
    body:SetWidth(340)
    body:SetJustifyH("CENTER")
    body:SetTextColor(0.95, 0.95, 0.95, 1)
    if body.SetFont then
        body:SetFont(AC.FONT_PATH or "Interface\\AddOns\\ArenaCore\\Media\\Fonts\\arenacore.ttf", 12, "OUTLINE")
    end
    body:SetText("Don't forget to check your talents before the match starts!")
    f.body = body

    -- ===================================================================
    -- DISMISS BUTTON
    -- ===================================================================
    local btn = CreateFrame("Button", nil, f)
    btn:SetSize(80, 22)
    btn:SetPoint("TOP", body, "BOTTOM", 0, -8)
    btn:EnableMouse(true)

    -- button bg
    local btnBg = btn:CreateTexture(nil, "BACKGROUND")
    btnBg:SetAllPoints()
    btnBg:SetColorTexture(0.01, 0.04, 0.01, 0.9)
    btn.bg = btnBg

    -- button border
    local btnBorder = btn:CreateTexture(nil, "BORDER")
    btnBorder:SetPoint("TOPLEFT", btn, "TOPLEFT", 0, 0)
    btnBorder:SetPoint("BOTTOMRIGHT", btn, "BOTTOMRIGHT", 0, 0)
    btnBorder:SetColorTexture(0.1, 0.7, 0.1, 1)
    btnBorder:SetHeight(1)
    btn.border = btnBorder

    local btnBorderB = btn:CreateTexture(nil, "BORDER")
    btnBorderB:SetPoint("BOTTOMLEFT", btn, "BOTTOMLEFT", 0, 0)
    btnBorderB:SetPoint("BOTTOMRIGHT", btn, "BOTTOMRIGHT", 0, 0)
    btnBorderB:SetHeight(1)
    btnBorderB:SetColorTexture(0.1, 0.7, 0.1, 1)

    local btnBorderL = btn:CreateTexture(nil, "BORDER")
    btnBorderL:SetPoint("TOPLEFT", btn, "TOPLEFT", 0, -1)
    btnBorderL:SetPoint("BOTTOMLEFT", btn, "BOTTOMLEFT", 0, 1)
    btnBorderL:SetWidth(1)
    btnBorderL:SetColorTexture(0.1, 0.7, 0.1, 1)

    local btnBorderR = btn:CreateTexture(nil, "BORDER")
    btnBorderR:SetPoint("TOPRIGHT", btn, "TOPRIGHT", 0, -1)
    btnBorderR:SetPoint("BOTTOMRIGHT", btn, "BOTTOMRIGHT", 0, 1)
    btnBorderR:SetWidth(1)
    btnBorderR:SetColorTexture(0.1, 0.7, 0.1, 1)

    -- button text
    local btnText = btn:CreateFontString(nil, "OVERLAY")
    btnText:SetAllPoints()
    btnText:SetJustifyH("CENTER")
    btnText:SetJustifyV("MIDDLE")
    btnText:SetTextColor(0.25, 1, 0.25, 1)
    if btnText.SetFont then
        btnText:SetFont(AC.FONT_PATH or "Interface\\AddOns\\ArenaCore\\Media\\Fonts\\arenacore.ttf", 11, "OUTLINE")
    end
    btnText:SetText("Dismiss")
    btn.text = btnText

    -- hover / click effects
    btn:SetScript("OnEnter", function(self)
        self.bg:SetColorTexture(0.02, 0.15, 0.02, 0.95)
        self.text:SetTextColor(0.5, 1, 0.5, 1)
    end)
    btn:SetScript("OnLeave", function(self)
        self.bg:SetColorTexture(0.01, 0.04, 0.01, 0.9)
        self.text:SetTextColor(0.25, 1, 0.25, 1)
    end)
    btn:SetScript("OnMouseDown", function(self)
        self.bg:SetColorTexture(0.04, 0.25, 0.04, 1)
    end)
    btn:SetScript("OnMouseUp", function(self)
        self.bg:SetColorTexture(0.02, 0.15, 0.02, 0.95)
    end)
    btn:SetScript("OnClick", function()
        dismissed = true
        f:Hide()
    end)

    f.dismissBtn = btn

    -- ===================================================================
    -- TOP EMERALD GLOW BAR (subtle pulse anchor)
    -- ===================================================================
    local topGlow = f:CreateTexture(nil, "ARTWORK", nil, -1)
    topGlow:SetPoint("TOPLEFT", f, "TOPLEFT", 2, -2)
    topGlow:SetPoint("TOPRIGHT", f, "TOPRIGHT", -2, -2)
    topGlow:SetHeight(1)
    topGlow:SetColorTexture(0.1, 1, 0.1, 0.6)
    f.topGlow = topGlow

    frame = f
    return f
end

------------------------------------------------------------------------
-- show / hide
------------------------------------------------------------------------
function TR:Show()
    local db = GetDB()
    if not db.enabled then return end
    if dismissed then return end
    if not frame then CreateReminderFrame() end
    if frame then frame:Show() end
end

function TR:Hide()
    if frame then frame:Hide() end
    if bgHideTimer then
        bgHideTimer:Cancel()
        bgHideTimer = nil
    end
    if rosterUpdateTimer then
        rosterUpdateTimer:Cancel()
        rosterUpdateTimer = nil
    end
end

function TR:Dismiss()
    dismissed = true
    if frame then frame:Hide() end
end

function TR:ResetDismiss()
    dismissed = false
end

function TR:IsShown()
    return frame and frame:IsShown()
end

------------------------------------------------------------------------
-- event handling
------------------------------------------------------------------------
local function OnEvent(self, event, ...)
    local db = GetDB()
    if not db.enabled then return end

    if event == "ARENA_PREP_OPPONENT_SPECIALIZATIONS" then
        dismissed = false
        TR:Show()

    elseif event == "ARENA_OPPONENT_UPDATE" then
        local unit, updateType = ...
        -- Only hide when opponent actually becomes visible (gates opened)
        if updateType == "seen" then
            TR:Hide()
        end

    elseif event == "GROUP_ROSTER_UPDATE" then
        -- Solo Shuffle round transition (also fires on initial arena entry)
        local _, instanceType = IsInInstance()
        if instanceType == "arena" then
            dismissed = false
            if rosterUpdateTimer then rosterUpdateTimer:Cancel() end
            rosterUpdateTimer = C_Timer.NewTimer(0.3, function()
                local _, it = IsInInstance()
                if it == "arena" then
                    TR:Show()
                end
            end)
        end

    elseif event == "PLAYER_ENTERING_WORLD" then
        local _, instanceType = IsInInstance()
        if instanceType == "arena" then
            -- If we're reloading in prep room, specs might already be available
            local numSpecs = GetNumArenaOpponentSpecs and GetNumArenaOpponentSpecs() or 0
            local numOpps = GetNumArenaOpponents and GetNumArenaOpponents() or 0
            if numSpecs > 0 and numOpps == 0 then
                dismissed = false
                TR:Show()
            else
                TR:Hide()
            end
        elseif instanceType == "pvp" then
            -- Entered a battleground
            local isArena = IsActiveBattlefieldArena and IsActiveBattlefieldArena()
            if not isArena then
                dismissed = false
                TR:Show()
                -- Safety net: auto-hide after 2 minutes if START_TIMER never fires
                if bgHideTimer then bgHideTimer:Cancel() end
                bgHideTimer = C_Timer.NewTimer(120, function()
                    TR:Hide()
                end)
            end
        else
            TR:Hide()
        end

    elseif event == "START_TIMER" then
        local timerType = ...
        if timerType == Enum.StartTimerType.PvPBeginTimer then
            TR:Hide()
        end
    end
end

------------------------------------------------------------------------
-- init
------------------------------------------------------------------------
local function InitEventFrame()
    if eventFrame then return end

    eventFrame = CreateFrame("Frame")
    eventFrame:RegisterEvent("ARENA_PREP_OPPONENT_SPECIALIZATIONS")
    eventFrame:RegisterEvent("ARENA_OPPONENT_UPDATE")
    eventFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
    eventFrame:RegisterEvent("GROUP_ROSTER_UPDATE")
    eventFrame:RegisterEvent("START_TIMER")
    eventFrame:SetScript("OnEvent", OnEvent)
end

function TR:Initialize()
    dismissed = false
    InitEventFrame()

    -- Check if we're already in a prep room on reload
    local _, instanceType = IsInInstance()
    if instanceType == "arena" then
        local numSpecs = GetNumArenaOpponentSpecs and GetNumArenaOpponentSpecs() or 0
        local numOpps = GetNumArenaOpponents and GetNumArenaOpponents() or 0
        if numSpecs > 0 and numOpps == 0 then
            TR:Show()
        end
    elseif instanceType == "pvp" then
        local isArena = IsActiveBattlefieldArena and IsActiveBattlefieldArena()
        if not isArena then
            TR:Show()
        end
    end
end

function TR:SetEnabled(enabled)
    enabled = (enabled == true)
    local db = GetDB()
    db.enabled = enabled

    if enabled then
        InitEventFrame()
    else
        TR:Hide()
    end
end
