"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useCallback, useRef, useEffect } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useAuth } from "../../../hooks/useAuth";
import { useLastAuthMethod } from "../../../hooks/useLastAuthMethod";
import { Button } from "../../ui/button";
import { Input } from "../../ui/input";
import { Label } from "../../ui/label";
import { Alert, AlertDescription } from "../../ui/alert";
import { Checkbox } from "../../ui/checkbox";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "../../ui/card";
import { Separator } from "../../ui/separator";
import { LastUsedBadge } from "../../ui/last-used-badge";
import { Mail, Lock, Loader2, AlertCircle, Users } from "lucide-react";
import { GoogleIcon } from "../../ui/google-icon";
import { createTestId, sel } from "../../../lib/test";
import { useTranslations } from "next-intl";
import { AuthTranslationPreloader } from "../../../lib/i18n/AuthTranslationPreloader";
import { DevKeyring } from "../DevKeyring";
import { DEV_CONFIG } from "../../../lib/config/config-sync";
function getErrorMessageFromCode(error, t, context) {
  const authError = error;
  const errorCode = authError.code || getErrorCodeFromMessage(error.message);
  const baseKey = context === "email" ? "login.errors" : "login.errors.google";
  switch (errorCode) {
    case "INVALID_CREDENTIALS":
      return t(`${baseKey}.invalidCredentials`, { defaultValue: error.message });
    case "USER_NOT_FOUND":
      return t(`${baseKey}.userNotFound`, { defaultValue: error.message });
    case "EMAIL_NOT_VERIFIED":
      return t(`${baseKey}.emailNotVerified`, { defaultValue: error.message });
    case "ACCOUNT_LOCKED":
      return t(`${baseKey}.accountLocked`, { defaultValue: error.message });
    case "RATE_LIMITED":
      return t(`${baseKey}.rateLimited`, { defaultValue: error.message });
    case "OAUTH_ERROR":
      return t(`${baseKey}.oauthError`, { defaultValue: error.message });
    case "NETWORK_ERROR":
      return t(`${baseKey}.networkError`, { defaultValue: error.message });
    case "SERVER_ERROR":
      return t(`${baseKey}.serverError`, { defaultValue: error.message });
    default:
      return error.message || t(context === "email" ? "login.messages.signInFailed" : "login.messages.googleSignInFailed");
  }
}
function getErrorCodeFromMessage(message) {
  const lowerMessage = message.toLowerCase();
  if (lowerMessage.includes("credential") || lowerMessage.includes("password") || lowerMessage.includes("invalid")) {
    return "INVALID_CREDENTIALS";
  }
  if (lowerMessage.includes("not found") || lowerMessage.includes("user does not exist")) {
    return "USER_NOT_FOUND";
  }
  if (lowerMessage.includes("verify") || lowerMessage.includes("verification")) {
    return "EMAIL_NOT_VERIFIED";
  }
  if (lowerMessage.includes("locked") || lowerMessage.includes("suspended")) {
    return "ACCOUNT_LOCKED";
  }
  if (lowerMessage.includes("rate") || lowerMessage.includes("too many")) {
    return "RATE_LIMITED";
  }
  if (lowerMessage.includes("oauth") || lowerMessage.includes("google") || lowerMessage.includes("provider")) {
    return "OAUTH_ERROR";
  }
  if (lowerMessage.includes("network") || lowerMessage.includes("connection")) {
    return "NETWORK_ERROR";
  }
  if (lowerMessage.includes("server") || lowerMessage.includes("internal")) {
    return "SERVER_ERROR";
  }
  return "UNKNOWN_ERROR";
}
const loginSchema = z.object({
  email: z.string().email({ message: "Invalid email" }),
  password: z.string().min(6, "Password must be at least 6 characters")
});
function LoginForm() {
  var _a;
  const [loadingProvider, setLoadingProvider] = useState(null);
  const [error, setError] = useState(null);
  const [statusMessage, setStatusMessage] = useState("");
  const [showEmailForm, setShowEmailForm] = useState(false);
  const isProcessingRef = useRef(false);
  const { signIn, googleSignIn } = useAuth();
  const { lastMethod, isReady } = useLastAuthMethod();
  const t = useTranslations("auth");
  const searchParams = useSearchParams();
  const inviteEmail = searchParams.get("email");
  const fromInvite = searchParams.get("fromInvite") === "true";
  const callbackUrl = searchParams.get("callbackUrl");
  useEffect(() => {
    if (fromInvite && inviteEmail) {
      setShowEmailForm(true);
    }
  }, [fromInvite, inviteEmail]);
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm({
    resolver: zodResolver(loginSchema),
    mode: "onSubmit",
    reValidateMode: "onChange",
    defaultValues: {
      email: inviteEmail || ""
    }
  });
  const onSubmit = useCallback(async (data) => {
    if (loadingProvider) return;
    setLoadingProvider("email");
    setError(null);
    setStatusMessage(t("login.messages.signingIn"));
    try {
      await signIn({
        ...data,
        redirectTo: callbackUrl || void 0
      });
      setStatusMessage(t("login.messages.signInSuccess"));
    } catch (err) {
      const error2 = err instanceof Error ? err : new Error(t("login.messages.signInFailed"));
      const errorMessage = getErrorMessageFromCode(error2, t, "email");
      setError(errorMessage);
      setStatusMessage(t("login.messages.signInError", { error: errorMessage }));
    } finally {
      setLoadingProvider(null);
    }
  }, [signIn, t, loadingProvider, callbackUrl]);
  const handleGoogleSignIn = useCallback(async () => {
    if (isProcessingRef.current || loadingProvider) return;
    isProcessingRef.current = true;
    setLoadingProvider("google");
    setError(null);
    setStatusMessage(t("login.messages.googleSigningIn"));
    try {
      await googleSignIn(callbackUrl || void 0);
      setStatusMessage(t("login.messages.googleSignInSuccess"));
    } catch (err) {
      const error2 = err instanceof Error ? err : new Error(t("login.messages.googleSignInFailed"));
      const errorMessage = getErrorMessageFromCode(error2, t, "google");
      setError(errorMessage);
      setStatusMessage(t("login.messages.googleSignInError", { error: errorMessage }));
    } finally {
      setLoadingProvider(null);
      isProcessingRef.current = false;
    }
  }, [googleSignIn, t, loadingProvider, callbackUrl]);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(AuthTranslationPreloader, {}),
    /* @__PURE__ */ jsx(
      "div",
      {
        "aria-live": "polite",
        "aria-atomic": "true",
        className: "sr-only",
        ...createTestId("login", "status", "message") && { "data-testid": createTestId("login", "status", "message") },
        children: statusMessage
      }
    ),
    /* @__PURE__ */ jsxs(
      Card,
      {
        className: "w-full max-w-md",
        "data-testid": createTestId("login", "card"),
        "data-cy": sel("auth.login.card"),
        children: [
          /* @__PURE__ */ jsxs(
            CardHeader,
            {
              className: "space-y-1",
              "data-testid": createTestId("login", "header"),
              "data-cy": sel("auth.login.header"),
              children: [
                /* @__PURE__ */ jsx(
                  CardTitle,
                  {
                    className: "text-2xl font-bold",
                    id: "login-heading",
                    role: "heading",
                    "aria-level": 1,
                    ...createTestId("login", "title") && { "data-testid": createTestId("login", "title") },
                    children: t("login.title")
                  }
                ),
                /* @__PURE__ */ jsx(
                  CardDescription,
                  {
                    ...createTestId("login", "description") && { "data-testid": createTestId("login", "description") },
                    children: t("login.description")
                  }
                )
              ]
            }
          ),
          /* @__PURE__ */ jsxs(CardContent, { children: [
            fromInvite && /* @__PURE__ */ jsxs(Alert, { className: "mb-4", "data-cy": "login-invite-banner", children: [
              /* @__PURE__ */ jsx(Users, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsx(AlertDescription, { children: t("login.inviteBanner") })
            ] }),
            isReady && lastMethod === "google" ? /* @__PURE__ */ jsx(LastUsedBadge, { text: t("login.form.lastUsed"), children: /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                size: "lg",
                onClick: handleGoogleSignIn,
                disabled: !!loadingProvider,
                className: "w-full mb-6",
                "aria-label": t("login.form.continueWithGoogleAria"),
                "data-testid": createTestId("login", "google", "button"),
                "data-cy": sel("auth.login.googleSignin"),
                children: [
                  loadingProvider === "google" ? /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin", "aria-hidden": "true" }) : /* @__PURE__ */ jsx(GoogleIcon, { className: "mr-2", "data-cy": "google-icon" }),
                  t("login.form.continueWithGoogle")
                ]
              }
            ) }) : /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                size: "lg",
                onClick: handleGoogleSignIn,
                disabled: !!loadingProvider,
                className: "w-full mb-6",
                "aria-label": t("login.form.continueWithGoogleAria"),
                "data-testid": createTestId("login", "google", "button"),
                "data-cy": sel("auth.login.googleSignin"),
                children: [
                  loadingProvider === "google" ? /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin", "aria-hidden": "true" }) : /* @__PURE__ */ jsx(GoogleIcon, { className: "mr-2", "data-cy": "google-icon" }),
                  t("login.form.continueWithGoogle")
                ]
              }
            ),
            !showEmailForm && /* @__PURE__ */ jsx("div", { className: "text-center", children: isReady && lastMethod === "email" ? /* @__PURE__ */ jsx(LastUsedBadge, { text: t("login.form.lastUsed"), children: /* @__PURE__ */ jsx(
              "button",
              {
                type: "button",
                onClick: () => setShowEmailForm(true),
                disabled: !!loadingProvider,
                className: "text-sm text-primary hover:underline focus:outline-none focus:ring-2 focus:ring-accent disabled:opacity-50 disabled:cursor-not-allowed",
                "data-testid": createTestId("login", "show-email", "button"),
                "data-cy": sel("auth.login.showEmail"),
                children: t("login.form.loginWithEmail", { defaultValue: "Sign in with Email" })
              }
            ) }) : /* @__PURE__ */ jsx(
              "button",
              {
                type: "button",
                onClick: () => setShowEmailForm(true),
                disabled: !!loadingProvider,
                className: "text-sm text-primary hover:underline focus:outline-none focus:ring-2 focus:ring-accent disabled:opacity-50 disabled:cursor-not-allowed",
                "data-testid": createTestId("login", "show-email", "button"),
                "data-cy": sel("auth.login.showEmail"),
                children: t("login.form.loginWithEmail", { defaultValue: "Sign in with Email" })
              }
            ) }),
            showEmailForm && /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsxs("div", { className: "relative my-6", children: [
                /* @__PURE__ */ jsx("div", { className: "absolute inset-0 flex items-center", children: /* @__PURE__ */ jsx(Separator, { className: "w-full" }) }),
                /* @__PURE__ */ jsx("div", { className: "relative flex justify-center text-xs uppercase", children: /* @__PURE__ */ jsx("span", { className: "bg-background px-2 text-muted-foreground", children: t("login.form.orContinueWith") }) })
              ] }),
              /* @__PURE__ */ jsxs(
                "form",
                {
                  onSubmit: handleSubmit(onSubmit),
                  className: "space-y-4",
                  "aria-labelledby": "login-heading",
                  "data-testid": createTestId("login", "form"),
                  "data-cy": sel("auth.login.form"),
                  children: [
                    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                      /* @__PURE__ */ jsx(
                        Label,
                        {
                          htmlFor: "email",
                          ...createTestId("login", "email", "label") && { "data-testid": createTestId("login", "email", "label") },
                          children: t("login.form.email")
                        }
                      ),
                      /* @__PURE__ */ jsxs("div", { className: "relative", children: [
                        /* @__PURE__ */ jsx(Mail, { className: "absolute left-3 top-3 h-4 w-4 text-muted-foreground", "aria-hidden": "true" }),
                        /* @__PURE__ */ jsx(
                          Input,
                          {
                            ...register("email"),
                            id: "email",
                            type: "email",
                            autoComplete: "email",
                            placeholder: t("login.form.emailPlaceholder"),
                            className: `pl-9 ${fromInvite ? "bg-muted cursor-not-allowed" : ""}`,
                            readOnly: fromInvite,
                            "aria-required": "true",
                            "aria-describedby": errors.email ? "email-error" : void 0,
                            "aria-invalid": errors.email ? "true" : "false",
                            "data-testid": createTestId("login", "email", "input"),
                            "data-cy": sel("auth.login.emailInput")
                          }
                        )
                      ] }),
                      errors.email && /* @__PURE__ */ jsx(
                        "p",
                        {
                          id: "email-error",
                          className: "text-sm text-destructive",
                          role: "alert",
                          "aria-live": "assertive",
                          "data-testid": createTestId("login", "email", "error"),
                          "data-cy": sel("auth.login.emailError"),
                          children: errors.email.message
                        }
                      )
                    ] }),
                    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                      /* @__PURE__ */ jsx(
                        Label,
                        {
                          htmlFor: "password",
                          ...createTestId("login", "password", "label") && { "data-testid": createTestId("login", "password", "label") },
                          children: t("login.form.password")
                        }
                      ),
                      /* @__PURE__ */ jsxs("div", { className: "relative", children: [
                        /* @__PURE__ */ jsx(Lock, { className: "absolute left-3 top-3 h-4 w-4 text-muted-foreground", "aria-hidden": "true" }),
                        /* @__PURE__ */ jsx(
                          Input,
                          {
                            ...register("password"),
                            id: "password",
                            type: "password",
                            autoComplete: "current-password",
                            placeholder: t("login.form.passwordPlaceholder"),
                            className: "pl-9",
                            "aria-required": "true",
                            "aria-describedby": errors.password ? "password-error" : void 0,
                            "aria-invalid": errors.password ? "true" : "false",
                            "data-testid": createTestId("login", "password", "input"),
                            "data-cy": sel("auth.login.passwordInput")
                          }
                        )
                      ] }),
                      errors.password && /* @__PURE__ */ jsx(
                        "p",
                        {
                          id: "password-error",
                          className: "text-sm text-destructive",
                          role: "alert",
                          "aria-live": "assertive",
                          "data-testid": createTestId("login", "password", "error"),
                          "data-cy": sel("auth.login.passwordError"),
                          children: errors.password.message
                        }
                      )
                    ] }),
                    error && /* @__PURE__ */ jsxs(
                      Alert,
                      {
                        variant: "destructive",
                        role: "alert",
                        "aria-live": "assertive",
                        "data-testid": createTestId("login", "error", "alert"),
                        "data-cy": sel("auth.login.errorAlert"),
                        children: [
                          /* @__PURE__ */ jsx(AlertCircle, { className: "h-4 w-4", "aria-hidden": "true" }),
                          /* @__PURE__ */ jsx(AlertDescription, { children: error })
                        ]
                      }
                    ),
                    /* @__PURE__ */ jsxs(
                      "div",
                      {
                        className: "flex items-center justify-between",
                        "data-testid": createTestId("login", "options", "section"),
                        "data-cy": sel("auth.login.options"),
                        children: [
                          /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2", children: [
                            /* @__PURE__ */ jsx(
                              Checkbox,
                              {
                                id: "remember",
                                "data-testid": createTestId("login", "remember", "checkbox"),
                                "data-cy": sel("auth.login.rememberCheckbox")
                              }
                            ),
                            /* @__PURE__ */ jsx(
                              Label,
                              {
                                htmlFor: "remember",
                                className: "text-sm font-normal cursor-pointer",
                                ...createTestId("login", "remember", "label") && { "data-testid": createTestId("login", "remember", "label") },
                                children: t("login.form.rememberMe")
                              }
                            )
                          ] }),
                          /* @__PURE__ */ jsx(
                            Link,
                            {
                              href: "/forgot-password",
                              className: "text-sm text-primary hover:underline focus:outline-none focus:ring-2 focus:ring-accent",
                              "aria-label": t("login.form.forgotPasswordAria"),
                              "data-testid": createTestId("login", "forgot", "link"),
                              "data-cy": sel("auth.login.forgotPassword"),
                              children: t("login.form.forgotPassword")
                            }
                          )
                        ]
                      }
                    ),
                    /* @__PURE__ */ jsx(
                      Button,
                      {
                        type: "submit",
                        disabled: !!loadingProvider,
                        className: "w-full",
                        "aria-describedby": "submit-help",
                        "data-testid": createTestId("login", "submit", "button"),
                        "data-cy": sel("auth.login.submit"),
                        children: loadingProvider === "email" ? /* @__PURE__ */ jsxs(Fragment, { children: [
                          /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin", "aria-hidden": "true" }),
                          t("login.form.signingIn")
                        ] }) : t("login.form.signInButton")
                      }
                    ),
                    /* @__PURE__ */ jsx("div", { id: "submit-help", className: "sr-only", children: t("login.form.submitHelp") }),
                    /* @__PURE__ */ jsx("div", { className: "text-center mt-4", children: /* @__PURE__ */ jsx(
                      "button",
                      {
                        type: "button",
                        onClick: () => setShowEmailForm(false),
                        className: "text-sm text-muted-foreground hover:text-primary focus:outline-none focus:ring-2 focus:ring-accent",
                        "data-testid": createTestId("login", "hide-email", "button"),
                        "data-cy": sel("auth.login.hideEmail"),
                        children: t("login.form.backToGoogle", { defaultValue: "Back to main options" })
                      }
                    ) })
                  ]
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsx(
            CardFooter,
            {
              "data-testid": createTestId("login", "footer"),
              "data-cy": sel("auth.login.footer"),
              children: /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground text-center w-full", children: [
                t("login.footer.noAccount"),
                " ",
                /* @__PURE__ */ jsx(
                  Link,
                  {
                    href: "/signup",
                    className: "text-primary hover:underline font-medium focus:outline-none focus:ring-2 focus:ring-accent",
                    "aria-label": t("login.footer.signUpAria"),
                    "data-testid": createTestId("login", "signup", "link"),
                    "data-cy": sel("auth.login.signupLink"),
                    children: t("login.footer.signUp")
                  }
                )
              ] })
            }
          )
        ]
      }
    ),
    ((_a = DEV_CONFIG) == null ? void 0 : _a.devKeyring) && /* @__PURE__ */ jsx(DevKeyring, { config: DEV_CONFIG.devKeyring })
  ] });
}
export {
  LoginForm
};
