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