import { cdnUrls } from "./consts.js";
import { isObject } from "../utils/assertion.js";
import { noop } from "../utils/function.js";
import { useCallbackRef } from "../utils/react.js";
import { createContext, useContext, useEffect, useState } from "react";
import { jsx } from "react/jsx-runtime";

//#region src/core/links.tsx
const LinksContext = createContext(void 0);
/**
* Adds loggedIn=1 parameter to the URL if 'isLoggedIn' flag is true, which means the user is logged in.
* If 'isLoggedIn' is falsy, loggedin param will be removed.
* This is supposed to aid login flow when navigating between Veracity applications.
*/
function getLoggedInLink(link, isLoggedIn) {
	try {
		const url = new URL(link);
		if (isLoggedIn) url.searchParams.append("loggedin", "1");
		else url.searchParams.delete("loggedin");
		return url.toString();
	} catch {
		return link;
	}
}
function LinksProvider(props) {
	const linksState = useState({});
	return /* @__PURE__ */ jsx(LinksContext.Provider, {
		value: linksState,
		...props
	});
}
/** Returns links and setLinks from LinksContext. */
function useLinks() {
	const context = useContext(LinksContext);
	if (context === void 0) {
		console.error("useLinks must be used within a LinksContext.");
		return [{}, noop];
	}
	return context;
}
/**
* Retrieves the links from CDN for the given environment and appends them with loggedin=1 parameter
* if user is logged in. Links will be reloaded when 'env' changes or updated when 'isLoggedIn' changes.
*/
function useLoadLinks(env, isLoggedIn) {
	const [, setLinks] = useLinks();
	const loadLinks = async (env) => {
		try {
			const response = await fetch(`${cdnUrls[env]}/common/data/links/base.json`);
			if (!response.ok) return;
			const data = await response.json();
			if (isObject(data)) setLinks(updateLoggedInParam(data));
		} catch {
			console.error("Failed to retrieve links");
		}
	};
	/**
	* Adds/removes loggedin=1 URL param for each link based on isLoggedIn arg.
	* useCallbackRef is used here to prevent a stale closure in async loadLinks.
	*/
	const updateLoggedInParam = useCallbackRef((links) => {
		return Object.keys(links).reduce((loggedInLinks, key) => {
			loggedInLinks[key] = getLoggedInLink(links[key], isLoggedIn);
			return loggedInLinks;
		}, {});
	});
	useEffect(() => {
		if (!env) return;
		loadLinks(env);
	}, [env]);
	useEffect(() => {
		setLinks(updateLoggedInParam);
	}, [isLoggedIn]);
}

//#endregion
export { LinksProvider, getLoggedInLink, useLinks, useLoadLinks };
globalThis.__vuiVersion__ = "4.0.1"
//# sourceMappingURL=links.js.map