-- KiraUI-Plugin_TargetedSpells.lua
-- Tweaks for the standalone "Targeted Spells" addon. Currently one
-- tweak: flip the cast swipe on the icons so a cast STARTS fully colored and
-- darkens toward its end (the Cooldown frame's reverse mode) instead of the
-- default dark-start that clears to color.

local addonName, ns = ...

local DEFAULTS = { reverse = true }

local function GetCfg() return ns.ModuleCfg('targetedSpells', DEFAULTS) end
ns.TSGetCfg = GetCfg

-- Every icon we've seen. Pooled frames are reused, never destroyed, so this
-- registry lets an options toggle re-style icons that are already on screen.
local icons = setmetatable({}, { __mode = 'k' })

local function ApplyOne(f)
	if f.Cooldown and f.Cooldown.SetReverse then
		f.Cooldown:SetReverse(GetCfg().reverse and true or false)
	end
end

local function ApplyAll()
	for f in pairs(icons) do ApplyOne(f) end
end
ns.TSApply = ApplyAll

-- Both the self and the party icons come from one frame pool built on
-- TargetedSpellsFrameTemplate, whose mixin is the GLOBAL
-- TargetedSpellsIconMixin. Pool frames copy the mixin methods at creation,
-- so hooking the mixin BEFORE any icon exists bakes our wrapper into every
-- icon. PostCreate runs on each (re)display, so the reverse flag also
-- reaches frames the moment they are reused from the pool.
local function HookMixin()
	local M = _G.TargetedSpellsIconMixin
	if not M then return false end
	if M.__kiraTSHooked then return true end
	M.__kiraTSHooked = true
	hooksecurefunc(M, 'PostCreate', function(self)
		icons[self] = true
		ApplyOne(self)
	end)
	return true
end

-- TargetedSpells is in our OptionalDeps, so normally it loads first and the
-- mixin exists here; the ADDON_LOADED path covers any other load order.
if HookMixin() then
	ns.hasTargetedSpells = true
else
	local f = CreateFrame('Frame')
	f:RegisterEvent('ADDON_LOADED')
	f:SetScript('OnEvent', function(self, _, name)
		if name == 'TargetedSpells' then
			ns.hasTargetedSpells = true
			HookMixin()
			self:UnregisterEvent('ADDON_LOADED')
		end
	end)
end
