import {
  AvatarBox
} from "./chunk-CP5IL4P6.js";
import {
  isFetchError
} from "./chunk-C6SUTRP2.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import "./chunk-U2EI2ZLM.js";
import {
  useAcceptInvite
} from "./chunk-RLRWDHME.js";
import {
  useSignInForInvite,
  useSignUpForInvite
} from "./chunk-K5324KIX.js";
import "./chunk-FV76G2D7.js";
import "./chunk-GHDLST2P.js";
import "./chunk-YVYYOBAE.js";
import "./chunk-L2NJPDUD.js";
import "./chunk-P7UBW2EI.js";
import "./chunk-MR6REQKT.js";
import "./chunk-EPSDO2MJ.js";
import "./chunk-BHEU34FL.js";
import {
  useSelectSeller
} from "./chunk-W34KDYZA.js";
import "./chunk-II3CLUXA.js";
import "./chunk-XKEYHWBS.js";
import "./chunk-J2XUEO2E.js";
import "./chunk-656G74I2.js";
import "./chunk-VWPNMEOE.js";
import "./chunk-O72AIZUN.js";
import "./chunk-VUWAOX7H.js";
import "./chunk-5DKUSZQ7.js";
import "./chunk-DIAWPVYS.js";
import "./chunk-4U2BLH45.js";
import "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import {
  assetUrl,
  sdk
} from "./chunk-DTGEFKK4.js";
import "./chunk-NBMM2TZK.js";

