/**
 * InputOTP — shadcn/WealthX
 * Base: npx shadcn\@latest add input-otp
 * Figma: https://www.figma.com/design/9V9F0NGVsif8LGmEhVjOcT/Design-System---shadcn?node-id=101-698
 *
 * WealthX overrides:
 *   - InputOTPSlot: removed first:rounded-l-md last:rounded-r-md — sharp corners (radius-none)
 */

import { type ReactElement } from "react";
import * as React from "react";
import { OTPInput, OTPInputContext } from "input-otp";
import { MinusIcon } from "lucide-react";
import { cn } from "@/lib/utils";

export type InputOTPProps = React.ComponentProps<typeof OTPInput> & {
  containerClassName?: string;
};

function InputOTP({
  className,
  containerClassName,
  ...props
}: InputOTPProps): ReactElement {
  return (
    <OTPInput
      className={cn("disabled:cursor-not-allowed", className)}
      containerClassName={cn(
        "flex items-center gap-2 has-disabled:opacity-50",
        containerClassName,
      )}
      data-slot="input-otp"
      {...props}
    />
  );
}

export type InputOTPGroupProps = React.ComponentProps<"div">;

function InputOTPGroup({
  className,
  ...props
}: InputOTPGroupProps): ReactElement {
  return (
    <div
      className={cn("flex items-center", className)}
      data-slot="input-otp-group"
      {...props}
    />
  );
}

export type InputOTPSlotProps = React.ComponentProps<"div"> & {
  index: number;
};

function InputOTPSlot({
  index,
  className,
  ...props
}: InputOTPSlotProps): ReactElement {
  const inputOTPContext = React.useContext(OTPInputContext);
  const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index] ?? {};

  return (
    <div
      className={cn(
        "relative flex h-9 w-9 items-center justify-center border-y border-r border-input text-body-small shadow-xs transition-all outline-none first:border-l aria-invalid:border-destructive data-[active=true]:z-10 data-[active=true]:border-ring data-[active=true]:ring-[3px] data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:border-destructive data-[active=true]:aria-invalid:ring-destructive/20 dark:bg-input/30 dark:data-[active=true]:aria-invalid:ring-destructive/40",
        className,
      )}
      data-active={isActive}
      data-slot="input-otp-slot"
      {...props}
    >
      {char}
      {hasFakeCaret ? (
        <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
          <div className="h-4 w-px animate-caret-blink bg-foreground duration-1000" />
        </div>
      ) : null}
    </div>
  );
}

export type InputOTPSeparatorProps = React.ComponentProps<"div">;

function InputOTPSeparator({ ...props }: InputOTPSeparatorProps): ReactElement {
  return (
    <div data-slot="input-otp-separator" role="separator" {...props}>
      <MinusIcon />
    </div>
  );
}

export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };
