"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useCallback, useMemo, useState } from "react";
import Link from "next/link";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Input } from "@open-mercato/ui/primitives/input";
import { EmailInput } from "@open-mercato/ui/primitives/email-input";
import { PasswordInput } from "@open-mercato/ui/primitives/password-input";
import { Label } from "@open-mercato/ui/primitives/label";
import { Button } from "@open-mercato/ui/primitives/button";
import { Alert, AlertDescription } from "@open-mercato/ui/primitives/alert";
import { EmptyState } from "@open-mercato/ui/primitives/empty-state";
import { SearchX, Check } from "lucide-react";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { usePortalContext } from "@open-mercato/ui/portal/PortalContext";
import { InjectionSpot } from "@open-mercato/ui/backend/injection/InjectionSpot";
import { PortalInjectionSpots } from "@open-mercato/ui/backend/injection/spotIds";
function PortalSignupPage({ params }) {
  const t = useT();
  const orgSlug = params.orgSlug;
  const { tenant } = usePortalContext();
  const [displayName, setDisplayName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState(null);
  const [fieldErrors, setFieldErrors] = useState({});
  const [success, setSuccess] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const handleSubmit = useCallback(
    async (event) => {
      event.preventDefault();
      setError(null);
      setFieldErrors({});
      if (!tenant.organizationId) {
        setError(t("portal.org.invalid", "Organization not found."));
        return;
      }
      setSubmitting(true);
      try {
        const result = await apiCall("/api/customer_accounts/signup", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ email, password, displayName, organizationId: tenant.organizationId })
        });
        if (result.status === 202 && result.result?.ok) {
          setSuccess(true);
          return;
        }
        const details = result.result?.details;
        const detailEntries = details ? Object.entries(details).filter(([, messages]) => (messages?.length ?? 0) > 0) : [];
        if (detailEntries.length > 0) {
          const mapped = {};
          for (const [fieldKey] of detailEntries) {
            if (fieldKey === "displayName") {
              mapped.displayName = t("portal.signup.error.displayName.required", "Full name is required.");
            } else if (fieldKey === "email") {
              mapped.email = t("portal.signup.error.email.invalid", "Please enter a valid email address.");
            } else if (fieldKey === "password") {
              mapped.password = t("portal.signup.error.password.minLength", "Password must be at least 8 characters.");
            }
          }
          const hasUnmappedField = detailEntries.some(([fieldKey]) => !(fieldKey in mapped));
          setFieldErrors(mapped);
          if (hasUnmappedField || Object.keys(mapped).length === 0) {
            setError(result.result?.error || t("portal.signup.error.generic", "Signup failed. Please try again."));
          }
        } else {
          setError(result.result?.error || t("portal.signup.error.generic", "Signup failed. Please try again."));
        }
      } catch {
        setError(t("portal.signup.error.generic", "Signup failed. Please try again."));
      } finally {
        setSubmitting(false);
      }
    },
    [displayName, email, password, tenant.organizationId, t]
  );
  const injectionContext = useMemo(
    () => ({ orgSlug }),
    [orgSlug]
  );
  if (tenant.loading) {
    return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center py-20", children: /* @__PURE__ */ jsx(Spinner, {}) });
  }
  if (tenant.error) {
    return /* @__PURE__ */ jsx("div", { className: "mx-auto w-full max-w-md py-12", children: /* @__PURE__ */ jsx(
      EmptyState,
      {
        variant: "subtle",
        size: "lg",
        icon: /* @__PURE__ */ jsx(SearchX, { className: "h-6 w-6", "aria-hidden": true }),
        title: t("portal.org.invalid", "Organization not found.")
      }
    ) });
  }
  if (success) {
    return /* @__PURE__ */ jsxs("div", { className: "mx-auto w-full max-w-sm text-center", children: [
      /* @__PURE__ */ jsx("div", { className: "mx-auto mb-4 flex size-12 items-center justify-center rounded-full bg-foreground text-background", children: /* @__PURE__ */ jsx(Check, { className: "size-6" }) }),
      /* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold tracking-tight", children: t("portal.signup.success.title", "Check your email") }),
      /* @__PURE__ */ jsx("p", { className: "mt-1.5 text-sm text-muted-foreground", children: t(
        "portal.signup.success.description",
        "If your registration was accepted, check your email for next steps before signing in. Some organizations require an administrator to activate new accounts."
      ) }),
      /* @__PURE__ */ jsx(Button, { asChild: true, className: "mt-6 w-full rounded-lg", children: /* @__PURE__ */ jsx(Link, { href: `/${orgSlug}/portal/login`, children: t("portal.signup.success.loginLink", "Sign In") }) })
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: "mx-auto w-full max-w-sm", children: [
    /* @__PURE__ */ jsxs("div", { className: "mb-8 text-center", children: [
      /* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold tracking-tight", children: t("portal.signup.title", "Create Account") }),
      /* @__PURE__ */ jsx("p", { className: "mt-1.5 text-sm text-muted-foreground", children: t("portal.signup.description", "Sign up for a portal account.") })
    ] }),
    /* @__PURE__ */ jsx(InjectionSpot, { spotId: PortalInjectionSpots.pageBefore("signup"), context: injectionContext }),
    /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, className: "flex flex-col gap-4", children: [
      error ? /* @__PURE__ */ jsx(Alert, { variant: "destructive", children: /* @__PURE__ */ jsx(AlertDescription, { children: error }) }) : null,
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "signup-name", className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground/70", children: t("portal.signup.displayName", "Full Name") }),
        /* @__PURE__ */ jsx(Input, { id: "signup-name", type: "text", autoComplete: "name", required: true, placeholder: t("portal.signup.displayName.placeholder", "Jane Smith"), value: displayName, onChange: (e) => setDisplayName(e.target.value), disabled: submitting, "aria-invalid": fieldErrors.displayName ? true : void 0, "aria-describedby": fieldErrors.displayName ? "signup-name-error" : void 0, className: "rounded-lg" }),
        fieldErrors.displayName && /* @__PURE__ */ jsx("p", { id: "signup-name-error", role: "alert", className: "text-sm text-destructive", children: fieldErrors.displayName })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "signup-email", className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground/70", children: t("portal.signup.email", "Email") }),
        /* @__PURE__ */ jsx(EmailInput, { id: "signup-email", required: true, placeholder: t("portal.signup.email.placeholder", "you@example.com"), value: email, onChange: (e) => setEmail(e.target.value), disabled: submitting, "aria-invalid": fieldErrors.email ? true : void 0, "aria-describedby": fieldErrors.email ? "signup-email-error" : void 0, className: "rounded-lg" }),
        fieldErrors.email && /* @__PURE__ */ jsx("p", { id: "signup-email-error", role: "alert", className: "text-sm text-destructive", children: fieldErrors.email })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "signup-password", className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground/70", children: t("portal.signup.password", "Password") }),
        /* @__PURE__ */ jsx(PasswordInput, { id: "signup-password", autoComplete: "new-password", required: true, placeholder: t("portal.signup.password.placeholder", "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"), value: password, onChange: (e) => setPassword(e.target.value), disabled: submitting, "aria-invalid": fieldErrors.password ? true : void 0, "aria-describedby": fieldErrors.password ? "signup-password-error" : void 0, className: "rounded-lg" }),
        fieldErrors.password && /* @__PURE__ */ jsx("p", { id: "signup-password-error", role: "alert", className: "text-sm text-destructive", children: fieldErrors.password })
      ] }),
      /* @__PURE__ */ jsx(Button, { type: "submit", disabled: submitting, className: "mt-1 w-full rounded-lg", children: submitting ? t("portal.signup.submitting", "Creating account...") : t("portal.signup.submit", "Create Account") }),
      /* @__PURE__ */ jsxs("p", { className: "text-center text-sm text-muted-foreground", children: [
        t("portal.signup.hasAccount", "Already have an account?"),
        " ",
        /* @__PURE__ */ jsx(Link, { href: `/${orgSlug}/portal/login`, className: "font-medium text-foreground underline underline-offset-4 hover:opacity-80", children: t("portal.signup.loginLink", "Sign in") })
      ] })
    ] }),
    /* @__PURE__ */ jsx(InjectionSpot, { spotId: PortalInjectionSpots.pageAfter("signup"), context: injectionContext })
  ] });
}
export {
  PortalSignupPage as default
};
//# sourceMappingURL=page.js.map
