import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { createFrontendModule, coreExtensionData, useApi, identityApiRef } from '@backstage/frontend-plugin-api';
import { useAsync, useMountEffect } from '@react-hookz/web';
import { createApp } from './createApp.esm.js';
import appPlugin from '@backstage/plugin-app';

function InternalCookieAuthRedirect() {
  const identityApi = useApi(identityApiRef);
  const [state, actions] = useAsync(async () => {
    const { token } = await identityApi.getCredentials();
    if (!token) {
      throw new Error("Expected Backstage token in sign-in response");
    }
    return token;
  });
  useMountEffect(actions.execute);
  if (state.status === "error" && state.error) {
    return /* @__PURE__ */ jsxs(Fragment, { children: [
      "An error occurred: ",
      state.error.message
    ] });
  }
  if (state.status === "success" && state.result) {
    return /* @__PURE__ */ jsxs(
      "form",
      {
        ref: (form) => form?.submit(),
        action: window.location.href,
        method: "POST",
        style: { visibility: "hidden" },
        children: [
          /* @__PURE__ */ jsx("input", { type: "hidden", name: "type", value: "sign-in" }),
          /* @__PURE__ */ jsx("input", { type: "hidden", name: "token", value: state.result }),
          /* @__PURE__ */ jsx("input", { type: "submit", value: "Continue" })
        ]
      }
    );
  }
  return null;
}
function createPublicSignInApp(options) {
  return createApp({
    ...options,
    features: [
      ...options?.features ?? [],
      // This is a rather than app plugin override in order for it to take precedence over any supplied app plugin override
      createFrontendModule({
        pluginId: "app",
        extensions: [
          appPlugin.getExtension("app/layout").override({
            factory: () => [
              coreExtensionData.reactElement(/* @__PURE__ */ jsx(InternalCookieAuthRedirect, {}))
            ]
          })
        ]
      })
    ]
  });
}

export { InternalCookieAuthRedirect, createPublicSignInApp };
//# sourceMappingURL=createPublicSignInApp.esm.js.map
