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

local Loader = {}
SlickUI.MissionLoader = Loader

function Loader:Load(followerTypeID, showPlanner)
	if not C_AddOns.IsAddOnLoaded("SlickUI_GarrisonMissions") then
		local loaded, reason = C_AddOns.LoadAddOn("SlickUI_GarrisonMissions")
		if not loaded and reason and reason ~= "ALREADY_LOADED" then
			SlickUI:Print("Garrison & Shipyard planner could not load: " .. tostring(reason))
			return false
		end
	end
	if SlickUI.GarrisonMissions then
		SlickUI.GarrisonMissions:SetFollowerType(followerTypeID)
		if showPlanner then SlickUI.GarrisonMissions:Show() end
		return true
	end
	return false
end

local function HookShipyardFrame()
	local shipyard = _G.GarrisonShipyardFrame
	if not shipyard or shipyard.SlickUIMissionLoaderHooked then return end
	shipyard.SlickUIMissionLoaderHooked = true
	shipyard:HookScript("OnShow", function(frame)
		Loader:Load(frame.followerTypeID or 2, false)
	end)
	if shipyard:IsShown() then Loader:Load(shipyard.followerTypeID or 2, false) end
end

local events = CreateFrame("Frame")
events:RegisterEvent("GARRISON_MISSION_NPC_OPENED")
events:RegisterEvent("ADDON_LOADED")
events:SetScript("OnEvent", function(_, event, ...)
	if event == "GARRISON_MISSION_NPC_OPENED" then
		local followerTypeID = ...
		if followerTypeID == 1 or followerTypeID == 2 then Loader:Load(followerTypeID, false) end
	elseif event == "ADDON_LOADED" and ... == "Blizzard_GarrisonUI" then
		HookShipyardFrame()
	end
end)
C_Timer.After(0, HookShipyardFrame)

SLASH_SLICKUIGARRISONMISSIONS1 = "/slickmissions"
SLASH_SLICKUIGARRISONMISSIONS2 = "/smissions"
SlashCmdList.SLICKUIGARRISONMISSIONS = function()
	Loader:Load(nil, true)
end
