"use client";
import { jsx } from "react/jsx-runtime";
import * as React from "react";
import { cn } from "@open-mercato/shared/lib/utils";
const DigitInput = React.forwardRef(
  ({
    value: valueProp,
    onChange,
    length = 6,
    disabled = false,
    autoFocus = false,
    inputMode = "numeric",
    mask = false,
    onComplete,
    className,
    cellClassName,
    "aria-label": ariaLabel,
    "aria-invalid": ariaInvalid,
    id,
    name
  }, ref) => {
    const [internalValue, setInternalValue] = React.useState("");
    const isControlled = valueProp !== void 0;
    const value = isControlled ? valueProp ?? "" : internalValue;
    const cellRefs = React.useRef([]);
    React.useImperativeHandle(
      ref,
      () => cellRefs.current[0] ?? null,
      []
    );
    const setCellRef = React.useCallback(
      (index) => (el) => {
        cellRefs.current[index] = el;
      },
      []
    );
    const commitValue = React.useCallback(
      (next) => {
        const clamped = next.slice(0, length);
        if (!isControlled) setInternalValue(clamped);
        onChange?.(clamped);
        if (clamped.length === length && onComplete) onComplete(clamped);
      },
      [isControlled, length, onChange, onComplete]
    );
    const filterChar = React.useCallback(
      (char) => {
        if (inputMode === "numeric" && !/^\d$/.test(char)) return null;
        return char;
      },
      [inputMode]
    );
    const focusCell = React.useCallback(
      (index) => {
        const target = cellRefs.current[Math.max(0, Math.min(length - 1, index))];
        if (target) target.focus();
      },
      [length]
    );
    const handleCellChange = React.useCallback(
      (index, raw) => {
        if (raw.length === 0) {
          const next2 = value.slice(0, index) + value.slice(index + 1);
          commitValue(next2);
          return;
        }
        const lastChar = raw.slice(-1);
        const filtered = filterChar(lastChar);
        if (filtered === null) return;
        const next = value.slice(0, index) + filtered + value.slice(index + 1);
        commitValue(next);
        if (index < length - 1) focusCell(index + 1);
      },
      [commitValue, filterChar, focusCell, length, value]
    );
    const handleKeyDown = React.useCallback(
      (index) => (event) => {
        if (event.key === "Backspace") {
          if (event.currentTarget.value === "" && index > 0) {
            event.preventDefault();
            const next = value.slice(0, index - 1) + value.slice(index);
            commitValue(next);
            focusCell(index - 1);
          }
        } else if (event.key === "ArrowLeft" && index > 0) {
          event.preventDefault();
          focusCell(index - 1);
        } else if (event.key === "ArrowRight" && index < length - 1) {
          event.preventDefault();
          focusCell(index + 1);
        }
      },
      [commitValue, focusCell, length, value]
    );
    const handlePaste = React.useCallback(
      (event) => {
        event.preventDefault();
        const pasted = event.clipboardData.getData("text/plain");
        const filtered = pasted.split("").map(filterChar).filter((c) => c !== null).join("").slice(0, length);
        if (filtered.length === 0) return;
        commitValue(filtered);
        const focusIndex = Math.min(filtered.length, length - 1);
        focusCell(focusIndex);
      },
      [commitValue, filterChar, focusCell, length]
    );
    return /* @__PURE__ */ jsx(
      "div",
      {
        className: cn("flex items-center gap-2", className),
        role: "group",
        "aria-label": ariaLabel ?? "Verification code",
        "aria-invalid": ariaInvalid || void 0,
        "data-slot": "digit-input",
        children: Array.from({ length }, (_, index) => {
          const cellValue = value[index] ?? "";
          return /* @__PURE__ */ jsx(
            "input",
            {
              ref: setCellRef(index),
              id: index === 0 ? id : void 0,
              name: index === 0 ? name : void 0,
              type: mask ? "password" : "text",
              inputMode: inputMode === "numeric" ? "numeric" : "text",
              autoComplete: "one-time-code",
              maxLength: 1,
              autoFocus: autoFocus && index === 0,
              value: cellValue,
              onChange: (event) => handleCellChange(index, event.target.value),
              onKeyDown: handleKeyDown(index),
              onPaste: handlePaste,
              disabled,
              "aria-label": `${ariaLabel ?? "Verification code"} digit ${index + 1}`,
              "aria-invalid": ariaInvalid || void 0,
              "data-slot": "digit-input-cell",
              "data-index": index,
              className: cn(
                "h-16 w-12 sm:w-14 rounded-[10px] border border-input bg-background text-center text-2xl font-medium shadow-xs transition-colors",
                "focus:outline-none focus-visible:border-foreground focus-visible:shadow-focus",
                "aria-[invalid=true]:border-destructive aria-[invalid=true]:focus-visible:border-destructive",
                "disabled:cursor-not-allowed disabled:bg-bg-disabled disabled:border-border-disabled disabled:shadow-none",
                "hover:bg-muted/40",
                cellClassName
              )
            },
            index
          );
        })
      }
    );
  }
);
DigitInput.displayName = "DigitInput";
export {
  DigitInput
};
//# sourceMappingURL=digit-input.js.map
