--core/context.lua, decides WHEN the FPS reductions should be active (backend).
--the reductions no longer apply immediately; they apply while any of the player's chosen
--conditions is true (in a dungeon / in a raid / during an encounter / always). this module
--evaluates that gate and re-applies the profile whenever the condition can change (zoning in
--or out of an instance -- encounter start/end is handled by core/encounter.lua, which also
--re-applies).

local _ = nil
local addonName, private = ...

private.Core = private.Core or {}

---@class FPSPP_Context
local Context = {}
private.Core.Context = Context

--frame used only to receive the zone/instance-change events.
local eventFrame = CreateFrame("Frame")

--true when the reductions should currently be active: any checked condition is met. "always"
--wins outright; otherwise it depends on the instance type and the encounter state.
---@return boolean
function Context:IsActive()
	local context = private.Core.Profile:Get().context
	if context.always == true then
		return true
	end

	--the instance type is IsInInstance()'s 2nd return; "party" is a 5-player dungeon.
	local instanceType = select(2, IsInInstance())
	local inEncounter = private.Core.Encounter:IsActive()

	if context.in_dungeon == true and instanceType == "party" then
		return true
	end

	if context.in_dungeon_encounter == true and instanceType == "party" and inEncounter then
		return true
	end

	if context.in_raid == true and instanceType == "raid" then
		return true
	end

	if context.in_raid_encounter == true and instanceType == "raid" and inEncounter then
		return true
	end

	return false
end

--registers the zone/instance-change events; each re-applies the profile so the reductions
--turn on/off as the player enters or leaves a matching context. called once from OnInit.
function Context:Initialize()
	eventFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
	eventFrame:RegisterEvent("ZONE_CHANGED_NEW_AREA")
	--keep the handler short: re-apply the profile against the new context.
	eventFrame:SetScript("OnEvent", function()
		private.Core.Optimizer:ApplyProfile()
	end)
end
