import { useCallback as e, useEffect as t, useRef as n, useState as r } from "react";
//#region src/features/oauth/useOAuthPopup.ts
var i = "loopstack:oauth:callback", a = 500, o = 3e5;
function s(e) {
	return typeof e == "object" && !!e && e.type === i;
}
function c(e, t, n) {
	let r = `width=${t},height=${n},left=${Math.round(window.screenX + (window.outerWidth - t) / 2)},top=${Math.round(window.screenY + (window.outerHeight - n) / 2)},popup=yes,noopener=no`;
	return window.open(e, "loopstack-oauth", r);
}
function l() {
	let [i, l] = r({ status: "idle" }), u = n(null), d = n(null), f = n(null), p = n(null), m = e(() => {
		d.current &&= (clearTimeout(d.current), null), f.current &&= (clearInterval(f.current), null), p.current = null;
	}, []), h = e(() => {
		u.current && !u.current.closed && u.current.close(), u.current = null;
	}, []);
	return t(() => {
		let e = (e) => {
			if (e.origin !== window.location.origin || !s(e.data) || !p.current) return;
			let t = e.data;
			t.error ? l({
				status: "error",
				error: t.errorDescription || t.error
			}) : t.code && t.state ? t.state === p.current ? l({
				status: "success",
				code: t.code,
				state: t.state
			}) : l({
				status: "error",
				error: "State mismatch. Possible CSRF attack."
			}) : l({
				status: "error",
				error: "Invalid callback response."
			}), m(), h();
		};
		return window.addEventListener("message", e), () => window.removeEventListener("message", e);
	}, [m, h]), t(() => () => {
		m();
	}, [m]), {
		result: i,
		open: e((e) => {
			let { authUrl: t, state: n, popupWidth: r = 500, popupHeight: i = 700, timeoutMs: s = o } = e;
			m(), h(), p.current = n;
			let g = c(t, r, i);
			if (!g) {
				l({ status: "blocked" });
				return;
			}
			u.current = g, l({ status: "pending" }), f.current = setInterval(() => {
				g.closed && (f.current && clearInterval(f.current), f.current = null, l((e) => e.status === "pending" ? {
					status: "error",
					error: "Authentication window was closed."
				} : e), m());
			}, a), d.current = setTimeout(() => {
				l((e) => e.status === "pending" ? { status: "timeout" } : e), m(), h();
			}, s);
		}, [m, h]),
		reset: e(() => {
			m(), h(), l({ status: "idle" });
		}, [m, h])
	};
}
//#endregion
export { l as useOAuthPopup };
