local _, ns = ...
local SlickUI = ns.SlickUI

local Loader = {}
SlickUI.CraftingLoader = Loader

function Loader:Load()
	if SlickUI.DB and SlickUI.DB.crafting and SlickUI.DB.crafting.enabled == false then return false end
	if C_AddOns.IsAddOnLoaded("SlickUI_Crafting") then return true end
	local loaded, reason = C_AddOns.LoadAddOn("SlickUI_Crafting")
	if not loaded and reason and reason ~= "ALREADY_LOADED" then
		SlickUI:Print("Crafting planner could not load: " .. tostring(reason))
	end
	return loaded == true
end

function Loader:SetEnabled(enabled)
	SlickUI.DB.crafting.enabled = enabled == true
	if not enabled then
		local planner = SlickUI.CraftingPlanner
		if planner and planner.SetEnabled then planner:SetEnabled(false) end
		return
	end
	self:Load()
	local planner = SlickUI.CraftingPlanner
	if planner and planner.SetEnabled then planner:SetEnabled(true) end
end

local events = CreateFrame("Frame")
events:RegisterEvent("TRADE_SKILL_SHOW")
events:RegisterEvent("PLAYER_LOGIN")
events:RegisterEvent("AUCTION_HOUSE_SHOW")
events:RegisterEvent("MERCHANT_SHOW")
events:RegisterEvent("MERCHANT_CLOSED")
events:SetScript("OnEvent", function(_, event)
	if event == "PLAYER_LOGIN" then
		Loader:Load()
		return
	end
	if event == "MERCHANT_CLOSED" then
		local planner = SlickUI.CraftingPlanner
		if planner and planner.VendorPrompt then planner.VendorPrompt:Hide() end
		return
	end
	if SlickUI.DB.crafting.enabled == false then return end
	if event == "MERCHANT_SHOW" then
		Loader:Load()
		if C_AddOns.IsAddOnLoaded("SlickUI_Crafting") and SlickUI.CraftingPlanner then
			SlickUI.CraftingPlanner:HandleMerchant()
		end
		return
	end
	Loader:Load()
end)
