import "./bootstrap.scss";

(async () => {
	if (!navigator.locks) {
		await import("./index");
		return;
	}
	await navigator.locks.request(
		"cheogram-active-tab",
		{ ifAvailable: true },
		async (lock) => {
			if (!lock) {
				const message = document.createElement("main");
				message.className = "startup-message";

				const text = document.createElement("p");
				text.setAttribute("role", "status");
				text.textContent =
					"Cheogram is already running in another tab or window. Close it, then try again here.";

				const retry = document.createElement("button");
				retry.textContent = "Try again";
				retry.onclick = () => window.location.reload();

				message.append(text, retry);
				document.getElementById("root")!.replaceChildren(message);

				return;
			}
			await import("./index").catch(console.error);

			// https://github.com/w3c/web-locks/blob/main/EXPLAINER.md#can-you-hold-a-lock-for-the-lifetime-of-a-tab
			await new Promise<void>(() => {});
		},
	);
})();
