local _, T = ...
local KR, EV = assert(T.Kindred:compatible(1,0), "Compatible version of Kindred required."), T.Evie

do -- zone:Zone/Sub Zone
	local function onZoneUpdate()
		local cz
		for i=1,4 do
			local z = (i == 1 and GetRealZoneText or i == 2 and GetSubZoneText or i == 3 and GetZoneText or GetMinimapZoneText)()
			if z and z ~= "" then
				cz = (cz and (cz .. "/") or "") .. z
			end
		end
		KR:SetStateConditionalValue("zone", cz or false)
	end
	onZoneUpdate()
	EV.RegisterEvent("ZONE_CHANGED", onZoneUpdate)
	EV.RegisterEvent("PLAYER_ENTERING_WORLD", onZoneUpdate)
end
do -- me:Player Name/Class
	local c, ce = UnitClass("player")
	KR:SetStateConditionalValue("me", UnitName("player") .. "/" .. c .. "/" .. ce:lower())
end
do -- known:spell id
	KR:SetSecureExecConditional("known", [=[-- KR_KnownSpell
		local ids = ...
		for sid in (type(ids) == "string" and ids or ""):gmatch("[^/]+") do
			local id = tonumber(sid:match("^%s*(%d+)%s*$"))
			if id and (FindSpellBookSlotBySpellID(id, true) or FindSpellBookSlotBySpellID(id, false)) then
				return true
			end
		end
		return false
	]=])
	local f = CreateFrame("FRAME")
	f:SetScript("OnUpdate", function(self)
		self:Hide()
		KR:PokeConditional("known")
	end)
	f:SetScript("OnEvent", f.Show)
	f:RegisterEvent("LEARNED_SPELL_IN_TAB")
	f:RegisterEvent("PLAYER_SPECIALIZATION_CHANGED")
	f:RegisterEvent("PLAYER_ENTERING_WORLD")
end
do -- spec:Spec Name
	local f = CreateFrame("FRAME", nil, nil, "SecureHandlerStateTemplate")
	f:SetFrameRef("KR", KR:seclib())
	f:Execute('KR, oldSpecGroup, oldSpecName = self:GetFrameRef("KR"), "", ""')
	f:SetAttribute("_onstate-spec", [=[-- onspecchange
		KR:RunAttribute("UpdateStateConditional", "spec", newstate, oldSpecGroup)
		oldSpecGroup = newstate
	]=])
	f:SetAttribute("_onstate-specname", [=[-- onspecchange
		KR:RunAttribute("UpdateStateConditional", "spec", newstate, oldSpecName)
		oldSpecName = newstate
	]=])
	RegisterStateDriver(f, "spec", "[spec:1] 1; [spec:2] 2")
	EV.RegisterEvent("PLAYER_LOGIN", function()
		local cnd, ns, sp, sl, sbest = nil, GetNumSpecializations(), {}, {}, {}
		local function pop(id, sid, lvl, ...)
			if sid then
				sp[sid], sl[sid] = sp[sid] == nil and id, lvl
				return pop(id, ...)
			end
		end
		for i=1,ns do
			pop(i, GetSpecializationSpells(i))
		end
		for sid, i in pairs(sp) do
			if i and (sbest[i] == nil or sl[sbest[i]] > sl[sid]) then
				sbest[i] = sid
			end
		end
		for i=1,ns do
			local id, name = GetSpecializationInfo(i)
			cnd = (cnd and (cnd .. "; ") or "") .. "[known:" .. sbest[i] .. "] " .. id .. "/" .. name
		end
		KR:RegisterStateDriver(f, "specname", cnd .. "; -1/unspec")
		return "remove"
	end)
end