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

local Loader = {}
SlickUI.CraftingLoader = Loader

function Loader:Load()
	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

local events = CreateFrame("Frame")
events:RegisterEvent("TRADE_SKILL_SHOW")
events:RegisterEvent("AUCTION_HOUSE_SHOW")
events:RegisterEvent("MERCHANT_SHOW")
events:SetScript("OnEvent", function(_, event)
	if event == "MERCHANT_SHOW" then
		SlickUI.DB.crafting.vendorItems = SlickUI.DB.crafting.vendorItems or {}
		for index = 1, (GetMerchantNumItems() or 0) do
			local itemID = GetMerchantItemID(index)
			if itemID then SlickUI.DB.crafting.vendorItems[itemID] = true end
		end
		local hasShopping = SlickUI.DB.crafting.shoppingList and #SlickUI.DB.crafting.shoppingList > 0
		if hasShopping then Loader:Load() end
		if C_AddOns.IsAddOnLoaded("SlickUI_Crafting") and SlickUI.CraftingPlanner then
			SlickUI.CraftingPlanner:HandleMerchant()
		end
		return
	end
	Loader:Load()
end)
