"use client";
import * as React4 from 'react';
import { cva } from 'class-variance-authority';
import { clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { OTPInput, OTPInputContext } from 'input-otp';
import { Slot } from '@radix-ui/react-slot';

function cn(...inputs) {
  return twMerge(clsx(inputs));
}
var alertVariants = cva(
  [
    "relative w-full rounded-lg border px-[var(--space-4,1rem)] py-[var(--space-3,0.75rem)] text-sm",
    "transition-all duration-[var(--duration-normal,200ms)] ease-out",
    "[&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:h-4 [&>svg]:w-4 [&>svg]:text-foreground",
    "[&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px]"
  ].join(" "),
  {
    variants: {
      variant: {
        default: "border-foreground/[0.08] bg-background text-foreground",
        destructive: "border-destructive/50 text-destructive [&>svg]:text-destructive bg-destructive/5"
      }
    },
    defaultVariants: { variant: "default" }
  }
);
var Alert = React4.forwardRef(({ className, variant, ...props }, ref) => /* @__PURE__ */ jsx(
  "div",
  {
    ref,
    role: "alert",
    className: cn(alertVariants({ variant }), className),
    ...props
  }
));
Alert.displayName = "Alert";
var AlertTitle = React4.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
  "h5",
  {
    ref,
    className: cn("mb-[var(--space-1,0.25rem)] font-medium leading-none tracking-tight", className),
    ...props
  }
));
AlertTitle.displayName = "AlertTitle";
var AlertDescription = React4.forwardRef(
  ({ className, ...props }, ref) => /* @__PURE__ */ jsx("div", { ref, className: cn("text-sm [&_p]:leading-relaxed", className), ...props })
);
AlertDescription.displayName = "AlertDescription";
var InputOTP = React4.forwardRef(
  ({ className, containerClassName, ...props }, ref) => /* @__PURE__ */ jsx(
    OTPInput,
    {
      ref,
      containerClassName: cn(
        "flex items-center gap-[var(--gap-sm,0.5rem)] has-[:disabled]:opacity-50",
        containerClassName
      ),
      className: cn(
        "disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",
        className
      ),
      ...props
    }
  )
);
InputOTP.displayName = "InputOTP";
var InputOTPGroup = React4.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx("div", { ref, className: cn("flex items-center", className), ...props }));
InputOTPGroup.displayName = "InputOTPGroup";
var InputOTPSlot = React4.forwardRef(
  ({ index, className, ...props }, ref) => {
    const inputOTPContext = React4.useContext(OTPInputContext);
    const slot = inputOTPContext.slots[index];
    const char = slot?.char ?? null;
    const hasFakeCaret = slot?.hasFakeCaret ?? false;
    const isActive = slot?.isActive ?? false;
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: cn(
          "relative flex h-[var(--control-height-md,2.5rem)] w-[var(--control-height-md,2.5rem)] items-center justify-center border-y border-r border-input text-sm transition-all duration-[var(--duration-normal,200ms)] ease-out",
          "inset-ring-1 inset-ring-foreground/[0.06]",
          "first:rounded-l-md first:border-l last:rounded-r-md",
          isActive && "z-10 ring-2 ring-ring ring-offset-2 ring-offset-background",
          className
        ),
        ...props,
        children: [
          char,
          hasFakeCaret && /* @__PURE__ */ jsx("div", { className: "pointer-events-none absolute inset-0 flex items-center justify-center", children: /* @__PURE__ */ jsx("div", { className: "h-4 w-px animate-pulse bg-foreground duration-1000" }) })
        ]
      }
    );
  }
);
InputOTPSlot.displayName = "InputOTPSlot";
var InputOTPSeparator = React4.forwardRef(({ ...props }, ref) => /* @__PURE__ */ jsx("div", { ref, role: "separator", ...props, children: /* @__PURE__ */ jsx(
  "svg",
  {
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 24 24",
    fill: "currentColor",
    className: "h-2 w-2 text-muted-foreground",
    "aria-hidden": "true",
    children: /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "6" })
  }
) }));
InputOTPSeparator.displayName = "InputOTPSeparator";
var buttonVariants = cva(
  [
    "inline-flex items-center justify-center gap-[var(--gap-sm,0.5rem)] whitespace-nowrap rounded-md text-sm font-medium",
    "transition-all duration-[var(--duration-normal,200ms)] ease-out",
    "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
    "disabled:pointer-events-none disabled:opacity-50",
    "active:scale-[0.98]",
    "[&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0"
  ].join(" "),
  {
    variants: {
      variant: {
        default: [
          "bg-primary text-primary-foreground",
          "shadow-sm shadow-primary/20",
          "hover:bg-primary/90 hover:shadow-md hover:shadow-primary/25"
        ].join(" "),
        destructive: [
          "bg-destructive text-destructive-foreground",
          "shadow-sm shadow-destructive/20",
          "hover:bg-destructive/90 hover:shadow-md hover:shadow-destructive/25"
        ].join(" "),
        outline: [
          "border border-input bg-background",
          "shadow-sm inset-ring-1 inset-ring-foreground/[0.06]",
          "hover:bg-accent hover:text-accent-foreground hover:shadow-md hover:inset-ring-foreground/12"
        ].join(" "),
        secondary: [
          "bg-secondary text-secondary-foreground",
          "shadow-sm inset-ring-1 inset-ring-foreground/[0.08]",
          "hover:bg-secondary/80 hover:shadow-md hover:inset-ring-foreground/15"
        ].join(" "),
        ghost: "hover:bg-accent hover:text-accent-foreground",
        link: "text-primary underline-offset-4 hover:underline"
      },
      size: {
        default: "h-[var(--control-height-md,2.5rem)] px-[var(--space-4,1rem)] py-[var(--space-2,0.5rem)]",
        sm: "h-[var(--control-height-sm,2.25rem)] rounded-md px-[var(--space-3,0.75rem)]",
        lg: "h-[var(--control-height-lg,2.75rem)] rounded-md px-[var(--space-8,2rem)] text-base",
        icon: "h-[var(--control-height-md,2.5rem)] w-[var(--control-height-md,2.5rem)]"
      }
    },
    defaultVariants: {
      variant: "default",
      size: "default"
    }
  }
);
var Button = React4.forwardRef(
  ({ className, variant, size, asChild = false, loading = false, children, disabled, ...props }, ref) => {
    const Comp = asChild ? Slot : "button";
    return /* @__PURE__ */ jsx(
      Comp,
      {
        className: cn(buttonVariants({ variant, size, className })),
        ref,
        disabled: disabled || loading,
        "aria-busy": loading || void 0,
        ...props,
        children: loading ? /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsxs(
            "svg",
            {
              className: "animate-spin h-4 w-4",
              xmlns: "http://www.w3.org/2000/svg",
              fill: "none",
              viewBox: "0 0 24 24",
              "aria-hidden": "true",
              children: [
                /* @__PURE__ */ jsx(
                  "circle",
                  {
                    className: "opacity-25",
                    cx: "12",
                    cy: "12",
                    r: "10",
                    stroke: "currentColor",
                    strokeWidth: "4"
                  }
                ),
                /* @__PURE__ */ jsx(
                  "path",
                  {
                    className: "opacity-75",
                    fill: "currentColor",
                    d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                  }
                )
              ]
            }
          ),
          children
        ] }) : children
      }
    );
  }
);
Button.displayName = "Button";
var HEADINGS = {
  "sign-in": {
    title: "Enter your sign-in code",
    description: "We sent a 6-digit code to your email or phone. Enter it below to sign in."
  },
  "verify-email": {
    title: "Verify your email",
    description: "Enter the 6-digit code we sent to confirm your email address."
  },
  mfa: {
    title: "Two-factor authentication",
    description: "Enter the 6-digit code from your authenticator app."
  }
};
function AuthVerifyOtp({
  adapter,
  intent,
  length = 6,
  resendCooldownSeconds = 30,
  className,
  onSuccess
}) {
  const [code, setCode] = React4.useState("");
  const [submitting, setSubmitting] = React4.useState(false);
  const [resending, setResending] = React4.useState(false);
  const [cooldownLeft, setCooldownLeft] = React4.useState(0);
  const [error, setError] = React4.useState(null);
  const lastSubmittedRef = React4.useRef("");
  React4.useEffect(() => {
    if (cooldownLeft <= 0) return;
    const timer = setTimeout(() => setCooldownLeft((s) => s - 1), 1e3);
    return () => clearTimeout(timer);
  }, [cooldownLeft]);
  const handleSubmit = React4.useCallback(
    async (codeToSubmit) => {
      if (!adapter.verifyOtp) {
        console.warn(
          "[AuthVerifyOtp] adapter.verifyOtp is not implemented \u2014 wire it up before exposing the form."
        );
        setError({
          code: "unimplemented",
          message: "Verification is currently unavailable. Please try again later."
        });
        return;
      }
      setError(null);
      setSubmitting(true);
      try {
        const result = await adapter.verifyOtp({ code: codeToSubmit, intent });
        if (!result.ok) {
          setError(
            result.error ?? { code: "unknown", message: "Couldn't verify code." }
          );
          setCode("");
          lastSubmittedRef.current = "";
          return;
        }
        onSuccess?.(result.redirect);
      } finally {
        setSubmitting(false);
      }
    },
    [adapter, intent, onSuccess]
  );
  React4.useEffect(() => {
    if (code.length !== length) return;
    if (submitting) return;
    if (lastSubmittedRef.current === code) return;
    lastSubmittedRef.current = code;
    void handleSubmit(code);
  }, [code, length, submitting, handleSubmit]);
  async function handleResend() {
    if (!adapter.resendOtp) {
      console.warn(
        "[AuthVerifyOtp] adapter.resendOtp is not implemented \u2014 hide the resend button or wire the method."
      );
      setError({
        code: "unimplemented",
        message: "Resending is currently unavailable. Please try again later."
      });
      return;
    }
    setError(null);
    setResending(true);
    try {
      const result = await adapter.resendOtp({ intent });
      if (!result.ok) {
        setError(result.error ?? { code: "unknown", message: "Couldn't resend code." });
        return;
      }
      setCooldownLeft(resendCooldownSeconds);
      setCode("");
    } finally {
      setResending(false);
    }
  }
  const heading = HEADINGS[intent];
  const slots = React4.useMemo(
    () => Array.from({ length }, (_, i) => i),
    [length]
  );
  const cooldownLabel = cooldownLeft > 0 ? `Resend in ${cooldownLeft}s` : "Resend code";
  return /* @__PURE__ */ jsx("div", { className: cn("flex min-h-svh items-center justify-center p-6 sm:p-10", className), children: /* @__PURE__ */ jsxs("div", { className: "w-full max-w-sm space-y-6", children: [
    /* @__PURE__ */ jsxs("header", { className: "space-y-2 text-center", children: [
      /* @__PURE__ */ jsx("h1", { className: "text-2xl font-semibold tracking-tight", children: heading.title }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: heading.description })
    ] }),
    error ? /* @__PURE__ */ jsxs(Alert, { variant: "destructive", children: [
      /* @__PURE__ */ jsx(AlertTitle, { children: "Couldn\u2019t verify code" }),
      /* @__PURE__ */ jsx(AlertDescription, { children: error.message })
    ] }) : null,
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-4", children: [
      /* @__PURE__ */ jsx(
        InputOTP,
        {
          maxLength: length,
          value: code,
          onChange: setCode,
          disabled: submitting,
          "aria-label": "One-time code",
          children: /* @__PURE__ */ jsx(InputOTPGroup, { children: slots.map((i) => /* @__PURE__ */ jsx(InputOTPSlot, { index: i }, i)) })
        }
      ),
      adapter.resendOtp ? /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: "ghost",
          size: "sm",
          onClick: handleResend,
          disabled: resending || cooldownLeft > 0 || submitting,
          loading: resending,
          children: cooldownLabel
        }
      ) : null
    ] })
  ] }) });
}

export { AuthVerifyOtp };
//# sourceMappingURL=auth-verify-otp.js.map
//# sourceMappingURL=auth-verify-otp.js.map