import { createApp, Component, getCurrentInstance } from "vue";

export const useUnmountComponent = () => {
	const instance = getCurrentInstance();
	const unmountComponent = () => {
		instance?.appContext.app.unmount();
		document.body.removeChild(instance?.appContext.app._container);
	};

	return {
		unmountComponent,
	};
};

export function mountComponent(RootComponent: Component, rootProps?: Record<string, unknown> | null | undefined) {
	const app = createApp(RootComponent, { ...rootProps, unmount });
	const root = document.createElement("div");

	function unmount() {
		app.unmount();
		document.body.removeChild(root);
	}

	document.body.appendChild(root);

	return {
		instance: app.mount(root),
		unmount,
	};
}
