-- Enable tool or plugin

if Mode == 'Plugin' then

	-- Set the UI root
	UIContainer = CoreGui;

	-- Create the toolbar button
	PluginButton = Plugin:CreateToolbar('Building Tools by F3X'):CreateButton(
		'Building Tools by F3X',
		'Building Tools by F3X',
		Assets.PluginIcon
	);

	-- Connect the button to the system
	PluginButton.Click:Connect(function ()
		PluginEnabled = not PluginEnabled;
		PluginButton:SetActive(PluginEnabled);

		-- Toggle the tool
		if PluginEnabled then
			Plugin:Activate(true);
			Enable(Plugin:GetMouse());
		else
			Disable();
		end;
	end);

	-- Disable the tool upon plugin deactivation
	Plugin.Deactivation:Connect(Disable);

	-- Sync Studio selection to internal selection
	Selection.Changed:Connect(function ()
		SelectionService:Set(Selection.Items);
	end);

	-- Sync internal selection to Studio selection on enabling
	Enabling:Connect(function ()
		Selection.Replace(SelectionService:Get());
	end);

	-- Roughly sync Studio history to internal history (API lacking necessary functionality)
	History.Changed:Connect(function ()
		ChangeHistoryService:SetWaypoint 'Building Tools by F3X';
	end);

elseif Mode == 'Tool' then

	-- Set the UI root
	UIContainer = Player:WaitForChild 'PlayerGui';

	-- Connect the tool to the system
	Tool.Equipped:Connect(Enable);
	Tool.Unequipped:Connect(Disable);

	-- Disable the tool if not parented
	if not Tool.Parent then
		Disable();
	end;

	-- Disable the tool automatically if not equipped or in backpack
	Tool.AncestryChanged:Connect(function (Item, Parent)
		if not Parent or not (Parent:IsA 'Backpack' or (Parent:IsA 'Model' and Players:GetPlayerFromCharacter(Parent))) then
			Disable();
		end;
	end);

end;
