import React from "react";

export function OTPField({ length = 6, size = "default", groupAfter = 3, value, defaultValue = "", onValueChange, className = "" }) {
  const [internal, setInternal] = React.useState(defaultValue);
  const val = value !== undefined ? value : internal;
  const refs = React.useRef([]);
  const setAt = (i, ch) => {
    const chars = val.padEnd(length, " ").split("");
    chars[i] = ch || " ";
    const next = chars.join("").replace(/\s+$/, "");
    if (value === undefined) setInternal(next);
    if (onValueChange) onValueChange(next.trim());
    if (ch && refs.current[i + 1]) refs.current[i + 1].focus();
  };
  const cells = [];
  for (let i = 0; i < length; i++) {
    cells.push(
      <input key={i} ref={(el) => { refs.current[i] = el; }} className="o-otp__input" data-slot="otp-field-input" inputMode="numeric" maxLength={1}
        value={(val[i] || "").trim()} onChange={(e) => setAt(i, e.target.value.slice(-1))} aria-label={"Digit " + (i + 1)} />
    );
    if (groupAfter && i === groupAfter - 1 && i < length - 1) cells.push(<span key={"sep" + i} className="o-otp__separator" data-slot="otp-field-separator" />);
  }
  return <div className={["o-otp", size === "lg" ? "o-otp--lg" : "", className].filter(Boolean).join(" ")} data-slot="otp-field" data-size={size}>{cells}</div>;
}
