import { toWesternDigits } from "@/lib/digits";

/**
 * The one-time-code field's pure rules.
 *
 * Pulled out of `EmailVerificationForm` because pasting is where these fields
 * usually break: a code copied out of an email arrives with spaces, dashes or a
 * trailing newline, and it can be pasted into the middle box rather than the
 * first one.
 */
export const OTP_LENGTH = 6;

export type OtpValues = {
  otp1: string;
  otp2: string;
  otp3: string;
  otp4: string;
  otp5: string;
  otp6: string;
};

export const EMPTY_OTP: OtpValues = {
  otp1: "",
  otp2: "",
  otp3: "",
  otp4: "",
  otp5: "",
  otp6: "",
};

/**
 * One box holds one digit; anything else the user types is dropped.
 * Arabic-Indic digits («٠١٢…», an Arabic keyboard's) are converted first —
 * they used to be dropped, so a code typed or pasted in Arabic never filled.
 */
export const digitsOnly = (raw: string) => toWesternDigits(raw).replace(/[^0-9]/g, "");

/**
 * The digits to distribute from a paste, never more than the field holds.
 *
 * Always filled from box 1 regardless of which box received the paste — a code
 * pasted into the third box is still the whole code, not its tail.
 */
export const parsePastedOtp = (pasted: string) =>
  [...digitsOnly(pasted).slice(0, OTP_LENGTH)];

/**
 * Where the caret lands after a paste: the box after the last one filled,
 * clamped to the last box.
 */
export const nextFocusIndex = (index: number, pastedLength: number) =>
  Math.min(index + pastedLength, OTP_LENGTH - 1);

/** True when every box holds something — whitespace does not count. */
export const isOtpComplete = (values: OtpValues) =>
  !Object.values(values).some((digit) => digit.trim() === "");

/** The assembled code, in box order. */
export const buildOtpString = (values: OtpValues) =>
  Object.values(values).join("");