// src/pages/invite/invite.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Alert,
  Button,
  Heading,
  Hint,
  Input,
  Text,
  toast
} from "@medusajs/ui";
import i18n from "i18next";
import { AnimatePresence, motion } from "motion/react";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { decodeToken } from "react-jwt";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import * as z from "zod";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var CreateAccountSchema = z.object({
  email: z.string().email(),
  first_name: z.string().optional(),
  last_name: z.string().optional(),
  password: z.string().min(1),
  repeat_password: z.string().optional(),
  existing_member: z.boolean()
}).superRefine(
  ({ first_name, last_name, password, repeat_password, existing_member }, ctx) => {
    if (!existing_member) {
      if (!first_name || first_name.trim().length === 0) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: i18n.t("register.validation.firstNameRequired"),
          path: ["first_name"]
        });
      }
      if (!last_name || last_name.trim().length === 0) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: i18n.t("register.validation.lastNameRequired"),
          path: ["last_name"]
        });
      }
      if (!repeat_password || password !== repeat_password) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: i18n.t("invite.passwordMismatch"),
          path: ["repeat_password"]
        });
      }
    }
  }
);
var Invite = () => {
  const [searchParams] = useSearchParams();
  const [success, setSuccess] = useState(false);
  const token = searchParams.get("token");
  const invite = token ? decodeToken(token) : null;
  const isValidInvite = invite && validateDecodedInvite(invite);
  return /* @__PURE__ */ jsxs("div", { className: "flex h-dvh w-dvw overflow-hidden", children: [
    /* @__PURE__ */ jsx("div", { className: "flex w-full flex-col lg:w-[584px] lg:shrink-0 h-full bg-ui-bg-base border-r border-ui-border-base overflow-y-auto", children: /* @__PURE__ */ jsx(AnimatePresence, { mode: "wait", children: success && invite ? /* @__PURE__ */ jsx(
      motion.div,
      {
        initial: { opacity: 0 },
        animate: { opacity: 1 },
        transition: { duration: 0.6, delay: 0.2 },
        className: "flex flex-1 flex-col items-center justify-center p-8 lg:px-14",
        children: /* @__PURE__ */ jsx(SuccessView, { sellerName: invite.seller_name })
      },
      "success"
    ) : /* @__PURE__ */ jsxs(
      motion.div,
      {
        exit: { opacity: 0, y: -20 },
        transition: { duration: 0.4, ease: "easeInOut" },
        className: "flex flex-1 flex-col p-8 lg:px-14 lg:py-12",
        children: [
          /* @__PURE__ */ jsx(AvatarBox, {}),
          /* @__PURE__ */ jsx("div", { className: "mt-8 w-full", children: isValidInvite ? /* @__PURE__ */ jsx(
            CreateView,
            {
              token,
              invite,
              onSuccess: () => setSuccess(true)
            }
          ) : /* @__PURE__ */ jsx(InvalidView, {}) })
        ]
      },
      "form"
    ) }) }),
    /* @__PURE__ */ jsx("div", { className: "hidden lg:flex flex-1 relative overflow-hidden", children: /* @__PURE__ */ jsx(
      "img",
      {
        src: assetUrl("/onboarding/illustration.svg"),
        alt: "",
        className: "h-full w-full object-cover"
      }
    ) })
  ] });
};
var SuccessView = ({ sellerName }) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { mutateAsync: selectSeller } = useSelectSeller();
  const hasRedirected = useRef(false);
  useEffect(() => {
    if (hasRedirected.current) return;
    hasRedirected.current = true;
    const redirect = async () => {
      await new Promise((r) => setTimeout(r, 2500));
      try {
        const { seller_members } = await sdk.vendor.sellers.query({});
        if (seller_members?.length === 1) {
          await selectSeller({ seller_id: seller_members[0].seller.id });
          navigate("/", { replace: true });
          return;
        }
      } catch {
      }
      navigate("/store-select", { replace: true });
    };
    redirect();
  }, [navigate, selectSeller]);
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center text-center", children: [
    /* @__PURE__ */ jsx(AvatarBox, { checked: true }),
    /* @__PURE__ */ jsxs(
      motion.div,
      {
        initial: { opacity: 0, y: 10 },
        animate: { opacity: 1, y: 0 },
        transition: { duration: 0.5, delay: 0.6 },
        children: [
          /* @__PURE__ */ jsx(Heading, { children: t("invite.successTitle", { name: sellerName }) }),
          /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle mt-1", children: t("invite.successHint") })
        ]
      }
    )
  ] });
};
var LoginLink = () => {
  const { t } = useTranslation();
  return /* @__PURE__ */ jsx("div", { className: "mt-8", children: /* @__PURE__ */ jsxs("span", { className: "text-ui-fg-muted txt-small", children: [
    t("invite.alreadyHaveAccount", "Already have an account?"),
    " ",
    /* @__PURE__ */ jsx(
      Link,
      {
        to: "/login",
        className: "txt-small text-ui-fg-interactive transition-fg hover:text-ui-fg-interactive-hover focus-visible:text-ui-fg-interactive-hover font-medium outline-none",
        children: t("invite.logIn", "Log in")
      }
    )
  ] }) });
};
var InvalidView = () => {
  const { t } = useTranslation();
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
    /* @__PURE__ */ jsx(Heading, { children: t("invite.invalidTokenTitle") }),
    /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle mt-1", children: t("invite.invalidTokenHint") }),
    /* @__PURE__ */ jsx(LoginLink, {})
  ] });
};
var CreateView = ({
  token,
  invite,
  onSuccess
}) => {
  const { t } = useTranslation();
  const [invalid, setInvalid] = useState(false);
  const isExistingMember = invite.existing_member;
  const form = useForm({
    resolver: zodResolver(CreateAccountSchema),
    defaultValues: {
      email: invite.email || "",
      first_name: "",
      last_name: "",
      password: "",
      repeat_password: "",
      existing_member: isExistingMember
    }
  });
  const { mutateAsync: signUp, isPending: isCreatingAuthUser } = useSignUpForInvite();
  const { mutateAsync: signIn, isPending: isSigningIn } = useSignInForInvite();
  const { mutateAsync: acceptInvite, isPending: isAcceptingInvite } = useAcceptInvite();
  const handleSubmit = form.handleSubmit(async (data) => {
    try {
      const { token: authToken } = isExistingMember ? await signIn({
        email: data.email,
        password: data.password
      }) : await signUp({
        email: data.email,
        password: data.password
      });
      await acceptInvite({
        invite_token: token,
        auth_token: authToken,
        first_name: isExistingMember ? void 0 : data.first_name,
        last_name: isExistingMember ? void 0 : data.last_name
      });
      const { token: freshToken } = await signIn({
        email: data.email,
        password: data.password
      });
      await sdk.auth.session.mutate({
        fetchOptions: {
          headers: {
            Authorization: `Bearer ${freshToken}`
          }
        }
      });
      toast.success(t("invite.toast.accepted"));
      onSuccess();
    } catch (error) {
      if (isFetchError(error)) {
        if (error.status === 401) {
          form.setError("root", {
            type: "manual",
            message: t("errors.invalidCredentials")
          });
          return;
        }
        if (error.status === 400) {
          form.setError("root", {
            type: "manual",
            message: t("invite.invalidInvite")
          });
          setInvalid(true);
          return;
        }
      }
      form.setError("root", {
        type: "manual",
        message: t("errors.serverError")
      });
    }
  });
  const serverError = form.formState.errors.root?.message;
  const validationError = form.formState.errors.email?.message || form.formState.errors.password?.message || form.formState.errors.repeat_password?.message;
  return /* @__PURE__ */ jsxs("div", { className: "flex w-full flex-col", children: [
    /* @__PURE__ */ jsx(Heading, { children: t("invite.title", {
      name: invite.seller_name
    }) }),
    /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle mt-1 mb-6", children: isExistingMember ? t("invite.existingMemberHint") : t("invite.hint") }),
    /* @__PURE__ */ jsx(Form, { ...form, children: /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, className: "flex w-full flex-col gap-y-6", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
        !isExistingMember && /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx(
            Form.Field,
            {
              control: form.control,
              name: "first_name",
              render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                /* @__PURE__ */ jsx(Form.Label, { children: t("register.firstName") }),
                /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { autoComplete: "given-name", ...field }) }),
                /* @__PURE__ */ jsx(Form.ErrorMessage, {})
              ] })
            }
          ),
          /* @__PURE__ */ jsx(
            Form.Field,
            {
              control: form.control,
              name: "last_name",
              render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                /* @__PURE__ */ jsx(Form.Label, { children: t("register.lastName") }),
                /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { autoComplete: "family-name", ...field }) }),
                /* @__PURE__ */ jsx(Form.ErrorMessage, {})
              ] })
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          Form.Field,
          {
            control: form.control,
            name: "password",
            render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
              /* @__PURE__ */ jsx(Form.Label, { children: t("fields.password") }),
              /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                Input,
                {
                  autoComplete: "new-password",
                  type: "password",
                  ...field
                }
              ) })
            ] })
          }
        ),
        !isExistingMember && /* @__PURE__ */ jsx(
          Form.Field,
          {
            control: form.control,
            name: "repeat_password",
            render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
              /* @__PURE__ */ jsx(Form.Label, { children: t("fields.repeatPassword") }),
              /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                Input,
                {
                  autoComplete: "off",
                  type: "password",
                  ...field
                }
              ) })
            ] })
          }
        ),
        validationError && /* @__PURE__ */ jsx(Hint, { className: "inline-flex", variant: "error", children: validationError }),
        serverError && /* @__PURE__ */ jsx(
          Alert,
          {
            className: "bg-ui-bg-base items-center p-2",
            dismissible: true,
            variant: "error",
            children: serverError
          }
        )
      ] }),
      /* @__PURE__ */ jsx(
        Button,
        {
          className: "w-full",
          type: "submit",
          isLoading: isCreatingAuthUser || isSigningIn || isAcceptingInvite,
          disabled: invalid,
          children: t("actions.continue")
        }
      )
    ] }) }),
    /* @__PURE__ */ jsx(LoginLink, {})
  ] });
};
var InviteSchema = z.object({
  id: z.string(),
  jti: z.string(),
  exp: z.number(),
  iat: z.number()
});
var validateDecodedInvite = (decoded) => {
  return InviteSchema.safeParse(decoded).success;
};
export {
  Invite as Component
};
