-- ApiVault window stacking and strata manager. Added in v0.4.0.
-- UI-only helper. No protected/secure execution and no runtime source file reads.
local addonName, ApiVault = ...

ApiVault.WindowManager = ApiVault.WindowManager or {}
local Manager = ApiVault.WindowManager

Manager.windows = Manager.windows or {}
Manager.level = Manager.level or 100
Manager.defaultStrata = "FULLSCREEN_DIALOG"

function Manager:Register(frame, name)
	if not frame then
		return frame
	end
	name = name or frame:GetName() or "ApiVaultWindow"
	if not frame.ApiVaultWindowManaged then
		frame.ApiVaultWindowManaged = true
		frame.ApiVaultWindowName = name
		table.insert(self.windows, frame)
		if frame.SetClampedToScreen then
			frame:SetClampedToScreen(true)
		end
		if frame.SetToplevel then
			frame:SetToplevel(true)
		end
		if frame.SetFrameStrata then
			frame:SetFrameStrata(self.defaultStrata)
		end
		frame:HookScript("OnShow", function(selfFrame)
			ApiVault.WindowManager:Raise(selfFrame)
		end)
		frame:HookScript("OnMouseDown", function(selfFrame)
			ApiVault.WindowManager:Raise(selfFrame)
		end)
	end
	self:Raise(frame)
	return frame
end

function Manager:Raise(frame)
	if not frame then
		return
	end
	self.level = (self.level or 100) + 10
	if self.level > 9000 then
		self.level = 200
	end
	if frame.SetFrameStrata then
		frame:SetFrameStrata(self.defaultStrata)
	end
	if frame.SetFrameLevel then
		frame:SetFrameLevel(self.level)
	end
end

function Manager:CloseAllExcept(exceptFrame)
	for _, frame in ipairs(self.windows or {}) do
		if frame and frame ~= exceptFrame and frame:IsShown() then
			frame:Hide()
		end
	end
end

function ApiVault:PrepareWindow(frame, name)
	if self.WindowManager and self.WindowManager.Register then
		return self.WindowManager:Register(frame, name)
	end
	return frame
end

function ApiVault:RaiseWindow(frame)
	if self.WindowManager and self.WindowManager.Raise then
		self.WindowManager:Raise(frame)
	end
end

function ApiVault:CloseOtherWindows(frame)
	if self.WindowManager and self.WindowManager.CloseAllExcept then
		self.WindowManager:CloseAllExcept(frame)
	end
end
