"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("react/jsx-runtime");
const reactClient = require("@contember/react-client");
const ui = require("@contember/ui");
const react = require("react");
const MiscPageLayout = require("../MiscPageLayout.cjs");
const Pages = require("../pageRouting/Pages.cjs");
const CreateResetPasswordRequestForm = require("../../tenant/components/password/CreateResetPasswordRequestForm.cjs");
const FillResetPasswordTokenForm = require("../../tenant/components/password/FillResetPasswordTokenForm.cjs");
const ResetPasswordForm = require("../../tenant/components/password/ResetPasswordForm.cjs");
const useRedirectToBacklink = require("../../tenant/components/person/useRedirectToBacklink.cjs");
const ProjectList = require("../Project/ProjectList.cjs");
const useIDPAutoInit = require("../../tenant/components/idp/useIDPAutoInit.cjs");
const IDPResponseHandler = require("../../tenant/components/idp/IDPResponseHandler.cjs");
const Login = require("../../tenant/components/person/Login.cjs");
const IDPInitButton = require("../../tenant/components/idp/IDPInitButton.cjs");
const reactRouting = require("@contember/react-routing");
const IdentityProvider = require("../Identity/IdentityProvider.cjs");
const Link = require("../../routing/Link.cjs");
const reactIdentity = require("@contember/react-identity");
const indexPageName = "index";
const resetRequestPageName = "resetRequest";
const redirectOnSuccessPageName = "resetRequestSuccess";
const passwordResetPageName = "passwordReset";
const LoginEntrypoint = (props) => {
  const routing = {
    basePath: props.basePath ?? "/",
    routes: {},
    defaultDimensions: {},
    pageInQuery: true
  };
  return /* @__PURE__ */ jsxRuntime.jsx(
    reactClient.ContemberClient,
    {
      apiBaseUrl: props.apiBaseUrl,
      sessionToken: props.sessionToken,
      loginToken: props.loginToken,
      children: /* @__PURE__ */ jsxRuntime.jsx(reactRouting.RoutingContext.Provider, { value: routing, children: /* @__PURE__ */ jsxRuntime.jsx(reactRouting.RequestProvider, { children: /* @__PURE__ */ jsxRuntime.jsx(ui.Providers, { children: /* @__PURE__ */ jsxRuntime.jsxs(Pages.Pages, { children: [
        /* @__PURE__ */ jsxRuntime.jsx(reactRouting.Page, { name: indexPageName, children: /* @__PURE__ */ jsxRuntime.jsx(IdentityProvider.IdentityProvider, { allowUnauthenticated: true, children: /* @__PURE__ */ jsxRuntime.jsx(
          LoginEntrypointIndex,
          {
            projects: props.projects,
            formatProjectUrl: props.formatProjectUrl,
            identityProviders: props.identityProviders,
            heading: props.heading,
            projectsPageActions: props.projectsPageActions,
            collapsedEmailLogin: props.collapsedEmailLogin
          }
        ) }) }),
        /* @__PURE__ */ jsxRuntime.jsx(reactRouting.Page, { name: resetRequestPageName, children: /* @__PURE__ */ jsxRuntime.jsx(MiscPageLayout.MiscPageLayout, { heading: "Password reset", actions: /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: /* @__PURE__ */ jsxRuntime.jsx(Link.Link, { to: indexPageName, children: "← Back to login" }) }), children: /* @__PURE__ */ jsxRuntime.jsx(CreateResetPasswordRequestForm.CreateResetPasswordRequestForm, { redirectOnSuccess: redirectOnSuccessPageName }) }) }),
        /* @__PURE__ */ jsxRuntime.jsx(reactRouting.Page, { name: redirectOnSuccessPageName, children: /* @__PURE__ */ jsxRuntime.jsxs(MiscPageLayout.MiscPageLayout, { heading: "Password reset", actions: /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: /* @__PURE__ */ jsxRuntime.jsx(Link.Link, { to: indexPageName, children: "← Back to login" }) }), children: [
          /* @__PURE__ */ jsxRuntime.jsx("p", { children: "Password reset request has been successfully created. Please check your inbox for the instructions." }),
          /* @__PURE__ */ jsxRuntime.jsx("p", { children: "Please follow the link in e-mail or copy the reset token here:" }),
          /* @__PURE__ */ jsxRuntime.jsx(FillResetPasswordTokenForm.FillResetPasswordTokenForm, { resetLink: `${passwordResetPageName}(token: $token)` })
        ] }) }),
        /* @__PURE__ */ jsxRuntime.jsx(reactRouting.Page, { name: passwordResetPageName, children: ({ token }) => /* @__PURE__ */ jsxRuntime.jsx(MiscPageLayout.MiscPageLayout, { heading: "Set a new password", actions: /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: /* @__PURE__ */ jsxRuntime.jsx(Link.Link, { to: indexPageName, children: "← Back to login" }) }), children: /* @__PURE__ */ jsxRuntime.jsx(ResetPasswordForm.ResetPasswordForm, { token, redirectOnSuccess: indexPageName }) }) })
      ] }) }) }) })
    }
  );
};
const LoginEntrypointIndex = (props) => {
  const logout = reactIdentity.useLogout();
  const identity = reactIdentity.useIdentity();
  const [projectSlugs, setProjectSlugs] = react.useState();
  const projectsProvider = props.projects;
  react.useEffect(() => {
    (async () => {
      if (identity === void 0) {
        return;
      }
      setProjectSlugs(projectsProvider instanceof Function ? await projectsProvider() : projectsProvider);
    })();
  }, [identity, projectsProvider]);
  const projects = react.useMemo(() => {
    return identity?.projects.filter((it) => projectSlugs?.includes(it.slug));
  }, [identity?.projects, projectSlugs]);
  useRedirectToBacklink.useRedirectToBacklink();
  if (identity === void 0) {
    return /* @__PURE__ */ jsxRuntime.jsx(MiscPageLayout.MiscPageLayout, { heading: props.heading ?? "Contember Admin", children: /* @__PURE__ */ jsxRuntime.jsx(LoginContainer, { identityProviders: props.identityProviders, collapsedEmailLogin: props.collapsedEmailLogin }) });
  } else if (projects === void 0) {
    return /* @__PURE__ */ jsxRuntime.jsx(
      MiscPageLayout.MiscPageLayout,
      {
        heading: "Projects",
        actions: /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
          props.projectsPageActions,
          /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { onClick: () => logout(), size: "small", distinction: "seamless", children: /* @__PURE__ */ jsxRuntime.jsx(ui.Icon, { blueprintIcon: "log-out" }) })
        ] }),
        children: "Loading projects..."
      }
    );
  } else if (projects.length === 1) {
    window.location.href = props.formatProjectUrl(projects[0]);
    return null;
  } else {
    return /* @__PURE__ */ jsxRuntime.jsx(
      MiscPageLayout.MiscPageLayout,
      {
        heading: "Projects",
        actions: props.projectsPageActions,
        footerActions: /* @__PURE__ */ jsxRuntime.jsxs(ui.Button, { onClick: () => logout(), distinction: "seamless", display: "block", children: [
          "Sign out ",
          /* @__PURE__ */ jsxRuntime.jsx(ui.Icon, { blueprintIcon: "log-out" })
        ] }),
        children: /* @__PURE__ */ jsxRuntime.jsx(ProjectList.ProjectListButtons, { projects, formatProjectUrl: props.formatProjectUrl })
      }
    );
  }
};
const LoginContainer = ({ identityProviders = [], collapsedEmailLogin: initialCollapsedEmailLogin }) => {
  const [collapsedEmailLogin, setCollapsedEmailLogin] = react.useState(initialCollapsedEmailLogin ?? false);
  const [error, setError] = react.useState();
  const redirectToBacklink = useRedirectToBacklink.useRedirectToBacklinkCallback();
  const idpAutoInit = useIDPAutoInit.useIDPAutoInit({ providers: identityProviders });
  const idpHandlerFeedback = IDPResponseHandler.useResponseHandlerFeedback({ onLogin: redirectToBacklink });
  const errors = react.useMemo(() => [
    ...error ? [{ message: error }] : [],
    ...idpAutoInit.type === "failed" ? [{ message: idpAutoInit.error }] : []
  ], [error, idpAutoInit]);
  if (idpHandlerFeedback !== null) {
    return idpHandlerFeedback;
  }
  if (idpAutoInit.type === "processing") {
    return /* @__PURE__ */ jsxRuntime.jsx(ui.SpinnerOverlay, {});
  }
  const visibleIdentityProviders = identityProviders.filter((it) => !it.hidden);
  const showAlternativeLoginButtons = visibleIdentityProviders.length > 0 || collapsedEmailLogin;
  return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(ui.ErrorList, { errors }),
    !collapsedEmailLogin && /* @__PURE__ */ jsxRuntime.jsx(Login.Login, { resetLink: resetRequestPageName, onLogin: redirectToBacklink }),
    showAlternativeLoginButtons && /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { children: [
      visibleIdentityProviders.map((it, i) => /* @__PURE__ */ jsxRuntime.jsx(IDPInitButton.IDPInitButton, { provider: it, onError: setError }, i)),
      collapsedEmailLogin && /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { onClick: () => setCollapsedEmailLogin(false), children: "Login with email" })
    ] })
  ] });
};
exports.LoginEntrypoint = LoginEntrypoint;
//# sourceMappingURL=LoginEntrypoint.cjs.map
