import{jsx as b}from"react/jsx-runtime";import{TextInput as W}from"./text-input.js";import{css as k}from"@styled/css";import{useState as B,useRef as D,useEffect as A,useCallback as g}from"react";const v=/\D/g,I=({pinLength:o,onComplete:T=i=>i,onChange:h=i=>i,originName:$,id:p="pin-code-input",autoFocus:y=!0})=>{const[i,C]=B(()=>Array.from({length:o},()=>"")),u=D(Array(o).fill(null));A(()=>{C(e=>o<e.length?e.slice(0,o):o>e.length?[...e,...Array(o-e.length).fill("")]:e)},[o]),A(()=>{var e;y&&u.current[0]&&((e=u.current[0])===null||e===void 0||e.focus())},[y,o]);const d=(e,n)=>{var r;C(n),h(n);const t=n.join("");t.length===o&&((r=u.current[e])===null||r===void 0||r.blur(),T(t))},j=g((e,n)=>{const r=[...i];n.replace(v,"").split("").forEach(t=>{var a,c;e>=o||(r[e]=t,e++,(c=(a=u?.current)===null||a===void 0?void 0:a[e])===null||c===void 0||c.focus())}),d(e,r)},[i,d]),N=g(e=>{var n,r;const t=parseInt(e.currentTarget.dataset.id||"",10),a=e.target.value.replace(v,"");if(a.length>1)return j(t,a);const c=[...i];c[t]=a,a.length&&((r=(n=u?.current)===null||n===void 0?void 0:n[t+1])===null||r===void 0||r.focus()),d(t,c)},[d]),R=g(e=>{var n,r,t,a,c;const x=e.currentTarget.value.length,s=parseInt(e.currentTarget.dataset.id||"",10),f=[...i];switch(e.key){case"Backspace":{if(x&&(f[s]="",d(s,f)),s){const l=f.reduceRight((m,E,L)=>m!==-1?m:E!==""?L:m,-1);(n=u?.current[l>=0?l:0])===null||n===void 0||n.focus()}return}case"ArrowLeft":{const l=s?s-1:o-1;(r=u?.current[l])===null||r===void 0||r.focus();return}case"ArrowRight":{const l=s===o-1?0:s+1;(t=u?.current[l])===null||t===void 0||t.focus();return}default:{const l=e.key.replace(v,"");x&&l.length&&l!==e.currentTarget.value&&(f[s]=l,d(s,f),(c=(a=u?.current)===null||a===void 0?void 0:a[s+1])===null||c===void 0||c.focus())}}},[h,d]),w=$?`${$} `:"";return b("form",{id:p,className:k({margin:0,minWidth:0,display:"flex",width:"100%",justifyContent:"space-between",maxWidth:"30rem",gap:2}),children:i.map((e,n)=>b(W.Char,{id:p?`${p}-${n}`:void 0,"aria-label":`${w}one time password input ${n+1}`,"data-id":n,name:`${w}one time password input ${n+1}`,value:i[n]||"",className:k({caretColor:"transparent"}),attr:{onChange:N,onKeyUp:R,autoComplete:n===0?"one-time-code":"off",inputMode:"numeric"},ref:r=>{u?.current&&(u.current[n]=r)}},`${p||void 0}-${n}`))})};export{I as PinCodeInput,I as default};
//# sourceMappingURL=pincode-input.js.map
