-- Core connections

Connections = {};

function ClearConnections()
	-- Clears and disconnects temporary connections
	for Index, Connection in pairs(Connections) do
		Connection:Disconnect();
		Connections[Index] = nil;
	end;
end;

function InitializeUI()
	-- Sets up the UI

	-- Ensure UI has not yet been initialized
	if UI then
		return;
	end;

	-- Create the root UI
	UI = Instance.new('ScreenGui')
	UI.Name = 'Building Tools by F3X (UI)'

	-- Set up dock
	Dock = Cheer(Tool.Interfaces.Dock, UI).Start(getfenv(0));

	-- Clean up UI on tool teardown
	UIMaid = Maid.new()
	Tool.AncestryChanged:Connect(function (Item, Parent)
		if Parent == nil then
			UIMaid:Destroy()
		end
	end)

	-- Register explorer button on dock
	ExplorerDockButton = Dock.AddSelectionButton(Assets.ExplorerDockIcon, 'EXPLORER\n(Shift + H)')
	ExplorerDockButton.Activated:Connect(ToggleExplorer)
	ExplorerDockButton.ImageTransparency = 0.66

end;

local UIElements = Tool:WaitForChild 'UI'
local ExplorerTemplate = require(UIElements:WaitForChild 'Explorer')

function ToggleExplorer()
	if not ExplorerVisible then
		OpenExplorer()
	else
		CloseExplorer()
	end
end

function OpenExplorer()

	-- Ensure explorer not already open
	if ExplorerHandle then
		return
	end

	-- Initialize explorer
	Explorer = Roact.createElement(ExplorerTemplate, {
		Core = getfenv(0),
		Close = CloseExplorer,
		Scope = Targeting.Scope
	})

	-- Mount explorer
	ExplorerHandle = Roact.mount(Explorer, UI, 'Explorer')
	ExplorerVisible = true

	-- Unmount explorer on tool cleanup
	UIMaid.Explorer = Support.Call(Roact.unmount, ExplorerHandle)
	UIMaid.ExplorerScope = Targeting.ScopeChanged:Connect(function (Scope)
		local UpdatedProps = Support.Merge({}, Explorer.props, { Scope = Scope })
		local UpdatedExplorer = Roact.createElement(ExplorerTemplate, UpdatedProps)
		ExplorerHandle = Roact.update(ExplorerHandle, UpdatedExplorer)
	end)

	-- Update dock
	ExplorerDockButton.ImageTransparency = 0

end

function CloseExplorer()

	-- Clean up explorer
	UIMaid.Explorer = nil
	UIMaid.ExplorerScope = nil
	ExplorerHandle = nil
	ExplorerVisible = nil

	-- Update dock
	ExplorerDockButton.ImageTransparency = 0.66

end
