iq-line-form-builder-renderer 1.1.70 → 1.1.71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/form-renderer.es.js
CHANGED
|
@@ -20855,7 +20855,7 @@ const UT = ({
|
|
|
20855
20855
|
N || $(!1);
|
|
20856
20856
|
}
|
|
20857
20857
|
};
|
|
20858
|
-
if (B
|
|
20858
|
+
if (B)
|
|
20859
20859
|
return /* @__PURE__ */ p("div", { className: "flex items-center justify-center py-12", children: /* @__PURE__ */ p(Xu, {}) });
|
|
20860
20860
|
if (!dt)
|
|
20861
20861
|
return /* @__PURE__ */ p("div", { className: "text-center py-12 text-muted-foreground", children: "Form not found" });
|
|
@@ -21683,7 +21683,7 @@ const UT = ({
|
|
|
21683
21683
|
style: Ao,
|
|
21684
21684
|
"data-form-renderer": A ? void 0 : "root",
|
|
21685
21685
|
children: /* @__PURE__ */ G("div", { className: "relative", children: [
|
|
21686
|
-
V && /* @__PURE__ */ p("div", { className: "absolute inset-0 z-10 flex items-center justify-center bg-background/60 rounded-md", children: /* @__PURE__ */ p(Xu, {}) }),
|
|
21686
|
+
(V || be) && /* @__PURE__ */ p("div", { className: "absolute inset-0 z-10 flex items-center justify-center bg-background/60 rounded-md", children: /* @__PURE__ */ p(Xu, {}) }),
|
|
21687
21687
|
/* @__PURE__ */ G(
|
|
21688
21688
|
"form",
|
|
21689
21689
|
{
|
|
@@ -49,4 +49,4 @@ If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHid
|
|
|
49
49
|
|
|
50
50
|
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return y.useEffect(()=>{e&&(document.getElementById(e)||console.error(r))},[r,e]),null},nC="DialogDescriptionWarning",oC=({contentRef:e,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${fm(nC).contentName}}.`;return y.useEffect(()=>{const o=e.current?.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(n))},[n,e,t]),null},sC=em,iC=nm,aC=om,lC=sm,cC=am,dC=dm;function uC({...e}){return u.jsx(sC,{"data-slot":"dialog",...e})}function fC({...e}){return u.jsx(iC,{"data-slot":"dialog-portal",...e})}function pC({className:e,...t}){return u.jsx(aC,{"data-slot":"dialog-overlay",className:W("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function mC({className:e,children:t,showCloseButton:r=!0,...n}){return u.jsxs(fC,{"data-slot":"dialog-portal",children:[u.jsx(pC,{}),u.jsxs(lC,{"data-slot":"dialog-content",className:W("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...n,children:[t,r&&u.jsxs(dC,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[u.jsx(Fo,{}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function hC({className:e,...t}){return u.jsx("div",{"data-slot":"dialog-header",className:W("flex flex-col gap-2 text-center sm:text-left",e),...t})}function gC({className:e,...t}){return u.jsx("div",{"data-slot":"dialog-footer",className:W("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function yC({className:e,...t}){return u.jsx(cC,{"data-slot":"dialog-title",className:W("text-lg leading-none font-semibold",e),...t})}async function bC(){const e={width:{ideal:1280},height:{ideal:720}},t=[{facingMode:{ideal:"environment"},...e},{facingMode:{ideal:"user"},...e},{...e},{}];let r;for(const n of t)try{return await navigator.mediaDevices.getUserMedia({video:Object.keys(n).length>0?n:!0,audio:!1})}catch(o){r=o}throw r instanceof Error?r:new Error("Could not access camera")}function pm(e){const t=()=>e.play();t().catch(()=>{requestAnimationFrame(()=>{t().catch(()=>{const r=()=>{t().catch(()=>{})};e.addEventListener("loadedmetadata",r,{once:!0}),e.addEventListener("canplay",r,{once:!0})})})})}const mm=({open:e,onOpenChange:t,onCaptured:r,validateFile:n,accept:o,disabled:s,onValidationMessage:i})=>{const a=S.useRef(null),d=S.useRef(null),c=S.useRef(null),l=S.useRef(null),[f,p]=S.useState(null),[m,b]=S.useState(!1),h=S.useCallback(()=>{a.current&&(a.current.srcObject=null)},[]),g=S.useCallback(()=>{c.current&&(c.current.getTracks().forEach(T=>T.stop()),c.current=null),h()},[h]);S.useEffect(()=>{if(!e){g(),p(null),b(!1);return}if(s)return;let T=!1;return p(null),b(!0),bC().then(C=>{if(T){C.getTracks().forEach(_=>_.stop());return}c.current=C,b(!1)}).catch(C=>{if(T)return;b(!1);const _=C instanceof Error?C.message:"Could not access camera";p(_)}),()=>{T=!0,c.current&&(c.current.getTracks().forEach(C=>C.stop()),c.current=null),h()}},[e,s,g,h]);const w=S.useCallback(T=>{a.current=T,T&&c.current&&e&&!f&&!m&&(T.srcObject=c.current,pm(T))},[e,f,m]);S.useLayoutEffect(()=>{if(!e||f||m||!c.current)return;let T=!1,C=0;const _=()=>{if(T)return;const O=a.current;!O||!c.current||(O.srcObject=c.current,pm(O))};_();const E=requestAnimationFrame(()=>{_(),C=requestAnimationFrame(_)});return()=>{T=!0,cancelAnimationFrame(E),cancelAnimationFrame(C),h()}},[e,f,m,h]);const v=S.useCallback(()=>{g(),p(null),b(!1),t(!1),l.current&&(l.current.value="")},[g,t]),x=S.useCallback(()=>{const T=a.current,C=d.current;if(!T||!C||!c.current||T.readyState<2)return;const _=T.videoWidth,E=T.videoHeight;if(_===0||E===0)return;C.width=_,C.height=E;const O=C.getContext("2d");O&&(O.drawImage(T,0,0),C.toBlob(N=>{if(!N)return;const j=new File([N],`camera-capture-${Date.now()}.jpg`,{type:"image/jpeg",lastModified:Date.now()}),R=n(j);if(R){i?.(R);return}i?.(void 0),r(j),v()},"image/jpeg",.92))},[r,n,v,i]),A=S.useCallback(T=>{const C=T.target.files?.[0];if(!C)return;const _=n(C);if(_){i?.(_);return}i?.(void 0),r(C),v(),l.current&&(l.current.value="")},[r,n,v,i]),I=typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function";return u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:l,type:"file",accept:o,capture:"user",onChange:A,className:"hidden","aria-hidden":!0}),u.jsx("canvas",{ref:d,className:"hidden","aria-hidden":!0}),u.jsx(uC,{open:e,onOpenChange:T=>{T||v()},children:u.jsxs(mC,{className:"sm:max-w-md",showCloseButton:!0,onPointerDownOutside:T=>T.preventDefault(),children:[u.jsx(hC,{children:u.jsx(yC,{children:"Take a photo"})}),f?u.jsxs("div",{className:"space-y-3 py-2",children:[u.jsx("p",{className:"text-sm text-destructive",children:f}),I&&u.jsx("p",{className:"text-xs text-muted-foreground",children:"You can choose an image from your device instead."}),u.jsx(yr,{type:"button",variant:"outline",className:"w-full",onClick:()=>l.current?.click(),children:"Choose from device"})]}):m?u.jsx("p",{className:"text-sm text-muted-foreground py-6 text-center",children:"Opening camera…"}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"relative rounded-lg overflow-hidden bg-black aspect-video",children:u.jsx("video",{ref:w,playsInline:!0,muted:!0,className:"w-full h-full object-cover"})}),u.jsxs(gC,{className:"gap-2 sm:gap-0",children:[u.jsx(yr,{type:"button",variant:"outline",onClick:v,children:"Cancel"}),u.jsx(yr,{type:"button",onClick:x,children:"Capture photo"})]})]})]})})]})},vC=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a})=>{const d=e.properties,[c,l]=S.useState(),[f,p]=S.useState(!1),[m,b]=S.useState(()=>new Set),[h,g]=S.useState("none"),w=e.metadata?typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata:null,v=e.validation?.find(V=>V.type==="fileSize"),x=e.validation?.find(V=>V.type==="fileType"),A=v?.value!=null?v.value:d?.maxSize??w?.maxSize??5*1024*1024,I=x?.value!=null?x.value:d?.accept??w?.accept??["image/*"],T=I.join(",")||"image/*",C=ls(e),_=S.useCallback(V=>{if(v){const le=Rr(V,v);if(le!==!0)return typeof le=="string"?le:"File size exceeds the maximum allowed size"}else if(V.size>A)return`File size must be less than ${so(A)}`;if(x){const le=Rr(V,x);if(le!==!0)return typeof le=="string"?le:"File type is not allowed"}return null},[v,x,A]),E=S.useMemo(()=>cs(t),[t]),O=yl(E),N=S.useCallback(V=>{const le=na(V,C);r(le),n?.()},[r,n,C]),j=S.useCallback(V=>{const le=_(V);if(le){l(le);return}l(void 0);const re=[...E];re.length>=C||(re.push(V),N(re),g("none"))},[E,C,_,N]),R=S.useCallback(V=>{const le=E.filter((re,ne)=>ne!==V);N(le)},[E,N]),M=S.useCallback(()=>{s||E.length>=C||(l(void 0),g("camera"),p(!0))},[s,E.length,C]),B=S.useCallback(V=>{p(V),V||g("none")},[]),P=o||c,H=e.appearance?.hideLabel??!1,D=[];(v||A)&&D.push(`Max size: ${so(A)}`),x&&I.length>0&&D.push(`Allowed: ${I.join(", ")}`),C>1&&D.push(`Up to ${C} photos`);const K=S.useCallback(V=>{window.open(V,"_blank","noopener,noreferrer")},[]),q=E.length===0,L=E.length<C,z=ml(C,E.length);return u.jsxs(_t,{field:e,error:P,isRequired:i,className:W(a,"!space-y-0"),hideLabel:H,children:[u.jsx("div",{className:"h-[70px] min-h-[70px] min-w-0 w-full flex flex-col",children:u.jsx("div",{role:"button",tabIndex:s||!L?-1:0,id:bt(e),onClick:V=>{s||V.target.closest("[data-remove-in-dropzone]")||V.target.closest("[data-no-open-picker]")||E.length>=C||M()},onKeyDown:V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),!s&&L&&M())},className:W("border-2 border-dashed rounded-lg p-1.5 text-center cursor-pointer transition-colors flex-1 min-h-0 flex flex-col items-center justify-center","hover:border-primary hover:bg-primary/5",P&&"border-destructive",s&&"opacity-50 cursor-not-allowed",f&&h==="camera"&&"opacity-70 pointer-events-none",!L&&E.length>0&&"cursor-default"),"aria-describedby":Vt(e,!!P),"aria-invalid":Zt(!!P),"aria-required":i,children:q?u.jsxs(u.Fragment,{children:[u.jsx(fs,{className:"mx-auto h-5 w-5 text-muted-foreground flex-shrink-0"}),u.jsx("p",{className:"text-[11px] text-muted-foreground leading-tight line-clamp-1",children:f?"Opening camera…":"Click to open camera"}),D.length>0&&u.jsx("p",{className:"text-[10px] text-muted-foreground line-clamp-1",children:D.join(" • ")})]}):z?u.jsx(bl,{item:E[0],objectUrl:O[0]??null,failedUrlKeys:m,onImageUrlError:V=>b(le=>new Set(le).add(V)),onRemove:()=>R(0),onOpenUrl:K,disabled:s}):u.jsx(gl,{items:E,maxFiles:C,disabled:s,objectUrls:O,failedUrlKeys:m,onImageUrlError:V=>b(le=>new Set(le).add(V)),onRemove:R,onOpenUrl:K,addSlot:L?u.jsxs("button",{type:"button","data-no-open-picker":!0,onClick:V=>{V.stopPropagation(),M()},disabled:s,className:"h-[56px] w-[56px] min-w-[56px] flex-shrink-0 rounded border border-dashed border-muted-foreground/40 flex flex-col items-center justify-center text-muted-foreground hover:border-primary hover:bg-primary/5 text-[10px] leading-tight px-0.5",children:[u.jsx(fs,{className:"h-4 w-4 mb-0.5","aria-hidden":!0}),"Add"]}):void 0})})}),u.jsx(mm,{open:f,onOpenChange:B,onCaptured:j,validateFile:_,accept:T,disabled:s,onValidationMessage:l})]})},wC=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a,buttonResponses:d})=>{const c=e.properties,l=S.useRef(null),[f,p]=S.useState(),[m,b]=S.useState(!1),[h,g]=S.useState(()=>new Set),[w,v]=S.useState("none"),x=e.metadata?typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata:null,A=e.validation?.find(ie=>ie.type==="fileSize"),I=e.validation?.find(ie=>ie.type==="fileType"),T=A?.value?A.value:c?.maxSize??x?.maxSize??5*1024*1024,C=I?.value?I.value:c?.accept??x?.accept??["image/*"],_=Array.isArray(C)?C.join(","):"image/*",E=ls(e),O=S.useCallback(ie=>{if(A){const G=Rr(ie,A);if(G!==!0)return typeof G=="string"?G:"File size exceeds the maximum allowed size"}else if(ie.size>T)return`File size must be less than ${so(T)}`;if(I){const G=Rr(ie,I);if(G!==!0)return typeof G=="string"?G:"File type is not allowed"}return null},[A,I,T]),N=S.useMemo(()=>cs(t),[t]),j=yl(N),R=S.useCallback(ie=>{const G=na(ie,E);r(G),n?.()},[r,n,E]),M=S.useCallback(ie=>{p(void 0);const G=Array.from(ie),ve=[...N];let be=null;for(const He of G){if(ve.length>=E)break;const he=O(He);if(he){be||(be=he);continue}ve.push(He)}if(be&&ve.length===N.length){p(be);return}be&&p(be),R(ve),v("none")},[N,E,O,R]),B=S.useCallback(ie=>{const G=ie.target.files;G&&G.length>0&&M(G),l.current&&(l.current.value="")},[M]),P=S.useCallback(ie=>{R(N.filter((G,ve)=>ve!==ie))},[N,R]),H=S.useCallback(()=>{s||N.length>=E||m||(p(void 0),v("file"),l.current?.click())},[s,N.length,E,m]),D=S.useCallback(()=>{s||N.length>=E||(p(void 0),v("camera"),b(!0))},[s,N.length,E]),K=S.useCallback(ie=>{const G=O(ie);if(G){p(G);return}p(void 0);const ve=[...N];ve.length>=E||(ve.push(ie),R(ve),v("none"))},[N,E,O,R]),q=S.useCallback(ie=>{b(ie),ie||v("none")},[]),L=o||f,z=e.appearance?.hideLabel??!1,V=[];(A||T)&&V.push(`Max size: ${so(T)}`),I&&C.length>0&&V.push(`Allowed: ${C.join(", ")}`),E>1&&V.push(`Up to ${E} photos`);const le=S.useMemo(()=>{if(!d)return null;const ie=Object.values(d);for(let G=ie.length-1;G>=0;G-=1){const ve=ie[G],be=typeof ve?.status=="string"?ve.status.toLowerCase():null;if(be&&be!=="success")continue;const He=ve?.code;if(typeof He=="number"&&(He<200||He>=300))continue;const he=ve?.data,Ee=he?.file_url||he?.fileUrl||ve?.file_url||ve?.fileUrl;if(typeof Ee=="string"&&Ee.trim())return Ee.trim()}return null},[d]),re=S.useCallback(ie=>{window.open(ie,"_blank","noopener,noreferrer")},[]),ne=N.length===0,Z=N.length<E,Y=ml(E,N.length),oe=Z&&!m?u.jsxs("div",{"data-no-open-picker":!0,className:"h-[56px] w-[56px] min-w-[56px] flex-shrink-0 rounded border border-dashed border-muted-foreground/40 flex flex-col items-center justify-center gap-0.5 text-muted-foreground",children:[u.jsx("button",{type:"button",disabled:s,onClick:ie=>{ie.stopPropagation(),H()},className:"flex flex-1 w-full items-center justify-center hover:bg-primary/10 rounded-t","aria-label":"Upload file",title:"Upload",children:u.jsx(ms,{className:"h-4 w-4","aria-hidden":!0})}),u.jsx("button",{type:"button",disabled:s,onClick:ie=>{ie.stopPropagation(),D()},className:"flex flex-1 w-full items-center justify-center hover:bg-primary/10 rounded-b border-t border-border/50","aria-label":"Open camera",title:"Camera",children:u.jsx(fs,{className:"h-4 w-4","aria-hidden":!0})})]}):void 0;return u.jsxs(_t,{field:e,error:L,isRequired:i,className:W(a,"!space-y-0"),hideLabel:z,children:[u.jsx("div",{className:"h-[70px] min-h-[70px] min-w-0 w-full flex flex-col",children:u.jsxs("div",{className:W("border-2 border-dashed rounded-lg p-1.5 transition-colors flex-1 min-h-0 flex flex-col items-center justify-center","hover:border-primary hover:bg-primary/5",L&&"border-destructive",s&&"opacity-50"),children:[u.jsx("input",{ref:l,id:bt(e),type:"file",accept:_,multiple:E>1,onChange:B,disabled:s||e.disabled||m||!Z,className:"hidden","aria-describedby":Vt(e,!!L),"aria-invalid":Zt(!!L),"aria-required":i}),ne?u.jsxs("div",{className:"flex flex-col items-center justify-center gap-1 w-full pointer-events-auto",children:[u.jsxs("div",{className:"flex items-center justify-center gap-3",children:[u.jsxs("button",{type:"button",disabled:s||m,onClick:H,className:W("inline-flex flex-col items-center gap-0.5 text-[11px] text-muted-foreground hover:text-foreground",s&&"pointer-events-none"),children:[u.jsx(ms,{className:"h-5 w-5","aria-hidden":!0}),u.jsx("span",{children:"Upload"})]}),u.jsxs("button",{type:"button",disabled:s,onClick:D,className:W("inline-flex flex-col items-center gap-0.5 text-[11px] text-muted-foreground hover:text-foreground",s&&"pointer-events-none",m&&"opacity-70"),children:[u.jsx(fs,{className:"h-5 w-5","aria-hidden":!0}),u.jsx("span",{children:"Camera"})]})]}),V.length>0&&u.jsx("p",{className:"text-[10px] text-muted-foreground line-clamp-2 text-center px-1",children:V.join(" • ")})]}):Y?u.jsx(bl,{item:N[0],objectUrl:j[0]??null,failedUrlKeys:h,onImageUrlError:ie=>g(G=>new Set(G).add(ie)),onRemove:()=>P(0),onOpenUrl:re,openTarget:N[0]instanceof File?le:void 0,disabled:s||e.disabled}):u.jsx(gl,{items:N,maxFiles:E,disabled:s,objectUrls:j,failedUrlKeys:h,onImageUrlError:ie=>g(G=>new Set(G).add(ie)),onRemove:P,resolveOpenUrl:(ie,G)=>G instanceof File&&N.length===1&&le?le:null,onOpenUrl:ie=>{ie?.trim()&&re(ie.trim())},addSlot:oe})]})}),u.jsx(mm,{open:m,onOpenChange:q,onCaptured:K,validateFile:O,accept:_,disabled:s,onValidationMessage:p})]})};function Wo(e){if(e instanceof Error){const t=e.message;if(t&&(t.includes("{")||t.includes("[")))try{const r=t.match(/\{[\s\S]*\}/);if(r){const n=JSON.parse(r[0]);return io(n)}}catch{}if(e.response){const r=e.response;if(typeof r=="string")try{const n=JSON.parse(r);return io(n)}catch{return r}else if(typeof r=="object")return io(r)}return t}if(e instanceof V0)return e.response?.data?io(e.response.data):e.message||"An unexpected error occurred";if(typeof e=="string")try{const t=JSON.parse(e);return io(t)}catch{return e}return typeof e=="object"&&e!==null?io(e):"An unexpected error occurred"}function io(e){if(e?.display_message&&typeof e.display_message=="string")return e.display_message.trim();if(e?.errors&&Array.isArray(e.errors)){const t=e.errors.filter(r=>r&&typeof r=="string");if(t.length>0)return t.join(". ")}if(e?.error?.explanation&&Array.isArray(e.error.explanation)){const t=e.error.explanation.filter(r=>r&&typeof r=="string");if(t.length>0)return t.join(". ")}if(e?.explanation&&Array.isArray(e.explanation)){const t=e.explanation.filter(r=>r&&typeof r=="string");if(t.length>0)return t.join(". ")}if(e?.errors&&Array.isArray(e.errors)){const t=e.errors.filter(r=>r!=null&&String(r).trim());if(t.length>0)return t.map(r=>typeof r=="string"?r:r?.message||String(r)).join(". ")}return e?.message&&typeof e.message=="string"?e.message:e?.display_message&&typeof e.display_message=="string"?e.display_message:e?.error?.display_message&&typeof e.error.display_message=="string"?e.error.display_message:e?.error?.message&&typeof e.error.message=="string"?e.error.message:e?.error&&typeof e.error=="string"?e.error:"An unexpected error occurred"}function SC(e){if(e==null||typeof e!="object")return;const t=e;if(typeof t.message=="string"&&t.message.trim())return t.message.trim();if(typeof t.display_message=="string"&&t.display_message.trim())return t.display_message.trim();if(t.data&&typeof t.data=="object"){const r=t.data;if(typeof r.message=="string"&&r.message.trim())return r.message.trim();if(typeof r.success_message=="string"&&r.success_message.trim())return r.success_message.trim();if(typeof r.display_message=="string"&&r.display_message.trim())return r.display_message.trim()}if(typeof t.success_message=="string"&&t.success_message.trim())return t.success_message.trim()}function xC(e,t){try{const r=SC(e);Dt.toast.success(r&&r.trim()?r:t)}catch{Dt.toast.success(t)}}function xl(e,t,r){try{const n=r(e);Dt.toast.error(n&&n.trim()?n:t)}catch{Dt.toast.error(t)}}function AC(e){const t=e.headers,r=["X-Message","X-Success-Message","X-Toast-Message","X-Success-Msg"];for(const n of r){const o=t.get(n);if(o&&typeof o=="string"&&o.trim())return o.trim()}}const fi="This field is required";function hm(e,t){if(!t?.length)return e;const r=t.find(n=>n.name===e);return r?.label&&r.label.trim()||e}function Al(e,t){if(!e)return"Please complete the required fields.";if(Array.isArray(e)){const s=e.map(i=>{const a=i.message||fi;if(t?.length&&i.field){const d=hm(i.field,t);return a===fi?`${d} is required`:`${d}: ${a}`}return a}).filter(i=>typeof i=="string"&&i.length>0);return s.length===0?"Please complete the required fields.":s.length===1?s[0]:`${s[0]} (and ${s.length-1} more)`}const n=Object.entries(e).map(([o,s])=>{const i=s?.trim()||fi;if(t?.length){const a=hm(o,t);return i===fi?`${a} is required`:`${a}: ${i}`}return i}).filter(o=>typeof o=="string"&&o.length>0);return n.length===0?"Please complete the required fields.":n.length===1?n[0]:`${n[0]} (and ${n.length-1} more)`}const CC=/^\{([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}$/i;function gm(e){const t=e.trim().match(CC);return t?t[1]:e}const EC={applicantId:["id","applicant_id"],applicant_id:["id","applicantId"],id:["applicantId","applicant_id"]};function Yr(e,t,r,n,o,s){let i=e;if(o&&typeof e=="string"&&(i=i.replace(/\{resp:([^}]+)\}/g,(a,d)=>{const c=d.trim().split(".");if(c.length<2)return a;const l=c[0],f=c.slice(1).join("."),p=o[l];if(p==null)return a;const m=pt(p,f);return m==null?a:String(m)}),i.includes("{documentId}")||i.includes("%7BdocumentId%7D"))){let a;for(const d of Object.values(o)){const c=pt(d,"data.id")??pt(d,"data.documentId");if(c!=null){a=String(c);break}}a&&(i=i.replace(/\{documentId\}/g,a).replace(/%7BdocumentId%7D/gi,a))}if(i.includes("{documentId}")||i.includes("%7BdocumentId%7D")){let a;const d=t?.documentId??(t&&pt(t,"documentId")),c=n?.documentId??(n&&pt(n,"documentId"));d!=null&&d!==""?a=String(d):c!=null&&c!==""&&(a=String(c)),a&&(i=i.replace(/\{documentId\}/g,a).replace(/%7BdocumentId%7D/gi,a))}return i=i.replace(/\{api:([^}]+)\}/g,(a,d)=>{const c=d.trim();if(s==null||c==="")return a;const l=pt(s,c);return l==null?a:String(l)}),i=i.replace(/\{(?:ctx:|\@)(\w+)\}/g,(a,d)=>n&&n[d]!==void 0&&n[d]!==null?String(n[d]):a),i=i.replace(/\{(\w+)\}/g,(a,d)=>{if(a.includes("ctx:")||a.includes("@"))return a;const c=r[d];if(c!=null)return gm(String(c));let l=t[d];if(l==null||l===""){const f=Object.keys(t).find(p=>p.toLowerCase()===d.toLowerCase());f&&(l=t[f])}if((l==null||l==="")&&(l=n?.[d]),l==null||l===""){const f=EC[d];if(f)for(const p of f){const m=t[p]??n?.[p];if(m!=null&&m!==""){l=m;break}}}return l!=null&&l!==""?gm(String(l)):a}),i}function Cl(e,t){if(!t?.length)return e;const r=new Map;for(const o of t){const s=o.name||o.key||o.id;s&&r.set(s,o)}const n={};for(const[o,s]of Object.entries(e)){const i=r.get(o);if(i?.type==="selectablelist"&&Array.isArray(s)&&s.length>0){const a=i.properties,d=i.metadata,c=typeof d=="object"&&d!==null?d:null,l=a?.submitFieldMapping??c?.submitFieldMapping;if(l&&typeof l=="object"&&Object.keys(l).length>0){const f=s.map(p=>{if(p==null||typeof p!="object")return p;const m={};for(const[b,h]of Object.entries(l))b!=null&&b!==""&&h!=null&&h!==""&&(m[b]=pt(p,h));return m});n[o]=f;continue}}n[o]=s}return n}function pi(e){return!!(e instanceof File||Array.isArray(e)&&e.length>0&&e[0]instanceof File)}function TC(e){return Object.values(e).some(t=>pi(t))}function _C(e,t){const r=new FormData;let n=!1;return Object.entries(e).forEach(([o,s])=>{const i=t?.[o]||o;s instanceof File?(r.append(i,s),n=!0):Array.isArray(s)&&s.length>0&&s[0]instanceof File?(s.forEach(a=>{r.append(i,a)}),n=!0):s!=null&&(typeof s=="object"?r.append(i,JSON.stringify(s)):r.append(i,String(s)))}),n?r:null}function NC(e,t,r){const n={};let o=!1;return Object.entries(e).forEach(([s,i])=>{const a=t?.[s]||s;if(pi(i)){n[a]=i,o=!0;return}const d=r?.[s]||"string";let c=i;if(d==="number"){const l=Number(i);c=isNaN(l)?i:l}else d==="boolean"?c=i==="true"||i===!0||i==="1"||i===1:d==="date"?c=String(i):i!=null?c=typeof i=="object"?i:String(i):c="";n[a]=c}),{transformed:n,hasFiles:o}}const ym=Object.freeze(Object.defineProperty({__proto__:null,hasFileValues:TC,isFileValue:pi,prepareFormDataWithFiles:_C,transformFormValuesWithFiles:NC},Symbol.toStringTag,{value:"Module"}));function kC(e){return e==="null"?null:e==="true"?!0:e==="false"?!1:e}function FC(e){const t=e,r=typeof t?.status=="string"?t.status.toLowerCase():null;if(r&&r!=="success")return!1;const n=t?.code;return!(typeof n=="number"&&(n<200||n>=300))}function OC(e,t){if(!t)return[];const r=e.trim().split(".");if(r.length<2)return[];const n=r[0],o=r.slice(1).join("."),s=[];return Object.entries(t).forEach(([i,a])=>{const d=i===n,c=i.startsWith(`${n}__addmore__`);if(!d&&!c||!FC(a))return;const l=pt(a,o);l==null||l===""||s.push(l)}),s}function mi(e,t,r,n,o,s){const i=e.trim().match(/^\{respAll:([^}]+)\}$/);if(i){const c=(i[1]||"").trim(),l=c.split("."),f=l.length>=2?l.slice(1).join("."):"";return(f==="data.id"||f==="data.documentId")&&n?.document_ids!=null&&Array.isArray(n.document_ids)?n.document_ids:OC(c,o)}const a=e.trim().match(/^\{(\w+)\}$/);if(a){const c=a[1],l=t[c];if(l!==void 0)return l;const f=Object.keys(t).find(p=>p.toLowerCase()===c.toLowerCase());if(f)return t[f]}const d=Yr(e,t,r,n,o,s);return kC(String(d))}const PC=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d,onClick:c,onSubmit:l,onReset:f,onCancel:p,isSubmitting:m=!1,formValues:b={},submissionContext:h,bffSubmitApi:g,onBffSubmitResult:w,extraSubmitPayload:v,buttonResponses:x,onButtonApiResponse:A,onValidateForm:I,getValidationErrors:T,allFields:C,onSubmittingChange:_,scopedFormValues:E,scopedFieldNameMap:O,prepopulateResponse:N=null})=>{const{gridStretch:j}=Ao(),[R,M]=S.useState(!1),B=e.properties,P=zi.useParams(),H=S.useMemo(()=>({...h,...v}),[h,v]),D=S.useMemo(()=>{if(!E||!O||Object.keys(O).length===0)return b;const we={};return Object.entries(E).forEach(([ct,Le])=>{const ee=O[ct]||ct;ee!==e.name&&(we[ee]=Le)}),we},[E,O,b,e.name]),q=(()=>{try{const we=e.metadata;if(typeof we=="string")return JSON.parse(we);if(we&&typeof we=="object")return we}catch{}return null})(),L=B?.submitAction??q?.submitAction,z=B?.apiEndpoint??e.apidata?.apiEndpoint??q?.apiEndpoint;let V=B?.action||q?.action;!V&&e.type==="button"&&(V="submit");const le=B?.variant||"default",re=B?.size||"default",ne=B?.hideLabel??e.appearance?.hideLabel??!1,Z=B?.buttonText||e.label||"Button",Y=B?.closeOnCancel??!0,oe=async()=>{if(E&&O&&Object.keys(O).length>0||!I)return!0;const we=await I();if(!we&&T)try{const ct=T();Dt.toast.error(Al(ct,C??void 0)||"Please fix the errors before submitting.")}catch{Dt.toast.error("Please fix the errors before submitting.")}return we},ie=async we=>{if(we.preventDefault(),(V==="submit"?"submit":V)==="submit"){if(g?.url){if(!await oe())return;M(!0),_?.(!0);try{const Le=await ve(),ee=(Le?.message??Le?.display_message??"Form submitted successfully!").trim();Dt.toast.success(ee||"Form submitted successfully!");const Ye=Le!=null&&typeof Le=="object"?Le:{status:"success",...Le!=null?{data:Le}:{}};A?.(e.name,Ye)}catch(Le){const ee=Wo(Le);Dt.toast.error(ee)}finally{M(!1),_?.(!1)}return}if(l){if(!await oe())return;M(!0),_?.(!0);try{await l(),A?.(e.name,{status:"success"})}finally{M(!1),_?.(!1)}return}Dt.toast.error("Submit not configured. BFF submit API is required for submit buttons.");return}else if(V==="reset"&&f)f();else if(V==="cancel")Y?p&&p():f&&f();else if(V==="download"){const Le=B?.downloadApiEndpoint||q?.downloadApiEndpoint||e.downloadApiEndpoint,ee=B?.downloadApiMethod||q?.downloadApiMethod||e.downloadApiMethod;if(Le){M(!0);try{const Ye=ee||"GET",et=Gr(Yr(Le,D,P,H,x,N??void 0)),Ue={method:Ye,headers:{}};Ye!=="GET"&&Ye!=="DELETE"&&(Ue.headers={"Content-Type":"application/json"});const Q=await fetch(et,Ue);if(!Q.ok)throw new Error(`Download failed: ${Q.statusText}`);const ce=await Q.blob(),ue=window.URL.createObjectURL(ce),xe=document.createElement("a");xe.href=ue;const Ae=Q.headers.get("Content-Disposition");let De="download";if(Ae){const rt=Ae.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);rt&&rt[1]&&(De=rt[1].replace(/['"]/g,""))}xe.download=De,document.body.appendChild(xe),xe.click(),document.body.removeChild(xe),window.URL.revokeObjectURL(ue);try{const rt=AC(Q);Dt.toast.success(rt&&rt.trim()?rt:"Download started.")}catch{Dt.toast.success("Download started.")}}catch(Ye){xl(Ye,"Failed to download file. Please check the API endpoint and try again.",Wo)}finally{M(!1)}}else Dt.toast.error("Download endpoint is not configured")}else if(V==="upload"||V==="custom"){const Le=V==="custom",ee=Le?"api":B?.uploadAction||q?.uploadAction||"database";if(ee==="database")if(l){M(!0);try{await l(we)}catch(Ye){throw Ye}finally{M(!1)}}else Dt.toast.error("Form submit handler is not available");else if(ee==="api"){const Ye=B?.uploadApiEndpoint||q?.uploadApiEndpoint||e.uploadApiEndpoint;if(B?.uploadApiMethod||q?.uploadApiMethod||e.uploadApiMethod,Ye){if(!await oe())return;M(!0);try{const et=await be();A?.(e.name,et),xC(et,Le?"Custom API call completed successfully!":"Upload completed successfully!")}catch(et){A?.(e.name,{status:"error",code:et?.response?.code??et?.response?.status??null,message:Wo(et)}),xl(et,Le?"Failed to call custom API. Please check the API endpoint and try again.":"Failed to upload. Please check the API endpoint and try again.",Wo)}finally{M(!1)}}else Dt.toast.error(Le?"Custom API endpoint is not configured":"Upload endpoint is not configured")}else ee==="custom"&&Dt.toast.info("Custom upload handler is not implemented")}else c?c():r&&t!==void 0&&r(t||"");n?.()},G=async()=>{if(!L||L!=="api"||!z)return null;const we=B?.apiBodyFields??q?.apiBodyFields;if((B?.apiBodyFieldsOnly??q?.apiBodyFieldsOnly??!1)&&we?.length){const xe={};return we.forEach(({key:Ae,value:De})=>{const rt=mi(De,D,P,H,x,N??void 0),vt=Ae==="user_id"?"context_user_id":Ae;xe[vt]=rt}),xe.user_id!==void 0&&xe.user_id!==null&&(xe.context_user_id=xe.context_user_id??xe.user_id,delete xe.user_id),xe}const Le=C?.length?Cl(D,C):D,ee=B?.apiFieldMapping??q?.apiFieldMapping,Ye=B?.apiFieldTypes??q?.apiFieldTypes,et=B?.apiBodyStructure??q?.apiBodyStructure,Ue={...Ye};C?.length&&C.forEach(xe=>{const Ae=xe.name||xe.key;Ae&&(xe.type==="terms"||xe.type==="checkbox")&&(Ue[Ae]="boolean")});const{transformFormValuesWithFiles:Q}=await Promise.resolve().then(()=>ym),{transformed:ce}=Q(Le,ee,Ue);let ue={};if(et==="flat"?ue={...ce}:ue={data:{...ce}},ee){const xe={};Object.keys(ue).forEach(Ae=>{const De=ee[Ae]||Ae;xe[De]=ue[Ae]}),ue=xe}return we?.length&&we.forEach(({key:xe,value:Ae})=>{const De=mi(Ae,D,P,H,x,N??void 0),rt=xe==="user_id"?"context_user_id":xe;ue[rt]=De}),ue.user_id!==void 0&&ue.user_id!==null&&(ue.context_user_id=ue.context_user_id??ue.user_id,delete ue.user_id),ue.data?.user_id!==void 0&&ue.data?.user_id!==null&&(ue.data.context_user_id=ue.data.context_user_id??ue.data.user_id,delete ue.data.user_id),ue},ve=async()=>{if(!g||!g.url)throw new Error("BFF submit API configuration is missing");const we=C?.length?Cl(b,C):b,ct={};Object.keys(we).forEach(Ge=>{const ut=e.name===Ge&&e.type==="button",We=Ge.toLowerCase().includes("button");!ut&&!We&&(ct[Ge]=we[Ge])});const Le=Object.keys(ct).filter(Ge=>pi(ct[Ge]));Le.forEach(Ge=>{ct[Ge]=""});const ee={workflow_id:g.payload?.workflow_id||"",current_step_id:g.payload?.current_step_id||"",form_data:ct},Ye=["workflow_id","current_step_id","form_data","submit_body","submit_api_endpoint","submit_api_method"];if(h&&typeof h=="object"&&Object.entries(h).forEach(([Ge,ut])=>{if(ut==null||Ye.includes(Ge))return;const We=Ge==="user_id"?"context_user_id":Ge;ee[We]=ee[We]??ut}),v&&typeof v=="object"&&Object.entries(v).forEach(([Ge,ut])=>{if(ut==null||Ye.includes(Ge))return;const We=Ge==="user_id"?"context_user_id":Ge;ee[We]=ee[We]??ut}),L==="api"&&z)try{const Ge=await G();if(Ge){const ut=B?.apiBodyStructure??q?.apiBodyStructure,We=B?.apiFieldMapping??q?.apiFieldMapping;Le.forEach(tr=>{const kr=We?.[tr]??tr,Ht=ct[tr]!==void 0&&typeof ct[tr]=="string"?ct[tr]:"";ut==="flat"?Ge[kr]=Ht:Ge.data&&typeof Ge.data=="object"?Ge.data[kr]=Ht:Ge[kr]=Ht}),ee.submit_body=Ge;let mt=Yr(z,D,P,H,x,N??void 0);mt=mt.replace(/\{([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}/gi,"$1"),mt=Gr(mt),ee.submit_api_endpoint=mt,ee.submit_api_method=B?.submitApiMethod||q?.submitApiMethod||"POST"}}catch{}const et=(g.method||"POST").toUpperCase(),Ue=Le.length>0,Q=ee.submit_api_endpoint??z??"",ce=typeof Q=="string"?Q.toLowerCase():"",ue=ce.includes("/upload")||ce.includes("/payments")||ce.includes("/bulk-upload"),xe=Ue&&ue;let Ae;const De={...g.headers||{}};if(xe){const Ge=new FormData;Ge.append("payload",JSON.stringify(ee));for(const ut of Le){const We=we[ut],mt=B?.apiFieldMapping?.[ut]??ut;We instanceof File?Ge.append(mt,We):Array.isArray(We)&&We.length>0&&We[0]instanceof File&&We.forEach(tr=>Ge.append(mt,tr))}Ae=Ge,delete De["content-type"],delete De["Content-Type"]}else De["Content-Type"]="application/json",Ae=JSON.stringify(ee);const rt=await fetch(g.url,{method:et,headers:De,body:Ae});if(!rt.ok){let Ge;const ut=await rt.text();try{Ge=JSON.parse(ut)}catch{Ge={message:ut}}const We=new Error(`BFF submission failed: ${rt.status}`);throw We.response=Ge,We}const vt=await rt.json();return w?.(vt),l&&await l(),vt},be=async()=>{const we=B?.uploadApiEndpoint||q?.uploadApiEndpoint;if(!we)throw new Error("Upload API endpoint is not configured");if(!B)throw new Error("Button properties are not configured");const ct=(B.uploadApiMethod||"POST").toUpperCase(),Le=Gr(Yr(we,D,P,H,x,N??void 0)),ee=B.apiBodyFieldsOnly??q?.apiBodyFieldsOnly??!1,Ye=B.apiBodyFieldsOnlyFormat??q?.apiBodyFieldsOnlyFormat??"json";let et={},Ue;const Q={};if(ee&&B.apiBodyFields&&B.apiBodyFields.length>0)if(B.apiBodyFields.forEach(({key:xe,value:Ae})=>{et[xe]=mi(Ae,D,P,H,x,N??void 0)}),Ye==="multipart"){const xe=new FormData;Object.entries(et).forEach(([Ae,De])=>{if(De instanceof File){xe.append(Ae,De);return}if(Array.isArray(De)&&De.length>0&&De[0]instanceof File){De.forEach(rt=>xe.append(Ae,rt));return}De!=null&&xe.append(Ae,typeof De=="object"?JSON.stringify(De):String(De))}),Ue=xe}else Ue=JSON.stringify(et),Q["Content-Type"]="application/json";else{const xe=D,{transformFormValuesWithFiles:Ae,prepareFormDataWithFiles:De,hasFileValues:rt}=await Promise.resolve().then(()=>ym),{transformed:vt,hasFiles:Ge}=Ae(xe,B.apiFieldMapping,B.apiFieldTypes);if((B.apiBodyStructure??q?.apiBodyStructure??"nested")==="flat"?et={...vt}:et={data:{...vt}},B.apiFieldMapping){const We={};Object.keys(et).forEach(mt=>{const tr=B.apiFieldMapping[mt]||mt;We[tr]=et[mt]}),et=We}if(B.apiBodyFields&&B.apiBodyFields.forEach(({key:We,value:mt})=>{et[We]=mi(mt,D,P,H,x,N??void 0)}),Ge||rt(et)){const We=De(et,B.apiFieldMapping);We?Ue=We:(Ue=JSON.stringify(et),Q["Content-Type"]="application/json")}else Ue=JSON.stringify(et),Q["Content-Type"]="application/json"}B.apiHeaders&&B.apiHeaders.forEach(({key:xe,value:Ae})=>{const De=Yr(Ae,D,P,H,x,N??void 0);(xe.toLowerCase()!=="content-type"||!(Ue instanceof FormData))&&(Q[xe]=De)});let ce=Le;if(B.apiQueryParams&&B.apiQueryParams.length>0){const xe=new URLSearchParams;B.apiQueryParams.forEach(({key:Ae,value:De})=>{const rt=Yr(De,D,P,H,x,N??void 0);xe.append(Ae,rt)}),ce=`${Le}?${xe.toString()}`}const ue=await fetch(ce,{method:ct,headers:Q,body:ct!=="GET"?Ue:void 0});if(!ue.ok){let xe;const Ae=await ue.text();try{xe=JSON.parse(Ae)}catch{xe={message:Ae}}const De=new Error(`Upload failed: ${ue.status}`);throw De.response=xe,De}try{return await ue.json()}catch{return{}}},He=V==="submit"?"submit":V,Ee=He==="submit"?"button":He==="submit"?"submit":He==="reset"?"reset":"button",ae=s||e.disabled||i||e.readOnly||R||He==="submit"&&m,ye=Z,je=Vn(e),st=Er(e.appearance)==="stretch";return u.jsx(_t,{field:e,error:o,isRequired:a,className:d,hideLabel:ne,children:u.jsx("div",{className:W(j&&!je&&"flex w-full min-w-0 flex-col",j&&je&&"min-w-0 shrink-0"),children:u.jsxs(yr,{id:bt(e),type:Ee,variant:le,size:re,disabled:ae,onClick:ie,className:W(e.appearance?.className,j&&!je&&"w-full min-w-0 shrink-0",j&&je&&!st&&"inline-flex w-auto max-w-full shrink-0",j&&je&&st&&"inline-flex w-full min-w-0 max-w-full shrink-0"),children:[R&&u.jsx("span",{className:"inline-block h-4 w-4 shrink-0 animate-spin rounded-full border-2 border-current border-t-transparent mr-2","aria-hidden":!0}),ye]})})})},IC=({field:e,disabled:t,readOnly:r,isRequired:n,className:o,buttonResponses:s,onButtonApiResponse:i})=>{const a=e.properties,d=a?.buttonText??e.label??"Edit",c=a?.variant??"outline",l=a?.size??"default",f=a?.hideLabel??e.appearance?.hideLabel??!1,p=e.name||e.key||e.id,m=Co(s?.[p]),b=t||e.disabled||r||e.readOnly||m,h=g=>{g.preventDefault(),!b&&i?.(p,{status:"success"})};return u.jsx(_t,{field:e,error:void 0,isRequired:n,className:o,hideLabel:f,children:u.jsx(yr,{id:bt(e),type:"button",variant:c,size:l,disabled:b,onClick:h,className:W(e.appearance?.className,(!Vn(e)||Er(e.appearance)==="stretch")&&"w-full min-w-0"),children:d})})},MC=({field:e,error:t,disabled:r,readOnly:n,isRequired:o,className:s,onAddMore:i})=>{const a=e.properties||{},d=a.variant||"outline",c=a.size||"default",l=a.buttonText||e.label||"Add More",f=a.hideLabel??e.appearance?.hideLabel??!1,p=r||n||e.disabled||e.readOnly;return u.jsx(_t,{field:e,error:t,isRequired:o,className:s,hideLabel:f,children:u.jsxs(yr,{id:bt(e),type:"button",variant:d,size:c,disabled:!!p,onClick:i,className:W("w-fit",e.appearance?.className),children:[u.jsx(id,{className:"h-4 w-4 mr-1"}),l]})})},LC=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d})=>{const c=e.properties,l=c?.max||5,f=c?.icon||"star",p=h=>{s||i||e.disabled||e.readOnly||(r(h),n?.())},m=h=>{},b=h=>{const g=t>=h+1,w=W("transition-colors cursor-pointer",g?"fill-yellow-400 text-yellow-400":"text-muted-foreground",(s||i||e.disabled||e.readOnly)&&"cursor-not-allowed opacity-50",!(s||i||e.disabled||e.readOnly)&&"hover:text-yellow-400");return f==="star"?u.jsx(ad,{className:W(w,"h-6 w-6"),onClick:()=>p(h+1),onMouseEnter:()=>m()},h):u.jsx(ad,{className:W(w,"h-6 w-6"),onClick:()=>p(h+1),onMouseEnter:()=>m()},h)};return u.jsx(_t,{field:e,error:o,isRequired:a,className:d,children:u.jsxs("div",{id:bt(e),className:"flex items-center gap-1",role:"radiogroup","aria-label":e.label,"aria-describedby":Vt(e,!!o),"aria-invalid":Zt(!!o),"aria-required":a,children:[Array.from({length:l},(h,g)=>b(g)),c?.showValue!==!1&&u.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:t>0?t:""})]})})};var bm=["PageUp","PageDown"],vm=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],wm={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},ao="Slider",[El,DC,BC]=la(ao),[Sm]=mr(ao,[BC]),[$C,hi]=Sm(ao),xm=y.forwardRef((e,t)=>{const{name:r,min:n=0,max:o=100,step:s=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:d=0,defaultValue:c=[n],value:l,onValueChange:f=()=>{},onValueCommit:p=()=>{},inverted:m=!1,form:b,...h}=e,g=y.useRef(new Set),w=y.useRef(0),x=i==="horizontal"?jC:UC,[A=[],I]=Wr({prop:l,defaultProp:c,onChange:N=>{[...g.current][w.current]?.focus(),f(N)}}),T=y.useRef(A);function C(N){const j=WC(A,N);O(N,j)}function _(N){O(N,w.current)}function E(){const N=T.current[w.current];A[w.current]!==N&&p(A)}function O(N,j,{commit:R}={commit:!1}){const M=YC(s),B=XC(Math.round((N-n)/s)*s+n,M),P=Oo(B,[n,o]);I((H=[])=>{const D=VC(H,P,j);if(KC(D,d*s)){w.current=D.indexOf(P);const K=String(D)!==String(H);return K&&R&&p(D),K?D:H}else return H})}return u.jsx($C,{scope:e.__scopeSlider,name:r,disabled:a,min:n,max:o,valueIndexToChangeRef:w,thumbs:g.current,values:A,orientation:i,form:b,children:u.jsx(El.Provider,{scope:e.__scopeSlider,children:u.jsx(El.Slot,{scope:e.__scopeSlider,children:u.jsx(x,{"aria-disabled":a,"data-disabled":a?"":void 0,...h,ref:t,onPointerDown:Be(h.onPointerDown,()=>{a||(T.current=A)}),min:n,max:o,inverted:m,onSlideStart:a?void 0:C,onSlideMove:a?void 0:_,onSlideEnd:a?void 0:E,onHomeKeyDown:()=>!a&&O(n,0,{commit:!0}),onEndKeyDown:()=>!a&&O(o,A.length-1,{commit:!0}),onStepKeyDown:({event:N,direction:j})=>{if(!a){const B=bm.includes(N.key)||N.shiftKey&&vm.includes(N.key)?10:1,P=w.current,H=A[P],D=s*B*j;O(H+D,P,{commit:!0})}}})})})})});xm.displayName=ao;var[Am,Cm]=Sm(ao,{startEdge:"left",endEdge:"right",size:"width",direction:1}),jC=y.forwardRef((e,t)=>{const{min:r,max:n,dir:o,inverted:s,onSlideStart:i,onSlideMove:a,onSlideEnd:d,onStepKeyDown:c,...l}=e,[f,p]=y.useState(null),m=tt(t,x=>p(x)),b=y.useRef(void 0),h=Wn(o),g=h==="ltr",w=g&&!s||!g&&s;function v(x){const A=b.current||f.getBoundingClientRect(),I=[0,A.width],C=Nl(I,w?[r,n]:[n,r]);return b.current=A,C(x-A.left)}return u.jsx(Am,{scope:e.__scopeSlider,startEdge:w?"left":"right",endEdge:w?"right":"left",direction:w?1:-1,size:"width",children:u.jsx(Em,{dir:h,"data-orientation":"horizontal",...l,ref:m,style:{...l.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:x=>{const A=v(x.clientX);i?.(A)},onSlideMove:x=>{const A=v(x.clientX);a?.(A)},onSlideEnd:()=>{b.current=void 0,d?.()},onStepKeyDown:x=>{const I=wm[w?"from-left":"from-right"].includes(x.key);c?.({event:x,direction:I?-1:1})}})})}),UC=y.forwardRef((e,t)=>{const{min:r,max:n,inverted:o,onSlideStart:s,onSlideMove:i,onSlideEnd:a,onStepKeyDown:d,...c}=e,l=y.useRef(null),f=tt(t,l),p=y.useRef(void 0),m=!o;function b(h){const g=p.current||l.current.getBoundingClientRect(),w=[0,g.height],x=Nl(w,m?[n,r]:[r,n]);return p.current=g,x(h-g.top)}return u.jsx(Am,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:u.jsx(Em,{"data-orientation":"vertical",...c,ref:f,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:h=>{const g=b(h.clientY);s?.(g)},onSlideMove:h=>{const g=b(h.clientY);i?.(g)},onSlideEnd:()=>{p.current=void 0,a?.()},onStepKeyDown:h=>{const w=wm[m?"from-bottom":"from-top"].includes(h.key);d?.({event:h,direction:w?-1:1})}})})}),Em=y.forwardRef((e,t)=>{const{__scopeSlider:r,onSlideStart:n,onSlideMove:o,onSlideEnd:s,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:d,...c}=e,l=hi(ao,r);return u.jsx(Ve.span,{...c,ref:t,onKeyDown:Be(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):bm.concat(vm).includes(f.key)&&(d(f),f.preventDefault())}),onPointerDown:Be(e.onPointerDown,f=>{const p=f.target;p.setPointerCapture(f.pointerId),f.preventDefault(),l.thumbs.has(p)?p.focus():n(f)}),onPointerMove:Be(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&o(f)}),onPointerUp:Be(e.onPointerUp,f=>{const p=f.target;p.hasPointerCapture(f.pointerId)&&(p.releasePointerCapture(f.pointerId),s(f))})})}),Tm="SliderTrack",_m=y.forwardRef((e,t)=>{const{__scopeSlider:r,...n}=e,o=hi(Tm,r);return u.jsx(Ve.span,{"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation,...n,ref:t})});_m.displayName=Tm;var Tl="SliderRange",Nm=y.forwardRef((e,t)=>{const{__scopeSlider:r,...n}=e,o=hi(Tl,r),s=Cm(Tl,r),i=y.useRef(null),a=tt(t,i),d=o.values.length,c=o.values.map(p=>Om(p,o.min,o.max)),l=d>1?Math.min(...c):0,f=100-Math.max(...c);return u.jsx(Ve.span,{"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,...n,ref:a,style:{...e.style,[s.startEdge]:l+"%",[s.endEdge]:f+"%"}})});Nm.displayName=Tl;var _l="SliderThumb",km=y.forwardRef((e,t)=>{const r=DC(e.__scopeSlider),[n,o]=y.useState(null),s=tt(t,a=>o(a)),i=y.useMemo(()=>n?r().findIndex(a=>a.ref.current===n):-1,[r,n]);return u.jsx(RC,{...e,ref:s,index:i})}),RC=y.forwardRef((e,t)=>{const{__scopeSlider:r,index:n,name:o,...s}=e,i=hi(_l,r),a=Cm(_l,r),[d,c]=y.useState(null),l=tt(t,v=>c(v)),f=d?i.form||!!d.closest("form"):!0,p=Mo(d),m=i.values[n],b=m===void 0?0:Om(m,i.min,i.max),h=HC(n,i.values.length),g=p?.[a.size],w=g?qC(g,b,a.direction):0;return y.useEffect(()=>{if(d)return i.thumbs.add(d),()=>{i.thumbs.delete(d)}},[d,i.thumbs]),u.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${b}% + ${w}px)`},children:[u.jsx(El.ItemSlot,{scope:e.__scopeSlider,children:u.jsx(Ve.span,{role:"slider","aria-label":e["aria-label"]||h,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...s,ref:l,style:m===void 0?{display:"none"}:e.style,onFocus:Be(e.onFocus,()=>{i.valueIndexToChangeRef.current=n})})}),f&&u.jsx(Fm,{name:o??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:m},n)]})});km.displayName=_l;var zC="RadioBubbleInput",Fm=y.forwardRef(({__scopeSlider:e,value:t,...r},n)=>{const o=y.useRef(null),s=tt(o,n),i=Lo(t);return y.useEffect(()=>{const a=o.current;if(!a)return;const d=window.HTMLInputElement.prototype,l=Object.getOwnPropertyDescriptor(d,"value").set;if(i!==t&&l){const f=new Event("input",{bubbles:!0});l.call(a,t),a.dispatchEvent(f)}},[i,t]),u.jsx(Ve.input,{style:{display:"none"},...r,ref:s,defaultValue:t})});Fm.displayName=zC;function VC(e=[],t,r){const n=[...e];return n[r]=t,n.sort((o,s)=>o-s)}function Om(e,t,r){const s=100/(r-t)*(e-t);return Oo(s,[0,100])}function HC(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function WC(e,t){if(e.length===1)return 0;const r=e.map(o=>Math.abs(o-t)),n=Math.min(...r);return r.indexOf(n)}function qC(e,t,r){const n=e/2,s=Nl([0,50],[0,n]);return(n-s(t)*r)*r}function GC(e){return e.slice(0,-1).map((t,r)=>e[r+1]-t)}function KC(e,t){if(t>0){const r=GC(e);return Math.min(...r)>=t}return!0}function Nl(e,t){return r=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const n=(t[1]-t[0])/(e[1]-e[0]);return t[0]+n*(r-e[0])}}function YC(e){return(String(e).split(".")[1]||"").length}function XC(e,t){const r=Math.pow(10,t);return Math.round(e*r)/r}var JC=xm,QC=_m,ZC=Nm,eE=km;function tE({className:e,defaultValue:t,value:r,min:n=0,max:o=100,...s}){const i=y.useMemo(()=>Array.isArray(r)?r:Array.isArray(t)?t:[n,o],[r,t,n,o]);return u.jsxs(JC,{"data-slot":"slider",defaultValue:t,value:r,min:n,max:o,className:W("relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",e),...s,children:[u.jsx(QC,{"data-slot":"slider-track",className:W("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"),children:u.jsx(ZC,{"data-slot":"slider-range",className:W("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:i.length},(a,d)=>u.jsx(eE,{"data-slot":"slider-thumb",className:"border-primary bg-background ring-ring/50 block size-4 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"},d))]})}const rE=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d})=>{const c=e.properties,l=c?.min??0,f=c?.max??100,p=c?.step??1,m=c?.showValue!==!1,b=c?.marks||[],h=w=>{s||i||e.disabled||e.readOnly||(r(w[0]??l),n?.())},g=t??l;return u.jsx(_t,{field:e,error:o,isRequired:a,className:d,children:u.jsxs("div",{className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[m&&u.jsx("span",{className:"text-sm font-medium",children:g}),!m&&u.jsx("span",{className:"text-sm text-muted-foreground",children:l}),!m&&u.jsx("span",{className:"text-sm text-muted-foreground",children:f})]}),u.jsx(tE,{id:bt(e),value:[g],onValueChange:h,min:l,max:f,step:p,disabled:s||e.disabled||i||e.readOnly,className:W("w-full",o&&"border-destructive",e.appearance?.className),"aria-describedby":Vt(e,!!o),"aria-invalid":Zt(!!o),"aria-required":a}),b.length>0&&u.jsx("div",{className:"flex justify-between text-xs text-muted-foreground",children:b.map((w,v)=>u.jsx("span",{className:"text-center",children:w.label},v))})]})})},nE=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d})=>{const c=S.useRef(null),[l,f]=S.useState(!1),p=s||e.disabled||i||e.readOnly,m=S.useCallback(w=>{if(p)return;f(!0);const v=c.current;if(!v)return;const x=v.getContext("2d");if(!x)return;const A=v.getBoundingClientRect(),I="touches"in w?w.touches[0].clientX-A.left:w.clientX-A.left,T="touches"in w?w.touches[0].clientY-A.top:w.clientY-A.top;x.beginPath(),x.moveTo(I,T)},[p]),b=S.useCallback(w=>{if(!l||p)return;const v=c.current;if(!v)return;const x=v.getContext("2d");if(!x)return;const A=v.getBoundingClientRect(),I="touches"in w?w.touches[0].clientX-A.left:w.clientX-A.left,T="touches"in w?w.touches[0].clientY-A.top:w.clientY-A.top;x.lineWidth=2,x.lineCap="round",x.strokeStyle="#000",x.lineTo(I,T),x.stroke(),x.beginPath(),x.moveTo(I,T)},[l,p]),h=S.useCallback(()=>{if(!l)return;f(!1);const w=c.current;if(!w)return;const v=w.toDataURL();r(v),n?.()},[l,r,n]),g=S.useCallback(()=>{const w=c.current;if(!w||p)return;const v=w.getContext("2d");v&&(v.clearRect(0,0,w.width,w.height),r(null),n?.())},[p,r,n]);return S.useEffect(()=>{const w=c.current;if(w&&(w.width=w.offsetWidth,w.height=200,t)){const v=new Image;v.onload=()=>{const x=w.getContext("2d");x&&x.drawImage(v,0,0)},v.src=t}},[t]),u.jsx(_t,{field:e,error:o,isRequired:a,className:d,children:u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:W("border-2 border-dashed rounded-lg overflow-hidden",o&&"border-destructive",p&&"opacity-50 cursor-not-allowed"),children:u.jsx("canvas",{ref:c,id:bt(e),className:"w-full cursor-crosshair touch-none",onMouseDown:m,onMouseMove:b,onMouseUp:h,onMouseLeave:h,onTouchStart:m,onTouchMove:b,onTouchEnd:h,"aria-describedby":Vt(e,!!o),"aria-invalid":Zt(!!o),"aria-required":a,style:{height:"200px"}})}),!p&&u.jsx("div",{className:"flex justify-end",children:u.jsxs(yr,{type:"button",variant:"outline",size:"sm",onClick:g,className:"text-xs",children:[u.jsx(ko,{className:"h-3 w-3 mr-1"}),"Clear"]})})]})})},oE=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d,hideRowControls:c=!1,formValues:l,submissionContext:f})=>{const p=e.properties,m=p?.columns||[],b=p?.minRows||1,h=p?.maxRows||10,g=!c&&p?.allowAddRow!==!1,w=!c&&p?.allowDeleteRow!==!1,v=s===!1&&i===!1?!1:s||e.disabled||i||e.readOnly,x=t||[],A=g&&x.length<h,I=w&&x.length>b,T=S.useCallback(()=>{if(!A||v)return;const E={};m.forEach(O=>{E[O.name]=O.defaultValue??""}),r([...x,E]),n?.()},[x,m,A,v,r,n]),C=S.useCallback(E=>{if(!I||v)return;const O=x.filter((N,j)=>j!==E);r(O),n?.()},[x,I,v,r,n]),_=S.useCallback((E,O,N)=>{if(v)return;const j=[...x];j[E]||(j[E]={}),j[E][O]=N,r(j),n?.()},[x,v,r,n]);return S.useEffect(()=>{if(x.length<b){const E=b-x.length,O=[];for(let N=0;N<E;N++){const j={};m.forEach(R=>{j[R.name]=R.defaultValue??""}),O.push(j)}r([...x,...O])}},[b,m,r,x.length]),m.length===0?u.jsx(_t,{field:e,error:o,isRequired:a,className:d,children:u.jsx("div",{className:"p-4 border rounded-md bg-muted/50 text-sm text-muted-foreground",children:"No columns defined for this table field"})}):u.jsx(_t,{field:e,error:o,isRequired:a,className:d,children:u.jsxs("div",{id:bt(e),className:W("border rounded-lg overflow-hidden shadow-sm bg-background",o&&"border-destructive",v&&"opacity-50"),style:p?.minWidth?{minWidth:p.minWidth}:void 0,"aria-describedby":Vt(e,!!o),"aria-invalid":Zt(!!o),"aria-required":a,children:[u.jsx("div",{className:"overflow-x-auto",children:u.jsxs("table",{className:"w-full border-collapse text-sm",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"border-b border-border bg-muted/60",children:[m.map(E=>u.jsxs("th",{className:"px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-muted-foreground whitespace-nowrap first:pl-6 last:pr-6",children:[E.label,a&&E.validation?.some(O=>O.type==="required")&&u.jsx("span",{className:"text-destructive ml-1",children:"*"})]},E.id)),w&&u.jsx("th",{className:"w-12"})]})}),u.jsx("tbody",{children:x.length===0?u.jsx("tr",{children:u.jsx("td",{colSpan:m.length+(w?1:0),className:"px-6 py-8 text-center text-sm text-muted-foreground",children:c?"No rows to display.":'No rows added yet. Click "Add Row" to get started.'})}):x.map((E,O)=>{const N=x[O],j=N&&typeof N=="object"&&!Array.isArray(N)?{...l??{},...N}:l;return u.jsxs("tr",{className:"border-b border-border/50 hover:bg-muted/30 transition-colors last:border-b-0",children:[m.map(R=>{const M={...R,name:`${e.name}_${O}_${R.name}`,appearance:{...R.appearance,hideLabel:!0}},B=R.name??"",P=E[B]!==void 0?E[B]:B&&Object.keys(E).find(z=>z.toLowerCase()===B.toLowerCase())?E[Object.keys(E).find(z=>z.toLowerCase()===B.toLowerCase())]:void 0,H=!!R.readOnly,D=z=>{if(z==null)return"";if(Array.isArray(z))return z.map(V=>typeof V=="object"&&V!==null&&"name"in V?String(V.name??V):String(V)).join(", ");if(typeof z=="object"&&z!==null&&!(z instanceof Date)){const V=z;return typeof V.name=="string"&&typeof V.code=="string"?`${V.code} ${V.name}`.trim():typeof V.name=="string"?V.name:typeof V.code=="string"?V.code:String(V.name??V.code??z)}return String(z)},K=z=>typeof z=="object"&&z!==null&&!Array.isArray(z)?D(z):String(z??""),q=R.name?.toLowerCase()==="type"||R.label?.toLowerCase()==="type";if(H){const z=D(P);return u.jsx("td",{className:"px-4 py-2.5 align-middle first:pl-6 last:pr-6",children:u.jsx("div",{className:"min-w-[120px] text-sm text-foreground",children:q&&z?u.jsx("span",{className:"inline-flex items-center rounded-full bg-primary/10 text-primary px-2.5 py-0.5 text-xs font-medium",children:z}):u.jsx("span",{className:"py-1 block",children:z})})},R.id)}const L=()=>{switch(R.type){case"text":case"password":case"url":return u.jsx(aa,{field:M,value:K(P),onChange:z=>_(O,R.name,z),disabled:v,readOnly:v,className:"w-full"});case"number":return u.jsx(Zc,{field:M,value:P??null,onChange:z=>_(O,R.name,z),disabled:v,readOnly:v,className:"w-full"});case"email":return u.jsx(ld,{field:M,value:K(P),onChange:z=>_(O,R.name,z),disabled:v,readOnly:v,className:"w-full"});case"phone":case"aadhaar":return u.jsx(cd,{field:M,value:K(P),onChange:z=>_(O,R.name,z),disabled:v,readOnly:v,className:"w-full"});case"textarea":return u.jsx(dd,{field:M,value:K(P),onChange:z=>_(O,R.name,z),disabled:v,readOnly:v,className:"w-full"});case"select":return u.jsx(Ff,{field:M,value:typeof P=="string"?P:K(P),onChange:z=>_(O,R.name,z),disabled:v,className:"w-full",formValues:j,submissionContext:f});case"multiselect":{const z=Array.isArray(P)?P:P!=null&&P!==""?[String(P)]:[];return u.jsx(Cp,{field:M,value:z,onChange:V=>_(O,R.name,V),disabled:v,className:"w-full",formValues:j,submissionContext:f})}case"asyncsearch":return u.jsx(tp,{field:M,value:P,onChange:z=>_(O,R.name,z),disabled:v,readOnly:v,className:"w-full",formValues:j,submissionContext:f});case"checkbox":return u.jsx(Ep,{field:M,value:P||!1,onChange:z=>_(O,R.name,z),disabled:v,className:"w-full"});case"radio":case"checkboxgroup":return u.jsx(Xp,{field:M,value:typeof P=="string"?P:K(P),onChange:z=>_(O,R.name,z),disabled:v,className:"w-full"});case"date":case"time":case"datetime":case"daterange":return u.jsx(Jp,{field:M,value:typeof P=="string"?P:K(P),onChange:z=>_(O,R.name,z),disabled:v,readOnly:v,className:"w-full"});default:return u.jsx(aa,{field:M,value:K(P),onChange:z=>_(O,R.name,z),disabled:v,readOnly:v,className:"w-full"})}};return u.jsx("td",{className:"px-4 py-2.5 align-middle first:pl-6 last:pr-6",children:u.jsx("div",{className:"min-w-[160px] w-full [&_input]:min-w-[10rem] [&_input]:overflow-visible [&_textarea]:min-h-[2.5rem]",children:L()})},R.id)}),w&&u.jsx("td",{className:"px-2 py-2",children:u.jsx(yr,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>C(O),disabled:!I||v,children:u.jsx(ko,{className:"h-4 w-4"})})})]},O)})})]})}),A&&u.jsx("div",{className:"p-3 border-t bg-muted/30",children:u.jsxs(yr,{type:"button",variant:"outline",size:"sm",onClick:T,disabled:v,className:"w-full",children:[u.jsx(id,{className:"h-4 w-4 mr-2"}),"Add Row"]})})]})})},sE=({field:e,value:t,error:r,disabled:n,isRequired:o,className:s,formValues:i={},submissionContext:a,extraSubmitPayload:d,skipApiCall:c=!1,prepopulateResponse:l=null})=>{const f=e.properties||{},p=f.source??"manual",m=Array.isArray(f.statuses)?f.statuses:[],b=(f.dataPath||"data").trim(),h=f.showStatusText===!0,g=(f.statusTextPath||"data.admissionStatus").trim(),w=f.showCurrentIndicator!==!1,[v,x]=S.useState(null),[A,I]=S.useState(!1),[T,C]=S.useState(null),_=zi.useParams(),E=S.useRef(i),O=S.useRef(a),N=S.useRef(d),j=S.useRef(_);E.current=i,O.current=a,N.current=d,j.current=_;const R=S.useCallback(async()=>{const D=f.apiEndpoint?.trim();if(!D){C("Status API endpoint is not configured");return}I(!0),C(null);try{const K=O.current,q=N.current,L=K!=null&&typeof K=="object"?{...K,...q||{}}:q||{},z=Gr(Yr(D,E.current,j.current,L,void 0,l??void 0)),V=(f.apiMethod||"GET").toUpperCase(),le=await fetch(z,{method:V,headers:V==="POST"?{"Content-Type":"application/json"}:void 0});if(!le.ok)throw new Error(`HTTP ${le.status}`);const re=await le.json(),ne=b?pt(re,b):re;x(ne&&typeof ne=="object"?ne:{})}catch(K){C(K instanceof Error?K.message:"Failed to load status"),x(null)}finally{I(!1)}},[f.apiEndpoint,f.apiMethod,b,l]);S.useEffect(()=>{p==="api"&&!c&&R()},[p,c,R]);const M=p==="api"?v:t&&typeof t=="object"?(b?pt(t,b):null)??t:null,B=h&&g&&M?String(pt(M,g)??pt({data:M},g)??""):"",P=D=>{if(!M||typeof M!="object")return!1;const K=M[D];return K===!0||K==="true"||K===1};let H=!1;return u.jsx(_t,{field:e,error:r||T||void 0,isRequired:o,className:W(s,"!space-y-0 h-full min-h-0 flex flex-col"),children:u.jsxs("div",{className:"rounded-lg border bg-card p-4 h-full min-h-0 flex flex-col",children:[A&&u.jsx("div",{className:"text-sm text-muted-foreground py-2",children:"Loading status..."}),h&&B&&!A&&u.jsx("p",{className:"text-sm text-muted-foreground mb-3 shrink-0","data-status-text":!0,children:B}),!A&&u.jsx("ul",{className:"flex-1 min-h-0 flex flex-col gap-y-8 overflow-y-auto pr-1 py-1",children:m.map(D=>{const K=P(D.key),q=w&&K&&!H;return q&&(H=!0),u.jsxs("li",{className:W("flex items-center gap-3 text-sm",K?"text-foreground":"text-muted-foreground"),children:[K?u.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-green-600 text-white","aria-hidden":!0,children:u.jsx(ps,{className:"h-3 w-3"})}):u.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 border-muted-foreground/40 bg-muted/50","aria-hidden":!0,children:u.jsx(nd,{className:"h-2.5 w-2.5 text-muted-foreground/60"})}),u.jsx("span",{className:"flex-1 min-w-0",children:D.label}),q&&u.jsx("span",{className:"shrink-0 text-xs font-medium text-primary",children:"Current"})]},D.key)})}),!A&&m.length===0&&u.jsx("p",{className:"text-sm text-muted-foreground",children:"No statuses configured."})]})})};function kl(e,t){if(!t||!e)return;const r=t.split(".");let n=e;for(const o of r){if(n==null||typeof n!="object")return;n=n[o]}return n}function lo(e,t){if(t){const r=kl(e,t);if(r!=null)return String(r)}return e.email!=null?String(e.email):e.personal_email!=null?String(e.personal_email):e.id!=null?String(e.id):JSON.stringify(e)}function iE(e,t,r,n){if(r?.length){const s=n??" | ",i=r.map(a=>kl(e,a)).filter(a=>a!=null).map(a=>String(a));if(i.length)return i.join(s)}if(t){const s=kl(e,t);if(s!=null)return String(s)}if(e.name!=null&&e.email!=null)return`${e.name} <${e.email}>`;if(e.name!=null)return String(e.name);if(e.email!=null)return String(e.email);const o=e.personal_email;return o!=null?String(o):JSON.stringify(e)}const aE=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a,submissionContext:d})=>{const c=e.properties||{},{dataSourceContextKey:l,labelField:f="name",valueField:p="email",displayFields:m,displayFieldsSeparator:b=" | ",showSelectAll:h=!0,selectAllByDefault:g=!0}=c;console.log("[SelectableList] Step 1: render",{fieldName:e.name,valueIsArray:Array.isArray(t),valueLength:Array.isArray(t)?t.length:0,valueSample:Array.isArray(t)&&t.length>0?t.slice(0,2):t,submissionContextKeys:d?Object.keys(d):[],dataSourceContextKey:l,contextKeyValue:d&&l?d[l]:void 0});const w=S.useMemo(()=>{if(!l||!d)return[];const N=d[l];return Array.isArray(N)?N:[]},[l,d]);console.log("[SelectableList] Step 2: contextList from submissionContext",{fieldName:e.name,contextListLength:w.length,contextListSample:w.length>0?w.slice(0,2):[]});const[v,x]=S.useState(()=>w.length>0?w:Array.isArray(t)?t:[]);S.useEffect(()=>{if(w.length>0){console.log("[SelectableList] Step 3: sync fullList from context",{fieldName:e.name,contextListLength:w.length}),x(w);return}Array.isArray(t)&&t.length>0&&x(N=>{const j=N.length===0||t.length>N.length?t:N;return console.log("[SelectableList] Step 3: sync fullList from value",{fieldName:e.name,valueLength:t.length,prevLength:N.length,nextLength:j.length}),j})},[w,t]);const A=S.useMemo(()=>{const N=Array.isArray(t)?t:[];return new Set(N.map(R=>lo(R,p)))},[t,p]),I=v.length>0&&v.every(N=>A.has(lo(N,p))),T=v.some(N=>A.has(lo(N,p))),C=S.useCallback((N,j)=>{const R=lo(N,p),M=Array.isArray(t)?t:[];j?A.has(R)||r([...M,N]):r(M.filter(B=>lo(B,p)!==R)),n?.()},[t,p,A,r,n]),_=S.useCallback(N=>{r(N===!0?[...v]:[]),n?.()},[v,r,n]),E=v.length>0?v:Array.isArray(t)?t:[],O=s||e.disabled;return console.log("[SelectableList] Data in list",{fieldName:e.name,listLength:E.length,listSource:v.length>0?"fullList":"value",valueLength:Array.isArray(t)?t.length:0,fullListLength:v.length,listData:E.length>0?E:[],listDataFirstThree:E.length>0?E.slice(0,3):[]}),u.jsx("div",{className:W("relative z-10 flex flex-col min-h-0 h-full w-full",E.length>0&&"min-h-[14rem]",a),children:u.jsx(_t,{field:e,error:o,isRequired:i,className:W("flex-1 min-h-0 flex flex-col",E.length>0&&"min-h-[14rem]"),children:u.jsx("div",{className:W("flex-1 min-h-0 flex flex-col",E.length>0&&"min-h-[14rem]"),children:u.jsxs("div",{className:W("flex-1 min-h-0 flex flex-col",E.length>0&&"overflow-visible"),children:[u.jsxs("div",{role:"listbox","aria-multiselectable":!0,className:W("border rounded-md divide-y overflow-y-auto overflow-x-hidden bg-muted/30 overscroll-contain touch-pan-y pb-3 pr-3 z-20 relative",E.length>0?"flex-1 min-h-0":"min-h-0"),children:[h&&E.length>0&&u.jsxs("div",{className:"flex flex-wrap items-center gap-2 px-3 py-2 sticky top-0 bg-background border-b z-10 shrink-0",children:[u.jsx(ti,{id:`${bt(e)}-select-all`,checked:I?!0:T?"indeterminate":!1,onCheckedChange:_,disabled:O,"aria-label":"Select all"}),u.jsxs(xn,{htmlFor:`${bt(e)}-select-all`,className:"text-sm font-medium cursor-pointer",children:["Select all (",E.length,")"]}),u.jsxs("div",{className:"flex gap-1 ml-auto",children:[u.jsx(yr,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",disabled:O||I,onClick:()=>{r([...v]),n?.()},children:"Select all"}),u.jsx(yr,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",disabled:O||!T,onClick:()=>{r([]),n?.()},children:"Unselect all"})]})]}),E.length===0?u.jsx("p",{className:"px-3 py-4 text-sm text-muted-foreground",children:"No items to display."}):u.jsx(u.Fragment,{children:E.map((N,j)=>{const R=lo(N,p),M=A.has(R),B=`${bt(e)}-${j}-${R}`;return u.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 min-h-[2.5rem] hover:bg-muted/50 shrink-0",role:"row",children:[u.jsx(ti,{id:B,checked:M,onCheckedChange:P=>C(N,P===!0),disabled:O,"aria-describedby":Vt(e,!!o)}),u.jsx(xn,{htmlFor:B,className:"text-sm cursor-pointer flex-1 truncate",children:iE(N,f,m,b)})]},R)})})]}),E.length>0&&A.size===0&&u.jsxs("p",{className:"flex items-center gap-1.5 mt-2 text-sm text-amber-600 dark:text-amber-500 shrink-0",role:"status",children:[u.jsx($y,{className:"h-4 w-4 shrink-0"}),"Please select at least one item."]})]})})})})},Pm=({field:e,children:t,className:r})=>{const n=e.properties,o=n?.collapsible??!1,s=n?.defaultCollapsed??!1,i=n?.columns??1,[a,d]=S.useState(s),c=()=>{o&&d(!a)},l={1:"grid-cols-1",2:"grid-cols-1 md:grid-cols-2",3:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3",4:"grid-cols-1 md:grid-cols-2 lg:grid-cols-4"};return u.jsxs("div",{className:W("border rounded-lg bg-card",r),children:[u.jsxs("div",{className:W("flex items-center gap-2 px-4 py-3 border-b bg-muted/50",o&&"cursor-pointer hover:bg-muted/70 transition-colors"),onClick:c,children:[o&&u.jsx("span",{className:"text-muted-foreground",children:a?u.jsx(rd,{className:"h-4 w-4"}):u.jsx(_o,{className:"h-4 w-4"})}),u.jsx("h3",{className:"font-medium text-sm",children:e.label}),e.description&&u.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:e.description})]}),!a&&u.jsx("div",{className:W("p-4 grid gap-4",l[i]),children:t})]})};var lE=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],cE=lE.reduce((e,t)=>{const r=ia(`Primitive.${t}`),n=y.forwardRef((o,s)=>{const{asChild:i,...a}=o,d=i?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(d,{...a,ref:s})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{}),dE="Separator",Im="horizontal",uE=["horizontal","vertical"],Mm=y.forwardRef((e,t)=>{const{decorative:r,orientation:n=Im,...o}=e,s=fE(n)?n:Im,a=r?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return u.jsx(cE.div,{"data-orientation":s,...a,...o,ref:t})});Mm.displayName=dE;function fE(e){return uE.includes(e)}var pE=Mm;function Fl({className:e,orientation:t="horizontal",decorative:r=!0,...n}){return u.jsx(pE,{"data-slot":"separator",decorative:r,orientation:t,className:W("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...n})}const mE=({field:e,className:t})=>u.jsx("div",{className:W("py-2",t),children:u.jsx(Fl,{})}),hE={h1:"text-3xl font-bold",h2:"text-2xl font-bold",h3:"text-xl font-semibold",h4:"text-lg font-semibold",h5:"text-base font-medium",h6:"text-sm font-medium"},gE=({field:e,className:t})=>{const r=e.properties,n=r?.headingLevel??"h3",o=r?.showHorizontalLine??!0,s=hE[n],i=n;return u.jsxs("div",{className:W("w-full min-w-0 space-y-1",t),children:[u.jsx(i,{className:W("m-0 text-foreground",s),children:e.label||"Header"}),e.description&&u.jsx("p",{className:"text-sm text-muted-foreground",children:e.description}),o&&u.jsx(Fl,{className:"w-full"})]})},yE={"top-left":"justify-start","top-center":"justify-center","top-right":"justify-end","middle-left":"justify-start",center:"justify-center","middle-right":"justify-end","bottom-left":"justify-start","bottom-center":"justify-center","bottom-right":"justify-end"},bE={h1:"text-3xl font-bold",h2:"text-2xl font-bold",h3:"text-xl font-semibold",h4:"text-lg font-semibold",h5:"text-base font-medium",h6:"text-sm font-medium"},vE=({field:e,className:t})=>{const r=e.properties,n=r?.position??"top-left",o=r?.headingLevel??"h3",s=r?.showHorizontalLine??!0,i=yE[n],a=bE[o],d=o;return u.jsxs("div",{className:W("w-full min-w-0 space-y-2",t),children:[u.jsx("div",{className:W("flex w-full",i),children:u.jsx(d,{className:W("m-0 text-foreground",a),children:e.label||"Section Heading"})}),s&&u.jsx(Fl,{className:"w-full"})]})},wE=({field:e,className:t})=>{const r=e.appearance?.size||"md",n={sm:"h-4",md:"h-8",lg:"h-12"};return u.jsx("div",{className:W(n[r],t),"aria-hidden":"true"})};function Lm(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function SE(e){if(Array.isArray(e))return e}function xE(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,o,s,i,a=[],d=!0,c=!1;try{if(s=(r=r.call(e)).next,t!==0)for(;!(d=(n=s.call(r)).done)&&(a.push(n.value),a.length!==t);d=!0);}catch(l){c=!0,o=l}finally{try{if(!d&&r.return!=null&&(i=r.return(),Object(i)!==i))return}finally{if(c)throw o}}return a}}function AE(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
51
51
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function CE(e,t){return SE(e)||xE(e,t)||EE(e,t)||AE()}function EE(e,t){if(e){if(typeof e=="string")return Lm(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Lm(e,t):void 0}}const Dm=Object.entries,Bm=Object.setPrototypeOf,TE=Object.isFrozen,_E=Object.getPrototypeOf,NE=Object.getOwnPropertyDescriptor;let or=Object.freeze,Nr=Object.seal,co=Object.create,$m=typeof Reflect<"u"&&Reflect,Ol=$m.apply,Pl=$m.construct;or||(or=function(t){return t}),Nr||(Nr=function(t){return t}),Ol||(Ol=function(t,r){for(var n=arguments.length,o=new Array(n>2?n-2:0),s=2;s<n;s++)o[s-2]=arguments[s];return t.apply(r,o)}),Pl||(Pl=function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return new t(...n)});const uo=$t(Array.prototype.forEach),kE=$t(Array.prototype.lastIndexOf),jm=$t(Array.prototype.pop),fo=$t(Array.prototype.push),FE=$t(Array.prototype.splice),sr=Array.isArray,qo=$t(String.prototype.toLowerCase),Il=$t(String.prototype.toString),Um=$t(String.prototype.match),po=$t(String.prototype.replace),Rm=$t(String.prototype.indexOf),OE=$t(String.prototype.trim),PE=$t(Number.prototype.toString),IE=$t(Boolean.prototype.toString),zm=typeof BigInt>"u"?null:$t(BigInt.prototype.toString),Vm=typeof Symbol>"u"?null:$t(Symbol.prototype.toString),Ot=$t(Object.prototype.hasOwnProperty),Go=$t(Object.prototype.toString),Yt=$t(RegExp.prototype.test),gi=ME(TypeError);function $t(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return Ol(e,t,n)}}function ME(e){return function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return Pl(e,r)}}function ot(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:qo;if(Bm&&Bm(e,null),!sr(t))return e;let n=t.length;for(;n--;){let o=t[n];if(typeof o=="string"){const s=r(o);s!==o&&(TE(t)||(t[n]=s),o=s)}e[o]=!0}return e}function LE(e){for(let t=0;t<e.length;t++)Ot(e,t)||(e[t]=null);return e}function dr(e){const t=co(null);for(const n of Dm(e)){var r=CE(n,2);const o=r[0],s=r[1];Ot(e,o)&&(sr(s)?t[o]=LE(s):s&&typeof s=="object"&&s.constructor===Object?t[o]=dr(s):t[o]=s)}return t}function DE(e){switch(typeof e){case"string":return e;case"number":return PE(e);case"boolean":return IE(e);case"bigint":return zm?zm(e):"0";case"symbol":return Vm?Vm(e):"Symbol()";case"undefined":return Go(e);case"function":case"object":{if(e===null)return Go(e);const t=e,r=Ln(t,"toString");if(typeof r=="function"){const n=r(t);return typeof n=="string"?n:Go(n)}return Go(e)}default:return Go(e)}}function Ln(e,t){for(;e!==null;){const n=NE(e,t);if(n){if(n.get)return $t(n.get);if(typeof n.value=="function")return $t(n.value)}e=_E(e)}function r(){return null}return r}function BE(e){try{return Yt(e,""),!0}catch{return!1}}const Hm=or(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Ml=or(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Ll=or(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),$E=or(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Dl=or(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),jE=or(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Wm=or(["#text"]),qm=or(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Bl=or(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Gm=or(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),yi=or(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),UE=Nr(/{{[\w\W]*|^[\w\W]*}}/g),RE=Nr(/<%[\w\W]*|^[\w\W]*%>/g),zE=Nr(/\${[\w\W]*/g),VE=Nr(/^data-[\-\w.\u00B7-\uFFFF]+$/),HE=Nr(/^aria-[\-\w]+$/),Km=Nr(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),WE=Nr(/^(?:\w+script|data):/i),qE=Nr(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),GE=Nr(/^html$/i),KE=Nr(/^[a-z][.\w]*(-[.\w]+)+$/i),mo={element:1,text:3,progressingInstruction:7,comment:8,document:9},YE=function(){return typeof window>"u"?null:window},XE=function(t,r){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let n=null;const o="data-tt-policy-suffix";r&&r.hasAttribute(o)&&(n=r.getAttribute(o));const s="dompurify"+(n?"#"+n:"");try{return t.createPolicy(s,{createHTML(i){return i},createScriptURL(i){return i}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},Ym=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Xm(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:YE();const t=Oe=>Xm(Oe);if(t.version="3.4.5",t.removed=[],!e||!e.document||e.document.nodeType!==mo.document||!e.Element)return t.isSupported=!1,t;let r=e.document;const n=r,o=n.currentScript,s=e.DocumentFragment,i=e.HTMLTemplateElement,a=e.Node,d=e.Element,c=e.NodeFilter,l=e.NamedNodeMap,f=l===void 0?e.NamedNodeMap||e.MozNamedAttrMap:l,p=e.HTMLFormElement,m=e.DOMParser,b=e.trustedTypes,h=d.prototype,g=Ln(h,"cloneNode"),w=Ln(h,"remove"),v=Ln(h,"nextSibling"),x=Ln(h,"childNodes"),A=Ln(h,"parentNode"),I=a&&a.prototype?Ln(a.prototype,"nodeType"):null;if(typeof i=="function"){const Oe=r.createElement("template");Oe.content&&Oe.content.ownerDocument&&(r=Oe.content.ownerDocument)}let T,C="";const _=r,E=_.implementation,O=_.createNodeIterator,N=_.createDocumentFragment,j=_.getElementsByTagName,R=n.importNode;let M=Ym();t.isSupported=typeof Dm=="function"&&typeof A=="function"&&E&&E.createHTMLDocument!==void 0;const B=UE,P=RE,H=zE,D=VE,K=HE,q=WE,L=qE,z=KE;let V=Km,le=null;const re=ot({},[...Hm,...Ml,...Ll,...Dl,...Wm]);let ne=null;const Z=ot({},[...qm,...Bl,...Gm,...yi]);let Y=Object.seal(co(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),oe=null,ie=null;const G=Object.seal(co(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ve=!0,be=!0,He=!1,he=!0,Ee=!1,ae=!0,ye=!1,je=!1,st=!1,we=!1,ct=!1,Le=!1,ee=!0,Ye=!1;const et="user-content-";let Ue=!0,Q=!1,ce={},ue=null;const xe=ot({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Ae=null;const De=ot({},["audio","video","img","source","image","track"]);let rt=null;const vt=ot({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ge="http://www.w3.org/1998/Math/MathML",ut="http://www.w3.org/2000/svg",We="http://www.w3.org/1999/xhtml";let mt=We,tr=!1,kr=null;const Ht=ot({},[Ge,ut,We],Il);let Fr=ot({},["mi","mo","mn","ms","mtext"]),jr=ot({},["annotation-xml"]);const on=ot({},["title","style","font","a","script"]);let jt=null;const vr=["application/xhtml+xml","text/html"],Bn="text/html";let wt=null,wr=null;const $n=r.createElement("form"),Lt=function(F){return F instanceof RegExp||F instanceof Function},Sr=function(){let F=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(wr&&wr===F)return;(!F||typeof F!="object")&&(F={}),F=dr(F),jt=vr.indexOf(F.PARSER_MEDIA_TYPE)===-1?Bn:F.PARSER_MEDIA_TYPE,wt=jt==="application/xhtml+xml"?Il:qo,le=Ot(F,"ALLOWED_TAGS")&&sr(F.ALLOWED_TAGS)?ot({},F.ALLOWED_TAGS,wt):re,ne=Ot(F,"ALLOWED_ATTR")&&sr(F.ALLOWED_ATTR)?ot({},F.ALLOWED_ATTR,wt):Z,kr=Ot(F,"ALLOWED_NAMESPACES")&&sr(F.ALLOWED_NAMESPACES)?ot({},F.ALLOWED_NAMESPACES,Il):Ht,rt=Ot(F,"ADD_URI_SAFE_ATTR")&&sr(F.ADD_URI_SAFE_ATTR)?ot(dr(vt),F.ADD_URI_SAFE_ATTR,wt):vt,Ae=Ot(F,"ADD_DATA_URI_TAGS")&&sr(F.ADD_DATA_URI_TAGS)?ot(dr(De),F.ADD_DATA_URI_TAGS,wt):De,ue=Ot(F,"FORBID_CONTENTS")&&sr(F.FORBID_CONTENTS)?ot({},F.FORBID_CONTENTS,wt):xe,oe=Ot(F,"FORBID_TAGS")&&sr(F.FORBID_TAGS)?ot({},F.FORBID_TAGS,wt):dr({}),ie=Ot(F,"FORBID_ATTR")&&sr(F.FORBID_ATTR)?ot({},F.FORBID_ATTR,wt):dr({}),ce=Ot(F,"USE_PROFILES")?F.USE_PROFILES&&typeof F.USE_PROFILES=="object"?dr(F.USE_PROFILES):F.USE_PROFILES:!1,ve=F.ALLOW_ARIA_ATTR!==!1,be=F.ALLOW_DATA_ATTR!==!1,He=F.ALLOW_UNKNOWN_PROTOCOLS||!1,he=F.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ee=F.SAFE_FOR_TEMPLATES||!1,ae=F.SAFE_FOR_XML!==!1,ye=F.WHOLE_DOCUMENT||!1,we=F.RETURN_DOM||!1,ct=F.RETURN_DOM_FRAGMENT||!1,Le=F.RETURN_TRUSTED_TYPE||!1,st=F.FORCE_BODY||!1,ee=F.SANITIZE_DOM!==!1,Ye=F.SANITIZE_NAMED_PROPS||!1,Ue=F.KEEP_CONTENT!==!1,Q=F.IN_PLACE||!1,V=BE(F.ALLOWED_URI_REGEXP)?F.ALLOWED_URI_REGEXP:Km,mt=typeof F.NAMESPACE=="string"?F.NAMESPACE:We,Fr=Ot(F,"MATHML_TEXT_INTEGRATION_POINTS")&&F.MATHML_TEXT_INTEGRATION_POINTS&&typeof F.MATHML_TEXT_INTEGRATION_POINTS=="object"?dr(F.MATHML_TEXT_INTEGRATION_POINTS):ot({},["mi","mo","mn","ms","mtext"]),jr=Ot(F,"HTML_INTEGRATION_POINTS")&&F.HTML_INTEGRATION_POINTS&&typeof F.HTML_INTEGRATION_POINTS=="object"?dr(F.HTML_INTEGRATION_POINTS):ot({},["annotation-xml"]);const se=Ot(F,"CUSTOM_ELEMENT_HANDLING")&&F.CUSTOM_ELEMENT_HANDLING&&typeof F.CUSTOM_ELEMENT_HANDLING=="object"?dr(F.CUSTOM_ELEMENT_HANDLING):co(null);if(Y=co(null),Ot(se,"tagNameCheck")&&Lt(se.tagNameCheck)&&(Y.tagNameCheck=se.tagNameCheck),Ot(se,"attributeNameCheck")&&Lt(se.attributeNameCheck)&&(Y.attributeNameCheck=se.attributeNameCheck),Ot(se,"allowCustomizedBuiltInElements")&&typeof se.allowCustomizedBuiltInElements=="boolean"&&(Y.allowCustomizedBuiltInElements=se.allowCustomizedBuiltInElements),Ee&&(be=!1),ct&&(we=!0),ce&&(le=ot({},Wm),ne=co(null),ce.html===!0&&(ot(le,Hm),ot(ne,qm)),ce.svg===!0&&(ot(le,Ml),ot(ne,Bl),ot(ne,yi)),ce.svgFilters===!0&&(ot(le,Ll),ot(ne,Bl),ot(ne,yi)),ce.mathMl===!0&&(ot(le,Dl),ot(ne,Gm),ot(ne,yi))),G.tagCheck=null,G.attributeCheck=null,Ot(F,"ADD_TAGS")&&(typeof F.ADD_TAGS=="function"?G.tagCheck=F.ADD_TAGS:sr(F.ADD_TAGS)&&(le===re&&(le=dr(le)),ot(le,F.ADD_TAGS,wt))),Ot(F,"ADD_ATTR")&&(typeof F.ADD_ATTR=="function"?G.attributeCheck=F.ADD_ATTR:sr(F.ADD_ATTR)&&(ne===Z&&(ne=dr(ne)),ot(ne,F.ADD_ATTR,wt))),Ot(F,"ADD_URI_SAFE_ATTR")&&sr(F.ADD_URI_SAFE_ATTR)&&ot(rt,F.ADD_URI_SAFE_ATTR,wt),Ot(F,"FORBID_CONTENTS")&&sr(F.FORBID_CONTENTS)&&(ue===xe&&(ue=dr(ue)),ot(ue,F.FORBID_CONTENTS,wt)),Ot(F,"ADD_FORBID_CONTENTS")&&sr(F.ADD_FORBID_CONTENTS)&&(ue===xe&&(ue=dr(ue)),ot(ue,F.ADD_FORBID_CONTENTS,wt)),Ue&&(le["#text"]=!0),ye&&ot(le,["html","head","body"]),le.table&&(ot(le,["tbody"]),delete oe.tbody),F.TRUSTED_TYPES_POLICY){if(typeof F.TRUSTED_TYPES_POLICY.createHTML!="function")throw gi('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof F.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw gi('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');T=F.TRUSTED_TYPES_POLICY,C=T.createHTML("")}else T===void 0&&(T=XE(b,o)),T!==null&&typeof C=="string"&&(C=T.createHTML(""));or&&or(F),wr=F},Jt=ot({},[...Ml,...Ll,...$E]),rr=ot({},[...Dl,...jE]),sn=function(F){let se=A(F);(!se||!se.tagName)&&(se={namespaceURI:mt,tagName:"template"});const pe=qo(F.tagName),it=qo(se.tagName);return kr[F.namespaceURI]?F.namespaceURI===ut?se.namespaceURI===We?pe==="svg":se.namespaceURI===Ge?pe==="svg"&&(it==="annotation-xml"||Fr[it]):!!Jt[pe]:F.namespaceURI===Ge?se.namespaceURI===We?pe==="math":se.namespaceURI===ut?pe==="math"&&jr[it]:!!rr[pe]:F.namespaceURI===We?se.namespaceURI===ut&&!jr[it]||se.namespaceURI===Ge&&!Fr[it]?!1:!rr[pe]&&(on[pe]||!Jt[pe]):!!(jt==="application/xhtml+xml"&&kr[F.namespaceURI]):!1},ur=function(F){fo(t.removed,{element:F});try{A(F).removeChild(F)}catch{w(F)}},Ct=function(F,se){try{fo(t.removed,{attribute:se.getAttributeNode(F),from:se})}catch{fo(t.removed,{attribute:null,from:se})}if(se.removeAttribute(F),F==="is")if(we||ct)try{ur(se)}catch{}else try{se.setAttribute(F,"")}catch{}},Qo=function(F){let se=null,pe=null;if(st)F="<remove></remove>"+F;else{const Et=Um(F,/^[\r\n\t ]+/);pe=Et&&Et[0]}jt==="application/xhtml+xml"&&mt===We&&(F='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+F+"</body></html>");const it=T?T.createHTML(F):F;if(mt===We)try{se=new m().parseFromString(it,jt)}catch{}if(!se||!se.documentElement){se=E.createDocument(mt,"template",null);try{se.documentElement.innerHTML=tr?C:it}catch{}}const Nt=se.body||se.documentElement;return F&&pe&&Nt.insertBefore(r.createTextNode(pe),Nt.childNodes[0]||null),mt===We?j.call(se,ye?"html":"body")[0]:ye?se.documentElement:Nt},xr=function(F){return O.call(F.ownerDocument||F,F,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Or=function(F){F.normalize();const se=O.call(F.ownerDocument||F,F,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let pe=se.nextNode();for(;pe;){let it=pe.data;uo([B,P,H],Nt=>{it=po(it,Nt," ")}),pe.data=it,pe=se.nextNode()}},Ar=function(F){return F instanceof p&&(typeof F.nodeName!="string"||typeof F.textContent!="string"||typeof F.removeChild!="function"||!(F.attributes instanceof f)||typeof F.removeAttribute!="function"||typeof F.setAttribute!="function"||typeof F.namespaceURI!="string"||typeof F.insertBefore!="function"||typeof F.hasChildNodes!="function")},fr=function(F){if(!I||typeof F!="object"||F===null)return!1;try{return typeof I(F)=="number"}catch{return!1}};function Wt(Oe,F,se){uo(Oe,pe=>{pe.call(t,F,se,wr)})}const Qt=function(F){let se=null;if(Wt(M.beforeSanitizeElements,F,null),Ar(F))return ur(F),!0;const pe=wt(F.nodeName);if(Wt(M.uponSanitizeElement,F,{tagName:pe,allowedTags:le}),ae&&F.hasChildNodes()&&!fr(F.firstElementChild)&&Yt(/<[/\w!]/g,F.innerHTML)&&Yt(/<[/\w!]/g,F.textContent)||ae&&F.namespaceURI===We&&pe==="style"&&fr(F.firstElementChild)||F.nodeType===mo.progressingInstruction||ae&&F.nodeType===mo.comment&&Yt(/<[/\w]/g,F.data))return ur(F),!0;if(oe[pe]||!(G.tagCheck instanceof Function&&G.tagCheck(pe))&&!le[pe]){if(!oe[pe]&&Ni(pe)&&(Y.tagNameCheck instanceof RegExp&&Yt(Y.tagNameCheck,pe)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(pe)))return!1;if(Ue&&!ue[pe]){const it=A(F)||F.parentNode,Nt=x(F)||F.childNodes;if(Nt&&it){const Et=Nt.length;for(let Pt=Et-1;Pt>=0;--Pt){const Ut=g(Nt[Pt],!0);it.insertBefore(Ut,v(F))}}}return ur(F),!0}return F instanceof d&&!sn(F)||(pe==="noscript"||pe==="noembed"||pe==="noframes")&&Yt(/<\/no(script|embed|frames)/i,F.innerHTML)?(ur(F),!0):(Ee&&F.nodeType===mo.text&&(se=F.textContent,uo([B,P,H],it=>{se=po(se,it," ")}),F.textContent!==se&&(fo(t.removed,{element:F.cloneNode()}),F.textContent=se)),Wt(M.afterSanitizeElements,F,null),!1)},Pr=function(F,se,pe){if(ie[se]||ee&&(se==="id"||se==="name")&&(pe in r||pe in $n))return!1;const it=ne[se]||G.attributeCheck instanceof Function&&G.attributeCheck(se,F);if(!(be&&!ie[se]&&Yt(D,se))){if(!(ve&&Yt(K,se))){if(!it||ie[se]){if(!(Ni(F)&&(Y.tagNameCheck instanceof RegExp&&Yt(Y.tagNameCheck,F)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(F))&&(Y.attributeNameCheck instanceof RegExp&&Yt(Y.attributeNameCheck,se)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(se,F))||se==="is"&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&Yt(Y.tagNameCheck,pe)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(pe))))return!1}else if(!rt[se]){if(!Yt(V,po(pe,L,""))){if(!((se==="src"||se==="xlink:href"||se==="href")&&F!=="script"&&Rm(pe,"data:")===0&&Ae[F])){if(!(He&&!Yt(q,po(pe,L,"")))){if(pe)return!1}}}}}}return!0},_i=ot({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Ni=function(F){return!_i[qo(F)]&&Yt(z,F)},ki=function(F){Wt(M.beforeSanitizeAttributes,F,null);const se=F.attributes;if(!se||Ar(F))return;const pe={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ne,forceKeepAttr:void 0};let it=se.length;for(;it--;){const Nt=se[it],Et=Nt.name,Pt=Nt.namespaceURI,Ut=Nt.value,kt=wt(Et),lt=Ut;let xt=Et==="value"?lt:OE(lt);if(pe.attrName=kt,pe.attrValue=xt,pe.keepAttr=!0,pe.forceKeepAttr=void 0,Wt(M.uponSanitizeAttribute,F,pe),xt=pe.attrValue,Ye&&(kt==="id"||kt==="name")&&Rm(xt,et)!==0&&(Ct(Et,F),xt=et+xt),ae&&Yt(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,xt)){Ct(Et,F);continue}if(kt==="attributename"&&Um(xt,"href")){Ct(Et,F);continue}if(pe.forceKeepAttr)continue;if(!pe.keepAttr){Ct(Et,F);continue}if(!he&&Yt(/\/>/i,xt)){Ct(Et,F);continue}Ee&&uo([B,P,H],pr=>{xt=po(xt,pr," ")});const Ir=wt(F.nodeName);if(!Pr(Ir,kt,xt)){Ct(Et,F);continue}if(T&&typeof b=="object"&&typeof b.getAttributeType=="function"&&!Pt)switch(b.getAttributeType(Ir,kt)){case"TrustedHTML":{xt=T.createHTML(xt);break}case"TrustedScriptURL":{xt=T.createScriptURL(xt);break}}if(xt!==lt)try{Pt?F.setAttributeNS(Pt,Et,xt):F.setAttribute(Et,xt),Ar(F)?ur(F):jm(t.removed)}catch{Ct(Et,F)}}Wt(M.afterSanitizeAttributes,F,null)},Zo=function(F){let se=null;const pe=xr(F);for(Wt(M.beforeSanitizeShadowDOM,F,null);se=pe.nextNode();)Wt(M.uponSanitizeShadowNode,se,null),Qt(se),ki(se),se.content instanceof s&&Zo(se.content);Wt(M.afterSanitizeShadowDOM,F,null)},Cr=function(F){if(F.nodeType===mo.element&&F.shadowRoot instanceof s){const it=F.shadowRoot;Cr(it),Zo(it)}const se=F.childNodes;if(!se)return;const pe=[];uo(se,it=>{fo(pe,it)});for(const it of pe)Cr(it)};return t.sanitize=function(Oe){let F=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},se=null,pe=null,it=null,Nt=null;if(tr=!Oe,tr&&(Oe="<!-->"),typeof Oe!="string"&&!fr(Oe)&&(Oe=DE(Oe),typeof Oe!="string"))throw gi("dirty is not a string, aborting");if(!t.isSupported)return Oe;if(je||Sr(F),t.removed=[],typeof Oe=="string"&&(Q=!1),Q){const Ut=Oe.nodeName;if(typeof Ut=="string"){const kt=wt(Ut);if(!le[kt]||oe[kt])throw gi("root node is forbidden and cannot be sanitized in-place")}Cr(Oe)}else if(fr(Oe))se=Qo("<!---->"),pe=se.ownerDocument.importNode(Oe,!0),pe.nodeType===mo.element&&pe.nodeName==="BODY"||pe.nodeName==="HTML"?se=pe:se.appendChild(pe),Cr(pe);else{if(!we&&!Ee&&!ye&&Oe.indexOf("<")===-1)return T&&Le?T.createHTML(Oe):Oe;if(se=Qo(Oe),!se)return we?null:Le?C:""}se&&st&&ur(se.firstChild);const Et=xr(Q?Oe:se);for(;it=Et.nextNode();)Qt(it),ki(it),it.content instanceof s&&Zo(it.content);if(Q)return Ee&&Or(Oe),Oe;if(we){if(Ee&&Or(se),ct)for(Nt=N.call(se.ownerDocument);se.firstChild;)Nt.appendChild(se.firstChild);else Nt=se;return(ne.shadowroot||ne.shadowrootmode)&&(Nt=R.call(n,Nt,!0)),Nt}let Pt=ye?se.outerHTML:se.innerHTML;return ye&&le["!doctype"]&&se.ownerDocument&&se.ownerDocument.doctype&&se.ownerDocument.doctype.name&&Yt(GE,se.ownerDocument.doctype.name)&&(Pt="<!DOCTYPE "+se.ownerDocument.doctype.name+`>
|
|
52
|
-
`+Pt),Ee&&uo([B,P,H],Ut=>{Pt=po(Pt,Ut," ")}),T&&Le?T.createHTML(Pt):Pt},t.setConfig=function(){let Oe=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Sr(Oe),je=!0},t.clearConfig=function(){wr=null,je=!1},t.isValidAttribute=function(Oe,F,se){wr||Sr({});const pe=wt(Oe),it=wt(F);return Pr(pe,it,se)},t.addHook=function(Oe,F){typeof F=="function"&&fo(M[Oe],F)},t.removeHook=function(Oe,F){if(F!==void 0){const se=kE(M[Oe],F);return se===-1?void 0:FE(M[Oe],se,1)[0]}return jm(M[Oe])},t.removeHooks=function(Oe){M[Oe]=[]},t.removeAllHooks=function(){M=Ym()},t}var JE=Xm();const QE=["a","b","br","div","em","h1","h2","h3","h4","h5","h6","i","img","li","ol","p","span","strong","table","tbody","td","th","thead","tr","u","ul"],ZE=["href","target","rel","src","alt","title","class","style","colspan","rowspan"];function eT(e){return e?JE.sanitize(e,{ALLOWED_TAGS:[...QE],ALLOWED_ATTR:[...ZE],ALLOW_DATA_ATTR:!1}):""}function tT(e,t,r=!1){return e.includes("{labelapi:")?e.replace(/\{labelapi:([^}]+)\}/g,(n,o)=>{const s=o.trim();if(s===""||t==null)return r?"":n;const i=pt(t,s);return i==null?r?"":n:String(i)}):e}function rT(e){return e&&e.replace(/\{api:[^}]*\}/gi,"").replace(/\{labelapi:[^}]*\}/gi,"").replace(/\{resp:[^}]*\}/gi,"").replace(/\{(?:ctx:|@)\w+\}/gi,"").replace(/\{documentId\}/gi,"").replace(/\{(\w+)\}/g,"")}const Jm={sm:"text-sm",md:"text-base",lg:"text-lg"},Qm={h1:"text-4xl font-bold tracking-tight",h2:"text-3xl font-semibold tracking-tight",h3:"text-2xl font-semibold",h4:"text-xl font-semibold",h5:"text-lg font-medium",h6:"text-base font-medium"},Zm={normal:"font-normal",medium:"font-medium",bold:"font-bold"},bi={left:"text-left",center:"text-center",right:"text-right",justify:"text-justify"};function Dn(e){return e.properties??{}}function nT(e){const t=Dn(e);return t.textContent!==void 0?t.textContent:e.label??""}function oT(e){return Dn(e).textContent===void 0||e.appearance?.hideLabel?!1:!!e.label?.trim()}function sT(e){return e?.contentLayout==="paragraph"?"paragraph":"single"}function $l(e,t={}){const{formValues:r={},urlParams:n={},submissionContext:o,buttonResponses:s,prepopulateResponse:i,labelApiResponse:a}=t,d=Yr(e,r,n,o,s,i),c=tT(d,a,!0);return rT(c)}const iT=/\{api:[^}]+\}/,aT=/\{labelapi:[^}]+\}/;function jl(e){return iT.test(e)}function Ul(e){return aT.test(e)}function lT(e){const t=e.captionTemplate??"",r=e.descriptionTemplate??"",n=jl(e.bodyTemplate)||jl(t)||jl(r),o=Ul(e.bodyTemplate)||Ul(t)||Ul(r);return!!(n&&e.prepopulateLoading||o&&e.labelApiConfigPresent&&(e.labelApiLoading||e.labelApiResponse===void 0&&e.labelApiError==null))}function eh(e,t){const r=t??Dn(e),n=r.variant??"body",o=e.appearance?.size??"md",s=Jm[o]??Jm.md,i=r.fontWeight??"medium";return n!=="body"?W("m-0 text-foreground",Qm[n]??Qm.h3,r.fontWeight&&Zm[r.fontWeight],r.italic&&"italic",r.underline&&"underline",r.textAlign&&bi[r.textAlign]):W("m-0 text-foreground",s,Zm[i],r.italic&&"italic",r.underline&&"underline",r.textAlign&&bi[r.textAlign])}function cT(e,t){const r=(t??Dn(e)).variant??"body";return r==="body"?"p":r}function Rl(e){const t=[];let r=0,n="";const o=()=>{n&&(t.push({type:"text",value:n}),n="")},s=(i,a,d)=>{if(!e.startsWith(i,r))return!1;const c=e.indexOf(a,r+i.length);if(c===-1)return!1;o();const l=e.slice(r+i.length,c);return t.push({type:d,children:Rl(l)}),r=c+a.length,!0};for(;r<e.length;){if(e[r]==="\\"&&r+1<e.length){n+=e[r+1],r+=2;continue}s("**","**","bold")||s("__","__","underline")||s("*","*","italic")||s("_","_","italic")||(n+=e[r],r+=1)}return o(),t}function dT(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function th(e){return e.map(t=>{if(t.type==="text")return dT(t.value);const r=th(t.children);return t.type==="bold"?`<strong class="font-bold">${r}</strong>`:t.type==="italic"?`<em class="italic">${r}</em>`:`<u class="underline">${r}</u>`}).join("")}function uT(e){return e?th(Rl(e)):""}function fT(e,t){return e?t==="markdown-lite"?uT(e):e:""}function rh(e,t){return e.map((r,n)=>{const o=`${t}-${n}`;if(r.type==="text")return r.value?S.createElement(S.Fragment,{key:o},r.value):null;const s=rh(r.children,o);return r.type==="bold"?S.createElement("strong",{key:o,className:"font-bold"},s):r.type==="italic"?S.createElement("em",{key:o,className:"italic"},s):S.createElement("u",{key:o,className:"underline"},s)})}function nh(e,t){if(!e)return null;if(t!=="markdown-lite")return e;const r=Rl(e);return r.length===1&&r[0]?.type==="text"?r[0].value:rh(r,"tl")}const pT="text-label-html prose prose-sm max-w-none [&_p]:m-0 [&_p+p]:mt-2 [&_ul]:my-1 [&_ol]:my-1";function oh(e,t){if(!e)return null;const{field:r,asDescription:n=!1}=t,o=t.textProps??Dn(r),s=t.contentLayout??sT(o),i=o.inlineFormat??"none";if(s==="paragraph"){const d=eT(fT(e,i));if(!d)return null;const c=n?W("m-0 text-sm",o.descriptionMuted!==!1?"text-muted-foreground":"text-foreground",o.textAlign&&bi[o.textAlign]):W(eh(r,o),pT);return S.createElement("div",{className:c,dangerouslySetInnerHTML:{__html:d}})}if(n)return S.createElement("p",{className:W("mt-0.5 text-sm",o.descriptionMuted!==!1?"text-muted-foreground":"text-foreground",o.textAlign&&bi[o.textAlign])},nh(e,i));const a=cT(r,o);return S.createElement(a,{className:eh(r,o)},nh(e,i))}function mT(e){const t=e.labelApiEndpoint?.trim();return!e.labelApiEnabled||!t?null:{labelApiEndpoint:t,labelApiMethod:e.labelApiMethod??"GET",labelApiQueryParams:e.labelApiQueryParams,labelApiHeaders:e.labelApiHeaders,labelApiBodyFields:e.labelApiBodyFields}}async function hT(e,t={}){const{formValues:r={},urlParams:n={},submissionContext:o}=t,s=f=>Yr(f,r,n,o),i=(e.labelApiMethod??"GET").toUpperCase();let a=Gr(s(e.labelApiEndpoint));const d=e.labelApiQueryParams??[];if(d.length){const f=new URLSearchParams;d.forEach(({key:m,value:b})=>{m.trim()&&f.append(m,s(b))});const p=f.toString();p&&(a=`${a}${a.includes("?")?"&":"?"}${p}`)}const c={"Content-Type":"application/json"};(e.labelApiHeaders??[]).forEach(({key:f,value:p})=>{f.trim()&&(c[f]=s(p))});let l;i==="POST"&&(e.labelApiBodyFields??[]).length&&(l={},e.labelApiBodyFields.forEach(({key:f,value:p})=>{f.trim()&&(l[f]=s(p))}));try{return i==="POST"?(await Pn.post(a,l??{},{headers:Object.keys(c).length?c:void 0})).data:(await Pn.get(a,{headers:Object.keys(c).length?c:void 0})).data}catch(f){const p=f,m=p.response?.status,b=typeof p.response?.data=="string"?p.response.data:p.message??"Request failed";throw new Error(m?`HTTP ${m}: ${b}`:String(b))}}const gT=({field:e,className:t,formValues:r,urlParams:n,submissionContext:o,buttonResponses:s,prepopulateResponse:i,prepopulateLoading:a=!1})=>{const d=Dn(e),c=S.useMemo(()=>mT(Dn(e)),[e.properties]),[l,f]=S.useState(void 0),[p,m]=S.useState(!1),[b,h]=S.useState(null),g=S.useMemo(()=>c?JSON.stringify({endpoint:c.labelApiEndpoint,method:c.labelApiMethod,query:c.labelApiQueryParams,headers:c.labelApiHeaders,body:c.labelApiBodyFields}):"",[c]),w=S.useCallback(async()=>{if(!c){f(void 0),h(null),m(!1);return}m(!0),h(null);try{const j=await hT(c,{formValues:r??{},urlParams:n??{},submissionContext:o});f(j)}catch(j){f(void 0),h(j instanceof Error?j.message:"Failed to load label API")}finally{m(!1)}},[c,r,n,o]);S.useEffect(()=>{g&&w()},[g,w]);const v=d.textAlign==="center"?"items-center":d.textAlign==="right"?"items-end":d.textAlign==="justify"?"items-stretch":"items-start",x=nT(e),A=oT(e),I=A&&e.label?e.label:"",T=e.description??"",C=lT({bodyTemplate:x,captionTemplate:I,descriptionTemplate:T,prepopulateLoading:a,labelApiConfigPresent:c!=null,labelApiLoading:p,labelApiResponse:l,labelApiError:b}),_={formValues:r??{},urlParams:n??{},submissionContext:o,buttonResponses:s,prepopulateResponse:i,labelApiResponse:l},E=x?$l(x,_):"",O=A&&e.label?$l(e.label,_):"",N=T?$l(T,_):"";return u.jsx("div",{className:W("w-full min-w-0 h-full min-h-[95px] flex flex-col justify-center py-0.5",v,t),children:C?u.jsx("p",{className:"text-sm text-muted-foreground m-0",children:"Loading…"}):u.jsxs(u.Fragment,{children:[b&&c?u.jsx("p",{className:"text-[10px] text-destructive mb-0.5",title:b,children:"Label API failed"}):null,O?u.jsx("div",{className:"text-sm font-medium text-foreground mb-1 w-full",children:O}):null,E?oh(E,{field:e,textProps:d}):null,N?oh(N,{field:e,textProps:d,asDescription:!0}):null]})})},zl=({legend:e,children:t,className:r,collapsible:n=!1,defaultCollapsed:o=!1,headerActions:s,onCollapsedChange:i})=>{const[a,d]=S.useState(o),c=S.useId(),l=f=>{f.stopPropagation(),n&&d(p=>{const m=!p;return i?.(m),m})};return u.jsxs("fieldset",{className:W("min-w-0 rounded-lg border bg-card p-4",r),"data-form-renderer":"config-section-border",children:[n?u.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2 border-b border-border pb-2",children:[u.jsxs("button",{type:"button",className:W("flex min-w-0 flex-1 items-center gap-2 text-left text-sm font-medium text-foreground","cursor-pointer rounded-sm hover:bg-muted/70 transition-colors focus:outline-none focus:ring-2 focus:ring-ring"),"aria-expanded":!a,"aria-controls":c,onClick:l,children:[u.jsx("span",{className:"shrink-0 text-muted-foreground","aria-hidden":!0,children:a?u.jsx(rd,{className:"h-4 w-4"}):u.jsx(_o,{className:"h-4 w-4"})}),u.jsx("span",{className:"truncate",children:e})]}),s!=null?u.jsx("div",{className:"shrink-0",children:s}):null]}):u.jsx("legend",{className:"px-1 text-sm font-medium text-foreground",children:e}),!a&&u.jsxs("div",{id:c,className:"space-y-3",children:[!n&&s!=null?u.jsx("div",{className:"flex justify-end",children:s}):null,t]})]})},nn=({field:e,value:t,error:r,onChange:n,onBlur:o,disabled:s,readOnly:i,isRequired:a,className:d,formValues:c={},submissionContext:l,onSubmit:f,onReset:p,onCancel:m,isSubmitting:b,bffSubmitApi:h,onBffSubmitResult:g,extraSubmitPayload:w,buttonResponses:v,onButtonApiResponse:x,onValidateForm:A,getValidationErrors:I,allFields:T,onSubmittingChange:C,onAddMore:_,scopedFormValues:E,scopedFieldNameMap:O,excludedOptionValues:N,prepopulateMappedFieldNames:j,fieldValueKey:R,hideTableRowControls:M=!1,urlParams:B={},prepopulateResponse:P=null,prepopulateLoading:H=!1})=>{switch(e.type){case"divider":return u.jsx(mE,{field:e,className:d});case"header":return u.jsx(gE,{field:e,className:d});case"sectionHeading":return u.jsx(vE,{field:e,className:d});case"spacer":return u.jsx(wE,{field:e,className:d});case"textLabel":return u.jsx(gT,{field:e,className:d,formValues:c,urlParams:B,submissionContext:l,buttonResponses:v,prepopulateResponse:P??void 0,prepopulateLoading:H});case"status":return u.jsx(sE,{field:e,value:t??null,error:r,disabled:s,isRequired:a,className:d,formValues:c,submissionContext:l,extraSubmitPayload:w,prepopulateResponse:P})}switch(e.type){case"text":case"password":case"url":return u.jsx(aa,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"number":return u.jsx(Zc,{field:e,value:t??null,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"email":return u.jsx(ld,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"phone":case"aadhaar":return u.jsx(cd,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"textarea":case"richtext":return u.jsx(dd,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"select":{const D=R??e.name??e.key??e.id,K=!!(D&&j?.has(D));return u.jsx(Ff,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,formValues:c,submissionContext:l,excludedOptionValues:N,isPrepopulateTarget:K})}case"multiselect":{const D=Array.isArray(t)?t:t!=null&&t!==""?[String(t)]:[];return u.jsx(Cp,{field:e,value:D,onChange:K=>n(K),onBlur:o,error:r,disabled:s,isRequired:a,className:d,formValues:c,submissionContext:l,excludedOptionValues:N})}case"asyncsearch":return u.jsx(tp,{field:e,value:t,onChange:D=>n(D),onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d,formValues:c,submissionContext:l});case"checkbox":case"terms":return u.jsx(Ep,{field:e,value:t||!1,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d});case"toggle":return u.jsx(gA,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d});case"radio":case"checkboxgroup":return u.jsx(Xp,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,excludedOptionValues:N});case"selectablelist":{const D=Array.isArray(t)?t:[];return console.log("[SelectableList] FieldRenderer: passing to SelectableListField",{fieldName:e.name,value:D,valueLength:D.length,submissionContextKeys:l?Object.keys(l):[]}),u.jsx(aE,{field:e,value:D,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,submissionContext:l})}case"date":case"time":case"datetime":case"daterange":return u.jsx(Jp,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"file":return u.jsx(RA,{field:e,value:t,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,buttonResponses:v});case"camera":return u.jsx(vC,{field:e,value:t??null,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d});case"photoChoice":return u.jsx(wC,{field:e,value:t??null,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,buttonResponses:v});case"signature":return u.jsx(nE,{field:e,value:t||null,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"rating":return u.jsx(LC,{field:e,value:t||0,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"slider":return u.jsx(rE,{field:e,value:t||0,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"table":return u.jsx(oE,{field:e,value:t||[],onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d,hideRowControls:M,formValues:c,submissionContext:l});case"button":return u.jsx(PC,{field:e,value:t,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d,onSubmit:f,onReset:p,onCancel:m,isSubmitting:b,formValues:c,submissionContext:l,buttonResponses:v,onButtonApiResponse:x,bffSubmitApi:h,onBffSubmitResult:g,extraSubmitPayload:w,onValidateForm:A,getValidationErrors:I,allFields:T,onSubmittingChange:C,scopedFormValues:E,scopedFieldNameMap:O,prepopulateResponse:P});case"editButton":return u.jsx(IC,{field:e,disabled:s,readOnly:i,isRequired:a,className:d,buttonResponses:v,onButtonApiResponse:x});case"addmore":return u.jsx(MC,{field:e,error:r,disabled:s,readOnly:i,isRequired:a,className:d,onAddMore:()=>_?.(e)});default:return u.jsx("div",{className:"p-3 border rounded-md bg-muted/50",children:u.jsxs("p",{className:"text-sm text-muted-foreground",children:["Unsupported field type: ",e.type]})})}},yT=({steps:e,currentStep:t,completedSteps:r,onStepClick:n,className:o})=>u.jsx("div",{className:W("mb-8",o),children:u.jsx("nav",{"aria-label":"Progress",children:u.jsx("ol",{className:"flex items-center",children:e.map((s,i)=>{const a=r.has(i),d=t===i,c=n&&(a||i===t+1||i<=t);return u.jsxs("li",{className:W("relative",i!==e.length-1&&"pr-8 sm:pr-20 flex-1"),children:[i!==e.length-1&&u.jsx("div",{className:W("absolute top-4 left-8 -right-8 sm:left-12 sm:-right-12 h-0.5",a?"bg-primary":"bg-border"),"aria-hidden":"true"}),u.jsx("button",{type:"button",onClick:()=>c&&n?.(i),disabled:!c,className:W("relative flex h-8 w-8 items-center justify-center rounded-full text-sm font-medium","transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2",a&&"bg-primary text-primary-foreground",d&&!a&&"border-2 border-primary text-primary",!a&&!d&&"border-2 border-border text-muted-foreground",c&&"cursor-pointer hover:bg-primary/10",!c&&"cursor-default"),"aria-current":d?"step":void 0,children:a?u.jsx(ps,{className:"h-4 w-4"}):u.jsx("span",{children:i+1})}),u.jsxs("div",{className:"mt-2",children:[u.jsx("span",{className:W("text-sm font-medium",d&&"text-primary",!d&&!a&&"text-muted-foreground"),children:s.name}),s.description&&u.jsx("p",{className:"text-xs text-muted-foreground hidden sm:block",children:s.description})]})]},s.id)})})})});function Ko(e){if(!e)return e;const t={...e};return e._id&&!e.id&&(t.id=e._id),delete t._id,t.formDefinitionId&&typeof t.formDefinitionId=="object"&&(t.formDefinitionId=t.formDefinitionId._id||t.formDefinitionId.id||t.formDefinitionId),t}function sh(e){return Array.isArray(e)?e.map(Ko):[]}function bT(e){if(!e.moduleId)throw new Error(`Form response missing required field: moduleId. Form ID: ${e._id||e.id}. Please ensure the backend returns moduleId when fetching forms.`);if(!e._id&&!e.id)throw new Error("Form response missing required field: id. Please ensure the backend returns _id or id when fetching forms.");let t;typeof e.moduleId=="object"&&e.moduleId._id?t=Ko(e.moduleId):t=e.moduleId;const r=e.isDefault??!1;if(!r&&!e.tenantId)throw new Error(`Form response missing required field: tenantId. Form ID: ${e._id||e.id}. Please ensure the backend returns tenantId when fetching non-default forms.`);return{id:e._id||e.id,name:e.name,description:e.description||"",version:e.version??1,status:e.status||"draft",category:e.category||"",createdAt:e.createdAt||new Date().toISOString(),updatedAt:e.updatedAt||e.createdAt||new Date().toISOString(),createdBy:e.createdBy||"",isActive:e.isActive??!0,isDefault:r,moduleId:t,tenantId:e.tenantId||void 0,featureId:e.featureId,config:e.config??void 0}}class vT{basePath="/api/form-builder/forms";async getForRendering(t,r){if(!Fn())throw new Error("Client ID is required");const o=r!==void 0?`${this.basePath}/${t}/render?version=${r}`:`${this.basePath}/${t}/render`,s=await Pn.get(o),i=s.data?.data||s.data,a=i?.BFF_submit_api||i?.bff_submit_api||s.data?.BFF_submit_api||s.data?.bff_submit_api,d=i.form||i;if(!d.moduleId&&!i.form?.moduleId)throw new Error(`Form response missing required field: moduleId. Form ID: ${t}. Please ensure the backend returns moduleId in the form response.`);if(!(d.isDefault??i.form?.isDefault??!1)&&!d.tenantId&&!i.form?.tenantId)throw new Error(`Form response missing required field: tenantId. Form ID: ${t}. Please ensure the backend returns tenantId for non-default forms.`);i.form?.moduleId&&!d.moduleId&&(d.moduleId=i.form.moduleId),i.form?.tenantId&&!d.tenantId&&(d.tenantId=i.form.tenantId),i.form?.isDefault!==void 0&&d.isDefault===void 0&&(d.isDefault=i.form.isDefault);const l=bT(d);i.form?.moduleId&&(typeof i.form.moduleId=="object"&&i.form.moduleId._id?l.moduleId=Ko(i.form.moduleId):typeof i.form.moduleId=="string"&&(l.moduleId=i.form.moduleId));const f=sh(i.fields||[]),p=i.layout?Ko(i.layout):null,m=sh(i.rules||[]),b=i.module?Ko(i.module):void 0,h=i.clientMapping||i.clientOverrides;return{form:l,fields:f,layout:p,rules:m,module:b,clientMapping:h,clientOverrides:h,BFF_submit_api:a||void 0}}}const ih=new vT;function ah({className:e,size:t="md",text:r="Loading...",fullScreen:n=!1}){const o={sm:"h-6 w-6",md:"h-12 w-12",lg:"h-16 w-16"},s=u.jsxs("div",{className:"text-center",children:[u.jsx("div",{className:W("animate-spin rounded-full border-b-2 border-blue-600 mx-auto mb-4",o[t],e)}),r&&u.jsx("p",{className:"text-gray-600",children:r})]});return n?u.jsx("div",{className:"min-h-screen bg-gradient-to-br from-blue-50 via-white to-indigo-50 flex items-center justify-center",children:s}):s}const wT={submitAction:"database",autoSave:!0,autoSaveInterval:30,showProgressBar:!0,allowDraft:!0,validateOnChange:!1,validateOnBlur:!0,showFieldErrors:"inline",layout:"default",submitButtonText:"Submit",resetButtonText:"Reset",showReset:!1,successMessage:"Form submitted successfully!",errorMessage:"An error occurred. Please try again."},ST=300;function xT(){return{...wT}}function AT(e){if(e.apidata&&typeof e.apidata=="object")return e.apidata;if(e.metadata)try{const t=typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata;if(t.apiEndpoint||t.apiKey||t.valueSource==="api")return{apiKey:t.apiKey,valueSource:t.valueSource,apiEndpoint:t.apiEndpoint,apiAutoDetect:t.apiAutoDetect,apiLabelField:t.apiLabelField,apiValueField:t.apiValueField,apiMethod:t.apiMethod,apiRealtime:t.apiRealtime,apiQueryParams:t.apiQueryParams,apiClientFilter:t.apiClientFilter}}catch{}return null}function CT(e){if(!e||typeof e!="object")return;const t=e,r=t.user_type??t.visibleToUserType??"",n=t.user_role??t.visibleToUserRole??"",o=Array.isArray(t.users)?t.users:Array.isArray(t.visibleToUserIds)?t.visibleToUserIds:[];if(!(r!=null&&r!==""||n!=null&&n!==""||o.length>0))return;const i={};return r!=null&&r!==""&&(i.visibleToUserType=r),n!=null&&n!==""&&(i.visibleToUserRole=n),o.length>0&&(i.visibleToUserIds=o),i}function ET(e){const t=xT();if(!e||typeof e!="object")return t;const r=e;return{...t,submitAction:r.submitAction||t.submitAction,apiEndpoint:r.apiEndpoint,dbTable:r.dbTable,emailTo:r.emailTo,workflowTrigger:r.workflowTrigger,workflowSubmissionConfig:r.workflowSubmissionConfig,prepopulateApi:r.prepopulateApi,prepopulateResponseRules:r.prepopulateResponseRules??void 0,autoSave:r.autoSave,autoSaveInterval:r.autoSaveInterval,showProgressBar:r.showProgressBar,allowDraft:r.allowDraft,validateOnChange:r.validateOnChange,validateOnBlur:r.validateOnBlur,showFieldErrors:r.showFieldErrors,layout:r.layout,submitButtonText:r.submitButtonText,resetButtonText:r.resetButtonText,showReset:r.showReset,successMessage:r.successMessage,successRedirect:r.successRedirect,errorMessage:r.errorMessage}}function vi(e,t,r,n){const o=t.map(c=>{let l=[],f={};try{c.options&&(l=JSON.parse(c.options)),c.metadata&&(f=JSON.parse(c.metadata))}catch{}const p=AT(c);p&&Object.assign(f,p),l.length>0&&(f.options=l);const m=[];if(c.validationRequired&&m.push({type:"required",message:"This field is required"}),c.validationMinLength!==null&&c.validationMinLength!==void 0&&m.push({type:"minLength",value:c.validationMinLength,message:`Minimum length is ${c.validationMinLength}`}),c.validationMaxLength!==null&&c.validationMaxLength!==void 0&&m.push({type:"maxLength",value:c.validationMaxLength,message:`Maximum length is ${c.validationMaxLength}`}),c.validationPattern&&m.push({type:"pattern",value:c.validationPattern,message:"Invalid format"}),c.validationRules&&typeof c.validationRules=="object"){const L=c.validationRules;if(L.required===!0&&!m.some(z=>z.type==="required")&&m.push({type:"required",message:"This field is required"}),L.allowLetters!==void 0&&m.push({type:"allowLetters",value:L.allowLetters}),L.allowNumbers!==void 0&&m.push({type:"allowNumbers",value:L.allowNumbers}),L.allowSpecialChars!==void 0&&m.push({type:"allowSpecialChars",value:L.allowSpecialChars}),L.minLetters!==void 0&&typeof L.minLetters=="number"&&m.push({type:"minLetters",value:L.minLetters}),L.maxLetters!==void 0&&typeof L.maxLetters=="number"&&m.push({type:"maxLetters",value:L.maxLetters}),L.minNumbers!==void 0&&typeof L.minNumbers=="number"&&m.push({type:"minNumbers",value:L.minNumbers}),L.maxNumbers!==void 0&&typeof L.maxNumbers=="number"&&m.push({type:"maxNumbers",value:L.maxNumbers}),L.minSpecialChars!==void 0&&typeof L.minSpecialChars=="number"&&m.push({type:"minSpecialChars",value:L.minSpecialChars}),L.maxSpecialChars!==void 0&&typeof L.maxSpecialChars=="number"&&m.push({type:"maxSpecialChars",value:L.maxSpecialChars}),L.fileSize!==void 0&&typeof L.fileSize=="number"){const z=L.fileSize/1048576;m.push({type:"fileSize",value:L.fileSize,message:`File size must be less than ${z.toFixed(2)} MB`})}if(L.fileType!==void 0){const z=Array.isArray(L.fileType)?L.fileType:typeof L.fileType=="string"?L.fileType.split(",").map(V=>V.trim()).filter(Boolean):[];z.length>0&&m.push({type:"fileType",value:z,message:"File type is not allowed"})}}const b=[],h=new Set;n.filter(L=>{const z=typeof L.targetFieldId=="object"?L.targetFieldId.id||L.targetFieldId._id:L.targetFieldId;return!!(z===c.id||z===c._id||z&&c.fieldKey&&z===c.fieldKey)}).forEach(L=>{try{const z=JSON.parse(L.conditionExpression);!z.id&&L.id&&(z.id=L.id);const V=typeof L.targetFieldId=="object"?L.targetFieldId?.id||L.targetFieldId?._id:L.targetFieldId;z.action&&(!z.then||!Array.isArray(z.then)||z.then.length===0)&&(z.then=[{action:z.action,...V&&{target:V}}]),(!z.then||!Array.isArray(z.then)||z.then.length===0)&&L.action&&(z.then=[{action:L.action,...V&&{target:V}}]),z.then&&Array.isArray(z.then)&&V&&(z.then=z.then.map(re=>!re.target&&V?{...re,target:V}:re));const le=L.conditionExpression||JSON.stringify(z);if(h.has(le))return;h.add(le),b.push(z)}catch{}});const w=c.disabled===!0||f?.disabled===!0||!1;let v=c.readOnly===!0||f?.readOnly===!0||!1;const x=c.hidden===!0||f?.hidden===!0||!1;(f?.valueSource==="calculated"||f?.formula)&&(v=!0);const{disabled:A,readOnly:I,hidden:T,...C}=f,_={};C.hideLabel!==void 0&&(_.hideLabel=C.hideLabel),C.labelPosition!==void 0&&(_.labelPlacement=C.labelPosition),C.size!==void 0&&(_.size=C.size),C.customClass!==void 0&&(_.className=C.customClass);const{labelPosition:E,size:O,customClass:N,visibility:j,...R}=C,M=Object.keys(R).length>0?R:void 0,B=Object.keys(_).length>0?_:void 0,P=c.visibility??f?.visibility??j;let H=CT(P);if(P&&!H){const L=P;(L.visibleToUserType!=null||L.visibleToUserRole!=null||Array.isArray(L.visibleToUserTypes)&&L.visibleToUserTypes.length>0||Array.isArray(L.visibleToUserRoles)&&L.visibleToUserRoles.length>0||Array.isArray(L.visibleToUserIds)&&L.visibleToUserIds.length>0||Array.isArray(L.hiddenFromUserIds)&&L.hiddenFromUserIds.length>0)&&(H={visibleToUserType:L.visibleToUserType??(Array.isArray(L.visibleToUserTypes)?L.visibleToUserTypes[0]:void 0),visibleToUserRole:L.visibleToUserRole??(Array.isArray(L.visibleToUserRoles)?L.visibleToUserRoles[0]:void 0),visibleToUserIds:L.visibleToUserIds,hiddenFromUserIds:L.hiddenFromUserIds})}const D=f?.columnName,q=!!c.parentFieldId&&typeof D=="string"?D:c.fieldKey;return{id:c.id,type:c.fieldType,name:q,label:c.label,description:c.helpText||void 0,placeholder:c.placeholder||void 0,defaultValue:c.defaultValue||void 0,position:{order:typeof c.positionOrder=="number"?c.positionOrder:c.positionRow??0,column:typeof c.positionColumn=="number"?c.positionColumn:1,columnSpan:typeof c.positionWidth=="number"?c.positionWidth:1},parentId:void 0,appearance:B,validation:m.length>0?m:void 0,conditions:b.length>0?b:void 0,properties:M,visibility:H&&(H.visibleToUserType!=null||H.visibleToUserRole!=null||Array.isArray(H.visibleToUserIds)&&H.visibleToUserIds.length>0||Array.isArray(H.hiddenFromUserIds)&&H.hiddenFromUserIds.length>0)?H:void 0,disabled:w,readOnly:v,hidden:x}});o.forEach((c,l)=>{if(c.visibility){const f=t[l];console.log("[backendToFormSchema] field with visibility",{fieldKey:f?.fieldKey??c.name,name:c.name,type:c.type,parentFieldId:f?.parentFieldId,visibility:c.visibility})}});const s=t;for(let c=0;c<o.length;c++){const l=s[c]?.parentFieldId;if(l){const f=o.find(m=>m.id===l||m.type==="table"&&m.name===l||m.type==="table"&&s[c].fieldKey?.startsWith?.(m.name+"_column_")),p=o[c];if(f&&f.type==="table"&&p){const m=f.properties||{};Array.isArray(m.columns)||(m.columns=[]),m.columns.push(p),f.properties=m}}}const i=o.filter((c,l)=>!s[l]?.parentFieldId);for(const c of i)if(c.type==="table"&&c.properties&&Array.isArray(c.properties.columns)){const l=c.properties.columns;for(const f of l){const p=f.properties?.columnName;typeof p=="string"&&(f.name=p)}l.sort((f,p)=>(f.position?.order??0)-(p.position?.order??0)||(f.position?.column??0)-(p.position?.column??0))}let a;const d=e.config;if(console.log("[Prepopulate] backendToFormSchema config",{formId:e.id,hasRawConfig:d!=null,rawConfigType:typeof d,rawConfigPreview:d!=null?typeof d=="string"?d.slice(0,300):JSON.stringify(d).slice(0,300):null}),d!=null)try{const c=typeof d=="string"?JSON.parse(d):d;c&&typeof c=="object"?a=ET(c):a={submitAction:"database",layout:"default",autoSave:!0,validateOnChange:!0,showFieldErrors:"inline"}}catch{a={submitAction:"database",layout:"default",autoSave:!0,validateOnChange:!0,showFieldErrors:"inline"}}else a={submitAction:"database",layout:"default",autoSave:!0,validateOnChange:!0,showFieldErrors:"inline"};return{id:e.id,name:e.name,description:e.description,version:e.version,status:e.status,config:a,fields:i,createdAt:e.createdAt,updatedAt:e.updatedAt,createdBy:e.createdBy,category:e.category,moduleId:typeof e.moduleId=="string"?e.moduleId:e.moduleId?.id,tenantId:e.tenantId,featureId:e.featureId,isDefault:e.isDefault}}function Xt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ho(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>ho(r));if(!Xt(e))return e;const t={};for(const[r,n]of Object.entries(e))t[r]=ho(n);return t}function lh(e,...t){const r={...e};for(const n of t)if(!(!n||!Xt(n)))for(const[o,s]of Object.entries(n)){const i=r[o];Xt(s)&&Xt(i)?r[o]=lh(i,s):r[o]=s}return r}function go(e){return Xt(e)?e:{}}function Vl(e){if(e==null)return{};if(typeof e=="string"){const t=e.trim();if(!t)return{};try{const r=JSON.parse(t);return Xt(r)?ho(r):{}}catch{return{}}}return Xt(e)?ho(e):{}}function ch(e){const t=e.apidata;return Xt(t)&&Object.keys(t).length>0}function TT(e){if(typeof e.metadata=="string"&&e.metadata.trim()!==""||typeof e.metadata=="object"&&e.metadata!==null&&!Array.isArray(e.metadata)&&Object.keys(e.metadata).length>0||ch(e))return!0;const t=e.fieldKey,r=e.fieldType,n=e.name,o=e.type;return!!(t&&(!n||String(n).trim()==="")||r&&(!o||String(o).trim()==="")||t&&n&&t!==n||r&&o&&r!==o||!n&&e.key&&typeof e.key=="string")}const dh=["hideLabel","contentAlign","contentVerticalAlign","labelPlacement","widthPercent","widthMode","className","verticalAlign","horizontalAlign","cellAlign","cellJustify","size","variant","minWidth","minHeight"];function _T(e,t){const r=e.appearance,n=Xt(r)&&Object.keys(r).length>0?ho(r):{},o=go(t.appearance),s={...n};for(const[i,a]of Object.entries(o))i!=="heightPercent"&&s[i]===void 0&&(s[i]=ho(a));for(const i of dh)s[i]===void 0&&t[i]!==void 0&&(s[i]=t[i]);return delete s.heightPercent,Object.keys(s).length>0?s:void 0}function wi(e,t){const r=go(e.position),n=typeof r.order=="number"&&!Number.isNaN(r.order)?r.order:typeof r.row=="number"&&!Number.isNaN(r.row)?r.row:typeof e.positionOrder=="number"?e.positionOrder:typeof e.order=="number"?e.order:typeof e.positionRow=="number"?e.positionRow:t,o=typeof r.column=="number"&&!Number.isNaN(r.column)?r.column:typeof e.positionColumn=="number"?e.positionColumn:1,s=typeof r.columnSpan=="number"&&!Number.isNaN(r.columnSpan)?r.columnSpan:typeof r.width=="number"&&!Number.isNaN(r.width)?r.width:typeof e.positionWidth=="number"?e.positionWidth:1,i=typeof r.rowSpan=="number"&&!Number.isNaN(r.rowSpan)?r.rowSpan:typeof e.positionRowSpan=="number"?e.positionRowSpan:1,a={order:n,column:o,columnSpan:s,rowSpan:i},d=r.cellGroupId,c=r.cellSlot,l=r.sharedCellLayout;return typeof d=="string"&&(a.cellGroupId=d),typeof c=="number"&&(a.cellSlot=c),(l==="row"||l==="stack")&&(a.sharedCellLayout=l),a}function NT(e,t){return wi(e,t)}function kT(e,t){const r=e,n=Vl(r.metadata),o=go(r.apidata),s=go(r.properties),i=lh({},n,o,s),a=(r.name!=null&&String(r.name).trim()!==""?r.name:void 0)??(typeof r.fieldKey=="string"?r.fieldKey:void 0)??(typeof r.key=="string"?r.key:void 0),d=(r.type!=null&&String(r.type).trim()!==""?r.type:void 0)??(typeof r.fieldType=="string"?r.fieldType:void 0),c=_T(r,n),l=NT(r,t),f={...r};return f.properties=i,a!==void 0&&(f.name=a),d!==void 0&&(f.type=d),c!==void 0?f.appearance=c:(!Xt(r.appearance)||Object.keys(r.appearance).length===0)&&delete f.appearance,f.position=l,Xt(f.appearance)&&delete f.appearance.heightPercent,f}function FT(e,t){if(!e||typeof e!="object")return!0;const r=e,n=Vl(r.metadata),o=Object.keys(n).length===0&&!(typeof r.metadata=="string"&&r.metadata.trim()!==""),s=!ch(r);if(TT(r)||!o||!s)return!1;const i=r.position;if(Xt(i)&&(typeof i.order=="number"&&!Number.isNaN(i.order)||typeof i.row=="number"&&!Number.isNaN(i.row)||typeof i.column=="number"&&!Number.isNaN(i.column))){if(Xt(i)&&(typeof i.row=="number"||typeof i.width=="number"))return!1}else if(typeof r.positionRow=="number"||typeof r.positionColumn=="number"||typeof r.positionWidth=="number"||typeof r.positionRowSpan=="number"||typeof r.positionOrder=="number")return!1;return!(Xt(n.appearance)||dh.some(c=>n[c]!==void 0&&(r.appearance==null||Xt(r.appearance)&&r.appearance[c]===void 0)))}function OT(e){const t=new Map;for(const r of e){if(!r||typeof r!="object")continue;const n=r,o=new Set;for(const s of[n.fieldKey,n.key,n.name,n.id,n._id])s!=null&&String(s).trim()!==""&&o.add(String(s).trim());for(const s of o)t.has(s)||t.set(s,n)}return t}function Si(e){const t=go(e.position);return typeof t.row=="number"&&!Number.isNaN(t.row)||typeof t.width=="number"&&!Number.isNaN(t.width)||typeof t.column=="number"&&!Number.isNaN(t.column)&&t.column>1||typeof e.positionColumn=="number"&&e.positionColumn>1||typeof e.positionRow=="number"}function Hl(e){const t=[],r=new Set,n=i=>{for(const a of i)a!=null&&typeof a=="object"&&!r.has(a)&&(r.add(a),t.push(a))},o=e.form;Xt(o)&&Array.isArray(o.fields)&&n(o.fields);const s=e.workflowFormFields;return Array.isArray(s)&&n(s),Array.isArray(e.fields)&&n(e.fields.filter(i=>{if(!i||typeof i!="object")return!1;const a=i;return(typeof a.fieldKey=="string"||typeof a.fieldType=="string")&&Si(a)})),t}function uh(e,t){const r=[...Array.isArray(t)?t:[],...Hl(e)];if(r.length===0)return e;const n=OT(r),o=e.fields;if(!Array.isArray(o)||o.length===0)return e;let s=!1;const i=o.map((a,d)=>{const c=a;if(Si(c))return a;const l=[c.key,c.name,c.id,c.fieldKey,c._id].filter(h=>h!=null&&String(h).trim()!=="").map(h=>String(h).trim());let f;for(const h of l)if(f=n.get(h),f)break;if(!f)return a;const p=wi(f,d),m=go(c.position);return m.order===p.order&&m.column===p.column&&m.columnSpan===p.columnSpan&&m.rowSpan===p.rowSpan?a:(s=!0,{...c,position:p})});return s?{...e,fields:i}:e}function fh(e){const t=e.fields;if(!Array.isArray(t)||t.length===0||!t.some(a=>a&&typeof a=="object"&&!Si(a)))return!1;if(e.BFF_submit_api!=null||e.bff_submit_api!=null||Xt(e.form)&&Array.isArray(e.form.fields)||Array.isArray(e.workflowFormFields)&&e.workflowFormFields.length>0)return!0;const n=e.config,o=n!=null&&typeof n=="object"?n.layout:void 0,s=o!=null&&typeof o=="object"&&!Array.isArray(o)?o:e.layout!=null&&typeof e.layout=="object"&&!Array.isArray(e.layout)?e.layout:null;return(typeof s?.columns=="number"?s.columns:1)>1}function xi(e,t){if(e==null||typeof e!="object")return e;const r=uh(e,t?.workflowFormFields),n=r.fields;if(!Array.isArray(n))return r;let o=r!==e;const s=n.map((i,a)=>{if(FT(i))return i;const d=kT(i,a);return d!==i&&(o=!0),d});return o?{...r,fields:s}:r}function PT(e,t){return xi(e,t)}let ph=null;function IT(e){ph=e}function mh(){return(ph?.()??"").replace(/\/+$/,"")}function Wl(e){const t=typeof e=="string"?e.trim():"";if(!t||/^https?:\/\//i.test(t))return t;const r=mh();if(r)return t.startsWith("/")?`${r}${t}`:`${r}/${t}`;if(typeof window<"u"&&window.location?.origin){const n=window.location.origin.replace(/\/+$/,"");return t.startsWith("/")?`${n}${t}`:`${n}/${t}`}return t}const hh=new Map;function gh(e){return hh.get(e)}function ql(e,t){!e||!Array.isArray(t)||t.length===0||hh.set(e,t)}function MT(e,t){const r=String(e??"").trim();!r||!Array.isArray(t)||t.length===0||ql(`form:${r}`,t)}function yh(e){const t=String(e??"").trim();if(t)return gh(`form:${t}`)}function Yo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xo(e){if(!Yo(e))return null;const t=e.BFF_submit_api??e.bff_submit_api;return!Yo(t)||typeof t.url!="string"||t.url.trim()===""?null:t}function LT(e){return Wl(e).match(/\/workflows\/modules\/([^/?#]+)\/submit\/?(?:[?#]|$)/i)?.[1]??null}function bh(e){const t=Wl(e);if(!t)return null;try{const r=new URL(t);return/\/submit\/?$/i.test(r.pathname)?(r.pathname=r.pathname.replace(/\/submit\/?$/i,"/state"),r.search="",r.toString()):null}catch{return null}}function vh(e,t){const r=e[t];if(r!=null&&String(r).trim()!=="")return String(r).trim();const n=t.toLowerCase();for(const[o,s]of Object.entries(e))if(o.toLowerCase()===n&&s!=null&&String(s).trim()!=="")return String(s).trim()}function DT(e){if(!Yo(e))return null;const t=e.form??(Yo(e.data)?e.data.form:void 0);return!Yo(t)||!Array.isArray(t.fields)||t.fields.length===0?null:t.fields}function BT(e,t,r){const n=t.headers??{},o=t.payload??{},s=r?.submissionContext??{},i=typeof s.tenant_id=="string"&&s.tenant_id.trim()||typeof s.tenantId=="string"&&s.tenantId.trim()||void 0,a=vh(n,"x-client-id"),d=typeof o.current_step_id=="string"&&o.current_step_id.trim()||void 0;if(!i||!a)return null;try{const c=new URL(e),l=new URLSearchParams(c.search);r?.featureId&&l.set("feature_id",r.featureId),l.set("tenant_id",i),l.set("client_id",a),d&&l.set("step_id",d);const f=s.context_user_id??s.user_id;return typeof f=="string"&&f.trim()&&l.set("user_id",f.trim()),c.search=l.toString(),c.toString()}catch{return null}}async function wh(e,t){const r=String(t?.formId??"").trim();if(r){const l=yh(r);if(l&&l.length>0)return l}const n=bh(e.url);if(!n)return null;const o=BT(n,e,t);if(!o)return null;const s=gh(o);if(s&&s.length>0)return s;const i={...e.headers??{}};vh(i,"accept")||(i.Accept="application/json");const a=await fetch(o,{method:"GET",headers:i,credentials:"include"});if(!a.ok)return null;let d;try{d=await a.json()}catch{return null}const c=DT(d);return!c||c.length===0?null:(ql(o,c),r&&ql(`form:${r}`,c),c)}function $T(e,t){const r=t??e;if(!r||typeof r!="object")return null;const n=e;if(!n||typeof n!="object"||n===r)return r;const o=Xo(n);return!o||Xo(r)?r:{...r,BFF_submit_api:o}}function Ai(e){const t=typeof e.position?.order=="number"?e.position.order:-1,r=typeof e.position?.column=="number"?e.position.column:1,n=e.position?.cellGroupId??"_";return`${t}:${r}:${n}`}function Ci(e){return[...e].sort((t,r)=>{const n=t.position?.cellSlot,o=r.position?.cellSlot;return typeof n=="number"&&typeof o=="number"&&n!==o?n-o:String(t.id).localeCompare(String(r.id))})}function Ei(e,t){if(e.length===0)return{rowSpan:1,columnSpan:1};let r=1,n=1;for(const o of e)r=Math.max(r,vo(o)),n=Math.max(n,Nc(o,t));return{rowSpan:r,columnSpan:n}}function Sh(e){const t=Ci(e);for(const r of t){const n=r.position?.sharedCellLayout;if(n==="row"||n==="stack")return n}return t.length===2?"row":"stack"}function jT(e,t){const r=new Map;for(const n of e){if(!t(n)||typeof n.position?.order!="number")continue;const o=Ai(n),s=r.get(o)??[];s.push(n),r.set(o,s)}return Array.from(r.values()).map(n=>Ci(n).slice(0,2))}function xh(e,t,r,n){const o=r.filter(a=>n(a)&&typeof a.position?.order=="number"&&a.position.order===e&&(a.position.column??1)===t+1);if(o.length===0)return[];const s=new Map;for(const a of o){const d=Ai(a),c=s.get(d)??[];c.push(a),s.set(d,c)}const i=[...s.values()][0]??[];return Ci(i).slice(0,2)}function UT(e,t,r,n){const o=r[0],s=o.position?.order,i=o.position?.column??1;if(typeof s!="number")return!1;const{rowSpan:a,columnSpan:d}=Ei(r,n),c=e===s&&t===i-1,l=e>=s&&e<s+a,f=t>=i-1&&t<i-1+d;return l&&f&&!c}const RT=new Set(["PENDING_PAYMENT","PAYMENT_PENDING","AWAITING_PAYMENT","PAID","PAYMENT_COMPLETED","PAYMENT_FAILED","REFUNDED","AUTHORIZED","CAPTURED","PARTIALLY_PAID"].map(e=>e.toUpperCase()));function Gl(e){return typeof e=="string"&&e.trim()!==""}function Kl(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;const t=e;if(t.payment_type!=null&&t.payment_type!==""||t.payment_mode!=null&&t.payment_mode!==""||t.transaction_id!=null&&String(t.transaction_id).trim()!==""||t.payment_status!=null&&String(t.payment_status).trim()!==""||typeof t.amount=="number"||Gl(t.amount)||typeof t.total_amount=="number"||Gl(t.total_amount)||Gl(t.currency)||t.gateway!=null&&String(t.gateway).trim()!==""||t.razorpay_order_id!=null&&String(t.razorpay_order_id).trim()!==""||t.stripe_payment_intent!=null&&String(t.stripe_payment_intent).trim()!=="")return!0;const r=t.status;return!!(typeof r=="string"&&RT.has(r.trim().toUpperCase()))}function zT(e){const t=pt(e,"data.items");if(!Array.isArray(t)||t.length===0)return;const r=t[0];if(r==null||typeof r!="object")return;const n=r;if(!(n.id===void 0||n.id===null||n.id===""))return{item:n,id:n.id}}function VT(e,t){const r=zT(e);if(!r)return;const n=pt(e,"data"),o=n!=null&&typeof n=="object"&&!Array.isArray(n)?n:void 0;if(t?.treatFirstItemIdAsPaymentId===!0||Kl(r.item)||o!=null&&Kl(o))return r.id}function HT(e){const t=e.properties,r=e.metadata;return[t?.uploadApiEndpoint,t?.apiEndpoint,r?.uploadApiEndpoint,r?.apiEndpoint].filter(o=>typeof o=="string"&&o.length>0)}function WT(e){return HT(e).some(t=>t.toLowerCase().includes("payment"))}function qT(e){const t=e.properties,r=e.metadata;return!!(t?.mergeSuccessDataIdAsPaymentId||r?.mergeSuccessDataIdAsPaymentId)}function GT(e,t){if(t?.type!=="button"||!Co(e))return;const r=pt(e,"data.id");if(r==null||String(r).trim()==="")return;const n=pt(e,"data");if(qT(t)||n!=null&&typeof n=="object"&&!Array.isArray(n)&&Kl(n)||WT(t))return r}const KT=new Set(["section","group","columns","divider","header","sectionHeading","spacer","addmore","textLabel"]);function YT(e,t){if(!e.length||!t?.length)return[];const r=new Map(t.map(o=>[o.id,o])),n=[];for(const o of e){const s=r.get(o);if(s?.fieldNames?.length)for(const i of s.fieldNames)i&&!n.includes(i)&&n.push(i)}return n}function XT(e,t){const r=e.properties,n=Array.isArray(r?.linkedFieldNames)?r.linkedFieldNames:[],o=YT(Array.isArray(r?.linkedSectionIds)?r.linkedSectionIds:[],t),s=new Set,i=[];for(const a of[...n,...o])!a||s.has(a)||(s.add(a),i.push(a));return i}function Ah(e,t){const r=e.properties,n=Array.isArray(r?.linkedSectionIds)?r.linkedSectionIds:[];if(!n.length||!t?.length)return[];const o=new Map(t.map(s=>[s.id,s]));return n.map(s=>o.get(s)).filter(s=>!!s)}function JT(e,t){return Ah(e,t).find(r=>r.heading?.enabled)}function Ch(e,t){const r=e.template??"";return(e.mode??"increment")==="fixed"?r:r.replace(/\{n\}/g,String(t+1))}function Eh(e,t,r,n){const o=XT(e,r);if(o.length===0)return[];const s=new Set(o);return t.filter(i=>{const a=n(i);return!a||i.id===e.id||KT.has(i.type)?!1:s.has(a)})}function QT(e,t,r){if(e.type!=="sectionHeading"||!t?.length)return;const n=r(e);if(n)for(const o of t){const s=o.heading;if(s?.enabled&&s.headingFieldName===n)return s}}function Yl(e){return[...e].sort((t,r)=>{const n=t.position?.order??0,o=r.position?.order??0;if(n!==o)return n-o;const s=t.position?.column??1,i=r.position?.column??1;return s-i})}function ZT(e,t,r){if(!e?.length)return[];const n=e.filter(i=>i.showBorder===!0);if(n.length===0)return[];const o=new Map;for(const i of t){const a=r(i);a&&o.set(a,i)}const s=[];for(const i of n){const a=i.fieldNames.map(c=>o.get(c)).filter(c=>!!c);if(a.length===0)continue;const d=Yl(a).map(c=>r(c)).filter(Boolean);s.push({section:i,fieldNames:d})}return s}function Jo(e,t=0){return e.heading?.enabled?Ch(e.heading,t):e.name}function Th(e,t,r){if(e.type!=="sectionHeading")return!1;const n=t.heading;return!n?.enabled||!n.headingFieldName?!1:r(e)===n.headingFieldName}function e_(e,t){const r=typeof e.position?.order=="number"?e.position.order:0,n=(e.position?.column??1)-1,o=vo(e),s=Nc(e,t);return{row:r,col:n,rowEnd:r+o-1,colEnd:n+s-1}}function Xl(e,t){let r=1/0,n=-1/0,o=1/0,s=-1/0;for(const i of e){const{row:a,col:d,rowEnd:c,colEnd:l}=e_(i,t);r=Math.min(r,a),n=Math.max(n,c),o=Math.min(o,d),s=Math.max(s,l)}return Number.isFinite(r)?{minRow:r,maxRow:n,minCol:o,maxCol:s,rowSpan:n-r+1,colSpan:s-o+1}:null}function t_(e,t,r,n){const o=e.map(l=>t.find(f=>n(f)===l)).filter(l=>!!l&&typeof l.position?.order=="number");if(o.length===0)return null;const s=Xl(o,r);if(!s)return null;const i=o.filter(l=>l.type!=="sectionHeading"),a=i.length>0?i:o,d=Math.min(...a.map(l=>l.position?.order??0)),c=Math.max(1,...a.map(l=>(l.position?.order??d)-d+vo(l)));return{minRow:s.minRow,maxRow:s.maxRow,minCol:s.minCol,maxCol:s.maxCol,blockHeight:c}}function r_(e,t){return e.maxRow+1+t*e.blockHeight}function n_(e,t,r,n){const o=new Map;for(const a of t){const d=r(a);d&&o.set(d,a)}const s=new Map,i=new Set;for(const a of e){const d=a.fieldNames.map(v=>o.get(v)).filter(v=>!!v);if(d.length===0)continue;const c=d.filter(v=>!Th(v,a.section,r)),l=Xl(d,n);if(!l)continue;const{minRow:f,minCol:p,rowSpan:m,colSpan:b}=l,h=`${f}-${p}`;if(s.has(h))continue;const g=new Set;let w=!1;for(let v=f;v<=f+m-1;v++){for(let x=p;x<=p+b-1;x++){const A=`${v}-${x}`;if(i.has(A)){w=!0;break}g.add(A)}if(w)break}if(!w){for(const v of g)i.add(v);s.set(h,{anchorRow:f,anchorCol:p,rowSpan:m,colSpan:b,run:a,legend:Jo(a.section,0),renderFields:c.length>0?c:d})}}return{anchorsByOrigin:s,coveredCells:i}}function o_(e,t,r,n,o,s,i){const a=new Set(i),d=new Map;for(const c of e){const l=_h(c.linkedFields.map(p=>s(p)).filter(Boolean),t),f=l?.section;f?.fieldNames?.length?f.fieldNames:c.templateFieldNames,c.blockIds.forEach((p,m)=>{const b=r.filter(C=>C.id.endsWith(`__${p}`));if(b.length===0||!l)return;const h=Xl(b,o);if(!h)return;const{minRow:g,minCol:w,rowSpan:v,colSpan:x}=h,A=`${g}-${w}`;for(let C=g;C<=g+v-1;C++)for(let _=w;_<=w+x-1;_++)a.add(`${C}-${_}`);const I=l,T=Jo(f,m+1);d.set(A,{anchorRow:g,anchorCol:w,rowSpan:v,colSpan:x,run:I,legend:T,renderFields:Yl(b),addMoreMeta:{addMoreFieldName:c.addMoreFieldName,blockId:p,blockIndex:m}})})}return{anchorsByOrigin:d,coveredCells:a}}function s_(e,t,r,n){const o=`${e}-${t}`;return r.has(o)?!n.get(o):!1}function i_(e,t,r){for(const n of r.values())if(e>=n.anchorRow&&e<n.anchorRow+n.rowSpan&&t>=n.anchorCol&&t<n.anchorCol+n.colSpan)return n}function a_(e,t,r,n){return!(!n||r.run.section.collapsible!==!0||e===r.anchorRow&&t===r.anchorCol)}function l_(e,t,r){const n=new Set;for(const o of e.values())if(t(o))for(let s=o.anchorRow+1;s<o.anchorRow+o.rowSpan;s++)r(s,o)||n.add(s);return n}function c_(e,t,r){const n=o=>r.has(o)?"minmax(0, auto)":`minmax(${t}, auto)`;return Array.from({length:e},(o,s)=>n(s)).join(" ")}function d_(e,t){return new Map([...e,...t])}function u_(e,t,r){if(t.length===0)return e.map(i=>({kind:"field",field:i}));const n=new Map;for(const i of t)for(const a of i.fieldNames)n.set(a,i);const o=[];let s=0;for(;s<e.length;){const i=e[s],a=r(i),d=a?n.get(a):void 0;if(!d){o.push({kind:"field",field:i}),s+=1;continue}const c=[],l=new Set(d.fieldNames);for(;s<e.length;){const p=r(e[s]);if(!p||!l.has(p))break;const m=e[s];Th(m,d.section,r)||c.push(m),s+=1}if(c.length===0)continue;const f=o[o.length-1];f?.kind==="border"&&f.run.section.id===d.section.id?f.fields.push(...c):o.push({kind:"border",run:d,fields:c})}return o}function _h(e,t){if(!t?.length)return;const r=new Set(e);for(const n of t){if(n.showBorder!==!0)continue;const o=n.fieldNames.filter(s=>r.has(s));if(o.length>0)return{section:n,fieldNames:o}}}const f_=2*6e4,Nh=50;class p_{map=new Map;ttlMs;constructor(t){this.ttlMs=t}get(t){const r=this.map.get(t);if(!r)return null;const o=Date.now()-r.storedAtMs>this.ttlMs;return{value:r.value,isStale:o}}set(t,r){this.map.set(t,{value:r,storedAtMs:Date.now()}),this.enforceMax()}delete(t){this.map.delete(t)}clear(){this.map.clear()}enforceMax(){if(this.map.size<=Nh)return;const t=Array.from(this.map.entries());t.sort((n,o)=>n[1].storedAtMs-o[1].storedAtMs),t.slice(0,Math.max(0,this.map.size-Nh)).forEach(([n])=>this.map.delete(n))}}function m_(e){return(e??"").trim()||"default"}function kh(e){const t=m_(e.scope),r=String(e.formId??"").trim(),n=e.version===void 0||e.version===null?"latest":String(e.version).trim();return`form-render:${t}:${r}:${n}`}const Fh=new p_(f_);function Oh(e){const t=kh(e),r=Fh.get(t);return r?{value:r.value,isStale:r.isStale}:null}function Ph(e,t){const r=kh(e);Fh.set(r,t)}function Ih(e){const t={};for(const[n,o]of Object.entries(e)){if(o==null){t[n]=o;continue}if(Array.isArray(o)){t[n]=o;continue}if(typeof o=="object"&&!(o instanceof Date)){const s=o;typeof s.name=="string"&&typeof s.code=="string"?t[n]=`${s.code} ${s.name}`.trim():typeof s.name=="string"?t[n]=s.name:typeof s.code=="string"?t[n]=s.code:typeof s.short_code=="string"?t[n]=s.short_code:t[n]=s.name??s.code??"";continue}t[n]=o}const r=t.time_slot??e.time_slot;return typeof r=="string"&&r.includes(" - ")&&(t.start=r.split(" - ")[0].trim()),t}const Mh=({schema:e,formId:t,initialValues:r,onSubmit:n,onChange:o,onValidationError:s,onClose:i,mode:a="fill",className:d,children:c,gridLayout:l,unstyled:f=!1,workflowFormFields:p,submissionContext:m,onWorkflowSubmitResult:b,initialExtraSubmitPayload:h,onExtraSubmitPayloadChange:g,workflowStepId:w,viewerContext:v,getViewerContext:x,hideTableRowControls:A=!1,themeVars:I,dark:T=!1,omitRootWrapper:C=!1})=>{const _=On(k=>k.viewerContext),E=S.useMemo(()=>{if(v!==void 0)return v;const k=x?.();return k!==void 0?k:_},[v,x,_]),[O,N]=S.useState(e||null),[j,R]=S.useState(!!t&&!e),[M,B]=S.useState(null),P=e?.BFF_submit_api??M,[H,D]=S.useState(!1),[K,q]=S.useState({}),[L,z]=S.useState({}),[V,le]=S.useState({}),[re,ne]=S.useState({}),[Z,Y]=S.useState({}),[oe,ie]=S.useState(null),[G,ve]=S.useState(null),[be,He]=S.useState(!1),he=zi.useParams(),Ee=qt(k=>k.setValues),ae=qt(k=>k.setSubmitting),ye=qt(k=>k.formDisabled),je=S.useRef(!1),st=S.useRef(void 0),we=S.useMemo(()=>{if(!e)return null;const k=e;if(k.form&&Array.isArray(k.form.fields))try{return vi(k.form,k.form.fields,k.form.layout||null,k.form.rules||[])}catch{return e}if(Array.isArray(k.fields)&&k.fields.some(X=>typeof X.metadata=="string"&&X.metadata.startsWith("{")||X.fieldType&&!X.type))try{const X={id:k.id||k._id||"temp",name:k.name||"Form",version:k.version??1,status:k.status||"draft",createdAt:k.createdAt||new Date().toISOString(),updatedAt:k.updatedAt||new Date().toISOString(),createdBy:k.createdBy||"system",category:k.category||"",moduleId:k.moduleId,tenantId:k.tenantId,featureId:k.featureId,isDefault:k.isDefault||!1};return vi(X,k.fields,k.layout||null,k.rules||[])}catch{return e}return e},[e]);S.useEffect(()=>{if(e){const k=e;k.BFF_submit_api&&B(k.BFF_submit_api)}},[e]),S.useEffect(()=>{const k=$T(e,we);if(!k){ve(null),He(!1);return}if(!fh(k)){ve(null),He(!1);return}const $=Hl(k);if($.length>0){ve($),He(!1);return}if(p!=null&&p.length>0){ve(p),He(!1);return}const X=String(k.id??k._id??"").trim(),J=X?yh(X):void 0;if(J&&J.length>0){ve(J),He(!1);return}const te=Xo(k)??Xo(e)??P,me=typeof k.featureId=="string"?k.featureId:typeof k.feature_id=="string"?k.feature_id:void 0;let _e=!1;return He(!0),(async()=>{try{if(te){const Pe=await wh(te,{submissionContext:m,featureId:me,formId:X||void 0});if(!_e&&Array.isArray(Pe)&&Pe.length>0){ve(Pe);return}}if(X){const Pe=typeof k.version=="number"?k.version:void 0,nt=(await ih.getForRendering(X,Pe)).fields;if(!_e&&Array.isArray(nt)&&nt.length>0){ve(nt);return}}_e||ve(null)}catch{_e||ve(null)}finally{_e||He(!1)}})(),()=>{_e=!0,He(!1)}},[we,e,p,m,P]);const ct=S.useMemo(()=>{const k=we||O,$=k?xi(k,{workflowFormFields:p??(G!=null&&G.length>0?G:void 0)}):null;if(!$)return null;const X=$.layout,J=$.rules,te=$.clientMapping,me=(Array.isArray($.fields)?$.fields:[]).map(ze=>{let fe={...ze};if(ze.validationRules&&typeof ze.validationRules=="object"&&!ze.validation){const ke=ze.validationRules,Te=[];ke.required===!0&&Te.push({type:"required",message:"This field is required"}),ke.minLength!==void 0&&typeof ke.minLength=="number"&&Te.push({type:"minLength",value:ke.minLength,message:`Minimum length is ${ke.minLength}`}),ke.maxLength!==void 0&&typeof ke.maxLength=="number"&&Te.push({type:"maxLength",value:ke.maxLength,message:`Maximum length is ${ke.maxLength}`}),ke.pattern&&typeof ke.pattern=="string"&&Te.push({type:"pattern",value:ke.pattern,message:"Invalid format"}),ke.allowLetters!==void 0&&Te.push({type:"allowLetters",value:ke.allowLetters}),ke.allowNumbers!==void 0&&Te.push({type:"allowNumbers",value:ke.allowNumbers}),ke.allowSpecialChars!==void 0&&Te.push({type:"allowSpecialChars",value:ke.allowSpecialChars}),Te.length>0&&(fe={...fe,validation:Te})}const Ne=ze.required===!0||ze.isRequired===!0,Xe=Array.isArray(fe.validation)&&fe.validation.some(ke=>ke.type==="required");if(Ne&&!Xe){const ke={type:"required",message:"This field is required"},Te=Array.isArray(fe.validation)?fe.validation:[];fe={...fe,validation:[...Te,ke]}}if(ze.apidata&&typeof ze.apidata=="object"){const ke=ze.apidata,Te=fe.properties||{},$e=(fe.type||ze.fieldType)==="status";if(!Te.apiEndpoint&&ke.apiEndpoint){const ht={...Te,apiEndpoint:ke.apiEndpoint,apiMethod:ke.apiMethod,apiKey:ke.apiKey,apiRealtime:ke.apiRealtime,apiAutoDetect:ke.apiAutoDetect,apiLabelField:ke.apiLabelField,apiValueField:ke.apiValueField,apiQueryParams:ke.apiQueryParams,apiClientFilter:ke.apiClientFilter,valueSource:ke.valueSource||(ke.apiEndpoint?"api":void 0),optionsSource:ke.optionsSource||(ke.apiEndpoint?"api":void 0)};$e&&(ht.source=Te.source??"api",Te.statuses!==void 0&&(ht.statuses=Te.statuses),Te.dataPath!==void 0&&(ht.dataPath=Te.dataPath),Te.showStatusText!==void 0&&(ht.showStatusText=Te.showStatusText),Te.statusTextPath!==void 0&&(ht.statusTextPath=Te.statusTextPath),Te.showCurrentIndicator!==void 0&&(ht.showCurrentIndicator=Te.showCurrentIndicator)),fe={...fe,properties:ht}}}const Ke=["select","multiselect","radio","checkboxgroup"],Je=fe.type||ze.fieldType;if(Ke.includes(Je)){const ke=ze.options,Te=fe.properties?.options,$e=Array.isArray(Te)&&Te.length>0;if(Array.isArray(ke)&&ke.length>0&&!$e){const ht=fe.properties||{};fe={...fe,properties:{...ht,options:ke}}}}return fe}),_e=$.config?.rules,Pe=J&&Array.isArray(J)?J:_e&&Array.isArray(_e)?_e:[],Re=Pe.length>0?me.map(ze=>{if((ze.conditions&&Array.isArray(ze.conditions)?ze.conditions:[]).length>0)return ze;const Ne=ze.id??ze._id,Xe=ze.name||ze.key,Ke=Pe.filter(Te=>{const $e=typeof Te.targetFieldId=="object"?Te.targetFieldId?.id??Te.targetFieldId?._id:Te.targetFieldId;return $e?$e===Ne||$e===Xe||$e===ze.fieldKey:!1});if(Ke.length===0)return ze;const Je=[],ke=new Set;return Ke.forEach(Te=>{try{const $e=typeof Te.conditionExpression=="string"?JSON.parse(Te.conditionExpression):Te.conditionExpression;if(!$e||typeof $e!="object")return;!$e.id&&Te.id&&($e.id=Te.id);const ht=typeof Te.targetFieldId=="object"?Te.targetFieldId?.id??Te.targetFieldId?._id:Te.targetFieldId;$e.action&&(!$e.then||!Array.isArray($e.then)||$e.then.length===0)&&($e.then=[{action:$e.action,...ht&&{target:ht}}]),(!$e.then||!Array.isArray($e.then)||$e.then.length===0)&&Te.action&&($e.then=[{action:Te.action,...ht&&{target:ht}}]),$e.then&&Array.isArray($e.then)&&ht&&($e.then=$e.then.map(yt=>!yt.target&&ht?{...yt,target:ht}:yt));const dt=Te.conditionExpression??JSON.stringify($e);if(ke.has(dt))return;ke.add(dt),Je.push($e)}catch{}}),Je.length===0?ze:{...ze,conditions:Je}}):me;let nt=$.config||{submitAction:"database",layout:"default",autoSave:!0,validateOnChange:!0,showFieldErrors:"inline"};return!nt.layout&&X?typeof X=="object"&&X!==null?nt.layout="default":typeof X=="string"&&["default","card","compact"].includes(X)?nt.layout=X:nt.layout="default":nt.layout||(nt.layout="default"),J&&!nt.rules&&(nt.rules=J),te&&!nt.clientMapping&&(nt.clientMapping=te),{...$,fields:Re,config:nt}},[we,O,p,G]);S.useEffect(()=>{we&&we!==O&&N(we)},[we]),S.useEffect(()=>{if(t&&!e){const k=(Fn()??"").trim()||"default",$=Oh({scope:k,formId:t,version:"latest"});$?.value?.schema?(N($.value.schema),$.value.bffSubmitApi&&B($.value.bffSubmitApi),R(!1),$.isStale&&Le({background:!0})):Le({background:!1})}},[t,e]);const Le=async({background:k})=>{if(!t)return;const $=t;k||R(!0);try{const X=await ih.getForRendering(t),J=vi(X.form,X.fields,X.layout,X.rules);if($!==t)return;N(J),X.BFF_submit_api&&B(X.BFF_submit_api);const te=(Fn()??"").trim()||"default";Ph({scope:te,formId:$,version:"latest"},{schema:J,bffSubmitApi:X.BFF_submit_api})}catch{}finally{k||R(!1)}};if(j||be)return u.jsx("div",{className:"flex items-center justify-center py-12",children:u.jsx(ah,{})});if(!ct)return u.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Form not found"});const ee=ct,Ye=S.useMemo(()=>new Set(Object.keys(ee.config?.prepopulateApi?.fieldMapping??{})),[ee.config?.prepopulateApi?.fieldMapping]),et=S.useCallback(async k=>{const $=ee?.fields?.length?Cl(k,ee.fields):k;if(n){const X=m?{...$,...m}:$;return n(X)}return{success:!0}},[n,m,ee?.fields]),{values:Ue,errors:Q,touched:ce,isSubmitting:ue,isValid:xe,submitCount:Ae,currentStep:De,totalSteps:rt,completedSteps:vt,currentStepFields:Ge,isLastStep:ut,setFieldValue:We,setFieldTouched:mt,handleSubmit:tr,validateForm:kr,resetForm:Ht,nextStep:Fr,goToStep:jr,shouldShowField:on,isFieldEnabled:jt,isFieldRequired:vr,loadDraft:Bn}=Wc({schema:ee,initialValues:r,onSubmit:et,onChange:o,workflowStepId:w});gy({fields:ee.fields,values:Ue,buttonResponses:L,prepopulateResponse:oe,prepopulateResponseRules:ee.config?.prepopulateResponseRules});const wt=qt(k=>k.readOnlyFields),wr=qt(k=>k.editableFields),$n=S.useCallback(k=>wt.has(k),[wt]),Lt=S.useCallback(k=>wr.has(k),[wr]);S.useEffect(()=>{ee.config?.allowDraft&&a==="fill"&&Bn()},[ee.id]),S.useEffect(()=>{st.current=ee.id,je.current=!1,q({}),le({}),ne({}),Y({}),ie(null)},[ee.id]),S.useEffect(()=>{const k=ee.config?.prepopulateApi,$=!!(k?.fieldMapping&&Object.keys(k?.fieldMapping??{}).length>0),X=(ee.config?.prepopulateResponseRules?.length??0)>0;if(!k?.enabled||!k.apiEndpoint?.trim()||!$&&!X||je.current)return;je.current=!0;const J=ee.id;st.current=ee.id;let te=!1;return D(!0),(async()=>{try{const me=qt.getState().values,_e=typeof m=="object"&&m!==null?{...m,...h||{}}:h||{},Pe=de=>Yr(de,me,he,_e);let Re=Gr(Pe(k.apiEndpoint));if(k.apiQueryParams?.length){const de=new URLSearchParams;k.apiQueryParams.forEach(({key:Ce,value:Fe})=>de.append(Ce,Pe(Fe))),Re=`${Re}${Re.includes("?")?"&":"?"}${de.toString()}`}const nt={};k.apiHeaders?.forEach(({key:de,value:Ce})=>{de.trim()&&(nt[de]=Pe(Ce))}),nt["Content-Type"]=nt["Content-Type"]??"application/json";let Rt;if(k.apiMethod==="POST"&&k.apiBodyFields?.length){const de={};k.apiBodyFields.forEach(({key:Ce,value:Fe})=>{Ce.trim()&&(de[Ce]=Pe(Fe))}),Rt=JSON.stringify(de)}const ze=await fetch(Re,{method:k.apiMethod,headers:nt,body:k.apiMethod==="POST"?Rt:void 0});if(!ze.ok){const de=await ze.text();throw new Error(de||`HTTP ${ze.status}`)}const fe=await ze.json(),Ne=de=>{try{return de.split("?")[0].split("/").filter(Boolean).pop()||de}catch{return de}},Xe=(de,Ce)=>{if(de==null)return null;const Fe=typeof de=="string"?de:de instanceof Date?de.toISOString():null;if(!Fe)return null;const Qe=typeof de=="object"&&de instanceof Date?de:new Date(Fe);if(Number.isNaN(Qe.getTime()))return null;const ft=St=>String(St).padStart(2,"0");if(Ce==="date")return Fe.length>=10&&Fe[4]==="-"&&Fe[7]==="-"?Fe.slice(0,10):Qe.toISOString().slice(0,10);if(Ce==="time")return`${ft(Qe.getHours())}:${ft(Qe.getMinutes())}:${ft(Qe.getSeconds())}`;if(Ce==="datetime"){const St=Qe.getFullYear(),gt=Qe.getMonth()+1,Se=Qe.getDate(),Tt=Qe.getHours(),Ze=Qe.getMinutes(),Mt=Qe.getSeconds();return`${St}-${ft(gt)}-${ft(Se)}T${ft(Tt)}:${ft(Ze)}:${ft(Mt)}`}return null},Ke=(de,Ce)=>{const Fe=ee.fields.find(Se=>Se.name===de||Se.key===de);if(!Fe)return Ce;if((Fe.type==="file"||Fe.type==="camera"||Fe.type==="photoChoice")&&typeof Ce=="string"&&Ce.startsWith("http"))return{url:Ce,name:Ne(Ce)};if(Fe.type==="date"||Fe.type==="datetime"||Fe.type==="time"){const Se=Xe(Ce,Fe.type);if(Se!==null)return Se}if(Fe.type==="multiselect")return Array.isArray(Ce)?Ce.map(Se=>typeof Se=="string"?Se:String(Se)):typeof Ce=="string"?Ce.trim()===""?[]:Ce.includes(",")?Ce.split(",").map(Se=>Se.trim()).filter(Boolean):[Ce]:Ce!=null&&Ce!==""?[String(Ce)]:[];if(Fe.type!=="radio"&&Fe.type!=="select")return Ce;const Qe=Fe.properties?.options??Fe.options;if(!Array.isArray(Qe)||Qe.length===0)return Ce;const ft=Qe.map(Se=>Se.value);if(ft.includes(Ce))return Ce;const St=String(Ce);if(ft.includes(St))return St;const gt=Qe.find(Se=>Se.value==Ce);return gt?gt.value:Ce},Je=new Set(ee.fields.filter(de=>de.type==="table").map(de=>de.name||de.key)),ke=de=>de.name||de.key||de.id,Te={},$e=[],ht=[];for(const[de,Ce]of Object.entries(k?.fieldMapping??{})){if(!Ce?.trim()||de.startsWith("__"))continue;const Fe=pt(fe,Ce),Qe=de.indexOf(".");if(Qe>0&&Je.has(de.slice(0,Qe))){const St=de.slice(0,Qe),gt=de.slice(Qe+1);$e.push({tableName:St,columnName:gt,path:Ce});continue}if(Je.has(de)&&Array.isArray(Fe)&&Fe.length>0&&typeof Fe[0]=="object"&&Fe[0]!==null){const gt=ee.fields.find(Ze=>(Ze.name||Ze.key)===de)?.properties?.columns||[],Se=Fe.map(Ih),Tt=Ze=>(Ze||"").toLowerCase().replace(/\s+/g,"_").trim();Te[de]=Se.map(Ze=>{const Mt={};for(const ar of gt){const Rn=ar.name??"";Mt[Rn]=Ze[Tt(Rn)]??Ze[Rn]}return Mt});continue}if(Fe!=null&&(Te[de]=Ke(de,Fe)),Fe==null)continue;let ft=Fe;if(Array.isArray(Fe)){const St=ee.fields.find(gt=>ke(gt)===de);if(St?.type==="addmore"){ht.push({addMoreFieldName:de,array:Fe});continue}if(St?.type==="multiselect"){const gt=k.multiselectArrayPropertyMap?.[de];gt&&Fe.length>0&&Fe.some(Se=>Se!=null&&typeof Se=="object")&&(ft=Fe.map(Se=>Se!=null&&typeof Se=="object"&> in Se?Se[gt]:void 0).filter(Se=>Se!=null))}}Te[de]=Ke(de,ft)}const dt={},yt={},It={};for(const{addMoreFieldName:de,array:Ce}of ht){const Fe=ee.fields.find(Tt=>ke(Tt)===de);if(!Fe||Fe.type!=="addmore")continue;const Qe=Eh(Fe,ee.fields,ee.config?.sections,ke);if(Qe.length===0)continue;const ft=k.addMoreFieldKeyMap?.[de],St=Ce.length>0&&Ce[0]!=null&&typeof Ce[0]=="object"?Ce[0]:null;if(St)for(const Tt of Qe){const Ze=ke(Tt),Mt=ft&&ft[Ze]||Ze,ar=St[Mt];ar!=null&&(Te[Ze]=Ke(Ze,ar))}const gt=Ce.slice(1),Se=gt.map((Tt,Ze)=>`prepop_${de}_${Ze}_${Date.now()}`);Se.length>0&&(yt[de]=Se);for(let Tt=0;Tt<gt.length;Tt++){const Ze=gt[Tt];if(Ze==null||typeof Ze!="object")continue;const Mt=Ze,ar=Mt.id;ar!=null&&String(ar).trim()!==""&&(It[`${de}__${Se[Tt]}`]=String(ar));for(const Rn of Qe){const Ri=ke(Rn),R_=ft&&ft[Ri]||Ri,nc=Mt[R_];if(nc==null)continue;const z_=`${Ri}__addmore__${de}__${Se[Tt]}`;dt[z_]=Ke(Ri,nc)}}}Object.keys(yt).length>0&&le(de=>({...de,...yt})),Object.keys(It).length>0&&Y(de=>({...de,...It}));const Ft=de=>(de||"").toLowerCase().replace(/\s+/g,"_").trim(),Ur=[...new Set($e.map(de=>de.tableName))];for(const de of Ur){if(Array.isArray(Te[de]))continue;const Ce=$e.find(Se=>Se.tableName===de);if(!Ce?.path?.includes("."))continue;const Fe=Ce.path.replace(/\.[^.]+$/,""),Qe=pt(fe,Fe);if(!Array.isArray(Qe)||Qe.length===0||typeof Qe[0]!="object"||Qe[0]===null)continue;const St=ee.fields.find(Se=>(Se.name||Se.key)===de)?.properties?.columns||[],gt=Qe.map(Ih);Te[de]=gt.map(Se=>{const Tt={};for(const Ze of St){const Mt=Ze.name??"",ar=Ft(Mt),Rn=Se[ar]??Se[Mt];Tt[Mt]=Rn}return Tt})}const Xr=(de,Ce)=>{const Fe=pt(fe,de);if(Array.isArray(Fe))return Fe;if(Fe!=null)return[Fe];if(!de.includes("."))return[];const Qe=de.replace(/\.[^.]+$/,""),ft=pt(fe,Qe);return!Array.isArray(ft)||ft.length===0||typeof ft[0]!="object"||ft[0]===null?[]:ft.map(St=>{const gt=St[Ce];if(gt!==null&&typeof gt=="object"&&!Array.isArray(gt)&&!(gt instanceof Date)){const Se=gt;return typeof Se.name=="string"&&typeof Se.code=="string"?`${Se.code} ${Se.name}`.trim():typeof Se.name=="string"?Se.name:typeof Se.code=="string"?Se.code:typeof Se.short_code=="string"?Se.short_code:Se.name??Se.code??""}return gt})};for(const{tableName:de,columnName:Ce,path:Fe}of $e){const Qe=Xr(Fe,Ce),St=ee.fields.find(Ze=>(Ze.name||Ze.key)===de)?.properties?.columns||[],gt=St.find(Ze=>(Ze.name||"").toLowerCase()===Ce.toLowerCase())?.name??Ce;let Se=Array.isArray(Te[de])?Te[de]:[];const Tt=Math.max(Se.length,Qe.length);if(Tt>Se.length)for(Se=[...Se];Se.length<Tt;){const Ze={};St.forEach(Mt=>{Ze[Mt.name||""]=""}),Se.push(Ze)}else Se=Se.map(Ze=>({...Ze}));Qe.forEach((Ze,Mt)=>{Se[Mt]&&(Se[Mt][gt]=Ze)}),Te[de]=Se}if(st.current===J){if(Object.keys(Te).length>0||Object.keys(dt).length>0){const Mt={...qt.getState().values,...Te,...dt};Ee(Mt)}const Ce=pt(fe,"data.user_id"),Fe=pt(fe,"data.items"),Qe=pt(fe,"data");let ft=Array.isArray(Fe)&&Fe.length>0&&Fe[0]!=null&&typeof Fe[0]=="object"&&Fe[0].id?Fe[0].id:void 0;ft===void 0&&Array.isArray(Qe)&&Qe.length>0&&Qe[0]!=null&&typeof Qe[0]=="object"&&Qe[0].id&&(ft=Qe[0].id),ft===void 0&&(ft=pt(fe,"data.0.id"));const St=VT(fe,{treatFirstItemIdAsPaymentId:k?.treatFirstItemIdAsPaymentId===!0}),gt=pt(fe,"data.id"),Se=pt(fe,"data.batch_id"),Tt=pt(fe,"data.program_id"),Ze={};Ce!=null&&(Ze.context_user_id=Ce),ft!=null&&ft!==""&&(Ze.documentId=ft),gt!=null&&String(gt).trim()!==""&&(m?.id===void 0||m?.id===null)&&(Ze.id=gt),Se!=null&&String(Se).trim()!==""&&((m?.admission_batch_id===void 0||m?.admission_batch_id===null)&&(Ze.admission_batch_id=Se),(m?.batch_id===void 0||m?.batch_id===null)&&(Ze.batch_id=Se)),Tt!=null&&String(Tt).trim()!==""&&(m?.program_id===void 0||m?.program_id===null)&&(Ze.program_id=Tt),St!=null&&String(St).trim()!==""&&(m?.payment_id===void 0||m?.payment_id===null)&&(Ze.payment_id=St),Object.keys(Ze).length>0&&q(Mt=>{const ar={...Mt,...Ze};return g?.(ar),ar}),ie(fe)}}catch(me){te||xl(me,"Prepopulate request failed.",Wo)}finally{D(!1)}})(),()=>{te=!0}},[ee.id,ee.config?.prepopulateApi?.enabled,ee.config?.prepopulateApi?.apiEndpoint,ee.config?.prepopulateApi?.apiMethod,JSON.stringify(ee.config?.prepopulateApi?.fieldMapping),ee.config?.prepopulateApi?.treatFirstItemIdAsPaymentId,m,h,he,Ee,le]),S.useEffect(()=>{Object.keys(Q).length>0&&s?.(Q)},[Q,s]);const Sr=rt>1,Jt=a==="view",rr=S.useCallback((k,$)=>Jt||!!$&&!Lt(k)||$n(k)&&!Lt(k),[Jt,Lt,$n]),sn=ee.fields.filter(k=>!k.parentId),Ct=[...Sr?Ge:sn.length>0?sn:ee.fields].filter(k=>!(!k||typeof k!="object"||!k.name&&!k.key)).sort((k,$)=>{const X=typeof k.position?.order=="number"?k.position.order:typeof k.positionOrder=="number"?k.positionOrder:Number.MAX_SAFE_INTEGER,J=typeof $.position?.order=="number"?$.position.order:typeof $.positionOrder=="number"?$.positionOrder:Number.MAX_SAFE_INTEGER;if(X!==J)return X-J;const te=typeof k.position?.column=="number"?k.position.column:1,me=typeof $.position?.column=="number"?$.position.column:1;return te-me}),Qo=S.useCallback(k=>{const $=qt.getState().errors,X=Object.keys($).find(J=>k.includes(J));X&&requestAnimationFrame(()=>{document.querySelector(`[data-field-name="${X}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})})},[]),xr=async k=>{if(k?.preventDefault(),Sr&&!ut){if(!await Fr())try{const J=qt.getState().errors;Dt.toast.error(Al(J,ee.fields)||"Please fix the errors before continuing."),Qo(Ct.map(te=>te.name||te.key||te.id).filter(Boolean))}catch{Dt.toast.error("Please fix the errors before continuing.")}return}const $=await tr(k);if($&&$.success===!1&&$.errors?.length)try{const X=qt.getState().errors;Dt.toast.error(Al(X,ee.fields)||"Submission failed. Please check the form."),Qo(Ct.map(J=>J.name||J.key||J.id).filter(Boolean))}catch{Dt.toast.error("Submission failed. Please check the form.")}return $},Or=S.useCallback(()=>{Ht(),i&&i()},[Ht,i]),Ar=S.useCallback((k,$)=>{const X=ee.fields.find(te=>te.type==="button"&&(te.name===k||te.key===k)),J=GT($,X);J!=null&&String(J).trim()!==""&&(m?.payment_id===void 0||m?.payment_id===null)&&q(te=>{const me={...te,payment_id:J};return g?.(me),me}),z(te=>{const me={...te,[k]:$};return!Co($)||!(X?.type==="button"&&X.properties?.action==="submit")||ee.fields.filter(Re=>Re.type==="editButton").map(Re=>Re.name).forEach(Re=>delete me[Re]),me})},[ee.fields,m,g]),fr=S.useCallback(async()=>await kr(),[kr]),Wt=S.useCallback(()=>qt.getState().errors,[]),Qt=S.useMemo(()=>({...h||{},...K}),[h,K]),Pr=S.useMemo(()=>({...typeof m=="object"&&m!==null?m:{},...Qt}),[m,Qt]),_i=ee.config?.layout??ee.layout??"default",Ni=["default","card","compact"].includes(_i)?_i:"default",ki={default:"",card:"bg-card border rounded-lg shadow-sm p-6",compact:"space-y-2"},Zo=S.useMemo(()=>{if(C)return;const k=ee.config?.theme?.cssVariables;if(!(!k&&!I))return{...k??{},...I??{}}},[C,ee.config?.theme?.cssVariables,I]),Cr=S.useMemo(()=>Wi({config:ee.config,layout:ee.layout},l),[ee.config,ee.layout,l]),Oe=S.useMemo(()=>Cr?{...Cr,verticalSpacing:Cr.verticalSpacing??Cr.spacing??"16px",horizontalSpacing:Cr.horizontalSpacing??Cr.spacing??"16px",rowHeight:Cr.rowHeight??zn}:null,[Cr]),F=Oe!==null,se=Oe?.rows??8,pe=Oe?.columns??3,it=Oe?.verticalSpacing??Oe?.spacing??"16px",Nt=Oe?.horizontalSpacing??Oe?.spacing??"16px",Et=Oe?.rowHeight??zn,Pt=S.useCallback(k=>{if(!E)return!0;const $=k.visibility;if(!$)return!0;const X=$.visibleToUserType??$.user_type,J=$.visibleToUserRole??$.user_role,te=Array.isArray($.visibleToUserIds)?$.visibleToUserIds:Array.isArray($.users)?$.users:[],me=Array.isArray($.hiddenFromUserIds)?$.hiddenFromUserIds:[];if(Array.isArray(me)&&me.length>0&&E.userId!=null&&me.includes(E.userId))return!1;if(te.length>0&&E.userId!=null&&te.includes(E.userId))return!0;const _e=X!=null&&X!==""&&E.userType!=null&&E.userType!==X,Pe=J!=null&&J!==""&&E.role!=null&&E.role!==J,Re=te.length>0&&(E.userId==null||!te.includes(E.userId));return!(_e||Pe||Re)},[E]),Ut=k=>{if(!Pt(k))return!1;const $=k.name||k.key||k.id,X=k.hidden===!0;return on($)||!X&&$},kt=ee.config?.sections,lt=S.useCallback(k=>k.name||k.key||k.id,[]),xt=S.useCallback(k=>{let $=k;if(k.type==="table"){const J=k.properties?.columns;if(Array.isArray(J)&&J.length>0){const te=J.filter(me=>Pt(me));$={...k,properties:{...k.properties,columns:te}}}}const X=QT($,kt,lt);return X?{...$,label:Ch(X,0)}:$},[Pt,kt,lt]),Ir=S.useCallback(k=>Eh(k,ee.fields,kt,lt),[ee.fields,kt,lt]),pr=S.useCallback((k,$,X)=>`${k}__addmore__${$}__${X}`,[]),Fi=S.useCallback((k,$)=>`${k}__${$??"base"}`,[]),Oi=S.useCallback((k,$)=>{const X=Fi(k.id,$);return re[X]??k.defaultCollapsed??!1},[re,Fi]),Zl=S.useCallback((k,$,X)=>{const J=Fi(k,$);ne(te=>te[J]===X?te:{...te,[J]:X})},[Fi]),Pi=S.useMemo(()=>{const k=[],$=ee.fields.filter(X=>X.type==="addmore");for(const X of $){const J=lt(X),me=Ir(X).find(nt=>{if(nt.type!=="button")return!1;const Rt=nt.properties,ze=nt.metadata;let fe=Rt?.action;if(!fe&&ze!=null)try{fe=(typeof ze=="string"?JSON.parse(ze):ze)?.action}catch{}return fe==="upload"||fe==="custom"});if(!me)continue;const _e=lt(me),Pe=V[J]||[],Re=pt(L[_e],"data.id")??pt(L[_e],"data.documentId")??K.documentId;Re!=null&&String(Re).trim()!==""&&k.push(String(Re));for(const nt of Pe){const Rt=pr(_e,J,nt),ze=pt(L[Rt],"data.id")??pt(L[Rt],"data.documentId"),fe=Z[`${J}__${nt}`],Ne=ze??fe;Ne!=null&&String(Ne).trim()!==""&&k.push(String(Ne))}}return k},[ee.fields,V,L,Z,K.documentId,lt,Ir,pr]);S.useEffect(()=>{q(k=>{const $={...k,document_ids:Pi},X=k.document_ids;return Array.isArray(X)&&X.length===Pi.length&&Pi.every((J,te)=>X[te]===J)?k:$})},[Pi]);const Ii=S.useCallback((k,$,X,J)=>{for(const te of X){const me=lt(te),_e=pr(me,k,$),Pe=J[_e];if(Pe==null)continue;const Re=te.type;if(Re==="file"||Re==="camera"||Re==="photoChoice"){if(typeof Pe=="object"&&Pe!==null&&("url"in Pe||"name"in Pe)||Array.isArray(Pe)&&Pe.length>0)return!0;continue}if(Array.isArray(Pe)){if(Pe.length>0)return!0;continue}if(typeof Pe=="string"&&Pe.trim()!==""||typeof Pe=="number"&&!Number.isNaN(Pe)||typeof Pe=="boolean"||typeof Pe=="object"&&Pe!==null&&Object.keys(Pe).length>0)return!0}return!1},[lt,pr]),jn=S.useCallback(k=>{const $=lt(k);if(!$)return;if(Ir(k).length===0){Dt.toast.error("No linked fields configured for this Add More button.");return}const J=`${Date.now()}_${Math.random().toString(36).slice(2,8)}`;le(te=>({...te,[$]:[...te[$]||[],J]}))},[lt,Ir]),Mi=S.useCallback((k,$)=>{le(X=>{const J=X[k]||[],te=J.filter(me=>me!==$);if(te.length===J.length)return X;if(te.length===0){const me={...X};return delete me[k],me}return{...X,[k]:te}})},[]),Li=S.useMemo(()=>Ct.filter(k=>!k.parentId),[Ct]),bn=S.useMemo(()=>{const k=[];return Ct.filter(X=>X.type==="addmore").sort((X,J)=>{const te=X.position?.order??0,me=J.position?.order??0;return te-me}).forEach(X=>{const J=lt(X),te=X.position?.order??0,me=V[J]||[],_e=Ir(X).sort((Xe,Ke)=>{const Je=Xe.position?.order??0,ke=Ke.position?.order??0;return Je!==ke?Je-ke:(Xe.position?.column??1)-(Ke.position?.column??1)});if(_e.length===0)return;const Pe=Ah(X,kt),Re=Pe[0]?.fieldNames?.length?Pe[0].fieldNames:_e.map(Xe=>lt(Xe)).filter(Boolean),nt=t_(Re,Li,pe,lt),Rt=Math.min(..._e.map(Xe=>Xe.position?.order??0)),ze=Math.max(1,..._e.map(Xe=>(Xe.position?.order??Rt)-Rt+vo(Xe))),fe=nt?.blockHeight??ze,Ne=me.length*fe;k.push({addMoreFieldName:J,baseOrder:te,blockHeight:fe,blockIds:me,linkedFields:_e,insertedRows:Ne,templateFieldNames:Re,templateBounds:nt})}),k},[Ct,Li,pe,lt,V,Ir,kt]),ec=S.useMemo(()=>({}),[]),Di=S.useMemo(()=>bn.length===0?Ct:Ct.map(k=>{const $=k.position?.order??0,X=bn.reduce((J,te)=>{const me=te.templateBounds?.maxRow??te.baseOrder;return $>me?J+te.insertedRows:J},0);return X===0?k:{...k,position:{...k.position,order:$+X}}}),[Ct,bn]),Bi=S.useCallback(k=>{const $={};return Object.entries(L).forEach(([X,J])=>{const te=k[X];te&&($[te]=J)}),$},[L]),yo=S.useMemo(()=>{const k=[],$={};return bn.forEach(X=>{const{addMoreFieldName:J,blockIds:te,linkedFields:me,blockHeight:_e,templateBounds:Pe}=X,Re=Math.min(...me.map(ze=>ze.position?.order??0)),Rt=ee.fields.find(ze=>lt(ze)===J&&ze.type==="addmore")?.properties;te.forEach((ze,fe)=>{const Ne={},Xe={},Ke={},Je=Pe?r_(Pe,fe):X.baseOrder+1+fe*_e,ke=Z[`${J}__${ze}`];me.forEach($e=>{const ht=lt($e),dt=pr(ht,J,ze),yt=($e.position?.order??Re)-Re;if(Ne[dt]=ht,Xe[dt]=Ue[dt],!(Rt?.linkedFieldAllowDuplicate?.[ht]??!0)&&($e.type==="select"||$e.type==="radio"||$e.type==="multiselect")){const Ft=[],Ur=Ue[ht];Ur!=null&&Ur!==""&&(Array.isArray(Ur)?Ft.push(...Ur.map(Jr=>String(Jr))):Ft.push(String(Ur))),te.filter(Jr=>Jr!==ze).forEach(Jr=>{const de=pr(ht,J,Jr),Ce=Ue[de];Ce!=null&&Ce!==""&&(Array.isArray(Ce)?Ft.push(...Ce.map(Fe=>String(Fe))):Ft.push(String(Ce)))}),Ft.length>0&&(Ke[dt]=[...new Set(Ft)])}k.push({...$e,id:`${$e.id}__${ze}`,name:dt,position:{...$e.position,order:Je+yt}})});const Te=Bi(Ne);Object.keys(Ne).forEach($e=>{$[$e]={scopedFormValues:Xe,scopedFieldNameMap:Ne,scopedButtonResponses:Te,...ke!=null&&{blockDocumentId:ke},...Ke[$e]&&{excludedOptionValues:Ke[$e]}}})})}),{clonedFields:k,scopeByFieldName:$}},[bn,Z,lt,pr,Ue,Bi,ee.fields]),es=S.useMemo(()=>[...Di,...yo.clonedFields].sort((k,$)=>{const X=k.position?.order??0,J=$.position?.order??0;if(X!==J)return X-J;const te=k.position?.column??1,me=$.position?.column??1;if(te!==me)return te-me;const _e=k.position?.cellSlot??0,Pe=$.position?.cellSlot??0;return _e!==Pe?_e-Pe:String(k.id).localeCompare(String($.id))}),[Di,yo.clonedFields]),$i=S.useMemo(()=>jT(es.filter(k=>!k.parentId),Ut),[es,Ut]),tc=S.useCallback((k,$)=>$i.some(X=>UT(k,$,X,pe)),[$i,pe]),$_=$i.length===0?0:Math.max(...$i.map(k=>(k[0]?.position?.order??0)+Ei(k,pe).rowSpan)),rc=Math.max(se,$_,1),ji=S.useMemo(()=>ZT(kt,Yl(Ct.filter(k=>!k.parentId)),lt),[kt,Ct,lt]),{anchorsByOrigin:qh,coveredCells:Gh}=S.useMemo(()=>n_(ji,Di,lt,pe),[ji,Di,lt,pe]),{anchorsByOrigin:Kh,coveredCells:Yh}=S.useMemo(()=>o_(bn.map(k=>({addMoreFieldName:k.addMoreFieldName,blockIds:k.blockIds,linkedFields:k.linkedFields,templateFieldNames:k.templateFieldNames})),kt,yo.clonedFields,Li,pe,lt,Gh),[bn,kt,yo.clonedFields,Li,pe,lt,Gh]),Un=S.useMemo(()=>d_(qh,Kh),[qh,Kh]),Xh=S.useMemo(()=>Yh,[Yh]),Jh=String(Et).endsWith("px")?Et:zn,Qh=S.useCallback((k,$)=>{for(let X=0;X<pe;X++){if(X>=$.anchorCol&&X<$.anchorCol+$.colSpan)continue;if(ec[`${k}-${X}`]||Un.get(`${k}-${X}`)||xh(k,X,es,Ut).length>0||tc(k,X))return!0}return!1},[pe,ec,Un,es,Ut,tc]),Zh=S.useMemo(()=>l_(Un,k=>{const $=k.run.section;return $.collapsible?Oi($,k.addMoreMeta?.blockId):!1},Qh),[Un,Oi,Qh]),j_=S.useMemo(()=>c_(rc,Jh,Zh),[rc,Jh,Zh]),U_=S.useMemo(()=>u_(Ct.filter(k=>!k.parentId&&Ut(k)),ji,lt),[Ct,ji,lt,Ut]),Ui=S.useCallback(k=>{if(F)return null;const $=lt(k),X=V[$]||[];if(X.length===0)return null;const J=Ir(k);if(J.length===0)return null;const te=JT(k,kt),me=J.map(Re=>lt(Re)).filter(Boolean),_e=_h(me,kt),Pe=(Re,nt,Rt,ze,fe,Ne,Xe)=>{const Ke=lt(Re),Je=pr(Ke,$,nt),ke=Re.hidden===!0;if(!(Pt(Re)&&(on(Ke)||!ke&&Ke)))return null;const $e={...Re,id:`${Re.id}__${nt}`,name:Je},dt=k.properties?.linkedFieldAllowDuplicate?.[Ke]??!0;let yt;if(!dt&&(Re.type==="select"||Re.type==="radio"||Re.type==="multiselect")){const It=[],Ft=Ue[Ke];Ft!=null&&Ft!==""&&(Array.isArray(Ft)?It.push(...Ft.map(Xr=>String(Xr))):It.push(String(Ft))),X.filter(Xr=>Xr!==nt).forEach(Xr=>{const Jr=pr(Ke,$,Xr),de=Ue[Jr];de!=null&&de!==""&&(Array.isArray(de)?It.push(...de.map(Ce=>String(Ce))):It.push(String(de)))}),It.length>0&&(yt=[...new Set(It)])}return u.jsx("div",{"data-field-name":Je,"data-form-renderer":"field-wrapper",children:u.jsx(nn,{field:$e,value:Ue[Je],error:ce[Je]||Ae>0?Q[Je]:void 0,onChange:It=>We(Je,It),onBlur:()=>mt(Je),disabled:ye||!jt(Ke)||Jt||!!Re.disabled,readOnly:rr(Ke,!!Re.readOnly),isRequired:vr(Ke),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:Je,buttonResponses:Ne,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:Xe,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,scopedFormValues:fe,scopedFieldNameMap:ze,excludedOptionValues:yt,hideTableRowControls:A})},$e.id)};return u.jsx("div",{className:"space-y-3 mt-3",children:X.map((Re,nt)=>{const Rt={},ze={};J.forEach(yt=>{const It=lt(yt),Ft=pr(It,$,Re);Rt[Ft]=It,ze[Ft]=Ue[Ft]});const fe=Bi(Rt),Ne=Ii($,Re,J,Ue),Xe=te?.heading!=null?Jo(te,nt+1):null,Ke=Z[`${$}__${Re}`],Je=Ke!=null?{...Qt,documentId:Ke}:Qt,ke=J.map(yt=>Pe(yt,Re,nt,Rt,ze,fe,Je)).filter(Boolean),$e=_e?.section?.collapsible===!0,ht=u.jsx("button",{type:"button",className:"inline-flex shrink-0 rounded-md p-1.5 text-destructive hover:bg-destructive/10 focus:outline-none focus:ring-2 focus:ring-ring disabled:pointer-events-none disabled:opacity-40",disabled:Ne,title:Ne?"Cannot remove: this entry has data":"Remove entry","aria-label":"Remove entry",onClick:yt=>{yt.preventDefault(),yt.stopPropagation(),Mi($,Re)},children:u.jsx(ko,{className:"h-5 w-5","aria-hidden":!0})}),dt=u.jsxs(u.Fragment,{children:[!$e&&u.jsxs("div",{className:"flex items-center justify-between gap-2",children:[Xe?u.jsx("p",{className:"text-sm font-medium text-foreground",children:Xe}):u.jsxs("p",{className:"text-xs text-muted-foreground",children:["Entry ",nt+1]}),ht]}),ke]});return u.jsx("div",{className:"rounded-md border p-3 space-y-3",children:_e?u.jsx(zl,{legend:_e.section.heading?.enabled?Jo(_e.section,nt+1):_e.section.name,collapsible:_e.section.collapsible,defaultCollapsed:_e.section.defaultCollapsed,headerActions:$e?ht:void 0,onCollapsedChange:yt=>Zl(_e.section.id,Re,yt),children:dt}):dt},`${k.id}-${Re}`)})})},[F,V,Z,lt,Ir,pr,Ii,Ue,ce,Ae,Q,We,mt,jt,Jt,vr,Pr,Ye,Ar,xr,Ht,Or,ue,P,b,Qt,fr,Wt,ee.fields,ae,on,Pt,Bi,Mi,A,kt,he,oe,H]);return u.jsx("div",{className:C?W("relative",d):W(Hi,T&&"dark",d),style:Zo,"data-form-renderer":C?void 0:"root",children:u.jsxs("div",{className:"relative",children:[H&&u.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/60 rounded-md",children:u.jsx(ah,{})}),u.jsxs("form",{onSubmit:xr,className:f?W("w-full min-w-0"):W("space-y-6 pb-[100px] w-full min-w-0",ki[Ni]),"data-form-renderer":"form","data-form-renderer-layout":F?"grid":"stack",children:[Sr&&ee.steps&&u.jsx(yT,{steps:ee.steps,currentStep:De,completedSteps:vt,onStepClick:jr}),u.jsx(ra.Provider,{value:{gridStretch:F},children:F?u.jsx("div",{className:f?"w-full min-w-0":"grid w-full min-w-0",style:{display:"grid",gridTemplateRows:j_,gridTemplateColumns:`repeat(${pe}, 1fr)`,rowGap:it,columnGap:Nt},"data-form-renderer":"grid",children:Array.from({length:rc},(k,$)=>Array.from({length:pe},(X,J)=>{if(tc($,J))return u.jsx("div",{className:"min-w-0 min-h-0",style:{gridRow:$+1,gridColumn:J+1,visibility:"hidden",pointerEvents:"none"},"data-form-renderer":"grid-cell","data-form-renderer-empty":!0},`empty-${$}-${J}`);if(s_($,J,Xh,Un)){const fe=i_($,J,Un);return fe&&a_($,J,fe,Oi(fe.run.section,fe.addMoreMeta?.blockId))?null:u.jsx("div",{className:"min-w-0 min-h-0",style:{gridRow:$+1,gridColumn:J+1,visibility:"hidden",pointerEvents:"none"},"data-form-renderer":"grid-cell","data-form-renderer-empty":!0},`section-border-cover-${$}-${J}`)}const te=Un.get(`${$}-${J}`);if(te){const fe=te.renderFields.filter(dt=>Ut(dt)),Ne=te.addMoreMeta,Xe=Ne!=null?bn.find(dt=>dt.addMoreFieldName===Ne.addMoreFieldName)?.linkedFields??[]:[],Ke=Ne!=null?Ii(Ne.addMoreFieldName,Ne.blockId,Xe,Ue):!1,Je=te.run.section,ke=Ne?.blockId,Te=Oi(Je,ke),$e=Je.collapsible&&Te?1:te.rowSpan,ht=Ne!=null?u.jsx("button",{type:"button",className:W("inline-flex shrink-0 rounded-md p-1.5 text-destructive hover:bg-destructive/10 focus:outline-none focus:ring-2 focus:ring-ring disabled:pointer-events-none disabled:opacity-40",f&&"text-red-600 hover:bg-red-500/10"),disabled:Ke,title:Ke?"Cannot remove: this entry has data":"Remove entry","aria-label":"Remove entry",onClick:dt=>{dt.preventDefault(),dt.stopPropagation(),Mi(Ne.addMoreFieldName,Ne.blockId)},children:u.jsx(ko,{className:"h-5 w-5","aria-hidden":!0})}):void 0;return u.jsx("div",{className:W("min-h-0 min-w-0",!(Je.collapsible&&Te)&&"self-stretch"),style:{gridRow:`${$+1} / span ${$e}`,gridColumn:`${J+1} / span ${te.colSpan}`},"data-form-renderer":"grid-cell","data-form-renderer-config-section-border-cell":!0,children:u.jsx(zl,{legend:te.legend,className:Je.collapsible&&Te?void 0:"h-full",collapsible:Je.collapsible,defaultCollapsed:Je.defaultCollapsed,headerActions:ht,onCollapsedChange:dt=>Zl(Je.id,ke,dt),children:u.jsx("div",{className:"grid w-full min-w-0",style:{gridTemplateColumns:`repeat(${pe}, 1fr)`,gridTemplateRows:`repeat(${te.rowSpan}, minmax(${String(Et).endsWith("px")?Et:zn}, auto))`,rowGap:it,columnGap:Nt},children:fe.map(dt=>{const yt=lt(dt),It=yo.scopeByFieldName[yt],Ft=It?.scopedFieldNameMap?.[yt]||yt,Ur=(dt.position?.order??te.anchorRow)-te.anchorRow,Xr=dt.position?.column??1,{rowSpan:Jr,columnSpan:de}=Ei([dt],pe),Ce=Ne!=null?Z[`${Ne.addMoreFieldName}__${Ne.blockId}`]:void 0,Fe=Ce!=null?{...Qt,documentId:Ce}:Qt;return u.jsx("div",{"data-field-name":yt,"data-form-renderer":"field-wrapper",className:"min-h-0 min-w-0",style:{gridRow:`${Ur+1} / span ${Jr}`,gridColumn:`${Xr} / span ${de}`,...dn(dt)},children:u.jsx(nn,{field:xt(dt),value:Ue[yt],error:ce[yt]||Ae>0?Q[yt]:void 0,onChange:Qe=>We(yt,Qe),onBlur:()=>mt(yt),disabled:dt.type==="table"&&a==="fill"?!1:ye||!jt(Ft)||Jt||!!dt.disabled,readOnly:dt.type==="table"&&a==="fill"?!1:rr(Ft,!!dt.readOnly),isRequired:vr(Ft),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:yt,buttonResponses:It?.scopedButtonResponses??L,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:Fe,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,onAddMore:jn,scopedFormValues:It?.scopedFormValues,scopedFieldNameMap:It?.scopedFieldNameMap,excludedOptionValues:It?.excludedOptionValues,hideTableRowControls:A})},dt.id)})})})},`section-border-${te.run.section.id}-${$}-${J}-${Ne?.blockId??"base"}`)}const me=xh($,J,es,Ut).filter(fe=>!(lt(fe)?.includes("__addmore__")&&Xh.has(`${$}-${J}`)));if(me.length===0){const fe=ec[`${$}-${J}`];if(fe){const Ne=ee.fields.find(Je=>Je.type==="addmore"&<(Je)===fe.addMoreFieldName),Xe=Ne!=null?Ir(Ne):[],Ke=Ii(fe.addMoreFieldName,fe.blockId,Xe,Ue);return u.jsx("div",{className:"min-h-0 min-w-0 flex flex-col items-center justify-center",style:{gridRow:$+1,gridColumn:J+1},"data-form-renderer":"grid-cell","data-form-renderer-add-more-remove":!0,children:u.jsx("button",{type:"button",className:W("inline-flex shrink-0 rounded-md p-1.5 text-destructive hover:bg-destructive/10 focus:outline-none focus:ring-2 focus:ring-ring disabled:pointer-events-none disabled:opacity-40",f&&"text-red-600 hover:bg-red-500/10"),disabled:Ke,title:Ke?"Cannot remove: this entry has data":"Remove entry","aria-label":"Remove entry",onClick:Je=>{Je.preventDefault(),Je.stopPropagation(),Mi(fe.addMoreFieldName,fe.blockId)},children:u.jsx(ko,{className:"h-5 w-5","aria-hidden":!0})})},`add-more-remove-${$}-${J}`)}return u.jsx("div",{className:"min-w-0",style:{pointerEvents:"none"},"data-form-renderer":"grid-cell","data-form-renderer-empty":!0},`empty-${$}-${J}`)}const _e=me[0],{rowSpan:Pe,columnSpan:Re}=Ei(me,pe);if(me.length===1&&_e.type==="section"){const fe=ee.fields.filter(Ne=>Ne.parentId===_e.id&&Ne.position!=null).sort((Ne,Xe)=>{const Ke=typeof Ne.position?.order=="number"?Ne.position.order:0,Je=typeof Xe.position?.order=="number"?Xe.position.order:0;return Ke-Je});return u.jsx("div",{className:"min-w-0 min-h-0 w-full overflow-hidden flex flex-col h-full",style:{gridRow:`${$+1} / span ${Pe}`,gridColumn:`${J+1} / span ${Re}`,...dn(_e)},"data-form-renderer":"grid-cell",children:u.jsx(Pm,{field:_e,children:fe.map(Ne=>{const Xe=Ne.name||Ne.key||Ne.id,Ke=Ne.hidden===!0;return Pt(Ne)&&(on(Xe)||!Ke&&Xe)?u.jsx("div",{"data-field-name":Xe,"data-form-renderer":"field-wrapper",children:u.jsx(nn,{field:xt(Ne),value:Ue[Xe],error:ce[Xe]||Ae>0?Q[Xe]:void 0,onChange:ke=>We(Xe,ke),onBlur:()=>mt(Xe),disabled:ye||!jt(Xe)||Jt||!!Ne.disabled,readOnly:rr(Xe,!!Ne.readOnly),isRequired:vr(Xe),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:Xe,buttonResponses:L,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:Qt,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,onAddMore:jn,hideTableRowControls:A})},Ne.id):null})})},_e.id)}const nt=Sh(me),Rt=me.some(fe=>["file","camera","photoChoice","addmore","table"].includes(fe.type)),ze=u.jsx("div",{className:W("flex min-h-0 w-full flex-1 gap-3",nt==="row"?"flex-row items-stretch":"flex-col items-stretch"),children:me.map(fe=>{const Ne=fe.name||fe.key||fe.id,Xe=fe.type==="sectionHeading",Ke=yo.scopeByFieldName[Ne],Je=Ke?.scopedFieldNameMap?.[Ne]||Ne,ke=Ke?.blockDocumentId!=null?{...Qt,documentId:Ke.blockDocumentId}:Qt,Te=fe.appearance?.hideLabel??fe.properties?.hideLabel??!1,$e=fe.type==="table"?fe.properties?.minWidth:void 0;return u.jsx("div",{"data-field-name":Ne,"data-form-renderer":"field-wrapper",className:W("flex min-h-0 min-w-0 flex-1 flex-col",xo(fe),Xe&&"items-center justify-center",Te&&"items-center"),style:{...$e?{minWidth:$e}:{},...dn(fe)},children:u.jsx(nn,{field:xt(fe),value:Ue[Ne],error:ce[Ne]||Ae>0?Q[Ne]:void 0,onChange:ht=>We(Ne,ht),onBlur:()=>mt(Ne),disabled:fe.type==="table"&&a==="fill"?!1:ye||!jt(Je)||Jt||!!fe.disabled,readOnly:fe.type==="table"&&a==="fill"?!1:rr(Je,!!fe.readOnly),isRequired:vr(Je),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:Ne,buttonResponses:Ke?.scopedButtonResponses??L,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:ke,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,onAddMore:jn,scopedFormValues:Ke?.scopedFormValues,scopedFieldNameMap:Ke?.scopedFieldNameMap,excludedOptionValues:Ke?.excludedOptionValues,hideTableRowControls:A})},fe.id)})});return u.jsx("div",{className:W(Fc(me),"self-stretch",Rt?"overflow-visible":"overflow-hidden"),style:{gridRow:`${$+1} / span ${Pe}`,gridColumn:`${J+1} / span ${Re}`,...dn(me[0])},"data-form-renderer":"grid-cell","data-field-name":me.map(fe=>fe.name||fe.key||fe.id).join(","),children:ze},me.map(fe=>fe.id).join("-"))}))}):u.jsx("div",{className:f?"":"space-y-4","data-form-renderer":"stack",children:Ct.map(k=>{if(!Ut(k))return null;const $=U_.find(J=>J.kind==="border"&&J.fields.some(te=>te.id===k.id));if($)return $.fields[0]?.id!==k.id?null:u.jsx(zl,{legend:Jo($.run.section,0),collapsible:$.run.section.collapsible,defaultCollapsed:$.run.section.defaultCollapsed,onCollapsedChange:J=>Zl($.run.section.id,void 0,J),children:$.fields.map(J=>{const te=lt(J);return!te||!Ut(J)?null:u.jsxs("div",{"data-field-name":te,"data-form-renderer":"field-wrapper",style:dn(J),children:[u.jsx(nn,{field:xt(J),value:Ue[te],error:ce[te]||Ae>0?Q[te]:void 0,onChange:me=>We(te,me),onBlur:()=>mt(te),disabled:J.type==="table"&&a==="fill"?!1:ye||!jt(te)||Jt||!!J.disabled,readOnly:J.type==="table"&&a==="fill"?!1:rr(te,!!J.readOnly),isRequired:vr(te),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:te,buttonResponses:L,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:Qt,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,onAddMore:jn,hideTableRowControls:A}),J.type==="addmore"&&Ui(J)]},J.id)})},`stack-border-${$.run.section.id}-${k.id}`);if(!k.parentId){const J=Ct.filter(me=>!me.parentId&&Ut(me)&&Ai(me)===Ai(k)),te=Ci(J).slice(0,2);if(te.length>1&&te[0].id!==k.id)return null;if(te.length>1){const me=Sh(te);return u.jsx("div",{"data-form-renderer":"shared-cell-stack",className:W("flex w-full min-w-0 gap-3",me==="row"?"flex-row items-stretch":"flex-col"),children:te.map(_e=>{const Pe=_e.name||_e.key||_e.id;return u.jsxs("div",{"data-field-name":Pe,"data-form-renderer":"field-wrapper",className:W("min-w-0 flex-1 flex flex-col",xo(_e)),style:dn(_e),children:[u.jsx(nn,{field:xt(_e),value:Ue[Pe],error:ce[Pe]||Ae>0?Q[Pe]:void 0,onChange:Re=>We(Pe,Re),onBlur:()=>mt(Pe),disabled:_e.type==="table"&&a==="fill"?!1:ye||!jt(Pe)||Jt||!!_e.disabled,readOnly:_e.type==="table"&&a==="fill"?!1:rr(Pe,!!_e.readOnly),isRequired:vr(Pe),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:Pe,buttonResponses:L,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:Qt,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,onAddMore:jn,hideTableRowControls:A}),_e.type==="addmore"&&Ui(_e)]},_e.id)})},te.map(_e=>_e.id).join("-"))}}if(k.type==="section"){const J=ee.fields.filter(te=>te.parentId===k.id&&te.position!=null).sort((te,me)=>{const _e=typeof te.position?.order=="number"?te.position.order:0,Pe=typeof me.position?.order=="number"?me.position.order:0;return _e-Pe});return u.jsx(Pm,{field:k,children:J.map(te=>{const me=te.name||te.key||te.id,_e=te.hidden===!0;return Pt(te)&&(on(me)||!_e&&me)?u.jsxs("div",{"data-field-name":me,"data-form-renderer":"field-wrapper",style:dn(te),children:[u.jsx(nn,{field:xt(te),value:Ue[me],error:ce[me]||Ae>0?Q[me]:void 0,onChange:Re=>We(me,Re),onBlur:()=>mt(me),disabled:ye||!jt(me)||Jt||!!te.disabled,readOnly:rr(me,!!te.readOnly),isRequired:vr(me),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:me,buttonResponses:L,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:Qt,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,onAddMore:jn,hideTableRowControls:A}),te.type==="addmore"&&Ui(te)]},te.id):null})},k.id)}const X=k.name||k.key||k.id;return u.jsxs("div",{"data-field-name":X,"data-form-renderer":"field-wrapper",style:dn(k),children:[u.jsx(nn,{field:xt(k),value:Ue[X],error:ce[X]||Ae>0?Q[X]:void 0,onChange:J=>We(X,J),onBlur:()=>mt(X),disabled:k.type==="table"&&a==="fill"?!1:ye||!jt(X)||Jt||!!k.disabled,readOnly:k.type==="table"&&a==="fill"?!1:rr(X,!!k.readOnly),isRequired:vr(X),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:X,buttonResponses:L,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:Qt,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,onAddMore:jn,hideTableRowControls:A}),k.type==="addmore"&&Ui(k)]},k.id)})})}),c]})]})})};function Jl(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function Lh(e,t){const r=e.form;if(!r)throw new Error("workflowStateToFormSchema requires workflowState.form to be set");const n=r.fields.filter(l=>l!=null&&l!==void 0).map((l,f)=>{if(!l||typeof l!="object")return null;const p={...l};if(l.fieldType&&!p.type&&(p.type=l.fieldType),l.fieldKey&&!p.key&&!p.name&&(p.key=l.fieldKey,p.name=l.fieldKey),typeof l.positionOrder=="number"&&!isNaN(l.positionOrder)?p.order=l.positionOrder:p.order=f,(typeof p.order!="number"||isNaN(p.order))&&(p.order=f),l.options&&typeof l.options=="string")try{p.options=JSON.parse(l.options)}catch{}if(l.metadata&&typeof l.metadata=="string")try{p.metadata=JSON.parse(l.metadata)}catch{}return p}).filter(l=>l!=null).sort((l,f)=>{const p=typeof l.order=="number"?l.order:0,m=typeof f.order=="number"?f.order:0;return p-m});n.forEach((l,f)=>{(!l||typeof l.order!="number"||isNaN(l.order))&&(l.order=f)});let o=r.layout;if(o){const l={...o};if(l.breakpoints&&typeof l.breakpoints=="string")try{l.breakpoints=JSON.parse(l.breakpoints)}catch{}if(l.responsiveConfig&&typeof l.responsiveConfig=="string")try{l.responsiveConfig=JSON.parse(l.responsiveConfig)}catch{}o=l}const s=n.filter(l=>l!=null&&typeof l=="object"&&typeof l.order=="number"&&!isNaN(l.order));let i={};const a=r.config;if(a!=null)if(typeof a=="string")try{i=JSON.parse(a)}catch{}else typeof a=="object"&&a!==null&&(i={...a});const d=l=>{let f={...l};if(l.conditionExpression&&typeof l.conditionExpression=="string")try{f={...l,conditionExpression:JSON.parse(l.conditionExpression)}}catch{}if(f.targetFieldId){const p=s.find(m=>m._id===f.targetFieldId||m.id===f.targetFieldId||m.fieldKey===f.targetFieldId);if(p){const m=p.key||p.fieldKey||p.name,b=p._id||p.id||f.targetFieldId;f.targetFieldKey=m,f.targetField=m,f.targetFieldById=b}}return f},c={id:r._id,name:r.name,description:r.description??"",version:r.version,status:r.status,fields:s.map((l,f)=>{const p=l,m=typeof l.metadata=="object"&&l.metadata!==null?l.metadata:{},b=m.hidden===!0||l.hidden===!0,h={id:l._id||l.id||l.fieldKey,type:l.type||l.fieldType,label:l.label,key:l.key||l.fieldKey||l.name,name:l.name||l.fieldKey||l.key};if(b&&(h.hidden=!0),h.id||(h.id=h.key||h.name),h.key||(h.key=h.id||h.name),h.name||(h.name=h.key||h.id),l.isRequired!==void 0&&(h.required=l.isRequired),l.placeholder&&(h.placeholder=l.placeholder),l.options&&Array.isArray(l.options)&&(h.options=l.options),l.apidata&&(h.apidata=l.apidata),p.appearance&&typeof p.appearance=="object"&&!Array.isArray(p.appearance)&&Object.keys(p.appearance).length>0&&(h.appearance=Jl(p.appearance)),p.ui!==void 0&&(h.ui=Jl(p.ui)),p.visibility!==void 0&&(h.visibility=Jl(p.visibility)),m.disabled!==void 0&&(h.disabled=m.disabled),m.readOnly!==void 0&&(h.readOnly=m.readOnly),m.hideLabel!==void 0&&(h.hideLabel=m.hideLabel,h.properties||(h.properties={}),h.properties.hideLabel=m.hideLabel,h.appearance||(h.appearance={}),h.appearance.hideLabel=m.hideLabel),(l.type==="file"||l.fieldType==="file"||l.type==="camera"||l.fieldType==="camera"||l.type==="photoChoice"||l.fieldType==="photoChoice")&&l.validationRules){const g=l.validationRules,w={...m};if(g.fileSize!==void 0&&(w.maxSize=g.fileSize),g.fileType&&Array.isArray(g.fileType)){const v=[];g.fileType.forEach(x=>{const A=x.startsWith(".")?x:`.${x}`;v.push(A),A===".csv"?v.push("text/csv"):A===".xls"?v.push("application/vnd.ms-excel"):A===".xlsx"&&v.push("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}),w.accept=v}h.metadata=w,w.maxSize!==void 0&&(h.maxSize=w.maxSize),w.accept!==void 0&&(h.accept=w.accept)}else if(m&&Object.keys(m).length>0){if(h.metadata=m,(l.type==="toggle"||l.fieldType==="toggle")&&(m.onValue!==void 0&&(h.onValue=m.onValue),m.offValue!==void 0&&(h.offValue=m.offValue),m.onText!==void 0&&(h.onText=m.onText),m.offText!==void 0&&(h.offText=m.offText)),(l.type==="button"||l.fieldType==="button")&&m.action==="download"&&m.downloadApiEndpoint&&typeof m.downloadApiEndpoint=="string"){let g=m.downloadApiEndpoint;g=g.replace(/\{ctx:([^}]+)\}/g,(w,v)=>{const x=t[v];return x!==void 0?String(x):w}),m.downloadApiEndpoint=g,h.metadata=m,h.downloadApiEndpoint=g}if((l.type==="button"||l.fieldType==="button")&&m.action==="submit"){const g=h.properties||{};m.submitAction!==void 0&&(g.submitAction=m.submitAction),m.submitApiMethod!==void 0&&(g.submitApiMethod=m.submitApiMethod),m.apiBodyStructure!==void 0&&(g.apiBodyStructure=m.apiBodyStructure),m.apiBodyFieldsOnly!==void 0&&(g.apiBodyFieldsOnly=m.apiBodyFieldsOnly),m.apiBodyFieldsOnlyFormat!==void 0&&(g.apiBodyFieldsOnlyFormat=m.apiBodyFieldsOnlyFormat),m.apiBodyFields!==void 0&&(g.apiBodyFields=m.apiBodyFields),m.buttonText!==void 0&&(g.buttonText=m.buttonText),m.action!==void 0&&(g.action=m.action),m.variant!==void 0&&(g.variant=m.variant),m.hideLabel!==void 0&&(g.hideLabel=m.hideLabel),l.apidata&&typeof l.apidata=="object"&&l.apidata.apiEndpoint&&(g.apiEndpoint=l.apidata.apiEndpoint),h.properties=g}if((l.type==="button"||l.fieldType==="button")&&(m.action==="upload"||m.action==="custom")){const g=h.properties||{};m.action!==void 0&&(g.action=m.action),m.buttonText!==void 0&&(g.buttonText=m.buttonText),m.variant!==void 0&&(g.variant=m.variant),m.hideLabel!==void 0&&(g.hideLabel=m.hideLabel),m.uploadAction!==void 0&&(g.uploadAction=m.uploadAction),m.uploadApiEndpoint!==void 0&&(g.uploadApiEndpoint=m.uploadApiEndpoint),m.uploadApiMethod!==void 0&&(g.uploadApiMethod=m.uploadApiMethod),m.apiBodyStructure!==void 0&&(g.apiBodyStructure=m.apiBodyStructure),m.apiBodyFieldsOnly!==void 0&&(g.apiBodyFieldsOnly=m.apiBodyFieldsOnly),m.apiBodyFieldsOnlyFormat!==void 0&&(g.apiBodyFieldsOnlyFormat=m.apiBodyFieldsOnlyFormat),m.apiFieldMapping!==void 0&&(g.apiFieldMapping=m.apiFieldMapping),m.apiQueryParams!==void 0&&(g.apiQueryParams=m.apiQueryParams),m.apiBodyFields!==void 0&&(g.apiBodyFields=m.apiBodyFields),m.apiHeaders!==void 0&&(g.apiHeaders=m.apiHeaders),h.properties=g}if(l.type==="status"||l.fieldType==="status"){const g=h.properties||{};if(m.source!==void 0&&(g.source=m.source),m.statuses!==void 0&&(g.statuses=m.statuses),m.dataPath!==void 0&&(g.dataPath=m.dataPath),m.showStatusText!==void 0&&(g.showStatusText=m.showStatusText),m.statusTextPath!==void 0&&(g.statusTextPath=m.statusTextPath),m.showCurrentIndicator!==void 0&&(g.showCurrentIndicator=m.showCurrentIndicator),l.apidata&&typeof l.apidata=="object"&&l.apidata.apiEndpoint){let w=l.apidata.apiEndpoint;w=w.replace(/\{ctx:([^}]+)\}/g,(v,x)=>{const A=t[x];return A!==void 0?String(A):v}),g.apiEndpoint=w,g.source===void 0&&(g.source="api")}l.apidata?.apiMethod!==void 0&&(g.apiMethod=l.apidata.apiMethod),h.properties=g}if(l.type==="addmore"||l.fieldType==="addmore"){const g=h.properties||{};m.linkedFieldNames!==void 0&&(g.linkedFieldNames=m.linkedFieldNames),m.linkedSectionIds!==void 0&&(g.linkedSectionIds=m.linkedSectionIds),m.linkedFieldAllowDuplicate!==void 0&&(g.linkedFieldAllowDuplicate=m.linkedFieldAllowDuplicate),m.buttonText!==void 0&&(g.buttonText=m.buttonText),m.variant!==void 0&&(g.variant=m.variant),m.size!==void 0&&(g.size=m.size),m.hideLabel!==void 0&&(g.hideLabel=m.hideLabel),h.properties=g}if(l.type==="selectablelist"||l.fieldType==="selectablelist"){const g=h.properties||{};m.submitFieldMapping!==void 0&&(g.submitFieldMapping=m.submitFieldMapping),m.displayFields!==void 0&&(g.displayFields=m.displayFields),m.displayFieldsSeparator!==void 0&&(g.displayFieldsSeparator=m.displayFieldsSeparator),m.dataSourceContextKey!==void 0&&(g.dataSourceContextKey=m.dataSourceContextKey),m.showSelectAll!==void 0&&(g.showSelectAll=m.showSelectAll),m.selectAllByDefault!==void 0&&(g.selectAllByDefault=m.selectAllByDefault),h.properties=g}}return l.validationRules&&l.type!=="file"&&l.fieldType!=="file"&&l.type!=="camera"&&l.fieldType!=="camera"&&l.type!=="photoChoice"&&l.fieldType!=="photoChoice"&&l.type!=="status"&&l.fieldType!=="status"&&(h.validationRules=l.validationRules),typeof l.order=="number"&&(h.order=l.order),h.position=wi(l,f),l.conditions&&Array.isArray(l.conditions)&&(h.conditions=l.conditions),h}).filter(l=>l!=null).sort((l,f)=>{const p=typeof l.order=="number"?l.order:0,m=typeof f.order=="number"?f.order:0;return p-m}),config:{...i,layout:o,...r.rules&&r.rules.length>0&&{rules:r.rules.map(d)},...r.clientMapping&&Object.keys(r.clientMapping).length>0&&{clientMapping:r.clientMapping}},...r.rules&&r.rules.length>0&&{rules:r.rules.map(d)},createdAt:"",updatedAt:"",moduleId:""};return xi(c)}var Ti="Tabs",[h_]=mr(Ti,[ai]),Dh=ai(),[g_,Ql]=h_(Ti),Bh=y.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,onValueChange:o,defaultValue:s,orientation:i="horizontal",dir:a,activationMode:d="automatic",...c}=e,l=Wn(a),[f,p]=Wr({prop:n,onChange:o,defaultProp:s??"",caller:Ti});return u.jsx(g_,{scope:r,baseId:Zr(),value:f,onValueChange:p,orientation:i,dir:l,activationMode:d,children:u.jsx(Ve.div,{dir:l,"data-orientation":i,...c,ref:t})})});Bh.displayName=Ti;var $h="TabsList",jh=y.forwardRef((e,t)=>{const{__scopeTabs:r,loop:n=!0,...o}=e,s=Ql($h,r),i=Dh(r);return u.jsx(Dp,{asChild:!0,...i,orientation:s.orientation,dir:s.dir,loop:n,children:u.jsx(Ve.div,{role:"tablist","aria-orientation":s.orientation,...o,ref:t})})});jh.displayName=$h;var Uh="TabsTrigger",Rh=y.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,disabled:o=!1,...s}=e,i=Ql(Uh,r),a=Dh(r),d=Hh(i.baseId,n),c=Wh(i.baseId,n),l=n===i.value;return u.jsx(Bp,{asChild:!0,...a,focusable:!o,active:l,children:u.jsx(Ve.button,{type:"button",role:"tab","aria-selected":l,"aria-controls":c,"data-state":l?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:d,...s,ref:t,onMouseDown:Be(e.onMouseDown,f=>{!o&&f.button===0&&f.ctrlKey===!1?i.onValueChange(n):f.preventDefault()}),onKeyDown:Be(e.onKeyDown,f=>{[" ","Enter"].includes(f.key)&&i.onValueChange(n)}),onFocus:Be(e.onFocus,()=>{const f=i.activationMode!=="manual";!l&&!o&&f&&i.onValueChange(n)})})})});Rh.displayName=Uh;var zh="TabsContent",Vh=y.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,forceMount:o,children:s,...i}=e,a=Ql(zh,r),d=Hh(a.baseId,n),c=Wh(a.baseId,n),l=n===a.value,f=y.useRef(l);return y.useEffect(()=>{const p=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(p)},[]),u.jsx(br,{present:o||l,children:({present:p})=>u.jsx(Ve.div,{"data-state":l?"active":"inactive","data-orientation":a.orientation,role:"tabpanel","aria-labelledby":d,hidden:!p,id:c,tabIndex:0,...i,ref:t,style:{...e.style,animationDuration:f.current?"0s":void 0},children:p&&s})})});Vh.displayName=zh;function Hh(e,t){return`${e}-trigger-${t}`}function Wh(e,t){return`${e}-content-${t}`}var y_=Bh,b_=jh,v_=Rh,w_=Vh;function S_({className:e,...t}){return u.jsx(y_,{"data-slot":"tabs",className:W("flex flex-col gap-2",e),...t})}function x_({className:e,...t}){return u.jsx(b_,{"data-slot":"tabs-list",className:W("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",e),...t})}function A_({className:e,...t}){return u.jsx(v_,{"data-slot":"tabs-trigger",className:W("data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function C_({className:e,...t}){return u.jsx(w_,{"data-slot":"tabs-content",className:W("flex-1 outline-none",e),...t})}function ir({className:e="",...t}){return u.jsx("div",{"data-slot":"skeleton","data-form-renderer":"skeleton",className:`animate-pulse rounded-md bg-neutral-200 dark:bg-neutral-700 ${e}`.trim(),...t})}function E_({className:e=""}){return u.jsxs("div",{className:`flex flex-col gap-4 ${e}`.trim(),"data-form-renderer":"workflow-steps-view-skeleton",children:[u.jsxs("div",{className:"flex w-full border-b border-neutral-200 dark:border-neutral-700 gap-0",children:[u.jsx(ir,{className:"h-10 w-24 rounded-none"}),u.jsx(ir,{className:"h-10 w-28 rounded-none ml-1"}),u.jsx(ir,{className:"h-10 w-20 rounded-none ml-1"})]}),u.jsxs("div",{className:"mt-4 flex flex-col gap-4 py-4",children:[u.jsx(ir,{className:"h-4 w-32"}),u.jsx(ir,{className:"h-10 w-full"}),u.jsx(ir,{className:"h-4 w-40"}),u.jsx(ir,{className:"h-10 w-full"}),u.jsx(ir,{className:"h-4 w-36"}),u.jsx(ir,{className:"h-24 w-full"})]})]})}function T_(){return u.jsxs("div",{className:"flex flex-col gap-4 py-4","data-form-renderer":"form-loading-skeleton",children:[u.jsx(ir,{className:"h-4 w-28"}),u.jsx(ir,{className:"h-10 w-full"}),u.jsx(ir,{className:"h-4 w-36"}),u.jsx(ir,{className:"h-10 w-full"}),u.jsx(ir,{className:"h-4 w-24"}),u.jsx(ir,{className:"h-20 w-full"})]})}const __=3e4,N_=10*6e4,k_=9e4,F_=15*6e4;function O_(e){return e!=null&&"on_success"in e&&e.on_success!=null}function P_(e,t){if(!t||typeof t!="object")return e;let r=e;return Object.entries(t).forEach(([n,o])=>{o!=null&&o!==""&&(r=r.replace(new RegExp(`\\{${n}\\}`,"g"),String(o)))}),r}const I_=({getWorkflowState:e,moduleId:t,tenantId:r,submissionContext:n,initialValues:o={},getAuthHeaders:s,onSuccess:i,bootstrapFeatureId:a,subjectUserId:d,viewStepId:c,clientId:l,className:f,onWorkflowSubmitResult:p,viewerContext:m,getViewerContext:b,dark:h=!1,themeVars:g})=>{const w=Vi.useQueryClient(),v=S.useMemo(()=>[d??"",c??"",l??""],[d,c,l]),x=S.useMemo(()=>({moduleId:t,tenantId:r,subjectUserId:d,viewStepId:c,clientId:l}),[t,r,d,c,l]),[A,I]=S.useState([]),[T,C]=S.useState(null),[_,E]=S.useState(null),[O,N]=S.useState(null),[j,R]=S.useState({}),M=S.useRef(null),B=S.useRef(null),P=S.useRef(null),H=S.useRef(null),D=S.useMemo(()=>A&&Array.isArray(A)?A.filter(ae=>ae.feature_id):[],[A]),K=Vi.useQuery({queryKey:["workflow-steps",t,a??"",r??"",v[0],v[1],v[2]],queryFn:()=>e({...x,featureId:a}),staleTime:__,gcTime:N_}),q=K.isPending,L=K.error?K.error instanceof Error?K.error.message:"Failed to load workflow steps":null;S.useEffect(()=>{const ae=K.data;if(!ae||A.length>0)return;const ye=ae.steps&&Array.isArray(ae.steps)?ae.steps:[];I(ye);const je=ye.filter(st=>st.feature_id);if(je.length>0){const st=ae.current_step_id,we=st&&je.some(ct=>ct.step_id===st);C(we?st:je[0].step_id)}},[K.data,A.length,a]);const z=S.useMemo(()=>{if(!T)return;const ae=A.find(je=>je.step_id===T),ye=M.current===T;return ae?.feature_id??(ye?H.current:void 0)??void 0},[T,A]),V=Vi.useQuery({queryKey:["workflow-step",t,z??"",r??"",v[0],v[1],v[2]],queryFn:()=>e({...x,featureId:z}),enabled:!!z,staleTime:k_,gcTime:F_,refetchOnWindowFocus:!0,refetchOnReconnect:!0}),le=V.isPending,re=V.error?V.error instanceof Error?V.error.message:"Failed to load form":null;S.useEffect(()=>{!V.data||M.current===T||(E(V.data),N(null),M.current=null,H.current=null)},[V.data,T]),S.useEffect(()=>{N(re)},[re]),S.useEffect(()=>{z===void 0&&M.current!==T&&(E(null),N(null),M.current=null,H.current=null)},[z,T]);const ne=S.useMemo(()=>{const ae=_?.form;if(!ae)return null;const ye=(r??Fn()??"").trim()||"default",je=Oh({scope:ye,formId:ae._id,version:ae.version});return je?.value?je.value:Lh(_,n)},[_,n,r]),Z=S.useMemo(()=>{const ae=_?.BFF_submit_api;if(!ae?.url)return;let ye=ae.url;if(ye.startsWith("http://")||ye.startsWith("https://"))try{const we=new URL(ye);ye=we.pathname+we.search}catch{}const je=s?.()??{},st={...ae.headers||{},"Content-Type":"application/json",...je};return{...ae,url:ye,headers:st}},[_?.BFF_submit_api,s]),Y=S.useMemo(()=>ne?{...ne,status:"published",...Z&&{BFF_submit_api:Z}}:null,[ne,Z]);S.useEffect(()=>{if(!ne?.id)return;const ae=(r??Fn()??"").trim()||"default";Ph({scope:ae,formId:ne.id,version:ne.version},ne)},[ne,r]);const oe=S.useMemo(()=>{if(!ne)return null;const ae=Wi({config:ne.config,layout:ne.layout},null);if(!ae)return null;const ye=ae.rows,je=ae.columns,st={verticalSpacing:ae.verticalSpacing??ae.spacing??"16px",horizontalSpacing:ae.horizontalSpacing??ae.spacing??"16px",rowHeight:ae.rowHeight??zn};let we=1;if(Array.isArray(ne.fields))for(const Le of ne.fields){const ee=Le?.position,Ye=typeof ee?.order=="number"?ee.order:0,et=typeof ee?.rowSpan=="number"?ee.rowSpan:1;we=Math.max(we,Ye+et)}return{rows:Math.min(ye,Math.max(1,we)),columns:je,verticalSpacing:st.verticalSpacing,horizontalSpacing:st.horizontalSpacing,rowHeight:st.rowHeight}},[ne]),ie=S.useMemo(()=>{const ye=Y?.config?.theme?.cssVariables;if(!(!ye&&!g))return{...ye??{},...g??{}}},[Y?.config,g]),G=S.useCallback(()=>{w.invalidateQueries({queryKey:["workflow-steps",t]}),w.invalidateQueries({queryKey:["workflow-step",t]})},[w,t]),ve=S.useCallback(ae=>{if(O_(ae)){const we=ae.on_success,ct=we?.action;if(ct==="redirect"&&we?.redirect_url){const Le=P_(we.redirect_url.trim(),n);window.location.href=Le;return}if(ct==="move"){const Le=we?.next_step_id,ee=we?.next_step_form;if(Le&&ee){M.current=null,H.current=null;const Ye=ee.featureId??we?.next_step_form_id??ee._id;w.removeQueries({queryKey:["workflow-step",t,Ye,r??"",v[0],v[1],v[2]]}),G(),I(et=>et.some(Q=>Q.step_id===Le)?et:[...et,{step_id:Le,step_name:ee.name||"Next step",feature_id:Ye}]),E(null),C(Le),i?.();return}return}if(ct==="stay"){G(),i?.();return}}const ye=ae;ye.steps&&Array.isArray(ye.steps)&&I(ye.steps);const je=(ye.steps&&Array.isArray(ye.steps)?ye.steps:A).filter(we=>we.feature_id),st=ye.current_step_id;st&&je.some(we=>we.step_id===st)?C(st):je.length>0&&C(je[0].step_id),E(null),G(),i?.(),p?.(ye)},[w,t,r,i,p,A,n,v,G]),be=S.useCallback(async ae=>_?.BFF_submit_api?(i?.(),{success:!0,message:"Saved successfully"}):{success:!1,message:"Submit not configured"},[_?.BFF_submit_api,i]),He=S.useCallback((ae,ye)=>{},[]),he=S.useCallback(ae=>{},[]);if(q)return u.jsx(E_,{className:f});if(L)return u.jsx("div",{className:W("rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive",f),children:L});if(D.length===0)return u.jsx("div",{className:W("py-12 text-center text-sm text-muted-foreground",f),children:"No workflow steps configured."});const Ee=_?.step_blocked_message;return u.jsx("div",{className:W(Hi,h&&"dark","flex flex-col gap-4",f),style:ie,"data-form-renderer":"workflow-steps-view",children:u.jsxs(S_,{value:T??"",onValueChange:ae=>C(ae),children:[u.jsx(x_,{className:"w-full justify-start border-b rounded-none h-auto p-0 bg-transparent gap-0","data-form-renderer":"workflow-tabs",children:D.map(ae=>u.jsx(A_,{value:ae.step_id,className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:shadow-none","data-form-renderer":"workflow-tab",children:ae.step_name},ae.step_id))}),D.map(ae=>u.jsx(C_,{value:ae.step_id,className:"mt-4 outline-none",children:ae.step_id!==T?null:le?u.jsx(T_,{}):O?u.jsx("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:O}):Ee&&!_?.form?u.jsx("div",{className:W("rounded-lg border border-amber-500/50 bg-amber-500/10 px-4 py-3 text-sm text-amber-800 dark:text-amber-200",f),"data-form-renderer":"workflow-step-blocked",children:Ee}):Y?.fields?.length?u.jsxs("div",{className:"py-4 [&_*]:box-border",children:[Ee?u.jsx("div",{className:W("mb-4 rounded-lg border border-amber-500/50 bg-amber-500/10 px-4 py-3 text-sm text-amber-800 dark:text-amber-200"),"data-form-renderer":"workflow-step-blocked",children:Ee}):null,(()=>{const ye=B.current!==T||P.current!==(Y?.id??null);if(T&&Y&&ye){B.current=T,P.current=Y.id??null;const je=qt.getState();je.setSchema(Y,{forceReset:!0});const st=qt.getState().values;je.setValues({...st,...o})}return null})(),u.jsx(Mh,{schema:Y,gridLayout:oe,omitRootWrapper:!0,submissionContext:n,initialValues:o,workflowStepId:T??void 0,viewerContext:m,getViewerContext:b,onSubmit:be,onChange:He,onValidationError:he,onClose:()=>{},mode:"fill",unstyled:!0,onWorkflowSubmitResult:ve,initialExtraSubmitPayload:Object.keys(j).length>0?j:void 0,onExtraSubmitPayloadChange:ye=>{if(ye&&typeof ye=="object"){const je={};ye.context_user_id!=null&&(je.context_user_id=ye.context_user_id),ye.id!=null&&(je.id=ye.id),ye.batch_id!=null&&(je.batch_id=ye.batch_id),ye.admission_batch_id!=null&&(je.admission_batch_id=ye.admission_batch_id),ye.program_id!=null&&(je.program_id=ye.program_id),Object.keys(je).length>0&&R(st=>({...st,...je}))}}},Y.id)]}):u.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No form schema available for this step."})},ae.step_id))]})})};function M_(e){return typeof e=="object"&&e!==null&&"apiEndpoint"in e}function L_({formSchema:e}){const t=S.useMemo(()=>{if(!e)return[];const s=[];(!e.name||e.name.trim()==="")&&s.push({id:"form-name-required",type:"error",message:"Form name is required"});const i=new Set,a=new Set;e.fields.forEach((l,f)=>{const p=`field-${l.id}`;if(a.has(l.id)&&s.push({id:`${p}-duplicate-id`,type:"error",message:`Field "${l.label||l.name||`Field ${f+1}`}" has a duplicate ID`,fieldId:l.id}),a.add(l.id),l.name&&i.has(l.name)&&s.push({id:`${p}-duplicate-name`,type:"error",message:`Field "${l.label||l.name}" has a duplicate name: "${l.name}"`,fieldId:l.id}),l.name&&i.add(l.name),(!l.label||l.label.trim()==="")&&s.push({id:`${p}-missing-label`,type:"warning",message:`Field "${l.name||l.id}" is missing a label`,fieldId:l.id}),(!l.name||l.name.trim()==="")&&s.push({id:`${p}-missing-name`,type:"error",message:`Field "${l.label||l.id}" is missing a field name`,fieldId:l.id}),l.name&&!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(l.name)&&s.push({id:`${p}-invalid-name`,type:"error",message:`Field "${l.label||l.name}" has an invalid name. Use only letters, numbers, and underscores.`,fieldId:l.id}),["select","multiselect","radio","checkboxgroup"].includes(l.type)){const h=l.properties;(!h?.options||h.options.length===0)&&s.push({id:`${p}-no-options`,type:"warning",message:`Field "${l.label||l.name}" has no options defined`,fieldId:l.id})}l.parentId&&(e.fields.some(g=>g.id===l.parentId)||s.push({id:`${p}-orphaned`,type:"error",message:`Field "${l.label||l.name}" references a non-existent parent`,fieldId:l.id}));const b=(h,g)=>{if(g.has(h))return!0;g.add(h);const w=e.fields.find(v=>v.id===h);return w?.parentId?b(w.parentId,g):!1};l.parentId&&b(l.id,new Set)&&s.push({id:`${p}-circular-reference`,type:"error",message:`Field "${l.label||l.name}" has a circular parent reference`,fieldId:l.id})}),e.config.workflowTrigger?.workflowId&&(e.fields.some(f=>f.validation?.some(p=>p.type==="required"))||s.push({id:"workflow-no-required-fields",type:"info",message:"Form linked to workflow but has no required fields"}));const d=e.fields.filter(l=>!l.parentId),c=new Map;return d.forEach(l=>{const f=l.position.order;c.has(f)||c.set(f,[]),c.get(f).push(l)}),c.forEach((l,f)=>{l.length>3&&s.push({id:`row-${f}-too-many-fields`,type:"warning",message:`Row ${f+1} has ${l.length} fields (maximum recommended is 3)`})}),s},[e]),r=S.useMemo(()=>t.filter(s=>s.type==="error"),[t]),n=S.useMemo(()=>t.filter(s=>s.type==="warning"),[t]),o=S.useMemo(()=>r.length===0,[r]);return{issues:t,errors:r,warnings:n,isValid:o}}function D_({field:e,value:t,allValues:r,validateOnChange:n=!1,validateOnBlur:o=!0,debounceMs:s=ST}){const[i,a]=S.useState(),[d,c]=S.useState(!1),l=S.useRef(void 0),f=S.useRef(t),p=S.useCallback(async()=>{if(!e.validation||e.validation.length===0){a(void 0);return}c(!0);let w;for(const v of e.validation){const x=Rr(t,v,r);if(typeof x=="string"){w=x;break}}return a(w),c(!1),w},[e.validation,t,r]),m=S.useCallback(()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{p()},s)},[p,s]);S.useEffect(()=>(n&&f.current!==t&&m(),f.current=t,()=>{l.current&&clearTimeout(l.current)}),[t,n,m]);const b=S.useCallback(()=>{o&&p()},[o,p]),h=S.useCallback(()=>{a(void 0)},[]),g=S.useCallback(w=>{a(w)},[]);return{error:i,isValidating:d,validate:p,handleBlur:b,clearError:h,setCustomError:g}}const B_={text:{type:"text",label:"Text Input",icon:"Type",category:"input",description:"Single line text input",defaultProps:{label:"Text Field",name:"text_field",placeholder:"Enter text..."}},number:{type:"number",label:"Number Input",icon:"Hash",category:"input",description:"Numeric input with optional constraints",defaultProps:{label:"Number Field",name:"number_field",placeholder:"0",properties:{min:0,step:1}}},email:{type:"email",label:"Email",icon:"Mail",category:"input",description:"Email address input with validation",defaultProps:{label:"Email",name:"email_field",placeholder:"example@domain.com",validation:[{type:"email"}]}},phone:{type:"phone",label:"Phone",icon:"Phone",category:"input",description:"Phone number input",defaultProps:{label:"Phone Number",name:"phone_field",placeholder:"+91 12345 67890"}},password:{type:"password",label:"Password",icon:"Lock",category:"input",description:"Secure password input",defaultProps:{label:"Password",name:"password_field",placeholder:"••••••••"}},url:{type:"url",label:"URL",icon:"Link",category:"input",description:"URL input with validation",defaultProps:{label:"URL",name:"url_field",placeholder:"https://example.com",validation:[{type:"url"}]}},date:{type:"date",label:"Date",icon:"Calendar",category:"datetime",description:"Date picker",defaultProps:{label:"Date",name:"date_field",placeholder:"Select date"}},time:{type:"time",label:"Time",icon:"Clock",category:"datetime",description:"Time picker",defaultProps:{label:"Time",name:"time_field",placeholder:"Select time"}},datetime:{type:"datetime",label:"Date & Time",icon:"CalendarClock",category:"datetime",description:"Combined date and time picker",defaultProps:{label:"Date & Time",name:"datetime_field",placeholder:"Select date and time"}},daterange:{type:"daterange",label:"Date Range",icon:"CalendarRange",category:"datetime",description:"Select a range of dates",defaultProps:{label:"Date Range",name:"daterange_field",placeholder:"Select date range"}},select:{type:"select",label:"Dropdown",icon:"ChevronDown",category:"selection",description:"Single selection dropdown",defaultProps:{label:"Select",name:"select_field",placeholder:"Select an option",properties:{options:[{label:"Option 1",value:"option1"},{label:"Option 2",value:"option2"},{label:"Option 3",value:"option3"}],searchable:!0,clearable:!0}}},multiselect:{type:"multiselect",label:"Multi Select",icon:"ListChecks",category:"selection",description:"Multiple selection dropdown",defaultProps:{label:"Multi Select",name:"multiselect_field",placeholder:"Select options",properties:{options:[{label:"Option 1",value:"option1"},{label:"Option 2",value:"option2"},{label:"Option 3",value:"option3"}],searchable:!0}}},radio:{type:"radio",label:"Radio Group",icon:"CircleDot",category:"selection",description:"Single selection radio buttons",defaultProps:{label:"Radio Group",name:"radio_field",properties:{options:[{label:"Option 1",value:"option1"},{label:"Option 2",value:"option2"},{label:"Option 3",value:"option3"}]}}},checkbox:{type:"checkbox",label:"Checkbox",icon:"CheckSquare",category:"selection",description:"Single checkbox for boolean values",defaultProps:{label:"I agree to the terms",name:"checkbox_field"}},toggle:{type:"toggle",label:"Toggle",icon:"ToggleLeft",category:"selection",description:"Toggle switch with configurable text values",defaultProps:{label:"Toggle",name:"toggle_field",description:"Toggle to switch between states",properties:{onValue:"On",offValue:"Off"}}},checkboxgroup:{type:"checkboxgroup",label:"Checkbox Group",icon:"CheckSquare",category:"selection",description:"Multiple checkboxes for selecting multiple values",defaultProps:{label:"Checkbox Group",name:"checkboxgroup_field",properties:{options:[{label:"Option 1",value:"option1"},{label:"Option 2",value:"option2"},{label:"Option 3",value:"option3"}]}}},selectablelist:{type:"selectablelist",label:"Selectable List",icon:"ListChecks",category:"selection",description:"List from response or context; select all or specific items. Value = selected array.",defaultProps:{label:"Recipients",name:"recipients",properties:{dataSourceContextKey:"recipients",labelField:"name",valueField:"email",showSelectAll:!0,selectAllByDefault:!0}}},asyncsearch:{type:"asyncsearch",label:"Async Search",icon:"Search",category:"selection",description:"Typeahead search against an API; submitted value is the selected option value.",defaultProps:{label:"Search",name:"async_search",placeholder:"Type to search…",properties:{apiEndpoint:"/api/form-builder/search",apiMethod:"GET",searchQueryParam:"q",searchSchedule:"debounce",intervalMs:300,minQueryLength:0,clearable:!0}}},terms:{type:"terms",label:"Terms & Conditions",icon:"FileText",category:"special",description:"Terms and conditions confirmation checkbox",defaultProps:{label:"I confirm that the details are true to my knowledge",name:"terms_conditions",validation:[{type:"required"}]}},textarea:{type:"textarea",label:"Text Area",icon:"AlignLeft",category:"rich",description:"Multi-line text input",defaultProps:{label:"Text Area",name:"textarea_field",placeholder:"Enter your text here...",properties:{minLength:0,maxLength:1e3}}},richtext:{type:"richtext",label:"Rich Text",icon:"FileText",category:"rich",description:"Rich text editor with formatting",defaultProps:{label:"Rich Text",name:"richtext_field"}},file:{type:"file",label:"File Upload",icon:"Upload",category:"rich",description:"File upload with drag and drop",defaultProps:{label:"File Upload",name:"file_field",properties:{accept:["image/*","application/pdf"],maxSize:5*1024*1024}}},camera:{type:"camera",label:"Use camera",icon:"Camera",category:"rich",description:"Take a photo with your camera",defaultProps:{label:"Take photo",name:"camera_field",properties:{accept:["image/*"],maxSize:5*1024*1024,multiple:!1}}},photoChoice:{type:"photoChoice",label:"Photo (upload or camera)",icon:"ImagePlus",category:"rich",description:"Upload a file or capture with the camera",defaultProps:{label:"Photo",name:"photo_choice_field",properties:{accept:["image/*"],maxSize:5*1024*1024,maxFiles:1}}},signature:{type:"signature",label:"Signature",icon:"Pencil",category:"rich",description:"Digital signature capture",defaultProps:{label:"Signature",name:"signature_field"}},rating:{type:"rating",label:"Rating",icon:"Star",category:"rich",description:"Star rating input",defaultProps:{label:"Rating",name:"rating_field",properties:{max:5,allowHalf:!1,icon:"star"}}},slider:{type:"slider",label:"Slider",icon:"SlidersHorizontal",category:"rich",description:"Numeric slider input",defaultProps:{label:"Slider",name:"slider_field",properties:{min:0,max:100,step:1,showValue:!0}}},table:{type:"table",label:"Table",icon:"Table",category:"special",description:"Repeatable table rows",defaultProps:{label:"Table",name:"table_field",properties:{columns:[],minRows:1,maxRows:10,allowAddRow:!0,allowDeleteRow:!0}}},aadhaar:{type:"aadhaar",label:"Aadhaar",icon:"CreditCard",category:"special",description:"Indian Aadhaar number input",defaultProps:{label:"Aadhaar Number",name:"aadhaar_field",placeholder:"XXXX XXXX XXXX"}},section:{type:"section",label:"Section",icon:"LayoutPanelTop",category:"container",description:"Group fields in a collapsible section",defaultProps:{label:"Section",name:"section",properties:{collapsible:!0,defaultCollapsed:!1,columns:1}}},group:{type:"group",label:"Group",icon:"Group",category:"container",description:"Group fields without visual separator",defaultProps:{label:"Group",name:"group"}},columns:{type:"columns",label:"Columns",icon:"Columns",category:"container",description:"Multi-column layout",defaultProps:{label:"Columns",name:"columns",properties:{columns:2}}},divider:{type:"divider",label:"Divider",icon:"Minus",category:"visual",description:"Horizontal line separator",defaultProps:{label:"",name:"divider"}},header:{type:"header",label:"Header",icon:"Heading",category:"visual",description:"Section header text (full row, configurable size)",defaultProps:{label:"Header",name:"header",properties:{headingLevel:"h3",showHorizontalLine:!0}}},sectionHeading:{type:"sectionHeading",label:"Section Heading",icon:"Heading",category:"visual",description:"Heading inside a grid box with configurable position and size",defaultProps:{label:"Section Heading",name:"section_heading",properties:{position:"top-left",headingLevel:"h3",showHorizontalLine:!0}}},spacer:{type:"spacer",label:"Spacer",icon:"Space",category:"visual",description:"Empty space for padding",defaultProps:{label:"",name:"spacer"}},textLabel:{type:"textLabel",label:"Text Label",icon:"Tag",category:"visual",description:"Standalone label text (no input)",defaultProps:{label:"Label",name:"text_label"}},status:{type:"status",label:"Status",icon:"ListChecks",category:"visual",description:"Populate status from Status API; label + response key; true = completed",defaultProps:{label:"Admission Status",name:"status_field",properties:{source:"api",statuses:[{label:"Registered",key:"registered"},{label:"Form Submitted",key:"formSubmitted"},{label:"Documents Verification",key:"documentsVerification"},{label:"Photos Clicked",key:"photosClicked"},{label:"Fitness Verification",key:"fitnessVerification"},{label:"Payment Completed",key:"paymentCompleted"},{label:"Hostel Allotted",key:"hostelAllotted"},{label:"Admission Completed",key:"admissionCompleted"}],showStatusText:!1,statusTextPath:"admissionStatus",showCurrentIndicator:!0}}},button:{type:"button",label:"Button",icon:"MousePointerClick",category:"special",description:"Clickable button element",defaultProps:{label:"Button",name:"button_field",properties:{variant:"default",size:"default",action:"download"}}},editButton:{type:"editButton",label:"Edit Button",icon:"Pencil",category:"special",description:"Toggle edit mode: enable/disable or show/hide other fields and buttons (no API call)",defaultProps:{label:"Edit",name:"edit_button",properties:{buttonText:"Edit",variant:"outline",size:"default",hideLabel:!1,rules:[]}}},addmore:{type:"addmore",label:"Add More",icon:"Plus",category:"special",description:"Duplicate linked fields as a new runtime block",defaultProps:{label:"Add More",name:"addmore_field",properties:{linkedFieldNames:[],linkedSectionIds:[],variant:"outline",size:"default"}}}};ge.FIELD_TYPE_REGISTRY=B_,ge.FORM_RENDERER_GRID_ROW_HEIGHT_DEFAULT=zn,ge.FORM_RENDERER_ROOT_CLASS=Hi,ge.FieldRenderer=nn,ge.FormRenderer=Mh,ge.RendererFieldLayoutContext=ra,ge.WorkflowStepsView=I_,ge.appearanceControlClasses=wo,ge.appearanceHasExplicitVerticalIntent=$c,ge.appearanceTextareaClasses=kc,ge.backendToFormSchema=vi,ge.buildWorkflowStateUrlFromBffSubmit=bh,ge.cellAlignmentClasses=Jg,ge.cellVerticalJustifyClassesForField=Xg,ge.effectiveWidthPercent=ss,ge.enrichFormSchemaFieldsFromWorkflowApi=uh,ge.extractBffSubmitApiBlock=Xo,ge.extractRawWorkflowFieldsFromSchema=Hl,ge.fetchWorkflowFormFieldsFromBffSubmitApi=wh,ge.fieldBlockBoxStyle=Yg,ge.fieldBlockBoxStyleForField=Dc,ge.fieldBlockHorizontalPlacementClass=Pc,ge.fieldBlockHorizontalSelfClass=Ic,ge.fieldBlockHorizontalSelfClassForField=Bc,ge.fieldBlockWidthStyle=Xi,ge.fieldBlockWidthStyleForField=Lc,ge.fieldGridShellFillsCellVertically=as,ge.fieldHasAuthoritativeWorkflowPosition=Si,ge.formBuilderHttp=Pn,ge.getBusinessApiOrigin=kf,ge.getClientId=Fn,ge.getRendererHostAuthHeaders=Kf,ge.getRendererHostViewerContext=kx,ge.getRendererStore=uy,ge.getWorkflowBffOrigin=mh,ge.gridCellFlexClasses=Oc,ge.gridCellFlexClassesForField=ta,ge.gridCellOuterFlexClasses=Fc,ge.hasExplicitFieldBlockWidth=Mc,ge.isAsyncSearchFieldProperties=M_,ge.isIntrinsicWidthButtonField=Vn,ge.mergeWorkflowFieldPosition=wi,ge.normalizeWorkflowFormSchema=PT,ge.normalizeWorkflowFormToRendererSchema=xi,ge.parseContentVerticalAlign=Qi,ge.parseMetadataJson=Vl,ge.parseModuleIdFromBffSubmitUrl=LT,ge.registerWorkflowFormFieldsForEnrich=MT,ge.resetRendererHostAuth=Nx,ge.resolveBusinessApiUrl=Gr,ge.resolveFormGridLayout=Wi,ge.resolveWorkflowBffUrl=Wl,ge.resolvedGridCellVerticalJustifyClasses=xo,ge.resolvedHorizontalAlign=Er,ge.resolvedVerticalAlign=So,ge.resolvedVerticalAlignForField=ea,ge.schemaNeedsWorkflowPositionEnrich=fh,ge.setBusinessApiOrigin=J0,ge.setFormBuilderAuthProvider=Fx,ge.setRendererHostAuthHeaders=_x,ge.setRendererHostViewerContext=Tx,ge.setWorkflowBffOrigin=IT,ge.useFieldValidation=D_,ge.useFormRenderer=Wc,ge.useFormValidation=L_,ge.useRendererFieldLayout=Ao,ge.useRendererHostAuthStore=On,ge.workflowStateToFormSchema=Lh,Object.defineProperty(ge,Symbol.toStringTag,{value:"Module"})}));
|
|
52
|
+
`+Pt),Ee&&uo([B,P,H],Ut=>{Pt=po(Pt,Ut," ")}),T&&Le?T.createHTML(Pt):Pt},t.setConfig=function(){let Oe=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Sr(Oe),je=!0},t.clearConfig=function(){wr=null,je=!1},t.isValidAttribute=function(Oe,F,se){wr||Sr({});const pe=wt(Oe),it=wt(F);return Pr(pe,it,se)},t.addHook=function(Oe,F){typeof F=="function"&&fo(M[Oe],F)},t.removeHook=function(Oe,F){if(F!==void 0){const se=kE(M[Oe],F);return se===-1?void 0:FE(M[Oe],se,1)[0]}return jm(M[Oe])},t.removeHooks=function(Oe){M[Oe]=[]},t.removeAllHooks=function(){M=Ym()},t}var JE=Xm();const QE=["a","b","br","div","em","h1","h2","h3","h4","h5","h6","i","img","li","ol","p","span","strong","table","tbody","td","th","thead","tr","u","ul"],ZE=["href","target","rel","src","alt","title","class","style","colspan","rowspan"];function eT(e){return e?JE.sanitize(e,{ALLOWED_TAGS:[...QE],ALLOWED_ATTR:[...ZE],ALLOW_DATA_ATTR:!1}):""}function tT(e,t,r=!1){return e.includes("{labelapi:")?e.replace(/\{labelapi:([^}]+)\}/g,(n,o)=>{const s=o.trim();if(s===""||t==null)return r?"":n;const i=pt(t,s);return i==null?r?"":n:String(i)}):e}function rT(e){return e&&e.replace(/\{api:[^}]*\}/gi,"").replace(/\{labelapi:[^}]*\}/gi,"").replace(/\{resp:[^}]*\}/gi,"").replace(/\{(?:ctx:|@)\w+\}/gi,"").replace(/\{documentId\}/gi,"").replace(/\{(\w+)\}/g,"")}const Jm={sm:"text-sm",md:"text-base",lg:"text-lg"},Qm={h1:"text-4xl font-bold tracking-tight",h2:"text-3xl font-semibold tracking-tight",h3:"text-2xl font-semibold",h4:"text-xl font-semibold",h5:"text-lg font-medium",h6:"text-base font-medium"},Zm={normal:"font-normal",medium:"font-medium",bold:"font-bold"},bi={left:"text-left",center:"text-center",right:"text-right",justify:"text-justify"};function Dn(e){return e.properties??{}}function nT(e){const t=Dn(e);return t.textContent!==void 0?t.textContent:e.label??""}function oT(e){return Dn(e).textContent===void 0||e.appearance?.hideLabel?!1:!!e.label?.trim()}function sT(e){return e?.contentLayout==="paragraph"?"paragraph":"single"}function $l(e,t={}){const{formValues:r={},urlParams:n={},submissionContext:o,buttonResponses:s,prepopulateResponse:i,labelApiResponse:a}=t,d=Yr(e,r,n,o,s,i),c=tT(d,a,!0);return rT(c)}const iT=/\{api:[^}]+\}/,aT=/\{labelapi:[^}]+\}/;function jl(e){return iT.test(e)}function Ul(e){return aT.test(e)}function lT(e){const t=e.captionTemplate??"",r=e.descriptionTemplate??"",n=jl(e.bodyTemplate)||jl(t)||jl(r),o=Ul(e.bodyTemplate)||Ul(t)||Ul(r);return!!(n&&e.prepopulateLoading||o&&e.labelApiConfigPresent&&(e.labelApiLoading||e.labelApiResponse===void 0&&e.labelApiError==null))}function eh(e,t){const r=t??Dn(e),n=r.variant??"body",o=e.appearance?.size??"md",s=Jm[o]??Jm.md,i=r.fontWeight??"medium";return n!=="body"?W("m-0 text-foreground",Qm[n]??Qm.h3,r.fontWeight&&Zm[r.fontWeight],r.italic&&"italic",r.underline&&"underline",r.textAlign&&bi[r.textAlign]):W("m-0 text-foreground",s,Zm[i],r.italic&&"italic",r.underline&&"underline",r.textAlign&&bi[r.textAlign])}function cT(e,t){const r=(t??Dn(e)).variant??"body";return r==="body"?"p":r}function Rl(e){const t=[];let r=0,n="";const o=()=>{n&&(t.push({type:"text",value:n}),n="")},s=(i,a,d)=>{if(!e.startsWith(i,r))return!1;const c=e.indexOf(a,r+i.length);if(c===-1)return!1;o();const l=e.slice(r+i.length,c);return t.push({type:d,children:Rl(l)}),r=c+a.length,!0};for(;r<e.length;){if(e[r]==="\\"&&r+1<e.length){n+=e[r+1],r+=2;continue}s("**","**","bold")||s("__","__","underline")||s("*","*","italic")||s("_","_","italic")||(n+=e[r],r+=1)}return o(),t}function dT(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function th(e){return e.map(t=>{if(t.type==="text")return dT(t.value);const r=th(t.children);return t.type==="bold"?`<strong class="font-bold">${r}</strong>`:t.type==="italic"?`<em class="italic">${r}</em>`:`<u class="underline">${r}</u>`}).join("")}function uT(e){return e?th(Rl(e)):""}function fT(e,t){return e?t==="markdown-lite"?uT(e):e:""}function rh(e,t){return e.map((r,n)=>{const o=`${t}-${n}`;if(r.type==="text")return r.value?S.createElement(S.Fragment,{key:o},r.value):null;const s=rh(r.children,o);return r.type==="bold"?S.createElement("strong",{key:o,className:"font-bold"},s):r.type==="italic"?S.createElement("em",{key:o,className:"italic"},s):S.createElement("u",{key:o,className:"underline"},s)})}function nh(e,t){if(!e)return null;if(t!=="markdown-lite")return e;const r=Rl(e);return r.length===1&&r[0]?.type==="text"?r[0].value:rh(r,"tl")}const pT="text-label-html prose prose-sm max-w-none [&_p]:m-0 [&_p+p]:mt-2 [&_ul]:my-1 [&_ol]:my-1";function oh(e,t){if(!e)return null;const{field:r,asDescription:n=!1}=t,o=t.textProps??Dn(r),s=t.contentLayout??sT(o),i=o.inlineFormat??"none";if(s==="paragraph"){const d=eT(fT(e,i));if(!d)return null;const c=n?W("m-0 text-sm",o.descriptionMuted!==!1?"text-muted-foreground":"text-foreground",o.textAlign&&bi[o.textAlign]):W(eh(r,o),pT);return S.createElement("div",{className:c,dangerouslySetInnerHTML:{__html:d}})}if(n)return S.createElement("p",{className:W("mt-0.5 text-sm",o.descriptionMuted!==!1?"text-muted-foreground":"text-foreground",o.textAlign&&bi[o.textAlign])},nh(e,i));const a=cT(r,o);return S.createElement(a,{className:eh(r,o)},nh(e,i))}function mT(e){const t=e.labelApiEndpoint?.trim();return!e.labelApiEnabled||!t?null:{labelApiEndpoint:t,labelApiMethod:e.labelApiMethod??"GET",labelApiQueryParams:e.labelApiQueryParams,labelApiHeaders:e.labelApiHeaders,labelApiBodyFields:e.labelApiBodyFields}}async function hT(e,t={}){const{formValues:r={},urlParams:n={},submissionContext:o}=t,s=f=>Yr(f,r,n,o),i=(e.labelApiMethod??"GET").toUpperCase();let a=Gr(s(e.labelApiEndpoint));const d=e.labelApiQueryParams??[];if(d.length){const f=new URLSearchParams;d.forEach(({key:m,value:b})=>{m.trim()&&f.append(m,s(b))});const p=f.toString();p&&(a=`${a}${a.includes("?")?"&":"?"}${p}`)}const c={"Content-Type":"application/json"};(e.labelApiHeaders??[]).forEach(({key:f,value:p})=>{f.trim()&&(c[f]=s(p))});let l;i==="POST"&&(e.labelApiBodyFields??[]).length&&(l={},e.labelApiBodyFields.forEach(({key:f,value:p})=>{f.trim()&&(l[f]=s(p))}));try{return i==="POST"?(await Pn.post(a,l??{},{headers:Object.keys(c).length?c:void 0})).data:(await Pn.get(a,{headers:Object.keys(c).length?c:void 0})).data}catch(f){const p=f,m=p.response?.status,b=typeof p.response?.data=="string"?p.response.data:p.message??"Request failed";throw new Error(m?`HTTP ${m}: ${b}`:String(b))}}const gT=({field:e,className:t,formValues:r,urlParams:n,submissionContext:o,buttonResponses:s,prepopulateResponse:i,prepopulateLoading:a=!1})=>{const d=Dn(e),c=S.useMemo(()=>mT(Dn(e)),[e.properties]),[l,f]=S.useState(void 0),[p,m]=S.useState(!1),[b,h]=S.useState(null),g=S.useMemo(()=>c?JSON.stringify({endpoint:c.labelApiEndpoint,method:c.labelApiMethod,query:c.labelApiQueryParams,headers:c.labelApiHeaders,body:c.labelApiBodyFields}):"",[c]),w=S.useCallback(async()=>{if(!c){f(void 0),h(null),m(!1);return}m(!0),h(null);try{const j=await hT(c,{formValues:r??{},urlParams:n??{},submissionContext:o});f(j)}catch(j){f(void 0),h(j instanceof Error?j.message:"Failed to load label API")}finally{m(!1)}},[c,r,n,o]);S.useEffect(()=>{g&&w()},[g,w]);const v=d.textAlign==="center"?"items-center":d.textAlign==="right"?"items-end":d.textAlign==="justify"?"items-stretch":"items-start",x=nT(e),A=oT(e),I=A&&e.label?e.label:"",T=e.description??"",C=lT({bodyTemplate:x,captionTemplate:I,descriptionTemplate:T,prepopulateLoading:a,labelApiConfigPresent:c!=null,labelApiLoading:p,labelApiResponse:l,labelApiError:b}),_={formValues:r??{},urlParams:n??{},submissionContext:o,buttonResponses:s,prepopulateResponse:i,labelApiResponse:l},E=x?$l(x,_):"",O=A&&e.label?$l(e.label,_):"",N=T?$l(T,_):"";return u.jsx("div",{className:W("w-full min-w-0 h-full min-h-[95px] flex flex-col justify-center py-0.5",v,t),children:C?u.jsx("p",{className:"text-sm text-muted-foreground m-0",children:"Loading…"}):u.jsxs(u.Fragment,{children:[b&&c?u.jsx("p",{className:"text-[10px] text-destructive mb-0.5",title:b,children:"Label API failed"}):null,O?u.jsx("div",{className:"text-sm font-medium text-foreground mb-1 w-full",children:O}):null,E?oh(E,{field:e,textProps:d}):null,N?oh(N,{field:e,textProps:d,asDescription:!0}):null]})})},zl=({legend:e,children:t,className:r,collapsible:n=!1,defaultCollapsed:o=!1,headerActions:s,onCollapsedChange:i})=>{const[a,d]=S.useState(o),c=S.useId(),l=f=>{f.stopPropagation(),n&&d(p=>{const m=!p;return i?.(m),m})};return u.jsxs("fieldset",{className:W("min-w-0 rounded-lg border bg-card p-4",r),"data-form-renderer":"config-section-border",children:[n?u.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2 border-b border-border pb-2",children:[u.jsxs("button",{type:"button",className:W("flex min-w-0 flex-1 items-center gap-2 text-left text-sm font-medium text-foreground","cursor-pointer rounded-sm hover:bg-muted/70 transition-colors focus:outline-none focus:ring-2 focus:ring-ring"),"aria-expanded":!a,"aria-controls":c,onClick:l,children:[u.jsx("span",{className:"shrink-0 text-muted-foreground","aria-hidden":!0,children:a?u.jsx(rd,{className:"h-4 w-4"}):u.jsx(_o,{className:"h-4 w-4"})}),u.jsx("span",{className:"truncate",children:e})]}),s!=null?u.jsx("div",{className:"shrink-0",children:s}):null]}):u.jsx("legend",{className:"px-1 text-sm font-medium text-foreground",children:e}),!a&&u.jsxs("div",{id:c,className:"space-y-3",children:[!n&&s!=null?u.jsx("div",{className:"flex justify-end",children:s}):null,t]})]})},nn=({field:e,value:t,error:r,onChange:n,onBlur:o,disabled:s,readOnly:i,isRequired:a,className:d,formValues:c={},submissionContext:l,onSubmit:f,onReset:p,onCancel:m,isSubmitting:b,bffSubmitApi:h,onBffSubmitResult:g,extraSubmitPayload:w,buttonResponses:v,onButtonApiResponse:x,onValidateForm:A,getValidationErrors:I,allFields:T,onSubmittingChange:C,onAddMore:_,scopedFormValues:E,scopedFieldNameMap:O,excludedOptionValues:N,prepopulateMappedFieldNames:j,fieldValueKey:R,hideTableRowControls:M=!1,urlParams:B={},prepopulateResponse:P=null,prepopulateLoading:H=!1})=>{switch(e.type){case"divider":return u.jsx(mE,{field:e,className:d});case"header":return u.jsx(gE,{field:e,className:d});case"sectionHeading":return u.jsx(vE,{field:e,className:d});case"spacer":return u.jsx(wE,{field:e,className:d});case"textLabel":return u.jsx(gT,{field:e,className:d,formValues:c,urlParams:B,submissionContext:l,buttonResponses:v,prepopulateResponse:P??void 0,prepopulateLoading:H});case"status":return u.jsx(sE,{field:e,value:t??null,error:r,disabled:s,isRequired:a,className:d,formValues:c,submissionContext:l,extraSubmitPayload:w,prepopulateResponse:P})}switch(e.type){case"text":case"password":case"url":return u.jsx(aa,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"number":return u.jsx(Zc,{field:e,value:t??null,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"email":return u.jsx(ld,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"phone":case"aadhaar":return u.jsx(cd,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"textarea":case"richtext":return u.jsx(dd,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"select":{const D=R??e.name??e.key??e.id,K=!!(D&&j?.has(D));return u.jsx(Ff,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,formValues:c,submissionContext:l,excludedOptionValues:N,isPrepopulateTarget:K})}case"multiselect":{const D=Array.isArray(t)?t:t!=null&&t!==""?[String(t)]:[];return u.jsx(Cp,{field:e,value:D,onChange:K=>n(K),onBlur:o,error:r,disabled:s,isRequired:a,className:d,formValues:c,submissionContext:l,excludedOptionValues:N})}case"asyncsearch":return u.jsx(tp,{field:e,value:t,onChange:D=>n(D),onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d,formValues:c,submissionContext:l});case"checkbox":case"terms":return u.jsx(Ep,{field:e,value:t||!1,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d});case"toggle":return u.jsx(gA,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d});case"radio":case"checkboxgroup":return u.jsx(Xp,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,excludedOptionValues:N});case"selectablelist":{const D=Array.isArray(t)?t:[];return console.log("[SelectableList] FieldRenderer: passing to SelectableListField",{fieldName:e.name,value:D,valueLength:D.length,submissionContextKeys:l?Object.keys(l):[]}),u.jsx(aE,{field:e,value:D,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,submissionContext:l})}case"date":case"time":case"datetime":case"daterange":return u.jsx(Jp,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"file":return u.jsx(RA,{field:e,value:t,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,buttonResponses:v});case"camera":return u.jsx(vC,{field:e,value:t??null,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d});case"photoChoice":return u.jsx(wC,{field:e,value:t??null,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,buttonResponses:v});case"signature":return u.jsx(nE,{field:e,value:t||null,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"rating":return u.jsx(LC,{field:e,value:t||0,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"slider":return u.jsx(rE,{field:e,value:t||0,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"table":return u.jsx(oE,{field:e,value:t||[],onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d,hideRowControls:M,formValues:c,submissionContext:l});case"button":return u.jsx(PC,{field:e,value:t,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d,onSubmit:f,onReset:p,onCancel:m,isSubmitting:b,formValues:c,submissionContext:l,buttonResponses:v,onButtonApiResponse:x,bffSubmitApi:h,onBffSubmitResult:g,extraSubmitPayload:w,onValidateForm:A,getValidationErrors:I,allFields:T,onSubmittingChange:C,scopedFormValues:E,scopedFieldNameMap:O,prepopulateResponse:P});case"editButton":return u.jsx(IC,{field:e,disabled:s,readOnly:i,isRequired:a,className:d,buttonResponses:v,onButtonApiResponse:x});case"addmore":return u.jsx(MC,{field:e,error:r,disabled:s,readOnly:i,isRequired:a,className:d,onAddMore:()=>_?.(e)});default:return u.jsx("div",{className:"p-3 border rounded-md bg-muted/50",children:u.jsxs("p",{className:"text-sm text-muted-foreground",children:["Unsupported field type: ",e.type]})})}},yT=({steps:e,currentStep:t,completedSteps:r,onStepClick:n,className:o})=>u.jsx("div",{className:W("mb-8",o),children:u.jsx("nav",{"aria-label":"Progress",children:u.jsx("ol",{className:"flex items-center",children:e.map((s,i)=>{const a=r.has(i),d=t===i,c=n&&(a||i===t+1||i<=t);return u.jsxs("li",{className:W("relative",i!==e.length-1&&"pr-8 sm:pr-20 flex-1"),children:[i!==e.length-1&&u.jsx("div",{className:W("absolute top-4 left-8 -right-8 sm:left-12 sm:-right-12 h-0.5",a?"bg-primary":"bg-border"),"aria-hidden":"true"}),u.jsx("button",{type:"button",onClick:()=>c&&n?.(i),disabled:!c,className:W("relative flex h-8 w-8 items-center justify-center rounded-full text-sm font-medium","transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2",a&&"bg-primary text-primary-foreground",d&&!a&&"border-2 border-primary text-primary",!a&&!d&&"border-2 border-border text-muted-foreground",c&&"cursor-pointer hover:bg-primary/10",!c&&"cursor-default"),"aria-current":d?"step":void 0,children:a?u.jsx(ps,{className:"h-4 w-4"}):u.jsx("span",{children:i+1})}),u.jsxs("div",{className:"mt-2",children:[u.jsx("span",{className:W("text-sm font-medium",d&&"text-primary",!d&&!a&&"text-muted-foreground"),children:s.name}),s.description&&u.jsx("p",{className:"text-xs text-muted-foreground hidden sm:block",children:s.description})]})]},s.id)})})})});function Ko(e){if(!e)return e;const t={...e};return e._id&&!e.id&&(t.id=e._id),delete t._id,t.formDefinitionId&&typeof t.formDefinitionId=="object"&&(t.formDefinitionId=t.formDefinitionId._id||t.formDefinitionId.id||t.formDefinitionId),t}function sh(e){return Array.isArray(e)?e.map(Ko):[]}function bT(e){if(!e.moduleId)throw new Error(`Form response missing required field: moduleId. Form ID: ${e._id||e.id}. Please ensure the backend returns moduleId when fetching forms.`);if(!e._id&&!e.id)throw new Error("Form response missing required field: id. Please ensure the backend returns _id or id when fetching forms.");let t;typeof e.moduleId=="object"&&e.moduleId._id?t=Ko(e.moduleId):t=e.moduleId;const r=e.isDefault??!1;if(!r&&!e.tenantId)throw new Error(`Form response missing required field: tenantId. Form ID: ${e._id||e.id}. Please ensure the backend returns tenantId when fetching non-default forms.`);return{id:e._id||e.id,name:e.name,description:e.description||"",version:e.version??1,status:e.status||"draft",category:e.category||"",createdAt:e.createdAt||new Date().toISOString(),updatedAt:e.updatedAt||e.createdAt||new Date().toISOString(),createdBy:e.createdBy||"",isActive:e.isActive??!0,isDefault:r,moduleId:t,tenantId:e.tenantId||void 0,featureId:e.featureId,config:e.config??void 0}}class vT{basePath="/api/form-builder/forms";async getForRendering(t,r){if(!Fn())throw new Error("Client ID is required");const o=r!==void 0?`${this.basePath}/${t}/render?version=${r}`:`${this.basePath}/${t}/render`,s=await Pn.get(o),i=s.data?.data||s.data,a=i?.BFF_submit_api||i?.bff_submit_api||s.data?.BFF_submit_api||s.data?.bff_submit_api,d=i.form||i;if(!d.moduleId&&!i.form?.moduleId)throw new Error(`Form response missing required field: moduleId. Form ID: ${t}. Please ensure the backend returns moduleId in the form response.`);if(!(d.isDefault??i.form?.isDefault??!1)&&!d.tenantId&&!i.form?.tenantId)throw new Error(`Form response missing required field: tenantId. Form ID: ${t}. Please ensure the backend returns tenantId for non-default forms.`);i.form?.moduleId&&!d.moduleId&&(d.moduleId=i.form.moduleId),i.form?.tenantId&&!d.tenantId&&(d.tenantId=i.form.tenantId),i.form?.isDefault!==void 0&&d.isDefault===void 0&&(d.isDefault=i.form.isDefault);const l=bT(d);i.form?.moduleId&&(typeof i.form.moduleId=="object"&&i.form.moduleId._id?l.moduleId=Ko(i.form.moduleId):typeof i.form.moduleId=="string"&&(l.moduleId=i.form.moduleId));const f=sh(i.fields||[]),p=i.layout?Ko(i.layout):null,m=sh(i.rules||[]),b=i.module?Ko(i.module):void 0,h=i.clientMapping||i.clientOverrides;return{form:l,fields:f,layout:p,rules:m,module:b,clientMapping:h,clientOverrides:h,BFF_submit_api:a||void 0}}}const ih=new vT;function ah({className:e,size:t="md",text:r="Loading...",fullScreen:n=!1}){const o={sm:"h-6 w-6",md:"h-12 w-12",lg:"h-16 w-16"},s=u.jsxs("div",{className:"text-center",children:[u.jsx("div",{className:W("animate-spin rounded-full border-b-2 border-blue-600 mx-auto mb-4",o[t],e)}),r&&u.jsx("p",{className:"text-gray-600",children:r})]});return n?u.jsx("div",{className:"min-h-screen bg-gradient-to-br from-blue-50 via-white to-indigo-50 flex items-center justify-center",children:s}):s}const wT={submitAction:"database",autoSave:!0,autoSaveInterval:30,showProgressBar:!0,allowDraft:!0,validateOnChange:!1,validateOnBlur:!0,showFieldErrors:"inline",layout:"default",submitButtonText:"Submit",resetButtonText:"Reset",showReset:!1,successMessage:"Form submitted successfully!",errorMessage:"An error occurred. Please try again."},ST=300;function xT(){return{...wT}}function AT(e){if(e.apidata&&typeof e.apidata=="object")return e.apidata;if(e.metadata)try{const t=typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata;if(t.apiEndpoint||t.apiKey||t.valueSource==="api")return{apiKey:t.apiKey,valueSource:t.valueSource,apiEndpoint:t.apiEndpoint,apiAutoDetect:t.apiAutoDetect,apiLabelField:t.apiLabelField,apiValueField:t.apiValueField,apiMethod:t.apiMethod,apiRealtime:t.apiRealtime,apiQueryParams:t.apiQueryParams,apiClientFilter:t.apiClientFilter}}catch{}return null}function CT(e){if(!e||typeof e!="object")return;const t=e,r=t.user_type??t.visibleToUserType??"",n=t.user_role??t.visibleToUserRole??"",o=Array.isArray(t.users)?t.users:Array.isArray(t.visibleToUserIds)?t.visibleToUserIds:[];if(!(r!=null&&r!==""||n!=null&&n!==""||o.length>0))return;const i={};return r!=null&&r!==""&&(i.visibleToUserType=r),n!=null&&n!==""&&(i.visibleToUserRole=n),o.length>0&&(i.visibleToUserIds=o),i}function ET(e){const t=xT();if(!e||typeof e!="object")return t;const r=e;return{...t,submitAction:r.submitAction||t.submitAction,apiEndpoint:r.apiEndpoint,dbTable:r.dbTable,emailTo:r.emailTo,workflowTrigger:r.workflowTrigger,workflowSubmissionConfig:r.workflowSubmissionConfig,prepopulateApi:r.prepopulateApi,prepopulateResponseRules:r.prepopulateResponseRules??void 0,autoSave:r.autoSave,autoSaveInterval:r.autoSaveInterval,showProgressBar:r.showProgressBar,allowDraft:r.allowDraft,validateOnChange:r.validateOnChange,validateOnBlur:r.validateOnBlur,showFieldErrors:r.showFieldErrors,layout:r.layout,submitButtonText:r.submitButtonText,resetButtonText:r.resetButtonText,showReset:r.showReset,successMessage:r.successMessage,successRedirect:r.successRedirect,errorMessage:r.errorMessage}}function vi(e,t,r,n){const o=t.map(c=>{let l=[],f={};try{c.options&&(l=JSON.parse(c.options)),c.metadata&&(f=JSON.parse(c.metadata))}catch{}const p=AT(c);p&&Object.assign(f,p),l.length>0&&(f.options=l);const m=[];if(c.validationRequired&&m.push({type:"required",message:"This field is required"}),c.validationMinLength!==null&&c.validationMinLength!==void 0&&m.push({type:"minLength",value:c.validationMinLength,message:`Minimum length is ${c.validationMinLength}`}),c.validationMaxLength!==null&&c.validationMaxLength!==void 0&&m.push({type:"maxLength",value:c.validationMaxLength,message:`Maximum length is ${c.validationMaxLength}`}),c.validationPattern&&m.push({type:"pattern",value:c.validationPattern,message:"Invalid format"}),c.validationRules&&typeof c.validationRules=="object"){const L=c.validationRules;if(L.required===!0&&!m.some(z=>z.type==="required")&&m.push({type:"required",message:"This field is required"}),L.allowLetters!==void 0&&m.push({type:"allowLetters",value:L.allowLetters}),L.allowNumbers!==void 0&&m.push({type:"allowNumbers",value:L.allowNumbers}),L.allowSpecialChars!==void 0&&m.push({type:"allowSpecialChars",value:L.allowSpecialChars}),L.minLetters!==void 0&&typeof L.minLetters=="number"&&m.push({type:"minLetters",value:L.minLetters}),L.maxLetters!==void 0&&typeof L.maxLetters=="number"&&m.push({type:"maxLetters",value:L.maxLetters}),L.minNumbers!==void 0&&typeof L.minNumbers=="number"&&m.push({type:"minNumbers",value:L.minNumbers}),L.maxNumbers!==void 0&&typeof L.maxNumbers=="number"&&m.push({type:"maxNumbers",value:L.maxNumbers}),L.minSpecialChars!==void 0&&typeof L.minSpecialChars=="number"&&m.push({type:"minSpecialChars",value:L.minSpecialChars}),L.maxSpecialChars!==void 0&&typeof L.maxSpecialChars=="number"&&m.push({type:"maxSpecialChars",value:L.maxSpecialChars}),L.fileSize!==void 0&&typeof L.fileSize=="number"){const z=L.fileSize/1048576;m.push({type:"fileSize",value:L.fileSize,message:`File size must be less than ${z.toFixed(2)} MB`})}if(L.fileType!==void 0){const z=Array.isArray(L.fileType)?L.fileType:typeof L.fileType=="string"?L.fileType.split(",").map(V=>V.trim()).filter(Boolean):[];z.length>0&&m.push({type:"fileType",value:z,message:"File type is not allowed"})}}const b=[],h=new Set;n.filter(L=>{const z=typeof L.targetFieldId=="object"?L.targetFieldId.id||L.targetFieldId._id:L.targetFieldId;return!!(z===c.id||z===c._id||z&&c.fieldKey&&z===c.fieldKey)}).forEach(L=>{try{const z=JSON.parse(L.conditionExpression);!z.id&&L.id&&(z.id=L.id);const V=typeof L.targetFieldId=="object"?L.targetFieldId?.id||L.targetFieldId?._id:L.targetFieldId;z.action&&(!z.then||!Array.isArray(z.then)||z.then.length===0)&&(z.then=[{action:z.action,...V&&{target:V}}]),(!z.then||!Array.isArray(z.then)||z.then.length===0)&&L.action&&(z.then=[{action:L.action,...V&&{target:V}}]),z.then&&Array.isArray(z.then)&&V&&(z.then=z.then.map(re=>!re.target&&V?{...re,target:V}:re));const le=L.conditionExpression||JSON.stringify(z);if(h.has(le))return;h.add(le),b.push(z)}catch{}});const w=c.disabled===!0||f?.disabled===!0||!1;let v=c.readOnly===!0||f?.readOnly===!0||!1;const x=c.hidden===!0||f?.hidden===!0||!1;(f?.valueSource==="calculated"||f?.formula)&&(v=!0);const{disabled:A,readOnly:I,hidden:T,...C}=f,_={};C.hideLabel!==void 0&&(_.hideLabel=C.hideLabel),C.labelPosition!==void 0&&(_.labelPlacement=C.labelPosition),C.size!==void 0&&(_.size=C.size),C.customClass!==void 0&&(_.className=C.customClass);const{labelPosition:E,size:O,customClass:N,visibility:j,...R}=C,M=Object.keys(R).length>0?R:void 0,B=Object.keys(_).length>0?_:void 0,P=c.visibility??f?.visibility??j;let H=CT(P);if(P&&!H){const L=P;(L.visibleToUserType!=null||L.visibleToUserRole!=null||Array.isArray(L.visibleToUserTypes)&&L.visibleToUserTypes.length>0||Array.isArray(L.visibleToUserRoles)&&L.visibleToUserRoles.length>0||Array.isArray(L.visibleToUserIds)&&L.visibleToUserIds.length>0||Array.isArray(L.hiddenFromUserIds)&&L.hiddenFromUserIds.length>0)&&(H={visibleToUserType:L.visibleToUserType??(Array.isArray(L.visibleToUserTypes)?L.visibleToUserTypes[0]:void 0),visibleToUserRole:L.visibleToUserRole??(Array.isArray(L.visibleToUserRoles)?L.visibleToUserRoles[0]:void 0),visibleToUserIds:L.visibleToUserIds,hiddenFromUserIds:L.hiddenFromUserIds})}const D=f?.columnName,q=!!c.parentFieldId&&typeof D=="string"?D:c.fieldKey;return{id:c.id,type:c.fieldType,name:q,label:c.label,description:c.helpText||void 0,placeholder:c.placeholder||void 0,defaultValue:c.defaultValue||void 0,position:{order:typeof c.positionOrder=="number"?c.positionOrder:c.positionRow??0,column:typeof c.positionColumn=="number"?c.positionColumn:1,columnSpan:typeof c.positionWidth=="number"?c.positionWidth:1},parentId:void 0,appearance:B,validation:m.length>0?m:void 0,conditions:b.length>0?b:void 0,properties:M,visibility:H&&(H.visibleToUserType!=null||H.visibleToUserRole!=null||Array.isArray(H.visibleToUserIds)&&H.visibleToUserIds.length>0||Array.isArray(H.hiddenFromUserIds)&&H.hiddenFromUserIds.length>0)?H:void 0,disabled:w,readOnly:v,hidden:x}});o.forEach((c,l)=>{if(c.visibility){const f=t[l];console.log("[backendToFormSchema] field with visibility",{fieldKey:f?.fieldKey??c.name,name:c.name,type:c.type,parentFieldId:f?.parentFieldId,visibility:c.visibility})}});const s=t;for(let c=0;c<o.length;c++){const l=s[c]?.parentFieldId;if(l){const f=o.find(m=>m.id===l||m.type==="table"&&m.name===l||m.type==="table"&&s[c].fieldKey?.startsWith?.(m.name+"_column_")),p=o[c];if(f&&f.type==="table"&&p){const m=f.properties||{};Array.isArray(m.columns)||(m.columns=[]),m.columns.push(p),f.properties=m}}}const i=o.filter((c,l)=>!s[l]?.parentFieldId);for(const c of i)if(c.type==="table"&&c.properties&&Array.isArray(c.properties.columns)){const l=c.properties.columns;for(const f of l){const p=f.properties?.columnName;typeof p=="string"&&(f.name=p)}l.sort((f,p)=>(f.position?.order??0)-(p.position?.order??0)||(f.position?.column??0)-(p.position?.column??0))}let a;const d=e.config;if(console.log("[Prepopulate] backendToFormSchema config",{formId:e.id,hasRawConfig:d!=null,rawConfigType:typeof d,rawConfigPreview:d!=null?typeof d=="string"?d.slice(0,300):JSON.stringify(d).slice(0,300):null}),d!=null)try{const c=typeof d=="string"?JSON.parse(d):d;c&&typeof c=="object"?a=ET(c):a={submitAction:"database",layout:"default",autoSave:!0,validateOnChange:!0,showFieldErrors:"inline"}}catch{a={submitAction:"database",layout:"default",autoSave:!0,validateOnChange:!0,showFieldErrors:"inline"}}else a={submitAction:"database",layout:"default",autoSave:!0,validateOnChange:!0,showFieldErrors:"inline"};return{id:e.id,name:e.name,description:e.description,version:e.version,status:e.status,config:a,fields:i,createdAt:e.createdAt,updatedAt:e.updatedAt,createdBy:e.createdBy,category:e.category,moduleId:typeof e.moduleId=="string"?e.moduleId:e.moduleId?.id,tenantId:e.tenantId,featureId:e.featureId,isDefault:e.isDefault}}function Xt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ho(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>ho(r));if(!Xt(e))return e;const t={};for(const[r,n]of Object.entries(e))t[r]=ho(n);return t}function lh(e,...t){const r={...e};for(const n of t)if(!(!n||!Xt(n)))for(const[o,s]of Object.entries(n)){const i=r[o];Xt(s)&&Xt(i)?r[o]=lh(i,s):r[o]=s}return r}function go(e){return Xt(e)?e:{}}function Vl(e){if(e==null)return{};if(typeof e=="string"){const t=e.trim();if(!t)return{};try{const r=JSON.parse(t);return Xt(r)?ho(r):{}}catch{return{}}}return Xt(e)?ho(e):{}}function ch(e){const t=e.apidata;return Xt(t)&&Object.keys(t).length>0}function TT(e){if(typeof e.metadata=="string"&&e.metadata.trim()!==""||typeof e.metadata=="object"&&e.metadata!==null&&!Array.isArray(e.metadata)&&Object.keys(e.metadata).length>0||ch(e))return!0;const t=e.fieldKey,r=e.fieldType,n=e.name,o=e.type;return!!(t&&(!n||String(n).trim()==="")||r&&(!o||String(o).trim()==="")||t&&n&&t!==n||r&&o&&r!==o||!n&&e.key&&typeof e.key=="string")}const dh=["hideLabel","contentAlign","contentVerticalAlign","labelPlacement","widthPercent","widthMode","className","verticalAlign","horizontalAlign","cellAlign","cellJustify","size","variant","minWidth","minHeight"];function _T(e,t){const r=e.appearance,n=Xt(r)&&Object.keys(r).length>0?ho(r):{},o=go(t.appearance),s={...n};for(const[i,a]of Object.entries(o))i!=="heightPercent"&&s[i]===void 0&&(s[i]=ho(a));for(const i of dh)s[i]===void 0&&t[i]!==void 0&&(s[i]=t[i]);return delete s.heightPercent,Object.keys(s).length>0?s:void 0}function wi(e,t){const r=go(e.position),n=typeof r.order=="number"&&!Number.isNaN(r.order)?r.order:typeof r.row=="number"&&!Number.isNaN(r.row)?r.row:typeof e.positionOrder=="number"?e.positionOrder:typeof e.order=="number"?e.order:typeof e.positionRow=="number"?e.positionRow:t,o=typeof r.column=="number"&&!Number.isNaN(r.column)?r.column:typeof e.positionColumn=="number"?e.positionColumn:1,s=typeof r.columnSpan=="number"&&!Number.isNaN(r.columnSpan)?r.columnSpan:typeof r.width=="number"&&!Number.isNaN(r.width)?r.width:typeof e.positionWidth=="number"?e.positionWidth:1,i=typeof r.rowSpan=="number"&&!Number.isNaN(r.rowSpan)?r.rowSpan:typeof e.positionRowSpan=="number"?e.positionRowSpan:1,a={order:n,column:o,columnSpan:s,rowSpan:i},d=r.cellGroupId,c=r.cellSlot,l=r.sharedCellLayout;return typeof d=="string"&&(a.cellGroupId=d),typeof c=="number"&&(a.cellSlot=c),(l==="row"||l==="stack")&&(a.sharedCellLayout=l),a}function NT(e,t){return wi(e,t)}function kT(e,t){const r=e,n=Vl(r.metadata),o=go(r.apidata),s=go(r.properties),i=lh({},n,o,s),a=(r.name!=null&&String(r.name).trim()!==""?r.name:void 0)??(typeof r.fieldKey=="string"?r.fieldKey:void 0)??(typeof r.key=="string"?r.key:void 0),d=(r.type!=null&&String(r.type).trim()!==""?r.type:void 0)??(typeof r.fieldType=="string"?r.fieldType:void 0),c=_T(r,n),l=NT(r,t),f={...r};return f.properties=i,a!==void 0&&(f.name=a),d!==void 0&&(f.type=d),c!==void 0?f.appearance=c:(!Xt(r.appearance)||Object.keys(r.appearance).length===0)&&delete f.appearance,f.position=l,Xt(f.appearance)&&delete f.appearance.heightPercent,f}function FT(e,t){if(!e||typeof e!="object")return!0;const r=e,n=Vl(r.metadata),o=Object.keys(n).length===0&&!(typeof r.metadata=="string"&&r.metadata.trim()!==""),s=!ch(r);if(TT(r)||!o||!s)return!1;const i=r.position;if(Xt(i)&&(typeof i.order=="number"&&!Number.isNaN(i.order)||typeof i.row=="number"&&!Number.isNaN(i.row)||typeof i.column=="number"&&!Number.isNaN(i.column))){if(Xt(i)&&(typeof i.row=="number"||typeof i.width=="number"))return!1}else if(typeof r.positionRow=="number"||typeof r.positionColumn=="number"||typeof r.positionWidth=="number"||typeof r.positionRowSpan=="number"||typeof r.positionOrder=="number")return!1;return!(Xt(n.appearance)||dh.some(c=>n[c]!==void 0&&(r.appearance==null||Xt(r.appearance)&&r.appearance[c]===void 0)))}function OT(e){const t=new Map;for(const r of e){if(!r||typeof r!="object")continue;const n=r,o=new Set;for(const s of[n.fieldKey,n.key,n.name,n.id,n._id])s!=null&&String(s).trim()!==""&&o.add(String(s).trim());for(const s of o)t.has(s)||t.set(s,n)}return t}function Si(e){const t=go(e.position);return typeof t.row=="number"&&!Number.isNaN(t.row)||typeof t.width=="number"&&!Number.isNaN(t.width)||typeof t.column=="number"&&!Number.isNaN(t.column)&&t.column>1||typeof e.positionColumn=="number"&&e.positionColumn>1||typeof e.positionRow=="number"}function Hl(e){const t=[],r=new Set,n=i=>{for(const a of i)a!=null&&typeof a=="object"&&!r.has(a)&&(r.add(a),t.push(a))},o=e.form;Xt(o)&&Array.isArray(o.fields)&&n(o.fields);const s=e.workflowFormFields;return Array.isArray(s)&&n(s),Array.isArray(e.fields)&&n(e.fields.filter(i=>{if(!i||typeof i!="object")return!1;const a=i;return(typeof a.fieldKey=="string"||typeof a.fieldType=="string")&&Si(a)})),t}function uh(e,t){const r=[...Array.isArray(t)?t:[],...Hl(e)];if(r.length===0)return e;const n=OT(r),o=e.fields;if(!Array.isArray(o)||o.length===0)return e;let s=!1;const i=o.map((a,d)=>{const c=a;if(Si(c))return a;const l=[c.key,c.name,c.id,c.fieldKey,c._id].filter(h=>h!=null&&String(h).trim()!=="").map(h=>String(h).trim());let f;for(const h of l)if(f=n.get(h),f)break;if(!f)return a;const p=wi(f,d),m=go(c.position);return m.order===p.order&&m.column===p.column&&m.columnSpan===p.columnSpan&&m.rowSpan===p.rowSpan?a:(s=!0,{...c,position:p})});return s?{...e,fields:i}:e}function fh(e){const t=e.fields;if(!Array.isArray(t)||t.length===0||!t.some(a=>a&&typeof a=="object"&&!Si(a)))return!1;if(e.BFF_submit_api!=null||e.bff_submit_api!=null||Xt(e.form)&&Array.isArray(e.form.fields)||Array.isArray(e.workflowFormFields)&&e.workflowFormFields.length>0)return!0;const n=e.config,o=n!=null&&typeof n=="object"?n.layout:void 0,s=o!=null&&typeof o=="object"&&!Array.isArray(o)?o:e.layout!=null&&typeof e.layout=="object"&&!Array.isArray(e.layout)?e.layout:null;return(typeof s?.columns=="number"?s.columns:1)>1}function xi(e,t){if(e==null||typeof e!="object")return e;const r=uh(e,t?.workflowFormFields),n=r.fields;if(!Array.isArray(n))return r;let o=r!==e;const s=n.map((i,a)=>{if(FT(i))return i;const d=kT(i,a);return d!==i&&(o=!0),d});return o?{...r,fields:s}:r}function PT(e,t){return xi(e,t)}let ph=null;function IT(e){ph=e}function mh(){return(ph?.()??"").replace(/\/+$/,"")}function Wl(e){const t=typeof e=="string"?e.trim():"";if(!t||/^https?:\/\//i.test(t))return t;const r=mh();if(r)return t.startsWith("/")?`${r}${t}`:`${r}/${t}`;if(typeof window<"u"&&window.location?.origin){const n=window.location.origin.replace(/\/+$/,"");return t.startsWith("/")?`${n}${t}`:`${n}/${t}`}return t}const hh=new Map;function gh(e){return hh.get(e)}function ql(e,t){!e||!Array.isArray(t)||t.length===0||hh.set(e,t)}function MT(e,t){const r=String(e??"").trim();!r||!Array.isArray(t)||t.length===0||ql(`form:${r}`,t)}function yh(e){const t=String(e??"").trim();if(t)return gh(`form:${t}`)}function Yo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xo(e){if(!Yo(e))return null;const t=e.BFF_submit_api??e.bff_submit_api;return!Yo(t)||typeof t.url!="string"||t.url.trim()===""?null:t}function LT(e){return Wl(e).match(/\/workflows\/modules\/([^/?#]+)\/submit\/?(?:[?#]|$)/i)?.[1]??null}function bh(e){const t=Wl(e);if(!t)return null;try{const r=new URL(t);return/\/submit\/?$/i.test(r.pathname)?(r.pathname=r.pathname.replace(/\/submit\/?$/i,"/state"),r.search="",r.toString()):null}catch{return null}}function vh(e,t){const r=e[t];if(r!=null&&String(r).trim()!=="")return String(r).trim();const n=t.toLowerCase();for(const[o,s]of Object.entries(e))if(o.toLowerCase()===n&&s!=null&&String(s).trim()!=="")return String(s).trim()}function DT(e){if(!Yo(e))return null;const t=e.form??(Yo(e.data)?e.data.form:void 0);return!Yo(t)||!Array.isArray(t.fields)||t.fields.length===0?null:t.fields}function BT(e,t,r){const n=t.headers??{},o=t.payload??{},s=r?.submissionContext??{},i=typeof s.tenant_id=="string"&&s.tenant_id.trim()||typeof s.tenantId=="string"&&s.tenantId.trim()||void 0,a=vh(n,"x-client-id"),d=typeof o.current_step_id=="string"&&o.current_step_id.trim()||void 0;if(!i||!a)return null;try{const c=new URL(e),l=new URLSearchParams(c.search);r?.featureId&&l.set("feature_id",r.featureId),l.set("tenant_id",i),l.set("client_id",a),d&&l.set("step_id",d);const f=s.context_user_id??s.user_id;return typeof f=="string"&&f.trim()&&l.set("user_id",f.trim()),c.search=l.toString(),c.toString()}catch{return null}}async function wh(e,t){const r=String(t?.formId??"").trim();if(r){const l=yh(r);if(l&&l.length>0)return l}const n=bh(e.url);if(!n)return null;const o=BT(n,e,t);if(!o)return null;const s=gh(o);if(s&&s.length>0)return s;const i={...e.headers??{}};vh(i,"accept")||(i.Accept="application/json");const a=await fetch(o,{method:"GET",headers:i,credentials:"include"});if(!a.ok)return null;let d;try{d=await a.json()}catch{return null}const c=DT(d);return!c||c.length===0?null:(ql(o,c),r&&ql(`form:${r}`,c),c)}function $T(e,t){const r=t??e;if(!r||typeof r!="object")return null;const n=e;if(!n||typeof n!="object"||n===r)return r;const o=Xo(n);return!o||Xo(r)?r:{...r,BFF_submit_api:o}}function Ai(e){const t=typeof e.position?.order=="number"?e.position.order:-1,r=typeof e.position?.column=="number"?e.position.column:1,n=e.position?.cellGroupId??"_";return`${t}:${r}:${n}`}function Ci(e){return[...e].sort((t,r)=>{const n=t.position?.cellSlot,o=r.position?.cellSlot;return typeof n=="number"&&typeof o=="number"&&n!==o?n-o:String(t.id).localeCompare(String(r.id))})}function Ei(e,t){if(e.length===0)return{rowSpan:1,columnSpan:1};let r=1,n=1;for(const o of e)r=Math.max(r,vo(o)),n=Math.max(n,Nc(o,t));return{rowSpan:r,columnSpan:n}}function Sh(e){const t=Ci(e);for(const r of t){const n=r.position?.sharedCellLayout;if(n==="row"||n==="stack")return n}return t.length===2?"row":"stack"}function jT(e,t){const r=new Map;for(const n of e){if(!t(n)||typeof n.position?.order!="number")continue;const o=Ai(n),s=r.get(o)??[];s.push(n),r.set(o,s)}return Array.from(r.values()).map(n=>Ci(n).slice(0,2))}function xh(e,t,r,n){const o=r.filter(a=>n(a)&&typeof a.position?.order=="number"&&a.position.order===e&&(a.position.column??1)===t+1);if(o.length===0)return[];const s=new Map;for(const a of o){const d=Ai(a),c=s.get(d)??[];c.push(a),s.set(d,c)}const i=[...s.values()][0]??[];return Ci(i).slice(0,2)}function UT(e,t,r,n){const o=r[0],s=o.position?.order,i=o.position?.column??1;if(typeof s!="number")return!1;const{rowSpan:a,columnSpan:d}=Ei(r,n),c=e===s&&t===i-1,l=e>=s&&e<s+a,f=t>=i-1&&t<i-1+d;return l&&f&&!c}const RT=new Set(["PENDING_PAYMENT","PAYMENT_PENDING","AWAITING_PAYMENT","PAID","PAYMENT_COMPLETED","PAYMENT_FAILED","REFUNDED","AUTHORIZED","CAPTURED","PARTIALLY_PAID"].map(e=>e.toUpperCase()));function Gl(e){return typeof e=="string"&&e.trim()!==""}function Kl(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;const t=e;if(t.payment_type!=null&&t.payment_type!==""||t.payment_mode!=null&&t.payment_mode!==""||t.transaction_id!=null&&String(t.transaction_id).trim()!==""||t.payment_status!=null&&String(t.payment_status).trim()!==""||typeof t.amount=="number"||Gl(t.amount)||typeof t.total_amount=="number"||Gl(t.total_amount)||Gl(t.currency)||t.gateway!=null&&String(t.gateway).trim()!==""||t.razorpay_order_id!=null&&String(t.razorpay_order_id).trim()!==""||t.stripe_payment_intent!=null&&String(t.stripe_payment_intent).trim()!=="")return!0;const r=t.status;return!!(typeof r=="string"&&RT.has(r.trim().toUpperCase()))}function zT(e){const t=pt(e,"data.items");if(!Array.isArray(t)||t.length===0)return;const r=t[0];if(r==null||typeof r!="object")return;const n=r;if(!(n.id===void 0||n.id===null||n.id===""))return{item:n,id:n.id}}function VT(e,t){const r=zT(e);if(!r)return;const n=pt(e,"data"),o=n!=null&&typeof n=="object"&&!Array.isArray(n)?n:void 0;if(t?.treatFirstItemIdAsPaymentId===!0||Kl(r.item)||o!=null&&Kl(o))return r.id}function HT(e){const t=e.properties,r=e.metadata;return[t?.uploadApiEndpoint,t?.apiEndpoint,r?.uploadApiEndpoint,r?.apiEndpoint].filter(o=>typeof o=="string"&&o.length>0)}function WT(e){return HT(e).some(t=>t.toLowerCase().includes("payment"))}function qT(e){const t=e.properties,r=e.metadata;return!!(t?.mergeSuccessDataIdAsPaymentId||r?.mergeSuccessDataIdAsPaymentId)}function GT(e,t){if(t?.type!=="button"||!Co(e))return;const r=pt(e,"data.id");if(r==null||String(r).trim()==="")return;const n=pt(e,"data");if(qT(t)||n!=null&&typeof n=="object"&&!Array.isArray(n)&&Kl(n)||WT(t))return r}const KT=new Set(["section","group","columns","divider","header","sectionHeading","spacer","addmore","textLabel"]);function YT(e,t){if(!e.length||!t?.length)return[];const r=new Map(t.map(o=>[o.id,o])),n=[];for(const o of e){const s=r.get(o);if(s?.fieldNames?.length)for(const i of s.fieldNames)i&&!n.includes(i)&&n.push(i)}return n}function XT(e,t){const r=e.properties,n=Array.isArray(r?.linkedFieldNames)?r.linkedFieldNames:[],o=YT(Array.isArray(r?.linkedSectionIds)?r.linkedSectionIds:[],t),s=new Set,i=[];for(const a of[...n,...o])!a||s.has(a)||(s.add(a),i.push(a));return i}function Ah(e,t){const r=e.properties,n=Array.isArray(r?.linkedSectionIds)?r.linkedSectionIds:[];if(!n.length||!t?.length)return[];const o=new Map(t.map(s=>[s.id,s]));return n.map(s=>o.get(s)).filter(s=>!!s)}function JT(e,t){return Ah(e,t).find(r=>r.heading?.enabled)}function Ch(e,t){const r=e.template??"";return(e.mode??"increment")==="fixed"?r:r.replace(/\{n\}/g,String(t+1))}function Eh(e,t,r,n){const o=XT(e,r);if(o.length===0)return[];const s=new Set(o);return t.filter(i=>{const a=n(i);return!a||i.id===e.id||KT.has(i.type)?!1:s.has(a)})}function QT(e,t,r){if(e.type!=="sectionHeading"||!t?.length)return;const n=r(e);if(n)for(const o of t){const s=o.heading;if(s?.enabled&&s.headingFieldName===n)return s}}function Yl(e){return[...e].sort((t,r)=>{const n=t.position?.order??0,o=r.position?.order??0;if(n!==o)return n-o;const s=t.position?.column??1,i=r.position?.column??1;return s-i})}function ZT(e,t,r){if(!e?.length)return[];const n=e.filter(i=>i.showBorder===!0);if(n.length===0)return[];const o=new Map;for(const i of t){const a=r(i);a&&o.set(a,i)}const s=[];for(const i of n){const a=i.fieldNames.map(c=>o.get(c)).filter(c=>!!c);if(a.length===0)continue;const d=Yl(a).map(c=>r(c)).filter(Boolean);s.push({section:i,fieldNames:d})}return s}function Jo(e,t=0){return e.heading?.enabled?Ch(e.heading,t):e.name}function Th(e,t,r){if(e.type!=="sectionHeading")return!1;const n=t.heading;return!n?.enabled||!n.headingFieldName?!1:r(e)===n.headingFieldName}function e_(e,t){const r=typeof e.position?.order=="number"?e.position.order:0,n=(e.position?.column??1)-1,o=vo(e),s=Nc(e,t);return{row:r,col:n,rowEnd:r+o-1,colEnd:n+s-1}}function Xl(e,t){let r=1/0,n=-1/0,o=1/0,s=-1/0;for(const i of e){const{row:a,col:d,rowEnd:c,colEnd:l}=e_(i,t);r=Math.min(r,a),n=Math.max(n,c),o=Math.min(o,d),s=Math.max(s,l)}return Number.isFinite(r)?{minRow:r,maxRow:n,minCol:o,maxCol:s,rowSpan:n-r+1,colSpan:s-o+1}:null}function t_(e,t,r,n){const o=e.map(l=>t.find(f=>n(f)===l)).filter(l=>!!l&&typeof l.position?.order=="number");if(o.length===0)return null;const s=Xl(o,r);if(!s)return null;const i=o.filter(l=>l.type!=="sectionHeading"),a=i.length>0?i:o,d=Math.min(...a.map(l=>l.position?.order??0)),c=Math.max(1,...a.map(l=>(l.position?.order??d)-d+vo(l)));return{minRow:s.minRow,maxRow:s.maxRow,minCol:s.minCol,maxCol:s.maxCol,blockHeight:c}}function r_(e,t){return e.maxRow+1+t*e.blockHeight}function n_(e,t,r,n){const o=new Map;for(const a of t){const d=r(a);d&&o.set(d,a)}const s=new Map,i=new Set;for(const a of e){const d=a.fieldNames.map(v=>o.get(v)).filter(v=>!!v);if(d.length===0)continue;const c=d.filter(v=>!Th(v,a.section,r)),l=Xl(d,n);if(!l)continue;const{minRow:f,minCol:p,rowSpan:m,colSpan:b}=l,h=`${f}-${p}`;if(s.has(h))continue;const g=new Set;let w=!1;for(let v=f;v<=f+m-1;v++){for(let x=p;x<=p+b-1;x++){const A=`${v}-${x}`;if(i.has(A)){w=!0;break}g.add(A)}if(w)break}if(!w){for(const v of g)i.add(v);s.set(h,{anchorRow:f,anchorCol:p,rowSpan:m,colSpan:b,run:a,legend:Jo(a.section,0),renderFields:c.length>0?c:d})}}return{anchorsByOrigin:s,coveredCells:i}}function o_(e,t,r,n,o,s,i){const a=new Set(i),d=new Map;for(const c of e){const l=_h(c.linkedFields.map(p=>s(p)).filter(Boolean),t),f=l?.section;f?.fieldNames?.length?f.fieldNames:c.templateFieldNames,c.blockIds.forEach((p,m)=>{const b=r.filter(C=>C.id.endsWith(`__${p}`));if(b.length===0||!l)return;const h=Xl(b,o);if(!h)return;const{minRow:g,minCol:w,rowSpan:v,colSpan:x}=h,A=`${g}-${w}`;for(let C=g;C<=g+v-1;C++)for(let _=w;_<=w+x-1;_++)a.add(`${C}-${_}`);const I=l,T=Jo(f,m+1);d.set(A,{anchorRow:g,anchorCol:w,rowSpan:v,colSpan:x,run:I,legend:T,renderFields:Yl(b),addMoreMeta:{addMoreFieldName:c.addMoreFieldName,blockId:p,blockIndex:m}})})}return{anchorsByOrigin:d,coveredCells:a}}function s_(e,t,r,n){const o=`${e}-${t}`;return r.has(o)?!n.get(o):!1}function i_(e,t,r){for(const n of r.values())if(e>=n.anchorRow&&e<n.anchorRow+n.rowSpan&&t>=n.anchorCol&&t<n.anchorCol+n.colSpan)return n}function a_(e,t,r,n){return!(!n||r.run.section.collapsible!==!0||e===r.anchorRow&&t===r.anchorCol)}function l_(e,t,r){const n=new Set;for(const o of e.values())if(t(o))for(let s=o.anchorRow+1;s<o.anchorRow+o.rowSpan;s++)r(s,o)||n.add(s);return n}function c_(e,t,r){const n=o=>r.has(o)?"minmax(0, auto)":`minmax(${t}, auto)`;return Array.from({length:e},(o,s)=>n(s)).join(" ")}function d_(e,t){return new Map([...e,...t])}function u_(e,t,r){if(t.length===0)return e.map(i=>({kind:"field",field:i}));const n=new Map;for(const i of t)for(const a of i.fieldNames)n.set(a,i);const o=[];let s=0;for(;s<e.length;){const i=e[s],a=r(i),d=a?n.get(a):void 0;if(!d){o.push({kind:"field",field:i}),s+=1;continue}const c=[],l=new Set(d.fieldNames);for(;s<e.length;){const p=r(e[s]);if(!p||!l.has(p))break;const m=e[s];Th(m,d.section,r)||c.push(m),s+=1}if(c.length===0)continue;const f=o[o.length-1];f?.kind==="border"&&f.run.section.id===d.section.id?f.fields.push(...c):o.push({kind:"border",run:d,fields:c})}return o}function _h(e,t){if(!t?.length)return;const r=new Set(e);for(const n of t){if(n.showBorder!==!0)continue;const o=n.fieldNames.filter(s=>r.has(s));if(o.length>0)return{section:n,fieldNames:o}}}const f_=2*6e4,Nh=50;class p_{map=new Map;ttlMs;constructor(t){this.ttlMs=t}get(t){const r=this.map.get(t);if(!r)return null;const o=Date.now()-r.storedAtMs>this.ttlMs;return{value:r.value,isStale:o}}set(t,r){this.map.set(t,{value:r,storedAtMs:Date.now()}),this.enforceMax()}delete(t){this.map.delete(t)}clear(){this.map.clear()}enforceMax(){if(this.map.size<=Nh)return;const t=Array.from(this.map.entries());t.sort((n,o)=>n[1].storedAtMs-o[1].storedAtMs),t.slice(0,Math.max(0,this.map.size-Nh)).forEach(([n])=>this.map.delete(n))}}function m_(e){return(e??"").trim()||"default"}function kh(e){const t=m_(e.scope),r=String(e.formId??"").trim(),n=e.version===void 0||e.version===null?"latest":String(e.version).trim();return`form-render:${t}:${r}:${n}`}const Fh=new p_(f_);function Oh(e){const t=kh(e),r=Fh.get(t);return r?{value:r.value,isStale:r.isStale}:null}function Ph(e,t){const r=kh(e);Fh.set(r,t)}function Ih(e){const t={};for(const[n,o]of Object.entries(e)){if(o==null){t[n]=o;continue}if(Array.isArray(o)){t[n]=o;continue}if(typeof o=="object"&&!(o instanceof Date)){const s=o;typeof s.name=="string"&&typeof s.code=="string"?t[n]=`${s.code} ${s.name}`.trim():typeof s.name=="string"?t[n]=s.name:typeof s.code=="string"?t[n]=s.code:typeof s.short_code=="string"?t[n]=s.short_code:t[n]=s.name??s.code??"";continue}t[n]=o}const r=t.time_slot??e.time_slot;return typeof r=="string"&&r.includes(" - ")&&(t.start=r.split(" - ")[0].trim()),t}const Mh=({schema:e,formId:t,initialValues:r,onSubmit:n,onChange:o,onValidationError:s,onClose:i,mode:a="fill",className:d,children:c,gridLayout:l,unstyled:f=!1,workflowFormFields:p,submissionContext:m,onWorkflowSubmitResult:b,initialExtraSubmitPayload:h,onExtraSubmitPayloadChange:g,workflowStepId:w,viewerContext:v,getViewerContext:x,hideTableRowControls:A=!1,themeVars:I,dark:T=!1,omitRootWrapper:C=!1})=>{const _=On(k=>k.viewerContext),E=S.useMemo(()=>{if(v!==void 0)return v;const k=x?.();return k!==void 0?k:_},[v,x,_]),[O,N]=S.useState(e||null),[j,R]=S.useState(!!t&&!e),[M,B]=S.useState(null),P=e?.BFF_submit_api??M,[H,D]=S.useState(!1),[K,q]=S.useState({}),[L,z]=S.useState({}),[V,le]=S.useState({}),[re,ne]=S.useState({}),[Z,Y]=S.useState({}),[oe,ie]=S.useState(null),[G,ve]=S.useState(null),[be,He]=S.useState(!1),he=zi.useParams(),Ee=qt(k=>k.setValues),ae=qt(k=>k.setSubmitting),ye=qt(k=>k.formDisabled),je=S.useRef(!1),st=S.useRef(void 0),we=S.useMemo(()=>{if(!e)return null;const k=e;if(k.form&&Array.isArray(k.form.fields))try{return vi(k.form,k.form.fields,k.form.layout||null,k.form.rules||[])}catch{return e}if(Array.isArray(k.fields)&&k.fields.some(X=>typeof X.metadata=="string"&&X.metadata.startsWith("{")||X.fieldType&&!X.type))try{const X={id:k.id||k._id||"temp",name:k.name||"Form",version:k.version??1,status:k.status||"draft",createdAt:k.createdAt||new Date().toISOString(),updatedAt:k.updatedAt||new Date().toISOString(),createdBy:k.createdBy||"system",category:k.category||"",moduleId:k.moduleId,tenantId:k.tenantId,featureId:k.featureId,isDefault:k.isDefault||!1};return vi(X,k.fields,k.layout||null,k.rules||[])}catch{return e}return e},[e]);S.useEffect(()=>{if(e){const k=e;k.BFF_submit_api&&B(k.BFF_submit_api)}},[e]),S.useEffect(()=>{const k=$T(e,we);if(!k){ve(null),He(!1);return}if(!fh(k)){ve(null),He(!1);return}const $=Hl(k);if($.length>0){ve($),He(!1);return}if(p!=null&&p.length>0){ve(p),He(!1);return}const X=String(k.id??k._id??"").trim(),J=X?yh(X):void 0;if(J&&J.length>0){ve(J),He(!1);return}const te=Xo(k)??Xo(e)??P,me=typeof k.featureId=="string"?k.featureId:typeof k.feature_id=="string"?k.feature_id:void 0;let _e=!1;return He(!0),(async()=>{try{if(te){const Pe=await wh(te,{submissionContext:m,featureId:me,formId:X||void 0});if(!_e&&Array.isArray(Pe)&&Pe.length>0){ve(Pe);return}}if(X){const Pe=typeof k.version=="number"?k.version:void 0,nt=(await ih.getForRendering(X,Pe)).fields;if(!_e&&Array.isArray(nt)&&nt.length>0){ve(nt);return}}_e||ve(null)}catch{_e||ve(null)}finally{_e||He(!1)}})(),()=>{_e=!0,He(!1)}},[we,e,p,m,P]);const ct=S.useMemo(()=>{const k=we||O,$=k?xi(k,{workflowFormFields:p??(G!=null&&G.length>0?G:void 0)}):null;if(!$)return null;const X=$.layout,J=$.rules,te=$.clientMapping,me=(Array.isArray($.fields)?$.fields:[]).map(ze=>{let fe={...ze};if(ze.validationRules&&typeof ze.validationRules=="object"&&!ze.validation){const ke=ze.validationRules,Te=[];ke.required===!0&&Te.push({type:"required",message:"This field is required"}),ke.minLength!==void 0&&typeof ke.minLength=="number"&&Te.push({type:"minLength",value:ke.minLength,message:`Minimum length is ${ke.minLength}`}),ke.maxLength!==void 0&&typeof ke.maxLength=="number"&&Te.push({type:"maxLength",value:ke.maxLength,message:`Maximum length is ${ke.maxLength}`}),ke.pattern&&typeof ke.pattern=="string"&&Te.push({type:"pattern",value:ke.pattern,message:"Invalid format"}),ke.allowLetters!==void 0&&Te.push({type:"allowLetters",value:ke.allowLetters}),ke.allowNumbers!==void 0&&Te.push({type:"allowNumbers",value:ke.allowNumbers}),ke.allowSpecialChars!==void 0&&Te.push({type:"allowSpecialChars",value:ke.allowSpecialChars}),Te.length>0&&(fe={...fe,validation:Te})}const Ne=ze.required===!0||ze.isRequired===!0,Xe=Array.isArray(fe.validation)&&fe.validation.some(ke=>ke.type==="required");if(Ne&&!Xe){const ke={type:"required",message:"This field is required"},Te=Array.isArray(fe.validation)?fe.validation:[];fe={...fe,validation:[...Te,ke]}}if(ze.apidata&&typeof ze.apidata=="object"){const ke=ze.apidata,Te=fe.properties||{},$e=(fe.type||ze.fieldType)==="status";if(!Te.apiEndpoint&&ke.apiEndpoint){const ht={...Te,apiEndpoint:ke.apiEndpoint,apiMethod:ke.apiMethod,apiKey:ke.apiKey,apiRealtime:ke.apiRealtime,apiAutoDetect:ke.apiAutoDetect,apiLabelField:ke.apiLabelField,apiValueField:ke.apiValueField,apiQueryParams:ke.apiQueryParams,apiClientFilter:ke.apiClientFilter,valueSource:ke.valueSource||(ke.apiEndpoint?"api":void 0),optionsSource:ke.optionsSource||(ke.apiEndpoint?"api":void 0)};$e&&(ht.source=Te.source??"api",Te.statuses!==void 0&&(ht.statuses=Te.statuses),Te.dataPath!==void 0&&(ht.dataPath=Te.dataPath),Te.showStatusText!==void 0&&(ht.showStatusText=Te.showStatusText),Te.statusTextPath!==void 0&&(ht.statusTextPath=Te.statusTextPath),Te.showCurrentIndicator!==void 0&&(ht.showCurrentIndicator=Te.showCurrentIndicator)),fe={...fe,properties:ht}}}const Ke=["select","multiselect","radio","checkboxgroup"],Je=fe.type||ze.fieldType;if(Ke.includes(Je)){const ke=ze.options,Te=fe.properties?.options,$e=Array.isArray(Te)&&Te.length>0;if(Array.isArray(ke)&&ke.length>0&&!$e){const ht=fe.properties||{};fe={...fe,properties:{...ht,options:ke}}}}return fe}),_e=$.config?.rules,Pe=J&&Array.isArray(J)?J:_e&&Array.isArray(_e)?_e:[],Re=Pe.length>0?me.map(ze=>{if((ze.conditions&&Array.isArray(ze.conditions)?ze.conditions:[]).length>0)return ze;const Ne=ze.id??ze._id,Xe=ze.name||ze.key,Ke=Pe.filter(Te=>{const $e=typeof Te.targetFieldId=="object"?Te.targetFieldId?.id??Te.targetFieldId?._id:Te.targetFieldId;return $e?$e===Ne||$e===Xe||$e===ze.fieldKey:!1});if(Ke.length===0)return ze;const Je=[],ke=new Set;return Ke.forEach(Te=>{try{const $e=typeof Te.conditionExpression=="string"?JSON.parse(Te.conditionExpression):Te.conditionExpression;if(!$e||typeof $e!="object")return;!$e.id&&Te.id&&($e.id=Te.id);const ht=typeof Te.targetFieldId=="object"?Te.targetFieldId?.id??Te.targetFieldId?._id:Te.targetFieldId;$e.action&&(!$e.then||!Array.isArray($e.then)||$e.then.length===0)&&($e.then=[{action:$e.action,...ht&&{target:ht}}]),(!$e.then||!Array.isArray($e.then)||$e.then.length===0)&&Te.action&&($e.then=[{action:Te.action,...ht&&{target:ht}}]),$e.then&&Array.isArray($e.then)&&ht&&($e.then=$e.then.map(yt=>!yt.target&&ht?{...yt,target:ht}:yt));const dt=Te.conditionExpression??JSON.stringify($e);if(ke.has(dt))return;ke.add(dt),Je.push($e)}catch{}}),Je.length===0?ze:{...ze,conditions:Je}}):me;let nt=$.config||{submitAction:"database",layout:"default",autoSave:!0,validateOnChange:!0,showFieldErrors:"inline"};return!nt.layout&&X?typeof X=="object"&&X!==null?nt.layout="default":typeof X=="string"&&["default","card","compact"].includes(X)?nt.layout=X:nt.layout="default":nt.layout||(nt.layout="default"),J&&!nt.rules&&(nt.rules=J),te&&!nt.clientMapping&&(nt.clientMapping=te),{...$,fields:Re,config:nt}},[we,O,p,G]);S.useEffect(()=>{we&&we!==O&&N(we)},[we]),S.useEffect(()=>{if(t&&!e){const k=(Fn()??"").trim()||"default",$=Oh({scope:k,formId:t,version:"latest"});$?.value?.schema?(N($.value.schema),$.value.bffSubmitApi&&B($.value.bffSubmitApi),R(!1),$.isStale&&Le({background:!0})):Le({background:!1})}},[t,e]);const Le=async({background:k})=>{if(!t)return;const $=t;k||R(!0);try{const X=await ih.getForRendering(t),J=vi(X.form,X.fields,X.layout,X.rules);if($!==t)return;N(J),X.BFF_submit_api&&B(X.BFF_submit_api);const te=(Fn()??"").trim()||"default";Ph({scope:te,formId:$,version:"latest"},{schema:J,bffSubmitApi:X.BFF_submit_api})}catch{}finally{k||R(!1)}};if(j)return u.jsx("div",{className:"flex items-center justify-center py-12",children:u.jsx(ah,{})});if(!ct)return u.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Form not found"});const ee=ct,Ye=S.useMemo(()=>new Set(Object.keys(ee.config?.prepopulateApi?.fieldMapping??{})),[ee.config?.prepopulateApi?.fieldMapping]),et=S.useCallback(async k=>{const $=ee?.fields?.length?Cl(k,ee.fields):k;if(n){const X=m?{...$,...m}:$;return n(X)}return{success:!0}},[n,m,ee?.fields]),{values:Ue,errors:Q,touched:ce,isSubmitting:ue,isValid:xe,submitCount:Ae,currentStep:De,totalSteps:rt,completedSteps:vt,currentStepFields:Ge,isLastStep:ut,setFieldValue:We,setFieldTouched:mt,handleSubmit:tr,validateForm:kr,resetForm:Ht,nextStep:Fr,goToStep:jr,shouldShowField:on,isFieldEnabled:jt,isFieldRequired:vr,loadDraft:Bn}=Wc({schema:ee,initialValues:r,onSubmit:et,onChange:o,workflowStepId:w});gy({fields:ee.fields,values:Ue,buttonResponses:L,prepopulateResponse:oe,prepopulateResponseRules:ee.config?.prepopulateResponseRules});const wt=qt(k=>k.readOnlyFields),wr=qt(k=>k.editableFields),$n=S.useCallback(k=>wt.has(k),[wt]),Lt=S.useCallback(k=>wr.has(k),[wr]);S.useEffect(()=>{ee.config?.allowDraft&&a==="fill"&&Bn()},[ee.id]),S.useEffect(()=>{st.current=ee.id,je.current=!1,q({}),le({}),ne({}),Y({}),ie(null)},[ee.id]),S.useEffect(()=>{const k=ee.config?.prepopulateApi,$=!!(k?.fieldMapping&&Object.keys(k?.fieldMapping??{}).length>0),X=(ee.config?.prepopulateResponseRules?.length??0)>0;if(!k?.enabled||!k.apiEndpoint?.trim()||!$&&!X||je.current)return;je.current=!0;const J=ee.id;st.current=ee.id;let te=!1;return D(!0),(async()=>{try{const me=qt.getState().values,_e=typeof m=="object"&&m!==null?{...m,...h||{}}:h||{},Pe=de=>Yr(de,me,he,_e);let Re=Gr(Pe(k.apiEndpoint));if(k.apiQueryParams?.length){const de=new URLSearchParams;k.apiQueryParams.forEach(({key:Ce,value:Fe})=>de.append(Ce,Pe(Fe))),Re=`${Re}${Re.includes("?")?"&":"?"}${de.toString()}`}const nt={};k.apiHeaders?.forEach(({key:de,value:Ce})=>{de.trim()&&(nt[de]=Pe(Ce))}),nt["Content-Type"]=nt["Content-Type"]??"application/json";let Rt;if(k.apiMethod==="POST"&&k.apiBodyFields?.length){const de={};k.apiBodyFields.forEach(({key:Ce,value:Fe})=>{Ce.trim()&&(de[Ce]=Pe(Fe))}),Rt=JSON.stringify(de)}const ze=await fetch(Re,{method:k.apiMethod,headers:nt,body:k.apiMethod==="POST"?Rt:void 0});if(!ze.ok){const de=await ze.text();throw new Error(de||`HTTP ${ze.status}`)}const fe=await ze.json(),Ne=de=>{try{return de.split("?")[0].split("/").filter(Boolean).pop()||de}catch{return de}},Xe=(de,Ce)=>{if(de==null)return null;const Fe=typeof de=="string"?de:de instanceof Date?de.toISOString():null;if(!Fe)return null;const Qe=typeof de=="object"&&de instanceof Date?de:new Date(Fe);if(Number.isNaN(Qe.getTime()))return null;const ft=St=>String(St).padStart(2,"0");if(Ce==="date")return Fe.length>=10&&Fe[4]==="-"&&Fe[7]==="-"?Fe.slice(0,10):Qe.toISOString().slice(0,10);if(Ce==="time")return`${ft(Qe.getHours())}:${ft(Qe.getMinutes())}:${ft(Qe.getSeconds())}`;if(Ce==="datetime"){const St=Qe.getFullYear(),gt=Qe.getMonth()+1,Se=Qe.getDate(),Tt=Qe.getHours(),Ze=Qe.getMinutes(),Mt=Qe.getSeconds();return`${St}-${ft(gt)}-${ft(Se)}T${ft(Tt)}:${ft(Ze)}:${ft(Mt)}`}return null},Ke=(de,Ce)=>{const Fe=ee.fields.find(Se=>Se.name===de||Se.key===de);if(!Fe)return Ce;if((Fe.type==="file"||Fe.type==="camera"||Fe.type==="photoChoice")&&typeof Ce=="string"&&Ce.startsWith("http"))return{url:Ce,name:Ne(Ce)};if(Fe.type==="date"||Fe.type==="datetime"||Fe.type==="time"){const Se=Xe(Ce,Fe.type);if(Se!==null)return Se}if(Fe.type==="multiselect")return Array.isArray(Ce)?Ce.map(Se=>typeof Se=="string"?Se:String(Se)):typeof Ce=="string"?Ce.trim()===""?[]:Ce.includes(",")?Ce.split(",").map(Se=>Se.trim()).filter(Boolean):[Ce]:Ce!=null&&Ce!==""?[String(Ce)]:[];if(Fe.type!=="radio"&&Fe.type!=="select")return Ce;const Qe=Fe.properties?.options??Fe.options;if(!Array.isArray(Qe)||Qe.length===0)return Ce;const ft=Qe.map(Se=>Se.value);if(ft.includes(Ce))return Ce;const St=String(Ce);if(ft.includes(St))return St;const gt=Qe.find(Se=>Se.value==Ce);return gt?gt.value:Ce},Je=new Set(ee.fields.filter(de=>de.type==="table").map(de=>de.name||de.key)),ke=de=>de.name||de.key||de.id,Te={},$e=[],ht=[];for(const[de,Ce]of Object.entries(k?.fieldMapping??{})){if(!Ce?.trim()||de.startsWith("__"))continue;const Fe=pt(fe,Ce),Qe=de.indexOf(".");if(Qe>0&&Je.has(de.slice(0,Qe))){const St=de.slice(0,Qe),gt=de.slice(Qe+1);$e.push({tableName:St,columnName:gt,path:Ce});continue}if(Je.has(de)&&Array.isArray(Fe)&&Fe.length>0&&typeof Fe[0]=="object"&&Fe[0]!==null){const gt=ee.fields.find(Ze=>(Ze.name||Ze.key)===de)?.properties?.columns||[],Se=Fe.map(Ih),Tt=Ze=>(Ze||"").toLowerCase().replace(/\s+/g,"_").trim();Te[de]=Se.map(Ze=>{const Mt={};for(const ar of gt){const Rn=ar.name??"";Mt[Rn]=Ze[Tt(Rn)]??Ze[Rn]}return Mt});continue}if(Fe!=null&&(Te[de]=Ke(de,Fe)),Fe==null)continue;let ft=Fe;if(Array.isArray(Fe)){const St=ee.fields.find(gt=>ke(gt)===de);if(St?.type==="addmore"){ht.push({addMoreFieldName:de,array:Fe});continue}if(St?.type==="multiselect"){const gt=k.multiselectArrayPropertyMap?.[de];gt&&Fe.length>0&&Fe.some(Se=>Se!=null&&typeof Se=="object")&&(ft=Fe.map(Se=>Se!=null&&typeof Se=="object"&> in Se?Se[gt]:void 0).filter(Se=>Se!=null))}}Te[de]=Ke(de,ft)}const dt={},yt={},It={};for(const{addMoreFieldName:de,array:Ce}of ht){const Fe=ee.fields.find(Tt=>ke(Tt)===de);if(!Fe||Fe.type!=="addmore")continue;const Qe=Eh(Fe,ee.fields,ee.config?.sections,ke);if(Qe.length===0)continue;const ft=k.addMoreFieldKeyMap?.[de],St=Ce.length>0&&Ce[0]!=null&&typeof Ce[0]=="object"?Ce[0]:null;if(St)for(const Tt of Qe){const Ze=ke(Tt),Mt=ft&&ft[Ze]||Ze,ar=St[Mt];ar!=null&&(Te[Ze]=Ke(Ze,ar))}const gt=Ce.slice(1),Se=gt.map((Tt,Ze)=>`prepop_${de}_${Ze}_${Date.now()}`);Se.length>0&&(yt[de]=Se);for(let Tt=0;Tt<gt.length;Tt++){const Ze=gt[Tt];if(Ze==null||typeof Ze!="object")continue;const Mt=Ze,ar=Mt.id;ar!=null&&String(ar).trim()!==""&&(It[`${de}__${Se[Tt]}`]=String(ar));for(const Rn of Qe){const Ri=ke(Rn),R_=ft&&ft[Ri]||Ri,nc=Mt[R_];if(nc==null)continue;const z_=`${Ri}__addmore__${de}__${Se[Tt]}`;dt[z_]=Ke(Ri,nc)}}}Object.keys(yt).length>0&&le(de=>({...de,...yt})),Object.keys(It).length>0&&Y(de=>({...de,...It}));const Ft=de=>(de||"").toLowerCase().replace(/\s+/g,"_").trim(),Ur=[...new Set($e.map(de=>de.tableName))];for(const de of Ur){if(Array.isArray(Te[de]))continue;const Ce=$e.find(Se=>Se.tableName===de);if(!Ce?.path?.includes("."))continue;const Fe=Ce.path.replace(/\.[^.]+$/,""),Qe=pt(fe,Fe);if(!Array.isArray(Qe)||Qe.length===0||typeof Qe[0]!="object"||Qe[0]===null)continue;const St=ee.fields.find(Se=>(Se.name||Se.key)===de)?.properties?.columns||[],gt=Qe.map(Ih);Te[de]=gt.map(Se=>{const Tt={};for(const Ze of St){const Mt=Ze.name??"",ar=Ft(Mt),Rn=Se[ar]??Se[Mt];Tt[Mt]=Rn}return Tt})}const Xr=(de,Ce)=>{const Fe=pt(fe,de);if(Array.isArray(Fe))return Fe;if(Fe!=null)return[Fe];if(!de.includes("."))return[];const Qe=de.replace(/\.[^.]+$/,""),ft=pt(fe,Qe);return!Array.isArray(ft)||ft.length===0||typeof ft[0]!="object"||ft[0]===null?[]:ft.map(St=>{const gt=St[Ce];if(gt!==null&&typeof gt=="object"&&!Array.isArray(gt)&&!(gt instanceof Date)){const Se=gt;return typeof Se.name=="string"&&typeof Se.code=="string"?`${Se.code} ${Se.name}`.trim():typeof Se.name=="string"?Se.name:typeof Se.code=="string"?Se.code:typeof Se.short_code=="string"?Se.short_code:Se.name??Se.code??""}return gt})};for(const{tableName:de,columnName:Ce,path:Fe}of $e){const Qe=Xr(Fe,Ce),St=ee.fields.find(Ze=>(Ze.name||Ze.key)===de)?.properties?.columns||[],gt=St.find(Ze=>(Ze.name||"").toLowerCase()===Ce.toLowerCase())?.name??Ce;let Se=Array.isArray(Te[de])?Te[de]:[];const Tt=Math.max(Se.length,Qe.length);if(Tt>Se.length)for(Se=[...Se];Se.length<Tt;){const Ze={};St.forEach(Mt=>{Ze[Mt.name||""]=""}),Se.push(Ze)}else Se=Se.map(Ze=>({...Ze}));Qe.forEach((Ze,Mt)=>{Se[Mt]&&(Se[Mt][gt]=Ze)}),Te[de]=Se}if(st.current===J){if(Object.keys(Te).length>0||Object.keys(dt).length>0){const Mt={...qt.getState().values,...Te,...dt};Ee(Mt)}const Ce=pt(fe,"data.user_id"),Fe=pt(fe,"data.items"),Qe=pt(fe,"data");let ft=Array.isArray(Fe)&&Fe.length>0&&Fe[0]!=null&&typeof Fe[0]=="object"&&Fe[0].id?Fe[0].id:void 0;ft===void 0&&Array.isArray(Qe)&&Qe.length>0&&Qe[0]!=null&&typeof Qe[0]=="object"&&Qe[0].id&&(ft=Qe[0].id),ft===void 0&&(ft=pt(fe,"data.0.id"));const St=VT(fe,{treatFirstItemIdAsPaymentId:k?.treatFirstItemIdAsPaymentId===!0}),gt=pt(fe,"data.id"),Se=pt(fe,"data.batch_id"),Tt=pt(fe,"data.program_id"),Ze={};Ce!=null&&(Ze.context_user_id=Ce),ft!=null&&ft!==""&&(Ze.documentId=ft),gt!=null&&String(gt).trim()!==""&&(m?.id===void 0||m?.id===null)&&(Ze.id=gt),Se!=null&&String(Se).trim()!==""&&((m?.admission_batch_id===void 0||m?.admission_batch_id===null)&&(Ze.admission_batch_id=Se),(m?.batch_id===void 0||m?.batch_id===null)&&(Ze.batch_id=Se)),Tt!=null&&String(Tt).trim()!==""&&(m?.program_id===void 0||m?.program_id===null)&&(Ze.program_id=Tt),St!=null&&String(St).trim()!==""&&(m?.payment_id===void 0||m?.payment_id===null)&&(Ze.payment_id=St),Object.keys(Ze).length>0&&q(Mt=>{const ar={...Mt,...Ze};return g?.(ar),ar}),ie(fe)}}catch(me){te||xl(me,"Prepopulate request failed.",Wo)}finally{D(!1)}})(),()=>{te=!0}},[ee.id,ee.config?.prepopulateApi?.enabled,ee.config?.prepopulateApi?.apiEndpoint,ee.config?.prepopulateApi?.apiMethod,JSON.stringify(ee.config?.prepopulateApi?.fieldMapping),ee.config?.prepopulateApi?.treatFirstItemIdAsPaymentId,m,h,he,Ee,le]),S.useEffect(()=>{Object.keys(Q).length>0&&s?.(Q)},[Q,s]);const Sr=rt>1,Jt=a==="view",rr=S.useCallback((k,$)=>Jt||!!$&&!Lt(k)||$n(k)&&!Lt(k),[Jt,Lt,$n]),sn=ee.fields.filter(k=>!k.parentId),Ct=[...Sr?Ge:sn.length>0?sn:ee.fields].filter(k=>!(!k||typeof k!="object"||!k.name&&!k.key)).sort((k,$)=>{const X=typeof k.position?.order=="number"?k.position.order:typeof k.positionOrder=="number"?k.positionOrder:Number.MAX_SAFE_INTEGER,J=typeof $.position?.order=="number"?$.position.order:typeof $.positionOrder=="number"?$.positionOrder:Number.MAX_SAFE_INTEGER;if(X!==J)return X-J;const te=typeof k.position?.column=="number"?k.position.column:1,me=typeof $.position?.column=="number"?$.position.column:1;return te-me}),Qo=S.useCallback(k=>{const $=qt.getState().errors,X=Object.keys($).find(J=>k.includes(J));X&&requestAnimationFrame(()=>{document.querySelector(`[data-field-name="${X}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})})},[]),xr=async k=>{if(k?.preventDefault(),Sr&&!ut){if(!await Fr())try{const J=qt.getState().errors;Dt.toast.error(Al(J,ee.fields)||"Please fix the errors before continuing."),Qo(Ct.map(te=>te.name||te.key||te.id).filter(Boolean))}catch{Dt.toast.error("Please fix the errors before continuing.")}return}const $=await tr(k);if($&&$.success===!1&&$.errors?.length)try{const X=qt.getState().errors;Dt.toast.error(Al(X,ee.fields)||"Submission failed. Please check the form."),Qo(Ct.map(J=>J.name||J.key||J.id).filter(Boolean))}catch{Dt.toast.error("Submission failed. Please check the form.")}return $},Or=S.useCallback(()=>{Ht(),i&&i()},[Ht,i]),Ar=S.useCallback((k,$)=>{const X=ee.fields.find(te=>te.type==="button"&&(te.name===k||te.key===k)),J=GT($,X);J!=null&&String(J).trim()!==""&&(m?.payment_id===void 0||m?.payment_id===null)&&q(te=>{const me={...te,payment_id:J};return g?.(me),me}),z(te=>{const me={...te,[k]:$};return!Co($)||!(X?.type==="button"&&X.properties?.action==="submit")||ee.fields.filter(Re=>Re.type==="editButton").map(Re=>Re.name).forEach(Re=>delete me[Re]),me})},[ee.fields,m,g]),fr=S.useCallback(async()=>await kr(),[kr]),Wt=S.useCallback(()=>qt.getState().errors,[]),Qt=S.useMemo(()=>({...h||{},...K}),[h,K]),Pr=S.useMemo(()=>({...typeof m=="object"&&m!==null?m:{},...Qt}),[m,Qt]),_i=ee.config?.layout??ee.layout??"default",Ni=["default","card","compact"].includes(_i)?_i:"default",ki={default:"",card:"bg-card border rounded-lg shadow-sm p-6",compact:"space-y-2"},Zo=S.useMemo(()=>{if(C)return;const k=ee.config?.theme?.cssVariables;if(!(!k&&!I))return{...k??{},...I??{}}},[C,ee.config?.theme?.cssVariables,I]),Cr=S.useMemo(()=>Wi({config:ee.config,layout:ee.layout},l),[ee.config,ee.layout,l]),Oe=S.useMemo(()=>Cr?{...Cr,verticalSpacing:Cr.verticalSpacing??Cr.spacing??"16px",horizontalSpacing:Cr.horizontalSpacing??Cr.spacing??"16px",rowHeight:Cr.rowHeight??zn}:null,[Cr]),F=Oe!==null,se=Oe?.rows??8,pe=Oe?.columns??3,it=Oe?.verticalSpacing??Oe?.spacing??"16px",Nt=Oe?.horizontalSpacing??Oe?.spacing??"16px",Et=Oe?.rowHeight??zn,Pt=S.useCallback(k=>{if(!E)return!0;const $=k.visibility;if(!$)return!0;const X=$.visibleToUserType??$.user_type,J=$.visibleToUserRole??$.user_role,te=Array.isArray($.visibleToUserIds)?$.visibleToUserIds:Array.isArray($.users)?$.users:[],me=Array.isArray($.hiddenFromUserIds)?$.hiddenFromUserIds:[];if(Array.isArray(me)&&me.length>0&&E.userId!=null&&me.includes(E.userId))return!1;if(te.length>0&&E.userId!=null&&te.includes(E.userId))return!0;const _e=X!=null&&X!==""&&E.userType!=null&&E.userType!==X,Pe=J!=null&&J!==""&&E.role!=null&&E.role!==J,Re=te.length>0&&(E.userId==null||!te.includes(E.userId));return!(_e||Pe||Re)},[E]),Ut=k=>{if(!Pt(k))return!1;const $=k.name||k.key||k.id,X=k.hidden===!0;return on($)||!X&&$},kt=ee.config?.sections,lt=S.useCallback(k=>k.name||k.key||k.id,[]),xt=S.useCallback(k=>{let $=k;if(k.type==="table"){const J=k.properties?.columns;if(Array.isArray(J)&&J.length>0){const te=J.filter(me=>Pt(me));$={...k,properties:{...k.properties,columns:te}}}}const X=QT($,kt,lt);return X?{...$,label:Ch(X,0)}:$},[Pt,kt,lt]),Ir=S.useCallback(k=>Eh(k,ee.fields,kt,lt),[ee.fields,kt,lt]),pr=S.useCallback((k,$,X)=>`${k}__addmore__${$}__${X}`,[]),Fi=S.useCallback((k,$)=>`${k}__${$??"base"}`,[]),Oi=S.useCallback((k,$)=>{const X=Fi(k.id,$);return re[X]??k.defaultCollapsed??!1},[re,Fi]),Zl=S.useCallback((k,$,X)=>{const J=Fi(k,$);ne(te=>te[J]===X?te:{...te,[J]:X})},[Fi]),Pi=S.useMemo(()=>{const k=[],$=ee.fields.filter(X=>X.type==="addmore");for(const X of $){const J=lt(X),me=Ir(X).find(nt=>{if(nt.type!=="button")return!1;const Rt=nt.properties,ze=nt.metadata;let fe=Rt?.action;if(!fe&&ze!=null)try{fe=(typeof ze=="string"?JSON.parse(ze):ze)?.action}catch{}return fe==="upload"||fe==="custom"});if(!me)continue;const _e=lt(me),Pe=V[J]||[],Re=pt(L[_e],"data.id")??pt(L[_e],"data.documentId")??K.documentId;Re!=null&&String(Re).trim()!==""&&k.push(String(Re));for(const nt of Pe){const Rt=pr(_e,J,nt),ze=pt(L[Rt],"data.id")??pt(L[Rt],"data.documentId"),fe=Z[`${J}__${nt}`],Ne=ze??fe;Ne!=null&&String(Ne).trim()!==""&&k.push(String(Ne))}}return k},[ee.fields,V,L,Z,K.documentId,lt,Ir,pr]);S.useEffect(()=>{q(k=>{const $={...k,document_ids:Pi},X=k.document_ids;return Array.isArray(X)&&X.length===Pi.length&&Pi.every((J,te)=>X[te]===J)?k:$})},[Pi]);const Ii=S.useCallback((k,$,X,J)=>{for(const te of X){const me=lt(te),_e=pr(me,k,$),Pe=J[_e];if(Pe==null)continue;const Re=te.type;if(Re==="file"||Re==="camera"||Re==="photoChoice"){if(typeof Pe=="object"&&Pe!==null&&("url"in Pe||"name"in Pe)||Array.isArray(Pe)&&Pe.length>0)return!0;continue}if(Array.isArray(Pe)){if(Pe.length>0)return!0;continue}if(typeof Pe=="string"&&Pe.trim()!==""||typeof Pe=="number"&&!Number.isNaN(Pe)||typeof Pe=="boolean"||typeof Pe=="object"&&Pe!==null&&Object.keys(Pe).length>0)return!0}return!1},[lt,pr]),jn=S.useCallback(k=>{const $=lt(k);if(!$)return;if(Ir(k).length===0){Dt.toast.error("No linked fields configured for this Add More button.");return}const J=`${Date.now()}_${Math.random().toString(36).slice(2,8)}`;le(te=>({...te,[$]:[...te[$]||[],J]}))},[lt,Ir]),Mi=S.useCallback((k,$)=>{le(X=>{const J=X[k]||[],te=J.filter(me=>me!==$);if(te.length===J.length)return X;if(te.length===0){const me={...X};return delete me[k],me}return{...X,[k]:te}})},[]),Li=S.useMemo(()=>Ct.filter(k=>!k.parentId),[Ct]),bn=S.useMemo(()=>{const k=[];return Ct.filter(X=>X.type==="addmore").sort((X,J)=>{const te=X.position?.order??0,me=J.position?.order??0;return te-me}).forEach(X=>{const J=lt(X),te=X.position?.order??0,me=V[J]||[],_e=Ir(X).sort((Xe,Ke)=>{const Je=Xe.position?.order??0,ke=Ke.position?.order??0;return Je!==ke?Je-ke:(Xe.position?.column??1)-(Ke.position?.column??1)});if(_e.length===0)return;const Pe=Ah(X,kt),Re=Pe[0]?.fieldNames?.length?Pe[0].fieldNames:_e.map(Xe=>lt(Xe)).filter(Boolean),nt=t_(Re,Li,pe,lt),Rt=Math.min(..._e.map(Xe=>Xe.position?.order??0)),ze=Math.max(1,..._e.map(Xe=>(Xe.position?.order??Rt)-Rt+vo(Xe))),fe=nt?.blockHeight??ze,Ne=me.length*fe;k.push({addMoreFieldName:J,baseOrder:te,blockHeight:fe,blockIds:me,linkedFields:_e,insertedRows:Ne,templateFieldNames:Re,templateBounds:nt})}),k},[Ct,Li,pe,lt,V,Ir,kt]),ec=S.useMemo(()=>({}),[]),Di=S.useMemo(()=>bn.length===0?Ct:Ct.map(k=>{const $=k.position?.order??0,X=bn.reduce((J,te)=>{const me=te.templateBounds?.maxRow??te.baseOrder;return $>me?J+te.insertedRows:J},0);return X===0?k:{...k,position:{...k.position,order:$+X}}}),[Ct,bn]),Bi=S.useCallback(k=>{const $={};return Object.entries(L).forEach(([X,J])=>{const te=k[X];te&&($[te]=J)}),$},[L]),yo=S.useMemo(()=>{const k=[],$={};return bn.forEach(X=>{const{addMoreFieldName:J,blockIds:te,linkedFields:me,blockHeight:_e,templateBounds:Pe}=X,Re=Math.min(...me.map(ze=>ze.position?.order??0)),Rt=ee.fields.find(ze=>lt(ze)===J&&ze.type==="addmore")?.properties;te.forEach((ze,fe)=>{const Ne={},Xe={},Ke={},Je=Pe?r_(Pe,fe):X.baseOrder+1+fe*_e,ke=Z[`${J}__${ze}`];me.forEach($e=>{const ht=lt($e),dt=pr(ht,J,ze),yt=($e.position?.order??Re)-Re;if(Ne[dt]=ht,Xe[dt]=Ue[dt],!(Rt?.linkedFieldAllowDuplicate?.[ht]??!0)&&($e.type==="select"||$e.type==="radio"||$e.type==="multiselect")){const Ft=[],Ur=Ue[ht];Ur!=null&&Ur!==""&&(Array.isArray(Ur)?Ft.push(...Ur.map(Jr=>String(Jr))):Ft.push(String(Ur))),te.filter(Jr=>Jr!==ze).forEach(Jr=>{const de=pr(ht,J,Jr),Ce=Ue[de];Ce!=null&&Ce!==""&&(Array.isArray(Ce)?Ft.push(...Ce.map(Fe=>String(Fe))):Ft.push(String(Ce)))}),Ft.length>0&&(Ke[dt]=[...new Set(Ft)])}k.push({...$e,id:`${$e.id}__${ze}`,name:dt,position:{...$e.position,order:Je+yt}})});const Te=Bi(Ne);Object.keys(Ne).forEach($e=>{$[$e]={scopedFormValues:Xe,scopedFieldNameMap:Ne,scopedButtonResponses:Te,...ke!=null&&{blockDocumentId:ke},...Ke[$e]&&{excludedOptionValues:Ke[$e]}}})})}),{clonedFields:k,scopeByFieldName:$}},[bn,Z,lt,pr,Ue,Bi,ee.fields]),es=S.useMemo(()=>[...Di,...yo.clonedFields].sort((k,$)=>{const X=k.position?.order??0,J=$.position?.order??0;if(X!==J)return X-J;const te=k.position?.column??1,me=$.position?.column??1;if(te!==me)return te-me;const _e=k.position?.cellSlot??0,Pe=$.position?.cellSlot??0;return _e!==Pe?_e-Pe:String(k.id).localeCompare(String($.id))}),[Di,yo.clonedFields]),$i=S.useMemo(()=>jT(es.filter(k=>!k.parentId),Ut),[es,Ut]),tc=S.useCallback((k,$)=>$i.some(X=>UT(k,$,X,pe)),[$i,pe]),$_=$i.length===0?0:Math.max(...$i.map(k=>(k[0]?.position?.order??0)+Ei(k,pe).rowSpan)),rc=Math.max(se,$_,1),ji=S.useMemo(()=>ZT(kt,Yl(Ct.filter(k=>!k.parentId)),lt),[kt,Ct,lt]),{anchorsByOrigin:qh,coveredCells:Gh}=S.useMemo(()=>n_(ji,Di,lt,pe),[ji,Di,lt,pe]),{anchorsByOrigin:Kh,coveredCells:Yh}=S.useMemo(()=>o_(bn.map(k=>({addMoreFieldName:k.addMoreFieldName,blockIds:k.blockIds,linkedFields:k.linkedFields,templateFieldNames:k.templateFieldNames})),kt,yo.clonedFields,Li,pe,lt,Gh),[bn,kt,yo.clonedFields,Li,pe,lt,Gh]),Un=S.useMemo(()=>d_(qh,Kh),[qh,Kh]),Xh=S.useMemo(()=>Yh,[Yh]),Jh=String(Et).endsWith("px")?Et:zn,Qh=S.useCallback((k,$)=>{for(let X=0;X<pe;X++){if(X>=$.anchorCol&&X<$.anchorCol+$.colSpan)continue;if(ec[`${k}-${X}`]||Un.get(`${k}-${X}`)||xh(k,X,es,Ut).length>0||tc(k,X))return!0}return!1},[pe,ec,Un,es,Ut,tc]),Zh=S.useMemo(()=>l_(Un,k=>{const $=k.run.section;return $.collapsible?Oi($,k.addMoreMeta?.blockId):!1},Qh),[Un,Oi,Qh]),j_=S.useMemo(()=>c_(rc,Jh,Zh),[rc,Jh,Zh]),U_=S.useMemo(()=>u_(Ct.filter(k=>!k.parentId&&Ut(k)),ji,lt),[Ct,ji,lt,Ut]),Ui=S.useCallback(k=>{if(F)return null;const $=lt(k),X=V[$]||[];if(X.length===0)return null;const J=Ir(k);if(J.length===0)return null;const te=JT(k,kt),me=J.map(Re=>lt(Re)).filter(Boolean),_e=_h(me,kt),Pe=(Re,nt,Rt,ze,fe,Ne,Xe)=>{const Ke=lt(Re),Je=pr(Ke,$,nt),ke=Re.hidden===!0;if(!(Pt(Re)&&(on(Ke)||!ke&&Ke)))return null;const $e={...Re,id:`${Re.id}__${nt}`,name:Je},dt=k.properties?.linkedFieldAllowDuplicate?.[Ke]??!0;let yt;if(!dt&&(Re.type==="select"||Re.type==="radio"||Re.type==="multiselect")){const It=[],Ft=Ue[Ke];Ft!=null&&Ft!==""&&(Array.isArray(Ft)?It.push(...Ft.map(Xr=>String(Xr))):It.push(String(Ft))),X.filter(Xr=>Xr!==nt).forEach(Xr=>{const Jr=pr(Ke,$,Xr),de=Ue[Jr];de!=null&&de!==""&&(Array.isArray(de)?It.push(...de.map(Ce=>String(Ce))):It.push(String(de)))}),It.length>0&&(yt=[...new Set(It)])}return u.jsx("div",{"data-field-name":Je,"data-form-renderer":"field-wrapper",children:u.jsx(nn,{field:$e,value:Ue[Je],error:ce[Je]||Ae>0?Q[Je]:void 0,onChange:It=>We(Je,It),onBlur:()=>mt(Je),disabled:ye||!jt(Ke)||Jt||!!Re.disabled,readOnly:rr(Ke,!!Re.readOnly),isRequired:vr(Ke),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:Je,buttonResponses:Ne,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:Xe,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,scopedFormValues:fe,scopedFieldNameMap:ze,excludedOptionValues:yt,hideTableRowControls:A})},$e.id)};return u.jsx("div",{className:"space-y-3 mt-3",children:X.map((Re,nt)=>{const Rt={},ze={};J.forEach(yt=>{const It=lt(yt),Ft=pr(It,$,Re);Rt[Ft]=It,ze[Ft]=Ue[Ft]});const fe=Bi(Rt),Ne=Ii($,Re,J,Ue),Xe=te?.heading!=null?Jo(te,nt+1):null,Ke=Z[`${$}__${Re}`],Je=Ke!=null?{...Qt,documentId:Ke}:Qt,ke=J.map(yt=>Pe(yt,Re,nt,Rt,ze,fe,Je)).filter(Boolean),$e=_e?.section?.collapsible===!0,ht=u.jsx("button",{type:"button",className:"inline-flex shrink-0 rounded-md p-1.5 text-destructive hover:bg-destructive/10 focus:outline-none focus:ring-2 focus:ring-ring disabled:pointer-events-none disabled:opacity-40",disabled:Ne,title:Ne?"Cannot remove: this entry has data":"Remove entry","aria-label":"Remove entry",onClick:yt=>{yt.preventDefault(),yt.stopPropagation(),Mi($,Re)},children:u.jsx(ko,{className:"h-5 w-5","aria-hidden":!0})}),dt=u.jsxs(u.Fragment,{children:[!$e&&u.jsxs("div",{className:"flex items-center justify-between gap-2",children:[Xe?u.jsx("p",{className:"text-sm font-medium text-foreground",children:Xe}):u.jsxs("p",{className:"text-xs text-muted-foreground",children:["Entry ",nt+1]}),ht]}),ke]});return u.jsx("div",{className:"rounded-md border p-3 space-y-3",children:_e?u.jsx(zl,{legend:_e.section.heading?.enabled?Jo(_e.section,nt+1):_e.section.name,collapsible:_e.section.collapsible,defaultCollapsed:_e.section.defaultCollapsed,headerActions:$e?ht:void 0,onCollapsedChange:yt=>Zl(_e.section.id,Re,yt),children:dt}):dt},`${k.id}-${Re}`)})})},[F,V,Z,lt,Ir,pr,Ii,Ue,ce,Ae,Q,We,mt,jt,Jt,vr,Pr,Ye,Ar,xr,Ht,Or,ue,P,b,Qt,fr,Wt,ee.fields,ae,on,Pt,Bi,Mi,A,kt,he,oe,H]);return u.jsx("div",{className:C?W("relative",d):W(Hi,T&&"dark",d),style:Zo,"data-form-renderer":C?void 0:"root",children:u.jsxs("div",{className:"relative",children:[(H||be)&&u.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/60 rounded-md",children:u.jsx(ah,{})}),u.jsxs("form",{onSubmit:xr,className:f?W("w-full min-w-0"):W("space-y-6 pb-[100px] w-full min-w-0",ki[Ni]),"data-form-renderer":"form","data-form-renderer-layout":F?"grid":"stack",children:[Sr&&ee.steps&&u.jsx(yT,{steps:ee.steps,currentStep:De,completedSteps:vt,onStepClick:jr}),u.jsx(ra.Provider,{value:{gridStretch:F},children:F?u.jsx("div",{className:f?"w-full min-w-0":"grid w-full min-w-0",style:{display:"grid",gridTemplateRows:j_,gridTemplateColumns:`repeat(${pe}, 1fr)`,rowGap:it,columnGap:Nt},"data-form-renderer":"grid",children:Array.from({length:rc},(k,$)=>Array.from({length:pe},(X,J)=>{if(tc($,J))return u.jsx("div",{className:"min-w-0 min-h-0",style:{gridRow:$+1,gridColumn:J+1,visibility:"hidden",pointerEvents:"none"},"data-form-renderer":"grid-cell","data-form-renderer-empty":!0},`empty-${$}-${J}`);if(s_($,J,Xh,Un)){const fe=i_($,J,Un);return fe&&a_($,J,fe,Oi(fe.run.section,fe.addMoreMeta?.blockId))?null:u.jsx("div",{className:"min-w-0 min-h-0",style:{gridRow:$+1,gridColumn:J+1,visibility:"hidden",pointerEvents:"none"},"data-form-renderer":"grid-cell","data-form-renderer-empty":!0},`section-border-cover-${$}-${J}`)}const te=Un.get(`${$}-${J}`);if(te){const fe=te.renderFields.filter(dt=>Ut(dt)),Ne=te.addMoreMeta,Xe=Ne!=null?bn.find(dt=>dt.addMoreFieldName===Ne.addMoreFieldName)?.linkedFields??[]:[],Ke=Ne!=null?Ii(Ne.addMoreFieldName,Ne.blockId,Xe,Ue):!1,Je=te.run.section,ke=Ne?.blockId,Te=Oi(Je,ke),$e=Je.collapsible&&Te?1:te.rowSpan,ht=Ne!=null?u.jsx("button",{type:"button",className:W("inline-flex shrink-0 rounded-md p-1.5 text-destructive hover:bg-destructive/10 focus:outline-none focus:ring-2 focus:ring-ring disabled:pointer-events-none disabled:opacity-40",f&&"text-red-600 hover:bg-red-500/10"),disabled:Ke,title:Ke?"Cannot remove: this entry has data":"Remove entry","aria-label":"Remove entry",onClick:dt=>{dt.preventDefault(),dt.stopPropagation(),Mi(Ne.addMoreFieldName,Ne.blockId)},children:u.jsx(ko,{className:"h-5 w-5","aria-hidden":!0})}):void 0;return u.jsx("div",{className:W("min-h-0 min-w-0",!(Je.collapsible&&Te)&&"self-stretch"),style:{gridRow:`${$+1} / span ${$e}`,gridColumn:`${J+1} / span ${te.colSpan}`},"data-form-renderer":"grid-cell","data-form-renderer-config-section-border-cell":!0,children:u.jsx(zl,{legend:te.legend,className:Je.collapsible&&Te?void 0:"h-full",collapsible:Je.collapsible,defaultCollapsed:Je.defaultCollapsed,headerActions:ht,onCollapsedChange:dt=>Zl(Je.id,ke,dt),children:u.jsx("div",{className:"grid w-full min-w-0",style:{gridTemplateColumns:`repeat(${pe}, 1fr)`,gridTemplateRows:`repeat(${te.rowSpan}, minmax(${String(Et).endsWith("px")?Et:zn}, auto))`,rowGap:it,columnGap:Nt},children:fe.map(dt=>{const yt=lt(dt),It=yo.scopeByFieldName[yt],Ft=It?.scopedFieldNameMap?.[yt]||yt,Ur=(dt.position?.order??te.anchorRow)-te.anchorRow,Xr=dt.position?.column??1,{rowSpan:Jr,columnSpan:de}=Ei([dt],pe),Ce=Ne!=null?Z[`${Ne.addMoreFieldName}__${Ne.blockId}`]:void 0,Fe=Ce!=null?{...Qt,documentId:Ce}:Qt;return u.jsx("div",{"data-field-name":yt,"data-form-renderer":"field-wrapper",className:"min-h-0 min-w-0",style:{gridRow:`${Ur+1} / span ${Jr}`,gridColumn:`${Xr} / span ${de}`,...dn(dt)},children:u.jsx(nn,{field:xt(dt),value:Ue[yt],error:ce[yt]||Ae>0?Q[yt]:void 0,onChange:Qe=>We(yt,Qe),onBlur:()=>mt(yt),disabled:dt.type==="table"&&a==="fill"?!1:ye||!jt(Ft)||Jt||!!dt.disabled,readOnly:dt.type==="table"&&a==="fill"?!1:rr(Ft,!!dt.readOnly),isRequired:vr(Ft),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:yt,buttonResponses:It?.scopedButtonResponses??L,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:Fe,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,onAddMore:jn,scopedFormValues:It?.scopedFormValues,scopedFieldNameMap:It?.scopedFieldNameMap,excludedOptionValues:It?.excludedOptionValues,hideTableRowControls:A})},dt.id)})})})},`section-border-${te.run.section.id}-${$}-${J}-${Ne?.blockId??"base"}`)}const me=xh($,J,es,Ut).filter(fe=>!(lt(fe)?.includes("__addmore__")&&Xh.has(`${$}-${J}`)));if(me.length===0){const fe=ec[`${$}-${J}`];if(fe){const Ne=ee.fields.find(Je=>Je.type==="addmore"&<(Je)===fe.addMoreFieldName),Xe=Ne!=null?Ir(Ne):[],Ke=Ii(fe.addMoreFieldName,fe.blockId,Xe,Ue);return u.jsx("div",{className:"min-h-0 min-w-0 flex flex-col items-center justify-center",style:{gridRow:$+1,gridColumn:J+1},"data-form-renderer":"grid-cell","data-form-renderer-add-more-remove":!0,children:u.jsx("button",{type:"button",className:W("inline-flex shrink-0 rounded-md p-1.5 text-destructive hover:bg-destructive/10 focus:outline-none focus:ring-2 focus:ring-ring disabled:pointer-events-none disabled:opacity-40",f&&"text-red-600 hover:bg-red-500/10"),disabled:Ke,title:Ke?"Cannot remove: this entry has data":"Remove entry","aria-label":"Remove entry",onClick:Je=>{Je.preventDefault(),Je.stopPropagation(),Mi(fe.addMoreFieldName,fe.blockId)},children:u.jsx(ko,{className:"h-5 w-5","aria-hidden":!0})})},`add-more-remove-${$}-${J}`)}return u.jsx("div",{className:"min-w-0",style:{pointerEvents:"none"},"data-form-renderer":"grid-cell","data-form-renderer-empty":!0},`empty-${$}-${J}`)}const _e=me[0],{rowSpan:Pe,columnSpan:Re}=Ei(me,pe);if(me.length===1&&_e.type==="section"){const fe=ee.fields.filter(Ne=>Ne.parentId===_e.id&&Ne.position!=null).sort((Ne,Xe)=>{const Ke=typeof Ne.position?.order=="number"?Ne.position.order:0,Je=typeof Xe.position?.order=="number"?Xe.position.order:0;return Ke-Je});return u.jsx("div",{className:"min-w-0 min-h-0 w-full overflow-hidden flex flex-col h-full",style:{gridRow:`${$+1} / span ${Pe}`,gridColumn:`${J+1} / span ${Re}`,...dn(_e)},"data-form-renderer":"grid-cell",children:u.jsx(Pm,{field:_e,children:fe.map(Ne=>{const Xe=Ne.name||Ne.key||Ne.id,Ke=Ne.hidden===!0;return Pt(Ne)&&(on(Xe)||!Ke&&Xe)?u.jsx("div",{"data-field-name":Xe,"data-form-renderer":"field-wrapper",children:u.jsx(nn,{field:xt(Ne),value:Ue[Xe],error:ce[Xe]||Ae>0?Q[Xe]:void 0,onChange:ke=>We(Xe,ke),onBlur:()=>mt(Xe),disabled:ye||!jt(Xe)||Jt||!!Ne.disabled,readOnly:rr(Xe,!!Ne.readOnly),isRequired:vr(Xe),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:Xe,buttonResponses:L,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:Qt,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,onAddMore:jn,hideTableRowControls:A})},Ne.id):null})})},_e.id)}const nt=Sh(me),Rt=me.some(fe=>["file","camera","photoChoice","addmore","table"].includes(fe.type)),ze=u.jsx("div",{className:W("flex min-h-0 w-full flex-1 gap-3",nt==="row"?"flex-row items-stretch":"flex-col items-stretch"),children:me.map(fe=>{const Ne=fe.name||fe.key||fe.id,Xe=fe.type==="sectionHeading",Ke=yo.scopeByFieldName[Ne],Je=Ke?.scopedFieldNameMap?.[Ne]||Ne,ke=Ke?.blockDocumentId!=null?{...Qt,documentId:Ke.blockDocumentId}:Qt,Te=fe.appearance?.hideLabel??fe.properties?.hideLabel??!1,$e=fe.type==="table"?fe.properties?.minWidth:void 0;return u.jsx("div",{"data-field-name":Ne,"data-form-renderer":"field-wrapper",className:W("flex min-h-0 min-w-0 flex-1 flex-col",xo(fe),Xe&&"items-center justify-center",Te&&"items-center"),style:{...$e?{minWidth:$e}:{},...dn(fe)},children:u.jsx(nn,{field:xt(fe),value:Ue[Ne],error:ce[Ne]||Ae>0?Q[Ne]:void 0,onChange:ht=>We(Ne,ht),onBlur:()=>mt(Ne),disabled:fe.type==="table"&&a==="fill"?!1:ye||!jt(Je)||Jt||!!fe.disabled,readOnly:fe.type==="table"&&a==="fill"?!1:rr(Je,!!fe.readOnly),isRequired:vr(Je),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:Ne,buttonResponses:Ke?.scopedButtonResponses??L,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:ke,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,onAddMore:jn,scopedFormValues:Ke?.scopedFormValues,scopedFieldNameMap:Ke?.scopedFieldNameMap,excludedOptionValues:Ke?.excludedOptionValues,hideTableRowControls:A})},fe.id)})});return u.jsx("div",{className:W(Fc(me),"self-stretch",Rt?"overflow-visible":"overflow-hidden"),style:{gridRow:`${$+1} / span ${Pe}`,gridColumn:`${J+1} / span ${Re}`,...dn(me[0])},"data-form-renderer":"grid-cell","data-field-name":me.map(fe=>fe.name||fe.key||fe.id).join(","),children:ze},me.map(fe=>fe.id).join("-"))}))}):u.jsx("div",{className:f?"":"space-y-4","data-form-renderer":"stack",children:Ct.map(k=>{if(!Ut(k))return null;const $=U_.find(J=>J.kind==="border"&&J.fields.some(te=>te.id===k.id));if($)return $.fields[0]?.id!==k.id?null:u.jsx(zl,{legend:Jo($.run.section,0),collapsible:$.run.section.collapsible,defaultCollapsed:$.run.section.defaultCollapsed,onCollapsedChange:J=>Zl($.run.section.id,void 0,J),children:$.fields.map(J=>{const te=lt(J);return!te||!Ut(J)?null:u.jsxs("div",{"data-field-name":te,"data-form-renderer":"field-wrapper",style:dn(J),children:[u.jsx(nn,{field:xt(J),value:Ue[te],error:ce[te]||Ae>0?Q[te]:void 0,onChange:me=>We(te,me),onBlur:()=>mt(te),disabled:J.type==="table"&&a==="fill"?!1:ye||!jt(te)||Jt||!!J.disabled,readOnly:J.type==="table"&&a==="fill"?!1:rr(te,!!J.readOnly),isRequired:vr(te),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:te,buttonResponses:L,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:Qt,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,onAddMore:jn,hideTableRowControls:A}),J.type==="addmore"&&Ui(J)]},J.id)})},`stack-border-${$.run.section.id}-${k.id}`);if(!k.parentId){const J=Ct.filter(me=>!me.parentId&&Ut(me)&&Ai(me)===Ai(k)),te=Ci(J).slice(0,2);if(te.length>1&&te[0].id!==k.id)return null;if(te.length>1){const me=Sh(te);return u.jsx("div",{"data-form-renderer":"shared-cell-stack",className:W("flex w-full min-w-0 gap-3",me==="row"?"flex-row items-stretch":"flex-col"),children:te.map(_e=>{const Pe=_e.name||_e.key||_e.id;return u.jsxs("div",{"data-field-name":Pe,"data-form-renderer":"field-wrapper",className:W("min-w-0 flex-1 flex flex-col",xo(_e)),style:dn(_e),children:[u.jsx(nn,{field:xt(_e),value:Ue[Pe],error:ce[Pe]||Ae>0?Q[Pe]:void 0,onChange:Re=>We(Pe,Re),onBlur:()=>mt(Pe),disabled:_e.type==="table"&&a==="fill"?!1:ye||!jt(Pe)||Jt||!!_e.disabled,readOnly:_e.type==="table"&&a==="fill"?!1:rr(Pe,!!_e.readOnly),isRequired:vr(Pe),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:Pe,buttonResponses:L,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:Qt,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,onAddMore:jn,hideTableRowControls:A}),_e.type==="addmore"&&Ui(_e)]},_e.id)})},te.map(_e=>_e.id).join("-"))}}if(k.type==="section"){const J=ee.fields.filter(te=>te.parentId===k.id&&te.position!=null).sort((te,me)=>{const _e=typeof te.position?.order=="number"?te.position.order:0,Pe=typeof me.position?.order=="number"?me.position.order:0;return _e-Pe});return u.jsx(Pm,{field:k,children:J.map(te=>{const me=te.name||te.key||te.id,_e=te.hidden===!0;return Pt(te)&&(on(me)||!_e&&me)?u.jsxs("div",{"data-field-name":me,"data-form-renderer":"field-wrapper",style:dn(te),children:[u.jsx(nn,{field:xt(te),value:Ue[me],error:ce[me]||Ae>0?Q[me]:void 0,onChange:Re=>We(me,Re),onBlur:()=>mt(me),disabled:ye||!jt(me)||Jt||!!te.disabled,readOnly:rr(me,!!te.readOnly),isRequired:vr(me),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:me,buttonResponses:L,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:Qt,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,onAddMore:jn,hideTableRowControls:A}),te.type==="addmore"&&Ui(te)]},te.id):null})},k.id)}const X=k.name||k.key||k.id;return u.jsxs("div",{"data-field-name":X,"data-form-renderer":"field-wrapper",style:dn(k),children:[u.jsx(nn,{field:xt(k),value:Ue[X],error:ce[X]||Ae>0?Q[X]:void 0,onChange:J=>We(X,J),onBlur:()=>mt(X),disabled:k.type==="table"&&a==="fill"?!1:ye||!jt(X)||Jt||!!k.disabled,readOnly:k.type==="table"&&a==="fill"?!1:rr(X,!!k.readOnly),isRequired:vr(X),formValues:Ue,submissionContext:Pr,prepopulateMappedFieldNames:Ye,urlParams:he,prepopulateResponse:oe,prepopulateLoading:H,fieldValueKey:X,buttonResponses:L,onButtonApiResponse:Ar,onSubmit:xr,onReset:Ht,onCancel:Or,isSubmitting:ue,bffSubmitApi:P,onBffSubmitResult:b,extraSubmitPayload:Qt,onValidateForm:fr,getValidationErrors:Wt,allFields:ee.fields,onSubmittingChange:ae,onAddMore:jn,hideTableRowControls:A}),k.type==="addmore"&&Ui(k)]},k.id)})})}),c]})]})})};function Jl(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function Lh(e,t){const r=e.form;if(!r)throw new Error("workflowStateToFormSchema requires workflowState.form to be set");const n=r.fields.filter(l=>l!=null&&l!==void 0).map((l,f)=>{if(!l||typeof l!="object")return null;const p={...l};if(l.fieldType&&!p.type&&(p.type=l.fieldType),l.fieldKey&&!p.key&&!p.name&&(p.key=l.fieldKey,p.name=l.fieldKey),typeof l.positionOrder=="number"&&!isNaN(l.positionOrder)?p.order=l.positionOrder:p.order=f,(typeof p.order!="number"||isNaN(p.order))&&(p.order=f),l.options&&typeof l.options=="string")try{p.options=JSON.parse(l.options)}catch{}if(l.metadata&&typeof l.metadata=="string")try{p.metadata=JSON.parse(l.metadata)}catch{}return p}).filter(l=>l!=null).sort((l,f)=>{const p=typeof l.order=="number"?l.order:0,m=typeof f.order=="number"?f.order:0;return p-m});n.forEach((l,f)=>{(!l||typeof l.order!="number"||isNaN(l.order))&&(l.order=f)});let o=r.layout;if(o){const l={...o};if(l.breakpoints&&typeof l.breakpoints=="string")try{l.breakpoints=JSON.parse(l.breakpoints)}catch{}if(l.responsiveConfig&&typeof l.responsiveConfig=="string")try{l.responsiveConfig=JSON.parse(l.responsiveConfig)}catch{}o=l}const s=n.filter(l=>l!=null&&typeof l=="object"&&typeof l.order=="number"&&!isNaN(l.order));let i={};const a=r.config;if(a!=null)if(typeof a=="string")try{i=JSON.parse(a)}catch{}else typeof a=="object"&&a!==null&&(i={...a});const d=l=>{let f={...l};if(l.conditionExpression&&typeof l.conditionExpression=="string")try{f={...l,conditionExpression:JSON.parse(l.conditionExpression)}}catch{}if(f.targetFieldId){const p=s.find(m=>m._id===f.targetFieldId||m.id===f.targetFieldId||m.fieldKey===f.targetFieldId);if(p){const m=p.key||p.fieldKey||p.name,b=p._id||p.id||f.targetFieldId;f.targetFieldKey=m,f.targetField=m,f.targetFieldById=b}}return f},c={id:r._id,name:r.name,description:r.description??"",version:r.version,status:r.status,fields:s.map((l,f)=>{const p=l,m=typeof l.metadata=="object"&&l.metadata!==null?l.metadata:{},b=m.hidden===!0||l.hidden===!0,h={id:l._id||l.id||l.fieldKey,type:l.type||l.fieldType,label:l.label,key:l.key||l.fieldKey||l.name,name:l.name||l.fieldKey||l.key};if(b&&(h.hidden=!0),h.id||(h.id=h.key||h.name),h.key||(h.key=h.id||h.name),h.name||(h.name=h.key||h.id),l.isRequired!==void 0&&(h.required=l.isRequired),l.placeholder&&(h.placeholder=l.placeholder),l.options&&Array.isArray(l.options)&&(h.options=l.options),l.apidata&&(h.apidata=l.apidata),p.appearance&&typeof p.appearance=="object"&&!Array.isArray(p.appearance)&&Object.keys(p.appearance).length>0&&(h.appearance=Jl(p.appearance)),p.ui!==void 0&&(h.ui=Jl(p.ui)),p.visibility!==void 0&&(h.visibility=Jl(p.visibility)),m.disabled!==void 0&&(h.disabled=m.disabled),m.readOnly!==void 0&&(h.readOnly=m.readOnly),m.hideLabel!==void 0&&(h.hideLabel=m.hideLabel,h.properties||(h.properties={}),h.properties.hideLabel=m.hideLabel,h.appearance||(h.appearance={}),h.appearance.hideLabel=m.hideLabel),(l.type==="file"||l.fieldType==="file"||l.type==="camera"||l.fieldType==="camera"||l.type==="photoChoice"||l.fieldType==="photoChoice")&&l.validationRules){const g=l.validationRules,w={...m};if(g.fileSize!==void 0&&(w.maxSize=g.fileSize),g.fileType&&Array.isArray(g.fileType)){const v=[];g.fileType.forEach(x=>{const A=x.startsWith(".")?x:`.${x}`;v.push(A),A===".csv"?v.push("text/csv"):A===".xls"?v.push("application/vnd.ms-excel"):A===".xlsx"&&v.push("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}),w.accept=v}h.metadata=w,w.maxSize!==void 0&&(h.maxSize=w.maxSize),w.accept!==void 0&&(h.accept=w.accept)}else if(m&&Object.keys(m).length>0){if(h.metadata=m,(l.type==="toggle"||l.fieldType==="toggle")&&(m.onValue!==void 0&&(h.onValue=m.onValue),m.offValue!==void 0&&(h.offValue=m.offValue),m.onText!==void 0&&(h.onText=m.onText),m.offText!==void 0&&(h.offText=m.offText)),(l.type==="button"||l.fieldType==="button")&&m.action==="download"&&m.downloadApiEndpoint&&typeof m.downloadApiEndpoint=="string"){let g=m.downloadApiEndpoint;g=g.replace(/\{ctx:([^}]+)\}/g,(w,v)=>{const x=t[v];return x!==void 0?String(x):w}),m.downloadApiEndpoint=g,h.metadata=m,h.downloadApiEndpoint=g}if((l.type==="button"||l.fieldType==="button")&&m.action==="submit"){const g=h.properties||{};m.submitAction!==void 0&&(g.submitAction=m.submitAction),m.submitApiMethod!==void 0&&(g.submitApiMethod=m.submitApiMethod),m.apiBodyStructure!==void 0&&(g.apiBodyStructure=m.apiBodyStructure),m.apiBodyFieldsOnly!==void 0&&(g.apiBodyFieldsOnly=m.apiBodyFieldsOnly),m.apiBodyFieldsOnlyFormat!==void 0&&(g.apiBodyFieldsOnlyFormat=m.apiBodyFieldsOnlyFormat),m.apiBodyFields!==void 0&&(g.apiBodyFields=m.apiBodyFields),m.buttonText!==void 0&&(g.buttonText=m.buttonText),m.action!==void 0&&(g.action=m.action),m.variant!==void 0&&(g.variant=m.variant),m.hideLabel!==void 0&&(g.hideLabel=m.hideLabel),l.apidata&&typeof l.apidata=="object"&&l.apidata.apiEndpoint&&(g.apiEndpoint=l.apidata.apiEndpoint),h.properties=g}if((l.type==="button"||l.fieldType==="button")&&(m.action==="upload"||m.action==="custom")){const g=h.properties||{};m.action!==void 0&&(g.action=m.action),m.buttonText!==void 0&&(g.buttonText=m.buttonText),m.variant!==void 0&&(g.variant=m.variant),m.hideLabel!==void 0&&(g.hideLabel=m.hideLabel),m.uploadAction!==void 0&&(g.uploadAction=m.uploadAction),m.uploadApiEndpoint!==void 0&&(g.uploadApiEndpoint=m.uploadApiEndpoint),m.uploadApiMethod!==void 0&&(g.uploadApiMethod=m.uploadApiMethod),m.apiBodyStructure!==void 0&&(g.apiBodyStructure=m.apiBodyStructure),m.apiBodyFieldsOnly!==void 0&&(g.apiBodyFieldsOnly=m.apiBodyFieldsOnly),m.apiBodyFieldsOnlyFormat!==void 0&&(g.apiBodyFieldsOnlyFormat=m.apiBodyFieldsOnlyFormat),m.apiFieldMapping!==void 0&&(g.apiFieldMapping=m.apiFieldMapping),m.apiQueryParams!==void 0&&(g.apiQueryParams=m.apiQueryParams),m.apiBodyFields!==void 0&&(g.apiBodyFields=m.apiBodyFields),m.apiHeaders!==void 0&&(g.apiHeaders=m.apiHeaders),h.properties=g}if(l.type==="status"||l.fieldType==="status"){const g=h.properties||{};if(m.source!==void 0&&(g.source=m.source),m.statuses!==void 0&&(g.statuses=m.statuses),m.dataPath!==void 0&&(g.dataPath=m.dataPath),m.showStatusText!==void 0&&(g.showStatusText=m.showStatusText),m.statusTextPath!==void 0&&(g.statusTextPath=m.statusTextPath),m.showCurrentIndicator!==void 0&&(g.showCurrentIndicator=m.showCurrentIndicator),l.apidata&&typeof l.apidata=="object"&&l.apidata.apiEndpoint){let w=l.apidata.apiEndpoint;w=w.replace(/\{ctx:([^}]+)\}/g,(v,x)=>{const A=t[x];return A!==void 0?String(A):v}),g.apiEndpoint=w,g.source===void 0&&(g.source="api")}l.apidata?.apiMethod!==void 0&&(g.apiMethod=l.apidata.apiMethod),h.properties=g}if(l.type==="addmore"||l.fieldType==="addmore"){const g=h.properties||{};m.linkedFieldNames!==void 0&&(g.linkedFieldNames=m.linkedFieldNames),m.linkedSectionIds!==void 0&&(g.linkedSectionIds=m.linkedSectionIds),m.linkedFieldAllowDuplicate!==void 0&&(g.linkedFieldAllowDuplicate=m.linkedFieldAllowDuplicate),m.buttonText!==void 0&&(g.buttonText=m.buttonText),m.variant!==void 0&&(g.variant=m.variant),m.size!==void 0&&(g.size=m.size),m.hideLabel!==void 0&&(g.hideLabel=m.hideLabel),h.properties=g}if(l.type==="selectablelist"||l.fieldType==="selectablelist"){const g=h.properties||{};m.submitFieldMapping!==void 0&&(g.submitFieldMapping=m.submitFieldMapping),m.displayFields!==void 0&&(g.displayFields=m.displayFields),m.displayFieldsSeparator!==void 0&&(g.displayFieldsSeparator=m.displayFieldsSeparator),m.dataSourceContextKey!==void 0&&(g.dataSourceContextKey=m.dataSourceContextKey),m.showSelectAll!==void 0&&(g.showSelectAll=m.showSelectAll),m.selectAllByDefault!==void 0&&(g.selectAllByDefault=m.selectAllByDefault),h.properties=g}}return l.validationRules&&l.type!=="file"&&l.fieldType!=="file"&&l.type!=="camera"&&l.fieldType!=="camera"&&l.type!=="photoChoice"&&l.fieldType!=="photoChoice"&&l.type!=="status"&&l.fieldType!=="status"&&(h.validationRules=l.validationRules),typeof l.order=="number"&&(h.order=l.order),h.position=wi(l,f),l.conditions&&Array.isArray(l.conditions)&&(h.conditions=l.conditions),h}).filter(l=>l!=null).sort((l,f)=>{const p=typeof l.order=="number"?l.order:0,m=typeof f.order=="number"?f.order:0;return p-m}),config:{...i,layout:o,...r.rules&&r.rules.length>0&&{rules:r.rules.map(d)},...r.clientMapping&&Object.keys(r.clientMapping).length>0&&{clientMapping:r.clientMapping}},...r.rules&&r.rules.length>0&&{rules:r.rules.map(d)},createdAt:"",updatedAt:"",moduleId:""};return xi(c)}var Ti="Tabs",[h_]=mr(Ti,[ai]),Dh=ai(),[g_,Ql]=h_(Ti),Bh=y.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,onValueChange:o,defaultValue:s,orientation:i="horizontal",dir:a,activationMode:d="automatic",...c}=e,l=Wn(a),[f,p]=Wr({prop:n,onChange:o,defaultProp:s??"",caller:Ti});return u.jsx(g_,{scope:r,baseId:Zr(),value:f,onValueChange:p,orientation:i,dir:l,activationMode:d,children:u.jsx(Ve.div,{dir:l,"data-orientation":i,...c,ref:t})})});Bh.displayName=Ti;var $h="TabsList",jh=y.forwardRef((e,t)=>{const{__scopeTabs:r,loop:n=!0,...o}=e,s=Ql($h,r),i=Dh(r);return u.jsx(Dp,{asChild:!0,...i,orientation:s.orientation,dir:s.dir,loop:n,children:u.jsx(Ve.div,{role:"tablist","aria-orientation":s.orientation,...o,ref:t})})});jh.displayName=$h;var Uh="TabsTrigger",Rh=y.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,disabled:o=!1,...s}=e,i=Ql(Uh,r),a=Dh(r),d=Hh(i.baseId,n),c=Wh(i.baseId,n),l=n===i.value;return u.jsx(Bp,{asChild:!0,...a,focusable:!o,active:l,children:u.jsx(Ve.button,{type:"button",role:"tab","aria-selected":l,"aria-controls":c,"data-state":l?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:d,...s,ref:t,onMouseDown:Be(e.onMouseDown,f=>{!o&&f.button===0&&f.ctrlKey===!1?i.onValueChange(n):f.preventDefault()}),onKeyDown:Be(e.onKeyDown,f=>{[" ","Enter"].includes(f.key)&&i.onValueChange(n)}),onFocus:Be(e.onFocus,()=>{const f=i.activationMode!=="manual";!l&&!o&&f&&i.onValueChange(n)})})})});Rh.displayName=Uh;var zh="TabsContent",Vh=y.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,forceMount:o,children:s,...i}=e,a=Ql(zh,r),d=Hh(a.baseId,n),c=Wh(a.baseId,n),l=n===a.value,f=y.useRef(l);return y.useEffect(()=>{const p=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(p)},[]),u.jsx(br,{present:o||l,children:({present:p})=>u.jsx(Ve.div,{"data-state":l?"active":"inactive","data-orientation":a.orientation,role:"tabpanel","aria-labelledby":d,hidden:!p,id:c,tabIndex:0,...i,ref:t,style:{...e.style,animationDuration:f.current?"0s":void 0},children:p&&s})})});Vh.displayName=zh;function Hh(e,t){return`${e}-trigger-${t}`}function Wh(e,t){return`${e}-content-${t}`}var y_=Bh,b_=jh,v_=Rh,w_=Vh;function S_({className:e,...t}){return u.jsx(y_,{"data-slot":"tabs",className:W("flex flex-col gap-2",e),...t})}function x_({className:e,...t}){return u.jsx(b_,{"data-slot":"tabs-list",className:W("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",e),...t})}function A_({className:e,...t}){return u.jsx(v_,{"data-slot":"tabs-trigger",className:W("data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function C_({className:e,...t}){return u.jsx(w_,{"data-slot":"tabs-content",className:W("flex-1 outline-none",e),...t})}function ir({className:e="",...t}){return u.jsx("div",{"data-slot":"skeleton","data-form-renderer":"skeleton",className:`animate-pulse rounded-md bg-neutral-200 dark:bg-neutral-700 ${e}`.trim(),...t})}function E_({className:e=""}){return u.jsxs("div",{className:`flex flex-col gap-4 ${e}`.trim(),"data-form-renderer":"workflow-steps-view-skeleton",children:[u.jsxs("div",{className:"flex w-full border-b border-neutral-200 dark:border-neutral-700 gap-0",children:[u.jsx(ir,{className:"h-10 w-24 rounded-none"}),u.jsx(ir,{className:"h-10 w-28 rounded-none ml-1"}),u.jsx(ir,{className:"h-10 w-20 rounded-none ml-1"})]}),u.jsxs("div",{className:"mt-4 flex flex-col gap-4 py-4",children:[u.jsx(ir,{className:"h-4 w-32"}),u.jsx(ir,{className:"h-10 w-full"}),u.jsx(ir,{className:"h-4 w-40"}),u.jsx(ir,{className:"h-10 w-full"}),u.jsx(ir,{className:"h-4 w-36"}),u.jsx(ir,{className:"h-24 w-full"})]})]})}function T_(){return u.jsxs("div",{className:"flex flex-col gap-4 py-4","data-form-renderer":"form-loading-skeleton",children:[u.jsx(ir,{className:"h-4 w-28"}),u.jsx(ir,{className:"h-10 w-full"}),u.jsx(ir,{className:"h-4 w-36"}),u.jsx(ir,{className:"h-10 w-full"}),u.jsx(ir,{className:"h-4 w-24"}),u.jsx(ir,{className:"h-20 w-full"})]})}const __=3e4,N_=10*6e4,k_=9e4,F_=15*6e4;function O_(e){return e!=null&&"on_success"in e&&e.on_success!=null}function P_(e,t){if(!t||typeof t!="object")return e;let r=e;return Object.entries(t).forEach(([n,o])=>{o!=null&&o!==""&&(r=r.replace(new RegExp(`\\{${n}\\}`,"g"),String(o)))}),r}const I_=({getWorkflowState:e,moduleId:t,tenantId:r,submissionContext:n,initialValues:o={},getAuthHeaders:s,onSuccess:i,bootstrapFeatureId:a,subjectUserId:d,viewStepId:c,clientId:l,className:f,onWorkflowSubmitResult:p,viewerContext:m,getViewerContext:b,dark:h=!1,themeVars:g})=>{const w=Vi.useQueryClient(),v=S.useMemo(()=>[d??"",c??"",l??""],[d,c,l]),x=S.useMemo(()=>({moduleId:t,tenantId:r,subjectUserId:d,viewStepId:c,clientId:l}),[t,r,d,c,l]),[A,I]=S.useState([]),[T,C]=S.useState(null),[_,E]=S.useState(null),[O,N]=S.useState(null),[j,R]=S.useState({}),M=S.useRef(null),B=S.useRef(null),P=S.useRef(null),H=S.useRef(null),D=S.useMemo(()=>A&&Array.isArray(A)?A.filter(ae=>ae.feature_id):[],[A]),K=Vi.useQuery({queryKey:["workflow-steps",t,a??"",r??"",v[0],v[1],v[2]],queryFn:()=>e({...x,featureId:a}),staleTime:__,gcTime:N_}),q=K.isPending,L=K.error?K.error instanceof Error?K.error.message:"Failed to load workflow steps":null;S.useEffect(()=>{const ae=K.data;if(!ae||A.length>0)return;const ye=ae.steps&&Array.isArray(ae.steps)?ae.steps:[];I(ye);const je=ye.filter(st=>st.feature_id);if(je.length>0){const st=ae.current_step_id,we=st&&je.some(ct=>ct.step_id===st);C(we?st:je[0].step_id)}},[K.data,A.length,a]);const z=S.useMemo(()=>{if(!T)return;const ae=A.find(je=>je.step_id===T),ye=M.current===T;return ae?.feature_id??(ye?H.current:void 0)??void 0},[T,A]),V=Vi.useQuery({queryKey:["workflow-step",t,z??"",r??"",v[0],v[1],v[2]],queryFn:()=>e({...x,featureId:z}),enabled:!!z,staleTime:k_,gcTime:F_,refetchOnWindowFocus:!0,refetchOnReconnect:!0}),le=V.isPending,re=V.error?V.error instanceof Error?V.error.message:"Failed to load form":null;S.useEffect(()=>{!V.data||M.current===T||(E(V.data),N(null),M.current=null,H.current=null)},[V.data,T]),S.useEffect(()=>{N(re)},[re]),S.useEffect(()=>{z===void 0&&M.current!==T&&(E(null),N(null),M.current=null,H.current=null)},[z,T]);const ne=S.useMemo(()=>{const ae=_?.form;if(!ae)return null;const ye=(r??Fn()??"").trim()||"default",je=Oh({scope:ye,formId:ae._id,version:ae.version});return je?.value?je.value:Lh(_,n)},[_,n,r]),Z=S.useMemo(()=>{const ae=_?.BFF_submit_api;if(!ae?.url)return;let ye=ae.url;if(ye.startsWith("http://")||ye.startsWith("https://"))try{const we=new URL(ye);ye=we.pathname+we.search}catch{}const je=s?.()??{},st={...ae.headers||{},"Content-Type":"application/json",...je};return{...ae,url:ye,headers:st}},[_?.BFF_submit_api,s]),Y=S.useMemo(()=>ne?{...ne,status:"published",...Z&&{BFF_submit_api:Z}}:null,[ne,Z]);S.useEffect(()=>{if(!ne?.id)return;const ae=(r??Fn()??"").trim()||"default";Ph({scope:ae,formId:ne.id,version:ne.version},ne)},[ne,r]);const oe=S.useMemo(()=>{if(!ne)return null;const ae=Wi({config:ne.config,layout:ne.layout},null);if(!ae)return null;const ye=ae.rows,je=ae.columns,st={verticalSpacing:ae.verticalSpacing??ae.spacing??"16px",horizontalSpacing:ae.horizontalSpacing??ae.spacing??"16px",rowHeight:ae.rowHeight??zn};let we=1;if(Array.isArray(ne.fields))for(const Le of ne.fields){const ee=Le?.position,Ye=typeof ee?.order=="number"?ee.order:0,et=typeof ee?.rowSpan=="number"?ee.rowSpan:1;we=Math.max(we,Ye+et)}return{rows:Math.min(ye,Math.max(1,we)),columns:je,verticalSpacing:st.verticalSpacing,horizontalSpacing:st.horizontalSpacing,rowHeight:st.rowHeight}},[ne]),ie=S.useMemo(()=>{const ye=Y?.config?.theme?.cssVariables;if(!(!ye&&!g))return{...ye??{},...g??{}}},[Y?.config,g]),G=S.useCallback(()=>{w.invalidateQueries({queryKey:["workflow-steps",t]}),w.invalidateQueries({queryKey:["workflow-step",t]})},[w,t]),ve=S.useCallback(ae=>{if(O_(ae)){const we=ae.on_success,ct=we?.action;if(ct==="redirect"&&we?.redirect_url){const Le=P_(we.redirect_url.trim(),n);window.location.href=Le;return}if(ct==="move"){const Le=we?.next_step_id,ee=we?.next_step_form;if(Le&&ee){M.current=null,H.current=null;const Ye=ee.featureId??we?.next_step_form_id??ee._id;w.removeQueries({queryKey:["workflow-step",t,Ye,r??"",v[0],v[1],v[2]]}),G(),I(et=>et.some(Q=>Q.step_id===Le)?et:[...et,{step_id:Le,step_name:ee.name||"Next step",feature_id:Ye}]),E(null),C(Le),i?.();return}return}if(ct==="stay"){G(),i?.();return}}const ye=ae;ye.steps&&Array.isArray(ye.steps)&&I(ye.steps);const je=(ye.steps&&Array.isArray(ye.steps)?ye.steps:A).filter(we=>we.feature_id),st=ye.current_step_id;st&&je.some(we=>we.step_id===st)?C(st):je.length>0&&C(je[0].step_id),E(null),G(),i?.(),p?.(ye)},[w,t,r,i,p,A,n,v,G]),be=S.useCallback(async ae=>_?.BFF_submit_api?(i?.(),{success:!0,message:"Saved successfully"}):{success:!1,message:"Submit not configured"},[_?.BFF_submit_api,i]),He=S.useCallback((ae,ye)=>{},[]),he=S.useCallback(ae=>{},[]);if(q)return u.jsx(E_,{className:f});if(L)return u.jsx("div",{className:W("rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive",f),children:L});if(D.length===0)return u.jsx("div",{className:W("py-12 text-center text-sm text-muted-foreground",f),children:"No workflow steps configured."});const Ee=_?.step_blocked_message;return u.jsx("div",{className:W(Hi,h&&"dark","flex flex-col gap-4",f),style:ie,"data-form-renderer":"workflow-steps-view",children:u.jsxs(S_,{value:T??"",onValueChange:ae=>C(ae),children:[u.jsx(x_,{className:"w-full justify-start border-b rounded-none h-auto p-0 bg-transparent gap-0","data-form-renderer":"workflow-tabs",children:D.map(ae=>u.jsx(A_,{value:ae.step_id,className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:shadow-none","data-form-renderer":"workflow-tab",children:ae.step_name},ae.step_id))}),D.map(ae=>u.jsx(C_,{value:ae.step_id,className:"mt-4 outline-none",children:ae.step_id!==T?null:le?u.jsx(T_,{}):O?u.jsx("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:O}):Ee&&!_?.form?u.jsx("div",{className:W("rounded-lg border border-amber-500/50 bg-amber-500/10 px-4 py-3 text-sm text-amber-800 dark:text-amber-200",f),"data-form-renderer":"workflow-step-blocked",children:Ee}):Y?.fields?.length?u.jsxs("div",{className:"py-4 [&_*]:box-border",children:[Ee?u.jsx("div",{className:W("mb-4 rounded-lg border border-amber-500/50 bg-amber-500/10 px-4 py-3 text-sm text-amber-800 dark:text-amber-200"),"data-form-renderer":"workflow-step-blocked",children:Ee}):null,(()=>{const ye=B.current!==T||P.current!==(Y?.id??null);if(T&&Y&&ye){B.current=T,P.current=Y.id??null;const je=qt.getState();je.setSchema(Y,{forceReset:!0});const st=qt.getState().values;je.setValues({...st,...o})}return null})(),u.jsx(Mh,{schema:Y,gridLayout:oe,omitRootWrapper:!0,submissionContext:n,initialValues:o,workflowStepId:T??void 0,viewerContext:m,getViewerContext:b,onSubmit:be,onChange:He,onValidationError:he,onClose:()=>{},mode:"fill",unstyled:!0,onWorkflowSubmitResult:ve,initialExtraSubmitPayload:Object.keys(j).length>0?j:void 0,onExtraSubmitPayloadChange:ye=>{if(ye&&typeof ye=="object"){const je={};ye.context_user_id!=null&&(je.context_user_id=ye.context_user_id),ye.id!=null&&(je.id=ye.id),ye.batch_id!=null&&(je.batch_id=ye.batch_id),ye.admission_batch_id!=null&&(je.admission_batch_id=ye.admission_batch_id),ye.program_id!=null&&(je.program_id=ye.program_id),Object.keys(je).length>0&&R(st=>({...st,...je}))}}},Y.id)]}):u.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No form schema available for this step."})},ae.step_id))]})})};function M_(e){return typeof e=="object"&&e!==null&&"apiEndpoint"in e}function L_({formSchema:e}){const t=S.useMemo(()=>{if(!e)return[];const s=[];(!e.name||e.name.trim()==="")&&s.push({id:"form-name-required",type:"error",message:"Form name is required"});const i=new Set,a=new Set;e.fields.forEach((l,f)=>{const p=`field-${l.id}`;if(a.has(l.id)&&s.push({id:`${p}-duplicate-id`,type:"error",message:`Field "${l.label||l.name||`Field ${f+1}`}" has a duplicate ID`,fieldId:l.id}),a.add(l.id),l.name&&i.has(l.name)&&s.push({id:`${p}-duplicate-name`,type:"error",message:`Field "${l.label||l.name}" has a duplicate name: "${l.name}"`,fieldId:l.id}),l.name&&i.add(l.name),(!l.label||l.label.trim()==="")&&s.push({id:`${p}-missing-label`,type:"warning",message:`Field "${l.name||l.id}" is missing a label`,fieldId:l.id}),(!l.name||l.name.trim()==="")&&s.push({id:`${p}-missing-name`,type:"error",message:`Field "${l.label||l.id}" is missing a field name`,fieldId:l.id}),l.name&&!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(l.name)&&s.push({id:`${p}-invalid-name`,type:"error",message:`Field "${l.label||l.name}" has an invalid name. Use only letters, numbers, and underscores.`,fieldId:l.id}),["select","multiselect","radio","checkboxgroup"].includes(l.type)){const h=l.properties;(!h?.options||h.options.length===0)&&s.push({id:`${p}-no-options`,type:"warning",message:`Field "${l.label||l.name}" has no options defined`,fieldId:l.id})}l.parentId&&(e.fields.some(g=>g.id===l.parentId)||s.push({id:`${p}-orphaned`,type:"error",message:`Field "${l.label||l.name}" references a non-existent parent`,fieldId:l.id}));const b=(h,g)=>{if(g.has(h))return!0;g.add(h);const w=e.fields.find(v=>v.id===h);return w?.parentId?b(w.parentId,g):!1};l.parentId&&b(l.id,new Set)&&s.push({id:`${p}-circular-reference`,type:"error",message:`Field "${l.label||l.name}" has a circular parent reference`,fieldId:l.id})}),e.config.workflowTrigger?.workflowId&&(e.fields.some(f=>f.validation?.some(p=>p.type==="required"))||s.push({id:"workflow-no-required-fields",type:"info",message:"Form linked to workflow but has no required fields"}));const d=e.fields.filter(l=>!l.parentId),c=new Map;return d.forEach(l=>{const f=l.position.order;c.has(f)||c.set(f,[]),c.get(f).push(l)}),c.forEach((l,f)=>{l.length>3&&s.push({id:`row-${f}-too-many-fields`,type:"warning",message:`Row ${f+1} has ${l.length} fields (maximum recommended is 3)`})}),s},[e]),r=S.useMemo(()=>t.filter(s=>s.type==="error"),[t]),n=S.useMemo(()=>t.filter(s=>s.type==="warning"),[t]),o=S.useMemo(()=>r.length===0,[r]);return{issues:t,errors:r,warnings:n,isValid:o}}function D_({field:e,value:t,allValues:r,validateOnChange:n=!1,validateOnBlur:o=!0,debounceMs:s=ST}){const[i,a]=S.useState(),[d,c]=S.useState(!1),l=S.useRef(void 0),f=S.useRef(t),p=S.useCallback(async()=>{if(!e.validation||e.validation.length===0){a(void 0);return}c(!0);let w;for(const v of e.validation){const x=Rr(t,v,r);if(typeof x=="string"){w=x;break}}return a(w),c(!1),w},[e.validation,t,r]),m=S.useCallback(()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{p()},s)},[p,s]);S.useEffect(()=>(n&&f.current!==t&&m(),f.current=t,()=>{l.current&&clearTimeout(l.current)}),[t,n,m]);const b=S.useCallback(()=>{o&&p()},[o,p]),h=S.useCallback(()=>{a(void 0)},[]),g=S.useCallback(w=>{a(w)},[]);return{error:i,isValidating:d,validate:p,handleBlur:b,clearError:h,setCustomError:g}}const B_={text:{type:"text",label:"Text Input",icon:"Type",category:"input",description:"Single line text input",defaultProps:{label:"Text Field",name:"text_field",placeholder:"Enter text..."}},number:{type:"number",label:"Number Input",icon:"Hash",category:"input",description:"Numeric input with optional constraints",defaultProps:{label:"Number Field",name:"number_field",placeholder:"0",properties:{min:0,step:1}}},email:{type:"email",label:"Email",icon:"Mail",category:"input",description:"Email address input with validation",defaultProps:{label:"Email",name:"email_field",placeholder:"example@domain.com",validation:[{type:"email"}]}},phone:{type:"phone",label:"Phone",icon:"Phone",category:"input",description:"Phone number input",defaultProps:{label:"Phone Number",name:"phone_field",placeholder:"+91 12345 67890"}},password:{type:"password",label:"Password",icon:"Lock",category:"input",description:"Secure password input",defaultProps:{label:"Password",name:"password_field",placeholder:"••••••••"}},url:{type:"url",label:"URL",icon:"Link",category:"input",description:"URL input with validation",defaultProps:{label:"URL",name:"url_field",placeholder:"https://example.com",validation:[{type:"url"}]}},date:{type:"date",label:"Date",icon:"Calendar",category:"datetime",description:"Date picker",defaultProps:{label:"Date",name:"date_field",placeholder:"Select date"}},time:{type:"time",label:"Time",icon:"Clock",category:"datetime",description:"Time picker",defaultProps:{label:"Time",name:"time_field",placeholder:"Select time"}},datetime:{type:"datetime",label:"Date & Time",icon:"CalendarClock",category:"datetime",description:"Combined date and time picker",defaultProps:{label:"Date & Time",name:"datetime_field",placeholder:"Select date and time"}},daterange:{type:"daterange",label:"Date Range",icon:"CalendarRange",category:"datetime",description:"Select a range of dates",defaultProps:{label:"Date Range",name:"daterange_field",placeholder:"Select date range"}},select:{type:"select",label:"Dropdown",icon:"ChevronDown",category:"selection",description:"Single selection dropdown",defaultProps:{label:"Select",name:"select_field",placeholder:"Select an option",properties:{options:[{label:"Option 1",value:"option1"},{label:"Option 2",value:"option2"},{label:"Option 3",value:"option3"}],searchable:!0,clearable:!0}}},multiselect:{type:"multiselect",label:"Multi Select",icon:"ListChecks",category:"selection",description:"Multiple selection dropdown",defaultProps:{label:"Multi Select",name:"multiselect_field",placeholder:"Select options",properties:{options:[{label:"Option 1",value:"option1"},{label:"Option 2",value:"option2"},{label:"Option 3",value:"option3"}],searchable:!0}}},radio:{type:"radio",label:"Radio Group",icon:"CircleDot",category:"selection",description:"Single selection radio buttons",defaultProps:{label:"Radio Group",name:"radio_field",properties:{options:[{label:"Option 1",value:"option1"},{label:"Option 2",value:"option2"},{label:"Option 3",value:"option3"}]}}},checkbox:{type:"checkbox",label:"Checkbox",icon:"CheckSquare",category:"selection",description:"Single checkbox for boolean values",defaultProps:{label:"I agree to the terms",name:"checkbox_field"}},toggle:{type:"toggle",label:"Toggle",icon:"ToggleLeft",category:"selection",description:"Toggle switch with configurable text values",defaultProps:{label:"Toggle",name:"toggle_field",description:"Toggle to switch between states",properties:{onValue:"On",offValue:"Off"}}},checkboxgroup:{type:"checkboxgroup",label:"Checkbox Group",icon:"CheckSquare",category:"selection",description:"Multiple checkboxes for selecting multiple values",defaultProps:{label:"Checkbox Group",name:"checkboxgroup_field",properties:{options:[{label:"Option 1",value:"option1"},{label:"Option 2",value:"option2"},{label:"Option 3",value:"option3"}]}}},selectablelist:{type:"selectablelist",label:"Selectable List",icon:"ListChecks",category:"selection",description:"List from response or context; select all or specific items. Value = selected array.",defaultProps:{label:"Recipients",name:"recipients",properties:{dataSourceContextKey:"recipients",labelField:"name",valueField:"email",showSelectAll:!0,selectAllByDefault:!0}}},asyncsearch:{type:"asyncsearch",label:"Async Search",icon:"Search",category:"selection",description:"Typeahead search against an API; submitted value is the selected option value.",defaultProps:{label:"Search",name:"async_search",placeholder:"Type to search…",properties:{apiEndpoint:"/api/form-builder/search",apiMethod:"GET",searchQueryParam:"q",searchSchedule:"debounce",intervalMs:300,minQueryLength:0,clearable:!0}}},terms:{type:"terms",label:"Terms & Conditions",icon:"FileText",category:"special",description:"Terms and conditions confirmation checkbox",defaultProps:{label:"I confirm that the details are true to my knowledge",name:"terms_conditions",validation:[{type:"required"}]}},textarea:{type:"textarea",label:"Text Area",icon:"AlignLeft",category:"rich",description:"Multi-line text input",defaultProps:{label:"Text Area",name:"textarea_field",placeholder:"Enter your text here...",properties:{minLength:0,maxLength:1e3}}},richtext:{type:"richtext",label:"Rich Text",icon:"FileText",category:"rich",description:"Rich text editor with formatting",defaultProps:{label:"Rich Text",name:"richtext_field"}},file:{type:"file",label:"File Upload",icon:"Upload",category:"rich",description:"File upload with drag and drop",defaultProps:{label:"File Upload",name:"file_field",properties:{accept:["image/*","application/pdf"],maxSize:5*1024*1024}}},camera:{type:"camera",label:"Use camera",icon:"Camera",category:"rich",description:"Take a photo with your camera",defaultProps:{label:"Take photo",name:"camera_field",properties:{accept:["image/*"],maxSize:5*1024*1024,multiple:!1}}},photoChoice:{type:"photoChoice",label:"Photo (upload or camera)",icon:"ImagePlus",category:"rich",description:"Upload a file or capture with the camera",defaultProps:{label:"Photo",name:"photo_choice_field",properties:{accept:["image/*"],maxSize:5*1024*1024,maxFiles:1}}},signature:{type:"signature",label:"Signature",icon:"Pencil",category:"rich",description:"Digital signature capture",defaultProps:{label:"Signature",name:"signature_field"}},rating:{type:"rating",label:"Rating",icon:"Star",category:"rich",description:"Star rating input",defaultProps:{label:"Rating",name:"rating_field",properties:{max:5,allowHalf:!1,icon:"star"}}},slider:{type:"slider",label:"Slider",icon:"SlidersHorizontal",category:"rich",description:"Numeric slider input",defaultProps:{label:"Slider",name:"slider_field",properties:{min:0,max:100,step:1,showValue:!0}}},table:{type:"table",label:"Table",icon:"Table",category:"special",description:"Repeatable table rows",defaultProps:{label:"Table",name:"table_field",properties:{columns:[],minRows:1,maxRows:10,allowAddRow:!0,allowDeleteRow:!0}}},aadhaar:{type:"aadhaar",label:"Aadhaar",icon:"CreditCard",category:"special",description:"Indian Aadhaar number input",defaultProps:{label:"Aadhaar Number",name:"aadhaar_field",placeholder:"XXXX XXXX XXXX"}},section:{type:"section",label:"Section",icon:"LayoutPanelTop",category:"container",description:"Group fields in a collapsible section",defaultProps:{label:"Section",name:"section",properties:{collapsible:!0,defaultCollapsed:!1,columns:1}}},group:{type:"group",label:"Group",icon:"Group",category:"container",description:"Group fields without visual separator",defaultProps:{label:"Group",name:"group"}},columns:{type:"columns",label:"Columns",icon:"Columns",category:"container",description:"Multi-column layout",defaultProps:{label:"Columns",name:"columns",properties:{columns:2}}},divider:{type:"divider",label:"Divider",icon:"Minus",category:"visual",description:"Horizontal line separator",defaultProps:{label:"",name:"divider"}},header:{type:"header",label:"Header",icon:"Heading",category:"visual",description:"Section header text (full row, configurable size)",defaultProps:{label:"Header",name:"header",properties:{headingLevel:"h3",showHorizontalLine:!0}}},sectionHeading:{type:"sectionHeading",label:"Section Heading",icon:"Heading",category:"visual",description:"Heading inside a grid box with configurable position and size",defaultProps:{label:"Section Heading",name:"section_heading",properties:{position:"top-left",headingLevel:"h3",showHorizontalLine:!0}}},spacer:{type:"spacer",label:"Spacer",icon:"Space",category:"visual",description:"Empty space for padding",defaultProps:{label:"",name:"spacer"}},textLabel:{type:"textLabel",label:"Text Label",icon:"Tag",category:"visual",description:"Standalone label text (no input)",defaultProps:{label:"Label",name:"text_label"}},status:{type:"status",label:"Status",icon:"ListChecks",category:"visual",description:"Populate status from Status API; label + response key; true = completed",defaultProps:{label:"Admission Status",name:"status_field",properties:{source:"api",statuses:[{label:"Registered",key:"registered"},{label:"Form Submitted",key:"formSubmitted"},{label:"Documents Verification",key:"documentsVerification"},{label:"Photos Clicked",key:"photosClicked"},{label:"Fitness Verification",key:"fitnessVerification"},{label:"Payment Completed",key:"paymentCompleted"},{label:"Hostel Allotted",key:"hostelAllotted"},{label:"Admission Completed",key:"admissionCompleted"}],showStatusText:!1,statusTextPath:"admissionStatus",showCurrentIndicator:!0}}},button:{type:"button",label:"Button",icon:"MousePointerClick",category:"special",description:"Clickable button element",defaultProps:{label:"Button",name:"button_field",properties:{variant:"default",size:"default",action:"download"}}},editButton:{type:"editButton",label:"Edit Button",icon:"Pencil",category:"special",description:"Toggle edit mode: enable/disable or show/hide other fields and buttons (no API call)",defaultProps:{label:"Edit",name:"edit_button",properties:{buttonText:"Edit",variant:"outline",size:"default",hideLabel:!1,rules:[]}}},addmore:{type:"addmore",label:"Add More",icon:"Plus",category:"special",description:"Duplicate linked fields as a new runtime block",defaultProps:{label:"Add More",name:"addmore_field",properties:{linkedFieldNames:[],linkedSectionIds:[],variant:"outline",size:"default"}}}};ge.FIELD_TYPE_REGISTRY=B_,ge.FORM_RENDERER_GRID_ROW_HEIGHT_DEFAULT=zn,ge.FORM_RENDERER_ROOT_CLASS=Hi,ge.FieldRenderer=nn,ge.FormRenderer=Mh,ge.RendererFieldLayoutContext=ra,ge.WorkflowStepsView=I_,ge.appearanceControlClasses=wo,ge.appearanceHasExplicitVerticalIntent=$c,ge.appearanceTextareaClasses=kc,ge.backendToFormSchema=vi,ge.buildWorkflowStateUrlFromBffSubmit=bh,ge.cellAlignmentClasses=Jg,ge.cellVerticalJustifyClassesForField=Xg,ge.effectiveWidthPercent=ss,ge.enrichFormSchemaFieldsFromWorkflowApi=uh,ge.extractBffSubmitApiBlock=Xo,ge.extractRawWorkflowFieldsFromSchema=Hl,ge.fetchWorkflowFormFieldsFromBffSubmitApi=wh,ge.fieldBlockBoxStyle=Yg,ge.fieldBlockBoxStyleForField=Dc,ge.fieldBlockHorizontalPlacementClass=Pc,ge.fieldBlockHorizontalSelfClass=Ic,ge.fieldBlockHorizontalSelfClassForField=Bc,ge.fieldBlockWidthStyle=Xi,ge.fieldBlockWidthStyleForField=Lc,ge.fieldGridShellFillsCellVertically=as,ge.fieldHasAuthoritativeWorkflowPosition=Si,ge.formBuilderHttp=Pn,ge.getBusinessApiOrigin=kf,ge.getClientId=Fn,ge.getRendererHostAuthHeaders=Kf,ge.getRendererHostViewerContext=kx,ge.getRendererStore=uy,ge.getWorkflowBffOrigin=mh,ge.gridCellFlexClasses=Oc,ge.gridCellFlexClassesForField=ta,ge.gridCellOuterFlexClasses=Fc,ge.hasExplicitFieldBlockWidth=Mc,ge.isAsyncSearchFieldProperties=M_,ge.isIntrinsicWidthButtonField=Vn,ge.mergeWorkflowFieldPosition=wi,ge.normalizeWorkflowFormSchema=PT,ge.normalizeWorkflowFormToRendererSchema=xi,ge.parseContentVerticalAlign=Qi,ge.parseMetadataJson=Vl,ge.parseModuleIdFromBffSubmitUrl=LT,ge.registerWorkflowFormFieldsForEnrich=MT,ge.resetRendererHostAuth=Nx,ge.resolveBusinessApiUrl=Gr,ge.resolveFormGridLayout=Wi,ge.resolveWorkflowBffUrl=Wl,ge.resolvedGridCellVerticalJustifyClasses=xo,ge.resolvedHorizontalAlign=Er,ge.resolvedVerticalAlign=So,ge.resolvedVerticalAlignForField=ea,ge.schemaNeedsWorkflowPositionEnrich=fh,ge.setBusinessApiOrigin=J0,ge.setFormBuilderAuthProvider=Fx,ge.setRendererHostAuthHeaders=_x,ge.setRendererHostViewerContext=Tx,ge.setWorkflowBffOrigin=IT,ge.useFieldValidation=D_,ge.useFormRenderer=Wc,ge.useFormValidation=L_,ge.useRendererFieldLayout=Ao,ge.useRendererHostAuthStore=On,ge.workflowStateToFormSchema=Lh,Object.defineProperty(ge,Symbol.toStringTag,{value:"Module"})}));
|