import { useMemo, useState, useEffect } from "react";
import { useInitIDPRedirect } from "./useInitIDPRedirect.js";
const useIDPAutoInit = ({ onError, providers }) => {
  const idp = useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    const idp2 = params.get("idp");
    if (idp2 !== null) {
      return idp2;
    }
    const backlink = params.get("backlink");
    if (backlink !== null) {
      const resolvedBacklink = new URL(backlink, window.location.href);
      return resolvedBacklink.searchParams.get("idp");
    }
  }, []);
  const [idpState, setIdpState] = useState(idp ? { type: "processing" } : { type: "nothing" });
  const onInitIDP = useInitIDPRedirect({ onError });
  useEffect(() => {
    if (!idp) {
      return;
    }
    const provider = providers.find((it) => it.provider === idp);
    if (provider) {
      (async () => {
        const result = await onInitIDP(provider);
        if (!result.ok) {
          setIdpState({ type: "failed", error: result.error });
        }
      })();
    } else {
      const error = `Undefined IdP ${idp}`;
      onError?.(error);
      setIdpState({ type: "failed", error });
    }
  }, [idp, onError, onInitIDP, providers]);
  return idpState;
};
export {
  useIDPAutoInit
};
//# sourceMappingURL=useIDPAutoInit.js.map
