"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 { 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 } 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 PortalLoginPage({ params }) {
  const t = useT();
  const orgSlug = params.orgSlug;
  const { tenant } = usePortalContext();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const handleSubmit = useCallback(
    async (event) => {
      event.preventDefault();
      setError(null);
      if (!tenant.organizationId) {
        setError(t("portal.org.invalid", "Organization not found."));
        return;
      }
      setSubmitting(true);
      try {
        const result = await apiCall("/api/customer_accounts/login", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          credentials: "include",
          body: JSON.stringify({ email, password, organizationId: tenant.organizationId })
        });
        if (result.ok && result.result?.ok) {
          window.location.assign(`/${orgSlug}/portal/dashboard`);
          return;
        }
        if (result.status === 401) {
          setError(t("portal.login.error.invalidCredentials", "Invalid email or password."));
        } else {
          setError(result.result?.error || t("portal.login.error.generic", "Login failed. Please try again."));
        }
      } catch {
        setError(t("portal.login.error.generic", "Login failed. Please try again."));
      } finally {
        setSubmitting(false);
      }
    },
    [email, password, tenant.organizationId, orgSlug, 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.")
      }
    ) });
  }
  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.login.title", "Sign In") }),
      /* @__PURE__ */ jsx("p", { className: "mt-1.5 text-sm text-muted-foreground", children: t("portal.login.description", "Enter your credentials to access the portal.") })
    ] }),
    /* @__PURE__ */ jsx(InjectionSpot, { spotId: PortalInjectionSpots.pageBefore("login"), 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: "login-email", className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground/70", children: t("portal.login.email", "Email") }),
        /* @__PURE__ */ jsx(EmailInput, { id: "login-email", required: true, placeholder: t("portal.login.email.placeholder", "you@example.com"), value: email, onChange: (e) => setEmail(e.target.value), disabled: submitting, className: "rounded-lg" })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "login-password", className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground/70", children: t("portal.login.password", "Password") }),
        /* @__PURE__ */ jsx(PasswordInput, { id: "login-password", autoComplete: "current-password", required: true, placeholder: t("portal.login.password.placeholder", "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"), value: password, onChange: (e) => setPassword(e.target.value), disabled: submitting, className: "rounded-lg" })
      ] }),
      /* @__PURE__ */ jsx(Button, { type: "submit", disabled: submitting, className: "mt-1 w-full rounded-lg", children: submitting ? t("portal.login.submitting", "Signing in...") : t("portal.login.submit", "Sign In") }),
      /* @__PURE__ */ jsxs("p", { className: "text-center text-sm text-muted-foreground", children: [
        t("portal.login.noAccount", "Don't have an account?"),
        " ",
        /* @__PURE__ */ jsx(Link, { href: `/${orgSlug}/portal/signup`, className: "font-medium text-foreground underline underline-offset-4 hover:opacity-80", children: t("portal.login.signupLink", "Sign up") })
      ] })
    ] }),
    /* @__PURE__ */ jsx(InjectionSpot, { spotId: PortalInjectionSpots.pageAfter("login"), context: injectionContext })
  ] });
}
export {
  PortalLoginPage as default
};
//# sourceMappingURL=page.js.map
