iq-line-form-builder-renderer 1.2.7 → 1.2.8

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.
@@ -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 b.useEffect(()=>{e&&(document.getElementById(e)||console.error(r))},[r,e]),null},VE="DialogDescriptionWarning",HE=({contentRef:e,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${lh(VE).contentName}}.`;return b.useEffect(()=>{const o=e.current?.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(n))},[n,e,t]),null},WE=Xm,RE=Zm,GE=eh,KE=th,qE=nh,YE=ih;function XE({...e}){return c.jsx(WE,{"data-slot":"dialog",...e})}function JE({...e}){return c.jsx(RE,{"data-slot":"dialog-portal",...e})}function QE({className:e,...t}){return c.jsx(GE,{"data-slot":"dialog-overlay",className:B("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 ZE({className:e,children:t,showCloseButton:r=!0,...n}){return c.jsxs(JE,{"data-slot":"dialog-portal",children:[c.jsx(QE,{}),c.jsxs(KE,{"data-slot":"dialog-content",className:B("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&&c.jsxs(YE,{"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:[c.jsx(Ko,{}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function eN({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-header",className:B("flex flex-col gap-2 text-center sm:text-left",e),...t})}function tN({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-footer",className:B("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function rN({className:e,...t}){return c.jsx(qE,{"data-slot":"dialog-title",className:B("text-lg leading-none font-semibold",e),...t})}async function nN(){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 ch(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 dh=({open:e,onOpenChange:t,onCaptured:r,validateFile:n,accept:o,disabled:s,onValidationMessage:i})=>{const a=S.useRef(null),d=S.useRef(null),u=S.useRef(null),l=S.useRef(null),[f,p]=S.useState(null),[m,g]=S.useState(!1),h=S.useCallback(()=>{a.current&&(a.current.srcObject=null)},[]),y=S.useCallback(()=>{u.current&&(u.current.getTracks().forEach(k=>k.stop()),u.current=null),h()},[h]);S.useEffect(()=>{if(!e){y(),p(null),g(!1);return}if(s)return;let k=!1;return p(null),g(!0),nN().then(N=>{if(k){N.getTracks().forEach(C=>C.stop());return}u.current=N,g(!1)}).catch(N=>{if(k)return;g(!1);const C=N instanceof Error?N.message:"Could not access camera";p(C)}),()=>{k=!0,u.current&&(u.current.getTracks().forEach(N=>N.stop()),u.current=null),h()}},[e,s,y,h]);const w=S.useCallback(k=>{a.current=k,k&&u.current&&e&&!f&&!m&&(k.srcObject=u.current,ch(k))},[e,f,m]);S.useLayoutEffect(()=>{if(!e||f||m||!u.current)return;let k=!1,N=0;const C=()=>{if(k)return;const I=a.current;!I||!u.current||(I.srcObject=u.current,ch(I))};C();const A=requestAnimationFrame(()=>{C(),N=requestAnimationFrame(C)});return()=>{k=!0,cancelAnimationFrame(A),cancelAnimationFrame(N),h()}},[e,f,m,h]);const v=S.useCallback(()=>{y(),p(null),g(!1),t(!1),l.current&&(l.current.value="")},[y,t]),x=S.useCallback(()=>{const k=a.current,N=d.current;if(!k||!N||!u.current||k.readyState<2)return;const C=k.videoWidth,A=k.videoHeight;if(C===0||A===0)return;N.width=C,N.height=A;const I=N.getContext("2d");I&&(I.drawImage(k,0,0),N.toBlob(T=>{if(!T)return;const W=new File([T],`camera-capture-${Date.now()}.jpg`,{type:"image/jpeg",lastModified:Date.now()}),X=n(W);if(X){i?.(X);return}i?.(void 0),r(W),v()},"image/jpeg",.92))},[r,n,v,i]),E=S.useCallback(k=>{const N=k.target.files?.[0];if(!N)return;const C=n(N);if(C){i?.(C);return}i?.(void 0),r(N),v(),l.current&&(l.current.value="")},[r,n,v,i]),P=typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function";return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:l,type:"file",accept:o,capture:"user",onChange:E,className:"hidden","aria-hidden":!0}),c.jsx("canvas",{ref:d,className:"hidden","aria-hidden":!0}),c.jsx(XE,{open:e,onOpenChange:k=>{k||v()},children:c.jsxs(ZE,{className:"sm:max-w-md",showCloseButton:!0,onPointerDownOutside:k=>k.preventDefault(),children:[c.jsx(eN,{children:c.jsx(rN,{children:"Take a photo"})}),f?c.jsxs("div",{className:"space-y-3 py-2",children:[c.jsx("p",{className:"text-sm text-destructive",children:f}),P&&c.jsx("p",{className:"text-xs text-muted-foreground",children:"You can choose an image from your device instead."}),c.jsx(Yt,{type:"button",variant:"outline",className:"w-full",onClick:()=>l.current?.click(),children:"Choose from device"})]}):m?c.jsx("p",{className:"text-sm text-muted-foreground py-6 text-center",children:"Opening camera…"}):c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"relative rounded-lg overflow-hidden bg-black aspect-video",children:c.jsx("video",{ref:w,playsInline:!0,muted:!0,className:"w-full h-full object-cover"})}),c.jsxs(tN,{className:"gap-2 sm:gap-0",children:[c.jsx(Yt,{type:"button",variant:"outline",onClick:v,children:"Cancel"}),c.jsx(Yt,{type:"button",onClick:x,children:"Capture photo"})]})]})]})})]})},oN=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a})=>{const d=e.properties,[u,l]=S.useState(),[f,p]=S.useState(!1),[m,g]=S.useState(()=>new Set),[h,y]=S.useState("none"),w=e.metadata?typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata:null,v=e.validation?.find(K=>K.type==="fileSize"),x=e.validation?.find(K=>K.type==="fileType"),E=v?.value!=null?v.value:d?.maxSize??w?.maxSize??5*1024*1024,P=x?.value!=null?x.value:d?.accept??w?.accept??["image/*"],k=P.join(",")||"image/*",N=Ms(e),C=S.useCallback(K=>{if(v){const J=Yr(K,v);if(J!==!0)return typeof J=="string"?J:"File size exceeds the maximum allowed size"}else if(K.size>E)return`File size must be less than ${yo(E)}`;if(x){const J=Yr(K,x);if(J!==!0)return typeof J=="string"?J:"File type is not allowed"}return null},[v,x,E]),A=S.useMemo(()=>Ls(t),[t]),I=ql(A),T=S.useCallback(K=>{const J=ka(K,N);r(J),n?.()},[r,n,N]),W=S.useCallback(K=>{const J=C(K);if(J){l(J);return}l(void 0);const ce=[...A];ce.length>=N||(ce.push(K),T(ce),y("none"))},[A,N,C,T]),X=S.useCallback(K=>{const J=A.filter((ce,ne)=>ne!==K);T(J)},[A,T]),O=S.useCallback(()=>{s||A.length>=N||(l(void 0),y("camera"),p(!0))},[s,A.length,N]),j=S.useCallback(K=>{p(K),K||y("none")},[]),M=o||u,D=e.appearance?.hideLabel??!1,L=[];(v||E)&&L.push(`Max size: ${yo(E)}`),x&&P.length>0&&L.push(`Allowed: ${P.join(", ")}`),N>1&&L.push(`Up to ${N} photos`);const U=S.useCallback(K=>{window.open(K,"_blank","noopener,noreferrer")},[]),$=A.length===0,ie=A.length<N,V=Rl(N,A.length);return c.jsxs(Et,{field:e,error:M,isRequired:i,className:B(a,"!space-y-0"),hideLabel:D,children:[c.jsx("div",{className:"h-[70px] min-h-[70px] min-w-0 w-full flex flex-col",children:c.jsx("div",{role:"button",tabIndex:s||!ie?-1:0,id:ht(e),onClick:K=>{s||K.target.closest("[data-remove-in-dropzone]")||K.target.closest("[data-no-open-picker]")||A.length>=N||O()},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),!s&&ie&&O())},className:B("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",M&&"border-destructive",s&&"opacity-50 cursor-not-allowed",f&&h==="camera"&&"opacity-70 pointer-events-none",!ie&&A.length>0&&"cursor-default"),"aria-describedby":jt(e,!!M),"aria-invalid":Jt(!!M),"aria-required":i,children:$?c.jsxs(c.Fragment,{children:[c.jsx(Us,{className:"mx-auto h-5 w-5 text-muted-foreground flex-shrink-0"}),c.jsx("p",{className:"text-[11px] text-muted-foreground leading-tight line-clamp-1",children:f?"Opening camera…":"Click to open camera"}),L.length>0&&c.jsx("p",{className:"text-[10px] text-muted-foreground line-clamp-1",children:L.join(" • ")})]}):V?c.jsx(Yl,{item:A[0],objectUrl:I[0]??null,failedUrlKeys:m,onImageUrlError:K=>g(J=>new Set(J).add(K)),onRemove:()=>X(0),onOpenUrl:U,disabled:s}):c.jsx(Kl,{items:A,maxFiles:N,disabled:s,objectUrls:I,failedUrlKeys:m,onImageUrlError:K=>g(J=>new Set(J).add(K)),onRemove:X,onOpenUrl:U,addSlot:ie?c.jsxs("button",{type:"button","data-no-open-picker":!0,onClick:K=>{K.stopPropagation(),O()},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:[c.jsx(Us,{className:"h-4 w-4 mb-0.5","aria-hidden":!0}),"Add"]}):void 0})})}),c.jsx(dh,{open:f,onOpenChange:j,onCaptured:W,validateFile:C,accept:k,disabled:s,onValidationMessage:l})]})},sN=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a,buttonResponses:d})=>{const u=e.properties,l=S.useRef(null),[f,p]=S.useState(),[m,g]=S.useState(!1),[h,y]=S.useState(()=>new Set),[w,v]=S.useState("none"),x=e.metadata?typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata:null,E=e.validation?.find(oe=>oe.type==="fileSize"),P=e.validation?.find(oe=>oe.type==="fileType"),k=E?.value?E.value:u?.maxSize??x?.maxSize??5*1024*1024,N=P?.value?P.value:u?.accept??x?.accept??["image/*"],C=Array.isArray(N)?N.join(","):"image/*",A=Ms(e),I=S.useCallback(oe=>{if(E){const re=Yr(oe,E);if(re!==!0)return typeof re=="string"?re:"File size exceeds the maximum allowed size"}else if(oe.size>k)return`File size must be less than ${yo(k)}`;if(P){const re=Yr(oe,P);if(re!==!0)return typeof re=="string"?re:"File type is not allowed"}return null},[E,P,k]),T=S.useMemo(()=>Ls(t),[t]),W=ql(T),X=S.useCallback(oe=>{const re=ka(oe,A);r(re),n?.()},[r,n,A]),O=S.useCallback(oe=>{p(void 0);const re=Array.from(oe),be=[...T];let de=null;for(const ot of re){if(be.length>=A)break;const Se=I(ot);if(Se){de||(de=Se);continue}be.push(ot)}if(de&&be.length===T.length){p(de);return}de&&p(de),X(be),v("none")},[T,A,I,X]),j=S.useCallback(oe=>{const re=oe.target.files;re&&re.length>0&&O(re),l.current&&(l.current.value="")},[O]),M=S.useCallback(oe=>{X(T.filter((re,be)=>be!==oe))},[T,X]),D=S.useCallback(()=>{s||T.length>=A||m||(p(void 0),v("file"),l.current?.click())},[s,T.length,A,m]),L=S.useCallback(()=>{s||T.length>=A||(p(void 0),v("camera"),g(!0))},[s,T.length,A]),U=S.useCallback(oe=>{const re=I(oe);if(re){p(re);return}p(void 0);const be=[...T];be.length>=A||(be.push(oe),X(be),v("none"))},[T,A,I,X]),$=S.useCallback(oe=>{g(oe),oe||v("none")},[]),ie=o||f,V=e.appearance?.hideLabel??!1,K=[];(E||k)&&K.push(`Max size: ${yo(k)}`),P&&N.length>0&&K.push(`Allowed: ${N.join(", ")}`),A>1&&K.push(`Up to ${A} photos`);const J=S.useMemo(()=>{if(!d)return null;const oe=Object.values(d);for(let re=oe.length-1;re>=0;re-=1){const be=oe[re],de=typeof be?.status=="string"?be.status.toLowerCase():null;if(de&&de!=="success")continue;const ot=be?.code;if(typeof ot=="number"&&(ot<200||ot>=300))continue;const Se=be?.data,xe=Se?.file_url||Se?.fileUrl||be?.file_url||be?.fileUrl;if(typeof xe=="string"&&xe.trim())return xe.trim()}return null},[d]),ce=S.useCallback(oe=>{window.open(oe,"_blank","noopener,noreferrer")},[]),ne=T.length===0,G=T.length<A,ee=Rl(A,T.length),Pe=G&&!m?c.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:[c.jsx("button",{type:"button",disabled:s,onClick:oe=>{oe.stopPropagation(),D()},className:"flex flex-1 w-full items-center justify-center hover:bg-primary/10 rounded-t","aria-label":"Upload file",title:"Upload",children:c.jsx(Hs,{className:"h-4 w-4","aria-hidden":!0})}),c.jsx("button",{type:"button",disabled:s,onClick:oe=>{oe.stopPropagation(),L()},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:c.jsx(Us,{className:"h-4 w-4","aria-hidden":!0})})]}):void 0;return c.jsxs(Et,{field:e,error:ie,isRequired:i,className:B(a,"!space-y-0"),hideLabel:V,children:[c.jsx("div",{className:"h-[70px] min-h-[70px] min-w-0 w-full flex flex-col",children:c.jsxs("div",{className:B("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",ie&&"border-destructive",s&&"opacity-50"),children:[c.jsx("input",{ref:l,id:ht(e),type:"file",accept:C,multiple:A>1,onChange:j,disabled:s||e.disabled||m||!G,className:"hidden","aria-describedby":jt(e,!!ie),"aria-invalid":Jt(!!ie),"aria-required":i}),ne?c.jsxs("div",{className:"flex flex-col items-center justify-center gap-1 w-full pointer-events-auto",children:[c.jsxs("div",{className:"flex items-center justify-center gap-3",children:[c.jsxs("button",{type:"button",disabled:s||m,onClick:D,className:B("inline-flex flex-col items-center gap-0.5 text-[11px] text-muted-foreground hover:text-foreground",s&&"pointer-events-none"),children:[c.jsx(Hs,{className:"h-5 w-5","aria-hidden":!0}),c.jsx("span",{children:"Upload"})]}),c.jsxs("button",{type:"button",disabled:s,onClick:L,className:B("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:[c.jsx(Us,{className:"h-5 w-5","aria-hidden":!0}),c.jsx("span",{children:"Camera"})]})]}),K.length>0&&c.jsx("p",{className:"text-[10px] text-muted-foreground line-clamp-2 text-center px-1",children:K.join(" • ")})]}):ee?c.jsx(Yl,{item:T[0],objectUrl:W[0]??null,failedUrlKeys:h,onImageUrlError:oe=>y(re=>new Set(re).add(oe)),onRemove:()=>M(0),onOpenUrl:ce,openTarget:T[0]instanceof File?J:void 0,disabled:s||e.disabled}):c.jsx(Kl,{items:T,maxFiles:A,disabled:s,objectUrls:W,failedUrlKeys:h,onImageUrlError:oe=>y(re=>new Set(re).add(oe)),onRemove:M,resolveOpenUrl:(oe,re)=>re instanceof File&&T.length===1&&J?J:null,onOpenUrl:oe=>{oe?.trim()&&ce(oe.trim())},addSlot:Pe})]})}),c.jsx(dh,{open:m,onOpenChange:$,onCaptured:U,validateFile:I,accept:C,disabled:s,onValidationMessage:p})]})};function ls(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 bo(n)}}catch{}if(e.response){const r=e.response;if(typeof r=="string")try{const n=JSON.parse(r);return bo(n)}catch{return r}else if(typeof r=="object")return bo(r)}return t}if(e instanceof IA)return e.response?.data?bo(e.response.data):e.message||"An unexpected error occurred";if(typeof e=="string")try{const t=JSON.parse(e);return bo(t)}catch{return e}return typeof e=="object"&&e!==null?bo(e):"An unexpected error occurred"}function bo(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 iN(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 aN(e,t){try{const r=iN(e);$t.toast.success(r&&r.trim()?r:t)}catch{$t.toast.success(t)}}function Zl(e,t,r){try{const n=r(e);$t.toast.error(n&&n.trim()?n:t)}catch{$t.toast.error(t)}}function lN(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 zi="This field is required";function uh(e,t){if(!t?.length)return e;const r=t.find(n=>n.name===e);return r?.label&&r.label.trim()||e}function ec(e,t){if(!e)return"Please complete the required fields.";if(Array.isArray(e)){const s=e.map(i=>{const a=i.message||zi;if(t?.length&&i.field){const d=uh(i.field,t);return a===zi?`${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()||zi;if(t?.length){const a=uh(o,t);return i===zi?`${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 cN=/^\{([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}$/i;function fh(e){const t=e.trim().match(cN);return t?t[1]:e}const dN={applicantId:["id","applicant_id"],applicant_id:["id","applicantId"],id:["applicantId","applicant_id"]};function rn(e,t,r,n,o,s){let i=e;if(o&&typeof e=="string"&&(i=i.replace(/\{resp:([^}]+)\}/g,(a,d)=>{const u=d.trim().split(".");if(u.length<2)return a;const l=u[0],f=u.slice(1).join("."),p=o[l];if(p==null)return a;const m=Qe(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 u=Qe(d,"data.id")??Qe(d,"data.documentId");if(u!=null){a=String(u);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&&Qe(t,"documentId")),u=n?.documentId??(n&&Qe(n,"documentId"));d!=null&&d!==""?a=String(d):u!=null&&u!==""&&(a=String(u)),a&&(i=i.replace(/\{documentId\}/g,a).replace(/%7BdocumentId%7D/gi,a))}return i=i.replace(/\{api:([^}]+)\}/g,(a,d)=>{const u=d.trim();if(s==null||u==="")return a;const l=Qe(s,u);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 u=r[d];if(u!=null)return fh(String(u));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=dN[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!==""?fh(String(l)):a}),i}function tc(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,u=typeof d=="object"&&d!==null?d:null,l=a?.submitFieldMapping??u?.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[g,h]of Object.entries(l))g!=null&&g!==""&&h!=null&&h!==""&&(m[g]=Qe(p,h));return m});n[o]=f;continue}}n[o]=s}return n}function Ui(e){return!!(e instanceof File||Array.isArray(e)&&e.length>0&&e[0]instanceof File)}function uN(e){return Object.values(e).some(t=>Ui(t))}function fN(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 pN(e,t,r){const n={};let o=!1;return Object.entries(e).forEach(([s,i])=>{const a=t?.[s]||s;if(Ui(i)){n[a]=i,o=!0;return}const d=r?.[s]||"string";let u=i;if(d==="number"){const l=Number(i);u=isNaN(l)?i:l}else d==="boolean"?u=i==="true"||i===!0||i==="1"||i===1:d==="date"?u=String(i):i!=null?u=typeof i=="object"?i:String(i):u="";n[a]=u}),{transformed:n,hasFiles:o}}const ph=Object.freeze(Object.defineProperty({__proto__:null,hasFileValues:uN,isFileValue:Ui,prepareFormDataWithFiles:fN,transformFormValuesWithFiles:pN},Symbol.toStringTag,{value:"Module"}));function mN(e){if(!e||typeof e!="object")return;const t=e;return(t.mode==="nested_by_section"?"nested_by_section":"flat")==="flat"?{mode:"flat"}:{mode:"nested_by_section",includeUnassignedAtRoot:t.includeUnassignedAtRoot!==!1}}function hN(e){if(!Array.isArray(e))return;const t=[];for(const r of e){if(!r||typeof r!="object")continue;const n=r,o=typeof n.id=="string"&&n.id.trim()?n.id.trim():"",s=typeof n.name=="string"&&n.name.trim()?n.name.trim():"";if(!o||!s)continue;const i=Array.isArray(n.fieldNames)?[...new Set(n.fieldNames.filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim()))]:[],a=typeof n.payloadKey=="string"&&n.payloadKey.trim()?n.payloadKey.trim():void 0;let d;if(n.fieldPayloadKeys&&typeof n.fieldPayloadKeys=="object"&&!Array.isArray(n.fieldPayloadKeys)){d={};for(const[u,l]of Object.entries(n.fieldPayloadKeys))typeof l=="string"&&l.trim()&&(d[u]=l.trim());Object.keys(d).length===0&&(d=void 0)}t.push({id:o,name:s,fieldNames:i,...n.showBorder===!0?{showBorder:!0}:{},...n.collapsible===!0?{collapsible:!0}:{},...n.defaultCollapsed===!0?{defaultCollapsed:!0}:{},...a?{payloadKey:a}:{},...d?{fieldPayloadKeys:d}:{},...n.heading&&typeof n.heading=="object"?{heading:n.heading}:{}})}return t.length>0?t:void 0}function mh(e){return e?.mode==="nested_by_section"}function hh(e){const t=e.payloadKey?.trim();return t||null}function gh(e,t){return t.fieldPayloadKeys?.[e]?.trim()||e}function yh(e,t,r,n){if(!mh(r)||!t?.length)return{...e};const o=new Set([]),s=r?.includeUnassignedAtRoot!==!1,i=new Set,a={};for(const d of t){const u=hh(d);if(!u)continue;const l={};for(const f of d.fieldNames){if(o.has(f)||!(f in e))continue;i.add(f);const p=gh(f,d);l[p]=e[f]}Object.keys(l).length>0&&(a[u]=l)}if(s)for(const[d,u]of Object.entries(e))o.has(d)||i.has(d)||(a[d]=u);return a}function gN(e,t,r){const n={...e??{}};if(!mh(r)||!t?.length)return n;for(const o of t){const s=hh(o);if(s)for(const i of o.fieldNames){if(n[i]?.trim())continue;const a=gh(i,o);n[i]=`${s}.${a}`}}return n}function yN(e){return e==="null"?null:e==="true"?!0:e==="false"?!1:e}function bN(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 vN(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,u=i.startsWith(`${n}__addmore__`);if(!d&&!u||!bN(a))return;const l=Qe(a,o);l==null||l===""||s.push(l)}),s}function Vi(e,t,r,n,o,s){const i=e.trim().match(/^\{respAll:([^}]+)\}$/);if(i){const u=(i[1]||"").trim(),l=u.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:vN(u,o)}const a=e.trim().match(/^\{(\w+)\}$/);if(a){const u=a[1],l=t[u];if(l!==void 0)return l;const f=Object.keys(t).find(p=>p.toLowerCase()===u.toLowerCase());if(f)return t[f]}const d=rn(e,t,r,n,o,s);return yN(String(d))}const wN=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d,onClick:u,onSubmit:l,onReset:f,onCancel:p,isSubmitting:m=!1,formValues:g={},submissionContext:h,bffSubmitApi:y,onBffSubmitResult:w,extraSubmitPayload:v,buttonResponses:x,onButtonApiResponse:E,onValidateForm:P,getValidationErrors:k,allFields:N,onSubmittingChange:C,scopedFormValues:A,scopedFieldNameMap:I,prepopulateResponse:T=null,formSections:W,submitPayload:X})=>{const{gridStretch:O}=zo(),[j,M]=S.useState(!1),D=e.properties,L=ha.useParams(),U=S.useMemo(()=>({...h,...v}),[h,v]),$=S.useMemo(()=>{if(!A||!I||Object.keys(I).length===0)return g;const Je={};return Object.entries(A).forEach(([q,$e])=>{const gt=I[q]||q;gt!==e.name&&(Je[gt]=$e)}),Je},[A,I,g,e.name]),V=(()=>{try{const Je=e.metadata;if(typeof Je=="string")return JSON.parse(Je);if(Je&&typeof Je=="object")return Je}catch{}return null})(),K=D?.submitAction??V?.submitAction,J=D?.apiEndpoint??e.apidata?.apiEndpoint??V?.apiEndpoint;let ce=D?.action||V?.action;!ce&&e.type==="button"&&(ce="submit");const ne=D?.variant||"default",G=D?.size||"default",ee=D?.hideLabel??e.appearance?.hideLabel??!1,Pe=D?.buttonText||e.label||"Button",oe=D?.closeOnCancel??!0,re=async()=>{if(A&&I&&Object.keys(I).length>0||!P)return!0;const Je=await P();if(!Je&&k)try{const q=k();$t.toast.error(ec(q,N??void 0)||"Please fix the errors before submitting.")}catch{$t.toast.error("Please fix the errors before submitting.")}return Je},be=async Je=>{if(Je.preventDefault(),(ce==="submit"?"submit":ce)==="submit"){if(y?.url){if(!await re())return;M(!0),C?.(!0);try{const $e=await ot(),gt=($e?.message??$e?.display_message??"Form submitted successfully!").trim();$t.toast.success(gt||"Form submitted successfully!");const Oe=$e!=null&&typeof $e=="object"?$e:{status:"success",...$e!=null?{data:$e}:{}};E?.(e.name,Oe)}catch($e){const gt=ls($e);$t.toast.error(gt)}finally{M(!1),C?.(!1)}return}if(l){if(!await re())return;M(!0),C?.(!0);try{await l(),E?.(e.name,{status:"success"})}finally{M(!1),C?.(!1)}return}$t.toast.error("Submit not configured. BFF submit API is required for submit buttons.");return}else if(ce==="reset"&&f)f();else if(ce==="cancel")oe?p&&p():f&&f();else if(ce==="download"){const $e=D?.downloadApiEndpoint||V?.downloadApiEndpoint||e.downloadApiEndpoint,gt=D?.downloadApiMethod||V?.downloadApiMethod||e.downloadApiMethod;if($e){M(!0);try{const Oe=gt||"GET",te=cn(rn($e,$,L,U,x,T??void 0)),pe={method:Oe,headers:{}};Oe!=="GET"&&Oe!=="DELETE"&&(pe.headers={"Content-Type":"application/json"});const We=await fetch(te,pe);if(!We.ok)throw new Error(`Download failed: ${We.statusText}`);const Pt=await We.blob(),je=window.URL.createObjectURL(Pt),Te=document.createElement("a");Te.href=je;const Xe=We.headers.get("Content-Disposition");let Ue="download";if(Xe){const ft=Xe.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);ft&&ft[1]&&(Ue=ft[1].replace(/['"]/g,""))}Te.download=Ue,document.body.appendChild(Te),Te.click(),document.body.removeChild(Te),window.URL.revokeObjectURL(je);try{const ft=lN(We);$t.toast.success(ft&&ft.trim()?ft:"Download started.")}catch{$t.toast.success("Download started.")}}catch(Oe){Zl(Oe,"Failed to download file. Please check the API endpoint and try again.",ls)}finally{M(!1)}}else $t.toast.error("Download endpoint is not configured")}else if(ce==="upload"||ce==="custom"){const $e=ce==="custom",gt=$e?"api":D?.uploadAction||V?.uploadAction||"database";if(gt==="database")if(l){M(!0);try{await l(Je)}catch(Oe){throw Oe}finally{M(!1)}}else $t.toast.error("Form submit handler is not available");else if(gt==="api"){const Oe=D?.uploadApiEndpoint||V?.uploadApiEndpoint||e.uploadApiEndpoint;if(D?.uploadApiMethod||V?.uploadApiMethod||e.uploadApiMethod,Oe){if(!await re())return;M(!0);try{const te=await Se();E?.(e.name,te),aN(te,$e?"Custom API call completed successfully!":"Upload completed successfully!")}catch(te){E?.(e.name,{status:"error",code:te?.response?.code??te?.response?.status??null,message:ls(te)}),Zl(te,$e?"Failed to call custom API. Please check the API endpoint and try again.":"Failed to upload. Please check the API endpoint and try again.",ls)}finally{M(!1)}}else $t.toast.error($e?"Custom API endpoint is not configured":"Upload endpoint is not configured")}else gt==="custom"&&$t.toast.info("Custom upload handler is not implemented")}else u?u():r&&t!==void 0&&r(t||"");n?.()},de=async()=>{if(!K||K!=="api"||!J)return null;const Je=D?.apiBodyFields??V?.apiBodyFields;if((D?.apiBodyFieldsOnly??V?.apiBodyFieldsOnly??!1)&&Je?.length){const Te={};return Je.forEach(({key:Xe,value:Ue})=>{const ft=Vi(Ue,$,L,U,x,T??void 0),St=Xe==="user_id"?"context_user_id":Xe;Te[St]=ft}),Te.user_id!==void 0&&Te.user_id!==null&&(Te.context_user_id=Te.context_user_id??Te.user_id,delete Te.user_id),Te}const $e=N?.length?tc($,N):$,gt=D?.apiFieldMapping??V?.apiFieldMapping,Oe=D?.apiFieldTypes??V?.apiFieldTypes,te=D?.apiBodyStructure??V?.apiBodyStructure,pe={...Oe};N?.length&&N.forEach(Te=>{const Xe=Te.name||Te.key;Xe&&(Te.type==="terms"||Te.type==="checkbox")&&(pe[Xe]="boolean")});const{transformFormValuesWithFiles:We}=await Promise.resolve().then(()=>ph),{transformed:Pt}=We($e,gt,pe);let je={};if(te==="flat"?je={...Pt}:je={data:{...Pt}},gt){const Te={};Object.keys(je).forEach(Xe=>{const Ue=gt[Xe]||Xe;Te[Ue]=je[Xe]}),je=Te}return Je?.length&&Je.forEach(({key:Te,value:Xe})=>{const Ue=Vi(Xe,$,L,U,x,T??void 0),ft=Te==="user_id"?"context_user_id":Te;je[ft]=Ue}),je.user_id!==void 0&&je.user_id!==null&&(je.context_user_id=je.context_user_id??je.user_id,delete je.user_id),je.data?.user_id!==void 0&&je.data?.user_id!==null&&(je.data.context_user_id=je.data.context_user_id??je.data.user_id,delete je.data.user_id),je},ot=async()=>{if(!y||!y.url)throw new Error("BFF submit API configuration is missing");const Je=N?.length?tc(g,N):g,q={};Object.keys(Je).forEach(ze=>{const yt=e.name===ze&&e.type==="button",pt=ze.toLowerCase().includes("button");!yt&&!pt&&(q[ze]=Je[ze])});const $e=Object.keys(q).filter(ze=>Ui(q[ze]));$e.forEach(ze=>{q[ze]=""});const gt=yh(q,W,X),Oe={workflow_id:y.payload?.workflow_id||"",current_step_id:y.payload?.current_step_id||"",form_data:gt},te=["workflow_id","current_step_id","form_data","submit_body","submit_api_endpoint","submit_api_method"];if(h&&typeof h=="object"&&Object.entries(h).forEach(([ze,yt])=>{if(yt==null||te.includes(ze))return;const pt=ze==="user_id"?"context_user_id":ze;Oe[pt]=Oe[pt]??yt}),v&&typeof v=="object"&&Object.entries(v).forEach(([ze,yt])=>{if(yt==null||te.includes(ze))return;const pt=ze==="user_id"?"context_user_id":ze;Oe[pt]=Oe[pt]??yt}),K==="api"&&J)try{const ze=await de();if(ze){const yt=D?.apiBodyStructure??V?.apiBodyStructure,pt=D?.apiFieldMapping??V?.apiFieldMapping;$e.forEach(Ut=>{const ur=pt?.[Ut]??Ut,Ar=q[Ut]!==void 0&&typeof q[Ut]=="string"?q[Ut]:"";yt==="flat"?ze[ur]=Ar:ze.data&&typeof ze.data=="object"?ze.data[ur]=Ar:ze[ur]=Ar}),Oe.submit_body=ze;let At=rn(J,$,L,U,x,T??void 0);At=At.replace(/\{([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}/gi,"$1"),At=cn(At),Oe.submit_api_endpoint=At,Oe.submit_api_method=D?.submitApiMethod||V?.submitApiMethod||"POST"}}catch{}const pe=(y.method||"POST").toUpperCase(),We=$e.length>0,Pt=Oe.submit_api_endpoint??J??"",je=typeof Pt=="string"?Pt.toLowerCase():"",Te=je.includes("/upload")||je.includes("/payments")||je.includes("/bulk-upload"),Xe=We&&Te;let Ue;const ft={...y.headers||{}};if(Xe){const ze=new FormData;ze.append("payload",JSON.stringify(Oe));for(const yt of $e){const pt=Je[yt],At=D?.apiFieldMapping?.[yt]??yt;pt instanceof File?ze.append(At,pt):Array.isArray(pt)&&pt.length>0&&pt[0]instanceof File&&pt.forEach(Ut=>ze.append(At,Ut))}Ue=ze,delete ft["content-type"],delete ft["Content-Type"]}else ft["Content-Type"]="application/json",Ue=JSON.stringify(Oe);const St=await fetch(y.url,{method:pe,headers:ft,body:Ue});if(!St.ok){let ze;const yt=await St.text();try{ze=JSON.parse(yt)}catch{ze={message:yt}}const pt=new Error(`BFF submission failed: ${St.status}`);throw pt.response=ze,pt}const xt=await St.json();return w?.(xt),l&&await l(),xt},Se=async()=>{const Je=D?.uploadApiEndpoint||V?.uploadApiEndpoint;if(!Je)throw new Error("Upload API endpoint is not configured");if(!D)throw new Error("Button properties are not configured");const q=(D.uploadApiMethod||"POST").toUpperCase(),$e=cn(rn(Je,$,L,U,x,T??void 0)),gt=D.apiBodyFieldsOnly??V?.apiBodyFieldsOnly??!1,Oe=D.apiBodyFieldsOnlyFormat??V?.apiBodyFieldsOnlyFormat??"json";let te={},pe;const We={};if(gt&&D.apiBodyFields&&D.apiBodyFields.length>0)if(D.apiBodyFields.forEach(({key:Te,value:Xe})=>{te[Te]=Vi(Xe,$,L,U,x,T??void 0)}),Oe==="multipart"){const Te=new FormData;Object.entries(te).forEach(([Xe,Ue])=>{if(Ue instanceof File){Te.append(Xe,Ue);return}if(Array.isArray(Ue)&&Ue.length>0&&Ue[0]instanceof File){Ue.forEach(ft=>Te.append(Xe,ft));return}Ue!=null&&Te.append(Xe,typeof Ue=="object"?JSON.stringify(Ue):String(Ue))}),pe=Te}else pe=JSON.stringify(te),We["Content-Type"]="application/json";else{const Te=$,{transformFormValuesWithFiles:Xe,prepareFormDataWithFiles:Ue,hasFileValues:ft}=await Promise.resolve().then(()=>ph),{transformed:St,hasFiles:xt}=Xe(Te,D.apiFieldMapping,D.apiFieldTypes);if((D.apiBodyStructure??V?.apiBodyStructure??"nested")==="flat"?te={...St}:te={data:{...St}},D.apiFieldMapping){const yt={};Object.keys(te).forEach(pt=>{const At=D.apiFieldMapping[pt]||pt;yt[At]=te[pt]}),te=yt}if(D.apiBodyFields&&D.apiBodyFields.forEach(({key:yt,value:pt})=>{te[yt]=Vi(pt,$,L,U,x,T??void 0)}),xt||ft(te)){const yt=Ue(te,D.apiFieldMapping);yt?pe=yt:(pe=JSON.stringify(te),We["Content-Type"]="application/json")}else pe=JSON.stringify(te),We["Content-Type"]="application/json"}D.apiHeaders&&D.apiHeaders.forEach(({key:Te,value:Xe})=>{const Ue=rn(Xe,$,L,U,x,T??void 0);(Te.toLowerCase()!=="content-type"||!(pe instanceof FormData))&&(We[Te]=Ue)});let Pt=$e;if(D.apiQueryParams&&D.apiQueryParams.length>0){const Te=new URLSearchParams;D.apiQueryParams.forEach(({key:Xe,value:Ue})=>{const ft=rn(Ue,$,L,U,x,T??void 0);Te.append(Xe,ft)}),Pt=`${$e}?${Te.toString()}`}const je=await fetch(Pt,{method:q,headers:We,body:q!=="GET"?pe:void 0});if(!je.ok){let Te;const Xe=await je.text();try{Te=JSON.parse(Xe)}catch{Te={message:Xe}}const Ue=new Error(`Upload failed: ${je.status}`);throw Ue.response=Te,Ue}try{return await je.json()}catch{return{}}},xe=ce==="submit"?"submit":ce,ve=xe==="submit"?"button":xe==="submit"?"submit":xe==="reset"?"reset":"button",Ye=s||e.disabled||i||e.readOnly||j||xe==="submit"&&m,ct=Pe,Ge=to(e),Kt=Fr(e.appearance)==="stretch";return c.jsx(Et,{field:e,error:o,isRequired:a,className:d,hideLabel:ee,children:c.jsx("div",{className:B(O&&!Ge&&"flex w-full min-w-0 flex-col",O&&Ge&&"min-w-0 shrink-0"),children:c.jsxs(Yt,{id:ht(e),type:ve,variant:ne,size:G,disabled:Ye,onClick:be,className:B(e.appearance?.className,O&&!Ge&&"w-full min-w-0 shrink-0",O&&Ge&&!Kt&&"inline-flex w-auto max-w-full shrink-0",O&&Ge&&Kt&&"inline-flex w-full min-w-0 max-w-full shrink-0"),children:[j&&c.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}),ct]})})})},SN=({field:e,disabled:t,readOnly:r,isRequired:n,className:o,buttonResponses:s,onButtonApiResponse:i})=>{const a=e.properties,d=a?.buttonText??e.label??"Edit",u=a?.variant??"outline",l=a?.size??"default",f=a?.hideLabel??e.appearance?.hideLabel??!1,p=e.name||e.key||e.id,m=Uo(s?.[p]),g=t||e.disabled||r||e.readOnly||m,h=y=>{y.preventDefault(),!g&&i?.(p,{status:"success"})};return c.jsx(Et,{field:e,error:void 0,isRequired:n,className:o,hideLabel:f,children:c.jsx(Yt,{id:ht(e),type:"button",variant:u,size:l,disabled:g,onClick:h,className:B(e.appearance?.className,(!to(e)||Fr(e.appearance)==="stretch")&&"w-full min-w-0"),children:d})})},xN=({field:e,error:t,disabled:r,readOnly:n,isRequired:o,className:s,onAddMore:i})=>{const a=e.properties||{},d=a.variant||"outline",u=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 c.jsx(Et,{field:e,error:t,isRequired:o,className:s,hideLabel:f,children:c.jsxs(Yt,{id:ht(e),type:"button",variant:d,size:u,disabled:!!p,onClick:i,className:B("w-fit",e.appearance?.className),children:[c.jsx(nu,{className:"h-4 w-4 mr-1"}),l]})})},bh=S.createContext(null);function AN({value:e,children:t}){return c.jsx(bh.Provider,{value:e,children:t})}function CN(){return S.useContext(bh)}function vh(e){const t=e.indexOf("__addmore__");return t>=0?e.slice(0,t):e}function cs(e){return e.name||e.key||e.id}function rc(e){return e.filter(t=>!t.parentId&&t.type==="sectionHeading"&&cs(t))}function EN(e){if(e.type!=="sectionHeading")return[];const t=e.properties||{};return Array.isArray(t.linkedFieldNames)?t.linkedFieldNames.filter(r=>typeof r=="string"&&r.trim().length>0):[]}function NN(e){const t=new Map;for(const r of rc(e)){const n=cs(r);for(const o of EN(r))t.set(o,n)}return t}function _N(e,t){const r=t.properties||{},n=Array.isArray(r.sectionHeadingNames)?r.sectionHeadingNames.filter(i=>typeof i=="string"&&i.trim()):[],o=rc(e);if(n.length===0)return o;const s=new Set(n);return o.filter(i=>s.has(cs(i)))}function kN(e){const t={};for(const r of rc(e))t[cs(r)]=!0;for(const r of e){if(r.type!=="customizeSections")continue;const n=r.properties||{};for(const o of n.defaultHiddenSectionNames??[])typeof o=="string"&&o.trim()&&(t[o.trim()]=!1)}return t}function wh(e,t,r,n){if(!e||t==="customizeSections")return!0;const o=vh(e),s=t==="sectionHeading"?o:n.get(o);return s?r[s]!==!1:!0}const TN=({field:e,error:t,disabled:r,readOnly:n,isRequired:o,className:s,designMode:i=!1})=>{const a=CN(),d=e.properties||{},u=d.variant||"outline",l=d.size||"default",f=d.buttonText||e.label||"Customise sections",p=d.menuTitle||"VISIBLE SECTIONS",m=d.hideLabel??e.appearance?.hideLabel??!1,g=r||n||e.disabled||e.readOnly,h=S.useMemo(()=>a?.allFields?.length?_N(a.allFields,e):[],[a?.allFields,e]);return c.jsx(Et,{field:e,error:t,isRequired:o,className:s,hideLabel:m,children:c.jsxs(Ol,{children:[c.jsx(Hp,{asChild:!0,children:c.jsxs(Yt,{id:ht(e),type:"button",variant:u,size:l,disabled:!!g,className:B("w-fit gap-2",e.appearance?.className),children:[c.jsx(Fv,{className:"h-4 w-4"}),f]})}),c.jsxs(Il,{align:"end",className:"w-64 p-0",children:[c.jsx("div",{className:"px-3 py-2 border-b",children:c.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wide text-muted-foreground",children:p})}),c.jsx("div",{className:"max-h-64 overflow-auto p-2 space-y-1",children:h.length===0?c.jsx("p",{className:"text-xs text-muted-foreground px-1 py-2",children:"No section headings on this form."}):h.map(y=>{const w=cs(y),v=y.label||w,x=i||!a?!0:a.visibility[w]!==!1;return c.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md px-1 py-1.5 hover:bg-muted/50",children:[c.jsx(Sn,{htmlFor:`ui-section-${e.id}-${w}`,className:"text-xs font-normal truncate",children:v}),c.jsx(Nm,{id:`ui-section-${e.id}-${w}`,checked:x,disabled:i||!a||!!g,onCheckedChange:E=>{!a||i||a.setSectionVisible(w,!!E)}})]},y.id)})})]})]})})},FN=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d})=>{const u=e.properties,l=u?.max||5,f=u?.icon||"star",p=h=>{s||i||e.disabled||e.readOnly||(r(h),n?.())},m=h=>{},g=h=>{const y=t>=h+1,w=B("transition-colors cursor-pointer",y?"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"?c.jsx(ou,{className:B(w,"h-6 w-6"),onClick:()=>p(h+1),onMouseEnter:()=>m()},h):c.jsx(ou,{className:B(w,"h-6 w-6"),onClick:()=>p(h+1),onMouseEnter:()=>m()},h)};return c.jsx(Et,{field:e,error:o,isRequired:a,className:d,children:c.jsxs("div",{id:ht(e),className:"flex items-center gap-1",role:"radiogroup","aria-label":e.label,"aria-describedby":jt(e,!!o),"aria-invalid":Jt(!!o),"aria-required":a,children:[Array.from({length:l},(h,y)=>g(y)),u?.showValue!==!1&&c.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:t>0?t:""})]})})};var Sh=["PageUp","PageDown"],xh=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Ah={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},vo="Slider",[nc,PN,ON]=Ba(vo),[Ch]=vr(vo,[ON]),[IN,Hi]=Ch(vo),Eh=b.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:u=[n],value:l,onValueChange:f=()=>{},onValueCommit:p=()=>{},inverted:m=!1,form:g,...h}=e,y=b.useRef(new Set),w=b.useRef(0),x=i==="horizontal"?MN:LN,[E=[],P]=Zr({prop:l,defaultProp:u,onChange:T=>{[...y.current][w.current]?.focus(),f(T)}}),k=b.useRef(E);function N(T){const W=zN(E,T);I(T,W)}function C(T){I(T,w.current)}function A(){const T=k.current[w.current];E[w.current]!==T&&p(E)}function I(T,W,{commit:X}={commit:!1}){const O=WN(s),j=RN(Math.round((T-n)/s)*s+n,O),M=qo(j,[n,o]);P((D=[])=>{const L=$N(D,M,W);if(HN(L,d*s)){w.current=L.indexOf(M);const U=String(L)!==String(D);return U&&X&&p(L),U?L:D}else return D})}return c.jsx(IN,{scope:e.__scopeSlider,name:r,disabled:a,min:n,max:o,valueIndexToChangeRef:w,thumbs:y.current,values:E,orientation:i,form:g,children:c.jsx(nc.Provider,{scope:e.__scopeSlider,children:c.jsx(nc.Slot,{scope:e.__scopeSlider,children:c.jsx(x,{"aria-disabled":a,"data-disabled":a?"":void 0,...h,ref:t,onPointerDown:Me(h.onPointerDown,()=>{a||(k.current=E)}),min:n,max:o,inverted:m,onSlideStart:a?void 0:N,onSlideMove:a?void 0:C,onSlideEnd:a?void 0:A,onHomeKeyDown:()=>!a&&I(n,0,{commit:!0}),onEndKeyDown:()=>!a&&I(o,E.length-1,{commit:!0}),onStepKeyDown:({event:T,direction:W})=>{if(!a){const j=Sh.includes(T.key)||T.shiftKey&&xh.includes(T.key)?10:1,M=w.current,D=E[M],L=s*j*W;I(D+L,M,{commit:!0})}}})})})})});Eh.displayName=vo;var[Nh,_h]=Ch(vo,{startEdge:"left",endEdge:"right",size:"width",direction:1}),MN=b.forwardRef((e,t)=>{const{min:r,max:n,dir:o,inverted:s,onSlideStart:i,onSlideMove:a,onSlideEnd:d,onStepKeyDown:u,...l}=e,[f,p]=b.useState(null),m=Ze(t,x=>p(x)),g=b.useRef(void 0),h=ro(o),y=h==="ltr",w=y&&!s||!y&&s;function v(x){const E=g.current||f.getBoundingClientRect(),P=[0,E.width],N=ic(P,w?[r,n]:[n,r]);return g.current=E,N(x-E.left)}return c.jsx(Nh,{scope:e.__scopeSlider,startEdge:w?"left":"right",endEdge:w?"right":"left",direction:w?1:-1,size:"width",children:c.jsx(kh,{dir:h,"data-orientation":"horizontal",...l,ref:m,style:{...l.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:x=>{const E=v(x.clientX);i?.(E)},onSlideMove:x=>{const E=v(x.clientX);a?.(E)},onSlideEnd:()=>{g.current=void 0,d?.()},onStepKeyDown:x=>{const P=Ah[w?"from-left":"from-right"].includes(x.key);u?.({event:x,direction:P?-1:1})}})})}),LN=b.forwardRef((e,t)=>{const{min:r,max:n,inverted:o,onSlideStart:s,onSlideMove:i,onSlideEnd:a,onStepKeyDown:d,...u}=e,l=b.useRef(null),f=Ze(t,l),p=b.useRef(void 0),m=!o;function g(h){const y=p.current||l.current.getBoundingClientRect(),w=[0,y.height],x=ic(w,m?[n,r]:[r,n]);return p.current=y,x(h-y.top)}return c.jsx(Nh,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:c.jsx(kh,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:h=>{const y=g(h.clientY);s?.(y)},onSlideMove:h=>{const y=g(h.clientY);i?.(y)},onSlideEnd:()=>{p.current=void 0,a?.()},onStepKeyDown:h=>{const w=Ah[m?"from-bottom":"from-top"].includes(h.key);d?.({event:h,direction:w?-1:1})}})})}),kh=b.forwardRef((e,t)=>{const{__scopeSlider:r,onSlideStart:n,onSlideMove:o,onSlideEnd:s,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:d,...u}=e,l=Hi(vo,r);return c.jsx(Be.span,{...u,ref:t,onKeyDown:Me(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):Sh.concat(xh).includes(f.key)&&(d(f),f.preventDefault())}),onPointerDown:Me(e.onPointerDown,f=>{const p=f.target;p.setPointerCapture(f.pointerId),f.preventDefault(),l.thumbs.has(p)?p.focus():n(f)}),onPointerMove:Me(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&o(f)}),onPointerUp:Me(e.onPointerUp,f=>{const p=f.target;p.hasPointerCapture(f.pointerId)&&(p.releasePointerCapture(f.pointerId),s(f))})})}),Th="SliderTrack",Fh=b.forwardRef((e,t)=>{const{__scopeSlider:r,...n}=e,o=Hi(Th,r);return c.jsx(Be.span,{"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation,...n,ref:t})});Fh.displayName=Th;var oc="SliderRange",Ph=b.forwardRef((e,t)=>{const{__scopeSlider:r,...n}=e,o=Hi(oc,r),s=_h(oc,r),i=b.useRef(null),a=Ze(t,i),d=o.values.length,u=o.values.map(p=>Mh(p,o.min,o.max)),l=d>1?Math.min(...u):0,f=100-Math.max(...u);return c.jsx(Be.span,{"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,...n,ref:a,style:{...e.style,[s.startEdge]:l+"%",[s.endEdge]:f+"%"}})});Ph.displayName=oc;var sc="SliderThumb",Oh=b.forwardRef((e,t)=>{const r=PN(e.__scopeSlider),[n,o]=b.useState(null),s=Ze(t,a=>o(a)),i=b.useMemo(()=>n?r().findIndex(a=>a.ref.current===n):-1,[r,n]);return c.jsx(DN,{...e,ref:s,index:i})}),DN=b.forwardRef((e,t)=>{const{__scopeSlider:r,index:n,name:o,...s}=e,i=Hi(sc,r),a=_h(sc,r),[d,u]=b.useState(null),l=Ze(t,v=>u(v)),f=d?i.form||!!d.closest("form"):!0,p=Jo(d),m=i.values[n],g=m===void 0?0:Mh(m,i.min,i.max),h=jN(n,i.values.length),y=p?.[a.size],w=y?UN(y,g,a.direction):0;return b.useEffect(()=>{if(d)return i.thumbs.add(d),()=>{i.thumbs.delete(d)}},[d,i.thumbs]),c.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${g}% + ${w}px)`},children:[c.jsx(nc.ItemSlot,{scope:e.__scopeSlider,children:c.jsx(Be.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:Me(e.onFocus,()=>{i.valueIndexToChangeRef.current=n})})}),f&&c.jsx(Ih,{name:o??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:m},n)]})});Oh.displayName=sc;var BN="RadioBubbleInput",Ih=b.forwardRef(({__scopeSlider:e,value:t,...r},n)=>{const o=b.useRef(null),s=Ze(o,n),i=Qo(t);return b.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]),c.jsx(Be.input,{style:{display:"none"},...r,ref:s,defaultValue:t})});Ih.displayName=BN;function $N(e=[],t,r){const n=[...e];return n[r]=t,n.sort((o,s)=>o-s)}function Mh(e,t,r){const s=100/(r-t)*(e-t);return qo(s,[0,100])}function jN(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function zN(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 UN(e,t,r){const n=e/2,s=ic([0,50],[0,n]);return(n-s(t)*r)*r}function VN(e){return e.slice(0,-1).map((t,r)=>e[r+1]-t)}function HN(e,t){if(t>0){const r=VN(e);return Math.min(...r)>=t}return!0}function ic(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 WN(e){return(String(e).split(".")[1]||"").length}function RN(e,t){const r=Math.pow(10,t);return Math.round(e*r)/r}var GN=Eh,KN=Fh,qN=Ph,YN=Oh;function XN({className:e,defaultValue:t,value:r,min:n=0,max:o=100,...s}){const i=b.useMemo(()=>Array.isArray(r)?r:Array.isArray(t)?t:[n,o],[r,t,n,o]);return c.jsxs(GN,{"data-slot":"slider",defaultValue:t,value:r,min:n,max:o,className:B("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:[c.jsx(KN,{"data-slot":"slider-track",className:B("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:c.jsx(qN,{"data-slot":"slider-range",className:B("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:i.length},(a,d)=>c.jsx(YN,{"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 JN=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d})=>{const u=e.properties,l=u?.min??0,f=u?.max??100,p=u?.step??1,m=u?.showValue!==!1,g=u?.marks||[],h=w=>{s||i||e.disabled||e.readOnly||(r(w[0]??l),n?.())},y=t??l;return c.jsx(Et,{field:e,error:o,isRequired:a,className:d,children:c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[m&&c.jsx("span",{className:"text-sm font-medium",children:y}),!m&&c.jsx("span",{className:"text-sm text-muted-foreground",children:l}),!m&&c.jsx("span",{className:"text-sm text-muted-foreground",children:f})]}),c.jsx(XN,{id:ht(e),value:[y],onValueChange:h,min:l,max:f,step:p,disabled:s||e.disabled||i||e.readOnly,className:B("w-full",o&&"border-destructive",e.appearance?.className),"aria-describedby":jt(e,!!o),"aria-invalid":Jt(!!o),"aria-required":a}),g.length>0&&c.jsx("div",{className:"flex justify-between text-xs text-muted-foreground",children:g.map((w,v)=>c.jsx("span",{className:"text-center",children:w.label},v))})]})})},QN=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d})=>{const u=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=u.current;if(!v)return;const x=v.getContext("2d");if(!x)return;const E=v.getBoundingClientRect(),P="touches"in w?w.touches[0].clientX-E.left:w.clientX-E.left,k="touches"in w?w.touches[0].clientY-E.top:w.clientY-E.top;x.beginPath(),x.moveTo(P,k)},[p]),g=S.useCallback(w=>{if(!l||p)return;const v=u.current;if(!v)return;const x=v.getContext("2d");if(!x)return;const E=v.getBoundingClientRect(),P="touches"in w?w.touches[0].clientX-E.left:w.clientX-E.left,k="touches"in w?w.touches[0].clientY-E.top:w.clientY-E.top;x.lineWidth=2,x.lineCap="round",x.strokeStyle="#000",x.lineTo(P,k),x.stroke(),x.beginPath(),x.moveTo(P,k)},[l,p]),h=S.useCallback(()=>{if(!l)return;f(!1);const w=u.current;if(!w)return;const v=w.toDataURL();r(v),n?.()},[l,r,n]),y=S.useCallback(()=>{const w=u.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=u.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]),c.jsx(Et,{field:e,error:o,isRequired:a,className:d,children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:B("border-2 border-dashed rounded-lg overflow-hidden",o&&"border-destructive",p&&"opacity-50 cursor-not-allowed"),children:c.jsx("canvas",{ref:u,id:ht(e),className:"w-full cursor-crosshair touch-none",onMouseDown:m,onMouseMove:g,onMouseUp:h,onMouseLeave:h,onTouchStart:m,onTouchMove:g,onTouchEnd:h,"aria-describedby":jt(e,!!o),"aria-invalid":Jt(!!o),"aria-required":a,style:{height:"200px"}})}),!p&&c.jsx("div",{className:"flex justify-end",children:c.jsxs(Yt,{type:"button",variant:"outline",size:"sm",onClick:y,className:"text-xs",children:[c.jsx(Go,{className:"h-3 w-3 mr-1"}),"Clear"]})})]})})},ZN=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d,hideRowControls:u=!1,formValues:l,submissionContext:f})=>{const p=e.properties,m=p?.columns||[],g=p?.minRows||1,h=p?.maxRows||10,y=!u&&p?.allowAddRow!==!1,w=!u&&p?.allowDeleteRow!==!1,v=s===!1&&i===!1?!1:s||e.disabled||i||e.readOnly,x=t||[],E=y&&x.length<h,P=w&&x.length>g,k=S.useCallback(()=>{if(!E||v)return;const O={};m.forEach(j=>{O[j.name]=j.defaultValue??""}),r([...x,O]),n?.()},[x,m,E,v,r,n]),N=S.useCallback(O=>{if(!P||v)return;const j=x.filter((M,D)=>D!==O);r(j),n?.()},[x,P,v,r,n]),C=S.useCallback((O,j,M)=>{if(v)return;const D=[...x];D[O]||(D[O]={}),D[O][j]=M,r(D),n?.()},[x,v,r,n]);if(S.useEffect(()=>{if(x.length<g){const O=g-x.length,j=[];for(let M=0;M<O;M++){const D={};m.forEach(L=>{D[L.name]=L.defaultValue??""}),j.push(D)}r([...x,...j])}},[g,m,r,x.length]),m.length===0)return c.jsx(Et,{field:e,error:o,isRequired:a,className:d,children:c.jsx("div",{className:"p-4 border rounded-md bg-muted/50 text-sm text-muted-foreground",children:"No columns defined for this table field"})});const A=Math.max(1,e.position?.rowSpan??1),I=Math.max(1,e.position?.columnSpan??1),T=Math.max(x.length,1),W=A>=3?"py-4":A>=2?"py-3":"py-2.5",X=I>=3?"px-4":I>=2?"px-3":"px-4";return c.jsx(Et,{field:e,error:o,isRequired:a,className:d,children:c.jsxs("div",{id:ht(e),className:B("flex h-full min-h-0 w-full min-w-0 flex-1 flex-col border rounded-lg overflow-hidden shadow-sm bg-background",o&&"border-destructive",v&&"opacity-50"),"aria-describedby":jt(e,!!o),"aria-invalid":Jt(!!o),"aria-required":a,children:[c.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:c.jsxs("table",{className:"w-full h-full min-h-full border-collapse text-sm table-fixed",style:p?.minWidth?{minWidth:p.minWidth}:void 0,children:[c.jsx("thead",{children:c.jsxs("tr",{className:"border-b border-border bg-muted/60",children:[m.map(O=>c.jsxs("th",{className:B(X,W,"text-left text-xs font-semibold uppercase tracking-wider text-muted-foreground whitespace-nowrap"),children:[O.label,a&&O.validation?.some(j=>j.type==="required")&&c.jsx("span",{className:"text-destructive ml-1",children:"*"})]},O.id)),w&&c.jsx("th",{className:"w-12"})]})}),c.jsx("tbody",{className:"h-full",children:x.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:m.length+(w?1:0),className:B(X,"py-8 text-center text-sm text-muted-foreground"),children:u?"No rows to display.":'No rows added yet. Click "Add Row" to get started.'})}):x.map((O,j)=>{const M=x[j],D=M&&typeof M=="object"&&!Array.isArray(M)?{...l??{},...M}:l;return c.jsxs("tr",{className:"border-b border-border/50 hover:bg-muted/30 transition-colors last:border-b-0",style:{height:`${100/T}%`},children:[m.map(L=>{const U={...L,name:`${e.name}_${j}_${L.name}`,appearance:{...L.appearance,hideLabel:!0}},$=L.name??"",ie=O[$]!==void 0?O[$]:$&&Object.keys(O).find(G=>G.toLowerCase()===$.toLowerCase())?O[Object.keys(O).find(G=>G.toLowerCase()===$.toLowerCase())]:void 0,V=!!L.readOnly,K=G=>{if(G==null)return"";if(Array.isArray(G))return G.map(ee=>typeof ee=="object"&&ee!==null&&"name"in ee?String(ee.name??ee):String(ee)).join(", ");if(typeof G=="object"&&G!==null&&!(G instanceof Date)){const ee=G;return typeof ee.name=="string"&&typeof ee.code=="string"?`${ee.code} ${ee.name}`.trim():typeof ee.name=="string"?ee.name:typeof ee.code=="string"?ee.code:String(ee.name??ee.code??G)}return String(G)},J=G=>typeof G=="object"&&G!==null&&!Array.isArray(G)?K(G):String(G??""),ce=L.name?.toLowerCase()==="type"||L.label?.toLowerCase()==="type";if(V){const G=K(ie);return c.jsx("td",{className:"px-4 py-2.5 align-middle first:pl-6 last:pr-6",children:c.jsx("div",{className:"min-w-[120px] text-sm text-foreground",children:ce&&G?c.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:G}):c.jsx("span",{className:"py-1 block",children:G})})},L.id)}const ne=()=>{switch(L.type){case"text":case"password":case"url":return c.jsx(Da,{field:U,value:J(ie),onChange:G=>C(j,L.name,G),disabled:v,readOnly:v,className:"w-full"});case"number":return c.jsx(Xd,{field:U,value:ie??null,onChange:G=>C(j,L.name,G),disabled:v,readOnly:v,className:"w-full"});case"email":return c.jsx(su,{field:U,value:J(ie),onChange:G=>C(j,L.name,G),disabled:v,readOnly:v,className:"w-full"});case"phone":case"aadhaar":return c.jsx(iu,{field:U,value:J(ie),onChange:G=>C(j,L.name,G),disabled:v,readOnly:v,className:"w-full"});case"textarea":return c.jsx(au,{field:U,value:J(ie),onChange:G=>C(j,L.name,G),disabled:v,readOnly:v,className:"w-full"});case"select":return c.jsx(kp,{field:U,value:typeof ie=="string"?ie:J(ie),onChange:G=>C(j,L.name,G),disabled:v,className:"w-full",formValues:D,submissionContext:f});case"multiselect":{const G=Array.isArray(ie)?ie:ie!=null&&ie!==""?[String(ie)]:[];return c.jsx(vm,{field:U,value:G,onChange:ee=>C(j,L.name,ee),disabled:v,className:"w-full",formValues:D,submissionContext:f})}case"asyncsearch":return c.jsx(Xp,{field:U,value:ie,onChange:G=>C(j,L.name,G),disabled:v,readOnly:v,className:"w-full",formValues:D,submissionContext:f});case"checkbox":return c.jsx(wm,{field:U,value:ie||!1,onChange:G=>C(j,L.name,G),disabled:v,className:"w-full"});case"radio":case"checkboxgroup":return c.jsx(Gm,{field:U,value:typeof ie=="string"?ie:J(ie),onChange:G=>C(j,L.name,G),disabled:v,className:"w-full"});case"date":case"time":case"datetime":case"daterange":return c.jsx(Km,{field:U,value:typeof ie=="string"?ie:J(ie),onChange:G=>C(j,L.name,G),disabled:v,readOnly:v,className:"w-full"});default:return c.jsx(Da,{field:U,value:J(ie),onChange:G=>C(j,L.name,G),disabled:v,readOnly:v,className:"w-full"})}};return c.jsx("td",{className:"px-4 py-2.5 align-middle first:pl-6 last:pr-6",children:c.jsx("div",{className:"min-w-[160px] w-full [&_input]:min-w-[10rem] [&_input]:overflow-visible [&_textarea]:min-h-[2.5rem]",children:ne()})},L.id)}),w&&c.jsx("td",{className:"px-2 py-2",children:c.jsx(Yt,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>N(j),disabled:!P||v,children:c.jsx(Go,{className:"h-4 w-4"})})})]},j)})})]})}),E&&c.jsx("div",{className:"shrink-0 p-3 border-t bg-muted/30",children:c.jsxs(Yt,{type:"button",variant:"outline",size:"sm",onClick:k,disabled:v,className:"w-full",children:[c.jsx(nu,{className:"h-4 w-4 mr-2"}),"Add Row"]})})]})})},e_="h-8 min-h-8 rounded-md border border-input bg-background px-2 text-sm shadow-none focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30",t_="flex min-h-8 w-full items-center gap-0.5 rounded-md border border-input bg-background px-2 focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/30",r_="h-8 min-w-[2ch] max-w-full flex-1 border-0 bg-transparent px-0 shadow-none focus-visible:ring-0";function Lh(e,t,r){const n=r?.emptyDisplay??"—";if(e==null||e==="")return n;const o=t?.format??"text",s=typeof e=="number"?e:Number(e);switch(o){case"currency":return Number.isNaN(s)?n:`${r?.currencySymbol??"₹"}${s.toLocaleString("en-IN",{minimumFractionDigits:0,maximumFractionDigits:2})}`;case"percent":return Number.isNaN(s)?n:`${s}%`;case"number":return Number.isNaN(s)?n:String(s);default:return String(e)}}function n_(e){const t=e.replace(/[^\d.-]/g,"");if(t===""||t==="-"||t===".")return null;const r=parseFloat(t);return Number.isNaN(r)?null:r}function o_(e){if(e==null||e==="")return"";const t=typeof e=="number"?e:Number(e);return Number.isNaN(t)?"":String(t)}function Dh(e,t){return Lh(e,{format:"currency"},t)}function ds(e){return e==null||e===""}function Bh(e){return e.mode??"editable"}function s_(e,t){return e.kind==="currency"||e.kind==="input"&&e.inputType==="number"?!0:t?.format==="currency"||t?.format==="number"||t?.format==="percent"}function $h(e,t,r){if(e!==void 0){if(e==="")return"";if(s_(t,r)){const n=Number(e);return Number.isNaN(n)?e:n}return e}}function ac(e,t){if(!(!e||!("defaultValue"in e)||e.defaultValue===void 0))return $h(e.defaultValue,e,t)}function lc(e,t,r){if(!t||!ds(e))return e;if(t.kind==="currency"&&Bh(t)==="static"&&t.value!==void 0)return $h(t.value,t,r);const n=ac(t,r);return n!==void 0?n:e}function i_(e,t,r){const n={...t};for(const[o,s]of Object.entries(e)){const i=r.find(d=>d.key===o);if(!ds(n[o]))continue;const a=lc(n[o],s,i);(!ds(a)||s&&"defaultValue"in s&&s.defaultValue==="")&&(n[o]=a)}return n}function Wi(e,t,r){if(!ds(e))return e;const n=ac(t,r);return n!==void 0?n:e}const a_=new Set(["all_items_summary","invoice_discount","grand_total"]);function l_(e,t){switch(t){case"dynamic":return e.filter(r=>r.rowKind==="dynamic");case"static":return e.filter(r=>r.rowKind==="static");case"all":return e;case"data":return e.filter(r=>r.rowKind==="dynamic"||r.rowKind==="static"&&!a_.has(r.slotId));default:return e}}function cc(e){if(typeof e=="number"&&!Number.isNaN(e))return e;const t=Number(e);return Number.isNaN(t)?0:t}function c_(e,t,r){const n=e.rowSlots.find(o=>o.kind==="static"?o.row.id===t.slotId:o.kind==="dynamic"&&o.block.id===t.slotId);if(n)return n.kind==="static"?n.row.cells[r]:n.block.cells[r]}function d_(e,t,r){const n=u=>cc(r.values[u]),o=(u,l)=>{const f=t.find(p=>p.slotId===u&&p.rowKind==="static");return f?cc(f.values[l]):0},s=(u,l="all")=>l_(t,l).reduce((f,p)=>f+cc(p.values[u]),0),i={...Ds.functions,cell:n,cellInRow:o,SUM:s},a=Object.keys(i),d=Object.values(i);try{const u=new Function(...a,`return (${e});`)(...d);return u==null||typeof u=="number"&&Number.isNaN(u)?null:u}catch{return null}}function wo(e,t){const r=t.rows.map(n=>({...n,values:{...n.values}}));for(const n of r)for(const o of e.columns){const s=c_(e,n,o.key);if(s?.kind==="formula"){const i=d_(s.expression,r,n),a=e.columns.find(d=>d.key===o.key);n.values[o.key]=ds(i)?ac(s,a)??i:i}}return{rows:r}}function u_(e,t,r,n,o,s){const i=t.rows.map(a=>a.rowInstanceId!==r||a.slotId!==n?a:{...a,values:{...a.values,[o]:s}});return wo(e,{rows:i})}function jh(e,t,r=[]){return t.map((n,o)=>{const s=typeof n=="object"&&n!==null?n:{},i=e.rowIdField&&s[e.rowIdField]!=null?String(s[e.rowIdField]):String(o),a={};for(const[u,l]of Object.entries(e.cells)){const f=r.find(p=>p.key===u);(l.kind==="api"&&l.path||l.kind==="currency"&&l.mode==="api"&&l.path)&&(a[u]=Wi(Qe(s,l.path),l,f))}const d=a.service??a.tariff_type;return{slotId:e.id,rowKind:"dynamic",rowInstanceId:i,label:typeof d=="string"?d:void 0,values:a}})}function dc(e,t,r){const n=[];for(const o of e.rowSlots)if(o.kind==="static"){const s=t.get(o.row.id);s&&n.push(s)}else n.push(...r.get(o.block.id)??[]);return n}function uc(e,t){const r=new Map,n=new Map;for(const o of e.rowSlots)if(o.kind==="static"){const s=t?.rows.find(i=>i.slotId===o.row.id&&i.rowKind==="static");r.set(o.row.id,{slotId:o.row.id,rowKind:"static",rowInstanceId:o.row.id,label:o.row.label,values:i_(o.row.cells,s?.values?{...s.values}:{},e.columns)})}else{const s=t?.rows.filter(i=>i.slotId===o.block.id&&i.rowKind==="dynamic")??[];n.set(o.block.id,s.map(i=>({...i,values:{...i.values}})))}return{rows:dc(e,r,n)}}function f_(e,t,r,n){const o=uc(e,n),s=e.rowSlots.find(d=>d.kind==="dynamic"&&d.block.id===t);if(!s||s.kind!=="dynamic")return wo(e,o);const i=new Map,a=new Map;for(const d of e.rowSlots)if(d.kind==="static"){const u=o.rows.find(l=>l.slotId===d.row.id&&l.rowKind==="static");u&&i.set(d.row.id,{...u,values:{...u.values}})}else{const u=d.block.id===t?jh(d.block,r,e.columns):o.rows.filter(l=>l.slotId===d.block.id&&l.rowKind==="dynamic");a.set(d.block.id,u.map(l=>({...l,values:{...l.values}})))}return wo(e,{rows:dc(e,i,a)})}function p_(e,t,r){const n=uc(e,r);if(t==null||typeof t!="object"||Array.isArray(t))return wo(e,n);const o=t,s=new Map,i=new Map;for(const a of e.rowSlots)if(a.kind==="static"){const u={...n.rows.find(f=>f.slotId===a.row.id&&f.rowKind==="static")?.values??{}},l=o[a.row.id]??o;for(const[f,p]of Object.entries(a.row.cells)){const m=e.columns.find(g=>g.key===f);(p.kind==="api"&&p.path||p.kind==="currency"&&p.mode==="api"&&p.path)&&(u[f]=Wi(Qe(l,p.path),p,m))}s.set(a.row.id,{slotId:a.row.id,rowKind:"static",rowInstanceId:a.row.id,label:a.row.label,values:u})}else{const d=a.block.apiArrayPath??a.block.id,u=Qe(o,d);i.set(a.block.id,Array.isArray(u)?jh(a.block,u,e.columns):[])}return wo(e,{rows:dc(e,s,i)})}function zh(e){if(!e)return"";const t=[];switch(e.fontSize){case"xs":t.push("text-xs");break;case"sm":t.push("text-sm");break;case"base":t.push("text-base");break;case"lg":t.push("text-lg");break;case"xl":t.push("text-xl");break}return e.bold?t.push("font-bold"):e.fontSize&&t.push("font-medium"),e.italic&&t.push("italic"),e.underline&&t.push("underline"),t.join(" ")}function m_(e){const t=e?.color?.trim();return t?{color:t}:{}}function fc(e){return{className:zh(e),style:m_(e)}}function h_(e){return e?!!(e.fontSize||e.bold||e.italic||e.underline||e.color?.trim()):!1}function g_(e,t){if(!e&&!t)return;const r={...e,...t};return h_(r)?r:void 0}function y_(e,t){const r=e?.kind==="label"?g_(t,e.cellStyle):e?.cellStyle;return fc(r)}function pc(e){return e==="center"?"text-center":e==="right"?"text-right":"text-left"}function Uh(e,t){return e?.align?e.align:t?.align??"left"}function b_(e,t,r){return e.rowSlots.find(n=>r==="static"?n.kind==="static"&&n.row.id===t:n.kind==="dynamic"&&n.block.id===t)}function Vh(e,t,r,n){const o=e.rowSlots.find(s=>r==="static"?s.kind==="static"&&s.row.id===t:s.kind==="dynamic"&&s.block.id===t);if(o)return o.kind==="static"?o.row.cells[n]:o.block.cells[n]}const v_=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d})=>{const u=e.properties??{},l=u.columns??[],f=u.currencySymbol??"₹",p=u.emptyDisplay??"—",m=s||i,g=S.useMemo(()=>{const N=uc(u,t);return wo(u,N)},[u,t]);S.useEffect(()=>{!t?.rows?.length&&g.rows.length&&r(g)},[t,g,r]);const h=S.useCallback((N,C,A,I,T)=>{if(m)return;const W=T==="number"?n_(I):I===""?null:I,X=u_(u,g,N,C,A,W);r(X)},[m,g,r,u]),y=(N,C,A,I,T,W)=>{const X=l.find($=>$.key===T),O=Vh(u,N,C,T),j=pc(Uh(O,X)),M=lc(W,O,X),D=b_(u,N,C),L=D?.kind==="static"?D.row.labelStyle:D?.kind==="dynamic"?D.block.labelStyle:void 0,U=y_(O,L);if(O?.kind==="label")return c.jsx("span",{className:B(U.className||"font-medium",j,!U.style.color&&"text-foreground"),style:U.style,children:I??p});if(O?.kind==="input"&&!m){const $=M==null||M===""?"":String(M);return c.jsx(wn,{type:"text",inputMode:O.inputType==="number"?"decimal":"text",value:$,onChange:ie=>h(A,N,T,ie.target.value,O.inputType),onBlur:n,className:B(e_,j,U.className),style:U.style,disabled:m})}if(O?.kind==="currency"){const $=Bh(O);if($==="static"){const V=O.value!==void 0&&O.value!==""?lc(null,{...O,mode:"static"},X):M;return c.jsx("span",{className:B("tabular-nums",j,U.className),style:U.style,children:Dh(V,{currencySymbol:f,emptyDisplay:p})})}if($==="api"||m)return c.jsx("span",{className:B("tabular-nums",j,U.className),style:U.style,children:Dh(M,{currencySymbol:f,emptyDisplay:p})});const ie=o_(M);return c.jsxs("div",{className:B(t_,j==="text-center"&&"justify-center",j==="text-right"&&"justify-end",j==="text-left"&&"justify-start",U.className),style:U.style,children:[c.jsx("span",{className:"shrink-0 tabular-nums",children:f}),c.jsx(wn,{type:"text",inputMode:"decimal",value:ie,onChange:V=>h(A,N,T,V.target.value,"number"),onBlur:n,className:r_,disabled:m})]})}return O?.kind==="static"?c.jsx("span",{className:B(j,U.className,!U.style.color&&"text-muted-foreground"),style:U.style,children:O.value}):c.jsx("span",{className:B(j,U.className),style:U.style,children:Lh(M,X,{currencySymbol:f,emptyDisplay:p})})},w=u.gridTitle?.trim()??"",v=Math.max(1,e.position?.rowSpan??1),x=Math.max(1,e.position?.columnSpan??1),E=Math.max(g.rows.length,1),P=v>=3?"py-4":v>=2?"py-3":"py-2",k=x>=3?"px-4":x>=2?"px-3":"px-2";return l.length===0?c.jsx(Et,{field:e,error:o,isRequired:a,className:d,children:c.jsx("div",{className:"p-4 border rounded-md bg-muted/50 text-sm text-muted-foreground",children:"No columns defined for this billing grid"})}):c.jsx(Et,{field:e,error:o,isRequired:a,className:d,children:c.jsxs("div",{id:ht(e),className:B("flex h-full min-h-0 w-full min-w-0 max-w-full flex-1 flex-col border rounded-lg overflow-hidden shadow-sm bg-background",o&&"border-destructive",m&&"opacity-70"),"aria-describedby":jt(e,!!o),"aria-invalid":Jt(!!o),"aria-required":a,children:[w?c.jsx("div",{className:B("shrink-0 px-4 py-2 border-b bg-muted/40",zh(u.gridTitleStyle)||"text-muted-foreground"),style:fc(u.gridTitleStyle).style,children:w}):null,c.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:c.jsxs("table",{className:"w-full h-full min-h-full border-collapse text-sm table-fixed",style:u.minWidth?{minWidth:u.minWidth}:void 0,children:[c.jsx("thead",{children:c.jsx("tr",{className:"border-b border-border bg-muted/60",children:l.map(N=>{const C=fc(N.headerStyle);return c.jsx("th",{className:B(k,P,"text-xs uppercase tracking-wider whitespace-nowrap",pc(N.align),C.className||"font-semibold text-muted-foreground"),style:C.style,children:N.label},N.id)})})}),c.jsx("tbody",{className:"h-full",children:g.rows.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:l.length,className:B(k,"py-8 text-center text-sm text-muted-foreground"),children:"No billing rows configured"})}):g.rows.map(N=>c.jsx("tr",{className:"border-b border-border/60",style:{height:`${100/E}%`},children:l.map(C=>{const A=Vh(u,N.slotId,N.rowKind,C.key),I=Uh(A,C);return c.jsx("td",{className:B(k,P,"align-middle whitespace-nowrap",pc(I)),children:y(N.slotId,N.rowKind,N.rowInstanceId,N.label,C.key,N.values[C.key])},C.id)})},`${N.slotId}-${N.rowInstanceId}`))})]})})]})})};function mc(e,t,r){return p_(e,t,r)}const w_=({field:e,value:t,error:r,disabled:n,isRequired:o,className:s,formValues:i={},submissionContext:a,extraSubmitPayload:d,skipApiCall:u=!1,prepopulateResponse:l=null})=>{const f=e.properties||{},p=f.source??"manual",m=Array.isArray(f.statuses)?f.statuses:[],g=(f.dataPath||"data").trim(),h=f.showStatusText===!0,y=(f.statusTextPath||"data.admissionStatus").trim(),w=f.showCurrentIndicator!==!1,[v,x]=S.useState(null),[E,P]=S.useState(!1),[k,N]=S.useState(null),C=ha.useParams(),A=S.useRef(i),I=S.useRef(a),T=S.useRef(d),W=S.useRef(C);A.current=i,I.current=a,T.current=d,W.current=C;const X=S.useCallback(async()=>{const L=f.apiEndpoint?.trim();if(!L){N("Status API endpoint is not configured");return}P(!0),N(null);try{const U=I.current,$=T.current,ie=U!=null&&typeof U=="object"?{...U,...$||{}}:$||{},V=cn(rn(L,A.current,W.current,ie,void 0,l??void 0)),K=(f.apiMethod||"GET").toUpperCase(),J=await fetch(V,{method:K,headers:K==="POST"?{"Content-Type":"application/json"}:void 0});if(!J.ok)throw new Error(`HTTP ${J.status}`);const ce=await J.json(),ne=g?Qe(ce,g):ce;x(ne&&typeof ne=="object"?ne:{})}catch(U){N(U instanceof Error?U.message:"Failed to load status"),x(null)}finally{P(!1)}},[f.apiEndpoint,f.apiMethod,g,l]);S.useEffect(()=>{p==="api"&&!u&&X()},[p,u,X]);const O=p==="api"?v:t&&typeof t=="object"?(g?Qe(t,g):null)??t:null,j=h&&y&&O?String(Qe(O,y)??Qe({data:O},y)??""):"",M=L=>{if(!O||typeof O!="object")return!1;const U=O[L];return U===!0||U==="true"||U===1};let D=!1;return c.jsx(Et,{field:e,error:r||k||void 0,isRequired:o,className:B(s,"!space-y-0 h-full min-h-0 flex flex-col"),children:c.jsxs("div",{className:"rounded-lg border bg-card p-4 h-full min-h-0 flex flex-col",children:[E&&c.jsx("div",{className:"text-sm text-muted-foreground py-2",children:"Loading status..."}),h&&j&&!E&&c.jsx("p",{className:"text-sm text-muted-foreground mb-3 shrink-0","data-status-text":!0,children:j}),!E&&c.jsx("ul",{className:"flex-1 min-h-0 flex flex-col gap-y-8 overflow-y-auto pr-1 py-1",children:m.map(L=>{const U=M(L.key),$=w&&U&&!D;return $&&(D=!0),c.jsxs("li",{className:B("flex items-center gap-3 text-sm",U?"text-foreground":"text-muted-foreground"),children:[U?c.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:c.jsx(Vs,{className:"h-3 w-3"})}):c.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:c.jsx(eu,{className:"h-2.5 w-2.5 text-muted-foreground/60"})}),c.jsx("span",{className:"flex-1 min-w-0",children:L.label}),$&&c.jsx("span",{className:"shrink-0 text-xs font-medium text-primary",children:"Current"})]},L.key)})}),!E&&m.length===0&&c.jsx("p",{className:"text-sm text-muted-foreground",children:"No statuses configured."})]})})};function hc(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 So(e,t){if(t){const r=hc(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 S_(e,t,r,n){if(r?.length){const s=n??" | ",i=r.map(a=>hc(e,a)).filter(a=>a!=null).map(a=>String(a));if(i.length)return i.join(s)}if(t){const s=hc(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 x_=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a,submissionContext:d})=>{const u=e.properties||{},{dataSourceContextKey:l,labelField:f="name",valueField:p="email",displayFields:m,displayFieldsSeparator:g=" | ",showSelectAll:h=!0,selectAllByDefault:y=!0}=u;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 T=d[l];return Array.isArray(T)?T:[]},[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(T=>{const W=T.length===0||t.length>T.length?t:T;return console.log("[SelectableList] Step 3: sync fullList from value",{fieldName:e.name,valueLength:t.length,prevLength:T.length,nextLength:W.length}),W})},[w,t]);const E=S.useMemo(()=>{const T=Array.isArray(t)?t:[];return new Set(T.map(X=>So(X,p)))},[t,p]),P=v.length>0&&v.every(T=>E.has(So(T,p))),k=v.some(T=>E.has(So(T,p))),N=S.useCallback((T,W)=>{const X=So(T,p),O=Array.isArray(t)?t:[];W?E.has(X)||r([...O,T]):r(O.filter(j=>So(j,p)!==X)),n?.()},[t,p,E,r,n]),C=S.useCallback(T=>{r(T===!0?[...v]:[]),n?.()},[v,r,n]),A=v.length>0?v:Array.isArray(t)?t:[],I=s||e.disabled;return console.log("[SelectableList] Data in list",{fieldName:e.name,listLength:A.length,listSource:v.length>0?"fullList":"value",valueLength:Array.isArray(t)?t.length:0,fullListLength:v.length,listData:A.length>0?A:[],listDataFirstThree:A.length>0?A.slice(0,3):[]}),c.jsx("div",{className:B("relative z-10 flex flex-col min-h-0 h-full w-full",A.length>0&&"min-h-[14rem]",a),children:c.jsx(Et,{field:e,error:o,isRequired:i,className:B("flex-1 min-h-0 flex flex-col",A.length>0&&"min-h-[14rem]"),children:c.jsx("div",{className:B("flex-1 min-h-0 flex flex-col",A.length>0&&"min-h-[14rem]"),children:c.jsxs("div",{className:B("flex-1 min-h-0 flex flex-col",A.length>0&&"overflow-visible"),children:[c.jsxs("div",{role:"listbox","aria-multiselectable":!0,className:B("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",A.length>0?"flex-1 min-h-0":"min-h-0"),children:[h&&A.length>0&&c.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:[c.jsx(Ti,{id:`${ht(e)}-select-all`,checked:P?!0:k?"indeterminate":!1,onCheckedChange:C,disabled:I,"aria-label":"Select all"}),c.jsxs(Sn,{htmlFor:`${ht(e)}-select-all`,className:"text-sm font-medium cursor-pointer",children:["Select all (",A.length,")"]}),c.jsxs("div",{className:"flex gap-1 ml-auto",children:[c.jsx(Yt,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I||P,onClick:()=>{r([...v]),n?.()},children:"Select all"}),c.jsx(Yt,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I||!k,onClick:()=>{r([]),n?.()},children:"Unselect all"})]})]}),A.length===0?c.jsx("p",{className:"px-3 py-4 text-sm text-muted-foreground",children:"No items to display."}):c.jsx(c.Fragment,{children:A.map((T,W)=>{const X=So(T,p),O=E.has(X),j=`${ht(e)}-${W}-${X}`;return c.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:[c.jsx(Ti,{id:j,checked:O,onCheckedChange:M=>N(T,M===!0),disabled:I,"aria-describedby":jt(e,!!o)}),c.jsx(Sn,{htmlFor:j,className:"text-sm cursor-pointer flex-1 truncate",children:S_(T,f,m,g)})]},X)})})]}),A.length>0&&E.size===0&&c.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:[c.jsx(_v,{className:"h-4 w-4 shrink-0"}),"Please select at least one item."]})]})})})})},Hh=({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),u=()=>{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 c.jsxs("div",{className:B("border rounded-lg bg-card",r),children:[c.jsxs("div",{className:B("flex items-center gap-2 px-4 py-3 border-b bg-muted/50",o&&"cursor-pointer hover:bg-muted/70 transition-colors"),onClick:u,children:[o&&c.jsx("span",{className:"text-muted-foreground",children:a?c.jsx(Zd,{className:"h-4 w-4"}):c.jsx(Wo,{className:"h-4 w-4"})}),c.jsx("h3",{className:"font-medium text-sm",children:e.label}),e.description&&c.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:e.description})]}),!a&&c.jsx("div",{className:B("p-4 grid gap-4",l[i]),children:t})]})};var A_=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],C_=A_.reduce((e,t)=>{const r=La(`Primitive.${t}`),n=b.forwardRef((o,s)=>{const{asChild:i,...a}=o,d=i?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c.jsx(d,{...a,ref:s})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{}),E_="Separator",Wh="horizontal",N_=["horizontal","vertical"],Rh=b.forwardRef((e,t)=>{const{decorative:r,orientation:n=Wh,...o}=e,s=__(n)?n:Wh,a=r?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return c.jsx(C_.div,{"data-orientation":s,...a,...o,ref:t})});Rh.displayName=E_;function __(e){return N_.includes(e)}var k_=Rh;function gc({className:e,orientation:t="horizontal",decorative:r=!0,...n}){return c.jsx(k_,{"data-slot":"separator",decorative:r,orientation:t,className:B("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 T_=({field:e,className:t})=>c.jsx("div",{className:B("py-2",t),children:c.jsx(gc,{})}),F_={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"},P_=({field:e,className:t})=>{const r=e.properties,n=r?.headingLevel??"h3",o=r?.showHorizontalLine??!0,s=F_[n],i=n;return c.jsxs("div",{className:B("w-full min-w-0 space-y-1",t),children:[c.jsx(i,{className:B("m-0 text-foreground",s),children:e.label||"Header"}),e.description&&c.jsx("p",{className:"text-sm text-muted-foreground",children:e.description}),o&&c.jsx(gc,{className:"w-full"})]})},O_={"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"},I_={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"},M_=({field:e,className:t})=>{const r=e.properties,n=r?.position??"top-left",o=r?.headingLevel??"h3",s=r?.showHorizontalLine??!0,i=O_[n],a=I_[o],d=o;return c.jsxs("div",{className:B("w-full min-w-0 space-y-2",t),children:[c.jsx("div",{className:B("flex w-full",i),children:c.jsx(d,{className:B("m-0 text-foreground",a),children:e.label||"Section Heading"})}),s&&c.jsx(gc,{className:"w-full"})]})},L_=({field:e,className:t})=>{const r=e.appearance?.size||"md",n={sm:"h-4",md:"h-8",lg:"h-12"};return c.jsx("div",{className:B(n[r],t),"aria-hidden":"true"})};function Gh(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 D_(e){if(Array.isArray(e))return e}function B_(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,u=!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){u=!0,o=l}finally{try{if(!d&&r.return!=null&&(i=r.return(),Object(i)!==i))return}finally{if(u)throw o}}return a}}function $_(){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 j_(e,t){return D_(e)||B_(e,t)||z_(e,t)||$_()}function z_(e,t){if(e){if(typeof e=="string")return Gh(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)?Gh(e,t):void 0}}const Kh=Object.entries,qh=Object.setPrototypeOf,U_=Object.isFrozen,V_=Object.getPrototypeOf,H_=Object.getOwnPropertyDescriptor;let lr=Object.freeze,Mr=Object.seal,xo=Object.create,Yh=typeof Reflect<"u"&&Reflect,yc=Yh.apply,bc=Yh.construct;lr||(lr=function(t){return t}),Mr||(Mr=function(t){return t}),yc||(yc=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)}),bc||(bc=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 Ao=zt(Array.prototype.forEach),W_=zt(Array.prototype.lastIndexOf),Xh=zt(Array.prototype.pop),Co=zt(Array.prototype.push),R_=zt(Array.prototype.splice),cr=Array.isArray,us=zt(String.prototype.toLowerCase),vc=zt(String.prototype.toString),Jh=zt(String.prototype.match),Eo=zt(String.prototype.replace),Qh=zt(String.prototype.indexOf),G_=zt(String.prototype.trim),K_=zt(Number.prototype.toString),q_=zt(Boolean.prototype.toString),Zh=typeof BigInt>"u"?null:zt(BigInt.prototype.toString),eg=typeof Symbol>"u"?null:zt(Symbol.prototype.toString),Ot=zt(Object.prototype.hasOwnProperty),fs=zt(Object.prototype.toString),Zt=zt(RegExp.prototype.test),Ri=Y_(TypeError);function zt(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 yc(e,t,n)}}function Y_(e){return function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return bc(e,r)}}function nt(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:us;if(qh&&qh(e,null),!cr(t))return e;let n=t.length;for(;n--;){let o=t[n];if(typeof o=="string"){const s=r(o);s!==o&&(U_(t)||(t[n]=s),o=s)}e[o]=!0}return e}function X_(e){for(let t=0;t<e.length;t++)Ot(e,t)||(e[t]=null);return e}function hr(e){const t=xo(null);for(const n of Kh(e)){var r=j_(n,2);const o=r[0],s=r[1];Ot(e,o)&&(cr(s)?t[o]=X_(s):s&&typeof s=="object"&&s.constructor===Object?t[o]=hr(s):t[o]=s)}return t}function J_(e){switch(typeof e){case"string":return e;case"number":return K_(e);case"boolean":return q_(e);case"bigint":return Zh?Zh(e):"0";case"symbol":return eg?eg(e):"Symbol()";case"undefined":return fs(e);case"function":case"object":{if(e===null)return fs(e);const t=e,r=Kn(t,"toString");if(typeof r=="function"){const n=r(t);return typeof n=="string"?n:fs(n)}return fs(e)}default:return fs(e)}}function Kn(e,t){for(;e!==null;){const n=H_(e,t);if(n){if(n.get)return zt(n.get);if(typeof n.value=="function")return zt(n.value)}e=V_(e)}function r(){return null}return r}function Q_(e){try{return Zt(e,""),!0}catch{return!1}}const tg=lr(["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"]),wc=lr(["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"]),Sc=lr(["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"]),Z_=lr(["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"]),xc=lr(["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"]),ek=lr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),rg=lr(["#text"]),ng=lr(["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"]),Ac=lr(["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"]),og=lr(["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"]),Gi=lr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),tk=Mr(/{{[\w\W]*|^[\w\W]*}}/g),rk=Mr(/<%[\w\W]*|^[\w\W]*%>/g),nk=Mr(/\${[\w\W]*/g),ok=Mr(/^data-[\-\w.\u00B7-\uFFFF]+$/),sk=Mr(/^aria-[\-\w]+$/),sg=Mr(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ik=Mr(/^(?:\w+script|data):/i),ak=Mr(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),lk=Mr(/^html$/i),ck=Mr(/^[a-z][.\w]*(-[.\w]+)+$/i),No={element:1,text:3,progressingInstruction:7,comment:8,document:9},dk=function(){return typeof window>"u"?null:window},uk=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}},ig=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function ag(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:dk();const t=Ee=>ag(Ee);if(t.version="3.4.5",t.removed=[],!e||!e.document||e.document.nodeType!==No.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,u=e.NodeFilter,l=e.NamedNodeMap,f=l===void 0?e.NamedNodeMap||e.MozNamedAttrMap:l,p=e.HTMLFormElement,m=e.DOMParser,g=e.trustedTypes,h=d.prototype,y=Kn(h,"cloneNode"),w=Kn(h,"remove"),v=Kn(h,"nextSibling"),x=Kn(h,"childNodes"),E=Kn(h,"parentNode"),P=a&&a.prototype?Kn(a.prototype,"nodeType"):null;if(typeof i=="function"){const Ee=r.createElement("template");Ee.content&&Ee.content.ownerDocument&&(r=Ee.content.ownerDocument)}let k,N="";const C=r,A=C.implementation,I=C.createNodeIterator,T=C.createDocumentFragment,W=C.getElementsByTagName,X=n.importNode;let O=ig();t.isSupported=typeof Kh=="function"&&typeof E=="function"&&A&&A.createHTMLDocument!==void 0;const j=tk,M=rk,D=nk,L=ok,U=sk,$=ik,ie=ak,V=ck;let K=sg,J=null;const ce=nt({},[...tg,...wc,...Sc,...xc,...rg]);let ne=null;const G=nt({},[...ng,...Ac,...og,...Gi]);let ee=Object.seal(xo(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}})),Pe=null,oe=null;const re=Object.seal(xo(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let be=!0,de=!0,ot=!1,Se=!0,xe=!1,ae=!0,ve=!1,Ye=!1,ct=!1,Ge=!1,Kt=!1,Je=!1,q=!0,$e=!1;const gt="user-content-";let Oe=!0,te=!1,pe={},We=null;const Pt=nt({},["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 je=null;const Te=nt({},["audio","video","img","source","image","track"]);let Xe=null;const Ue=nt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ft="http://www.w3.org/1998/Math/MathML",St="http://www.w3.org/2000/svg",xt="http://www.w3.org/1999/xhtml";let ze=xt,yt=!1,pt=null;const At=nt({},[ft,St,xt],vc);let Ut=nt({},["mi","mo","mn","ms","mtext"]),ur=nt({},["annotation-xml"]);const Ar=nt({},["title","style","font","a","script"]);let Vt=null;const Po=["application/xhtml+xml","text/html"],Xn="text/html";let Ct=null,Cr=null;const Jn=r.createElement("form"),It=function(F){return F instanceof RegExp||F instanceof Function},Er=function(){let F=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Cr&&Cr===F)return;(!F||typeof F!="object")&&(F={}),F=hr(F),Vt=Po.indexOf(F.PARSER_MEDIA_TYPE)===-1?Xn:F.PARSER_MEDIA_TYPE,Ct=Vt==="application/xhtml+xml"?vc:us,J=Ot(F,"ALLOWED_TAGS")&&cr(F.ALLOWED_TAGS)?nt({},F.ALLOWED_TAGS,Ct):ce,ne=Ot(F,"ALLOWED_ATTR")&&cr(F.ALLOWED_ATTR)?nt({},F.ALLOWED_ATTR,Ct):G,pt=Ot(F,"ALLOWED_NAMESPACES")&&cr(F.ALLOWED_NAMESPACES)?nt({},F.ALLOWED_NAMESPACES,vc):At,Xe=Ot(F,"ADD_URI_SAFE_ATTR")&&cr(F.ADD_URI_SAFE_ATTR)?nt(hr(Ue),F.ADD_URI_SAFE_ATTR,Ct):Ue,je=Ot(F,"ADD_DATA_URI_TAGS")&&cr(F.ADD_DATA_URI_TAGS)?nt(hr(Te),F.ADD_DATA_URI_TAGS,Ct):Te,We=Ot(F,"FORBID_CONTENTS")&&cr(F.FORBID_CONTENTS)?nt({},F.FORBID_CONTENTS,Ct):Pt,Pe=Ot(F,"FORBID_TAGS")&&cr(F.FORBID_TAGS)?nt({},F.FORBID_TAGS,Ct):hr({}),oe=Ot(F,"FORBID_ATTR")&&cr(F.FORBID_ATTR)?nt({},F.FORBID_ATTR,Ct):hr({}),pe=Ot(F,"USE_PROFILES")?F.USE_PROFILES&&typeof F.USE_PROFILES=="object"?hr(F.USE_PROFILES):F.USE_PROFILES:!1,be=F.ALLOW_ARIA_ATTR!==!1,de=F.ALLOW_DATA_ATTR!==!1,ot=F.ALLOW_UNKNOWN_PROTOCOLS||!1,Se=F.ALLOW_SELF_CLOSE_IN_ATTR!==!1,xe=F.SAFE_FOR_TEMPLATES||!1,ae=F.SAFE_FOR_XML!==!1,ve=F.WHOLE_DOCUMENT||!1,Ge=F.RETURN_DOM||!1,Kt=F.RETURN_DOM_FRAGMENT||!1,Je=F.RETURN_TRUSTED_TYPE||!1,ct=F.FORCE_BODY||!1,q=F.SANITIZE_DOM!==!1,$e=F.SANITIZE_NAMED_PROPS||!1,Oe=F.KEEP_CONTENT!==!1,te=F.IN_PLACE||!1,K=Q_(F.ALLOWED_URI_REGEXP)?F.ALLOWED_URI_REGEXP:sg,ze=typeof F.NAMESPACE=="string"?F.NAMESPACE:xt,Ut=Ot(F,"MATHML_TEXT_INTEGRATION_POINTS")&&F.MATHML_TEXT_INTEGRATION_POINTS&&typeof F.MATHML_TEXT_INTEGRATION_POINTS=="object"?hr(F.MATHML_TEXT_INTEGRATION_POINTS):nt({},["mi","mo","mn","ms","mtext"]),ur=Ot(F,"HTML_INTEGRATION_POINTS")&&F.HTML_INTEGRATION_POINTS&&typeof F.HTML_INTEGRATION_POINTS=="object"?hr(F.HTML_INTEGRATION_POINTS):nt({},["annotation-xml"]);const Y=Ot(F,"CUSTOM_ELEMENT_HANDLING")&&F.CUSTOM_ELEMENT_HANDLING&&typeof F.CUSTOM_ELEMENT_HANDLING=="object"?hr(F.CUSTOM_ELEMENT_HANDLING):xo(null);if(ee=xo(null),Ot(Y,"tagNameCheck")&&It(Y.tagNameCheck)&&(ee.tagNameCheck=Y.tagNameCheck),Ot(Y,"attributeNameCheck")&&It(Y.attributeNameCheck)&&(ee.attributeNameCheck=Y.attributeNameCheck),Ot(Y,"allowCustomizedBuiltInElements")&&typeof Y.allowCustomizedBuiltInElements=="boolean"&&(ee.allowCustomizedBuiltInElements=Y.allowCustomizedBuiltInElements),xe&&(de=!1),Kt&&(Ge=!0),pe&&(J=nt({},rg),ne=xo(null),pe.html===!0&&(nt(J,tg),nt(ne,ng)),pe.svg===!0&&(nt(J,wc),nt(ne,Ac),nt(ne,Gi)),pe.svgFilters===!0&&(nt(J,Sc),nt(ne,Ac),nt(ne,Gi)),pe.mathMl===!0&&(nt(J,xc),nt(ne,og),nt(ne,Gi))),re.tagCheck=null,re.attributeCheck=null,Ot(F,"ADD_TAGS")&&(typeof F.ADD_TAGS=="function"?re.tagCheck=F.ADD_TAGS:cr(F.ADD_TAGS)&&(J===ce&&(J=hr(J)),nt(J,F.ADD_TAGS,Ct))),Ot(F,"ADD_ATTR")&&(typeof F.ADD_ATTR=="function"?re.attributeCheck=F.ADD_ATTR:cr(F.ADD_ATTR)&&(ne===G&&(ne=hr(ne)),nt(ne,F.ADD_ATTR,Ct))),Ot(F,"ADD_URI_SAFE_ATTR")&&cr(F.ADD_URI_SAFE_ATTR)&&nt(Xe,F.ADD_URI_SAFE_ATTR,Ct),Ot(F,"FORBID_CONTENTS")&&cr(F.FORBID_CONTENTS)&&(We===Pt&&(We=hr(We)),nt(We,F.FORBID_CONTENTS,Ct)),Ot(F,"ADD_FORBID_CONTENTS")&&cr(F.ADD_FORBID_CONTENTS)&&(We===Pt&&(We=hr(We)),nt(We,F.ADD_FORBID_CONTENTS,Ct)),Oe&&(J["#text"]=!0),ve&&nt(J,["html","head","body"]),J.table&&(nt(J,["tbody"]),delete Pe.tbody),F.TRUSTED_TYPES_POLICY){if(typeof F.TRUSTED_TYPES_POLICY.createHTML!="function")throw Ri('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof F.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Ri('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');k=F.TRUSTED_TYPES_POLICY,N=k.createHTML("")}else k===void 0&&(k=uk(g,o)),k!==null&&typeof N=="string"&&(N=k.createHTML(""));lr&&lr(F),Cr=F},er=nt({},[...wc,...Sc,...Z_]),sr=nt({},[...xc,...ek]),fn=function(F){let Y=E(F);(!Y||!Y.tagName)&&(Y={namespaceURI:ze,tagName:"template"});const he=us(F.tagName),st=us(Y.tagName);return pt[F.namespaceURI]?F.namespaceURI===St?Y.namespaceURI===xt?he==="svg":Y.namespaceURI===ft?he==="svg"&&(st==="annotation-xml"||Ut[st]):!!er[he]:F.namespaceURI===ft?Y.namespaceURI===xt?he==="math":Y.namespaceURI===St?he==="math"&&ur[st]:!!sr[he]:F.namespaceURI===xt?Y.namespaceURI===St&&!ur[st]||Y.namespaceURI===ft&&!Ut[st]?!1:!sr[he]&&(Ar[he]||!er[he]):!!(Vt==="application/xhtml+xml"&&pt[F.namespaceURI]):!1},yr=function(F){Co(t.removed,{element:F});try{E(F).removeChild(F)}catch{w(F)}},kt=function(F,Y){try{Co(t.removed,{attribute:Y.getAttributeNode(F),from:Y})}catch{Co(t.removed,{attribute:null,from:Y})}if(Y.removeAttribute(F),F==="is")if(Ge||Kt)try{yr(Y)}catch{}else try{Y.setAttribute(F,"")}catch{}},Ss=function(F){let Y=null,he=null;if(ct)F="<remove></remove>"+F;else{const wt=Jh(F,/^[\r\n\t ]+/);he=wt&&wt[0]}Vt==="application/xhtml+xml"&&ze===xt&&(F='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+F+"</body></html>");const st=k?k.createHTML(F):F;if(ze===xt)try{Y=new m().parseFromString(st,Vt)}catch{}if(!Y||!Y.documentElement){Y=A.createDocument(ze,"template",null);try{Y.documentElement.innerHTML=yt?N:st}catch{}}const Tt=Y.body||Y.documentElement;return F&&he&&Tt.insertBefore(r.createTextNode(he),Tt.childNodes[0]||null),ze===xt?W.call(Y,ve?"html":"body")[0]:ve?Y.documentElement:Tt},Nr=function(F){return I.call(F.ownerDocument||F,F,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},Dr=function(F){F.normalize();const Y=I.call(F.ownerDocument||F,F,u.SHOW_TEXT|u.SHOW_COMMENT|u.SHOW_CDATA_SECTION|u.SHOW_PROCESSING_INSTRUCTION,null);let he=Y.nextNode();for(;he;){let st=he.data;Ao([j,M,D],Tt=>{st=Eo(st,Tt," ")}),he.data=st,he=Y.nextNode()}},_r=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")},br=function(F){if(!P||typeof F!="object"||F===null)return!1;try{return typeof P(F)=="number"}catch{return!1}};function qt(Ee,F,Y){Ao(Ee,he=>{he.call(t,F,Y,Cr)})}const tr=function(F){let Y=null;if(qt(O.beforeSanitizeElements,F,null),_r(F))return yr(F),!0;const he=Ct(F.nodeName);if(qt(O.uponSanitizeElement,F,{tagName:he,allowedTags:J}),ae&&F.hasChildNodes()&&!br(F.firstElementChild)&&Zt(/<[/\w!]/g,F.innerHTML)&&Zt(/<[/\w!]/g,F.textContent)||ae&&F.namespaceURI===xt&&he==="style"&&br(F.firstElementChild)||F.nodeType===No.progressingInstruction||ae&&F.nodeType===No.comment&&Zt(/<[/\w]/g,F.data))return yr(F),!0;if(Pe[he]||!(re.tagCheck instanceof Function&&re.tagCheck(he))&&!J[he]){if(!Pe[he]&&Zi(he)&&(ee.tagNameCheck instanceof RegExp&&Zt(ee.tagNameCheck,he)||ee.tagNameCheck instanceof Function&&ee.tagNameCheck(he)))return!1;if(Oe&&!We[he]){const st=E(F)||F.parentNode,Tt=x(F)||F.childNodes;if(Tt&&st){const wt=Tt.length;for(let Mt=wt-1;Mt>=0;--Mt){const $r=y(Tt[Mt],!0);st.insertBefore($r,v(F))}}}return yr(F),!0}return F instanceof d&&!fn(F)||(he==="noscript"||he==="noembed"||he==="noframes")&&Zt(/<\/no(script|embed|frames)/i,F.innerHTML)?(yr(F),!0):(xe&&F.nodeType===No.text&&(Y=F.textContent,Ao([j,M,D],st=>{Y=Eo(Y,st," ")}),F.textContent!==Y&&(Co(t.removed,{element:F.cloneNode()}),F.textContent=Y)),qt(O.afterSanitizeElements,F,null),!1)},Br=function(F,Y,he){if(oe[Y]||q&&(Y==="id"||Y==="name")&&(he in r||he in Jn))return!1;const st=ne[Y]||re.attributeCheck instanceof Function&&re.attributeCheck(Y,F);if(!(de&&!oe[Y]&&Zt(L,Y))){if(!(be&&Zt(U,Y))){if(!st||oe[Y]){if(!(Zi(F)&&(ee.tagNameCheck instanceof RegExp&&Zt(ee.tagNameCheck,F)||ee.tagNameCheck instanceof Function&&ee.tagNameCheck(F))&&(ee.attributeNameCheck instanceof RegExp&&Zt(ee.attributeNameCheck,Y)||ee.attributeNameCheck instanceof Function&&ee.attributeNameCheck(Y,F))||Y==="is"&&ee.allowCustomizedBuiltInElements&&(ee.tagNameCheck instanceof RegExp&&Zt(ee.tagNameCheck,he)||ee.tagNameCheck instanceof Function&&ee.tagNameCheck(he))))return!1}else if(!Xe[Y]){if(!Zt(K,Eo(he,ie,""))){if(!((Y==="src"||Y==="xlink:href"||Y==="href")&&F!=="script"&&Qh(he,"data:")===0&&je[F])){if(!(ot&&!Zt($,Eo(he,ie,"")))){if(he)return!1}}}}}}return!0},Qi=nt({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Zi=function(F){return!Qi[us(F)]&&Zt(V,F)},ea=function(F){qt(O.beforeSanitizeAttributes,F,null);const Y=F.attributes;if(!Y||_r(F))return;const he={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ne,forceKeepAttr:void 0};let st=Y.length;for(;st--;){const Tt=Y[st],wt=Tt.name,Mt=Tt.namespaceURI,$r=Tt.value,ir=Ct(wt),Oo=$r;let Lt=wt==="value"?Oo:G_(Oo);if(he.attrName=ir,he.attrValue=Lt,he.keepAttr=!0,he.forceKeepAttr=void 0,qt(O.uponSanitizeAttribute,F,he),Lt=he.attrValue,$e&&(ir==="id"||ir==="name")&&Qh(Lt,gt)!==0&&(kt(wt,F),Lt=gt+Lt),ae&&Zt(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Lt)){kt(wt,F);continue}if(ir==="attributename"&&Jh(Lt,"href")){kt(wt,F);continue}if(he.forceKeepAttr)continue;if(!he.keepAttr){kt(wt,F);continue}if(!Se&&Zt(/\/>/i,Lt)){kt(wt,F);continue}xe&&Ao([j,M,D],et=>{Lt=Eo(Lt,et," ")});const ta=Ct(F.nodeName);if(!Br(ta,ir,Lt)){kt(wt,F);continue}if(k&&typeof g=="object"&&typeof g.getAttributeType=="function"&&!Mt)switch(g.getAttributeType(ta,ir)){case"TrustedHTML":{Lt=k.createHTML(Lt);break}case"TrustedScriptURL":{Lt=k.createScriptURL(Lt);break}}if(Lt!==Oo)try{Mt?F.setAttributeNS(Mt,wt,Lt):F.setAttribute(wt,Lt),_r(F)?yr(F):Xh(t.removed)}catch{kt(wt,F)}}qt(O.afterSanitizeAttributes,F,null)},xs=function(F){let Y=null;const he=Nr(F);for(qt(O.beforeSanitizeShadowDOM,F,null);Y=he.nextNode();)qt(O.uponSanitizeShadowNode,Y,null),tr(Y),ea(Y),Y.content instanceof s&&xs(Y.content);qt(O.afterSanitizeShadowDOM,F,null)},kr=function(F){if(F.nodeType===No.element&&F.shadowRoot instanceof s){const st=F.shadowRoot;kr(st),xs(st)}const Y=F.childNodes;if(!Y)return;const he=[];Ao(Y,st=>{Co(he,st)});for(const st of he)kr(st)};return t.sanitize=function(Ee){let F=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Y=null,he=null,st=null,Tt=null;if(yt=!Ee,yt&&(Ee="<!-->"),typeof Ee!="string"&&!br(Ee)&&(Ee=J_(Ee),typeof Ee!="string"))throw Ri("dirty is not a string, aborting");if(!t.isSupported)return Ee;if(Ye||Er(F),t.removed=[],typeof Ee=="string"&&(te=!1),te){const $r=Ee.nodeName;if(typeof $r=="string"){const ir=Ct($r);if(!J[ir]||Pe[ir])throw Ri("root node is forbidden and cannot be sanitized in-place")}kr(Ee)}else if(br(Ee))Y=Ss("<!---->"),he=Y.ownerDocument.importNode(Ee,!0),he.nodeType===No.element&&he.nodeName==="BODY"||he.nodeName==="HTML"?Y=he:Y.appendChild(he),kr(he);else{if(!Ge&&!xe&&!ve&&Ee.indexOf("<")===-1)return k&&Je?k.createHTML(Ee):Ee;if(Y=Ss(Ee),!Y)return Ge?null:Je?N:""}Y&&ct&&yr(Y.firstChild);const wt=Nr(te?Ee:Y);for(;st=wt.nextNode();)tr(st),ea(st),st.content instanceof s&&xs(st.content);if(te)return xe&&Dr(Ee),Ee;if(Ge){if(xe&&Dr(Y),Kt)for(Tt=T.call(Y.ownerDocument);Y.firstChild;)Tt.appendChild(Y.firstChild);else Tt=Y;return(ne.shadowroot||ne.shadowrootmode)&&(Tt=X.call(n,Tt,!0)),Tt}let Mt=ve?Y.outerHTML:Y.innerHTML;return ve&&J["!doctype"]&&Y.ownerDocument&&Y.ownerDocument.doctype&&Y.ownerDocument.doctype.name&&Zt(lk,Y.ownerDocument.doctype.name)&&(Mt="<!DOCTYPE "+Y.ownerDocument.doctype.name+`>
52
- `+Mt),xe&&Ao([j,M,D],$r=>{Mt=Eo(Mt,$r," ")}),k&&Je?k.createHTML(Mt):Mt},t.setConfig=function(){let Ee=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Er(Ee),Ye=!0},t.clearConfig=function(){Cr=null,Ye=!1},t.isValidAttribute=function(Ee,F,Y){Cr||Er({});const he=Ct(Ee),st=Ct(F);return Br(he,st,Y)},t.addHook=function(Ee,F){typeof F=="function"&&Co(O[Ee],F)},t.removeHook=function(Ee,F){if(F!==void 0){const Y=W_(O[Ee],F);return Y===-1?void 0:R_(O[Ee],Y,1)[0]}return Xh(O[Ee])},t.removeHooks=function(Ee){O[Ee]=[]},t.removeAllHooks=function(){O=ig()},t}var fk=ag();const pk=["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"],mk=["href","target","rel","src","alt","title","class","style","colspan","rowspan"];function hk(e){return e?fk.sanitize(e,{ALLOWED_TAGS:[...pk],ALLOWED_ATTR:[...mk],ALLOW_DATA_ATTR:!1}):""}function gk(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=Qe(t,s);return i==null?r?"":n:String(i)}):e}function yk(e){return e&&e.replace(/\{api:[^}]*\}/gi,"").replace(/\{labelapi:[^}]*\}/gi,"").replace(/\{resp:[^}]*\}/gi,"").replace(/\{(?:ctx:|@)\w+\}/gi,"").replace(/\{documentId\}/gi,"").replace(/\{(\w+)\}/g,"")}const lg={sm:"text-sm",md:"text-base",lg:"text-lg"},cg={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"},dg={normal:"font-normal",medium:"font-medium",bold:"font-bold"},Ki={left:"text-left",center:"text-center",right:"text-right",justify:"text-justify"};function qn(e){return e.properties??{}}function bk(e){const t=qn(e);return t.textContent!==void 0?t.textContent:e.label??""}function vk(e){return qn(e).textContent===void 0||e.appearance?.hideLabel?!1:!!e.label?.trim()}function wk(e){return e?.contentLayout==="paragraph"?"paragraph":"single"}function Cc(e,t={}){const{formValues:r={},urlParams:n={},submissionContext:o,buttonResponses:s,prepopulateResponse:i,labelApiResponse:a}=t,d=rn(e,r,n,o,s,i),u=gk(d,a,!0);return yk(u)}const Sk=/\{api:[^}]+\}/,xk=/\{labelapi:[^}]+\}/;function Ec(e){return Sk.test(e)}function Nc(e){return xk.test(e)}function Ak(e){const t=e.captionTemplate??"",r=e.descriptionTemplate??"",n=Ec(e.bodyTemplate)||Ec(t)||Ec(r),o=Nc(e.bodyTemplate)||Nc(t)||Nc(r);return!!(n&&e.prepopulateLoading||o&&e.labelApiConfigPresent&&(e.labelApiLoading||e.labelApiResponse===void 0&&e.labelApiError==null))}function ug(e,t){const r=t??qn(e),n=r.variant??"body",o=e.appearance?.size??"md",s=lg[o]??lg.md,i=r.fontWeight??"medium";return n!=="body"?B("m-0 text-foreground",cg[n]??cg.h3,r.fontWeight&&dg[r.fontWeight],r.italic&&"italic",r.underline&&"underline",r.textAlign&&Ki[r.textAlign]):B("m-0 text-foreground",s,dg[i],r.italic&&"italic",r.underline&&"underline",r.textAlign&&Ki[r.textAlign])}function Ck(e,t){const r=(t??qn(e)).variant??"body";return r==="body"?"p":r}function _c(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 u=e.indexOf(a,r+i.length);if(u===-1)return!1;o();const l=e.slice(r+i.length,u);return t.push({type:d,children:_c(l)}),r=u+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 Ek(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function fg(e){return e.map(t=>{if(t.type==="text")return Ek(t.value);const r=fg(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 Nk(e){return e?fg(_c(e)):""}function _k(e,t){return e?t==="markdown-lite"?Nk(e):e:""}function pg(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=pg(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 mg(e,t){if(!e)return null;if(t!=="markdown-lite")return e;const r=_c(e);return r.length===1&&r[0]?.type==="text"?r[0].value:pg(r,"tl")}const kk="text-label-html prose prose-sm max-w-none [&_p]:m-0 [&_p+p]:mt-2 [&_ul]:my-1 [&_ol]:my-1";function hg(e,t){if(!e)return null;const{field:r,asDescription:n=!1}=t,o=t.textProps??qn(r),s=t.contentLayout??wk(o),i=o.inlineFormat??"none";if(s==="paragraph"){const d=hk(_k(e,i));if(!d)return null;const u=n?B("m-0 text-sm",o.descriptionMuted!==!1?"text-muted-foreground":"text-foreground",o.textAlign&&Ki[o.textAlign]):B(ug(r,o),kk);return S.createElement("div",{className:u,dangerouslySetInnerHTML:{__html:d}})}if(n)return S.createElement("p",{className:B("mt-0.5 text-sm",o.descriptionMuted!==!1?"text-muted-foreground":"text-foreground",o.textAlign&&Ki[o.textAlign])},mg(e,i));const a=Ck(r,o);return S.createElement(a,{className:ug(r,o)},mg(e,i))}function Tk(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 Fk(e,t={}){const{formValues:r={},urlParams:n={},submissionContext:o}=t,s=f=>rn(f,r,n,o),i=(e.labelApiMethod??"GET").toUpperCase();let a=cn(s(e.labelApiEndpoint));const d=e.labelApiQueryParams??[];if(d.length){const f=new URLSearchParams;d.forEach(({key:m,value:g})=>{m.trim()&&f.append(m,s(g))});const p=f.toString();p&&(a=`${a}${a.includes("?")?"&":"?"}${p}`)}const u={"Content-Type":"application/json"};(e.labelApiHeaders??[]).forEach(({key:f,value:p})=>{f.trim()&&(u[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 dn.post(a,l??{},{headers:Object.keys(u).length?u:void 0})).data:(await dn.get(a,{headers:Object.keys(u).length?u:void 0})).data}catch(f){const p=f,m=p.response?.status,g=typeof p.response?.data=="string"?p.response.data:p.message??"Request failed";throw new Error(m?`HTTP ${m}: ${g}`:String(g))}}const Pk=({field:e,className:t,formValues:r,urlParams:n,submissionContext:o,buttonResponses:s,prepopulateResponse:i,prepopulateLoading:a=!1})=>{const d=qn(e),u=S.useMemo(()=>Tk(qn(e)),[e.properties]),[l,f]=S.useState(void 0),[p,m]=S.useState(!1),[g,h]=S.useState(null),y=S.useMemo(()=>u?JSON.stringify({endpoint:u.labelApiEndpoint,method:u.labelApiMethod,query:u.labelApiQueryParams,headers:u.labelApiHeaders,body:u.labelApiBodyFields}):"",[u]),w=S.useCallback(async()=>{if(!u){f(void 0),h(null),m(!1);return}m(!0),h(null);try{const W=await Fk(u,{formValues:r??{},urlParams:n??{},submissionContext:o});f(W)}catch(W){f(void 0),h(W instanceof Error?W.message:"Failed to load label API")}finally{m(!1)}},[u,r,n,o]);S.useEffect(()=>{y&&w()},[y,w]);const v=d.textAlign==="center"?"items-center":d.textAlign==="right"?"items-end":d.textAlign==="justify"?"items-stretch":"items-start",x=bk(e),E=vk(e),P=E&&e.label?e.label:"",k=e.description??"",N=Ak({bodyTemplate:x,captionTemplate:P,descriptionTemplate:k,prepopulateLoading:a,labelApiConfigPresent:u!=null,labelApiLoading:p,labelApiResponse:l,labelApiError:g}),C={formValues:r??{},urlParams:n??{},submissionContext:o,buttonResponses:s,prepopulateResponse:i,labelApiResponse:l},A=x?Cc(x,C):"",I=E&&e.label?Cc(e.label,C):"",T=k?Cc(k,C):"";return c.jsx("div",{className:B("w-full min-w-0 h-full min-h-[95px] flex flex-col justify-center py-0.5",v,t),children:N?c.jsx("p",{className:"text-sm text-muted-foreground m-0",children:"Loading…"}):c.jsxs(c.Fragment,{children:[g&&u?c.jsx("p",{className:"text-[10px] text-destructive mb-0.5",title:g,children:"Label API failed"}):null,I?c.jsx("div",{className:"text-sm font-medium text-foreground mb-1 w-full",children:I}):null,A?hg(A,{field:e,textProps:d}):null,T?hg(T,{field:e,textProps:d,asDescription:!0}):null]})})},kc=({legend:e,children:t,className:r,collapsible:n=!1,defaultCollapsed:o=!1,headerActions:s,onCollapsedChange:i})=>{const[a,d]=S.useState(o),u=S.useId(),l=f=>{f.stopPropagation(),n&&d(p=>{const m=!p;return i?.(m),m})};return c.jsxs("fieldset",{className:B("min-w-0 rounded-lg border bg-card p-4",r),"data-form-renderer":"config-section-border",children:[n?c.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2 border-b border-border pb-2",children:[c.jsxs("button",{type:"button",className:B("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":u,onClick:l,children:[c.jsx("span",{className:"shrink-0 text-muted-foreground","aria-hidden":!0,children:a?c.jsx(Zd,{className:"h-4 w-4"}):c.jsx(Wo,{className:"h-4 w-4"})}),c.jsx("span",{className:"truncate",children:e})]}),s!=null?c.jsx("div",{className:"shrink-0",children:s}):null]}):c.jsx("legend",{className:"px-1 text-sm font-medium text-foreground",children:e}),!a&&c.jsxs("div",{id:u,className:"space-y-3",children:[!n&&s!=null?c.jsx("div",{className:"flex justify-end",children:s}):null,t]})]})},un=({field:e,value:t,error:r,onChange:n,onBlur:o,disabled:s,readOnly:i,isRequired:a,className:d,formValues:u={},submissionContext:l,onSubmit:f,onReset:p,onCancel:m,isSubmitting:g,bffSubmitApi:h,onBffSubmitResult:y,extraSubmitPayload:w,buttonResponses:v,onButtonApiResponse:x,onValidateForm:E,getValidationErrors:P,allFields:k,onSubmittingChange:N,onAddMore:C,scopedFormValues:A,scopedFieldNameMap:I,excludedOptionValues:T,prepopulateMappedFieldNames:W,fieldValueKey:X,hideTableRowControls:O=!1,urlParams:j={},prepopulateResponse:M=null,prepopulateLoading:D=!1,formSections:L,submitPayload:U})=>{switch(e.type){case"divider":return c.jsx(T_,{field:e,className:d});case"header":return c.jsx(P_,{field:e,className:d});case"sectionHeading":return c.jsx(M_,{field:e,className:d});case"spacer":return c.jsx(L_,{field:e,className:d});case"textLabel":return c.jsx(Pk,{field:e,className:d,formValues:u,urlParams:j,submissionContext:l,buttonResponses:v,prepopulateResponse:M??void 0,prepopulateLoading:D});case"status":return c.jsx(w_,{field:e,value:t??null,error:r,disabled:s,isRequired:a,className:d,formValues:u,submissionContext:l,extraSubmitPayload:w,prepopulateResponse:M})}switch(e.type){case"text":case"password":case"url":return c.jsx(Da,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"number":return c.jsx(Xd,{field:e,value:t??null,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"email":return c.jsx(su,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"phone":case"aadhaar":return c.jsx(iu,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"textarea":case"richtext":return c.jsx(au,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"select":{const $=X??e.name??e.key??e.id,ie=!!($&&W?.has($));return c.jsx(kp,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,formValues:u,submissionContext:l,excludedOptionValues:T,isPrepopulateTarget:ie})}case"multiselect":{const $=Array.isArray(t)?t:t!=null&&t!==""?[String(t)]:[];return c.jsx(vm,{field:e,value:$,onChange:ie=>n(ie),onBlur:o,error:r,disabled:s,isRequired:a,className:d,formValues:u,submissionContext:l,excludedOptionValues:T})}case"asyncsearch":return c.jsx(Xp,{field:e,value:t,onChange:$=>n($),onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d,formValues:u,submissionContext:l});case"checkbox":case"terms":return c.jsx(wm,{field:e,value:t||!1,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d});case"toggle":return c.jsx(tE,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d});case"radio":case"checkboxgroup":return c.jsx(Gm,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,excludedOptionValues:T});case"selectablelist":{const $=Array.isArray(t)?t:[];return console.log("[SelectableList] FieldRenderer: passing to SelectableListField",{fieldName:e.name,value:$,valueLength:$.length,submissionContextKeys:l?Object.keys(l):[]}),c.jsx(x_,{field:e,value:$,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,submissionContext:l})}case"date":case"time":case"datetime":case"daterange":return c.jsx(Km,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"file":return c.jsx(NE,{field:e,value:t,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,buttonResponses:v});case"camera":return c.jsx(oN,{field:e,value:t??null,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d});case"photoChoice":return c.jsx(sN,{field:e,value:t??null,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,buttonResponses:v});case"signature":return c.jsx(QN,{field:e,value:t||null,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"rating":return c.jsx(FN,{field:e,value:t||0,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"slider":return c.jsx(JN,{field:e,value:t||0,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"table":return c.jsx(ZN,{field:e,value:t||[],onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d,hideRowControls:O,formValues:u,submissionContext:l});case"billingGrid":return c.jsx(v_,{field:e,value:t||{rows:[]},onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"button":return c.jsx(wN,{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:g,formValues:u,submissionContext:l,buttonResponses:v,onButtonApiResponse:x,bffSubmitApi:h,onBffSubmitResult:y,extraSubmitPayload:w,onValidateForm:E,getValidationErrors:P,allFields:k,onSubmittingChange:N,scopedFormValues:A,scopedFieldNameMap:I,prepopulateResponse:M,formSections:L,submitPayload:U});case"editButton":return c.jsx(SN,{field:e,disabled:s,readOnly:i,isRequired:a,className:d,buttonResponses:v,onButtonApiResponse:x});case"addmore":return c.jsx(xN,{field:e,error:r,disabled:s,readOnly:i,isRequired:a,className:d,onAddMore:()=>C?.(e)});case"customizeSections":return c.jsx(TN,{field:e,error:r,disabled:s,readOnly:i,isRequired:a,className:d});default:return c.jsx("div",{className:"p-3 border rounded-md bg-muted/50",children:c.jsxs("p",{className:"text-sm text-muted-foreground",children:["Unsupported field type: ",e.type]})})}},Ok=({steps:e,currentStep:t,completedSteps:r,onStepClick:n,className:o})=>c.jsx("div",{className:B("mb-8",o),children:c.jsx("nav",{"aria-label":"Progress",children:c.jsx("ol",{className:"flex items-center",children:e.map((s,i)=>{const a=r.has(i),d=t===i,u=n&&(a||i===t+1||i<=t);return c.jsxs("li",{className:B("relative",i!==e.length-1&&"pr-8 sm:pr-20 flex-1"),children:[i!==e.length-1&&c.jsx("div",{className:B("absolute top-4 left-8 -right-8 sm:left-12 sm:-right-12 h-0.5",a?"bg-primary":"bg-border"),"aria-hidden":"true"}),c.jsx("button",{type:"button",onClick:()=>u&&n?.(i),disabled:!u,className:B("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",u&&"cursor-pointer hover:bg-primary/10",!u&&"cursor-default"),"aria-current":d?"step":void 0,children:a?c.jsx(Vs,{className:"h-4 w-4"}):c.jsx("span",{children:i+1})}),c.jsxs("div",{className:"mt-2",children:[c.jsx("span",{className:B("text-sm font-medium",d&&"text-primary",!d&&!a&&"text-muted-foreground"),children:s.name}),s.description&&c.jsx("p",{className:"text-xs text-muted-foreground hidden sm:block",children:s.description})]})]},s.id)})})})});function ps(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 gg(e){return Array.isArray(e)?e.map(ps):[]}function Ik(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=ps(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 Mk{basePath="/api/form-builder/forms";async getForRendering(t,r){if(!Tn())throw new Error("Client ID is required");const o=r!==void 0?`${this.basePath}/${t}/render?version=${r}`:`${this.basePath}/${t}/render`,s=await dn.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=Ik(d);i.form?.moduleId&&(typeof i.form.moduleId=="object"&&i.form.moduleId._id?l.moduleId=ps(i.form.moduleId):typeof i.form.moduleId=="string"&&(l.moduleId=i.form.moduleId));const f=gg(i.fields||[]),p=i.layout?ps(i.layout):null,m=gg(i.rules||[]),g=i.module?ps(i.module):void 0,h=i.clientMapping||i.clientOverrides;return{form:l,fields:f,layout:p,rules:m,module:g,clientMapping:h,clientOverrides:h,BFF_submit_api:a||void 0}}}const Lk=new Mk;function Pn({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=c.jsxs("div",{className:"text-center",children:[c.jsx("div",{className:B("animate-spin rounded-full border-b-2 border-blue-600 mx-auto mb-4",o[t],e)}),r&&c.jsx("p",{className:"text-gray-600",children:r})]});return n?c.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 Dk={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."},Bk=300;function $k(){return{...Dk}}function jk(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 zk(e){const t=$k();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,sections:hN(r.sections),submitPayload:mN(r.submitPayload),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 ms(e,t,r,n){const o=t.map(l=>{let f=[],p={};try{l.options&&(f=JSON.parse(l.options)),l.metadata&&(p=JSON.parse(l.metadata))}catch{}const m=jd(l);m&&Object.assign(p,m),f.length>0&&(p.options=f);const g=[];if(l.validationRequired&&g.push({type:"required",message:"This field is required"}),l.validationMinLength!==null&&l.validationMinLength!==void 0&&g.push({type:"minLength",value:l.validationMinLength,message:`Minimum length is ${l.validationMinLength}`}),l.validationMaxLength!==null&&l.validationMaxLength!==void 0&&g.push({type:"maxLength",value:l.validationMaxLength,message:`Maximum length is ${l.validationMaxLength}`}),l.validationPattern&&g.push({type:"pattern",value:l.validationPattern,message:"Invalid format"}),l.validationRules&&typeof l.validationRules=="object"){const V=l.validationRules;if(V.required===!0&&!g.some(K=>K.type==="required")&&g.push({type:"required",message:"This field is required"}),V.allowLetters!==void 0&&g.push({type:"allowLetters",value:V.allowLetters}),V.allowNumbers!==void 0&&g.push({type:"allowNumbers",value:V.allowNumbers}),V.allowSpecialChars!==void 0&&g.push({type:"allowSpecialChars",value:V.allowSpecialChars}),V.minLetters!==void 0&&typeof V.minLetters=="number"&&g.push({type:"minLetters",value:V.minLetters}),V.maxLetters!==void 0&&typeof V.maxLetters=="number"&&g.push({type:"maxLetters",value:V.maxLetters}),V.minNumbers!==void 0&&typeof V.minNumbers=="number"&&g.push({type:"minNumbers",value:V.minNumbers}),V.maxNumbers!==void 0&&typeof V.maxNumbers=="number"&&g.push({type:"maxNumbers",value:V.maxNumbers}),V.minSpecialChars!==void 0&&typeof V.minSpecialChars=="number"&&g.push({type:"minSpecialChars",value:V.minSpecialChars}),V.maxSpecialChars!==void 0&&typeof V.maxSpecialChars=="number"&&g.push({type:"maxSpecialChars",value:V.maxSpecialChars}),V.fileSize!==void 0&&typeof V.fileSize=="number"){const K=V.fileSize/1048576;g.push({type:"fileSize",value:V.fileSize,message:`File size must be less than ${K.toFixed(2)} MB`})}if(V.fileType!==void 0){const K=Array.isArray(V.fileType)?V.fileType:typeof V.fileType=="string"?V.fileType.split(",").map(J=>J.trim()).filter(Boolean):[];K.length>0&&g.push({type:"fileType",value:K,message:"File type is not allowed"})}}const h=[],y=new Set;n.filter(V=>{const K=typeof V.targetFieldId=="object"?V.targetFieldId.id||V.targetFieldId._id:V.targetFieldId;return!!(K===l.id||K===l._id||K&&l.fieldKey&&K===l.fieldKey)}).forEach(V=>{try{const K=JSON.parse(V.conditionExpression);!K.id&&V.id&&(K.id=V.id);const J=typeof V.targetFieldId=="object"?V.targetFieldId?.id||V.targetFieldId?._id:V.targetFieldId;K.action&&(!K.then||!Array.isArray(K.then)||K.then.length===0)&&(K.then=[{action:K.action,...J&&{target:J}}]),(!K.then||!Array.isArray(K.then)||K.then.length===0)&&V.action&&(K.then=[{action:V.action,...J&&{target:J}}]),K.then&&Array.isArray(K.then)&&J&&(K.then=K.then.map(ne=>!ne.target&&J?{...ne,target:J}:ne));const ce=V.conditionExpression||JSON.stringify(K);if(y.has(ce))return;y.add(ce),h.push(K)}catch{}});const v=l.disabled===!0||p?.disabled===!0||!1;let x=l.readOnly===!0||p?.readOnly===!0||!1;const E=l.hidden===!0||p?.hidden===!0||!1;(p?.valueSource==="calculated"||p?.formula)&&(x=!0);const{disabled:P,readOnly:k,hidden:N,...C}=p,A={};C.hideLabel!==void 0&&(A.hideLabel=C.hideLabel),C.labelPosition!==void 0&&(A.labelPlacement=C.labelPosition),C.size!==void 0&&(A.size=C.size),C.customClass!==void 0&&(A.className=C.customClass);const{labelPosition:I,size:T,customClass:W,visibility:X,...O}=C,j=Object.keys(O).length>0?O:void 0,M=Object.keys(A).length>0?A:void 0,D=l.visibility??p?.visibility??X;let L=jk(D);if(D&&!L){const V=D;(V.visibleToUserType!=null||V.visibleToUserRole!=null||Array.isArray(V.visibleToUserTypes)&&V.visibleToUserTypes.length>0||Array.isArray(V.visibleToUserRoles)&&V.visibleToUserRoles.length>0||Array.isArray(V.visibleToUserIds)&&V.visibleToUserIds.length>0||Array.isArray(V.hiddenFromUserIds)&&V.hiddenFromUserIds.length>0)&&(L={visibleToUserType:V.visibleToUserType??(Array.isArray(V.visibleToUserTypes)?V.visibleToUserTypes[0]:void 0),visibleToUserRole:V.visibleToUserRole??(Array.isArray(V.visibleToUserRoles)?V.visibleToUserRoles[0]:void 0),visibleToUserIds:V.visibleToUserIds,hiddenFromUserIds:V.hiddenFromUserIds})}const U=p?.columnName,ie=!!l.parentFieldId&&typeof U=="string"?U:l.fieldKey;return{id:l.id,type:l.fieldType,name:ie,label:l.label,description:l.helpText||void 0,placeholder:l.placeholder||void 0,defaultValue:l.defaultValue||void 0,position:{order:typeof l.positionOrder=="number"?l.positionOrder:l.positionRow??0,column:typeof l.positionColumn=="number"?l.positionColumn:1,columnSpan:typeof l.positionWidth=="number"?l.positionWidth:1},parentId:void 0,appearance:M,validation:g.length>0?g:void 0,conditions:h.length>0?h:void 0,properties:j,visibility:L&&(L.visibleToUserType!=null||L.visibleToUserRole!=null||Array.isArray(L.visibleToUserIds)&&L.visibleToUserIds.length>0||Array.isArray(L.hiddenFromUserIds)&&L.hiddenFromUserIds.length>0)?L:void 0,disabled:v,readOnly:x,hidden:E}});o.forEach((l,f)=>{if(l.visibility){const p=t[f];console.log("[backendToFormSchema] field with visibility",{fieldKey:p?.fieldKey??l.name,name:l.name,type:l.type,parentFieldId:p?.parentFieldId,visibility:l.visibility})}});const s=t;for(let l=0;l<o.length;l++){const f=s[l]?.parentFieldId;if(f){const p=o.find(g=>g.id===f||g.type==="table"&&g.name===f||g.type==="table"&&s[l].fieldKey?.startsWith?.(g.name+"_column_")),m=o[l];if(p&&p.type==="table"&&m){const g=p.properties||{};Array.isArray(g.columns)||(g.columns=[]),g.columns.push(m),p.properties=g}}}const i=o.filter((l,f)=>!s[f]?.parentFieldId);for(const l of i)if(l.type==="table"&&l.properties&&Array.isArray(l.properties.columns)){const f=l.properties.columns;for(const p of f){const m=p.properties?.columnName;typeof m=="string"&&(p.name=m)}f.sort((p,m)=>(p.position?.order??0)-(m.position?.order??0)||(p.position?.column??0)-(m.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 l=typeof d=="string"?JSON.parse(d):d;l&&typeof l=="object"?a=zk(l):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"};const u=Ns(r);return u&&(a={...a,grid:u}),{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}}const Uk=3;function _o(e){if(typeof e=="number"&&!Number.isNaN(e))return e}function ko(e,t){const r=e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;return _o(r?.cellSlot)??_o(r?.stackSlot)??_o(r?.cellSlotIndex)??_o(r?.slotIndex)??_o(t?.cellSlotIndex)??_o(t?.stackSlot)}function hs(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;if(t?.sharedCellLayout==="row"||t?.sharedCellLayout==="stack")return t.sharedCellLayout;if(t?.stackDirection==="horizontal")return"row";if(t?.stackDirection==="vertical")return"stack"}function qi(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 Tc(e){return[...e].sort((t,r)=>{const n=ko(t.position),o=ko(r.position);return typeof n=="number"&&typeof o=="number"&&n!==o?n-o:String(t.id).localeCompare(String(r.id))})}function gs(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,Do(o)),n=Math.max(n,bd(o,t));return{rowSpan:r,columnSpan:n}}function yg(e){const t=Tc(e);for(const r of t){const n=hs(r.position);if(n)return n}return t.length>=2?"row":"stack"}function bg(e){return Tc(e).slice(0,Uk)}function Vk(e,t){const r=new Map;for(const n of e){if(!t(n)||typeof n.position?.order!="number")continue;const o=qi(n),s=r.get(o)??[];s.push(n),r.set(o,s)}return Array.from(r.values()).map(n=>bg(n))}function vg(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=qi(a),u=s.get(d)??[];u.push(a),s.set(d,u)}const i=[...s.values()][0]??[];return bg(i)}function Hk(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}=gs(r,n),u=e===s&&t===i-1,l=e>=s&&e<s+a,f=t>=i-1&&t<i-1+d;return l&&f&&!u}function Wk(e,t,r){const n=new Set(r??[]);for(const o of e){const s=o[0]?.position?.order??0,{rowSpan:i}=gs(o,t);for(let a=s;a<s+i;a++)n.add(a)}return n}function Rk(e){const t=[...e].sort((n,o)=>n-o),r=new Map;return t.forEach((n,o)=>r.set(n,o)),{originalToDisplay:r,displayRowCount:Math.max(t.length,1),sortedOriginalRows:t}}function Gk(e,t,r){const n=r.get(e);if(n===void 0)return;let o=0;for(let s=e;s<e+t&&r.has(s);s++)o++;return`${n+1} / span ${Math.max(o,1)}`}function gr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function To(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>To(r));if(!gr(e))return e;const t={};for(const[r,n]of Object.entries(e))t[r]=To(n);return t}function wg(e,...t){const r={...e};for(const n of t)if(!(!n||!gr(n)))for(const[o,s]of Object.entries(n)){const i=r[o];gr(s)&&gr(i)?r[o]=wg(i,s):r[o]=s}return r}function Yn(e){return gr(e)?e:{}}function ys(e){if(e==null)return{};if(typeof e=="string"){const t=e.trim();if(!t)return{};try{const r=JSON.parse(t);return gr(r)?To(r):{}}catch{return{}}}return gr(e)?To(e):{}}function Sg(e){const t=e.apidata;return gr(t)&&Object.keys(t).length>0}function Kk(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||Sg(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 xg=["hideLabel","contentAlign","contentVerticalAlign","labelPlacement","widthPercent","widthMode","className","verticalAlign","horizontalAlign","cellAlign","cellJustify","size","variant","minWidth","minHeight"];function qk(e,t){const r=e.appearance,n=gr(r)&&Object.keys(r).length>0?To(r):{},o=Yn(t.appearance),s={...n};for(const[i,a]of Object.entries(o))i!=="heightPercent"&&s[i]===void 0&&(s[i]=To(a));for(const i of xg)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 Yk(e,t){const r=Yn(e.position),n=ys(e.metadata),o=Yn(e.layout),s=typeof r.order=="number"&&!Number.isNaN(r.order)?r.order:typeof e.positionOrder=="number"?e.positionOrder:typeof e.order=="number"?e.order:typeof e.positionRow=="number"?e.positionRow:t,i=typeof r.column=="number"&&!Number.isNaN(r.column)?r.column:typeof e.positionColumn=="number"?e.positionColumn:1,a=typeof r.columnSpan=="number"&&!Number.isNaN(r.columnSpan)?r.columnSpan:typeof e.positionWidth=="number"?e.positionWidth:1,d=typeof r.rowSpan=="number"&&!Number.isNaN(r.rowSpan)?r.rowSpan:typeof e.positionRowSpan=="number"?e.positionRowSpan:1,u={order:s,column:i,columnSpan:a,rowSpan:d},l=r.cellGroupId??o.cellGroupId,f=ko(r,{cellSlotIndex:e.cellSlotIndex??o.cellSlotIndex,stackSlot:n.stackSlot??o.stackSlot}),p=hs(r)??hs(o)??(n.stackDirection==="horizontal"||o.stackDirection==="horizontal"?"row":n.stackDirection==="vertical"||o.stackDirection==="vertical"?"stack":void 0);return typeof l=="string"&&(u.cellGroupId=l),typeof f=="number"&&(u.cellSlot=f),(p==="row"||p==="stack")&&(u.sharedCellLayout=p),u}function Xk(e,t){const r=e,n=ys(r.metadata),o=Yn(r.apidata),s=Yn(r.properties),i=wg({},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),u=qk(r,n),l=Yk(r,t),f={...r};return f.properties=i,a!==void 0&&(f.name=a),d!==void 0&&(f.type=d),u!==void 0?f.appearance=u:(!gr(r.appearance)||Object.keys(r.appearance).length===0)&&delete f.appearance,f.position=l,gr(f.appearance)&&delete f.appearance.heightPercent,f}function Jk(e,t){if(!e||typeof e!="object")return!0;const r=e,n=ys(r.metadata),o=Object.keys(n).length===0&&!(typeof r.metadata=="string"&&r.metadata.trim()!==""),s=!Sg(r);if(Kk(r)||!o||!s)return!1;const i=r.position;return!(!(gr(i)&&typeof i.order=="number"&&!Number.isNaN(i.order))&&(typeof r.positionRow=="number"||typeof r.positionColumn=="number"||typeof r.positionWidth=="number"||typeof r.positionRowSpan=="number"||typeof r.positionOrder=="number")||gr(n.appearance)||xg.some(u=>n[u]!==void 0&&(r.appearance==null||gr(r.appearance)&&r.appearance[u]===void 0))||Qk(r))}function Qk(e){const t=Yn(e.position),r=Yn(e.layout),n=ys(e.metadata);return(typeof e.cellSlotIndex=="number"||typeof t.stackSlot=="number"||typeof t.cellSlot=="number"||typeof t.cellSlotIndex=="number"||typeof n.stackSlot=="number"||typeof r.stackSlot=="number")&&typeof t.cellSlot!="number"||(t.stackDirection==="horizontal"||t.stackDirection==="vertical"||n.stackDirection==="horizontal"||n.stackDirection==="vertical"||r.stackDirection==="horizontal"||r.stackDirection==="vertical")&&t.sharedCellLayout!=="row"&&t.sharedCellLayout!=="stack"}function Yi(e){if(e==null||typeof e!="object")return e;const t=e.fields;if(!Array.isArray(t))return e;let r=!1;const n=t.map((o,s)=>{if(Jk(o))return o;const i=Xk(o,s);return i!==o&&(r=!0),i});return r?{...e,fields:n}:e}function Zk(e){return Yi(e)}const eT=new Set(["PENDING_PAYMENT","PAYMENT_PENDING","AWAITING_PAYMENT","PAID","PAYMENT_COMPLETED","PAYMENT_FAILED","REFUNDED","AUTHORIZED","CAPTURED","PARTIALLY_PAID"].map(e=>e.toUpperCase()));function Fc(e){return typeof e=="string"&&e.trim()!==""}function Pc(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"||Fc(t.amount)||typeof t.total_amount=="number"||Fc(t.total_amount)||Fc(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"&&eT.has(r.trim().toUpperCase()))}function tT(e){const t=Qe(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 rT(e,t){const r=tT(e);if(!r)return;const n=Qe(e,"data"),o=n!=null&&typeof n=="object"&&!Array.isArray(n)?n:void 0;if(t?.treatFirstItemIdAsPaymentId===!0||Pc(r.item)||o!=null&&Pc(o))return r.id}function nT(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 oT(e){return nT(e).some(t=>t.toLowerCase().includes("payment"))}function sT(e){const t=e.properties,r=e.metadata;return!!(t?.mergeSuccessDataIdAsPaymentId||r?.mergeSuccessDataIdAsPaymentId)}function iT(e,t){if(t?.type!=="button"||!Uo(e))return;const r=Qe(e,"data.id");if(r==null||String(r).trim()==="")return;const n=Qe(e,"data");if(sT(t)||n!=null&&typeof n=="object"&&!Array.isArray(n)&&Pc(n)||oT(t))return r}const aT=new Set(["section","group","columns","divider","header","sectionHeading","spacer","addmore","textLabel","customizeSections"]);function lT(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 cT(e,t){const r=e.properties,n=Array.isArray(r?.linkedFieldNames)?r.linkedFieldNames:[],o=lT(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 Ag(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 dT(e,t){return Ag(e,t).find(r=>r.heading?.enabled)}function Cg(e,t){const r=e.template??"";return(e.mode??"increment")==="fixed"?r:r.replace(/\{n\}/g,String(t+1))}function Eg(e,t,r,n){const o=cT(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||aT.has(i.type)?!1:s.has(a)})}function uT(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 Oc(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 fT(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(u=>o.get(u)).filter(u=>!!u);if(a.length===0)continue;const d=Oc(a).map(u=>r(u)).filter(Boolean);s.push({section:i,fieldNames:d})}return s}function bs(e,t=0){return e.heading?.enabled?Cg(e.heading,t):e.name}function Ng(e,t,r){if(e.type!=="sectionHeading")return!1;const n=t.heading;return!n?.enabled||!n.headingFieldName?!1:r(e)===n.headingFieldName}function pT(e,t){const r=typeof e.position?.order=="number"?e.position.order:0,n=(e.position?.column??1)-1,o=Do(e),s=bd(e,t);return{row:r,col:n,rowEnd:r+o-1,colEnd:n+s-1}}function Ic(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:u,colEnd:l}=pT(i,t);r=Math.min(r,a),n=Math.max(n,u),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 mT(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=Ic(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)),u=Math.max(1,...a.map(l=>(l.position?.order??d)-d+Do(l)));return{minRow:s.minRow,maxRow:s.maxRow,minCol:s.minCol,maxCol:s.maxCol,blockHeight:u}}function hT(e,t){return e.maxRow+1+t*e.blockHeight}function gT(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 u=d.filter(v=>!Ng(v,a.section,r)),l=Ic(d,n);if(!l)continue;const{minRow:f,minCol:p,rowSpan:m,colSpan:g}=l,h=`${f}-${p}`;if(s.has(h))continue;const y=new Set;let w=!1;for(let v=f;v<=f+m-1;v++){for(let x=p;x<=p+g-1;x++){const E=`${v}-${x}`;if(i.has(E)){w=!0;break}y.add(E)}if(w)break}if(!w){for(const v of y)i.add(v);s.set(h,{anchorRow:f,anchorCol:p,rowSpan:m,colSpan:g,run:a,legend:bs(a.section,0),renderFields:u.length>0?u:d})}}return{anchorsByOrigin:s,coveredCells:i}}function yT(e,t,r,n,o,s,i){const a=new Set(i),d=new Map;for(const u of e){const l=_g(u.linkedFields.map(p=>s(p)).filter(Boolean),t),f=l?.section;f?.fieldNames?.length?f.fieldNames:u.templateFieldNames,u.blockIds.forEach((p,m)=>{const g=r.filter(N=>N.id.endsWith(`__${p}`));if(g.length===0||!l)return;const h=Ic(g,o);if(!h)return;const{minRow:y,minCol:w,rowSpan:v,colSpan:x}=h,E=`${y}-${w}`;for(let N=y;N<=y+v-1;N++)for(let C=w;C<=w+x-1;C++)a.add(`${N}-${C}`);const P=l,k=bs(f,m+1);d.set(E,{anchorRow:y,anchorCol:w,rowSpan:v,colSpan:x,run:P,legend:k,renderFields:Oc(g),addMoreMeta:{addMoreFieldName:u.addMoreFieldName,blockId:p,blockIndex:m}})})}return{anchorsByOrigin:d,coveredCells:a}}function bT(e,t,r,n){const o=`${e}-${t}`;return r.has(o)?!n.get(o):!1}function vT(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 wT(e,t,r,n){return!(!n||r.run.section.collapsible!==!0||e===r.anchorRow&&t===r.anchorCol)}function ST(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 xT(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 AT(e,t){return new Map([...e,...t])}function CT(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 u=[],l=new Set(d.fieldNames);for(;s<e.length;){const p=r(e[s]);if(!p||!l.has(p))break;const m=e[s];Ng(m,d.section,r)||u.push(m),s+=1}if(u.length===0)continue;const f=o[o.length-1];f?.kind==="border"&&f.run.section.id===d.section.id?f.fields.push(...u):o.push({kind:"border",run:d,fields:u})}return o}function _g(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 ET=2*6e4,kg=50;class NT{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<=kg)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-kg)).forEach(([n])=>this.map.delete(n))}}function _T(e){return(e??"").trim()||"default"}function Tg(e){const t=_T(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 Fg=new NT(ET);function Pg(e){const t=Tg(e),r=Fg.get(t);return r?{value:r.value,isStale:r.isStale}:null}function Og(e,t){const r=Tg(e);Fg.set(r,t)}function Ig(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 Mc=({schema:e,formId:t,initialValues:r,onSubmit:n,onChange:o,onValidationError:s,onClose:i,mode:a="fill",className:d,children:u,gridLayout:l,unstyled:f=!1,submissionContext:p,onWorkflowSubmitResult:m,initialExtraSubmitPayload:g,onExtraSubmitPayloadChange:h,workflowStepId:y,viewerContext:w,getViewerContext:v,hideTableRowControls:x=!1,themeVars:E,dark:P=!1,omitRootWrapper:k=!1})=>{const N=Rn(_=>_.viewerContext),C=S.useMemo(()=>{if(w!==void 0)return w;const _=v?.();return _!==void 0?_:N},[w,v,N]),[A,I]=S.useState(e||null),[T,W]=S.useState(!!t&&!e),[X,O]=S.useState(null),j=e?.BFF_submit_api??X,[M,D]=S.useState(!1),[L,U]=S.useState({}),[$,ie]=S.useState({}),[V,K]=S.useState({}),[J,ce]=S.useState({}),[ne,G]=S.useState({}),[ee,Pe]=S.useState(null),oe=ha.useParams(),re=Nt(_=>_.setValues),be=Nt(_=>_.setSubmitting),de=Nt(_=>_.formDisabled),ot=Nt(_=>_.visibleFields),Se=Nt(_=>_.requiredFields),xe=Nt(_=>_.updateVisibility),ae=Nt(_=>_.updateRequired),ve=Nt(_=>_.setFieldError),Ye=S.useRef(!1),ct=S.useRef(void 0),Ge=S.useMemo(()=>{if(!e)return null;const _=e;if(_.form&&Array.isArray(_.form.fields))try{return ms(_.form,_.form.fields,_.form.layout||null,_.form.rules||[])}catch{return e}if(Array.isArray(_.fields)&&_.fields.some(z=>typeof z.metadata=="string"&&z.metadata.startsWith("{")||z.fieldType&&!z.type))try{const z={id:_.id||_._id||"temp",name:_.name||"Form",version:_.version??1,status:_.status||"draft",createdAt:_.createdAt||new Date().toISOString(),updatedAt:_.updatedAt||new Date().toISOString(),createdBy:_.createdBy||"system",category:_.category||"",moduleId:_.moduleId,tenantId:_.tenantId,featureId:_.featureId,isDefault:_.isDefault||!1};return ms(z,_.fields,_.layout||null,_.rules||[])}catch{return e}return e},[e]);S.useEffect(()=>{if(e){const _=e;_.BFF_submit_api&&O(_.BFF_submit_api)}},[e]);const Kt=S.useMemo(()=>{const _=Ge||A,H=_?Yi(_):null;if(!H)return null;const z=H.layout,Z=H.rules,Q=H.clientMapping,le=(Array.isArray(H.fields)?H.fields:[]).map(Le=>{let Ve={...Le};if(Le.validationRules&&typeof Le.validationRules=="object"&&!Le.validation){const fe=Le.validationRules,Fe=[];fe.required===!0&&Fe.push({type:"required",message:"This field is required"}),fe.minLength!==void 0&&typeof fe.minLength=="number"&&Fe.push({type:"minLength",value:fe.minLength,message:`Minimum length is ${fe.minLength}`}),fe.maxLength!==void 0&&typeof fe.maxLength=="number"&&Fe.push({type:"maxLength",value:fe.maxLength,message:`Maximum length is ${fe.maxLength}`}),fe.pattern&&typeof fe.pattern=="string"&&Fe.push({type:"pattern",value:fe.pattern,message:"Invalid format"}),fe.allowLetters!==void 0&&Fe.push({type:"allowLetters",value:fe.allowLetters}),fe.allowNumbers!==void 0&&Fe.push({type:"allowNumbers",value:fe.allowNumbers}),fe.allowSpecialChars!==void 0&&Fe.push({type:"allowSpecialChars",value:fe.allowSpecialChars}),Fe.length>0&&(Ve={...Ve,validation:Fe})}const we=Le.required===!0||Le.isRequired===!0,Ae=Array.isArray(Ve.validation)&&Ve.validation.some(fe=>fe.type==="required");if(we&&!Ae){const fe={type:"required",message:"This field is required"},Fe=Array.isArray(Ve.validation)?Ve.validation:[];Ve={...Ve,validation:[...Fe,fe]}}if(Le.apidata&&typeof Le.apidata=="object"){const fe=Le.apidata,Fe=Ve.properties||{},ye=(Ve.type||Le.fieldType)==="status";if(!Fe.apiEndpoint&&fe.apiEndpoint){const dt={...Fe,apiEndpoint:fe.apiEndpoint,apiMethod:fe.apiMethod,apiKey:fe.apiKey,apiRealtime:fe.apiRealtime,apiAutoDetect:fe.apiAutoDetect,apiLabelField:fe.apiLabelField,apiValueField:fe.apiValueField,apiQueryParams:fe.apiQueryParams,apiClientFilter:fe.apiClientFilter,valueSource:fe.valueSource||(fe.apiEndpoint?"api":void 0),optionsSource:fe.optionsSource||(fe.apiEndpoint?"api":void 0)};ye&&(dt.source=Fe.source??"api",Fe.statuses!==void 0&&(dt.statuses=Fe.statuses),Fe.dataPath!==void 0&&(dt.dataPath=Fe.dataPath),Fe.showStatusText!==void 0&&(dt.showStatusText=Fe.showStatusText),Fe.statusTextPath!==void 0&&(dt.statusTextPath=Fe.statusTextPath),Fe.showCurrentIndicator!==void 0&&(dt.showCurrentIndicator=Fe.showCurrentIndicator)),Ve={...Ve,properties:dt}}}const He=["select","multiselect","radio","checkboxgroup"],rt=Ve.type||Le.fieldType;if(He.includes(rt)){const fe=Le.options,Fe=Ve.properties?.options,ye=Array.isArray(Fe)&&Fe.length>0;if(Array.isArray(fe)&&fe.length>0&&!ye){const dt=Ve.properties||{};Ve={...Ve,properties:{...dt,options:fe}}}}return Ve}),Ce=H.config?.rules,Ne=Z&&Array.isArray(Z)?Z:Ce&&Array.isArray(Ce)?Ce:[],De=Ne.length>0?le.map(Le=>{if((Le.conditions&&Array.isArray(Le.conditions)?Le.conditions:[]).length>0)return Le;const we=Le.id??Le._id,Ae=Le.name||Le.key,He=Ne.filter(Fe=>{const ye=typeof Fe.targetFieldId=="object"?Fe.targetFieldId?.id??Fe.targetFieldId?._id:Fe.targetFieldId;return ye?ye===we||ye===Ae||ye===Le.fieldKey:!1});if(He.length===0)return Le;const rt=[],fe=new Set;return He.forEach(Fe=>{try{const ye=typeof Fe.conditionExpression=="string"?JSON.parse(Fe.conditionExpression):Fe.conditionExpression;if(!ye||typeof ye!="object")return;!ye.id&&Fe.id&&(ye.id=Fe.id);const dt=typeof Fe.targetFieldId=="object"?Fe.targetFieldId?.id??Fe.targetFieldId?._id:Fe.targetFieldId;ye.action&&(!ye.then||!Array.isArray(ye.then)||ye.then.length===0)&&(ye.then=[{action:ye.action,...dt&&{target:dt}}]),(!ye.then||!Array.isArray(ye.then)||ye.then.length===0)&&Fe.action&&(ye.then=[{action:Fe.action,...dt&&{target:dt}}]),ye.then&&Array.isArray(ye.then)&&dt&&(ye.then=ye.then.map(Bt=>!Bt.target&&dt?{...Bt,target:dt}:Bt));const Wt=Fe.conditionExpression??JSON.stringify(ye);if(fe.has(Wt))return;fe.add(Wt),rt.push(ye)}catch{}}),rt.length===0?Le:{...Le,conditions:rt}}):le;let at=H.config||{submitAction:"database",layout:"default",autoSave:!0,validateOnChange:!0,showFieldErrors:"inline"};return!at.layout&&z?typeof z=="object"&&z!==null?at.layout="default":typeof z=="string"&&["default","card","compact"].includes(z)?at.layout=z:at.layout="default":at.layout||(at.layout="default"),Z&&!at.rules&&(at.rules=Z),Q&&!at.clientMapping&&(at.clientMapping=Q),{...H,fields:De,config:at}},[Ge,A]);S.useEffect(()=>{Ge&&Ge!==A&&I(Ge)},[Ge]),S.useEffect(()=>{if(t&&!e){const _=(Tn()??"").trim()||"default",H=Pg({scope:_,formId:t,version:"latest"});H?.value?.schema?(I(H.value.schema),H.value.bffSubmitApi&&O(H.value.bffSubmitApi),W(!1),H.isStale&&Je({background:!0})):Je({background:!1})}},[t,e]);const Je=async({background:_})=>{if(!t)return;const H=t;_||W(!0);try{const z=await Lk.getForRendering(t),Z=ms(z.form,z.fields,z.layout,z.rules);if(H!==t)return;I(Z),z.BFF_submit_api&&O(z.BFF_submit_api);const Q=(Tn()??"").trim()||"default";Og({scope:Q,formId:H,version:"latest"},{schema:Z,bffSubmitApi:z.BFF_submit_api})}catch{}finally{_||W(!1)}};if(T)return c.jsx("div",{className:"flex items-center justify-center py-12",children:c.jsx(Pn,{})});if(!Kt)return c.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Form not found"});const q=Kt,$e=S.useMemo(()=>new Set(Object.keys(q.config?.prepopulateApi?.fieldMapping??{})),[q.config?.prepopulateApi?.fieldMapping]),gt=S.useCallback(async _=>{const H=q?.fields?.length?tc(_,q.fields):_,z=yh(H,q.config?.sections,q.config?.submitPayload);if(n){const Z=p?{...z,...p}:z;return n(Z)}return{success:!0}},[n,p,q?.fields,q.config?.sections,q.config?.submitPayload]),{values:Oe,errors:te,touched:pe,isSubmitting:We,isValid:Pt,submitCount:je,currentStep:Te,totalSteps:Xe,completedSteps:Ue,currentStepFields:ft,isLastStep:St,setFieldValue:xt,setFieldTouched:ze,handleSubmit:yt,validateForm:pt,resetForm:At,nextStep:Ut,goToStep:ur,shouldShowField:Ar,isFieldEnabled:Vt,isFieldRequired:Po,loadDraft:Xn}=Vd({schema:q,initialValues:r,onSubmit:gt,onChange:o,workflowStepId:y});sv({fields:q.fields,values:Oe,buttonResponses:$,prepopulateResponse:ee,prepopulateResponseRules:q.config?.prepopulateResponseRules});const Ct=Nt(_=>_.readOnlyFields),Cr=Nt(_=>_.editableFields),Jn=S.useCallback(_=>Ct.has(_),[Ct]),It=S.useCallback(_=>Cr.has(_),[Cr]);S.useEffect(()=>{q.config?.allowDraft&&a==="fill"&&Xn()},[q.id]),S.useEffect(()=>{ct.current=q.id,Ye.current=!1,U({}),K({}),ce({}),G({}),Pe(null)},[q.id]),S.useEffect(()=>{const _=q.config?.prepopulateApi,H=!!(_?.fieldMapping&&Object.keys(_?.fieldMapping??{}).length>0),z=(q.config?.prepopulateResponseRules?.length??0)>0;if(!_?.enabled||!_.apiEndpoint?.trim()||!H&&!z||Ye.current)return;Ye.current=!0;const Z=q.id;ct.current=q.id;let Q=!1;return D(!0),(async()=>{try{const le=Nt.getState().values,Ce=typeof p=="object"&&p!==null?{...p,...g||{}}:g||{},Ne=se=>rn(se,le,oe,Ce);let De=cn(Ne(_.apiEndpoint));if(_.apiQueryParams?.length){const se=new URLSearchParams;_.apiQueryParams.forEach(({key:Ie,value:me})=>se.append(Ie,Ne(me))),De=`${De}${De.includes("?")?"&":"?"}${se.toString()}`}const at={};_.apiHeaders?.forEach(({key:se,value:Ie})=>{se.trim()&&(at[se]=Ne(Ie))}),at["Content-Type"]=at["Content-Type"]??"application/json";let Ht;if(_.apiMethod==="POST"&&_.apiBodyFields?.length){const se={};_.apiBodyFields.forEach(({key:Ie,value:me})=>{Ie.trim()&&(se[Ie]=Ne(me))}),Ht=JSON.stringify(se)}const Le=await fetch(De,{method:_.apiMethod,headers:at,body:_.apiMethod==="POST"?Ht:void 0});if(!Le.ok){const se=await Le.text();throw new Error(se||`HTTP ${Le.status}`)}const Ve=await Le.json(),we=se=>{try{return se.split("?")[0].split("/").filter(Boolean).pop()||se}catch{return se}},Ae=(se,Ie)=>{if(se==null)return null;const me=typeof se=="string"?se:se instanceof Date?se.toISOString():null;if(!me)return null;const Ke=typeof se=="object"&&se instanceof Date?se:new Date(me);if(Number.isNaN(Ke.getTime()))return null;const ut=mt=>String(mt).padStart(2,"0");if(Ie==="date")return me.length>=10&&me[4]==="-"&&me[7]==="-"?me.slice(0,10):Ke.toISOString().slice(0,10);if(Ie==="time")return`${ut(Ke.getHours())}:${ut(Ke.getMinutes())}:${ut(Ke.getSeconds())}`;if(Ie==="datetime"){const mt=Ke.getFullYear(),tt=Ke.getMonth()+1,ue=Ke.getDate(),bt=Ke.getHours(),Re=Ke.getMinutes(),Ft=Ke.getSeconds();return`${mt}-${ut(tt)}-${ut(ue)}T${ut(bt)}:${ut(Re)}:${ut(Ft)}`}return null},He=(se,Ie)=>{const me=q.fields.find(ue=>ue.name===se||ue.key===se);if(!me)return Ie;if((me.type==="file"||me.type==="camera"||me.type==="photoChoice")&&typeof Ie=="string"&&Ie.startsWith("http"))return{url:Ie,name:we(Ie)};if(me.type==="date"||me.type==="datetime"||me.type==="time"){const ue=Ae(Ie,me.type);if(ue!==null)return ue}if(me.type==="multiselect")return Array.isArray(Ie)?Ie.map(ue=>typeof ue=="string"?ue:String(ue)):typeof Ie=="string"?Ie.trim()===""?[]:Ie.includes(",")?Ie.split(",").map(ue=>ue.trim()).filter(Boolean):[Ie]:Ie!=null&&Ie!==""?[String(Ie)]:[];if(me.type!=="radio"&&me.type!=="select")return Ie;const Ke=me.properties?.options??me.options;if(!Array.isArray(Ke)||Ke.length===0)return Ie;const ut=Ke.map(ue=>ue.value);if(ut.includes(Ie))return Ie;const mt=String(Ie);if(ut.includes(mt))return mt;const tt=Ke.find(ue=>ue.value==Ie);return tt?tt.value:Ie},rt=new Set(q.fields.filter(se=>se.type==="table").map(se=>se.name||se.key)),fe=new Set(q.fields.filter(se=>se.type==="billingGrid").map(se=>se.name||se.key)),Fe=se=>se.name||se.key||se.id,ye={},dt=[],Wt=[],Bt=gN(_?.fieldMapping,q.config?.sections,q.config?.submitPayload);for(const[se,Ie]of Object.entries(Bt)){if(!Ie?.trim()||se.startsWith("__"))continue;const me=Qe(Ve,Ie),Ke=se.indexOf(".");if(Ke>0&&fe.has(se.slice(0,Ke))){const mt=se.slice(0,Ke),tt=se.slice(Ke+1),bt=q.fields.find(Re=>(Re.name||Re.key)===mt)?.properties;if(bt?.rowSlots?.length){const Re=tt.startsWith("__block__")?tt.slice(9):tt,Ft=ye[mt]??Nt.getState().values[mt];Array.isArray(me)?ye[mt]=f_(bt,Re,me,Ft):me!=null&&(ye[mt]=mc(bt,me,Ft))}continue}if(Ke>0&&rt.has(se.slice(0,Ke))){const mt=se.slice(0,Ke),tt=se.slice(Ke+1);dt.push({tableName:mt,columnName:tt,path:Ie});continue}if(fe.has(se)&&me!==void 0&&me!==null&&typeof me=="object"){const tt=q.fields.find(ue=>(ue.name||ue.key)===se)?.properties;if(tt?.rowSlots?.length){if(Array.isArray(me)){const ue=tt.rowSlots.find(bt=>bt.kind==="dynamic");if(ue&&ue.kind==="dynamic"){const bt=ue.block.apiArrayPath??"items";ye[se]=mc(tt,{[bt]:me})}}else ye[se]=mc(tt,me);continue}}if(rt.has(se)&&Array.isArray(me)&&me.length>0&&typeof me[0]=="object"&&me[0]!==null){const tt=q.fields.find(Re=>(Re.name||Re.key)===se)?.properties?.columns||[],ue=me.map(Ig),bt=Re=>(Re||"").toLowerCase().replace(/\s+/g,"_").trim();ye[se]=ue.map(Re=>{const Ft={};for(const fr of tt){const eo=fr.name??"";Ft[eo]=Re[bt(eo)]??Re[eo]}return Ft});continue}if(me!=null&&(ye[se]=He(se,me)),me==null)continue;let ut=me;if(Array.isArray(me)){const mt=q.fields.find(tt=>Fe(tt)===se);if(mt?.type==="addmore"){Wt.push({addMoreFieldName:se,array:me});continue}if(mt?.type==="multiselect"){const tt=_.multiselectArrayPropertyMap?.[se];tt&&me.length>0&&me.some(ue=>ue!=null&&typeof ue=="object")&&(ut=me.map(ue=>ue!=null&&typeof ue=="object"&&tt in ue?ue[tt]:void 0).filter(ue=>ue!=null))}}ye[se]=He(se,ut)}const lt={},vt={},rr={};for(const{addMoreFieldName:se,array:Ie}of Wt){const me=q.fields.find(bt=>Fe(bt)===se);if(!me||me.type!=="addmore")continue;const Ke=Eg(me,q.fields,q.config?.sections,Fe);if(Ke.length===0)continue;const ut=_.addMoreFieldKeyMap?.[se],mt=Ie.length>0&&Ie[0]!=null&&typeof Ie[0]=="object"?Ie[0]:null;if(mt)for(const bt of Ke){const Re=Fe(bt),Ft=ut&&ut[Re]||Re,fr=mt[Ft];fr!=null&&(ye[Re]=He(Re,fr))}const tt=Ie.slice(1),ue=tt.map((bt,Re)=>`prepop_${se}_${Re}_${Date.now()}`);ue.length>0&&(vt[se]=ue);for(let bt=0;bt<tt.length;bt++){const Re=tt[bt];if(Re==null||typeof Re!="object")continue;const Ft=Re,fr=Ft.id;fr!=null&&String(fr).trim()!==""&&(rr[`${se}__${ue[bt]}`]=String(fr));for(const eo of Ke){const ma=Fe(eo),hP=ut&&ut[ma]||ma,Kc=Ft[hP];if(Kc==null)continue;const gP=`${ma}__addmore__${se}__${ue[bt]}`;lt[gP]=He(ma,Kc)}}}Object.keys(vt).length>0&&K(se=>({...se,...vt})),Object.keys(rr).length>0&&G(se=>({...se,...rr}));const jr=se=>(se||"").toLowerCase().replace(/\s+/g,"_").trim(),Kr=[...new Set(dt.map(se=>se.tableName))];for(const se of Kr){if(Array.isArray(ye[se]))continue;const Ie=dt.find(ue=>ue.tableName===se);if(!Ie?.path?.includes("."))continue;const me=Ie.path.replace(/\.[^.]+$/,""),Ke=Qe(Ve,me);if(!Array.isArray(Ke)||Ke.length===0||typeof Ke[0]!="object"||Ke[0]===null)continue;const mt=q.fields.find(ue=>(ue.name||ue.key)===se)?.properties?.columns||[],tt=Ke.map(Ig);ye[se]=tt.map(ue=>{const bt={};for(const Re of mt){const Ft=Re.name??"",fr=jr(Ft),eo=ue[fr]??ue[Ft];bt[Ft]=eo}return bt})}const zr=(se,Ie)=>{const me=Qe(Ve,se);if(Array.isArray(me))return me;if(me!=null)return[me];if(!se.includes("."))return[];const Ke=se.replace(/\.[^.]+$/,""),ut=Qe(Ve,Ke);return!Array.isArray(ut)||ut.length===0||typeof ut[0]!="object"||ut[0]===null?[]:ut.map(mt=>{const tt=mt[Ie];if(tt!==null&&typeof tt=="object"&&!Array.isArray(tt)&&!(tt instanceof Date)){const ue=tt;return typeof ue.name=="string"&&typeof ue.code=="string"?`${ue.code} ${ue.name}`.trim():typeof ue.name=="string"?ue.name:typeof ue.code=="string"?ue.code:typeof ue.short_code=="string"?ue.short_code:ue.name??ue.code??""}return tt})};for(const{tableName:se,columnName:Ie,path:me}of dt){const Ke=zr(me,Ie),mt=q.fields.find(Re=>(Re.name||Re.key)===se)?.properties?.columns||[],tt=mt.find(Re=>(Re.name||"").toLowerCase()===Ie.toLowerCase())?.name??Ie;let ue=Array.isArray(ye[se])?ye[se]:[];const bt=Math.max(ue.length,Ke.length);if(bt>ue.length)for(ue=[...ue];ue.length<bt;){const Re={};mt.forEach(Ft=>{Re[Ft.name||""]=""}),ue.push(Re)}else ue=ue.map(Re=>({...Re}));Ke.forEach((Re,Ft)=>{ue[Ft]&&(ue[Ft][tt]=Re)}),ye[se]=ue}if(ct.current===Z){if(Object.keys(ye).length>0||Object.keys(lt).length>0){const Ft={...Nt.getState().values,...ye,...lt};re(Ft)}const Ie=Qe(Ve,"data.user_id"),me=Qe(Ve,"data.items"),Ke=Qe(Ve,"data");let ut=Array.isArray(me)&&me.length>0&&me[0]!=null&&typeof me[0]=="object"&&me[0].id?me[0].id:void 0;ut===void 0&&Array.isArray(Ke)&&Ke.length>0&&Ke[0]!=null&&typeof Ke[0]=="object"&&Ke[0].id&&(ut=Ke[0].id),ut===void 0&&(ut=Qe(Ve,"data.0.id"));const mt=rT(Ve,{treatFirstItemIdAsPaymentId:_?.treatFirstItemIdAsPaymentId===!0}),tt=Qe(Ve,"data.id"),ue=Qe(Ve,"data.batch_id"),bt=Qe(Ve,"data.program_id"),Re={};Ie!=null&&(Re.context_user_id=Ie),ut!=null&&ut!==""&&(Re.documentId=ut),tt!=null&&String(tt).trim()!==""&&(p?.id===void 0||p?.id===null)&&(Re.id=tt),ue!=null&&String(ue).trim()!==""&&((p?.admission_batch_id===void 0||p?.admission_batch_id===null)&&(Re.admission_batch_id=ue),(p?.batch_id===void 0||p?.batch_id===null)&&(Re.batch_id=ue)),bt!=null&&String(bt).trim()!==""&&(p?.program_id===void 0||p?.program_id===null)&&(Re.program_id=bt),mt!=null&&String(mt).trim()!==""&&(p?.payment_id===void 0||p?.payment_id===null)&&(Re.payment_id=mt),Object.keys(Re).length>0&&U(Ft=>{const fr={...Ft,...Re};return h?.(fr),fr}),Pe(Ve)}}catch(le){Q||Zl(le,"Prepopulate request failed.",ls)}finally{D(!1)}})(),()=>{Q=!0}},[q.id,q.config?.prepopulateApi?.enabled,q.config?.prepopulateApi?.apiEndpoint,q.config?.prepopulateApi?.apiMethod,JSON.stringify(q.config?.prepopulateApi?.fieldMapping),q.config?.prepopulateApi?.treatFirstItemIdAsPaymentId,p,g,oe,re,K]),S.useEffect(()=>{Object.keys(te).length>0&&s?.(te)},[te,s]);const Er=Xe>1,er=a==="view",sr=S.useCallback((_,H)=>er||!!H&&!It(_)||Jn(_)&&!It(_),[er,It,Jn]),fn=q.fields.filter(_=>!_.parentId),kt=[...Er?ft:fn.length>0?fn:q.fields].filter(_=>!(!_||typeof _!="object"||!_.name&&!_.key)).sort((_,H)=>{const z=typeof _.position?.order=="number"?_.position.order:typeof _.positionOrder=="number"?_.positionOrder:Number.MAX_SAFE_INTEGER,Z=typeof H.position?.order=="number"?H.position.order:typeof H.positionOrder=="number"?H.positionOrder:Number.MAX_SAFE_INTEGER;if(z!==Z)return z-Z;const Q=typeof _.position?.column=="number"?_.position.column:1,le=typeof H.position?.column=="number"?H.position.column:1;return Q-le}),Ss=S.useCallback(_=>{const H=Nt.getState().errors,z=Object.keys(H).find(Z=>_.includes(Z));z&&requestAnimationFrame(()=>{document.querySelector(`[data-field-name="${z}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})})},[]),Nr=async _=>{if(_?.preventDefault(),Er&&!St){if(!await Ut())try{const Z=Nt.getState().errors;$t.toast.error(ec(Z,q.fields)||"Please fix the errors before continuing."),Ss(kt.map(Q=>Q.name||Q.key||Q.id).filter(Boolean))}catch{$t.toast.error("Please fix the errors before continuing.")}return}const H=await yt(_);if(H&&H.success===!1&&H.errors?.length)try{const z=Nt.getState().errors;$t.toast.error(ec(z,q.fields)||"Submission failed. Please check the form."),Ss(kt.map(Z=>Z.name||Z.key||Z.id).filter(Boolean))}catch{$t.toast.error("Submission failed. Please check the form.")}return H},Dr=S.useCallback(()=>{At(),i&&i()},[At,i]),_r=S.useCallback((_,H)=>{const z=q.fields.find(Q=>Q.type==="button"&&(Q.name===_||Q.key===_)),Z=iT(H,z);Z!=null&&String(Z).trim()!==""&&(p?.payment_id===void 0||p?.payment_id===null)&&U(Q=>{const le={...Q,payment_id:Z};return h?.(le),le}),ie(Q=>{const le={...Q,[_]:H};return!Uo(H)||!(z?.type==="button"&&z.properties?.action==="submit")||q.fields.filter(De=>De.type==="editButton").map(De=>De.name).forEach(De=>delete le[De]),le})},[q.fields,p,h]),br=S.useCallback(async()=>await pt(),[pt]),qt=S.useCallback(()=>Nt.getState().errors,[]),tr=S.useMemo(()=>({...g||{},...L}),[g,L]),Br=S.useMemo(()=>({...typeof p=="object"&&p!==null?p:{},...tr}),[p,tr]),Qi=q.config?.layout??q.layout??"default",Zi=["default","card","compact"].includes(Qi)?Qi:"default",ea={default:"",card:"bg-card border rounded-lg shadow-sm p-6",compact:"space-y-2"},xs=S.useMemo(()=>{if(k)return;const _=q.config?.theme?.cssVariables;if(!(!_&&!E))return{..._??{},...E??{}}},[k,q.config?.theme?.cssVariables,E]),kr=S.useMemo(()=>_s({config:q.config,layout:q.layout},l),[q.config,q.layout,l]),Ee=S.useMemo(()=>kr?{...kr,verticalSpacing:kr.verticalSpacing??kr.spacing??"16px",horizontalSpacing:kr.horizontalSpacing??kr.spacing??"16px",rowHeight:kr.rowHeight??In}:null,[kr]),F=Ee!==null;Ee?.rows;const Y=Ee?.columns??3,he=Ee?.verticalSpacing??Ee?.spacing??"16px",st=Ee?.horizontalSpacing??Ee?.spacing??"16px",Tt=Ee?.rowHeight??In,wt=S.useCallback(_=>{if(!C)return!0;const H=_.visibility;if(!H)return!0;const z=H.visibleToUserType??H.user_type,Z=H.visibleToUserRole??H.user_role,Q=Array.isArray(H.visibleToUserIds)?H.visibleToUserIds:Array.isArray(H.users)?H.users:[],le=Array.isArray(H.hiddenFromUserIds)?H.hiddenFromUserIds:[];if(Array.isArray(le)&&le.length>0&&C.userId!=null&&le.includes(C.userId))return!1;if(Q.length>0&&C.userId!=null&&Q.includes(C.userId))return!0;const Ce=z!=null&&z!==""&&C.userType!=null&&C.userType!==z,Ne=Z!=null&&Z!==""&&C.role!=null&&C.role!==Z,De=Q.length>0&&(C.userId==null||!Q.includes(C.userId));return!(Ce||Ne||De)},[C]),Mt=S.useMemo(()=>NN(q.fields),[q.fields]),$r=S.useMemo(()=>kN(q.fields),[q.fields]),[ir,Oo]=S.useState($r);S.useEffect(()=>{Oo($r)},[q.id,$r]);const Lt=S.useCallback((_,H)=>{Oo(z=>z[_]===H?z:{...z,[_]:H})},[]),ta=S.useMemo(()=>({visibility:ir,setSectionVisible:Lt,fieldToHeading:Mt,allFields:q.fields}),[ir,Lt,Mt,q.fields]),et=S.useCallback(_=>_.name||_.key||_.id,[]),Tr=_=>{if(!wt(_))return!1;const H=_.name||_.key||_.id;if(!wh(H,_.type,ir,Mt))return!1;const z=_.hidden===!0;return Ar(H)||!z&&H},yy=S.useCallback(_=>{const H=q.fields.find(Z=>et(Z)===_);if(H)return H.type;const z=vh(_);return q.fields.find(Z=>et(Z)===z)?.type},[q.fields,et]),ra=S.useCallback(_=>wh(_,yy(_),ir,Mt),[ir,Mt,yy]),pn=S.useCallback(_=>ra(_)?Po(_):!1,[ra,Po]);S.useEffect(()=>{const{visibleFields:_,requiredFields:H,errors:z}=Nt.getState(),Z=new Set(_),Q=new Set(H),le=[];for(const Ce of q.fields){const Ne=et(Ce);Ne&&(ra(Ne)||(Z.delete(Ne),Q.delete(Ne),z[Ne]&&le.push(Ne)))}xe(Array.from(Z)),ae(Array.from(Q));for(const Ce of le)ve(Ce,void 0)},[ir,Mt,q.fields,q.id,et,ra,xe,ae,ve,ot,Se]);const Dt=q.config?.sections,Qn=S.useCallback(_=>{let H=_;if(_.type==="table"){const Z=_.properties?.columns;if(Array.isArray(Z)&&Z.length>0){const Q=Z.filter(le=>wt(le));H={..._,properties:{..._.properties,columns:Q}}}}const z=uT(H,Dt,et);return z?{...H,label:Cg(z,0)}:H},[wt,Dt,et]),mn=S.useCallback(_=>Eg(_,q.fields,Dt,et),[q.fields,Dt,et]),Gr=S.useCallback((_,H,z)=>`${_}__addmore__${H}__${z}`,[]),na=S.useCallback((_,H)=>`${_}__${H??"base"}`,[]),oa=S.useCallback((_,H)=>{const z=na(_.id,H);return J[z]??_.defaultCollapsed??!1},[J,na]),Wc=S.useCallback((_,H,z)=>{const Z=na(_,H);ce(Q=>Q[Z]===z?Q:{...Q,[Z]:z})},[na]),sa=S.useMemo(()=>{const _=[],H=q.fields.filter(z=>z.type==="addmore");for(const z of H){const Z=et(z),le=mn(z).find(at=>{if(at.type!=="button")return!1;const Ht=at.properties,Le=at.metadata;let Ve=Ht?.action;if(!Ve&&Le!=null)try{Ve=(typeof Le=="string"?JSON.parse(Le):Le)?.action}catch{}return Ve==="upload"||Ve==="custom"});if(!le)continue;const Ce=et(le),Ne=V[Z]||[],De=Qe($[Ce],"data.id")??Qe($[Ce],"data.documentId")??L.documentId;De!=null&&String(De).trim()!==""&&_.push(String(De));for(const at of Ne){const Ht=Gr(Ce,Z,at),Le=Qe($[Ht],"data.id")??Qe($[Ht],"data.documentId"),Ve=ne[`${Z}__${at}`],we=Le??Ve;we!=null&&String(we).trim()!==""&&_.push(String(we))}}return _},[q.fields,V,$,ne,L.documentId,et,mn,Gr]);S.useEffect(()=>{U(_=>{const H={..._,document_ids:sa},z=_.document_ids;return Array.isArray(z)&&z.length===sa.length&&sa.every((Z,Q)=>z[Q]===Z)?_:H})},[sa]);const ia=S.useCallback((_,H,z,Z)=>{for(const Q of z){const le=et(Q),Ce=Gr(le,_,H),Ne=Z[Ce];if(Ne==null)continue;const De=Q.type;if(De==="file"||De==="camera"||De==="photoChoice"){if(typeof Ne=="object"&&Ne!==null&&("url"in Ne||"name"in Ne)||Array.isArray(Ne)&&Ne.length>0)return!0;continue}if(Array.isArray(Ne)){if(Ne.length>0)return!0;continue}if(typeof Ne=="string"&&Ne.trim()!==""||typeof Ne=="number"&&!Number.isNaN(Ne)||typeof Ne=="boolean"||typeof Ne=="object"&&Ne!==null&&Object.keys(Ne).length>0)return!0}return!1},[et,Gr]),Zn=S.useCallback(_=>{const H=et(_);if(!H)return;if(mn(_).length===0){$t.toast.error("No linked fields configured for this Add More button.");return}const Z=`${Date.now()}_${Math.random().toString(36).slice(2,8)}`;K(Q=>({...Q,[H]:[...Q[H]||[],Z]}))},[et,mn]),aa=S.useCallback((_,H)=>{K(z=>{const Z=z[_]||[],Q=Z.filter(le=>le!==H);if(Q.length===Z.length)return z;if(Q.length===0){const le={...z};return delete le[_],le}return{...z,[_]:Q}})},[]),la=S.useMemo(()=>kt.filter(_=>!_.parentId),[kt]),On=S.useMemo(()=>{const _=[];return kt.filter(z=>z.type==="addmore").sort((z,Z)=>{const Q=z.position?.order??0,le=Z.position?.order??0;return Q-le}).forEach(z=>{const Z=et(z),Q=z.position?.order??0,le=V[Z]||[],Ce=mn(z).sort((Ae,He)=>{const rt=Ae.position?.order??0,fe=He.position?.order??0;return rt!==fe?rt-fe:(Ae.position?.column??1)-(He.position?.column??1)});if(Ce.length===0)return;const Ne=Ag(z,Dt),De=Ne[0]?.fieldNames?.length?Ne[0].fieldNames:Ce.map(Ae=>et(Ae)).filter(Boolean),at=mT(De,la,Y,et),Ht=Math.min(...Ce.map(Ae=>Ae.position?.order??0)),Le=Math.max(1,...Ce.map(Ae=>(Ae.position?.order??Ht)-Ht+Do(Ae))),Ve=at?.blockHeight??Le,we=le.length*Ve;_.push({addMoreFieldName:Z,baseOrder:Q,blockHeight:Ve,blockIds:le,linkedFields:Ce,insertedRows:we,templateFieldNames:De,templateBounds:at})}),_},[kt,la,Y,et,V,mn,Dt]),As=S.useMemo(()=>({}),[]),ca=S.useMemo(()=>On.length===0?kt:kt.map(_=>{const H=_.position?.order??0,z=On.reduce((Z,Q)=>{const le=Q.templateBounds?.maxRow??Q.baseOrder;return H>le?Z+Q.insertedRows:Z},0);return z===0?_:{..._,position:{..._.position,order:H+z}}}),[kt,On]),da=S.useCallback(_=>{const H={};return Object.entries($).forEach(([z,Z])=>{const Q=_[z];Q&&(H[Q]=Z)}),H},[$]),Io=S.useMemo(()=>{const _=[],H={};return On.forEach(z=>{const{addMoreFieldName:Z,blockIds:Q,linkedFields:le,blockHeight:Ce,templateBounds:Ne}=z,De=Math.min(...le.map(Le=>Le.position?.order??0)),Ht=q.fields.find(Le=>et(Le)===Z&&Le.type==="addmore")?.properties;Q.forEach((Le,Ve)=>{const we={},Ae={},He={},rt=Ne?hT(Ne,Ve):z.baseOrder+1+Ve*Ce,fe=ne[`${Z}__${Le}`];le.forEach(ye=>{const dt=et(ye),Wt=Gr(dt,Z,Le),Bt=(ye.position?.order??De)-De;if(we[Wt]=dt,Ae[Wt]=Oe[Wt],!(Ht?.linkedFieldAllowDuplicate?.[dt]??!0)&&(ye.type==="select"||ye.type==="radio"||ye.type==="multiselect")){const vt=[],rr=Oe[dt];rr!=null&&rr!==""&&(Array.isArray(rr)?vt.push(...rr.map(Kr=>String(Kr))):vt.push(String(rr))),Q.filter(Kr=>Kr!==Le).forEach(Kr=>{const zr=Gr(dt,Z,Kr),qr=Oe[zr];qr!=null&&qr!==""&&(Array.isArray(qr)?vt.push(...qr.map(se=>String(se))):vt.push(String(qr)))}),vt.length>0&&(He[Wt]=[...new Set(vt)])}_.push({...ye,id:`${ye.id}__${Le}`,name:Wt,position:{...ye.position,order:rt+Bt}})});const Fe=da(we);Object.keys(we).forEach(ye=>{H[ye]={scopedFormValues:Ae,scopedFieldNameMap:we,scopedButtonResponses:Fe,...fe!=null&&{blockDocumentId:fe},...He[ye]&&{excludedOptionValues:He[ye]}}})})}),{clonedFields:_,scopeByFieldName:H}},[On,ne,et,Gr,Oe,da,q.fields]),Cs=S.useMemo(()=>[...ca,...Io.clonedFields].sort((_,H)=>{const z=_.position?.order??0,Z=H.position?.order??0;if(z!==Z)return z-Z;const Q=_.position?.column??1,le=H.position?.column??1;if(Q!==le)return Q-le;const Ce=ko(_.position)??0,Ne=ko(H.position)??0;return Ce!==Ne?Ce-Ne:String(_.id).localeCompare(String(H.id))}),[ca,Io.clonedFields]),Mo=S.useMemo(()=>Vk(Cs.filter(_=>!_.parentId),Tr),[Cs,Tr]),Rc=S.useCallback((_,H)=>Mo.some(z=>Hk(_,H,z,Y)),[Mo,Y]);Mo.length===0||Math.max(...Mo.map(_=>(_[0]?.position?.order??0)+gs(_,Y).rowSpan));const ua=S.useMemo(()=>fT(Dt,Oc(kt.filter(_=>!_.parentId)),et),[Dt,kt,et]),{anchorsByOrigin:by,coveredCells:vy}=S.useMemo(()=>gT(ua,ca,et,Y),[ua,ca,et,Y]),{anchorsByOrigin:wy,coveredCells:Sy}=S.useMemo(()=>yT(On.map(_=>({addMoreFieldName:_.addMoreFieldName,blockIds:_.blockIds,linkedFields:_.linkedFields,templateFieldNames:_.templateFieldNames})),Dt,Io.clonedFields,la,Y,et,vy),[On,Dt,Io.clonedFields,la,Y,et,vy]),hn=S.useMemo(()=>AT(by,wy),[by,wy]),xy=S.useMemo(()=>Sy,[Sy]),Ay=String(Tt).endsWith("px")?Tt:In,Cy=S.useCallback((_,H)=>{for(let z=0;z<Y;z++){if(z>=H.anchorCol&&z<H.anchorCol+H.colSpan)continue;if(As[`${_}-${z}`]||hn.get(`${_}-${z}`)||vg(_,z,Cs,Tr).length>0||Rc(_,z))return!0}return!1},[Y,As,hn,Cs,Tr,Rc]),Ey=S.useMemo(()=>ST(hn,_=>{const H=_.run.section;return H.collapsible?oa(H,_.addMoreMeta?.blockId):!1},Cy),[hn,oa,Cy]),Ny=S.useMemo(()=>{const _=[];for(const H of Object.keys(As)){const z=Number(H.split("-")[0]);Number.isNaN(z)||_.push(z)}for(const H of hn.values())if(H.renderFields.some(z=>Tr(z)))for(let z=H.anchorRow;z<H.anchorRow+H.rowSpan;z++)_.push(z);return Wk(Mo,Y,_)},[Mo,Y,As,hn,Tr]),{originalToDisplayRow:fa,displayRowCount:uP,sortedOccupiedRows:fP}=S.useMemo(()=>{const _=Rk(Ny);return{originalToDisplayRow:_.originalToDisplay,displayRowCount:_.displayRowCount,sortedOccupiedRows:_.sortedOriginalRows}},[Ny]),_y=Math.max(uP,1),Gc=S.useCallback((_,H=1)=>Gk(_,H,fa),[fa]),ky=S.useMemo(()=>{const _=new Set;for(const H of Ey){const z=fa.get(H);z!==void 0&&_.add(z)}return _},[Ey,fa]),pP=S.useMemo(()=>xT(_y,Ay,ky),[_y,Ay,ky]),mP=S.useMemo(()=>CT(kt.filter(_=>!_.parentId&&Tr(_)),ua,et),[kt,ua,et,Tr]),pa=S.useCallback(_=>{if(F)return null;const H=et(_),z=V[H]||[];if(z.length===0)return null;const Z=mn(_);if(Z.length===0)return null;const Q=dT(_,Dt),le=Z.map(De=>et(De)).filter(Boolean),Ce=_g(le,Dt),Ne=(De,at,Ht,Le,Ve,we,Ae)=>{const He=et(De),rt=Gr(He,H,at),fe=De.hidden===!0;if(!(wt(De)&&(Ar(He)||!fe&&He)))return null;const ye={...De,id:`${De.id}__${at}`,name:rt},Wt=_.properties?.linkedFieldAllowDuplicate?.[He]??!0;let Bt;if(!Wt&&(De.type==="select"||De.type==="radio"||De.type==="multiselect")){const lt=[],vt=Oe[He];vt!=null&&vt!==""&&(Array.isArray(vt)?lt.push(...vt.map(jr=>String(jr))):lt.push(String(vt))),z.filter(jr=>jr!==at).forEach(jr=>{const Kr=Gr(He,H,jr),zr=Oe[Kr];zr!=null&&zr!==""&&(Array.isArray(zr)?lt.push(...zr.map(qr=>String(qr))):lt.push(String(zr)))}),lt.length>0&&(Bt=[...new Set(lt)])}return c.jsx("div",{"data-field-name":rt,"data-form-renderer":"field-wrapper",children:c.jsx(un,{field:ye,value:Oe[rt],error:pe[rt]||je>0?te[rt]:void 0,onChange:lt=>xt(rt,lt),onBlur:()=>ze(rt),disabled:de||!Vt(He)||er||!!De.disabled,readOnly:sr(He,!!De.readOnly),isRequired:pn(He),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:rt,buttonResponses:we,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:Ae,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,scopedFormValues:Ve,scopedFieldNameMap:Le,excludedOptionValues:Bt,hideTableRowControls:x})},ye.id)};return c.jsx("div",{className:"space-y-3 mt-3",children:z.map((De,at)=>{const Ht={},Le={};Z.forEach(Bt=>{const lt=et(Bt),vt=Gr(lt,H,De);Ht[vt]=lt,Le[vt]=Oe[vt]});const Ve=da(Ht),we=ia(H,De,Z,Oe),Ae=Q?.heading!=null?bs(Q,at+1):null,He=ne[`${H}__${De}`],rt=He!=null?{...tr,documentId:He}:tr,fe=Z.map(Bt=>Ne(Bt,De,at,Ht,Le,Ve,rt)).filter(Boolean),ye=Ce?.section?.collapsible===!0,dt=c.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:we,title:we?"Cannot remove: this entry has data":"Remove entry","aria-label":"Remove entry",onClick:Bt=>{Bt.preventDefault(),Bt.stopPropagation(),aa(H,De)},children:c.jsx(Go,{className:"h-5 w-5","aria-hidden":!0})}),Wt=c.jsxs(c.Fragment,{children:[!ye&&c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[Ae?c.jsx("p",{className:"text-sm font-medium text-foreground",children:Ae}):c.jsxs("p",{className:"text-xs text-muted-foreground",children:["Entry ",at+1]}),dt]}),fe]});return c.jsx("div",{className:"rounded-md border p-3 space-y-3",children:Ce?c.jsx(kc,{legend:Ce.section.heading?.enabled?bs(Ce.section,at+1):Ce.section.name,collapsible:Ce.section.collapsible,defaultCollapsed:Ce.section.defaultCollapsed,headerActions:ye?dt:void 0,onCollapsedChange:Bt=>Wc(Ce.section.id,De,Bt),children:Wt}):Wt},`${_.id}-${De}`)})})},[F,V,ne,et,mn,Gr,ia,Oe,pe,je,te,xt,ze,Vt,er,pn,Br,$e,_r,Nr,At,Dr,We,j,m,tr,br,qt,q.fields,be,Ar,wt,da,aa,x,Dt,oe,ee,M]);return c.jsx("div",{className:k?B("relative",d):B(ga,P&&"dark",d),style:xs,"data-form-renderer":k?void 0:"root",children:c.jsxs("div",{className:"relative",children:[M&&c.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/60 rounded-md",children:c.jsx(Pn,{})}),c.jsx("form",{onSubmit:Nr,className:f?B("w-full min-w-0"):B("space-y-6 pb-[100px] w-full min-w-0",ea[Zi]),"data-form-renderer":"form","data-form-renderer-layout":F?"grid":"stack",children:c.jsxs(AN,{value:ta,children:[Er&&q.steps&&c.jsx(Ok,{steps:q.steps,currentStep:Te,completedSteps:Ue,onStepClick:ur}),c.jsx(_a.Provider,{value:{gridStretch:F},children:F?c.jsx("div",{className:f?"w-full min-w-0":"grid w-full min-w-0",style:{display:"grid",gridTemplateRows:pP,gridTemplateColumns:`repeat(${Y}, 1fr)`,rowGap:he,columnGap:st},"data-form-renderer":"grid",children:fP.map(_=>Array.from({length:Y},(H,z)=>{const Z=Gc(_);if(!Z)return null;if(Rc(_,z))return c.jsx("div",{className:"min-w-0 min-h-0",style:{gridRow:Z,gridColumn:z+1,visibility:"hidden",pointerEvents:"none"},"data-form-renderer":"grid-cell","data-form-renderer-empty":!0},`empty-${_}-${z}`);if(bT(_,z,xy,hn)){const we=vT(_,z,hn);return we&&wT(_,z,we,oa(we.run.section,we.addMoreMeta?.blockId))?null:c.jsx("div",{className:"min-w-0 min-h-0",style:{gridRow:Z,gridColumn:z+1,visibility:"hidden",pointerEvents:"none"},"data-form-renderer":"grid-cell","data-form-renderer-empty":!0},`section-border-cover-${_}-${z}`)}const Q=hn.get(`${_}-${z}`);if(Q){const we=Q.renderFields.filter(lt=>Tr(lt));if(we.length===0)return null;const Ae=Q.addMoreMeta,He=Ae!=null?On.find(lt=>lt.addMoreFieldName===Ae.addMoreFieldName)?.linkedFields??[]:[],rt=Ae!=null?ia(Ae.addMoreFieldName,Ae.blockId,He,Oe):!1,fe=Q.run.section,Fe=Ae?.blockId,ye=oa(fe,Fe),dt=fe.collapsible&&ye?1:Q.rowSpan,Wt=Gc(Q.anchorRow,dt)??Z,Bt=Ae!=null?c.jsx("button",{type:"button",className:B("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:rt,title:rt?"Cannot remove: this entry has data":"Remove entry","aria-label":"Remove entry",onClick:lt=>{lt.preventDefault(),lt.stopPropagation(),aa(Ae.addMoreFieldName,Ae.blockId)},children:c.jsx(Go,{className:"h-5 w-5","aria-hidden":!0})}):void 0;return c.jsx("div",{className:B("min-h-0 min-w-0",!(fe.collapsible&&ye)&&"self-stretch"),style:{gridRow:Wt,gridColumn:`${z+1} / span ${Q.colSpan}`},"data-form-renderer":"grid-cell","data-form-renderer-config-section-border-cell":!0,children:c.jsx(kc,{legend:Q.legend,className:fe.collapsible&&ye?void 0:"h-full",collapsible:fe.collapsible,defaultCollapsed:fe.defaultCollapsed,headerActions:Bt,onCollapsedChange:lt=>Wc(fe.id,Fe,lt),children:c.jsx("div",{className:"grid w-full min-w-0",style:{gridTemplateColumns:`repeat(${Y}, 1fr)`,gridTemplateRows:`repeat(${Q.rowSpan}, minmax(${String(Tt).endsWith("px")?Tt:In}, auto))`,rowGap:he,columnGap:st},children:we.map(lt=>{const vt=et(lt),rr=Io.scopeByFieldName[vt],jr=rr?.scopedFieldNameMap?.[vt]||vt,Kr=(lt.position?.order??Q.anchorRow)-Q.anchorRow,zr=lt.position?.column??1,{rowSpan:qr,columnSpan:se}=gs([lt],Y),Ie=Ae!=null?ne[`${Ae.addMoreFieldName}__${Ae.blockId}`]:void 0,me=Ie!=null?{...tr,documentId:Ie}:tr;return c.jsx("div",{"data-field-name":vt,"data-form-renderer":"field-wrapper",className:"min-h-0 min-w-0",style:{gridRow:`${Kr+1} / span ${qr}`,gridColumn:`${zr} / span ${se}`,...xn(lt)},children:c.jsx(un,{field:Qn(lt),value:Oe[vt],error:pe[vt]||je>0?te[vt]:void 0,onChange:Ke=>xt(vt,Ke),onBlur:()=>ze(vt),disabled:(lt.type==="table"||lt.type==="billingGrid")&&a==="fill"?!1:de||!Vt(jr)||er||!!lt.disabled,readOnly:(lt.type==="table"||lt.type==="billingGrid")&&a==="fill"?!1:sr(jr,!!lt.readOnly),isRequired:pn(jr),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:vt,buttonResponses:rr?.scopedButtonResponses??$,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:me,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,onAddMore:Zn,scopedFormValues:rr?.scopedFormValues,scopedFieldNameMap:rr?.scopedFieldNameMap,excludedOptionValues:rr?.excludedOptionValues,hideTableRowControls:x})},lt.id)})})})},`section-border-${Q.run.section.id}-${_}-${z}-${Ae?.blockId??"base"}`)}const le=vg(_,z,Cs,Tr).filter(we=>!(et(we)?.includes("__addmore__")&&xy.has(`${_}-${z}`)));if(le.length===0){const we=As[`${_}-${z}`];if(we){const Ae=q.fields.find(fe=>fe.type==="addmore"&&et(fe)===we.addMoreFieldName),He=Ae!=null?mn(Ae):[],rt=ia(we.addMoreFieldName,we.blockId,He,Oe);return c.jsx("div",{className:"min-h-0 min-w-0 flex flex-col items-center justify-center",style:{gridRow:Z,gridColumn:z+1},"data-form-renderer":"grid-cell","data-form-renderer-add-more-remove":!0,children:c.jsx("button",{type:"button",className:B("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:rt,title:rt?"Cannot remove: this entry has data":"Remove entry","aria-label":"Remove entry",onClick:fe=>{fe.preventDefault(),fe.stopPropagation(),aa(we.addMoreFieldName,we.blockId)},children:c.jsx(Go,{className:"h-5 w-5","aria-hidden":!0})})},`add-more-remove-${_}-${z}`)}return c.jsx("div",{className:"min-w-0",style:{pointerEvents:"none"},"data-form-renderer":"grid-cell","data-form-renderer-empty":!0},`empty-${_}-${z}`)}const Ce=le[0],{rowSpan:Ne,columnSpan:De}=gs(le,Y),at=Gc(_,Ne)??Z;if(le.length===1&&Ce.type==="section"){const we=q.fields.filter(Ae=>Ae.parentId===Ce.id&&Ae.position!=null).sort((Ae,He)=>{const rt=typeof Ae.position?.order=="number"?Ae.position.order:0,fe=typeof He.position?.order=="number"?He.position.order:0;return rt-fe});return c.jsx("div",{className:"min-w-0 min-h-0 w-full overflow-hidden flex flex-col h-full",style:{gridRow:at,gridColumn:`${z+1} / span ${De}`,...xn(Ce)},"data-form-renderer":"grid-cell",children:c.jsx(Hh,{field:Ce,children:we.map(Ae=>{const He=Ae.name||Ae.key||Ae.id,rt=Ae.hidden===!0;return wt(Ae)&&(Ar(He)||!rt&&He)?c.jsx("div",{"data-field-name":He,"data-form-renderer":"field-wrapper",children:c.jsx(un,{field:Qn(Ae),value:Oe[He],error:pe[He]||je>0?te[He]:void 0,onChange:Fe=>xt(He,Fe),onBlur:()=>ze(He),disabled:de||!Vt(He)||er||!!Ae.disabled,readOnly:sr(He,!!Ae.readOnly),isRequired:pn(He),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:He,buttonResponses:$,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:tr,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,onAddMore:Zn,hideTableRowControls:x})},Ae.id):null})})},Ce.id)}const Ht=yg(le),Le=le.some(we=>["file","camera","photoChoice","addmore","table","billingGrid"].includes(we.type)),Ve=c.jsx("div",{className:B("flex min-h-0 w-full flex-1 gap-3",Ht==="row"?"flex-row items-stretch":"flex-col items-stretch"),children:le.map(we=>{const Ae=we.name||we.key||we.id,He=we.type==="sectionHeading",rt=Io.scopeByFieldName[Ae],fe=rt?.scopedFieldNameMap?.[Ae]||Ae,Fe=rt?.blockDocumentId!=null?{...tr,documentId:rt.blockDocumentId}:tr,ye=we.appearance?.hideLabel??we.properties?.hideLabel??!1,dt=we.type==="table"||we.type==="billingGrid"?we.properties?.minWidth:void 0;return c.jsx("div",{"data-field-name":Ae,"data-form-renderer":"field-wrapper",className:B("flex min-h-0 min-w-0 flex-1 flex-col",jo(we),He&&"items-center justify-center",ye&&"items-center"),style:{...dt?{minWidth:dt}:{},...xn(we)},children:c.jsx(un,{field:Qn(we),value:Oe[Ae],error:pe[Ae]||je>0?te[Ae]:void 0,onChange:Wt=>xt(Ae,Wt),onBlur:()=>ze(Ae),disabled:(we.type==="table"||we.type==="billingGrid")&&a==="fill"?!1:de||!Vt(fe)||er||!!we.disabled,readOnly:(we.type==="table"||we.type==="billingGrid")&&a==="fill"?!1:sr(fe,!!we.readOnly),isRequired:pn(fe),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:Ae,buttonResponses:rt?.scopedButtonResponses??$,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:Fe,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,onAddMore:Zn,scopedFormValues:rt?.scopedFormValues,scopedFieldNameMap:rt?.scopedFieldNameMap,excludedOptionValues:rt?.excludedOptionValues,hideTableRowControls:x})},we.id)})});return c.jsx("div",{className:B(wd(le),"self-stretch",Le?"overflow-visible":"overflow-hidden"),style:{gridRow:at,gridColumn:`${z+1} / span ${De}`,...xn(le[0])},"data-form-renderer":"grid-cell","data-field-name":le.map(we=>we.name||we.key||we.id).join(","),children:Ve},le.map(we=>we.id).join("-"))}))}):c.jsx("div",{className:f?"":"space-y-4","data-form-renderer":"stack",children:kt.map(_=>{if(!Tr(_))return null;const H=mP.find(Z=>Z.kind==="border"&&Z.fields.some(Q=>Q.id===_.id));if(H)return H.fields[0]?.id!==_.id?null:c.jsx(kc,{legend:bs(H.run.section,0),collapsible:H.run.section.collapsible,defaultCollapsed:H.run.section.defaultCollapsed,onCollapsedChange:Z=>Wc(H.run.section.id,void 0,Z),children:H.fields.map(Z=>{const Q=et(Z);return!Q||!Tr(Z)?null:c.jsxs("div",{"data-field-name":Q,"data-form-renderer":"field-wrapper",style:xn(Z),children:[c.jsx(un,{field:Qn(Z),value:Oe[Q],error:pe[Q]||je>0?te[Q]:void 0,onChange:le=>xt(Q,le),onBlur:()=>ze(Q),disabled:(Z.type==="table"||Z.type==="billingGrid")&&a==="fill"?!1:de||!Vt(Q)||er||!!Z.disabled,readOnly:(Z.type==="table"||Z.type==="billingGrid")&&a==="fill"?!1:sr(Q,!!Z.readOnly),isRequired:pn(Q),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:Q,buttonResponses:$,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:tr,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,onAddMore:Zn,hideTableRowControls:x}),Z.type==="addmore"&&pa(Z)]},Z.id)})},`stack-border-${H.run.section.id}-${_.id}`);if(!_.parentId){const Z=kt.filter(le=>!le.parentId&&Tr(le)&&qi(le)===qi(_)),Q=Tc(Z).slice(0,2);if(Q.length>1&&Q[0].id!==_.id)return null;if(Q.length>1){const le=yg(Q);return c.jsx("div",{"data-form-renderer":"shared-cell-stack",className:B("flex w-full min-w-0 gap-3",le==="row"?"flex-row items-stretch":"flex-col"),children:Q.map(Ce=>{const Ne=Ce.name||Ce.key||Ce.id;return c.jsxs("div",{"data-field-name":Ne,"data-form-renderer":"field-wrapper",className:B("min-w-0 flex-1 flex flex-col",jo(Ce)),style:xn(Ce),children:[c.jsx(un,{field:Qn(Ce),value:Oe[Ne],error:pe[Ne]||je>0?te[Ne]:void 0,onChange:De=>xt(Ne,De),onBlur:()=>ze(Ne),disabled:(Ce.type==="table"||Ce.type==="billingGrid")&&a==="fill"?!1:de||!Vt(Ne)||er||!!Ce.disabled,readOnly:(Ce.type==="table"||Ce.type==="billingGrid")&&a==="fill"?!1:sr(Ne,!!Ce.readOnly),isRequired:pn(Ne),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:Ne,buttonResponses:$,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:tr,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,onAddMore:Zn,hideTableRowControls:x}),Ce.type==="addmore"&&pa(Ce)]},Ce.id)})},Q.map(Ce=>Ce.id).join("-"))}}if(_.type==="section"){const Z=q.fields.filter(Q=>Q.parentId===_.id&&Q.position!=null).sort((Q,le)=>{const Ce=typeof Q.position?.order=="number"?Q.position.order:0,Ne=typeof le.position?.order=="number"?le.position.order:0;return Ce-Ne});return c.jsx(Hh,{field:_,children:Z.map(Q=>{const le=Q.name||Q.key||Q.id,Ce=Q.hidden===!0;return wt(Q)&&(Ar(le)||!Ce&&le)?c.jsxs("div",{"data-field-name":le,"data-form-renderer":"field-wrapper",style:xn(Q),children:[c.jsx(un,{field:Qn(Q),value:Oe[le],error:pe[le]||je>0?te[le]:void 0,onChange:De=>xt(le,De),onBlur:()=>ze(le),disabled:de||!Vt(le)||er||!!Q.disabled,readOnly:sr(le,!!Q.readOnly),isRequired:pn(le),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:le,buttonResponses:$,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:tr,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,onAddMore:Zn,hideTableRowControls:x}),Q.type==="addmore"&&pa(Q)]},Q.id):null})},_.id)}const z=_.name||_.key||_.id;return c.jsxs("div",{"data-field-name":z,"data-form-renderer":"field-wrapper",style:xn(_),children:[c.jsx(un,{field:Qn(_),value:Oe[z],error:pe[z]||je>0?te[z]:void 0,onChange:Z=>xt(z,Z),onBlur:()=>ze(z),disabled:(_.type==="table"||_.type==="billingGrid")&&a==="fill"?!1:de||!Vt(z)||er||!!_.disabled,readOnly:(_.type==="table"||_.type==="billingGrid")&&a==="fill"?!1:sr(z,!!_.readOnly),isRequired:pn(z),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:z,buttonResponses:$,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:tr,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,onAddMore:Zn,hideTableRowControls:x}),_.type==="addmore"&&pa(_)]},_.id)})})}),u]})})]})})};function Lc(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function Mg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}function kT(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,g=p._id||p.id||f.targetFieldId;f.targetFieldKey=m,f.targetField=m,f.targetFieldById=g}}return f},u={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:{},g=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(g&&(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=Lc(p.appearance)),p.ui!==void 0&&(h.ui=Lc(p.ui)),p.visibility!==void 0&&(h.visibility=Lc(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 A=l.validationRules,I={...m};if(A.fileSize!==void 0&&(I.maxSize=A.fileSize),A.fileType&&Array.isArray(A.fileType)){const T=[];A.fileType.forEach(W=>{const X=W.startsWith(".")?W:`.${W}`;T.push(X),X===".csv"?T.push("text/csv"):X===".xls"?T.push("application/vnd.ms-excel"):X===".xlsx"&&T.push("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}),I.accept=T}h.metadata=I,I.maxSize!==void 0&&(h.maxSize=I.maxSize),I.accept!==void 0&&(h.accept=I.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 A=m.downloadApiEndpoint;A=A.replace(/\{ctx:([^}]+)\}/g,(I,T)=>{const W=t[T];return W!==void 0?String(W):I}),m.downloadApiEndpoint=A,h.metadata=m,h.downloadApiEndpoint=A}if((l.type==="button"||l.fieldType==="button")&&m.action==="submit"){const A=h.properties||{};m.submitAction!==void 0&&(A.submitAction=m.submitAction),m.submitApiMethod!==void 0&&(A.submitApiMethod=m.submitApiMethod),m.apiBodyStructure!==void 0&&(A.apiBodyStructure=m.apiBodyStructure),m.apiBodyFieldsOnly!==void 0&&(A.apiBodyFieldsOnly=m.apiBodyFieldsOnly),m.apiBodyFieldsOnlyFormat!==void 0&&(A.apiBodyFieldsOnlyFormat=m.apiBodyFieldsOnlyFormat),m.apiBodyFields!==void 0&&(A.apiBodyFields=m.apiBodyFields),m.buttonText!==void 0&&(A.buttonText=m.buttonText),m.action!==void 0&&(A.action=m.action),m.variant!==void 0&&(A.variant=m.variant),m.hideLabel!==void 0&&(A.hideLabel=m.hideLabel),l.apidata&&typeof l.apidata=="object"&&l.apidata.apiEndpoint&&(A.apiEndpoint=l.apidata.apiEndpoint),h.properties=A}if((l.type==="button"||l.fieldType==="button")&&(m.action==="upload"||m.action==="custom")){const A=h.properties||{};m.action!==void 0&&(A.action=m.action),m.buttonText!==void 0&&(A.buttonText=m.buttonText),m.variant!==void 0&&(A.variant=m.variant),m.hideLabel!==void 0&&(A.hideLabel=m.hideLabel),m.uploadAction!==void 0&&(A.uploadAction=m.uploadAction),m.uploadApiEndpoint!==void 0&&(A.uploadApiEndpoint=m.uploadApiEndpoint),m.uploadApiMethod!==void 0&&(A.uploadApiMethod=m.uploadApiMethod),m.apiBodyStructure!==void 0&&(A.apiBodyStructure=m.apiBodyStructure),m.apiBodyFieldsOnly!==void 0&&(A.apiBodyFieldsOnly=m.apiBodyFieldsOnly),m.apiBodyFieldsOnlyFormat!==void 0&&(A.apiBodyFieldsOnlyFormat=m.apiBodyFieldsOnlyFormat),m.apiFieldMapping!==void 0&&(A.apiFieldMapping=m.apiFieldMapping),m.apiQueryParams!==void 0&&(A.apiQueryParams=m.apiQueryParams),m.apiBodyFields!==void 0&&(A.apiBodyFields=m.apiBodyFields),m.apiHeaders!==void 0&&(A.apiHeaders=m.apiHeaders),h.properties=A}if(l.type==="status"||l.fieldType==="status"){const A=h.properties||{};if(m.source!==void 0&&(A.source=m.source),m.statuses!==void 0&&(A.statuses=m.statuses),m.dataPath!==void 0&&(A.dataPath=m.dataPath),m.showStatusText!==void 0&&(A.showStatusText=m.showStatusText),m.statusTextPath!==void 0&&(A.statusTextPath=m.statusTextPath),m.showCurrentIndicator!==void 0&&(A.showCurrentIndicator=m.showCurrentIndicator),l.apidata&&typeof l.apidata=="object"&&l.apidata.apiEndpoint){let I=l.apidata.apiEndpoint;I=I.replace(/\{ctx:([^}]+)\}/g,(T,W)=>{const X=t[W];return X!==void 0?String(X):T}),A.apiEndpoint=I,A.source===void 0&&(A.source="api")}l.apidata?.apiMethod!==void 0&&(A.apiMethod=l.apidata.apiMethod),h.properties=A}if(l.type==="addmore"||l.fieldType==="addmore"){const A=h.properties||{};m.linkedFieldNames!==void 0&&(A.linkedFieldNames=m.linkedFieldNames),m.linkedSectionIds!==void 0&&(A.linkedSectionIds=m.linkedSectionIds),m.linkedFieldAllowDuplicate!==void 0&&(A.linkedFieldAllowDuplicate=m.linkedFieldAllowDuplicate),m.buttonText!==void 0&&(A.buttonText=m.buttonText),m.variant!==void 0&&(A.variant=m.variant),m.size!==void 0&&(A.size=m.size),m.hideLabel!==void 0&&(A.hideLabel=m.hideLabel),h.properties=A}if(l.type==="selectablelist"||l.fieldType==="selectablelist"){const A=h.properties||{};m.submitFieldMapping!==void 0&&(A.submitFieldMapping=m.submitFieldMapping),m.displayFields!==void 0&&(A.displayFields=m.displayFields),m.displayFieldsSeparator!==void 0&&(A.displayFieldsSeparator=m.displayFieldsSeparator),m.dataSourceContextKey!==void 0&&(A.dataSourceContextKey=m.dataSourceContextKey),m.showSelectAll!==void 0&&(A.showSelectAll=m.showSelectAll),m.selectAllByDefault!==void 0&&(A.selectAllByDefault=m.selectAllByDefault),h.properties=A}}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);const y=l,w=Mg(y.position),v=l.metadata&&typeof l.metadata=="object"&&!Array.isArray(l.metadata)?l.metadata:{},x=Mg(y.layout),P={order:typeof y.positionOrder=="number"?y.positionOrder:l.order??f,column:typeof w.column=="number"?w.column:typeof y.positionColumn=="number"?y.positionColumn:1,columnSpan:typeof w.columnSpan=="number"?w.columnSpan:typeof w.width=="number"?w.width:typeof y.positionWidth=="number"?y.positionWidth:1,rowSpan:typeof w.rowSpan=="number"?w.rowSpan:typeof y.positionRowSpan=="number"?y.positionRowSpan:1},k=ko(w,{cellSlotIndex:y.cellSlotIndex??x.cellSlotIndex,stackSlot:v.stackSlot??x.stackSlot});typeof k=="number"&&(P.cellSlot=k);const N=w.cellGroupId??x.cellGroupId;typeof N=="string"&&(P.cellGroupId=N);const C=hs(w)??hs(x)??(v.stackDirection==="horizontal"||x.stackDirection==="horizontal"?"row":v.stackDirection==="vertical"||x.stackDirection==="vertical"?"stack":void 0);return(C==="row"||C==="stack")&&(P.sharedCellLayout=C),h.position=P,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 Yi(u)}var Xi="Tabs",[TT]=vr(Xi,[Li]),Lg=Li(),[FT,Dc]=TT(Xi),Dg=b.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,onValueChange:o,defaultValue:s,orientation:i="horizontal",dir:a,activationMode:d="automatic",...u}=e,l=ro(a),[f,p]=Zr({prop:n,onChange:o,defaultProp:s??"",caller:Xi});return c.jsx(FT,{scope:r,baseId:on(),value:f,onValueChange:p,orientation:i,dir:l,activationMode:d,children:c.jsx(Be.div,{dir:l,"data-orientation":i,...u,ref:t})})});Dg.displayName=Xi;var Bg="TabsList",$g=b.forwardRef((e,t)=>{const{__scopeTabs:r,loop:n=!0,...o}=e,s=Dc(Bg,r),i=Lg(r);return c.jsx(Om,{asChild:!0,...i,orientation:s.orientation,dir:s.dir,loop:n,children:c.jsx(Be.div,{role:"tablist","aria-orientation":s.orientation,...o,ref:t})})});$g.displayName=Bg;var jg="TabsTrigger",zg=b.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,disabled:o=!1,...s}=e,i=Dc(jg,r),a=Lg(r),d=Hg(i.baseId,n),u=Wg(i.baseId,n),l=n===i.value;return c.jsx(Im,{asChild:!0,...a,focusable:!o,active:l,children:c.jsx(Be.button,{type:"button",role:"tab","aria-selected":l,"aria-controls":u,"data-state":l?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:d,...s,ref:t,onMouseDown:Me(e.onMouseDown,f=>{!o&&f.button===0&&f.ctrlKey===!1?i.onValueChange(n):f.preventDefault()}),onKeyDown:Me(e.onKeyDown,f=>{[" ","Enter"].includes(f.key)&&i.onValueChange(n)}),onFocus:Me(e.onFocus,()=>{const f=i.activationMode!=="manual";!l&&!o&&f&&i.onValueChange(n)})})})});zg.displayName=jg;var Ug="TabsContent",Vg=b.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,forceMount:o,children:s,...i}=e,a=Dc(Ug,r),d=Hg(a.baseId,n),u=Wg(a.baseId,n),l=n===a.value,f=b.useRef(l);return b.useEffect(()=>{const p=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(p)},[]),c.jsx(xr,{present:o||l,children:({present:p})=>c.jsx(Be.div,{"data-state":l?"active":"inactive","data-orientation":a.orientation,role:"tabpanel","aria-labelledby":d,hidden:!p,id:u,tabIndex:0,...i,ref:t,style:{...e.style,animationDuration:f.current?"0s":void 0},children:p&&s})})});Vg.displayName=Ug;function Hg(e,t){return`${e}-trigger-${t}`}function Wg(e,t){return`${e}-content-${t}`}var PT=Dg,OT=$g,IT=zg,MT=Vg;function Rg({className:e,...t}){return c.jsx(PT,{"data-slot":"tabs",className:B("flex flex-col gap-2",e),...t})}function Gg({className:e,...t}){return c.jsx(OT,{"data-slot":"tabs-list",className:B("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",e),...t})}function Kg({className:e,...t}){return c.jsx(IT,{"data-slot":"tabs-trigger",className:B("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 qg({className:e,...t}){return c.jsx(MT,{"data-slot":"tabs-content",className:B("flex-1 outline-none",e),...t})}function dr({className:e="",...t}){return c.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 LT({className:e=""}){return c.jsxs("div",{className:`flex flex-col gap-4 ${e}`.trim(),"data-form-renderer":"workflow-steps-view-skeleton",children:[c.jsxs("div",{className:"flex w-full border-b border-neutral-200 dark:border-neutral-700 gap-0",children:[c.jsx(dr,{className:"h-10 w-24 rounded-none"}),c.jsx(dr,{className:"h-10 w-28 rounded-none ml-1"}),c.jsx(dr,{className:"h-10 w-20 rounded-none ml-1"})]}),c.jsxs("div",{className:"mt-4 flex flex-col gap-4 py-4",children:[c.jsx(dr,{className:"h-4 w-32"}),c.jsx(dr,{className:"h-10 w-full"}),c.jsx(dr,{className:"h-4 w-40"}),c.jsx(dr,{className:"h-10 w-full"}),c.jsx(dr,{className:"h-4 w-36"}),c.jsx(dr,{className:"h-24 w-full"})]})]})}function DT(){return c.jsxs("div",{className:"flex flex-col gap-4 py-4","data-form-renderer":"form-loading-skeleton",children:[c.jsx(dr,{className:"h-4 w-28"}),c.jsx(dr,{className:"h-10 w-full"}),c.jsx(dr,{className:"h-4 w-36"}),c.jsx(dr,{className:"h-10 w-full"}),c.jsx(dr,{className:"h-4 w-24"}),c.jsx(dr,{className:"h-20 w-full"})]})}const BT=3e4,$T=10*6e4,jT=9e4,zT=15*6e4;function UT(e){return e!=null&&"on_success"in e&&e.on_success!=null}function VT(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 Yg=({getWorkflowState:e,moduleId:t,tenantId:r,submissionContext:n,initialValues:o={},getAuthHeaders:s,onSuccess:i,bootstrapFeatureId:a,subjectUserId:d,viewStepId:u,clientId:l,className:f,onWorkflowSubmitResult:p,viewerContext:m,getViewerContext:g,dark:h=!1,themeVars:y})=>{const w=gn.useQueryClient(),v=S.useMemo(()=>[d??"",u??"",l??""],[d,u,l]),x=S.useMemo(()=>({moduleId:t,tenantId:r,subjectUserId:d,viewStepId:u,clientId:l}),[t,r,d,u,l]),[E,P]=S.useState([]),[k,N]=S.useState(null),[C,A]=S.useState(null),[I,T]=S.useState(null),[W,X]=S.useState({}),O=S.useRef(null),j=S.useRef(null),M=S.useRef(null),D=S.useRef(null),L=S.useMemo(()=>E&&Array.isArray(E)?E.filter(ae=>ae.feature_id):[],[E]),U=gn.useQuery({queryKey:["workflow-steps",t,a??"",r??"",v[0],v[1],v[2]],queryFn:()=>e({...x,featureId:a}),staleTime:BT,gcTime:$T}),$=U.isPending,ie=U.error?U.error instanceof Error?U.error.message:"Failed to load workflow steps":null;S.useEffect(()=>{const ae=U.data;if(!ae||E.length>0)return;const ve=ae.steps&&Array.isArray(ae.steps)?ae.steps:[];P(ve);const Ye=ve.filter(ct=>ct.feature_id);if(Ye.length>0){const ct=ae.current_step_id,Ge=ct&&Ye.some(Kt=>Kt.step_id===ct);N(Ge?ct:Ye[0].step_id)}},[U.data,E.length,a]);const V=S.useMemo(()=>{if(!k)return;const ae=E.find(Ye=>Ye.step_id===k),ve=O.current===k;return ae?.feature_id??(ve?D.current:void 0)??void 0},[k,E]),K=gn.useQuery({queryKey:["workflow-step",t,V??"",r??"",v[0],v[1],v[2]],queryFn:()=>e({...x,featureId:V}),enabled:!!V,staleTime:jT,gcTime:zT,refetchOnWindowFocus:!0,refetchOnReconnect:!0}),J=K.isPending,ce=K.error?K.error instanceof Error?K.error.message:"Failed to load form":null;S.useEffect(()=>{!K.data||O.current===k||(A(K.data),T(null),O.current=null,D.current=null)},[K.data,k]),S.useEffect(()=>{T(ce)},[ce]),S.useEffect(()=>{V===void 0&&O.current!==k&&(A(null),T(null),O.current=null,D.current=null)},[V,k]);const ne=S.useMemo(()=>{const ae=C?.form;if(!ae)return null;const ve=(r??Tn()??"").trim()||"default",Ye=Pg({scope:ve,formId:ae._id,version:ae.version});return Ye?.value?Ye.value:kT(C,n)},[C,n,r]),G=S.useMemo(()=>{const ae=C?.BFF_submit_api;if(!ae?.url)return;let ve=ae.url;if(ve.startsWith("http://")||ve.startsWith("https://"))try{const Ge=new URL(ve);ve=Ge.pathname+Ge.search}catch{}const Ye=s?.()??{},ct={...ae.headers||{},"Content-Type":"application/json",...Ye};return{...ae,url:ve,headers:ct}},[C?.BFF_submit_api,s]),ee=S.useMemo(()=>ne?{...ne,status:"published",...G&&{BFF_submit_api:G}}:null,[ne,G]);S.useEffect(()=>{if(!ne?.id)return;const ae=(r??Tn()??"").trim()||"default";Og({scope:ae,formId:ne.id,version:ne.version},ne)},[ne,r]);const Pe=S.useMemo(()=>{if(!ne)return null;const ae=_s({config:ne.config,layout:ne.layout},null);if(!ae)return null;const ve=ae.rows,Ye=ae.columns,ct={verticalSpacing:ae.verticalSpacing??ae.spacing??"16px",horizontalSpacing:ae.horizontalSpacing??ae.spacing??"16px",rowHeight:ae.rowHeight??In};let Ge=1;if(Array.isArray(ne.fields))for(const Je of ne.fields){const q=Je?.position,$e=typeof q?.order=="number"?q.order:0,gt=typeof q?.rowSpan=="number"?q.rowSpan:1;Ge=Math.max(Ge,$e+gt)}return{rows:Math.min(ve,Math.max(1,Ge)),columns:Ye,verticalSpacing:ct.verticalSpacing,horizontalSpacing:ct.horizontalSpacing,rowHeight:ct.rowHeight}},[ne]),oe=S.useMemo(()=>{const ve=ee?.config?.theme?.cssVariables;if(!(!ve&&!y))return{...ve??{},...y??{}}},[ee?.config,y]),re=S.useCallback(()=>{w.invalidateQueries({queryKey:["workflow-steps",t]}),w.invalidateQueries({queryKey:["workflow-step",t]})},[w,t]),be=S.useCallback(ae=>{if(UT(ae)){const Ge=ae.on_success,Kt=Ge?.action;if(Kt==="redirect"&&Ge?.redirect_url){const Je=VT(Ge.redirect_url.trim(),n);window.location.href=Je;return}if(Kt==="move"){const Je=Ge?.next_step_id,q=Ge?.next_step_form;if(Je&&q){O.current=null,D.current=null;const $e=q.featureId??Ge?.next_step_form_id??q._id;w.removeQueries({queryKey:["workflow-step",t,$e,r??"",v[0],v[1],v[2]]}),re(),P(gt=>gt.some(te=>te.step_id===Je)?gt:[...gt,{step_id:Je,step_name:q.name||"Next step",feature_id:$e}]),A(null),N(Je),i?.();return}return}if(Kt==="stay"){re(),i?.();return}}const ve=ae;ve.steps&&Array.isArray(ve.steps)&&P(ve.steps);const Ye=(ve.steps&&Array.isArray(ve.steps)?ve.steps:E).filter(Ge=>Ge.feature_id),ct=ve.current_step_id;ct&&Ye.some(Ge=>Ge.step_id===ct)?N(ct):Ye.length>0&&N(Ye[0].step_id),A(null),re(),i?.(),p?.(ve)},[w,t,r,i,p,E,n,v,re]),de=S.useCallback(async ae=>C?.BFF_submit_api?(i?.(),{success:!0,message:"Saved successfully"}):{success:!1,message:"Submit not configured"},[C?.BFF_submit_api,i]),ot=S.useCallback((ae,ve)=>{},[]),Se=S.useCallback(ae=>{},[]);if($)return c.jsx(LT,{className:f});if(ie)return c.jsx("div",{className:B("rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive",f),children:ie});if(L.length===0)return c.jsx("div",{className:B("py-12 text-center text-sm text-muted-foreground",f),children:"No workflow steps configured."});const xe=C?.step_blocked_message;return c.jsx("div",{className:B(ga,h&&"dark","flex flex-col gap-4",f),style:oe,"data-form-renderer":"workflow-steps-view",children:c.jsxs(Rg,{value:k??"",onValueChange:ae=>N(ae),children:[c.jsx(Gg,{className:"w-full justify-start border-b rounded-none h-auto p-0 bg-transparent gap-0","data-form-renderer":"workflow-tabs",children:L.map(ae=>c.jsx(Kg,{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))}),L.map(ae=>c.jsx(qg,{value:ae.step_id,className:"mt-4 outline-none",children:ae.step_id!==k?null:J?c.jsx(DT,{}):I?c.jsx("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:I}):xe&&!C?.form?c.jsx("div",{className:B("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:xe}):ee?.fields?.length?c.jsxs("div",{className:"py-4 [&_*]:box-border",children:[xe?c.jsx("div",{className:B("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:xe}):null,(()=>{const ve=j.current!==k||M.current!==(ee?.id??null);if(k&&ee&&ve){j.current=k,M.current=ee.id??null;const Ye=Nt.getState();Ye.setSchema(ee,{forceReset:!0});const ct=Nt.getState().values;Ye.setValues({...ct,...o})}return null})(),c.jsx(Mc,{schema:ee,gridLayout:Pe,omitRootWrapper:!0,submissionContext:n,initialValues:o,workflowStepId:k??void 0,viewerContext:m,getViewerContext:g,onSubmit:de,onChange:ot,onValidationError:Se,onClose:()=>{},mode:"fill",unstyled:!0,onWorkflowSubmitResult:be,initialExtraSubmitPayload:Object.keys(W).length>0?W:void 0,onExtraSubmitPayloadChange:ve=>{if(ve&&typeof ve=="object"){const Ye={};ve.context_user_id!=null&&(Ye.context_user_id=ve.context_user_id),ve.id!=null&&(Ye.id=ve.id),ve.batch_id!=null&&(Ye.batch_id=ve.batch_id),ve.admission_batch_id!=null&&(Ye.admission_batch_id=ve.admission_batch_id),ve.program_id!=null&&(Ye.program_id=ve.program_id),Object.keys(Ye).length>0&&X(ct=>({...ct,...Ye}))}}},ee.id)]}):c.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No form schema available for this step."})},ae.step_id))]})})};function HT(e){return typeof e=="object"&&e!==null&&"apiEndpoint"in e}function WT({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(y=>y.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 g=(h,y)=>{if(y.has(h))return!0;y.add(h);const w=e.fields.find(v=>v.id===h);return w?.parentId?g(w.parentId,y):!1};l.parentId&&g(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),u=new Map;return d.forEach(l=>{const f=l.position.order;u.has(f)||u.set(f,[]),u.get(f).push(l)}),u.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 RT({field:e,value:t,allValues:r,validateOnChange:n=!1,validateOnBlur:o=!0,debounceMs:s=Bk}){const[i,a]=S.useState(),[d,u]=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}u(!0);let w;for(const v of e.validation){const x=Yr(t,v,r);if(typeof x=="string"){w=x;break}}return a(w),u(!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 g=S.useCallback(()=>{o&&p()},[o,p]),h=S.useCallback(()=>{a(void 0)},[]),y=S.useCallback(w=>{a(w)},[]);return{error:i,isValidating:d,validate:p,handleBlur:g,clearError:h,setCustomError:y}}const Xg="—";function Xt(){return{kind:"static",value:Xg}}function GT(){return{currencySymbol:"₹",emptyDisplay:Xg,columns:[{id:"col_tariff",key:"tariff_type",label:"Tariff type",format:"text",align:"left"},{id:"col_service",key:"service",label:"Service",format:"text",align:"left"},{id:"col_unit",key:"unit_price",label:"Unit price",format:"currency",align:"right"},{id:"col_disc_pct",key:"discount_pct",label:"Discount (%)",format:"percent",align:"right"},{id:"col_disc_amt",key:"discount_amount",label:"Discount (₹)",format:"currency",align:"right"},{id:"col_net",key:"net_price",label:"Net price",format:"currency",align:"right"},{id:"col_tax",key:"tax_pct",label:"Tax (%)",format:"percent",align:"right"},{id:"col_total",key:"total",label:"Total",format:"currency",align:"right"}],rowSlots:[{kind:"static",row:{id:"registration_fee",label:"Registration fee",cells:{tariff_type:{kind:"label"},service:Xt(),unit_price:{kind:"api",path:"unit_price"},discount_pct:{kind:"input",inputType:"number"},discount_amount:{kind:"formula",expression:"cell('unit_price') * cell('discount_pct') / 100"},net_price:{kind:"formula",expression:"cell('unit_price') - cell('discount_amount')"},tax_pct:{kind:"api",path:"tax_pct"},total:{kind:"formula",expression:"cell('net_price') * (1 + cell('tax_pct') / 100)"}}}},{kind:"dynamic",block:{id:"line_items",apiArrayPath:"items",rowIdField:"id",cells:{tariff_type:Xt(),service:{kind:"api",path:"service"},unit_price:{kind:"api",path:"unit_price"},discount_pct:Xt(),discount_amount:{kind:"formula",expression:"cell('unit_price') * cell('discount_pct') / 100"},net_price:{kind:"formula",expression:"cell('unit_price') - cell('discount_amount')"},tax_pct:{kind:"api",path:"tax_pct"},total:{kind:"formula",expression:"cell('net_price') * (1 + cell('tax_pct') / 100)"}}}},{kind:"static",row:{id:"all_items_summary",label:"All items summary",cells:{tariff_type:{kind:"label"},service:Xt(),unit_price:{kind:"formula",expression:"SUM('unit_price', 'data')"},discount_pct:Xt(),discount_amount:{kind:"formula",expression:"SUM('discount_amount', 'data')"},net_price:{kind:"formula",expression:"SUM('net_price', 'data')"},tax_pct:Xt(),total:{kind:"formula",expression:"SUM('total', 'data')"}}}},{kind:"static",row:{id:"invoice_discount",label:"Invoice discount",cells:{tariff_type:{kind:"label"},service:Xt(),unit_price:Xt(),discount_pct:Xt(),discount_amount:{kind:"input",inputType:"number"},net_price:Xt(),tax_pct:Xt(),total:Xt()}}},{kind:"static",row:{id:"grand_total",label:"Grand total",cells:{tariff_type:{kind:"label"},service:Xt(),unit_price:Xt(),discount_pct:Xt(),discount_amount:Xt(),net_price:Xt(),tax_pct:Xt(),total:{kind:"formula",expression:"SUM('total', 'data') - cellInRow('invoice_discount', 'discount_amount')"}}}}]}}const KT={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}}},billingGrid:{type:"billingGrid",label:"Billing Grid",icon:"Receipt",category:"special",description:"Configurable billing/tariff grid with formulas and API line items",defaultProps:{label:"Billing",name:"billing",properties:GT()}},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"}}},customizeSections:{type:"customizeSections",label:"Customise Sections",icon:"ListFilter",category:"special",description:"Show or hide UI sections defined by Section Heading fields",defaultProps:{label:"Customise Sections",name:"customize_sections",properties:{sectionHeadingNames:[],defaultHiddenSectionNames:[],variant:"outline",size:"default",buttonText:"Customise sections",menuTitle:"VISIBLE SECTIONS"}}}},Jg={padding:"md",showBorder:!1};function Qg(e,t){const r="full";return e?{padding:e.padding??Jg.padding,maxWidth:e.maxWidth??r,showBorder:e.showBorder??Jg.showBorder}:{padding:"md",maxWidth:r,showBorder:!1}}function qT(e){switch(e??"md"){case"none":return"";case"sm":return"p-3";case"lg":return"p-6 md:p-8";default:return"p-4 md:p-6"}}function YT(e,t){if(t==="full-bleed")return"w-full max-w-none";switch(e??"full"){case"full":return"w-full max-w-none";case"sm":return"mx-auto w-full max-w-screen-sm";case"md":return"mx-auto w-full max-w-screen-md";case"lg":return"mx-auto w-full max-w-screen-lg";case"xl":return"mx-auto w-full max-w-screen-xl";case"2xl":return"mx-auto w-full max-w-2xl";case"4xl":return"mx-auto w-full max-w-4xl";case"5xl":return"mx-auto w-full max-w-5xl";case"6xl":return"mx-auto w-full max-w-6xl";case"7xl":return"mx-auto w-full max-w-7xl";default:return"w-full max-w-none"}}function XT(e){switch(e){case"sidebar-main":return"grid grid-cols-1 gap-6 lg:grid-cols-[240px_1fr]";case"full-bleed":return"w-full";default:return"w-full"}}function JT(e){const t=Qg(e.container,e.layout);return B(XT(e.layout),YT(t.maxWidth,e.layout),qT(t.padding),t.showBorder&&"rounded-lg border border-border")}const Ji=1;function QT(){return{version:Ji,layout:"stack",container:{padding:"md",maxWidth:"full",showBorder:!1},dataBindings:[],widgets:[],filterGroups:[]}}function Zg(e){return{...e,config:e.config??{},children:Array.isArray(e.children)?e.children.map(Zg):void 0}}function ZT(e){return{version:Ji,layout:e.layout??"stack",container:Qg(e.container,e.layout),meta:e.meta,dataBindings:Array.isArray(e.dataBindings)?e.dataBindings:[],dataApis:e.dataApis??{},prepopulateApi:e.prepopulateApi,widgets:Array.isArray(e.widgets)?e.widgets.map(Zg):[],filterGroups:Array.isArray(e.filterGroups)?e.filterGroups:[],eventHandlers:e.eventHandlers??[],navigation:e.navigation}}function eF(e){const t=e;return!t||typeof t!="object"?QT():(t.version!==Ji&&(t.version=Ji),ZT(t))}const ey={};let ty=null;function tF(e){ty=e}function rF(){return(ey?.VITE_API_BASE_URL?.trim()||ey?.VITE_API_URL?.trim()||"").replace(/\/$/,"")}const vs=_t.create({baseURL:rF()});vs.interceptors.request.use(e=>{const t=Tn();t&&(e.params={...e.params,clientId:t}),typeof FormData<"u"&&e.data instanceof FormData&&delete e.headers["Content-Type"];let r=ty?.();if((!r||Object.keys(r).length===0)&&(r=Ml()),r){const n=e.headers??{};for(const[o,s]of Object.entries(r))s!==void 0&&s!==""&&(n[o]=s);e.headers=n}return e});async function ry(e){const t=await vs.get("/api/page-builder/pages/resolve",{params:e}),r=t.data?.data??t.data;if(!r?.pageId)throw new Error("Page resolve failed: no pageId returned");return r}async function Bc(e,t,r){const n=await vs.get(`/api/page-builder/pages/${e}/render`,{params:{clientId:t,...r!==void 0?{version:r}:{}}}),o=n.data?.data??n.data;if(!o?.schema)throw new Error("Page render failed: no schema returned");return o}async function $c(e){const{clientId:t,api:r,context:n,filterState:o}=e,s=await vs.post(`/api/page-builder/clients/${t}/data-sources/execute`,{api:r,context:n,filterState:o});return s.data?.data??s.data}function nF(e,t){if(!t)return{};const r={};for(const[n,o]of Object.entries(t)){if(!o.trim())continue;const s=Qe(e,o);s!==void 0&&(r[n]=s)}return r}const ny=S.createContext(null);function oy(e,t){const r={};for(const n of e){let o;switch(n.source){case"route.param":o=n.param?t[n.param]:void 0;break;case"route.query":o=n.param?t[n.param]:void 0;break;case"context.user":o=n.param?t.user?.[n.param]:t.user;break;case"context.client":o=n.param?t.client?.[n.param]:t.client??t.clientId;break;case"context.tenant":o=n.param?t.tenant?.[n.param]:t.tenant??t.tenantId;break;case"static":o=n.value;break;case"widget.state":o=n.sample;break;default:o=void 0}o===void 0&&n.sample!==void 0&&(o=n.sample),o!==void 0&&(r[n.key]=o)}return r}function oF({schema:e,context:t={},clientId:r,nestingDepth:n=0,onAction:o,getWorkflowState:s,parentContext:i,children:a}){const[d,u]=S.useState(()=>i?i.filterGroups:{}),l=S.useRef(d);l.current=d;const[f,p]=S.useState({}),[m,g]=S.useState("idle"),h=S.useRef(null),y=String(r??t.clientId??i?.clientId??""),w=JSON.stringify(t);S.useEffect(()=>{if(i)return;const C=e.prepopulateApi;if(!C?.enabled||!C.api?.path||!y){p({}),g("idle"),h.current=null;return}const A=JSON.stringify({path:C.api.path,method:C.api.method,queryParams:C.api.queryParams,headers:C.api.headers,bodyFields:C.api.bodyFields,auth:C.api.auth,mapping:C.contextMapping,bindings:e.dataBindings,context:w});if(h.current===A)return;let I=!1;return h.current=A,g("loading"),(async()=>{try{const T=oy(e.dataBindings??[],t),W={...t,...T},X=await $c({clientId:y,api:C.api,context:W});if(I)return;const O=nF(X,C.contextMapping);p({...O,prepopulateResponse:X}),g("ready")}catch{I||(p({}),g("error"))}})(),()=>{I=!0}},[i,e.prepopulateApi,e.dataBindings,w,y]);const v=S.useMemo(()=>{if(i)return{...i.context,...t};const C=oy(e.dataBindings??[],t);return{...t,...C,...f}},[i,t,e.dataBindings,f]),x=String(r??v.clientId??i?.clientId??""),E=S.useCallback((C,A,I)=>{u(T=>({...T,[C]:{...T[C]??{},[A]:I}}))},[]),P=S.useCallback(C=>l.current[C]??{},[]),k=S.useCallback((C,A,I,T)=>{(o??i?.onAction)?.({...C,sourceWidgetId:A,event:I,payload:T})},[o,i?.onAction]),N=S.useMemo(()=>({schema:e,context:v,clientId:x,prepopulateStatus:i?.prepopulateStatus??m,nestingDepth:n,onAction:o??i?.onAction,getWorkflowState:s??i?.getWorkflowState,filterGroups:d,setFilterValue:E,getFilterGroup:P,dispatchAction:k}),[e,v,x,m,n,o,i?.onAction,s,i?.getWorkflowState,d,E,P,k]);return c.jsx(ny.Provider,{value:N,children:a})}function Lr(){const e=S.useContext(ny);if(!e)throw new Error("usePageContext must be used within PageContextProvider");return e}const sF=5,sy=1;function Fo(e){return Number.isFinite(e)?Math.min(sF,Math.max(sy,Math.round(e))):sy}function iF(e,t){const r=Fo(t),n=Array.from({length:r},()=>[]);return e.forEach((o,s)=>{const i=o.config,a=i.columnIndex!==void 0?Math.min(Math.max(0,i.columnIndex),r-1):s%r;n[a].push(o)}),n}function aF(e){return Number.isFinite(e)?Math.min(100,Math.max(0,Math.round(e))):0}function lF(e,t){const r=Math.max(1,t),n=Math.min(100,Math.max(0,Math.round(e))),o=Math.floor(n/r),s=n-o*r;return Array.from({length:r},(i,a)=>o+(a<s?1:0))}function iy(e){return lF(100,Fo(e))}function cF(e){const t=e.trim(),r=/^(\d+(?:\.\d+)?)\s*%?$/.exec(t);return r?aF(Number(r[1])):null}function ay(e,t){const r=Fo(t),n=[];for(let s=0;s<r;s++){const i=cF(e?.[s]??"");if(i===null)return iy(r);n.push(i)}return n.reduce((s,i)=>s+i,0)!==100?iy(r):n}function dF(e){return e==="sm"?"gap-2":e==="lg"?"gap-6":"gap-4"}function ly(e,t){return ay(t,Fo(e)).map(n=>`minmax(0, ${n}fr)`).join(" ")}function uF(e){return e.length?e.map(t=>`minmax(0, ${t}fr)`).join(" "):"minmax(0, 1fr)"}function fF(e,t,r,n){const o=Fo(t),s=iF(e,o),i=ay(r,o);if(!(n?.collapseEmpty!==!1))return{columns:s,gridTemplate:ly(o,r),sourceIndices:s.map((p,m)=>m)};const d=s.map((p,m)=>({colChildren:p,index:m,percent:i[m]??0})).filter(p=>p.colChildren.length>0);if(d.length===0||d.length===s.length)return{columns:s,gridTemplate:ly(o,r),sourceIndices:s.map((p,m)=>m)};const u=d.reduce((p,m)=>p+m.percent,0),l=d.map(p=>u>0?Math.round(p.percent/u*100):Math.round(100/d.length)),f=100-l.reduce((p,m)=>p+m,0);return f!==0&&l.length>0&&(l[0]+=f),{columns:d.map(p=>p.colChildren),gridTemplate:uF(l),sourceIndices:d.map(p=>p.index)}}function jc(e,t="solid"){return e?t==="dashed"?"rounded-md border border-dashed border-border":"rounded-md border border-border":""}function pF(e){return B(jc(e.showBorder,e.borderStyle??"solid"),e.showBorder&&"p-3")}function mF(e){return B(jc(e.showBorder,e.borderStyle??"solid"),e.showBorder&&"p-2")}function hF(e,t){return e.columnBorders?.[t]!==void 0?!!e.columnBorders[t]:!!e.showColumnBorders}function gF(e,t){const r=hF(e,t);return B(jc(r,e.borderStyle??"dashed"),r&&"p-2")}function yF(e){if(e)return{minHeight:`${e}vh`}}function bF({widget:e,renderChildren:t}){const r=e.config,[n,o]=S.useState(r.defaultCollapsed??!1);return c.jsxs("section",{className:B("space-y-4",pF(r)),"data-widget-id":e.id,children:[r.heading&&c.jsx("div",{className:"flex items-center gap-2",children:r.collapsible?c.jsx("button",{type:"button",className:"text-left text-lg font-semibold hover:underline",onClick:()=>o(s=>!s),children:r.heading}):c.jsx("h2",{className:"text-lg font-semibold",children:r.heading})}),r.showDivider&&c.jsx("hr",{className:"border-border"}),!n&&e.children?.length?c.jsx("div",{className:"space-y-4",children:t?.(e.children)}):null]})}function vF({widget:e,renderChildren:t}){const r=e.config,n=Fo(r.columns??2),o=r.collapseEmptyColumns!==!1,s=fF(e.children??[],n,r.columnWidths,{collapseEmpty:o});return c.jsx("div",{className:B("grid w-full min-w-0 items-stretch",dF(r.gap),mF(r)),style:{gridTemplateColumns:s.gridTemplate,...yF(r.minHeightPercent)},"data-widget-id":e.id,children:s.columns.map((i,a)=>{const d=s.sourceIndices[a]??a;return c.jsx("div",{className:B("flex min-h-[inherit] min-w-0 flex-col space-y-4 overflow-hidden",gF(r,d)),children:t?.(i)},d)})})}function wF({widget:e,renderChildren:t}){const r=e.config,n=r.variant==="outline"?"border bg-background":r.variant==="elevated"?"border bg-background shadow-md":"border bg-card";return c.jsxs("div",{className:B("rounded-lg p-4",n),"data-widget-id":e.id,children:[(r.title||r.subtitle)&&c.jsxs("div",{className:"mb-4",children:[r.title&&c.jsx("h3",{className:"font-semibold",children:r.title}),r.subtitle&&c.jsx("p",{className:"text-sm text-muted-foreground",children:r.subtitle})]}),e.children?.length?c.jsx("div",{className:"space-y-4",children:t?.(e.children)}):null]})}function cy(e,t){if(e.variable){const r=t[e.variable];return r!=null?String(r):e.fallback??e.text??""}return e.text??""}function SF({widget:e}){const t=e.config,{context:r}=Lr(),n=cy(t,r),o=t.level??2,s=t.align==="center"?"text-center":t.align==="right"?"text-right":"text-left",i=o===1?"text-3xl":o===2?"text-2xl":o===3?"text-xl":"text-lg";return c.jsx("div",{role:"heading","aria-level":o,className:B("font-semibold tracking-tight",i,s),"data-widget-id":e.id,children:n})}function xF({widget:e}){const t=e.config,{context:r}=Lr(),n=cy(t,r),o=t.preset==="caption"?"text-sm text-muted-foreground":t.preset==="small"?"text-xs text-muted-foreground":"text-base",s=t.align==="center"?"text-center":t.align==="right"?"text-right":"text-left";return c.jsx("p",{className:B(o,s),"data-widget-id":e.id,children:n})}function AF(e,t){return!e||typeof e!="string"?e:e.replace(/\{\{([^}]+)\}\}/g,(r,n)=>{const o=n.trim(),s=t[o];return s==null?"":String(s)})}function dy(e,t){const r={...e};for(const[n,o]of Object.entries(r))typeof o=="string"&&(r[n]=AF(o,t));return r}function CF(e,t){return e.replace(/\{\{([^}]+)\}\}/g,(r,n)=>{const o=t[n.trim()];return o!=null?String(o):""})}function uy(e,t,r,n){if(e.type==="navigate"){const o=CF(e.href,t);if(!o.trim())return;e.openIn==="new"?window.open(o,"_blank","noopener,noreferrer"):window.location.assign(o);return}if(e.type==="navigate_page"&&e.pageId){r({...e,params:e.params?dy(e.params,t):void 0},n,"click");return}if(e.type==="workflow"&&e.workflowId){r(e,n,"click");return}r(e,n,"click")}function EF({widget:e}){const t=e.config,{context:r,dispatchAction:n}=Lr();return c.jsx(Yt,{variant:t.variant??"default",size:t.size??"default","data-widget-id":e.id,onClick:()=>uy(t.action,r,n,e.id),children:t.label})}const NF={start:"justify-start",center:"justify-center",end:"justify-end","space-between":"justify-between"},_F={sm:"gap-2",md:"gap-3",lg:"gap-4"};function kF({widget:e}){const t=e.config,{context:r,dispatchAction:n}=Lr(),o=t.buttons??[];return c.jsx("div",{className:B("flex flex-wrap items-center",NF[t.align??"start"],_F[t.gap??"sm"],t.wrap===!1&&"flex-nowrap"),"data-widget-id":e.id,children:o.map(s=>c.jsx(Yt,{variant:s.variant??"outline",size:s.size??"default","data-widget-id":e.id,"data-button-id":s.id,onClick:()=>uy(s.action,r,n,e.id),children:s.label},s.id))})}function TF(e){const t=e.prepopulateApi;return!!(t?.enabled&&t.api?.path)}function FF(e,t){const r=Qe(e,t??"");return r===void 0?null:r}function fy(e,t){if(e.mode==="pageApi"&&e.dataSourceRef)return t[e.dataSourceRef];if(e.mode==="api")return e.api}function py({widgetId:e,dataSource:t,enabled:r=!0,page:n,pageSize:o,search:s}){const{schema:i,context:a,clientId:d,getFilterGroup:u,prepopulateStatus:l}=Lr(),f=S.useMemo(()=>t.filterGroupKey?u(t.filterGroupKey):{},[t.filterGroupKey,u]),p=t.mode==="context"&&TF(i),m=r&&(t.mode==="static"||(t.mode==="context"?!p||l!=="loading":!!d)),g=S.useMemo(()=>["page-ds",e,t,a,f,n,o,s,l],[e,t,a,f,n,o,s,l]);return gn.useQuery({queryKey:g,enabled:m,staleTime:fy(t,i.dataApis??{})?.staleTimeMs??3e4,queryFn:async()=>{if(t.mode==="static")return t.staticData;if(t.mode==="context")return FF(a,t.contextPath);const h=fy(t,i.dataApis??{});if(!h)throw new Error(`No API config for data source on widget ${e}`);const y={...a};if(t.requestBindings)for(const x of t.requestBindings){let E;x.source==="binding"?E=a[x.key]:x.source==="filter"&&(E=f[x.key]),E!==void 0&&(y[x.param]=E)}const v={...dy(y,a),...n!==void 0?{page:n,pageSize:o,search:s}:{}};return $c({clientId:d,api:h,context:v,filterState:f})}})}function zc(e,t){if(e==null)return"";if(!t||t.type==="none")return String(e);switch(t.type){case"number":{const r=Number(e);return Number.isNaN(r)?String(e):r.toFixed(t.decimals??0)}case"currency":{const r=Number(e);return Number.isNaN(r)?String(e):new Intl.NumberFormat(void 0,{style:"currency",currency:t.currency??"USD"}).format(r)}case"percent":{const r=Number(e);return Number.isNaN(r)?String(e):`${r.toFixed(t.decimals??0)}%`}case"date":{const r=new Date(String(e));return Number.isNaN(r.getTime())?String(e):r.toLocaleDateString(void 0,{...t.format?{}:{}})}case"template":return t.template.replace(/\{\{value\}\}/g,String(e));default:return String(e)}}function ws(e,t){const r=Qe(e,t.path);return r==null?t.fallback??r:t.formatter?zc(r,t.formatter):r}function PF(e,t){if(!t)return{};const r={};for(const[n,o]of Object.entries(t))o in e&&(r[n]=e[o]);return r}const OF={default:"border bg-card",success:"border border-green-200 bg-green-50 text-green-900",warning:"border border-amber-200 bg-amber-50 text-amber-900",danger:"border border-red-200 bg-red-50 text-red-900"},IF={rectangle:"rounded-lg",square:"aspect-square rounded-lg",circle:"aspect-square rounded-full"},MF={sm:"p-2 text-xs",md:"p-4 text-sm",lg:"p-6 text-base"},Uc={sm:"text-lg",md:"text-2xl",lg:"text-3xl"},LF={sm:"gap-2",md:"gap-3",lg:"gap-4"};function DF({title:e,value:t,trend:r,variant:n="default",shape:o="rectangle",size:s="md",layout:i="vertical",isLoading:a,isError:d}){const u=i==="horizontal";return c.jsxs("div",{className:B(OF[n??"default"],IF[o??"rectangle"],MF[s??"md"],u&&"flex items-center justify-between gap-3"),children:[c.jsxs("div",{className:B(u&&"min-w-0"),children:[e&&c.jsx("p",{className:B("font-medium text-muted-foreground",u?"text-sm":""),children:e}),r!=null&&r!==""&&!u&&c.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:String(r)})]}),a?c.jsx(Pn,{className:"my-2"}):d?c.jsx("p",{className:B("font-bold text-destructive",Uc[s??"md"]),children:"Error"}):c.jsx("p",{className:B("font-bold",u?Uc[s??"md"]:`mt-1 ${Uc[s??"md"]}`),children:String(t)}),u&&r!==null&&r!==void 0&&r!==""&&c.jsx("p",{className:"text-xs text-muted-foreground",children:String(r)})]})}function my({stat:e,widgetId:t}){const{data:r,isLoading:n,isError:o}=py({widgetId:t,dataSource:e.dataSource}),i=(()=>{if(r==null)return e.valueMapping.fallback??"—";if(e.dataSource.mode==="context"){const d=r;return e.valueMapping.formatter?zc(d,e.valueMapping.formatter):d}if(e.dataSource.mode==="static"){const d=e.valueMapping.path?.trim()||"value",u=ws(r,{...e.valueMapping,path:d});if(u!=null)return e.valueMapping.formatter?zc(u,e.valueMapping.formatter):u;if(typeof r=="object"&&r!==null&&!Array.isArray(r)){const l=r;if(l.value!==void 0&&l.value!==null)return l.value}return e.valueMapping.fallback??"—"}return ws(r,e.valueMapping)})(),a=e.trendMapping&&r!==void 0&&e.dataSource.mode!=="context"?ws(r,e.trendMapping):e.trendMapping&&e.dataSource.mode==="context"&&e.trendMapping.path?ws({value:r},e.trendMapping):null;return c.jsx(DF,{title:e.title,value:i,trend:a,variant:e.variant,shape:e.shape,size:e.size,layout:e.layout,isLoading:n,isError:o})}function BF({widget:e}){const t=e.config;return c.jsx("div",{"data-widget-id":e.id,children:c.jsx(my,{stat:t,widgetId:e.id})})}function $F({stat:e,widgetId:t}){return c.jsx(my,{stat:e,widgetId:`${t}-${e.id}`})}function jF({widget:e}){const t=e.config,r=t.stats??[],n=t.columns??1,o=t.direction==="horizontal";return c.jsx("div",{"data-widget-id":e.id,className:B(o?"flex flex-wrap":"grid",!o&&n===1&&"grid-cols-1",!o&&n===2&&"grid-cols-2",!o&&n===3&&"grid-cols-3",!o&&n===4&&"grid-cols-4",LF[t.gap??"md"]),children:r.map(s=>c.jsx($F,{stat:s,widgetId:e.id},s.id))})}function zF({widget:e}){const t=e.config,{setFilterValue:r}=Lr(),[n,o]=S.useState("");return S.useEffect(()=>{const s=t.debounceMs??300,i=setTimeout(()=>{r(t.filterGroupKey,"search",n)},s);return()=>clearTimeout(i)},[n,t.debounceMs,t.filterGroupKey,r]),c.jsx("input",{type:"search",className:"flex h-9 w-full max-w-sm rounded-md border border-input bg-background px-3 py-1 text-sm shadow-xs",placeholder:t.placeholder??"Search…",value:n,onChange:s=>o(s.target.value),"data-widget-id":e.id})}function UF(e,t){if(!e)return[];const r=t?Qe(e,t):e;if(Array.isArray(r))return r;if(typeof r=="object"&&r!==null){const n=r;if(Array.isArray(n.items))return n.items;if(Array.isArray(n.data))return n.data}return[]}function VF({widget:e}){const t=e.config,{dispatchAction:r}=Lr(),[n,o]=S.useState(1),[s,i]=S.useState(""),a=t.pagination?.pageSize??10,{data:d,isLoading:u,isError:l}=py({widgetId:e.id,dataSource:t.dataSource,page:n,pageSize:a,search:t.search?.enabled?s:void 0}),f=t.dataSource.mode==="pageApi"?void 0:t.dataSource.api?.itemsPath,p=UF(d,f??"data.items"),m=(g,h)=>{const y=t.dataSource.responseMapping.find(w=>w.target===h);return y?ws(g,y):Qe(g,h)??""};return c.jsxs("div",{className:"space-y-3","data-widget-id":e.id,children:[t.search?.enabled&&c.jsx("input",{type:"search",className:"flex h-9 w-full max-w-sm rounded-md border border-input bg-background px-3 py-1 text-sm",placeholder:t.search.placeholder??"Search…",value:s,onChange:g=>{i(g.target.value),o(1)}}),c.jsx("div",{className:"overflow-x-auto rounded-md border",children:c.jsxs("table",{className:"w-full text-sm",children:[c.jsx("thead",{children:c.jsx("tr",{className:"border-b bg-muted/50",children:t.columns.map(g=>c.jsx("th",{className:B("px-3 py-2 text-left font-medium",g.align==="center"&&"text-center",g.align==="right"&&"text-right"),style:g.width?{width:g.width}:void 0,children:g.header},g.id))})}),c.jsx("tbody",{children:u?c.jsx("tr",{children:c.jsx("td",{colSpan:t.columns.length,className:"px-3 py-8 text-center",children:c.jsx(Pn,{})})}):l?c.jsx("tr",{children:c.jsx("td",{colSpan:t.columns.length,className:"px-3 py-8 text-center text-destructive",children:"Failed to load data"})}):p.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:t.columns.length,className:"px-3 py-8 text-center text-muted-foreground",children:t.emptyMessage??"No data"})}):p.map((g,h)=>c.jsx("tr",{className:"cursor-pointer border-b hover:bg-muted/30",onClick:()=>{r({type:"emit",eventName:"row_click",payload:{row:g}},e.id,"row_click")},children:t.columns.map(y=>c.jsx("td",{className:B("px-3 py-2",y.align==="center"&&"text-center",y.align==="right"&&"text-right"),children:String(m(g,y.field))},y.id))},h))})]})}),t.pagination?.enabled&&c.jsxs("div",{className:"flex items-center justify-between text-sm",children:[c.jsxs("span",{className:"text-muted-foreground",children:["Page ",n]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{type:"button",className:"rounded border px-2 py-1 disabled:opacity-50",disabled:n<=1,onClick:()=>o(g=>Math.max(1,g-1)),children:"Previous"}),c.jsx("button",{type:"button",className:"rounded border px-2 py-1",disabled:p.length<a,onClick:()=>o(g=>g+1),children:"Next"})]})]})]})}const HF=75;function WF(e){return e??HF}function Vc({scrollBehavior:e="page",maxHeightPercent:t,children:r,className:n}){if(e!=="contained")return c.jsx(c.Fragment,{children:r});const o=WF(t);return c.jsx("div",{className:B("min-w-0 overflow-y-auto overflow-x-hidden",n),style:{maxHeight:`${o}vh`},"data-form-embed-scroll":"contained",children:r})}function RF(e,t,r){return["embedded-form",e,t,r??"latest"]}async function GF(e,t){try{const r=await dn.get(`/api/form-builder/form-layouts/form/${e}`,{params:{clientId:t}});let n=r.data?.data??r.data;for(;n&&typeof n=="object"&&!Array.isArray(n)&&n.data!=null&&typeof n.data=="object"&&!("rows"in n)&&!("columns"in n)&&!("formDefinitionId"in n);)n=n.data;return!n||typeof n!="object"||Array.isArray(n)||!("rows"in n)&&!("columns"in n)&&!("formDefinitionId"in n)?null:n}catch{return null}}async function KF(e,t,r){const n=r!==void 0?`/api/form-builder/forms/${e}/render?version=${r}`:`/api/form-builder/forms/${e}/render`,o=await dn.get(n,{params:{clientId:t}}),i=o.data?.data??o.data,a=i.form??i,d=i.fields??a.fields??[];let u=i.layout??a.layout??null;(!u||typeof u.columns!="number")&&(u=await GF(e,t));const l=i.rules??a.rules??[],f=ms(a,d,u,l),p=_s({config:f.config,layout:f.layout},Ns(u))??Ns(u);return{schema:f,gridLayout:p}}const qF=300*1e3;function hy({formId:e,mode:t="fill",contextFieldMapping:r,pageContext:n,clientId:o,formVersion:s,scrollBehavior:i,maxHeightPercent:a}){const{data:d,isLoading:u,isError:l,error:f}=gn.useQuery({queryKey:RF(e,o,s),queryFn:()=>KF(e,o,s),staleTime:qF}),p=S.useMemo(()=>PF(n,r),[n,r]);return u?c.jsx(Vc,{scrollBehavior:i,maxHeightPercent:a,children:c.jsx(Pn,{})}):l?c.jsx(Vc,{scrollBehavior:i,maxHeightPercent:a,children:c.jsx("p",{className:"text-sm text-destructive",children:f instanceof Error?f.message:"Failed to load form"})}):d?.schema?c.jsx(Vc,{scrollBehavior:i,maxHeightPercent:a,children:c.jsx(Mc,{schema:d.schema,mode:t,gridLayout:d.gridLayout,initialValues:p,submissionContext:n})}):null}function YF({widget:e}){const t=e.config,{context:r,clientId:n}=Lr();return t.formId?c.jsx(hy,{formId:t.formId,mode:t.mode??"fill",contextFieldMapping:t.contextFieldMapping,pageContext:r,clientId:n,scrollBehavior:t.scrollBehavior,maxHeightPercent:t.maxHeightPercent}):c.jsx("p",{className:"text-sm text-muted-foreground",children:"No form configured"})}function XF({widget:e}){const t=e.config,{context:r,getWorkflowState:n,clientId:o}=Lr(),s=String(r.moduleId??"");if(!n)return c.jsxs("div",{className:"rounded-md border border-dashed p-4 text-sm text-muted-foreground","data-widget-id":e.id,children:["Workflow embed requires ",c.jsx("code",{className:"text-xs",children:"getWorkflowState"})," on PageRenderer. Workflow ID: ",t.workflowId]});if(!s)return c.jsx("p",{className:"text-sm text-destructive","data-widget-id":e.id,children:"moduleId required in page context for workflow embed"});const i={};if(t.contextVariableMapping)for(const[a,d]of Object.entries(t.contextVariableMapping)){const u=r[d];u!=null&&(i[a]=String(u))}return c.jsx(Yg,{getWorkflowState:n,moduleId:s,tenantId:r.tenantId?String(r.tenantId):void 0,clientId:o||void 0,submissionContext:i})}function JF({widget:e}){const t=e.config,{schema:r,dispatchAction:n}=Lr(),o=t.previousPage??r.navigation?.previousPage,s=t.nextPage??r.navigation?.nextPage,i=t.showPrevious!==!1&&!!o,a=t.showNext!==!1&&!!s,d=t.showBreadcrumbs&&r.navigation?.breadcrumbs?.length,u=t.align==="center"?"justify-center":t.align==="right"?"justify-end":t.align==="space-between"?"justify-between":"justify-start",l=f=>{n({type:"navigate_page",pageId:f.pageId},e.id,"click")};return c.jsxs("nav",{className:"space-y-3","data-widget-id":e.id,children:[d&&c.jsx("ol",{className:"flex flex-wrap items-center gap-1 text-sm text-muted-foreground",children:r.navigation.breadcrumbs.map((f,p)=>c.jsxs("li",{className:"flex items-center gap-1",children:[p>0&&c.jsx("span",{children:"/"}),f.href?c.jsx("a",{href:f.href,className:"hover:underline",children:f.label}):c.jsx("span",{children:f.label})]},p))}),c.jsxs("div",{className:B("flex items-center gap-2",u),children:[i&&o&&c.jsx(Yt,{variant:"outline",size:"sm",onClick:()=>l(o),children:o.label??"Previous"}),a&&s&&c.jsx(Yt,{variant:"default",size:"sm",onClick:()=>l(s),children:s.label??"Next"})]})]})}function QF(e,t){return e?.length?e.filter(r=>r.config.tabId===t):[]}const ZF=1;function eP(e){switch(e){case"pills":return"bg-transparent gap-1 p-0 h-auto";case"underline":return"bg-transparent rounded-none border-b p-0 h-auto w-full justify-start gap-4";default:return""}}function tP(e){switch(e){case"pills":return"rounded-full data-[state=active]:bg-primary data-[state=active]:text-primary-foreground";case"underline":return"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:shadow-none bg-transparent";default:return""}}function rP(e,t,r){return e?new Set(r?[r]:[]):new Set(t.map(n=>n.id))}function nP({tab:e,shouldRender:t,pageContext:r,clientId:n}){return t?e.formId?c.jsx(hy,{formId:e.formId,mode:e.formMode??"fill",contextFieldMapping:e.contextFieldMapping,pageContext:r,clientId:n,scrollBehavior:e.scrollBehavior,maxHeightPercent:e.maxHeightPercent}):c.jsx("p",{className:"text-sm text-muted-foreground",children:"No form configured for this tab"}):null}function oP({tab:e,shouldLoad:t,shouldRender:r,nestingDepth:n,pageContext:o,clientId:s,onAction:i,getWorkflowState:a}){const d=Lr(),{data:u,isLoading:l,isError:f,error:p}=gn.useQuery({queryKey:["tab-page",e.pageId,e.pageVersion,s],enabled:t&&!!e.pageId,queryFn:async()=>Bc(e.pageId,s,e.pageVersion)});return r?n>=ZF?c.jsx("div",{className:"rounded-md border border-destructive/50 bg-destructive/5 p-4 text-sm text-destructive",children:"Nested page tabs not supported"}):e.pageId?l?c.jsx(Pn,{}):f?c.jsx("p",{className:"text-sm text-destructive",children:p instanceof Error?p.message:"Failed to load page"}):u?c.jsx(Hc,{page:u,context:o,nestingDepth:n+1,inheritContext:!0,onAction:i,getWorkflowState:a,parentContext:d}):null:c.jsx("p",{className:"text-sm text-muted-foreground",children:"No page configured for this tab"}):null}function sP({tab:e,widgetChildren:t,renderChildren:r}){const n=QF(t,e.id);return n.length===0?c.jsx("p",{className:"text-sm text-muted-foreground py-4",children:"No widgets in this tab"}):c.jsx(c.Fragment,{children:r?.(n)})}function iP({widget:e,renderChildren:t}){const r=e.config,{context:n,clientId:o,nestingDepth:s,onAction:i,getWorkflowState:a}=Lr(),d=r.tabs??[],u=r.defaultTabId??d[0]?.id??"",l=r.lazyLoad!==!1,[f,p]=S.useState(u),[m,g]=S.useState(()=>rP(l,d,u)),h=w=>{g(v=>new Set(v).add(w)),p(w)},y=S.useMemo(()=>!l,[l]);return d.length===0?c.jsx("p",{className:"text-sm text-muted-foreground","data-widget-id":e.id,children:"No tabs configured"}):c.jsxs(Rg,{value:f,onValueChange:h,className:"w-full","data-widget-id":e.id,children:[c.jsx(Gg,{className:B("mb-4",eP(r.variant)),children:d.map(w=>c.jsx(Kg,{value:w.id,disabled:w.disabled,className:tP(r.variant),children:w.label},w.id))}),d.map(w=>{const v=m.has(w.id),x=y||v,E=y||v;return c.jsxs(qg,{value:w.id,forceMount:y||void 0,className:B("mt-0",y&&"data-[state=inactive]:hidden"),children:[w.contentType==="widgets"&&E&&c.jsx(sP,{tab:w,widgetChildren:e.children??[],renderChildren:t}),w.contentType==="form"&&c.jsx(nP,{tab:w,shouldRender:x,pageContext:n,clientId:o}),w.contentType==="page"&&c.jsx(oP,{tab:w,shouldLoad:x,shouldRender:E,nestingDepth:s,pageContext:n,clientId:o,onAction:i,getWorkflowState:a})]},w.id)})]})}const aP={section:bF,columns:vF,card:wF,tab_group:iP,heading:SF,text:xF,button:EF,button_group:kF,stat_card:BF,stat_grid:jF,data_table:VF,search_filter:zF,form_embed:YF,workflow_embed:XF,page_nav:JF};function lP({widget:e}){return c.jsxs("div",{className:"rounded-md border border-dashed border-muted-foreground/40 bg-muted/20 p-3 text-sm text-muted-foreground","data-widget-id":e.id,"data-widget-type":e.type,children:["Unsupported widget: ",c.jsx("code",{className:"text-xs",children:e.type}),e.label&&c.jsxs("span",{className:"ml-1",children:["(",e.label,")"]})]})}function cP({widget:e,renderChildren:t}){const r=aP[e.type]??lP;return c.jsx(r,{widget:e,renderChildren:t})}function gy(e,t){return e.map(r=>c.jsx(cP,{widget:r,renderChildren:t},r.id))}function Hc({page:e,context:t={},onAction:r,chrome:n="none",className:o,nestingDepth:s=0,getWorkflowState:i,inheritContext:a=!1,parentContext:d}){const u=S.useMemo(()=>eF(e.schema),[e.schema]),l=p=>gy(p,l),f=c.jsxs("div",{className:B("studio-page-content min-h-0 min-w-0",JT(u),o),"data-page-id":e.id,"data-nesting-depth":s,children:[n==="minimal"&&u.meta?.title&&c.jsxs("header",{className:"mb-6 border-b pb-4",children:[c.jsx("h1",{className:"text-2xl font-semibold",children:u.meta.title}),u.meta.description&&c.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:u.meta.description})]}),c.jsx("div",{className:"space-y-6",children:gy(u.widgets,l)})]});return a&&d?f:c.jsx(oF,{schema:u,context:t,clientId:String(t.clientId??""),nestingDepth:s,onAction:r,getWorkflowState:i,parentContext:d,children:f})}function dP({clientId:e,tenantId:t,moduleId:r,featureId:n,pageId:o,routePath:s,routeParams:i={},isDefault:a,context:d={},version:u,chrome:l="none",onAction:f,getWorkflowState:p}){const m=S.useMemo(()=>({...i,...d,clientId:e,tenantId:t,moduleId:r,featureId:n}),[i,d,e,t,r,n]),{data:g,isLoading:h,isError:y,error:w}=gn.useQuery({queryKey:["page-resolve",e,t,r,n,o,s,a,u],queryFn:()=>ry({clientId:e,tenantId:t,moduleId:r,featureId:n,routePath:s,isDefault:a,version:u}),enabled:!o}),v=o??g?.pageId,x=u??g?.version,{data:E,isLoading:P,isError:k,error:N}=gn.useQuery({queryKey:["page-render",v,e,x],queryFn:()=>Bc(v,e,x),enabled:!!v});return!o&&h?c.jsx("div",{className:"flex items-center justify-center p-12",children:c.jsx(Pn,{})}):y?c.jsx("div",{className:"rounded-md border border-destructive/50 bg-destructive/5 p-4 text-sm text-destructive",children:w instanceof Error?w.message:"Failed to resolve page"}):v?P?c.jsx("div",{className:"flex items-center justify-center p-12",children:c.jsx(Pn,{})}):k||!E?c.jsx("div",{className:"rounded-md border border-destructive/50 bg-destructive/5 p-4 text-sm text-destructive",children:N instanceof Error?N.message:"Failed to load page"}):c.jsx(Hc,{page:E,context:m,chrome:l,nestingDepth:0,onAction:f,getWorkflowState:p}):c.jsx("div",{className:"rounded-md border p-4 text-sm text-muted-foreground",children:"No page found for the given scope or route."})}ge.FIELD_TYPE_REGISTRY=KT,ge.FORM_RENDERER_GRID_ROW_HEIGHT_DEFAULT=In,ge.FORM_RENDERER_ROOT_CLASS=ga,ge.FieldRenderer=un,ge.FormRenderer=Mc,ge.PageRenderer=Hc,ge.RendererFieldLayoutContext=_a,ge.StudioPageHost=dP,ge.WorkflowStepsView=Yg,ge.appearanceControlClasses=Bo,ge.appearanceHasExplicitVerticalIntent=kd,ge.appearanceTextareaClasses=vd,ge.backendToFormSchema=ms,ge.cellAlignmentClasses=Nb,ge.cellVerticalJustifyClassesForField=Eb,ge.effectiveWidthPercent=Ps,ge.executeDataSource=$c,ge.fetchPageRender=Bc,ge.fieldBlockBoxStyle=Cb,ge.fieldBlockBoxStyleForField=Nd,ge.fieldBlockHorizontalPlacementClass=xd,ge.fieldBlockHorizontalSelfClass=Ad,ge.fieldBlockHorizontalSelfClassForField=_d,ge.fieldBlockWidthStyle=Sa,ge.fieldBlockWidthStyleForField=Ed,ge.fieldGridShellFillsCellVertically=Is,ge.formBuilderHttp=dn,ge.formLayoutRecordToGridConfig=Ns,ge.getBusinessApiOrigin=Np,ge.getClientId=Tn,ge.getRendererHostAuthHeaders=Ml,ge.getRendererHostViewerContext=bC,ge.getRendererStore=ev,ge.gridCellFlexClasses=Sd,ge.gridCellFlexClassesForField=Na,ge.gridCellOuterFlexClasses=wd,ge.hasExplicitFieldBlockWidth=Cd,ge.isAsyncSearchFieldProperties=HT,ge.isIntrinsicWidthButtonField=to,ge.normalizeWorkflowFormSchema=Zk,ge.normalizeWorkflowFormToRendererSchema=Yi,ge.pageBuilderHttp=vs,ge.parseContentVerticalAlign=Aa,ge.parseMetadataJson=ys,ge.resetRendererHostAuth=yC,ge.resolveBusinessApiUrl=cn,ge.resolveFormGridLayout=_s,ge.resolvePage=ry,ge.resolvedGridCellVerticalJustifyClasses=jo,ge.resolvedHorizontalAlign=Fr,ge.resolvedVerticalAlign=$o,ge.resolvedVerticalAlignForField=Ea,ge.setBusinessApiOrigin=UA,ge.setFormBuilderAuthProvider=vC,ge.setPageBuilderAuthProvider=tF,ge.setRendererHostAuthHeaders=gC,ge.setRendererHostViewerContext=hC,ge.useFieldValidation=RT,ge.useFormRenderer=Vd,ge.useFormValidation=WT,ge.useRendererFieldLayout=zo,ge.useRendererHostAuthStore=Rn,Object.defineProperty(ge,Symbol.toStringTag,{value:"Module"})}));
52
+ `+Mt),xe&&Ao([j,M,D],$r=>{Mt=Eo(Mt,$r," ")}),k&&Je?k.createHTML(Mt):Mt},t.setConfig=function(){let Ee=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Er(Ee),Ye=!0},t.clearConfig=function(){Cr=null,Ye=!1},t.isValidAttribute=function(Ee,F,Y){Cr||Er({});const he=Ct(Ee),st=Ct(F);return Br(he,st,Y)},t.addHook=function(Ee,F){typeof F=="function"&&Co(O[Ee],F)},t.removeHook=function(Ee,F){if(F!==void 0){const Y=W_(O[Ee],F);return Y===-1?void 0:R_(O[Ee],Y,1)[0]}return Xh(O[Ee])},t.removeHooks=function(Ee){O[Ee]=[]},t.removeAllHooks=function(){O=ig()},t}var fk=ag();const pk=["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"],mk=["href","target","rel","src","alt","title","class","style","colspan","rowspan"];function hk(e){return e?fk.sanitize(e,{ALLOWED_TAGS:[...pk],ALLOWED_ATTR:[...mk],ALLOW_DATA_ATTR:!1}):""}function gk(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=Qe(t,s);return i==null?r?"":n:String(i)}):e}function yk(e){return e&&e.replace(/\{api:[^}]*\}/gi,"").replace(/\{labelapi:[^}]*\}/gi,"").replace(/\{resp:[^}]*\}/gi,"").replace(/\{(?:ctx:|@)\w+\}/gi,"").replace(/\{documentId\}/gi,"").replace(/\{(\w+)\}/g,"")}const lg={sm:"text-sm",md:"text-base",lg:"text-lg"},cg={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"},dg={normal:"font-normal",medium:"font-medium",bold:"font-bold"},Ki={left:"text-left",center:"text-center",right:"text-right",justify:"text-justify"};function qn(e){return e.properties??{}}function bk(e){const t=qn(e);return t.textContent!==void 0?t.textContent:e.label??""}function vk(e){return qn(e).textContent===void 0||e.appearance?.hideLabel?!1:!!e.label?.trim()}function wk(e){return e?.contentLayout==="paragraph"?"paragraph":"single"}function Cc(e,t={}){const{formValues:r={},urlParams:n={},submissionContext:o,buttonResponses:s,prepopulateResponse:i,labelApiResponse:a}=t,d=rn(e,r,n,o,s,i),u=gk(d,a,!0);return yk(u)}const Sk=/\{api:[^}]+\}/,xk=/\{labelapi:[^}]+\}/;function Ec(e){return Sk.test(e)}function Nc(e){return xk.test(e)}function Ak(e){const t=e.captionTemplate??"",r=e.descriptionTemplate??"",n=Ec(e.bodyTemplate)||Ec(t)||Ec(r),o=Nc(e.bodyTemplate)||Nc(t)||Nc(r);return!!(n&&e.prepopulateLoading||o&&e.labelApiConfigPresent&&(e.labelApiLoading||e.labelApiResponse===void 0&&e.labelApiError==null))}function ug(e,t){const r=t??qn(e),n=r.variant??"body",o=e.appearance?.size??"md",s=lg[o]??lg.md,i=r.fontWeight??"medium";return n!=="body"?B("m-0 text-foreground",cg[n]??cg.h3,r.fontWeight&&dg[r.fontWeight],r.italic&&"italic",r.underline&&"underline",r.textAlign&&Ki[r.textAlign]):B("m-0 text-foreground",s,dg[i],r.italic&&"italic",r.underline&&"underline",r.textAlign&&Ki[r.textAlign])}function Ck(e,t){const r=(t??qn(e)).variant??"body";return r==="body"?"p":r}function _c(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 u=e.indexOf(a,r+i.length);if(u===-1)return!1;o();const l=e.slice(r+i.length,u);return t.push({type:d,children:_c(l)}),r=u+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 Ek(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function fg(e){return e.map(t=>{if(t.type==="text")return Ek(t.value);const r=fg(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 Nk(e){return e?fg(_c(e)):""}function _k(e,t){return e?t==="markdown-lite"?Nk(e):e:""}function pg(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=pg(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 mg(e,t){if(!e)return null;if(t!=="markdown-lite")return e;const r=_c(e);return r.length===1&&r[0]?.type==="text"?r[0].value:pg(r,"tl")}const kk="text-label-html prose prose-sm max-w-none [&_p]:m-0 [&_p+p]:mt-2 [&_ul]:my-1 [&_ol]:my-1";function hg(e,t){if(!e)return null;const{field:r,asDescription:n=!1}=t,o=t.textProps??qn(r),s=t.contentLayout??wk(o),i=o.inlineFormat??"none";if(s==="paragraph"){const d=hk(_k(e,i));if(!d)return null;const u=n?B("m-0 text-sm",o.descriptionMuted!==!1?"text-muted-foreground":"text-foreground",o.textAlign&&Ki[o.textAlign]):B(ug(r,o),kk);return S.createElement("div",{className:u,dangerouslySetInnerHTML:{__html:d}})}if(n)return S.createElement("p",{className:B("mt-0.5 text-sm",o.descriptionMuted!==!1?"text-muted-foreground":"text-foreground",o.textAlign&&Ki[o.textAlign])},mg(e,i));const a=Ck(r,o);return S.createElement(a,{className:ug(r,o)},mg(e,i))}function Tk(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 Fk(e,t={}){const{formValues:r={},urlParams:n={},submissionContext:o}=t,s=f=>rn(f,r,n,o),i=(e.labelApiMethod??"GET").toUpperCase();let a=cn(s(e.labelApiEndpoint));const d=e.labelApiQueryParams??[];if(d.length){const f=new URLSearchParams;d.forEach(({key:m,value:g})=>{m.trim()&&f.append(m,s(g))});const p=f.toString();p&&(a=`${a}${a.includes("?")?"&":"?"}${p}`)}const u={"Content-Type":"application/json"};(e.labelApiHeaders??[]).forEach(({key:f,value:p})=>{f.trim()&&(u[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 dn.post(a,l??{},{headers:Object.keys(u).length?u:void 0})).data:(await dn.get(a,{headers:Object.keys(u).length?u:void 0})).data}catch(f){const p=f,m=p.response?.status,g=typeof p.response?.data=="string"?p.response.data:p.message??"Request failed";throw new Error(m?`HTTP ${m}: ${g}`:String(g))}}const Pk=({field:e,className:t,formValues:r,urlParams:n,submissionContext:o,buttonResponses:s,prepopulateResponse:i,prepopulateLoading:a=!1})=>{const d=qn(e),u=S.useMemo(()=>Tk(qn(e)),[e.properties]),[l,f]=S.useState(void 0),[p,m]=S.useState(!1),[g,h]=S.useState(null),y=S.useMemo(()=>u?JSON.stringify({endpoint:u.labelApiEndpoint,method:u.labelApiMethod,query:u.labelApiQueryParams,headers:u.labelApiHeaders,body:u.labelApiBodyFields}):"",[u]),w=S.useCallback(async()=>{if(!u){f(void 0),h(null),m(!1);return}m(!0),h(null);try{const W=await Fk(u,{formValues:r??{},urlParams:n??{},submissionContext:o});f(W)}catch(W){f(void 0),h(W instanceof Error?W.message:"Failed to load label API")}finally{m(!1)}},[u,r,n,o]);S.useEffect(()=>{y&&w()},[y,w]);const v=d.textAlign==="center"?"items-center":d.textAlign==="right"?"items-end":d.textAlign==="justify"?"items-stretch":"items-start",x=bk(e),E=vk(e),P=E&&e.label?e.label:"",k=e.description??"",N=Ak({bodyTemplate:x,captionTemplate:P,descriptionTemplate:k,prepopulateLoading:a,labelApiConfigPresent:u!=null,labelApiLoading:p,labelApiResponse:l,labelApiError:g}),C={formValues:r??{},urlParams:n??{},submissionContext:o,buttonResponses:s,prepopulateResponse:i,labelApiResponse:l},A=x?Cc(x,C):"",I=E&&e.label?Cc(e.label,C):"",T=k?Cc(k,C):"";return c.jsx("div",{className:B("w-full min-w-0 h-full min-h-[95px] flex flex-col justify-center py-0.5",v,t),children:N?c.jsx("p",{className:"text-sm text-muted-foreground m-0",children:"Loading…"}):c.jsxs(c.Fragment,{children:[g&&u?c.jsx("p",{className:"text-[10px] text-destructive mb-0.5",title:g,children:"Label API failed"}):null,I?c.jsx("div",{className:"text-sm font-medium text-foreground mb-1 w-full",children:I}):null,A?hg(A,{field:e,textProps:d}):null,T?hg(T,{field:e,textProps:d,asDescription:!0}):null]})})},kc=({legend:e,children:t,className:r,collapsible:n=!1,defaultCollapsed:o=!1,headerActions:s,onCollapsedChange:i})=>{const[a,d]=S.useState(o),u=S.useId(),l=f=>{f.stopPropagation(),n&&d(p=>{const m=!p;return i?.(m),m})};return c.jsxs("fieldset",{className:B("min-w-0 rounded-lg border bg-card p-4",r),"data-form-renderer":"config-section-border",children:[n?c.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2 border-b border-border pb-2",children:[c.jsxs("button",{type:"button",className:B("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":u,onClick:l,children:[c.jsx("span",{className:"shrink-0 text-muted-foreground","aria-hidden":!0,children:a?c.jsx(Zd,{className:"h-4 w-4"}):c.jsx(Wo,{className:"h-4 w-4"})}),c.jsx("span",{className:"truncate",children:e})]}),s!=null?c.jsx("div",{className:"shrink-0",children:s}):null]}):c.jsx("legend",{className:"px-1 text-sm font-medium text-foreground",children:e}),!a&&c.jsxs("div",{id:u,className:"space-y-3",children:[!n&&s!=null?c.jsx("div",{className:"flex justify-end",children:s}):null,t]})]})},un=({field:e,value:t,error:r,onChange:n,onBlur:o,disabled:s,readOnly:i,isRequired:a,className:d,formValues:u={},submissionContext:l,onSubmit:f,onReset:p,onCancel:m,isSubmitting:g,bffSubmitApi:h,onBffSubmitResult:y,extraSubmitPayload:w,buttonResponses:v,onButtonApiResponse:x,onValidateForm:E,getValidationErrors:P,allFields:k,onSubmittingChange:N,onAddMore:C,scopedFormValues:A,scopedFieldNameMap:I,excludedOptionValues:T,prepopulateMappedFieldNames:W,fieldValueKey:X,hideTableRowControls:O=!1,urlParams:j={},prepopulateResponse:M=null,prepopulateLoading:D=!1,formSections:L,submitPayload:U})=>{switch(e.type){case"divider":return c.jsx(T_,{field:e,className:d});case"header":return c.jsx(P_,{field:e,className:d});case"sectionHeading":return c.jsx(M_,{field:e,className:d});case"spacer":return c.jsx(L_,{field:e,className:d});case"textLabel":return c.jsx(Pk,{field:e,className:d,formValues:u,urlParams:j,submissionContext:l,buttonResponses:v,prepopulateResponse:M??void 0,prepopulateLoading:D});case"status":return c.jsx(w_,{field:e,value:t??null,error:r,disabled:s,isRequired:a,className:d,formValues:u,submissionContext:l,extraSubmitPayload:w,prepopulateResponse:M})}switch(e.type){case"text":case"password":case"url":return c.jsx(Da,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"number":return c.jsx(Xd,{field:e,value:t??null,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"email":return c.jsx(su,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"phone":case"aadhaar":return c.jsx(iu,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"textarea":case"richtext":return c.jsx(au,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"select":{const $=X??e.name??e.key??e.id,ie=!!($&&W?.has($));return c.jsx(kp,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,formValues:u,submissionContext:l,excludedOptionValues:T,isPrepopulateTarget:ie})}case"multiselect":{const $=Array.isArray(t)?t:t!=null&&t!==""?[String(t)]:[];return c.jsx(vm,{field:e,value:$,onChange:ie=>n(ie),onBlur:o,error:r,disabled:s,isRequired:a,className:d,formValues:u,submissionContext:l,excludedOptionValues:T})}case"asyncsearch":return c.jsx(Xp,{field:e,value:t,onChange:$=>n($),onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d,formValues:u,submissionContext:l});case"checkbox":case"terms":return c.jsx(wm,{field:e,value:t||!1,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d});case"toggle":return c.jsx(tE,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d});case"radio":case"checkboxgroup":return c.jsx(Gm,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,excludedOptionValues:T});case"selectablelist":{const $=Array.isArray(t)?t:[];return console.log("[SelectableList] FieldRenderer: passing to SelectableListField",{fieldName:e.name,value:$,valueLength:$.length,submissionContextKeys:l?Object.keys(l):[]}),c.jsx(x_,{field:e,value:$,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,submissionContext:l})}case"date":case"time":case"datetime":case"daterange":return c.jsx(Km,{field:e,value:t||"",onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"file":return c.jsx(NE,{field:e,value:t,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,buttonResponses:v});case"camera":return c.jsx(oN,{field:e,value:t??null,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d});case"photoChoice":return c.jsx(sN,{field:e,value:t??null,onChange:n,onBlur:o,error:r,disabled:s,isRequired:a,className:d,buttonResponses:v});case"signature":return c.jsx(QN,{field:e,value:t||null,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"rating":return c.jsx(FN,{field:e,value:t||0,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"slider":return c.jsx(JN,{field:e,value:t||0,onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"table":return c.jsx(ZN,{field:e,value:t||[],onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d,hideRowControls:O,formValues:u,submissionContext:l});case"billingGrid":return c.jsx(v_,{field:e,value:t||{rows:[]},onChange:n,onBlur:o,error:r,disabled:s,readOnly:i,isRequired:a,className:d});case"button":return c.jsx(wN,{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:g,formValues:u,submissionContext:l,buttonResponses:v,onButtonApiResponse:x,bffSubmitApi:h,onBffSubmitResult:y,extraSubmitPayload:w,onValidateForm:E,getValidationErrors:P,allFields:k,onSubmittingChange:N,scopedFormValues:A,scopedFieldNameMap:I,prepopulateResponse:M,formSections:L,submitPayload:U});case"editButton":return c.jsx(SN,{field:e,disabled:s,readOnly:i,isRequired:a,className:d,buttonResponses:v,onButtonApiResponse:x});case"addmore":return c.jsx(xN,{field:e,error:r,disabled:s,readOnly:i,isRequired:a,className:d,onAddMore:()=>C?.(e)});case"customizeSections":return c.jsx(TN,{field:e,error:r,disabled:s,readOnly:i,isRequired:a,className:d});default:return c.jsx("div",{className:"p-3 border rounded-md bg-muted/50",children:c.jsxs("p",{className:"text-sm text-muted-foreground",children:["Unsupported field type: ",e.type]})})}},Ok=({steps:e,currentStep:t,completedSteps:r,onStepClick:n,className:o})=>c.jsx("div",{className:B("mb-8",o),children:c.jsx("nav",{"aria-label":"Progress",children:c.jsx("ol",{className:"flex items-center",children:e.map((s,i)=>{const a=r.has(i),d=t===i,u=n&&(a||i===t+1||i<=t);return c.jsxs("li",{className:B("relative",i!==e.length-1&&"pr-8 sm:pr-20 flex-1"),children:[i!==e.length-1&&c.jsx("div",{className:B("absolute top-4 left-8 -right-8 sm:left-12 sm:-right-12 h-0.5",a?"bg-primary":"bg-border"),"aria-hidden":"true"}),c.jsx("button",{type:"button",onClick:()=>u&&n?.(i),disabled:!u,className:B("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",u&&"cursor-pointer hover:bg-primary/10",!u&&"cursor-default"),"aria-current":d?"step":void 0,children:a?c.jsx(Vs,{className:"h-4 w-4"}):c.jsx("span",{children:i+1})}),c.jsxs("div",{className:"mt-2",children:[c.jsx("span",{className:B("text-sm font-medium",d&&"text-primary",!d&&!a&&"text-muted-foreground"),children:s.name}),s.description&&c.jsx("p",{className:"text-xs text-muted-foreground hidden sm:block",children:s.description})]})]},s.id)})})})});function ps(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 gg(e){return Array.isArray(e)?e.map(ps):[]}function Ik(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=ps(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 Mk{basePath="/api/form-builder/forms";async getForRendering(t,r){if(!Tn())throw new Error("Client ID is required");const o=r!==void 0?`${this.basePath}/${t}/render?version=${r}`:`${this.basePath}/${t}/render`,s=await dn.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=Ik(d);i.form?.moduleId&&(typeof i.form.moduleId=="object"&&i.form.moduleId._id?l.moduleId=ps(i.form.moduleId):typeof i.form.moduleId=="string"&&(l.moduleId=i.form.moduleId));const f=gg(i.fields||[]),p=i.layout?ps(i.layout):null,m=gg(i.rules||[]),g=i.module?ps(i.module):void 0,h=i.clientMapping||i.clientOverrides;return{form:l,fields:f,layout:p,rules:m,module:g,clientMapping:h,clientOverrides:h,BFF_submit_api:a||void 0}}}const Lk=new Mk;function Pn({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=c.jsxs("div",{className:"text-center",children:[c.jsx("div",{className:B("animate-spin rounded-full border-b-2 border-blue-600 mx-auto mb-4",o[t],e)}),r&&c.jsx("p",{className:"text-gray-600",children:r})]});return n?c.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 Dk={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."},Bk=300;function $k(){return{...Dk}}function jk(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 zk(e){const t=$k();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,sections:hN(r.sections),submitPayload:mN(r.submitPayload),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 ms(e,t,r,n){const o=t.map(l=>{let f=[],p={};try{l.options&&(f=JSON.parse(l.options)),l.metadata&&(p=JSON.parse(l.metadata))}catch{}const m=jd(l);m&&Object.assign(p,m),f.length>0&&(p.options=f);const g=[];if(l.validationRequired&&g.push({type:"required",message:"This field is required"}),l.validationMinLength!==null&&l.validationMinLength!==void 0&&g.push({type:"minLength",value:l.validationMinLength,message:`Minimum length is ${l.validationMinLength}`}),l.validationMaxLength!==null&&l.validationMaxLength!==void 0&&g.push({type:"maxLength",value:l.validationMaxLength,message:`Maximum length is ${l.validationMaxLength}`}),l.validationPattern&&g.push({type:"pattern",value:l.validationPattern,message:"Invalid format"}),l.validationRules&&typeof l.validationRules=="object"){const V=l.validationRules;if(V.required===!0&&!g.some(K=>K.type==="required")&&g.push({type:"required",message:"This field is required"}),V.allowLetters!==void 0&&g.push({type:"allowLetters",value:V.allowLetters}),V.allowNumbers!==void 0&&g.push({type:"allowNumbers",value:V.allowNumbers}),V.allowSpecialChars!==void 0&&g.push({type:"allowSpecialChars",value:V.allowSpecialChars}),V.minLetters!==void 0&&typeof V.minLetters=="number"&&g.push({type:"minLetters",value:V.minLetters}),V.maxLetters!==void 0&&typeof V.maxLetters=="number"&&g.push({type:"maxLetters",value:V.maxLetters}),V.minNumbers!==void 0&&typeof V.minNumbers=="number"&&g.push({type:"minNumbers",value:V.minNumbers}),V.maxNumbers!==void 0&&typeof V.maxNumbers=="number"&&g.push({type:"maxNumbers",value:V.maxNumbers}),V.minSpecialChars!==void 0&&typeof V.minSpecialChars=="number"&&g.push({type:"minSpecialChars",value:V.minSpecialChars}),V.maxSpecialChars!==void 0&&typeof V.maxSpecialChars=="number"&&g.push({type:"maxSpecialChars",value:V.maxSpecialChars}),V.fileSize!==void 0&&typeof V.fileSize=="number"){const K=V.fileSize/1048576;g.push({type:"fileSize",value:V.fileSize,message:`File size must be less than ${K.toFixed(2)} MB`})}if(V.fileType!==void 0){const K=Array.isArray(V.fileType)?V.fileType:typeof V.fileType=="string"?V.fileType.split(",").map(J=>J.trim()).filter(Boolean):[];K.length>0&&g.push({type:"fileType",value:K,message:"File type is not allowed"})}}const h=[],y=new Set;n.filter(V=>{const K=typeof V.targetFieldId=="object"?V.targetFieldId.id||V.targetFieldId._id:V.targetFieldId;return!!(K===l.id||K===l._id||K&&l.fieldKey&&K===l.fieldKey)}).forEach(V=>{try{const K=JSON.parse(V.conditionExpression);!K.id&&V.id&&(K.id=V.id);const J=typeof V.targetFieldId=="object"?V.targetFieldId?.id||V.targetFieldId?._id:V.targetFieldId;K.action&&(!K.then||!Array.isArray(K.then)||K.then.length===0)&&(K.then=[{action:K.action,...J&&{target:J}}]),(!K.then||!Array.isArray(K.then)||K.then.length===0)&&V.action&&(K.then=[{action:V.action,...J&&{target:J}}]),K.then&&Array.isArray(K.then)&&J&&(K.then=K.then.map(ne=>!ne.target&&J?{...ne,target:J}:ne));const ce=V.conditionExpression||JSON.stringify(K);if(y.has(ce))return;y.add(ce),h.push(K)}catch{}});const v=l.disabled===!0||p?.disabled===!0||!1;let x=l.readOnly===!0||p?.readOnly===!0||!1;const E=l.hidden===!0||p?.hidden===!0||!1;(p?.valueSource==="calculated"||p?.formula)&&(x=!0);const{disabled:P,readOnly:k,hidden:N,...C}=p,A={};C.hideLabel!==void 0&&(A.hideLabel=C.hideLabel),C.labelPosition!==void 0&&(A.labelPlacement=C.labelPosition),C.size!==void 0&&(A.size=C.size),C.customClass!==void 0&&(A.className=C.customClass);const{labelPosition:I,size:T,customClass:W,visibility:X,...O}=C,j=Object.keys(O).length>0?O:void 0,M=Object.keys(A).length>0?A:void 0,D=l.visibility??p?.visibility??X;let L=jk(D);if(D&&!L){const V=D;(V.visibleToUserType!=null||V.visibleToUserRole!=null||Array.isArray(V.visibleToUserTypes)&&V.visibleToUserTypes.length>0||Array.isArray(V.visibleToUserRoles)&&V.visibleToUserRoles.length>0||Array.isArray(V.visibleToUserIds)&&V.visibleToUserIds.length>0||Array.isArray(V.hiddenFromUserIds)&&V.hiddenFromUserIds.length>0)&&(L={visibleToUserType:V.visibleToUserType??(Array.isArray(V.visibleToUserTypes)?V.visibleToUserTypes[0]:void 0),visibleToUserRole:V.visibleToUserRole??(Array.isArray(V.visibleToUserRoles)?V.visibleToUserRoles[0]:void 0),visibleToUserIds:V.visibleToUserIds,hiddenFromUserIds:V.hiddenFromUserIds})}const U=p?.columnName,ie=!!l.parentFieldId&&typeof U=="string"?U:l.fieldKey;return{id:l.id,type:l.fieldType,name:ie,label:l.label,description:l.helpText||void 0,placeholder:l.placeholder||void 0,defaultValue:l.defaultValue||void 0,position:{order:typeof l.positionOrder=="number"?l.positionOrder:l.positionRow??0,column:typeof l.positionColumn=="number"?l.positionColumn:1,columnSpan:typeof l.positionWidth=="number"?l.positionWidth:1},parentId:void 0,appearance:M,validation:g.length>0?g:void 0,conditions:h.length>0?h:void 0,properties:j,visibility:L&&(L.visibleToUserType!=null||L.visibleToUserRole!=null||Array.isArray(L.visibleToUserIds)&&L.visibleToUserIds.length>0||Array.isArray(L.hiddenFromUserIds)&&L.hiddenFromUserIds.length>0)?L:void 0,disabled:v,readOnly:x,hidden:E}});o.forEach((l,f)=>{if(l.visibility){const p=t[f];console.log("[backendToFormSchema] field with visibility",{fieldKey:p?.fieldKey??l.name,name:l.name,type:l.type,parentFieldId:p?.parentFieldId,visibility:l.visibility})}});const s=t;for(let l=0;l<o.length;l++){const f=s[l]?.parentFieldId;if(f){const p=o.find(g=>g.id===f||g.type==="table"&&g.name===f||g.type==="table"&&s[l].fieldKey?.startsWith?.(g.name+"_column_")),m=o[l];if(p&&p.type==="table"&&m){const g=p.properties||{};Array.isArray(g.columns)||(g.columns=[]),g.columns.push(m),p.properties=g}}}const i=o.filter((l,f)=>!s[f]?.parentFieldId);for(const l of i)if(l.type==="table"&&l.properties&&Array.isArray(l.properties.columns)){const f=l.properties.columns;for(const p of f){const m=p.properties?.columnName;typeof m=="string"&&(p.name=m)}f.sort((p,m)=>(p.position?.order??0)-(m.position?.order??0)||(p.position?.column??0)-(m.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 l=typeof d=="string"?JSON.parse(d):d;l&&typeof l=="object"?a=zk(l):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"};const u=Ns(r);return u&&(a={...a,grid:u}),{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}}const Uk=3;function _o(e){if(typeof e=="number"&&!Number.isNaN(e))return e}function ko(e,t){const r=e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;return _o(r?.cellSlot)??_o(r?.stackSlot)??_o(r?.cellSlotIndex)??_o(r?.slotIndex)??_o(t?.cellSlotIndex)??_o(t?.stackSlot)}function hs(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;if(t?.sharedCellLayout==="row"||t?.sharedCellLayout==="stack")return t.sharedCellLayout;if(t?.stackDirection==="horizontal")return"row";if(t?.stackDirection==="vertical")return"stack"}function qi(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 Tc(e){return[...e].sort((t,r)=>{const n=ko(t.position),o=ko(r.position);return typeof n=="number"&&typeof o=="number"&&n!==o?n-o:String(t.id).localeCompare(String(r.id))})}function gs(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,Do(o)),n=Math.max(n,bd(o,t));return{rowSpan:r,columnSpan:n}}function yg(e){const t=Tc(e);for(const r of t){const n=hs(r.position);if(n)return n}return t.length>=2?"row":"stack"}function bg(e){return Tc(e).slice(0,Uk)}function Vk(e,t){const r=new Map;for(const n of e){if(!t(n)||typeof n.position?.order!="number")continue;const o=qi(n),s=r.get(o)??[];s.push(n),r.set(o,s)}return Array.from(r.values()).map(n=>bg(n))}function vg(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=qi(a),u=s.get(d)??[];u.push(a),s.set(d,u)}const i=[...s.values()][0]??[];return bg(i)}function Hk(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}=gs(r,n),u=e===s&&t===i-1,l=e>=s&&e<s+a,f=t>=i-1&&t<i-1+d;return l&&f&&!u}function Wk(e,t,r){const n=new Set(r??[]);for(const o of e){const s=o[0]?.position?.order??0,{rowSpan:i}=gs(o,t);for(let a=s;a<s+i;a++)n.add(a)}return n}function Rk(e){const t=[...e].sort((n,o)=>n-o),r=new Map;return t.forEach((n,o)=>r.set(n,o)),{originalToDisplay:r,displayRowCount:Math.max(t.length,1),sortedOriginalRows:t}}function Gk(e,t,r){const n=r.get(e);if(n===void 0)return;let o=0;for(let s=e;s<e+t&&r.has(s);s++)o++;return`${n+1} / span ${Math.max(o,1)}`}function gr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function To(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>To(r));if(!gr(e))return e;const t={};for(const[r,n]of Object.entries(e))t[r]=To(n);return t}function wg(e,...t){const r={...e};for(const n of t)if(!(!n||!gr(n)))for(const[o,s]of Object.entries(n)){const i=r[o];gr(s)&&gr(i)?r[o]=wg(i,s):r[o]=s}return r}function Yn(e){return gr(e)?e:{}}function ys(e){if(e==null)return{};if(typeof e=="string"){const t=e.trim();if(!t)return{};try{const r=JSON.parse(t);return gr(r)?To(r):{}}catch{return{}}}return gr(e)?To(e):{}}function Sg(e){const t=e.apidata;return gr(t)&&Object.keys(t).length>0}function Kk(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||Sg(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 xg=["hideLabel","contentAlign","contentVerticalAlign","labelPlacement","widthPercent","widthMode","className","verticalAlign","horizontalAlign","cellAlign","cellJustify","size","variant","minWidth","minHeight"];function qk(e,t){const r=e.appearance,n=gr(r)&&Object.keys(r).length>0?To(r):{},o=Yn(t.appearance),s={...n};for(const[i,a]of Object.entries(o))i!=="heightPercent"&&s[i]===void 0&&(s[i]=To(a));for(const i of xg)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 Yk(e,t){const r=Yn(e.position),n=ys(e.metadata),o=Yn(e.layout),s=typeof r.order=="number"&&!Number.isNaN(r.order)?r.order:typeof e.positionOrder=="number"?e.positionOrder:typeof e.order=="number"?e.order:typeof e.positionRow=="number"?e.positionRow:t,i=typeof r.column=="number"&&!Number.isNaN(r.column)?r.column:typeof e.positionColumn=="number"?e.positionColumn:1,a=typeof r.columnSpan=="number"&&!Number.isNaN(r.columnSpan)?r.columnSpan:typeof e.positionWidth=="number"?e.positionWidth:1,d=typeof r.rowSpan=="number"&&!Number.isNaN(r.rowSpan)?r.rowSpan:typeof e.positionRowSpan=="number"?e.positionRowSpan:1,u={order:s,column:i,columnSpan:a,rowSpan:d},l=r.cellGroupId??o.cellGroupId,f=ko(r,{cellSlotIndex:e.cellSlotIndex??o.cellSlotIndex,stackSlot:n.stackSlot??o.stackSlot}),p=hs(r)??hs(o)??(n.stackDirection==="horizontal"||o.stackDirection==="horizontal"?"row":n.stackDirection==="vertical"||o.stackDirection==="vertical"?"stack":void 0);return typeof l=="string"&&(u.cellGroupId=l),typeof f=="number"&&(u.cellSlot=f),(p==="row"||p==="stack")&&(u.sharedCellLayout=p),u}function Xk(e,t){const r=e,n=ys(r.metadata),o=Yn(r.apidata),s=Yn(r.properties),i=wg({},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),u=qk(r,n),l=Yk(r,t),f={...r};return f.properties=i,a!==void 0&&(f.name=a),d!==void 0&&(f.type=d),u!==void 0?f.appearance=u:(!gr(r.appearance)||Object.keys(r.appearance).length===0)&&delete f.appearance,f.position=l,gr(f.appearance)&&delete f.appearance.heightPercent,f}function Jk(e,t){if(!e||typeof e!="object")return!0;const r=e,n=ys(r.metadata),o=Object.keys(n).length===0&&!(typeof r.metadata=="string"&&r.metadata.trim()!==""),s=!Sg(r);if(Kk(r)||!o||!s)return!1;const i=r.position;return!(!(gr(i)&&typeof i.order=="number"&&!Number.isNaN(i.order))&&(typeof r.positionRow=="number"||typeof r.positionColumn=="number"||typeof r.positionWidth=="number"||typeof r.positionRowSpan=="number"||typeof r.positionOrder=="number")||gr(n.appearance)||xg.some(u=>n[u]!==void 0&&(r.appearance==null||gr(r.appearance)&&r.appearance[u]===void 0))||Qk(r))}function Qk(e){const t=Yn(e.position),r=Yn(e.layout),n=ys(e.metadata);return(typeof e.cellSlotIndex=="number"||typeof t.stackSlot=="number"||typeof t.cellSlot=="number"||typeof t.cellSlotIndex=="number"||typeof n.stackSlot=="number"||typeof r.stackSlot=="number")&&typeof t.cellSlot!="number"||(t.stackDirection==="horizontal"||t.stackDirection==="vertical"||n.stackDirection==="horizontal"||n.stackDirection==="vertical"||r.stackDirection==="horizontal"||r.stackDirection==="vertical")&&t.sharedCellLayout!=="row"&&t.sharedCellLayout!=="stack"}function Yi(e){if(e==null||typeof e!="object")return e;const t=e.fields;if(!Array.isArray(t))return e;let r=!1;const n=t.map((o,s)=>{if(Jk(o))return o;const i=Xk(o,s);return i!==o&&(r=!0),i});return r?{...e,fields:n}:e}function Zk(e){return Yi(e)}const eT=new Set(["PENDING_PAYMENT","PAYMENT_PENDING","AWAITING_PAYMENT","PAID","PAYMENT_COMPLETED","PAYMENT_FAILED","REFUNDED","AUTHORIZED","CAPTURED","PARTIALLY_PAID"].map(e=>e.toUpperCase()));function Fc(e){return typeof e=="string"&&e.trim()!==""}function Pc(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"||Fc(t.amount)||typeof t.total_amount=="number"||Fc(t.total_amount)||Fc(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"&&eT.has(r.trim().toUpperCase()))}function tT(e){const t=Qe(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 rT(e,t){const r=tT(e);if(!r)return;const n=Qe(e,"data"),o=n!=null&&typeof n=="object"&&!Array.isArray(n)?n:void 0;if(t?.treatFirstItemIdAsPaymentId===!0||Pc(r.item)||o!=null&&Pc(o))return r.id}function nT(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 oT(e){return nT(e).some(t=>t.toLowerCase().includes("payment"))}function sT(e){const t=e.properties,r=e.metadata;return!!(t?.mergeSuccessDataIdAsPaymentId||r?.mergeSuccessDataIdAsPaymentId)}function iT(e,t){if(t?.type!=="button"||!Uo(e))return;const r=Qe(e,"data.id");if(r==null||String(r).trim()==="")return;const n=Qe(e,"data");if(sT(t)||n!=null&&typeof n=="object"&&!Array.isArray(n)&&Pc(n)||oT(t))return r}const aT=new Set(["section","group","columns","divider","header","sectionHeading","spacer","addmore","textLabel","customizeSections"]);function lT(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 cT(e,t){const r=e.properties,n=Array.isArray(r?.linkedFieldNames)?r.linkedFieldNames:[],o=lT(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 Ag(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 dT(e,t){return Ag(e,t).find(r=>r.heading?.enabled)}function Cg(e,t){const r=e.template??"";return(e.mode??"increment")==="fixed"?r:r.replace(/\{n\}/g,String(t+1))}function Eg(e,t,r,n){const o=cT(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||aT.has(i.type)?!1:s.has(a)})}function uT(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 Oc(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 fT(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(u=>o.get(u)).filter(u=>!!u);if(a.length===0)continue;const d=Oc(a).map(u=>r(u)).filter(Boolean);s.push({section:i,fieldNames:d})}return s}function bs(e,t=0){return e.heading?.enabled?Cg(e.heading,t):e.name}function Ng(e,t,r){if(e.type!=="sectionHeading")return!1;const n=t.heading;return!n?.enabled||!n.headingFieldName?!1:r(e)===n.headingFieldName}function pT(e,t){const r=typeof e.position?.order=="number"?e.position.order:0,n=(e.position?.column??1)-1,o=Do(e),s=bd(e,t);return{row:r,col:n,rowEnd:r+o-1,colEnd:n+s-1}}function Ic(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:u,colEnd:l}=pT(i,t);r=Math.min(r,a),n=Math.max(n,u),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 mT(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=Ic(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)),u=Math.max(1,...a.map(l=>(l.position?.order??d)-d+Do(l)));return{minRow:s.minRow,maxRow:s.maxRow,minCol:s.minCol,maxCol:s.maxCol,blockHeight:u}}function hT(e,t){return e.maxRow+1+t*e.blockHeight}function gT(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 u=d.filter(v=>!Ng(v,a.section,r)),l=Ic(d,n);if(!l)continue;const{minRow:f,minCol:p,rowSpan:m,colSpan:g}=l,h=`${f}-${p}`;if(s.has(h))continue;const y=new Set;let w=!1;for(let v=f;v<=f+m-1;v++){for(let x=p;x<=p+g-1;x++){const E=`${v}-${x}`;if(i.has(E)){w=!0;break}y.add(E)}if(w)break}if(!w){for(const v of y)i.add(v);s.set(h,{anchorRow:f,anchorCol:p,rowSpan:m,colSpan:g,run:a,legend:bs(a.section,0),renderFields:u.length>0?u:d})}}return{anchorsByOrigin:s,coveredCells:i}}function yT(e,t,r,n,o,s,i){const a=new Set(i),d=new Map;for(const u of e){const l=_g(u.linkedFields.map(p=>s(p)).filter(Boolean),t),f=l?.section;f?.fieldNames?.length?f.fieldNames:u.templateFieldNames,u.blockIds.forEach((p,m)=>{const g=r.filter(N=>N.id.endsWith(`__${p}`));if(g.length===0||!l)return;const h=Ic(g,o);if(!h)return;const{minRow:y,minCol:w,rowSpan:v,colSpan:x}=h,E=`${y}-${w}`;for(let N=y;N<=y+v-1;N++)for(let C=w;C<=w+x-1;C++)a.add(`${N}-${C}`);const P=l,k=bs(f,m+1);d.set(E,{anchorRow:y,anchorCol:w,rowSpan:v,colSpan:x,run:P,legend:k,renderFields:Oc(g),addMoreMeta:{addMoreFieldName:u.addMoreFieldName,blockId:p,blockIndex:m}})})}return{anchorsByOrigin:d,coveredCells:a}}function bT(e,t,r,n){const o=`${e}-${t}`;return r.has(o)?!n.get(o):!1}function vT(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 wT(e,t,r,n){return!(!n||r.run.section.collapsible!==!0||e===r.anchorRow&&t===r.anchorCol)}function ST(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 xT(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 AT(e,t){return new Map([...e,...t])}function CT(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 u=[],l=new Set(d.fieldNames);for(;s<e.length;){const p=r(e[s]);if(!p||!l.has(p))break;const m=e[s];Ng(m,d.section,r)||u.push(m),s+=1}if(u.length===0)continue;const f=o[o.length-1];f?.kind==="border"&&f.run.section.id===d.section.id?f.fields.push(...u):o.push({kind:"border",run:d,fields:u})}return o}function _g(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 ET=2*6e4,kg=50;class NT{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<=kg)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-kg)).forEach(([n])=>this.map.delete(n))}}function _T(e){return(e??"").trim()||"default"}function Tg(e){const t=_T(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 Fg=new NT(ET);function Pg(e){const t=Tg(e),r=Fg.get(t);return r?{value:r.value,isStale:r.isStale}:null}function Og(e,t){const r=Tg(e);Fg.set(r,t)}function Ig(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 Mc=({schema:e,formId:t,initialValues:r,onSubmit:n,onChange:o,onValidationError:s,onClose:i,mode:a="fill",className:d,children:u,gridLayout:l,unstyled:f=!1,submissionContext:p,onWorkflowSubmitResult:m,initialExtraSubmitPayload:g,onExtraSubmitPayloadChange:h,workflowStepId:y,viewerContext:w,getViewerContext:v,hideTableRowControls:x=!1,themeVars:E,dark:P=!1,omitRootWrapper:k=!1})=>{const N=Rn(_=>_.viewerContext),C=S.useMemo(()=>{if(w!==void 0)return w;const _=v?.();return _!==void 0?_:N},[w,v,N]),[A,I]=S.useState(e||null),[T,W]=S.useState(!!t&&!e),[X,O]=S.useState(null),j=e?.BFF_submit_api??X,[M,D]=S.useState(!1),[L,U]=S.useState({}),[$,ie]=S.useState({}),[V,K]=S.useState({}),[J,ce]=S.useState({}),[ne,G]=S.useState({}),[ee,Pe]=S.useState(null),oe=ha.useParams(),re=Nt(_=>_.setValues),be=Nt(_=>_.setSubmitting),de=Nt(_=>_.formDisabled),ot=Nt(_=>_.visibleFields),Se=Nt(_=>_.requiredFields),xe=Nt(_=>_.updateVisibility),ae=Nt(_=>_.updateRequired),ve=Nt(_=>_.setFieldError),Ye=S.useRef(!1),ct=S.useRef(void 0),Ge=S.useMemo(()=>{if(!e)return null;const _=e;if(_.form&&Array.isArray(_.form.fields))try{return ms(_.form,_.form.fields,_.form.layout||null,_.form.rules||[])}catch{return e}if(Array.isArray(_.fields)&&_.fields.some(z=>typeof z.metadata=="string"&&z.metadata.startsWith("{")||z.fieldType&&!z.type))try{const z={id:_.id||_._id||"temp",name:_.name||"Form",version:_.version??1,status:_.status||"draft",createdAt:_.createdAt||new Date().toISOString(),updatedAt:_.updatedAt||new Date().toISOString(),createdBy:_.createdBy||"system",category:_.category||"",moduleId:_.moduleId,tenantId:_.tenantId,featureId:_.featureId,isDefault:_.isDefault||!1};return ms(z,_.fields,_.layout||null,_.rules||[])}catch{return e}return e},[e]);S.useEffect(()=>{if(e){const _=e;_.BFF_submit_api&&O(_.BFF_submit_api)}},[e]);const Kt=S.useMemo(()=>{const _=Ge||A,H=_?Yi(_):null;if(!H)return null;const z=H.layout,Z=H.rules,Q=H.clientMapping,le=(Array.isArray(H.fields)?H.fields:[]).map(Le=>{let Ve={...Le};if(Le.validationRules&&typeof Le.validationRules=="object"&&!Le.validation){const fe=Le.validationRules,Fe=[];fe.required===!0&&Fe.push({type:"required",message:"This field is required"}),fe.minLength!==void 0&&typeof fe.minLength=="number"&&Fe.push({type:"minLength",value:fe.minLength,message:`Minimum length is ${fe.minLength}`}),fe.maxLength!==void 0&&typeof fe.maxLength=="number"&&Fe.push({type:"maxLength",value:fe.maxLength,message:`Maximum length is ${fe.maxLength}`}),fe.pattern&&typeof fe.pattern=="string"&&Fe.push({type:"pattern",value:fe.pattern,message:"Invalid format"}),fe.allowLetters!==void 0&&Fe.push({type:"allowLetters",value:fe.allowLetters}),fe.allowNumbers!==void 0&&Fe.push({type:"allowNumbers",value:fe.allowNumbers}),fe.allowSpecialChars!==void 0&&Fe.push({type:"allowSpecialChars",value:fe.allowSpecialChars}),Fe.length>0&&(Ve={...Ve,validation:Fe})}const we=Le.required===!0||Le.isRequired===!0,Ae=Array.isArray(Ve.validation)&&Ve.validation.some(fe=>fe.type==="required");if(we&&!Ae){const fe={type:"required",message:"This field is required"},Fe=Array.isArray(Ve.validation)?Ve.validation:[];Ve={...Ve,validation:[...Fe,fe]}}if(Le.apidata&&typeof Le.apidata=="object"){const fe=Le.apidata,Fe=Ve.properties||{},ye=(Ve.type||Le.fieldType)==="status";if(!Fe.apiEndpoint&&fe.apiEndpoint){const dt={...Fe,apiEndpoint:fe.apiEndpoint,apiMethod:fe.apiMethod,apiKey:fe.apiKey,apiRealtime:fe.apiRealtime,apiAutoDetect:fe.apiAutoDetect,apiLabelField:fe.apiLabelField,apiValueField:fe.apiValueField,apiQueryParams:fe.apiQueryParams,apiClientFilter:fe.apiClientFilter,valueSource:fe.valueSource||(fe.apiEndpoint?"api":void 0),optionsSource:fe.optionsSource||(fe.apiEndpoint?"api":void 0)};ye&&(dt.source=Fe.source??"api",Fe.statuses!==void 0&&(dt.statuses=Fe.statuses),Fe.dataPath!==void 0&&(dt.dataPath=Fe.dataPath),Fe.showStatusText!==void 0&&(dt.showStatusText=Fe.showStatusText),Fe.statusTextPath!==void 0&&(dt.statusTextPath=Fe.statusTextPath),Fe.showCurrentIndicator!==void 0&&(dt.showCurrentIndicator=Fe.showCurrentIndicator)),Ve={...Ve,properties:dt}}}const He=["select","multiselect","radio","checkboxgroup"],rt=Ve.type||Le.fieldType;if(He.includes(rt)){const fe=Le.options,Fe=Ve.properties?.options,ye=Array.isArray(Fe)&&Fe.length>0;if(Array.isArray(fe)&&fe.length>0&&!ye){const dt=Ve.properties||{};Ve={...Ve,properties:{...dt,options:fe}}}}return Ve}),Ce=H.config?.rules,Ne=Z&&Array.isArray(Z)?Z:Ce&&Array.isArray(Ce)?Ce:[],De=Ne.length>0?le.map(Le=>{if((Le.conditions&&Array.isArray(Le.conditions)?Le.conditions:[]).length>0)return Le;const we=Le.id??Le._id,Ae=Le.name||Le.key,He=Ne.filter(Fe=>{const ye=typeof Fe.targetFieldId=="object"?Fe.targetFieldId?.id??Fe.targetFieldId?._id:Fe.targetFieldId;return ye?ye===we||ye===Ae||ye===Le.fieldKey:!1});if(He.length===0)return Le;const rt=[],fe=new Set;return He.forEach(Fe=>{try{const ye=typeof Fe.conditionExpression=="string"?JSON.parse(Fe.conditionExpression):Fe.conditionExpression;if(!ye||typeof ye!="object")return;!ye.id&&Fe.id&&(ye.id=Fe.id);const dt=typeof Fe.targetFieldId=="object"?Fe.targetFieldId?.id??Fe.targetFieldId?._id:Fe.targetFieldId;ye.action&&(!ye.then||!Array.isArray(ye.then)||ye.then.length===0)&&(ye.then=[{action:ye.action,...dt&&{target:dt}}]),(!ye.then||!Array.isArray(ye.then)||ye.then.length===0)&&Fe.action&&(ye.then=[{action:Fe.action,...dt&&{target:dt}}]),ye.then&&Array.isArray(ye.then)&&dt&&(ye.then=ye.then.map(Bt=>!Bt.target&&dt?{...Bt,target:dt}:Bt));const Wt=Fe.conditionExpression??JSON.stringify(ye);if(fe.has(Wt))return;fe.add(Wt),rt.push(ye)}catch{}}),rt.length===0?Le:{...Le,conditions:rt}}):le;let at=H.config||{submitAction:"database",layout:"default",autoSave:!0,validateOnChange:!0,showFieldErrors:"inline"};return!at.layout&&z?typeof z=="object"&&z!==null?at.layout="default":typeof z=="string"&&["default","card","compact"].includes(z)?at.layout=z:at.layout="default":at.layout||(at.layout="default"),Z&&!at.rules&&(at.rules=Z),Q&&!at.clientMapping&&(at.clientMapping=Q),{...H,fields:De,config:at}},[Ge,A]);S.useEffect(()=>{Ge&&Ge!==A&&I(Ge)},[Ge]),S.useEffect(()=>{if(t&&!e){const _=(Tn()??"").trim()||"default",H=Pg({scope:_,formId:t,version:"latest"});H?.value?.schema?(I(H.value.schema),H.value.bffSubmitApi&&O(H.value.bffSubmitApi),W(!1),H.isStale&&Je({background:!0})):Je({background:!1})}},[t,e]);const Je=async({background:_})=>{if(!t)return;const H=t;_||W(!0);try{const z=await Lk.getForRendering(t),Z=ms(z.form,z.fields,z.layout,z.rules);if(H!==t)return;I(Z),z.BFF_submit_api&&O(z.BFF_submit_api);const Q=(Tn()??"").trim()||"default";Og({scope:Q,formId:H,version:"latest"},{schema:Z,bffSubmitApi:z.BFF_submit_api})}catch{}finally{_||W(!1)}};if(T)return c.jsx("div",{className:"flex items-center justify-center py-12",children:c.jsx(Pn,{})});if(!Kt)return c.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Form not found"});const q=Kt,$e=S.useMemo(()=>new Set(Object.keys(q.config?.prepopulateApi?.fieldMapping??{})),[q.config?.prepopulateApi?.fieldMapping]),gt=S.useCallback(async _=>{const H=q?.fields?.length?tc(_,q.fields):_,z=yh(H,q.config?.sections,q.config?.submitPayload);if(n){const Z=p?{...z,...p}:z;return n(Z)}return{success:!0}},[n,p,q?.fields,q.config?.sections,q.config?.submitPayload]),{values:Oe,errors:te,touched:pe,isSubmitting:We,isValid:Pt,submitCount:je,currentStep:Te,totalSteps:Xe,completedSteps:Ue,currentStepFields:ft,isLastStep:St,setFieldValue:xt,setFieldTouched:ze,handleSubmit:yt,validateForm:pt,resetForm:At,nextStep:Ut,goToStep:ur,shouldShowField:Ar,isFieldEnabled:Vt,isFieldRequired:Po,loadDraft:Xn}=Vd({schema:q,initialValues:r,onSubmit:gt,onChange:o,workflowStepId:y});sv({fields:q.fields,values:Oe,buttonResponses:$,prepopulateResponse:ee,prepopulateResponseRules:q.config?.prepopulateResponseRules});const Ct=Nt(_=>_.readOnlyFields),Cr=Nt(_=>_.editableFields),Jn=S.useCallback(_=>Ct.has(_),[Ct]),It=S.useCallback(_=>Cr.has(_),[Cr]);S.useEffect(()=>{q.config?.allowDraft&&a==="fill"&&Xn()},[q.id]),S.useEffect(()=>{ct.current=q.id,Ye.current=!1,U({}),K({}),ce({}),G({}),Pe(null)},[q.id]),S.useEffect(()=>{const _=q.config?.prepopulateApi,H=!!(_?.fieldMapping&&Object.keys(_?.fieldMapping??{}).length>0),z=(q.config?.prepopulateResponseRules?.length??0)>0;if(!_?.enabled||!_.apiEndpoint?.trim()||!H&&!z||Ye.current)return;Ye.current=!0;const Z=q.id;ct.current=q.id;let Q=!1;return D(!0),(async()=>{try{const le=Nt.getState().values,Ce=typeof p=="object"&&p!==null?{...p,...g||{}}:g||{},Ne=se=>rn(se,le,oe,Ce);let De=cn(Ne(_.apiEndpoint));if(_.apiQueryParams?.length){const se=new URLSearchParams;_.apiQueryParams.forEach(({key:Ie,value:me})=>se.append(Ie,Ne(me))),De=`${De}${De.includes("?")?"&":"?"}${se.toString()}`}const at={};_.apiHeaders?.forEach(({key:se,value:Ie})=>{se.trim()&&(at[se]=Ne(Ie))}),at["Content-Type"]=at["Content-Type"]??"application/json";let Ht;if(_.apiMethod==="POST"&&_.apiBodyFields?.length){const se={};_.apiBodyFields.forEach(({key:Ie,value:me})=>{Ie.trim()&&(se[Ie]=Ne(me))}),Ht=JSON.stringify(se)}const Le=await fetch(De,{method:_.apiMethod,headers:at,body:_.apiMethod==="POST"?Ht:void 0});if(!Le.ok){const se=await Le.text();throw new Error(se||`HTTP ${Le.status}`)}const Ve=await Le.json(),we=se=>{try{return se.split("?")[0].split("/").filter(Boolean).pop()||se}catch{return se}},Ae=(se,Ie)=>{if(se==null)return null;const me=typeof se=="string"?se:se instanceof Date?se.toISOString():null;if(!me)return null;const Ke=typeof se=="object"&&se instanceof Date?se:new Date(me);if(Number.isNaN(Ke.getTime()))return null;const ut=mt=>String(mt).padStart(2,"0");if(Ie==="date")return me.length>=10&&me[4]==="-"&&me[7]==="-"?me.slice(0,10):Ke.toISOString().slice(0,10);if(Ie==="time")return`${ut(Ke.getHours())}:${ut(Ke.getMinutes())}:${ut(Ke.getSeconds())}`;if(Ie==="datetime"){const mt=Ke.getFullYear(),tt=Ke.getMonth()+1,ue=Ke.getDate(),bt=Ke.getHours(),Re=Ke.getMinutes(),Ft=Ke.getSeconds();return`${mt}-${ut(tt)}-${ut(ue)}T${ut(bt)}:${ut(Re)}:${ut(Ft)}`}return null},He=(se,Ie)=>{const me=q.fields.find(ue=>ue.name===se||ue.key===se);if(!me)return Ie;if((me.type==="file"||me.type==="camera"||me.type==="photoChoice")&&typeof Ie=="string"&&Ie.startsWith("http"))return{url:Ie,name:we(Ie)};if(me.type==="date"||me.type==="datetime"||me.type==="time"){const ue=Ae(Ie,me.type);if(ue!==null)return ue}if(me.type==="multiselect")return Array.isArray(Ie)?Ie.map(ue=>typeof ue=="string"?ue:String(ue)):typeof Ie=="string"?Ie.trim()===""?[]:Ie.includes(",")?Ie.split(",").map(ue=>ue.trim()).filter(Boolean):[Ie]:Ie!=null&&Ie!==""?[String(Ie)]:[];if(me.type!=="radio"&&me.type!=="select")return Ie;const Ke=me.properties?.options??me.options;if(!Array.isArray(Ke)||Ke.length===0)return Ie;const ut=Ke.map(ue=>ue.value);if(ut.includes(Ie))return Ie;const mt=String(Ie);if(ut.includes(mt))return mt;const tt=Ke.find(ue=>ue.value==Ie);return tt?tt.value:Ie},rt=new Set(q.fields.filter(se=>se.type==="table").map(se=>se.name||se.key)),fe=new Set(q.fields.filter(se=>se.type==="billingGrid").map(se=>se.name||se.key)),Fe=se=>se.name||se.key||se.id,ye={},dt=[],Wt=[],Bt=gN(_?.fieldMapping,q.config?.sections,q.config?.submitPayload);for(const[se,Ie]of Object.entries(Bt)){if(!Ie?.trim()||se.startsWith("__"))continue;const me=Qe(Ve,Ie),Ke=se.indexOf(".");if(Ke>0&&fe.has(se.slice(0,Ke))){const mt=se.slice(0,Ke),tt=se.slice(Ke+1),bt=q.fields.find(Re=>(Re.name||Re.key)===mt)?.properties;if(bt?.rowSlots?.length){const Re=tt.startsWith("__block__")?tt.slice(9):tt,Ft=ye[mt]??Nt.getState().values[mt];Array.isArray(me)?ye[mt]=f_(bt,Re,me,Ft):me!=null&&(ye[mt]=mc(bt,me,Ft))}continue}if(Ke>0&&rt.has(se.slice(0,Ke))){const mt=se.slice(0,Ke),tt=se.slice(Ke+1);dt.push({tableName:mt,columnName:tt,path:Ie});continue}if(fe.has(se)&&me!==void 0&&me!==null&&typeof me=="object"){const tt=q.fields.find(ue=>(ue.name||ue.key)===se)?.properties;if(tt?.rowSlots?.length){if(Array.isArray(me)){const ue=tt.rowSlots.find(bt=>bt.kind==="dynamic");if(ue&&ue.kind==="dynamic"){const bt=ue.block.apiArrayPath??"items";ye[se]=mc(tt,{[bt]:me})}}else ye[se]=mc(tt,me);continue}}if(rt.has(se)&&Array.isArray(me)&&me.length>0&&typeof me[0]=="object"&&me[0]!==null){const tt=q.fields.find(Re=>(Re.name||Re.key)===se)?.properties?.columns||[],ue=me.map(Ig),bt=Re=>(Re||"").toLowerCase().replace(/\s+/g,"_").trim();ye[se]=ue.map(Re=>{const Ft={};for(const fr of tt){const eo=fr.name??"";Ft[eo]=Re[bt(eo)]??Re[eo]}return Ft});continue}if(me!=null&&(ye[se]=He(se,me)),me==null)continue;let ut=me;if(Array.isArray(me)){const mt=q.fields.find(tt=>Fe(tt)===se);if(mt?.type==="addmore"){Wt.push({addMoreFieldName:se,array:me});continue}if(mt?.type==="multiselect"){const tt=_.multiselectArrayPropertyMap?.[se];tt&&me.length>0&&me.some(ue=>ue!=null&&typeof ue=="object")&&(ut=me.map(ue=>ue!=null&&typeof ue=="object"&&tt in ue?ue[tt]:void 0).filter(ue=>ue!=null))}}ye[se]=He(se,ut)}const lt={},vt={},rr={};for(const{addMoreFieldName:se,array:Ie}of Wt){const me=q.fields.find(bt=>Fe(bt)===se);if(!me||me.type!=="addmore")continue;const Ke=Eg(me,q.fields,q.config?.sections,Fe);if(Ke.length===0)continue;const ut=_.addMoreFieldKeyMap?.[se],mt=Ie.length>0&&Ie[0]!=null&&typeof Ie[0]=="object"?Ie[0]:null;if(mt)for(const bt of Ke){const Re=Fe(bt),Ft=ut&&ut[Re]||Re,fr=mt[Ft];fr!=null&&(ye[Re]=He(Re,fr))}const tt=Ie.slice(1),ue=tt.map((bt,Re)=>`prepop_${se}_${Re}_${Date.now()}`);ue.length>0&&(vt[se]=ue);for(let bt=0;bt<tt.length;bt++){const Re=tt[bt];if(Re==null||typeof Re!="object")continue;const Ft=Re,fr=Ft.id;fr!=null&&String(fr).trim()!==""&&(rr[`${se}__${ue[bt]}`]=String(fr));for(const eo of Ke){const ma=Fe(eo),hP=ut&&ut[ma]||ma,Kc=Ft[hP];if(Kc==null)continue;const gP=`${ma}__addmore__${se}__${ue[bt]}`;lt[gP]=He(ma,Kc)}}}Object.keys(vt).length>0&&K(se=>({...se,...vt})),Object.keys(rr).length>0&&G(se=>({...se,...rr}));const jr=se=>(se||"").toLowerCase().replace(/\s+/g,"_").trim(),Kr=[...new Set(dt.map(se=>se.tableName))];for(const se of Kr){if(Array.isArray(ye[se]))continue;const Ie=dt.find(ue=>ue.tableName===se);if(!Ie?.path?.includes("."))continue;const me=Ie.path.replace(/\.[^.]+$/,""),Ke=Qe(Ve,me);if(!Array.isArray(Ke)||Ke.length===0||typeof Ke[0]!="object"||Ke[0]===null)continue;const mt=q.fields.find(ue=>(ue.name||ue.key)===se)?.properties?.columns||[],tt=Ke.map(Ig);ye[se]=tt.map(ue=>{const bt={};for(const Re of mt){const Ft=Re.name??"",fr=jr(Ft),eo=ue[fr]??ue[Ft];bt[Ft]=eo}return bt})}const zr=(se,Ie)=>{const me=Qe(Ve,se);if(Array.isArray(me))return me;if(me!=null)return[me];if(!se.includes("."))return[];const Ke=se.replace(/\.[^.]+$/,""),ut=Qe(Ve,Ke);return!Array.isArray(ut)||ut.length===0||typeof ut[0]!="object"||ut[0]===null?[]:ut.map(mt=>{const tt=mt[Ie];if(tt!==null&&typeof tt=="object"&&!Array.isArray(tt)&&!(tt instanceof Date)){const ue=tt;return typeof ue.name=="string"&&typeof ue.code=="string"?`${ue.code} ${ue.name}`.trim():typeof ue.name=="string"?ue.name:typeof ue.code=="string"?ue.code:typeof ue.short_code=="string"?ue.short_code:ue.name??ue.code??""}return tt})};for(const{tableName:se,columnName:Ie,path:me}of dt){const Ke=zr(me,Ie),mt=q.fields.find(Re=>(Re.name||Re.key)===se)?.properties?.columns||[],tt=mt.find(Re=>(Re.name||"").toLowerCase()===Ie.toLowerCase())?.name??Ie;let ue=Array.isArray(ye[se])?ye[se]:[];const bt=Math.max(ue.length,Ke.length);if(bt>ue.length)for(ue=[...ue];ue.length<bt;){const Re={};mt.forEach(Ft=>{Re[Ft.name||""]=""}),ue.push(Re)}else ue=ue.map(Re=>({...Re}));Ke.forEach((Re,Ft)=>{ue[Ft]&&(ue[Ft][tt]=Re)}),ye[se]=ue}if(ct.current===Z){if(Object.keys(ye).length>0||Object.keys(lt).length>0){const Ft={...Nt.getState().values,...ye,...lt};re(Ft)}const Ie=Qe(Ve,"data.user_id"),me=Qe(Ve,"data.items"),Ke=Qe(Ve,"data");let ut=Array.isArray(me)&&me.length>0&&me[0]!=null&&typeof me[0]=="object"&&me[0].id?me[0].id:void 0;ut===void 0&&Array.isArray(Ke)&&Ke.length>0&&Ke[0]!=null&&typeof Ke[0]=="object"&&Ke[0].id&&(ut=Ke[0].id),ut===void 0&&(ut=Qe(Ve,"data.0.id"));const mt=rT(Ve,{treatFirstItemIdAsPaymentId:_?.treatFirstItemIdAsPaymentId===!0}),tt=Qe(Ve,"data.id"),ue=Qe(Ve,"data.batch_id"),bt=Qe(Ve,"data.program_id"),Re={};Ie!=null&&(Re.context_user_id=Ie),ut!=null&&ut!==""&&(Re.documentId=ut),tt!=null&&String(tt).trim()!==""&&(p?.id===void 0||p?.id===null)&&(Re.id=tt),ue!=null&&String(ue).trim()!==""&&((p?.admission_batch_id===void 0||p?.admission_batch_id===null)&&(Re.admission_batch_id=ue),(p?.batch_id===void 0||p?.batch_id===null)&&(Re.batch_id=ue)),bt!=null&&String(bt).trim()!==""&&(p?.program_id===void 0||p?.program_id===null)&&(Re.program_id=bt),mt!=null&&String(mt).trim()!==""&&(p?.payment_id===void 0||p?.payment_id===null)&&(Re.payment_id=mt),Object.keys(Re).length>0&&U(Ft=>{const fr={...Ft,...Re};return h?.(fr),fr}),Pe(Ve)}}catch(le){Q||Zl(le,"Prepopulate request failed.",ls)}finally{D(!1)}})(),()=>{Q=!0}},[q.id,q.config?.prepopulateApi?.enabled,q.config?.prepopulateApi?.apiEndpoint,q.config?.prepopulateApi?.apiMethod,JSON.stringify(q.config?.prepopulateApi?.fieldMapping),q.config?.prepopulateApi?.treatFirstItemIdAsPaymentId,p,g,oe,re,K]),S.useEffect(()=>{Object.keys(te).length>0&&s?.(te)},[te,s]);const Er=Xe>1,er=a==="view",sr=S.useCallback((_,H)=>er||!!H&&!It(_)||Jn(_)&&!It(_),[er,It,Jn]),fn=q.fields.filter(_=>!_.parentId),kt=[...Er?ft:fn.length>0?fn:q.fields].filter(_=>!(!_||typeof _!="object"||!_.name&&!_.key)).sort((_,H)=>{const z=typeof _.position?.order=="number"?_.position.order:typeof _.positionOrder=="number"?_.positionOrder:Number.MAX_SAFE_INTEGER,Z=typeof H.position?.order=="number"?H.position.order:typeof H.positionOrder=="number"?H.positionOrder:Number.MAX_SAFE_INTEGER;if(z!==Z)return z-Z;const Q=typeof _.position?.column=="number"?_.position.column:1,le=typeof H.position?.column=="number"?H.position.column:1;return Q-le}),Ss=S.useCallback(_=>{const H=Nt.getState().errors,z=Object.keys(H).find(Z=>_.includes(Z));z&&requestAnimationFrame(()=>{document.querySelector(`[data-field-name="${z}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})})},[]),Nr=async _=>{if(_?.preventDefault(),Er&&!St){if(!await Ut())try{const Z=Nt.getState().errors;$t.toast.error(ec(Z,q.fields)||"Please fix the errors before continuing."),Ss(kt.map(Q=>Q.name||Q.key||Q.id).filter(Boolean))}catch{$t.toast.error("Please fix the errors before continuing.")}return}const H=await yt(_);if(H&&H.success===!1&&H.errors?.length)try{const z=Nt.getState().errors;$t.toast.error(ec(z,q.fields)||"Submission failed. Please check the form."),Ss(kt.map(Z=>Z.name||Z.key||Z.id).filter(Boolean))}catch{$t.toast.error("Submission failed. Please check the form.")}return H},Dr=S.useCallback(()=>{At(),i&&i()},[At,i]),_r=S.useCallback((_,H)=>{const z=q.fields.find(Q=>Q.type==="button"&&(Q.name===_||Q.key===_)),Z=iT(H,z);Z!=null&&String(Z).trim()!==""&&(p?.payment_id===void 0||p?.payment_id===null)&&U(Q=>{const le={...Q,payment_id:Z};return h?.(le),le}),ie(Q=>{const le={...Q,[_]:H};return!Uo(H)||!(z?.type==="button"&&z.properties?.action==="submit")||q.fields.filter(De=>De.type==="editButton").map(De=>De.name).forEach(De=>delete le[De]),le})},[q.fields,p,h]),br=S.useCallback(async()=>await pt(),[pt]),qt=S.useCallback(()=>Nt.getState().errors,[]),tr=S.useMemo(()=>({...g||{},...L}),[g,L]),Br=S.useMemo(()=>({...typeof p=="object"&&p!==null?p:{},...tr}),[p,tr]),Qi=q.config?.layout??q.layout??"default",Zi=["default","card","compact"].includes(Qi)?Qi:"default",ea={default:"",card:"bg-card border rounded-lg shadow-sm p-6",compact:"space-y-2"},xs=S.useMemo(()=>{if(k)return;const _=q.config?.theme?.cssVariables;if(!(!_&&!E))return{..._??{},...E??{}}},[k,q.config?.theme?.cssVariables,E]),kr=S.useMemo(()=>_s({config:q.config,layout:q.layout},l),[q.config,q.layout,l]),Ee=S.useMemo(()=>kr?{...kr,verticalSpacing:kr.verticalSpacing??kr.spacing??"16px",horizontalSpacing:kr.horizontalSpacing??kr.spacing??"16px",rowHeight:kr.rowHeight??In}:null,[kr]),F=Ee!==null;Ee?.rows;const Y=Ee?.columns??3,he=Ee?.verticalSpacing??Ee?.spacing??"16px",st=Ee?.horizontalSpacing??Ee?.spacing??"16px",Tt=Ee?.rowHeight??In,wt=S.useCallback(_=>{if(!C)return!0;const H=_.visibility;if(!H)return!0;const z=H.visibleToUserType??H.user_type,Z=H.visibleToUserRole??H.user_role,Q=Array.isArray(H.visibleToUserIds)?H.visibleToUserIds:Array.isArray(H.users)?H.users:[],le=Array.isArray(H.hiddenFromUserIds)?H.hiddenFromUserIds:[];if(Array.isArray(le)&&le.length>0&&C.userId!=null&&le.includes(C.userId))return!1;if(Q.length>0&&C.userId!=null&&Q.includes(C.userId))return!0;const Ce=z!=null&&z!==""&&C.userType!=null&&C.userType!==z,Ne=Z!=null&&Z!==""&&C.role!=null&&C.role!==Z,De=Q.length>0&&(C.userId==null||!Q.includes(C.userId));return!(Ce||Ne||De)},[C]),Mt=S.useMemo(()=>NN(q.fields),[q.fields]),$r=S.useMemo(()=>kN(q.fields),[q.fields]),[ir,Oo]=S.useState($r);S.useEffect(()=>{Oo($r)},[q.id,$r]);const Lt=S.useCallback((_,H)=>{Oo(z=>z[_]===H?z:{...z,[_]:H})},[]),ta=S.useMemo(()=>({visibility:ir,setSectionVisible:Lt,fieldToHeading:Mt,allFields:q.fields}),[ir,Lt,Mt,q.fields]),et=S.useCallback(_=>_.name||_.key||_.id,[]),Tr=_=>{if(!wt(_))return!1;const H=_.name||_.key||_.id;if(!wh(H,_.type,ir,Mt))return!1;const z=_.hidden===!0;return Ar(H)||!z&&H},yy=S.useCallback(_=>{const H=q.fields.find(Z=>et(Z)===_);if(H)return H.type;const z=vh(_);return q.fields.find(Z=>et(Z)===z)?.type},[q.fields,et]),ra=S.useCallback(_=>wh(_,yy(_),ir,Mt),[ir,Mt,yy]),pn=S.useCallback(_=>ra(_)?Po(_):!1,[ra,Po]);S.useEffect(()=>{const{visibleFields:_,requiredFields:H,errors:z}=Nt.getState(),Z=new Set(_),Q=new Set(H),le=[];for(const Ce of q.fields){const Ne=et(Ce);Ne&&(ra(Ne)||(Z.delete(Ne),Q.delete(Ne),z[Ne]&&le.push(Ne)))}xe(Array.from(Z)),ae(Array.from(Q));for(const Ce of le)ve(Ce,void 0)},[ir,Mt,q.fields,q.id,et,ra,xe,ae,ve,ot,Se]);const Dt=q.config?.sections,Qn=S.useCallback(_=>{let H=_;if(_.type==="table"){const Z=_.properties?.columns;if(Array.isArray(Z)&&Z.length>0){const Q=Z.filter(le=>wt(le));H={..._,properties:{..._.properties,columns:Q}}}}const z=uT(H,Dt,et);return z?{...H,label:Cg(z,0)}:H},[wt,Dt,et]),mn=S.useCallback(_=>Eg(_,q.fields,Dt,et),[q.fields,Dt,et]),Gr=S.useCallback((_,H,z)=>`${_}__addmore__${H}__${z}`,[]),na=S.useCallback((_,H)=>`${_}__${H??"base"}`,[]),oa=S.useCallback((_,H)=>{const z=na(_.id,H);return J[z]??_.defaultCollapsed??!1},[J,na]),Wc=S.useCallback((_,H,z)=>{const Z=na(_,H);ce(Q=>Q[Z]===z?Q:{...Q,[Z]:z})},[na]),sa=S.useMemo(()=>{const _=[],H=q.fields.filter(z=>z.type==="addmore");for(const z of H){const Z=et(z),le=mn(z).find(at=>{if(at.type!=="button")return!1;const Ht=at.properties,Le=at.metadata;let Ve=Ht?.action;if(!Ve&&Le!=null)try{Ve=(typeof Le=="string"?JSON.parse(Le):Le)?.action}catch{}return Ve==="upload"||Ve==="custom"});if(!le)continue;const Ce=et(le),Ne=V[Z]||[],De=Qe($[Ce],"data.id")??Qe($[Ce],"data.documentId")??L.documentId;De!=null&&String(De).trim()!==""&&_.push(String(De));for(const at of Ne){const Ht=Gr(Ce,Z,at),Le=Qe($[Ht],"data.id")??Qe($[Ht],"data.documentId"),Ve=ne[`${Z}__${at}`],we=Le??Ve;we!=null&&String(we).trim()!==""&&_.push(String(we))}}return _},[q.fields,V,$,ne,L.documentId,et,mn,Gr]);S.useEffect(()=>{U(_=>{const H={..._,document_ids:sa},z=_.document_ids;return Array.isArray(z)&&z.length===sa.length&&sa.every((Z,Q)=>z[Q]===Z)?_:H})},[sa]);const ia=S.useCallback((_,H,z,Z)=>{for(const Q of z){const le=et(Q),Ce=Gr(le,_,H),Ne=Z[Ce];if(Ne==null)continue;const De=Q.type;if(De==="file"||De==="camera"||De==="photoChoice"){if(typeof Ne=="object"&&Ne!==null&&("url"in Ne||"name"in Ne)||Array.isArray(Ne)&&Ne.length>0)return!0;continue}if(Array.isArray(Ne)){if(Ne.length>0)return!0;continue}if(typeof Ne=="string"&&Ne.trim()!==""||typeof Ne=="number"&&!Number.isNaN(Ne)||typeof Ne=="boolean"||typeof Ne=="object"&&Ne!==null&&Object.keys(Ne).length>0)return!0}return!1},[et,Gr]),Zn=S.useCallback(_=>{const H=et(_);if(!H)return;if(mn(_).length===0){$t.toast.error("No linked fields configured for this Add More button.");return}const Z=`${Date.now()}_${Math.random().toString(36).slice(2,8)}`;K(Q=>({...Q,[H]:[...Q[H]||[],Z]}))},[et,mn]),aa=S.useCallback((_,H)=>{K(z=>{const Z=z[_]||[],Q=Z.filter(le=>le!==H);if(Q.length===Z.length)return z;if(Q.length===0){const le={...z};return delete le[_],le}return{...z,[_]:Q}})},[]),la=S.useMemo(()=>kt.filter(_=>!_.parentId),[kt]),On=S.useMemo(()=>{const _=[];return kt.filter(z=>z.type==="addmore").sort((z,Z)=>{const Q=z.position?.order??0,le=Z.position?.order??0;return Q-le}).forEach(z=>{const Z=et(z),Q=z.position?.order??0,le=V[Z]||[],Ce=mn(z).sort((Ae,He)=>{const rt=Ae.position?.order??0,fe=He.position?.order??0;return rt!==fe?rt-fe:(Ae.position?.column??1)-(He.position?.column??1)});if(Ce.length===0)return;const Ne=Ag(z,Dt),De=Ne[0]?.fieldNames?.length?Ne[0].fieldNames:Ce.map(Ae=>et(Ae)).filter(Boolean),at=mT(De,la,Y,et),Ht=Math.min(...Ce.map(Ae=>Ae.position?.order??0)),Le=Math.max(1,...Ce.map(Ae=>(Ae.position?.order??Ht)-Ht+Do(Ae))),Ve=at?.blockHeight??Le,we=le.length*Ve;_.push({addMoreFieldName:Z,baseOrder:Q,blockHeight:Ve,blockIds:le,linkedFields:Ce,insertedRows:we,templateFieldNames:De,templateBounds:at})}),_},[kt,la,Y,et,V,mn,Dt]),As=S.useMemo(()=>({}),[]),ca=S.useMemo(()=>On.length===0?kt:kt.map(_=>{const H=_.position?.order??0,z=On.reduce((Z,Q)=>{const le=Q.templateBounds?.maxRow??Q.baseOrder;return H>le?Z+Q.insertedRows:Z},0);return z===0?_:{..._,position:{..._.position,order:H+z}}}),[kt,On]),da=S.useCallback(_=>{const H={};return Object.entries($).forEach(([z,Z])=>{const Q=_[z];Q&&(H[Q]=Z)}),H},[$]),Io=S.useMemo(()=>{const _=[],H={};return On.forEach(z=>{const{addMoreFieldName:Z,blockIds:Q,linkedFields:le,blockHeight:Ce,templateBounds:Ne}=z,De=Math.min(...le.map(Le=>Le.position?.order??0)),Ht=q.fields.find(Le=>et(Le)===Z&&Le.type==="addmore")?.properties;Q.forEach((Le,Ve)=>{const we={},Ae={},He={},rt=Ne?hT(Ne,Ve):z.baseOrder+1+Ve*Ce,fe=ne[`${Z}__${Le}`];le.forEach(ye=>{const dt=et(ye),Wt=Gr(dt,Z,Le),Bt=(ye.position?.order??De)-De;if(we[Wt]=dt,Ae[Wt]=Oe[Wt],!(Ht?.linkedFieldAllowDuplicate?.[dt]??!0)&&(ye.type==="select"||ye.type==="radio"||ye.type==="multiselect")){const vt=[],rr=Oe[dt];rr!=null&&rr!==""&&(Array.isArray(rr)?vt.push(...rr.map(Kr=>String(Kr))):vt.push(String(rr))),Q.filter(Kr=>Kr!==Le).forEach(Kr=>{const zr=Gr(dt,Z,Kr),qr=Oe[zr];qr!=null&&qr!==""&&(Array.isArray(qr)?vt.push(...qr.map(se=>String(se))):vt.push(String(qr)))}),vt.length>0&&(He[Wt]=[...new Set(vt)])}_.push({...ye,id:`${ye.id}__${Le}`,name:Wt,position:{...ye.position,order:rt+Bt}})});const Fe=da(we);Object.keys(we).forEach(ye=>{H[ye]={scopedFormValues:Ae,scopedFieldNameMap:we,scopedButtonResponses:Fe,...fe!=null&&{blockDocumentId:fe},...He[ye]&&{excludedOptionValues:He[ye]}}})})}),{clonedFields:_,scopeByFieldName:H}},[On,ne,et,Gr,Oe,da,q.fields]),Cs=S.useMemo(()=>[...ca,...Io.clonedFields].sort((_,H)=>{const z=_.position?.order??0,Z=H.position?.order??0;if(z!==Z)return z-Z;const Q=_.position?.column??1,le=H.position?.column??1;if(Q!==le)return Q-le;const Ce=ko(_.position)??0,Ne=ko(H.position)??0;return Ce!==Ne?Ce-Ne:String(_.id).localeCompare(String(H.id))}),[ca,Io.clonedFields]),Mo=S.useMemo(()=>Vk(Cs.filter(_=>!_.parentId),Tr),[Cs,Tr]),Rc=S.useCallback((_,H)=>Mo.some(z=>Hk(_,H,z,Y)),[Mo,Y]);Mo.length===0||Math.max(...Mo.map(_=>(_[0]?.position?.order??0)+gs(_,Y).rowSpan));const ua=S.useMemo(()=>fT(Dt,Oc(kt.filter(_=>!_.parentId)),et),[Dt,kt,et]),{anchorsByOrigin:by,coveredCells:vy}=S.useMemo(()=>gT(ua,ca,et,Y),[ua,ca,et,Y]),{anchorsByOrigin:wy,coveredCells:Sy}=S.useMemo(()=>yT(On.map(_=>({addMoreFieldName:_.addMoreFieldName,blockIds:_.blockIds,linkedFields:_.linkedFields,templateFieldNames:_.templateFieldNames})),Dt,Io.clonedFields,la,Y,et,vy),[On,Dt,Io.clonedFields,la,Y,et,vy]),hn=S.useMemo(()=>AT(by,wy),[by,wy]),xy=S.useMemo(()=>Sy,[Sy]),Ay=String(Tt).endsWith("px")?Tt:In,Cy=S.useCallback((_,H)=>{for(let z=0;z<Y;z++){if(z>=H.anchorCol&&z<H.anchorCol+H.colSpan)continue;if(As[`${_}-${z}`]||hn.get(`${_}-${z}`)||vg(_,z,Cs,Tr).length>0||Rc(_,z))return!0}return!1},[Y,As,hn,Cs,Tr,Rc]),Ey=S.useMemo(()=>ST(hn,_=>{const H=_.run.section;return H.collapsible?oa(H,_.addMoreMeta?.blockId):!1},Cy),[hn,oa,Cy]),Ny=S.useMemo(()=>{const _=[];for(const H of Object.keys(As)){const z=Number(H.split("-")[0]);Number.isNaN(z)||_.push(z)}for(const H of hn.values())if(H.renderFields.some(z=>Tr(z)))for(let z=H.anchorRow;z<H.anchorRow+H.rowSpan;z++)_.push(z);return Wk(Mo,Y,_)},[Mo,Y,As,hn,Tr]),{originalToDisplayRow:fa,displayRowCount:uP,sortedOccupiedRows:fP}=S.useMemo(()=>{const _=Rk(Ny);return{originalToDisplayRow:_.originalToDisplay,displayRowCount:_.displayRowCount,sortedOccupiedRows:_.sortedOriginalRows}},[Ny]),_y=Math.max(uP,1),Gc=S.useCallback((_,H=1)=>Gk(_,H,fa),[fa]),ky=S.useMemo(()=>{const _=new Set;for(const H of Ey){const z=fa.get(H);z!==void 0&&_.add(z)}return _},[Ey,fa]),pP=S.useMemo(()=>xT(_y,Ay,ky),[_y,Ay,ky]),mP=S.useMemo(()=>CT(kt.filter(_=>!_.parentId&&Tr(_)),ua,et),[kt,ua,et,Tr]),pa=S.useCallback(_=>{if(F)return null;const H=et(_),z=V[H]||[];if(z.length===0)return null;const Z=mn(_);if(Z.length===0)return null;const Q=dT(_,Dt),le=Z.map(De=>et(De)).filter(Boolean),Ce=_g(le,Dt),Ne=(De,at,Ht,Le,Ve,we,Ae)=>{const He=et(De),rt=Gr(He,H,at),fe=De.hidden===!0;if(!(wt(De)&&(Ar(He)||!fe&&He)))return null;const ye={...De,id:`${De.id}__${at}`,name:rt},Wt=_.properties?.linkedFieldAllowDuplicate?.[He]??!0;let Bt;if(!Wt&&(De.type==="select"||De.type==="radio"||De.type==="multiselect")){const lt=[],vt=Oe[He];vt!=null&&vt!==""&&(Array.isArray(vt)?lt.push(...vt.map(jr=>String(jr))):lt.push(String(vt))),z.filter(jr=>jr!==at).forEach(jr=>{const Kr=Gr(He,H,jr),zr=Oe[Kr];zr!=null&&zr!==""&&(Array.isArray(zr)?lt.push(...zr.map(qr=>String(qr))):lt.push(String(zr)))}),lt.length>0&&(Bt=[...new Set(lt)])}return c.jsx("div",{"data-field-name":rt,"data-form-renderer":"field-wrapper",children:c.jsx(un,{field:ye,value:Oe[rt],error:pe[rt]||je>0?te[rt]:void 0,onChange:lt=>xt(rt,lt),onBlur:()=>ze(rt),disabled:de||!Vt(He)||er||!!De.disabled,readOnly:sr(He,!!De.readOnly),isRequired:pn(He),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:rt,buttonResponses:we,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:Ae,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,scopedFormValues:Ve,scopedFieldNameMap:Le,excludedOptionValues:Bt,hideTableRowControls:x})},ye.id)};return c.jsx("div",{className:"space-y-3 mt-3",children:z.map((De,at)=>{const Ht={},Le={};Z.forEach(Bt=>{const lt=et(Bt),vt=Gr(lt,H,De);Ht[vt]=lt,Le[vt]=Oe[vt]});const Ve=da(Ht),we=ia(H,De,Z,Oe),Ae=Q?.heading!=null?bs(Q,at+1):null,He=ne[`${H}__${De}`],rt=He!=null?{...tr,documentId:He}:tr,fe=Z.map(Bt=>Ne(Bt,De,at,Ht,Le,Ve,rt)).filter(Boolean),ye=Ce?.section?.collapsible===!0,dt=c.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:we,title:we?"Cannot remove: this entry has data":"Remove entry","aria-label":"Remove entry",onClick:Bt=>{Bt.preventDefault(),Bt.stopPropagation(),aa(H,De)},children:c.jsx(Go,{className:"h-5 w-5","aria-hidden":!0})}),Wt=c.jsxs(c.Fragment,{children:[!ye&&c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[Ae?c.jsx("p",{className:"text-sm font-medium text-foreground",children:Ae}):c.jsxs("p",{className:"text-xs text-muted-foreground",children:["Entry ",at+1]}),dt]}),fe]});return c.jsx("div",{className:"rounded-md border p-3 space-y-3",children:Ce?c.jsx(kc,{legend:Ce.section.heading?.enabled?bs(Ce.section,at+1):Ce.section.name,collapsible:Ce.section.collapsible,defaultCollapsed:Ce.section.defaultCollapsed,headerActions:ye?dt:void 0,onCollapsedChange:Bt=>Wc(Ce.section.id,De,Bt),children:Wt}):Wt},`${_.id}-${De}`)})})},[F,V,ne,et,mn,Gr,ia,Oe,pe,je,te,xt,ze,Vt,er,pn,Br,$e,_r,Nr,At,Dr,We,j,m,tr,br,qt,q.fields,be,Ar,wt,da,aa,x,Dt,oe,ee,M]);return c.jsx("div",{className:k?B("relative",d):B(ga,P&&"dark",d),style:xs,"data-form-renderer":k?void 0:"root",children:c.jsxs("div",{className:"relative",children:[M&&c.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/60 rounded-md",children:c.jsx(Pn,{})}),c.jsx("form",{onSubmit:Nr,className:f?B("w-full min-w-0"):B("space-y-6 pb-[100px] w-full min-w-0",ea[Zi]),"data-form-renderer":"form","data-form-renderer-layout":F?"grid":"stack",children:c.jsxs(AN,{value:ta,children:[Er&&q.steps&&c.jsx(Ok,{steps:q.steps,currentStep:Te,completedSteps:Ue,onStepClick:ur}),c.jsx(_a.Provider,{value:{gridStretch:F},children:F?c.jsx("div",{className:f?"w-full min-w-0":"grid w-full min-w-0",style:{display:"grid",gridTemplateRows:pP,gridTemplateColumns:`repeat(${Y}, 1fr)`,rowGap:he,columnGap:st},"data-form-renderer":"grid",children:fP.map(_=>Array.from({length:Y},(H,z)=>{const Z=Gc(_);if(!Z)return null;if(Rc(_,z))return c.jsx("div",{className:"min-w-0 min-h-0",style:{gridRow:Z,gridColumn:z+1,visibility:"hidden",pointerEvents:"none"},"data-form-renderer":"grid-cell","data-form-renderer-empty":!0},`empty-${_}-${z}`);if(bT(_,z,xy,hn)){const we=vT(_,z,hn);return we&&wT(_,z,we,oa(we.run.section,we.addMoreMeta?.blockId))?null:c.jsx("div",{className:"min-w-0 min-h-0",style:{gridRow:Z,gridColumn:z+1,visibility:"hidden",pointerEvents:"none"},"data-form-renderer":"grid-cell","data-form-renderer-empty":!0},`section-border-cover-${_}-${z}`)}const Q=hn.get(`${_}-${z}`);if(Q){const we=Q.renderFields.filter(lt=>Tr(lt));if(we.length===0)return null;const Ae=Q.addMoreMeta,He=Ae!=null?On.find(lt=>lt.addMoreFieldName===Ae.addMoreFieldName)?.linkedFields??[]:[],rt=Ae!=null?ia(Ae.addMoreFieldName,Ae.blockId,He,Oe):!1,fe=Q.run.section,Fe=Ae?.blockId,ye=oa(fe,Fe),dt=fe.collapsible&&ye?1:Q.rowSpan,Wt=Gc(Q.anchorRow,dt)??Z,Bt=Ae!=null?c.jsx("button",{type:"button",className:B("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:rt,title:rt?"Cannot remove: this entry has data":"Remove entry","aria-label":"Remove entry",onClick:lt=>{lt.preventDefault(),lt.stopPropagation(),aa(Ae.addMoreFieldName,Ae.blockId)},children:c.jsx(Go,{className:"h-5 w-5","aria-hidden":!0})}):void 0;return c.jsx("div",{className:B("min-h-0 min-w-0",!(fe.collapsible&&ye)&&"self-stretch"),style:{gridRow:Wt,gridColumn:`${z+1} / span ${Q.colSpan}`},"data-form-renderer":"grid-cell","data-form-renderer-config-section-border-cell":!0,children:c.jsx(kc,{legend:Q.legend,className:fe.collapsible&&ye?void 0:"h-full",collapsible:fe.collapsible,defaultCollapsed:fe.defaultCollapsed,headerActions:Bt,onCollapsedChange:lt=>Wc(fe.id,Fe,lt),children:c.jsx("div",{className:"grid w-full min-w-0",style:{gridTemplateColumns:`repeat(${Y}, 1fr)`,gridTemplateRows:`repeat(${Q.rowSpan}, minmax(${String(Tt).endsWith("px")?Tt:In}, auto))`,rowGap:he,columnGap:st},children:we.map(lt=>{const vt=et(lt),rr=Io.scopeByFieldName[vt],jr=rr?.scopedFieldNameMap?.[vt]||vt,Kr=(lt.position?.order??Q.anchorRow)-Q.anchorRow,zr=lt.position?.column??1,{rowSpan:qr,columnSpan:se}=gs([lt],Y),Ie=Ae!=null?ne[`${Ae.addMoreFieldName}__${Ae.blockId}`]:void 0,me=Ie!=null?{...tr,documentId:Ie}:tr;return c.jsx("div",{"data-field-name":vt,"data-form-renderer":"field-wrapper",className:"min-h-0 min-w-0",style:{gridRow:`${Kr+1} / span ${qr}`,gridColumn:`${zr} / span ${se}`,...xn(lt)},children:c.jsx(un,{field:Qn(lt),value:Oe[vt],error:pe[vt]||je>0?te[vt]:void 0,onChange:Ke=>xt(vt,Ke),onBlur:()=>ze(vt),disabled:(lt.type==="table"||lt.type==="billingGrid")&&a==="fill"?!1:de||!Vt(jr)||er||!!lt.disabled,readOnly:(lt.type==="table"||lt.type==="billingGrid")&&a==="fill"?!1:sr(jr,!!lt.readOnly),isRequired:pn(jr),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:vt,buttonResponses:rr?.scopedButtonResponses??$,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:me,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,onAddMore:Zn,scopedFormValues:rr?.scopedFormValues,scopedFieldNameMap:rr?.scopedFieldNameMap,excludedOptionValues:rr?.excludedOptionValues,hideTableRowControls:x})},lt.id)})})})},`section-border-${Q.run.section.id}-${_}-${z}-${Ae?.blockId??"base"}`)}const le=vg(_,z,Cs,Tr).filter(we=>!(et(we)?.includes("__addmore__")&&xy.has(`${_}-${z}`)));if(le.length===0){const we=As[`${_}-${z}`];if(we){const Ae=q.fields.find(fe=>fe.type==="addmore"&&et(fe)===we.addMoreFieldName),He=Ae!=null?mn(Ae):[],rt=ia(we.addMoreFieldName,we.blockId,He,Oe);return c.jsx("div",{className:"min-h-0 min-w-0 flex flex-col items-center justify-center",style:{gridRow:Z,gridColumn:z+1},"data-form-renderer":"grid-cell","data-form-renderer-add-more-remove":!0,children:c.jsx("button",{type:"button",className:B("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:rt,title:rt?"Cannot remove: this entry has data":"Remove entry","aria-label":"Remove entry",onClick:fe=>{fe.preventDefault(),fe.stopPropagation(),aa(we.addMoreFieldName,we.blockId)},children:c.jsx(Go,{className:"h-5 w-5","aria-hidden":!0})})},`add-more-remove-${_}-${z}`)}return c.jsx("div",{className:"min-w-0",style:{pointerEvents:"none"},"data-form-renderer":"grid-cell","data-form-renderer-empty":!0},`empty-${_}-${z}`)}const Ce=le[0],{rowSpan:Ne,columnSpan:De}=gs(le,Y),at=Gc(_,Ne)??Z;if(le.length===1&&Ce.type==="section"){const we=q.fields.filter(Ae=>Ae.parentId===Ce.id&&Ae.position!=null).sort((Ae,He)=>{const rt=typeof Ae.position?.order=="number"?Ae.position.order:0,fe=typeof He.position?.order=="number"?He.position.order:0;return rt-fe});return c.jsx("div",{className:"min-w-0 min-h-0 w-full overflow-hidden flex flex-col h-full",style:{gridRow:at,gridColumn:`${z+1} / span ${De}`,...xn(Ce)},"data-form-renderer":"grid-cell",children:c.jsx(Hh,{field:Ce,children:we.map(Ae=>{const He=Ae.name||Ae.key||Ae.id,rt=Ae.hidden===!0;return wt(Ae)&&(Ar(He)||!rt&&He)?c.jsx("div",{"data-field-name":He,"data-form-renderer":"field-wrapper",children:c.jsx(un,{field:Qn(Ae),value:Oe[He],error:pe[He]||je>0?te[He]:void 0,onChange:Fe=>xt(He,Fe),onBlur:()=>ze(He),disabled:de||!Vt(He)||er||!!Ae.disabled,readOnly:sr(He,!!Ae.readOnly),isRequired:pn(He),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:He,buttonResponses:$,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:tr,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,onAddMore:Zn,hideTableRowControls:x})},Ae.id):null})})},Ce.id)}const Ht=yg(le),Le=le.some(we=>["file","camera","photoChoice","addmore","table","billingGrid"].includes(we.type)),Ve=c.jsx("div",{className:B("flex min-h-0 w-full flex-1 gap-3",Ht==="row"?"flex-row items-stretch":"flex-col items-stretch"),children:le.map(we=>{const Ae=we.name||we.key||we.id,He=we.type==="sectionHeading",rt=Io.scopeByFieldName[Ae],fe=rt?.scopedFieldNameMap?.[Ae]||Ae,Fe=rt?.blockDocumentId!=null?{...tr,documentId:rt.blockDocumentId}:tr,ye=we.appearance?.hideLabel??we.properties?.hideLabel??!1,dt=we.type==="table"||we.type==="billingGrid"?we.properties?.minWidth:void 0;return c.jsx("div",{"data-field-name":Ae,"data-form-renderer":"field-wrapper",className:B("flex min-h-0 min-w-0 flex-1 flex-col",jo(we),He&&"items-center justify-center",ye&&"items-center"),style:{...dt?{minWidth:dt}:{},...xn(we)},children:c.jsx(un,{field:Qn(we),value:Oe[Ae],error:pe[Ae]||je>0?te[Ae]:void 0,onChange:Wt=>xt(Ae,Wt),onBlur:()=>ze(Ae),disabled:(we.type==="table"||we.type==="billingGrid")&&a==="fill"?!1:de||!Vt(fe)||er||!!we.disabled,readOnly:(we.type==="table"||we.type==="billingGrid")&&a==="fill"?!1:sr(fe,!!we.readOnly),isRequired:pn(fe),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:Ae,buttonResponses:rt?.scopedButtonResponses??$,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:Fe,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,onAddMore:Zn,scopedFormValues:rt?.scopedFormValues,scopedFieldNameMap:rt?.scopedFieldNameMap,excludedOptionValues:rt?.excludedOptionValues,hideTableRowControls:x})},we.id)})});return c.jsx("div",{className:B(wd(le),"self-stretch",Le?"overflow-visible":"overflow-hidden"),style:{gridRow:at,gridColumn:`${z+1} / span ${De}`,...xn(le[0])},"data-form-renderer":"grid-cell","data-field-name":le.map(we=>we.name||we.key||we.id).join(","),children:Ve},le.map(we=>we.id).join("-"))}))}):c.jsx("div",{className:f?"":"space-y-4","data-form-renderer":"stack",children:kt.map(_=>{if(!Tr(_))return null;const H=mP.find(Z=>Z.kind==="border"&&Z.fields.some(Q=>Q.id===_.id));if(H)return H.fields[0]?.id!==_.id?null:c.jsx(kc,{legend:bs(H.run.section,0),collapsible:H.run.section.collapsible,defaultCollapsed:H.run.section.defaultCollapsed,onCollapsedChange:Z=>Wc(H.run.section.id,void 0,Z),children:H.fields.map(Z=>{const Q=et(Z);return!Q||!Tr(Z)?null:c.jsxs("div",{"data-field-name":Q,"data-form-renderer":"field-wrapper",style:xn(Z),children:[c.jsx(un,{field:Qn(Z),value:Oe[Q],error:pe[Q]||je>0?te[Q]:void 0,onChange:le=>xt(Q,le),onBlur:()=>ze(Q),disabled:(Z.type==="table"||Z.type==="billingGrid")&&a==="fill"?!1:de||!Vt(Q)||er||!!Z.disabled,readOnly:(Z.type==="table"||Z.type==="billingGrid")&&a==="fill"?!1:sr(Q,!!Z.readOnly),isRequired:pn(Q),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:Q,buttonResponses:$,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:tr,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,onAddMore:Zn,hideTableRowControls:x}),Z.type==="addmore"&&pa(Z)]},Z.id)})},`stack-border-${H.run.section.id}-${_.id}`);if(!_.parentId){const Z=kt.filter(le=>!le.parentId&&Tr(le)&&qi(le)===qi(_)),Q=Tc(Z).slice(0,2);if(Q.length>1&&Q[0].id!==_.id)return null;if(Q.length>1){const le=yg(Q);return c.jsx("div",{"data-form-renderer":"shared-cell-stack",className:B("flex w-full min-w-0 gap-3",le==="row"?"flex-row items-stretch":"flex-col"),children:Q.map(Ce=>{const Ne=Ce.name||Ce.key||Ce.id;return c.jsxs("div",{"data-field-name":Ne,"data-form-renderer":"field-wrapper",className:B("min-w-0 flex-1 flex flex-col",jo(Ce)),style:xn(Ce),children:[c.jsx(un,{field:Qn(Ce),value:Oe[Ne],error:pe[Ne]||je>0?te[Ne]:void 0,onChange:De=>xt(Ne,De),onBlur:()=>ze(Ne),disabled:(Ce.type==="table"||Ce.type==="billingGrid")&&a==="fill"?!1:de||!Vt(Ne)||er||!!Ce.disabled,readOnly:(Ce.type==="table"||Ce.type==="billingGrid")&&a==="fill"?!1:sr(Ne,!!Ce.readOnly),isRequired:pn(Ne),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:Ne,buttonResponses:$,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:tr,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,onAddMore:Zn,hideTableRowControls:x}),Ce.type==="addmore"&&pa(Ce)]},Ce.id)})},Q.map(Ce=>Ce.id).join("-"))}}if(_.type==="section"){const Z=q.fields.filter(Q=>Q.parentId===_.id&&Q.position!=null).sort((Q,le)=>{const Ce=typeof Q.position?.order=="number"?Q.position.order:0,Ne=typeof le.position?.order=="number"?le.position.order:0;return Ce-Ne});return c.jsx(Hh,{field:_,children:Z.map(Q=>{const le=Q.name||Q.key||Q.id,Ce=Q.hidden===!0;return wt(Q)&&(Ar(le)||!Ce&&le)?c.jsxs("div",{"data-field-name":le,"data-form-renderer":"field-wrapper",style:xn(Q),children:[c.jsx(un,{field:Qn(Q),value:Oe[le],error:pe[le]||je>0?te[le]:void 0,onChange:De=>xt(le,De),onBlur:()=>ze(le),disabled:de||!Vt(le)||er||!!Q.disabled,readOnly:sr(le,!!Q.readOnly),isRequired:pn(le),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:le,buttonResponses:$,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:tr,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,onAddMore:Zn,hideTableRowControls:x}),Q.type==="addmore"&&pa(Q)]},Q.id):null})},_.id)}const z=_.name||_.key||_.id;return c.jsxs("div",{"data-field-name":z,"data-form-renderer":"field-wrapper",style:xn(_),children:[c.jsx(un,{field:Qn(_),value:Oe[z],error:pe[z]||je>0?te[z]:void 0,onChange:Z=>xt(z,Z),onBlur:()=>ze(z),disabled:(_.type==="table"||_.type==="billingGrid")&&a==="fill"?!1:de||!Vt(z)||er||!!_.disabled,readOnly:(_.type==="table"||_.type==="billingGrid")&&a==="fill"?!1:sr(z,!!_.readOnly),isRequired:pn(z),formValues:Oe,submissionContext:Br,prepopulateMappedFieldNames:$e,urlParams:oe,prepopulateResponse:ee,prepopulateLoading:M,formSections:Dt,submitPayload:q.config?.submitPayload,fieldValueKey:z,buttonResponses:$,onButtonApiResponse:_r,onSubmit:Nr,onReset:At,onCancel:Dr,isSubmitting:We,bffSubmitApi:j,onBffSubmitResult:m,extraSubmitPayload:tr,onValidateForm:br,getValidationErrors:qt,allFields:q.fields,onSubmittingChange:be,onAddMore:Zn,hideTableRowControls:x}),_.type==="addmore"&&pa(_)]},_.id)})})}),u]})})]})})};function Lc(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function Mg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}function kT(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,g=p._id||p.id||f.targetFieldId;f.targetFieldKey=m,f.targetField=m,f.targetFieldById=g}}return f},u={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:{},g=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(g&&(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=Lc(p.appearance)),p.ui!==void 0&&(h.ui=Lc(p.ui)),p.visibility!==void 0&&(h.visibility=Lc(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 A=l.validationRules,I={...m};if(A.fileSize!==void 0&&(I.maxSize=A.fileSize),A.fileType&&Array.isArray(A.fileType)){const T=[];A.fileType.forEach(W=>{const X=W.startsWith(".")?W:`.${W}`;T.push(X),X===".csv"?T.push("text/csv"):X===".xls"?T.push("application/vnd.ms-excel"):X===".xlsx"&&T.push("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}),I.accept=T}h.metadata=I,I.maxSize!==void 0&&(h.maxSize=I.maxSize),I.accept!==void 0&&(h.accept=I.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 A=m.downloadApiEndpoint;A=A.replace(/\{ctx:([^}]+)\}/g,(I,T)=>{const W=t[T];return W!==void 0?String(W):I}),m.downloadApiEndpoint=A,h.metadata=m,h.downloadApiEndpoint=A}if((l.type==="button"||l.fieldType==="button")&&m.action==="submit"){const A=h.properties||{};m.submitAction!==void 0&&(A.submitAction=m.submitAction),m.submitApiMethod!==void 0&&(A.submitApiMethod=m.submitApiMethod),m.apiBodyStructure!==void 0&&(A.apiBodyStructure=m.apiBodyStructure),m.apiBodyFieldsOnly!==void 0&&(A.apiBodyFieldsOnly=m.apiBodyFieldsOnly),m.apiBodyFieldsOnlyFormat!==void 0&&(A.apiBodyFieldsOnlyFormat=m.apiBodyFieldsOnlyFormat),m.apiBodyFields!==void 0&&(A.apiBodyFields=m.apiBodyFields),m.buttonText!==void 0&&(A.buttonText=m.buttonText),m.action!==void 0&&(A.action=m.action),m.variant!==void 0&&(A.variant=m.variant),m.hideLabel!==void 0&&(A.hideLabel=m.hideLabel),l.apidata&&typeof l.apidata=="object"&&l.apidata.apiEndpoint&&(A.apiEndpoint=l.apidata.apiEndpoint),h.properties=A}if((l.type==="button"||l.fieldType==="button")&&(m.action==="upload"||m.action==="custom")){const A=h.properties||{};m.action!==void 0&&(A.action=m.action),m.buttonText!==void 0&&(A.buttonText=m.buttonText),m.variant!==void 0&&(A.variant=m.variant),m.hideLabel!==void 0&&(A.hideLabel=m.hideLabel),m.uploadAction!==void 0&&(A.uploadAction=m.uploadAction),m.uploadApiEndpoint!==void 0&&(A.uploadApiEndpoint=m.uploadApiEndpoint),m.uploadApiMethod!==void 0&&(A.uploadApiMethod=m.uploadApiMethod),m.apiBodyStructure!==void 0&&(A.apiBodyStructure=m.apiBodyStructure),m.apiBodyFieldsOnly!==void 0&&(A.apiBodyFieldsOnly=m.apiBodyFieldsOnly),m.apiBodyFieldsOnlyFormat!==void 0&&(A.apiBodyFieldsOnlyFormat=m.apiBodyFieldsOnlyFormat),m.apiFieldMapping!==void 0&&(A.apiFieldMapping=m.apiFieldMapping),m.apiQueryParams!==void 0&&(A.apiQueryParams=m.apiQueryParams),m.apiBodyFields!==void 0&&(A.apiBodyFields=m.apiBodyFields),m.apiHeaders!==void 0&&(A.apiHeaders=m.apiHeaders),h.properties=A}if(l.type==="status"||l.fieldType==="status"){const A=h.properties||{};if(m.source!==void 0&&(A.source=m.source),m.statuses!==void 0&&(A.statuses=m.statuses),m.dataPath!==void 0&&(A.dataPath=m.dataPath),m.showStatusText!==void 0&&(A.showStatusText=m.showStatusText),m.statusTextPath!==void 0&&(A.statusTextPath=m.statusTextPath),m.showCurrentIndicator!==void 0&&(A.showCurrentIndicator=m.showCurrentIndicator),l.apidata&&typeof l.apidata=="object"&&l.apidata.apiEndpoint){let I=l.apidata.apiEndpoint;I=I.replace(/\{ctx:([^}]+)\}/g,(T,W)=>{const X=t[W];return X!==void 0?String(X):T}),A.apiEndpoint=I,A.source===void 0&&(A.source="api")}l.apidata?.apiMethod!==void 0&&(A.apiMethod=l.apidata.apiMethod),h.properties=A}if(l.type==="addmore"||l.fieldType==="addmore"){const A=h.properties||{};m.linkedFieldNames!==void 0&&(A.linkedFieldNames=m.linkedFieldNames),m.linkedSectionIds!==void 0&&(A.linkedSectionIds=m.linkedSectionIds),m.linkedFieldAllowDuplicate!==void 0&&(A.linkedFieldAllowDuplicate=m.linkedFieldAllowDuplicate),m.buttonText!==void 0&&(A.buttonText=m.buttonText),m.variant!==void 0&&(A.variant=m.variant),m.size!==void 0&&(A.size=m.size),m.hideLabel!==void 0&&(A.hideLabel=m.hideLabel),h.properties=A}if(l.type==="selectablelist"||l.fieldType==="selectablelist"){const A=h.properties||{};m.submitFieldMapping!==void 0&&(A.submitFieldMapping=m.submitFieldMapping),m.displayFields!==void 0&&(A.displayFields=m.displayFields),m.displayFieldsSeparator!==void 0&&(A.displayFieldsSeparator=m.displayFieldsSeparator),m.dataSourceContextKey!==void 0&&(A.dataSourceContextKey=m.dataSourceContextKey),m.showSelectAll!==void 0&&(A.showSelectAll=m.showSelectAll),m.selectAllByDefault!==void 0&&(A.selectAllByDefault=m.selectAllByDefault),h.properties=A}}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);const y=l,w=Mg(y.position),v=l.metadata&&typeof l.metadata=="object"&&!Array.isArray(l.metadata)?l.metadata:{},x=Mg(y.layout),P={order:typeof y.positionOrder=="number"?y.positionOrder:l.order??f,column:typeof w.column=="number"?w.column:typeof y.positionColumn=="number"?y.positionColumn:1,columnSpan:typeof w.columnSpan=="number"?w.columnSpan:typeof w.width=="number"?w.width:typeof y.positionWidth=="number"?y.positionWidth:1,rowSpan:typeof w.rowSpan=="number"?w.rowSpan:typeof y.positionRowSpan=="number"?y.positionRowSpan:1},k=ko(w,{cellSlotIndex:y.cellSlotIndex??x.cellSlotIndex,stackSlot:v.stackSlot??x.stackSlot});typeof k=="number"&&(P.cellSlot=k);const N=w.cellGroupId??x.cellGroupId;typeof N=="string"&&(P.cellGroupId=N);const C=hs(w)??hs(x)??(v.stackDirection==="horizontal"||x.stackDirection==="horizontal"?"row":v.stackDirection==="vertical"||x.stackDirection==="vertical"?"stack":void 0);return(C==="row"||C==="stack")&&(P.sharedCellLayout=C),h.position=P,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 Yi(u)}var Xi="Tabs",[TT]=vr(Xi,[Li]),Lg=Li(),[FT,Dc]=TT(Xi),Dg=b.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,onValueChange:o,defaultValue:s,orientation:i="horizontal",dir:a,activationMode:d="automatic",...u}=e,l=ro(a),[f,p]=Zr({prop:n,onChange:o,defaultProp:s??"",caller:Xi});return c.jsx(FT,{scope:r,baseId:on(),value:f,onValueChange:p,orientation:i,dir:l,activationMode:d,children:c.jsx(Be.div,{dir:l,"data-orientation":i,...u,ref:t})})});Dg.displayName=Xi;var Bg="TabsList",$g=b.forwardRef((e,t)=>{const{__scopeTabs:r,loop:n=!0,...o}=e,s=Dc(Bg,r),i=Lg(r);return c.jsx(Om,{asChild:!0,...i,orientation:s.orientation,dir:s.dir,loop:n,children:c.jsx(Be.div,{role:"tablist","aria-orientation":s.orientation,...o,ref:t})})});$g.displayName=Bg;var jg="TabsTrigger",zg=b.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,disabled:o=!1,...s}=e,i=Dc(jg,r),a=Lg(r),d=Hg(i.baseId,n),u=Wg(i.baseId,n),l=n===i.value;return c.jsx(Im,{asChild:!0,...a,focusable:!o,active:l,children:c.jsx(Be.button,{type:"button",role:"tab","aria-selected":l,"aria-controls":u,"data-state":l?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:d,...s,ref:t,onMouseDown:Me(e.onMouseDown,f=>{!o&&f.button===0&&f.ctrlKey===!1?i.onValueChange(n):f.preventDefault()}),onKeyDown:Me(e.onKeyDown,f=>{[" ","Enter"].includes(f.key)&&i.onValueChange(n)}),onFocus:Me(e.onFocus,()=>{const f=i.activationMode!=="manual";!l&&!o&&f&&i.onValueChange(n)})})})});zg.displayName=jg;var Ug="TabsContent",Vg=b.forwardRef((e,t)=>{const{__scopeTabs:r,value:n,forceMount:o,children:s,...i}=e,a=Dc(Ug,r),d=Hg(a.baseId,n),u=Wg(a.baseId,n),l=n===a.value,f=b.useRef(l);return b.useEffect(()=>{const p=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(p)},[]),c.jsx(xr,{present:o||l,children:({present:p})=>c.jsx(Be.div,{"data-state":l?"active":"inactive","data-orientation":a.orientation,role:"tabpanel","aria-labelledby":d,hidden:!p,id:u,tabIndex:0,...i,ref:t,style:{...e.style,animationDuration:f.current?"0s":void 0},children:p&&s})})});Vg.displayName=Ug;function Hg(e,t){return`${e}-trigger-${t}`}function Wg(e,t){return`${e}-content-${t}`}var PT=Dg,OT=$g,IT=zg,MT=Vg;function Rg({className:e,...t}){return c.jsx(PT,{"data-slot":"tabs",className:B("flex flex-col gap-2",e),...t})}function Gg({className:e,...t}){return c.jsx(OT,{"data-slot":"tabs-list",className:B("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",e),...t})}function Kg({className:e,...t}){return c.jsx(IT,{"data-slot":"tabs-trigger",className:B("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 qg({className:e,...t}){return c.jsx(MT,{"data-slot":"tabs-content",className:B("flex-1 outline-none",e),...t})}function dr({className:e="",...t}){return c.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 LT({className:e=""}){return c.jsxs("div",{className:`flex flex-col gap-4 ${e}`.trim(),"data-form-renderer":"workflow-steps-view-skeleton",children:[c.jsxs("div",{className:"flex w-full border-b border-neutral-200 dark:border-neutral-700 gap-0",children:[c.jsx(dr,{className:"h-10 w-24 rounded-none"}),c.jsx(dr,{className:"h-10 w-28 rounded-none ml-1"}),c.jsx(dr,{className:"h-10 w-20 rounded-none ml-1"})]}),c.jsxs("div",{className:"mt-4 flex flex-col gap-4 py-4",children:[c.jsx(dr,{className:"h-4 w-32"}),c.jsx(dr,{className:"h-10 w-full"}),c.jsx(dr,{className:"h-4 w-40"}),c.jsx(dr,{className:"h-10 w-full"}),c.jsx(dr,{className:"h-4 w-36"}),c.jsx(dr,{className:"h-24 w-full"})]})]})}function DT(){return c.jsxs("div",{className:"flex flex-col gap-4 py-4","data-form-renderer":"form-loading-skeleton",children:[c.jsx(dr,{className:"h-4 w-28"}),c.jsx(dr,{className:"h-10 w-full"}),c.jsx(dr,{className:"h-4 w-36"}),c.jsx(dr,{className:"h-10 w-full"}),c.jsx(dr,{className:"h-4 w-24"}),c.jsx(dr,{className:"h-20 w-full"})]})}const BT=3e4,$T=10*6e4,jT=9e4,zT=15*6e4;function UT(e){return e!=null&&"on_success"in e&&e.on_success!=null}function VT(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 Yg=({getWorkflowState:e,moduleId:t,tenantId:r,submissionContext:n,initialValues:o={},getAuthHeaders:s,onSuccess:i,bootstrapFeatureId:a,subjectUserId:d,viewStepId:u,clientId:l,className:f,onWorkflowSubmitResult:p,viewerContext:m,getViewerContext:g,dark:h=!1,themeVars:y})=>{const w=gn.useQueryClient(),v=S.useMemo(()=>[d??"",u??"",l??""],[d,u,l]),x=S.useMemo(()=>({moduleId:t,tenantId:r,subjectUserId:d,viewStepId:u,clientId:l}),[t,r,d,u,l]),[E,P]=S.useState([]),[k,N]=S.useState(null),[C,A]=S.useState(null),[I,T]=S.useState(null),[W,X]=S.useState({}),O=S.useRef(null),j=S.useRef(null),M=S.useRef(null),D=S.useRef(null),L=S.useMemo(()=>E&&Array.isArray(E)?E.filter(ae=>ae.feature_id):[],[E]),U=gn.useQuery({queryKey:["workflow-steps",t,a??"",r??"",v[0],v[1],v[2]],queryFn:()=>e({...x,featureId:a}),staleTime:BT,gcTime:$T}),$=U.isPending,ie=U.error?U.error instanceof Error?U.error.message:"Failed to load workflow steps":null;S.useEffect(()=>{const ae=U.data;if(!ae||E.length>0)return;const ve=ae.steps&&Array.isArray(ae.steps)?ae.steps:[];P(ve);const Ye=ve.filter(ct=>ct.feature_id);if(Ye.length>0){const ct=ae.current_step_id,Ge=ct&&Ye.some(Kt=>Kt.step_id===ct);N(Ge?ct:Ye[0].step_id)}},[U.data,E.length,a]);const V=S.useMemo(()=>{if(!k)return;const ae=E.find(Ye=>Ye.step_id===k),ve=O.current===k;return ae?.feature_id??(ve?D.current:void 0)??void 0},[k,E]),K=gn.useQuery({queryKey:["workflow-step",t,V??"",r??"",v[0],v[1],v[2]],queryFn:()=>e({...x,featureId:V}),enabled:!!V,staleTime:jT,gcTime:zT,refetchOnWindowFocus:!0,refetchOnReconnect:!0}),J=K.isPending,ce=K.error?K.error instanceof Error?K.error.message:"Failed to load form":null;S.useEffect(()=>{!K.data||O.current===k||(A(K.data),T(null),O.current=null,D.current=null)},[K.data,k]),S.useEffect(()=>{T(ce)},[ce]),S.useEffect(()=>{V===void 0&&O.current!==k&&(A(null),T(null),O.current=null,D.current=null)},[V,k]);const ne=S.useMemo(()=>{const ae=C?.form;if(!ae)return null;const ve=(r??Tn()??"").trim()||"default",Ye=Pg({scope:ve,formId:ae._id,version:ae.version});return Ye?.value?Ye.value:kT(C,n)},[C,n,r]),G=S.useMemo(()=>{const ae=C?.BFF_submit_api;if(!ae?.url)return;let ve=ae.url;if(ve.startsWith("http://")||ve.startsWith("https://"))try{const Ge=new URL(ve);ve=Ge.pathname+Ge.search}catch{}const Ye=s?.()??{},ct={...ae.headers||{},"Content-Type":"application/json",...Ye};return{...ae,url:ve,headers:ct}},[C?.BFF_submit_api,s]),ee=S.useMemo(()=>ne?{...ne,status:"published",...G&&{BFF_submit_api:G}}:null,[ne,G]);S.useEffect(()=>{if(!ne?.id)return;const ae=(r??Tn()??"").trim()||"default";Og({scope:ae,formId:ne.id,version:ne.version},ne)},[ne,r]);const Pe=S.useMemo(()=>{if(!ne)return null;const ae=_s({config:ne.config,layout:ne.layout},null);if(!ae)return null;const ve=ae.rows,Ye=ae.columns,ct={verticalSpacing:ae.verticalSpacing??ae.spacing??"16px",horizontalSpacing:ae.horizontalSpacing??ae.spacing??"16px",rowHeight:ae.rowHeight??In};let Ge=1;if(Array.isArray(ne.fields))for(const Je of ne.fields){const q=Je?.position,$e=typeof q?.order=="number"?q.order:0,gt=typeof q?.rowSpan=="number"?q.rowSpan:1;Ge=Math.max(Ge,$e+gt)}return{rows:Math.min(ve,Math.max(1,Ge)),columns:Ye,verticalSpacing:ct.verticalSpacing,horizontalSpacing:ct.horizontalSpacing,rowHeight:ct.rowHeight}},[ne]),oe=S.useMemo(()=>{const ve=ee?.config?.theme?.cssVariables;if(!(!ve&&!y))return{...ve??{},...y??{}}},[ee?.config,y]),re=S.useCallback(()=>{w.invalidateQueries({queryKey:["workflow-steps",t]}),w.invalidateQueries({queryKey:["workflow-step",t]})},[w,t]),be=S.useCallback(ae=>{if(UT(ae)){const Ge=ae.on_success,Kt=Ge?.action;if(Kt==="redirect"&&Ge?.redirect_url){const Je=VT(Ge.redirect_url.trim(),n);window.location.href=Je;return}if(Kt==="move"){const Je=Ge?.next_step_id,q=Ge?.next_step_form;if(Je&&q){O.current=null,D.current=null;const $e=q.featureId??Ge?.next_step_form_id??q._id;w.removeQueries({queryKey:["workflow-step",t,$e,r??"",v[0],v[1],v[2]]}),re(),P(gt=>gt.some(te=>te.step_id===Je)?gt:[...gt,{step_id:Je,step_name:q.name||"Next step",feature_id:$e}]),A(null),N(Je),i?.();return}return}if(Kt==="stay"){re(),i?.();return}}const ve=ae;ve.steps&&Array.isArray(ve.steps)&&P(ve.steps);const Ye=(ve.steps&&Array.isArray(ve.steps)?ve.steps:E).filter(Ge=>Ge.feature_id),ct=ve.current_step_id;ct&&Ye.some(Ge=>Ge.step_id===ct)?N(ct):Ye.length>0&&N(Ye[0].step_id),A(null),re(),i?.(),p?.(ve)},[w,t,r,i,p,E,n,v,re]),de=S.useCallback(async ae=>C?.BFF_submit_api?(i?.(),{success:!0,message:"Saved successfully"}):{success:!1,message:"Submit not configured"},[C?.BFF_submit_api,i]),ot=S.useCallback((ae,ve)=>{},[]),Se=S.useCallback(ae=>{},[]);if($)return c.jsx(LT,{className:f});if(ie)return c.jsx("div",{className:B("rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive",f),children:ie});if(L.length===0)return c.jsx("div",{className:B("py-12 text-center text-sm text-muted-foreground",f),children:"No workflow steps configured."});const xe=C?.step_blocked_message;return c.jsx("div",{className:B(ga,h&&"dark","flex flex-col gap-4",f),style:oe,"data-form-renderer":"workflow-steps-view",children:c.jsxs(Rg,{value:k??"",onValueChange:ae=>N(ae),children:[c.jsx(Gg,{className:"w-full justify-start border-b rounded-none h-auto p-0 bg-transparent gap-0","data-form-renderer":"workflow-tabs",children:L.map(ae=>c.jsx(Kg,{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))}),L.map(ae=>c.jsx(qg,{value:ae.step_id,className:"mt-4 outline-none",children:ae.step_id!==k?null:J?c.jsx(DT,{}):I?c.jsx("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:I}):xe&&!C?.form?c.jsx("div",{className:B("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:xe}):ee?.fields?.length?c.jsxs("div",{className:"py-4 [&_*]:box-border",children:[xe?c.jsx("div",{className:B("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:xe}):null,(()=>{const ve=j.current!==k||M.current!==(ee?.id??null);if(k&&ee&&ve){j.current=k,M.current=ee.id??null;const Ye=Nt.getState();Ye.setSchema(ee,{forceReset:!0});const ct=Nt.getState().values;Ye.setValues({...ct,...o})}return null})(),c.jsx(Mc,{schema:ee,gridLayout:Pe,omitRootWrapper:!0,submissionContext:n,initialValues:o,workflowStepId:k??void 0,viewerContext:m,getViewerContext:g,onSubmit:de,onChange:ot,onValidationError:Se,onClose:()=>{},mode:"fill",unstyled:!0,onWorkflowSubmitResult:be,initialExtraSubmitPayload:Object.keys(W).length>0?W:void 0,onExtraSubmitPayloadChange:ve=>{if(ve&&typeof ve=="object"){const Ye={};ve.context_user_id!=null&&(Ye.context_user_id=ve.context_user_id),ve.id!=null&&(Ye.id=ve.id),ve.batch_id!=null&&(Ye.batch_id=ve.batch_id),ve.admission_batch_id!=null&&(Ye.admission_batch_id=ve.admission_batch_id),ve.program_id!=null&&(Ye.program_id=ve.program_id),Object.keys(Ye).length>0&&X(ct=>({...ct,...Ye}))}}},ee.id)]}):c.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:"No form schema available for this step."})},ae.step_id))]})})};function HT(e){return typeof e=="object"&&e!==null&&"apiEndpoint"in e}function WT({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(y=>y.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 g=(h,y)=>{if(y.has(h))return!0;y.add(h);const w=e.fields.find(v=>v.id===h);return w?.parentId?g(w.parentId,y):!1};l.parentId&&g(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),u=new Map;return d.forEach(l=>{const f=l.position.order;u.has(f)||u.set(f,[]),u.get(f).push(l)}),u.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 RT({field:e,value:t,allValues:r,validateOnChange:n=!1,validateOnBlur:o=!0,debounceMs:s=Bk}){const[i,a]=S.useState(),[d,u]=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}u(!0);let w;for(const v of e.validation){const x=Yr(t,v,r);if(typeof x=="string"){w=x;break}}return a(w),u(!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 g=S.useCallback(()=>{o&&p()},[o,p]),h=S.useCallback(()=>{a(void 0)},[]),y=S.useCallback(w=>{a(w)},[]);return{error:i,isValidating:d,validate:p,handleBlur:g,clearError:h,setCustomError:y}}const Xg="—";function Xt(){return{kind:"static",value:Xg}}function GT(){return{currencySymbol:"₹",emptyDisplay:Xg,columns:[{id:"col_tariff",key:"tariff_type",label:"Tariff type",format:"text",align:"left"},{id:"col_service",key:"service",label:"Service",format:"text",align:"left"},{id:"col_unit",key:"unit_price",label:"Unit price",format:"currency",align:"right"},{id:"col_disc_pct",key:"discount_pct",label:"Discount (%)",format:"percent",align:"right"},{id:"col_disc_amt",key:"discount_amount",label:"Discount (₹)",format:"currency",align:"right"},{id:"col_net",key:"net_price",label:"Net price",format:"currency",align:"right"},{id:"col_tax",key:"tax_pct",label:"Tax (%)",format:"percent",align:"right"},{id:"col_total",key:"total",label:"Total",format:"currency",align:"right"}],rowSlots:[{kind:"static",row:{id:"registration_fee",label:"Registration fee",cells:{tariff_type:{kind:"label"},service:Xt(),unit_price:{kind:"api",path:"unit_price"},discount_pct:{kind:"input",inputType:"number"},discount_amount:{kind:"formula",expression:"cell('unit_price') * cell('discount_pct') / 100"},net_price:{kind:"formula",expression:"cell('unit_price') - cell('discount_amount')"},tax_pct:{kind:"api",path:"tax_pct"},total:{kind:"formula",expression:"cell('net_price') * (1 + cell('tax_pct') / 100)"}}}},{kind:"dynamic",block:{id:"line_items",apiArrayPath:"items",rowIdField:"id",cells:{tariff_type:Xt(),service:{kind:"api",path:"service"},unit_price:{kind:"api",path:"unit_price"},discount_pct:Xt(),discount_amount:{kind:"formula",expression:"cell('unit_price') * cell('discount_pct') / 100"},net_price:{kind:"formula",expression:"cell('unit_price') - cell('discount_amount')"},tax_pct:{kind:"api",path:"tax_pct"},total:{kind:"formula",expression:"cell('net_price') * (1 + cell('tax_pct') / 100)"}}}},{kind:"static",row:{id:"all_items_summary",label:"All items summary",cells:{tariff_type:{kind:"label"},service:Xt(),unit_price:{kind:"formula",expression:"SUM('unit_price', 'data')"},discount_pct:Xt(),discount_amount:{kind:"formula",expression:"SUM('discount_amount', 'data')"},net_price:{kind:"formula",expression:"SUM('net_price', 'data')"},tax_pct:Xt(),total:{kind:"formula",expression:"SUM('total', 'data')"}}}},{kind:"static",row:{id:"invoice_discount",label:"Invoice discount",cells:{tariff_type:{kind:"label"},service:Xt(),unit_price:Xt(),discount_pct:Xt(),discount_amount:{kind:"input",inputType:"number"},net_price:Xt(),tax_pct:Xt(),total:Xt()}}},{kind:"static",row:{id:"grand_total",label:"Grand total",cells:{tariff_type:{kind:"label"},service:Xt(),unit_price:Xt(),discount_pct:Xt(),discount_amount:Xt(),net_price:Xt(),tax_pct:Xt(),total:{kind:"formula",expression:"SUM('total', 'data') - cellInRow('invoice_discount', 'discount_amount')"}}}}]}}const KT={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}}},billingGrid:{type:"billingGrid",label:"Billing Grid",icon:"Receipt",category:"special",description:"Configurable billing/tariff grid with formulas and API line items",defaultProps:{label:"Billing",name:"billing",properties:GT()}},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"}}},customizeSections:{type:"customizeSections",label:"Customise Sections",icon:"ListFilter",category:"special",description:"Show or hide UI sections defined by Section Heading fields",defaultProps:{label:"Customise Sections",name:"customize_sections",properties:{sectionHeadingNames:[],defaultHiddenSectionNames:[],variant:"outline",size:"default",buttonText:"Customise sections",menuTitle:"VISIBLE SECTIONS"}}}},Jg={padding:"md",showBorder:!1};function Qg(e,t){const r="full";return e?{padding:e.padding??Jg.padding,maxWidth:e.maxWidth??r,showBorder:e.showBorder??Jg.showBorder}:{padding:"md",maxWidth:r,showBorder:!1}}function qT(e){switch(e??"md"){case"none":return"";case"sm":return"p-3";case"lg":return"p-6 md:p-8";default:return"p-4 md:p-6"}}function YT(e,t){if(t==="full-bleed")return"w-full max-w-none";switch(e??"full"){case"full":return"w-full max-w-none";case"sm":return"mx-auto w-full max-w-screen-sm";case"md":return"mx-auto w-full max-w-screen-md";case"lg":return"mx-auto w-full max-w-screen-lg";case"xl":return"mx-auto w-full max-w-screen-xl";case"2xl":return"mx-auto w-full max-w-2xl";case"4xl":return"mx-auto w-full max-w-4xl";case"5xl":return"mx-auto w-full max-w-5xl";case"6xl":return"mx-auto w-full max-w-6xl";case"7xl":return"mx-auto w-full max-w-7xl";default:return"w-full max-w-none"}}function XT(e){switch(e){case"sidebar-main":return"grid grid-cols-1 gap-6 lg:grid-cols-[240px_1fr]";case"full-bleed":return"w-full";default:return"w-full"}}function JT(e){const t=Qg(e.container,e.layout);return B(XT(e.layout),YT(t.maxWidth,e.layout),qT(t.padding),t.showBorder&&"rounded-lg border border-border")}const Ji=1;function QT(){return{version:Ji,layout:"stack",container:{padding:"md",maxWidth:"full",showBorder:!1},dataBindings:[],widgets:[],filterGroups:[]}}function Zg(e){return{...e,config:e.config??{},children:Array.isArray(e.children)?e.children.map(Zg):void 0}}function ZT(e){return{version:Ji,layout:e.layout??"stack",container:Qg(e.container,e.layout),meta:e.meta,dataBindings:Array.isArray(e.dataBindings)?e.dataBindings:[],dataApis:e.dataApis??{},prepopulateApi:e.prepopulateApi,widgets:Array.isArray(e.widgets)?e.widgets.map(Zg):[],filterGroups:Array.isArray(e.filterGroups)?e.filterGroups:[],eventHandlers:e.eventHandlers??[],navigation:e.navigation}}function eF(e){const t=e;return!t||typeof t!="object"?QT():(t.version!==Ji&&(t.version=Ji),ZT(t))}const ey={};let ty=null;function tF(e){ty=e}function rF(){return(ey?.VITE_API_BASE_URL?.trim()||ey?.VITE_API_URL?.trim()||"").replace(/\/$/,"")}const vs=_t.create({baseURL:rF()});vs.interceptors.request.use(e=>{const t=Tn();t&&(e.params={...e.params,clientId:t}),typeof FormData<"u"&&e.data instanceof FormData&&delete e.headers["Content-Type"];let r=ty?.();if((!r||Object.keys(r).length===0)&&(r=Ml()),r){const n=e.headers??{};for(const[o,s]of Object.entries(r))s!==void 0&&s!==""&&(n[o]=s);e.headers=n}return e});async function ry(e){const t=await vs.get("/api/page-builder/pages/resolve",{params:e}),r=t.data?.data??t.data;if(!r?.pageId)throw new Error("Page resolve failed: no pageId returned");return r}async function Bc(e,t,r){const n=await vs.get(`/api/page-builder/pages/${e}/render`,{params:{clientId:t,...r!==void 0?{version:r}:{}}}),o=n.data?.data??n.data;if(!o?.schema)throw new Error("Page render failed: no schema returned");return o}async function $c(e){const{clientId:t,api:r,context:n,filterState:o}=e,s=await vs.post(`/api/page-builder/clients/${t}/data-sources/execute`,{api:r,context:n,filterState:o});return s.data?.data??s.data}function nF(e,t){if(!t)return{};const r={};for(const[n,o]of Object.entries(t)){if(!o.trim())continue;const s=Qe(e,o);s!==void 0&&(r[n]=s)}return r}const ny=S.createContext(null);function oy(e,t){const r={};for(const n of e){let o;switch(n.source){case"route.param":o=n.param?t[n.param]:void 0;break;case"route.query":o=n.param?t[n.param]:void 0;break;case"context.user":o=n.param?t.user?.[n.param]:t.user;break;case"context.client":o=n.param?t.client?.[n.param]:t.client??t.clientId;break;case"context.tenant":o=n.param?t.tenant?.[n.param]:t.tenant??t.tenantId;break;case"static":o=n.value;break;case"widget.state":o=n.sample;break;default:o=void 0}o===void 0&&n.sample!==void 0&&(o=n.sample),o!==void 0&&(r[n.key]=o)}return r}function oF({schema:e,context:t={},clientId:r,nestingDepth:n=0,onAction:o,getWorkflowState:s,parentContext:i,children:a}){const[d,u]=S.useState(()=>i?i.filterGroups:{}),l=S.useRef(d);l.current=d;const[f,p]=S.useState({}),[m,g]=S.useState("idle"),h=S.useRef(null),y=String(r??t.clientId??i?.clientId??""),w=JSON.stringify(t);S.useEffect(()=>{if(i)return;const C=e.prepopulateApi;if(!C?.enabled||!C.api?.path||!y){p({}),g("idle"),h.current=null;return}const A=JSON.stringify({path:C.api.path,method:C.api.method,queryParams:C.api.queryParams,headers:C.api.headers,bodyFields:C.api.bodyFields,auth:C.api.auth,mapping:C.contextMapping,bindings:e.dataBindings,context:w});if(h.current===A)return;let I=!1;return h.current=A,g("loading"),(async()=>{try{const T=oy(e.dataBindings??[],t),W={...t,...T},X=await $c({clientId:y,api:C.api,context:W});if(I)return;const O=nF(X,C.contextMapping);p({...O,prepopulateResponse:X}),g("ready")}catch{I||(p({}),g("error"))}})(),()=>{I=!0,h.current=null}},[i,e.prepopulateApi,e.dataBindings,w,y]);const v=S.useMemo(()=>{if(i)return{...i.context,...t};const C=oy(e.dataBindings??[],t);return{...t,...C,...f}},[i,t,e.dataBindings,f]),x=String(r??v.clientId??i?.clientId??""),E=S.useCallback((C,A,I)=>{u(T=>({...T,[C]:{...T[C]??{},[A]:I}}))},[]),P=S.useCallback(C=>l.current[C]??{},[]),k=S.useCallback((C,A,I,T)=>{(o??i?.onAction)?.({...C,sourceWidgetId:A,event:I,payload:T})},[o,i?.onAction]),N=S.useMemo(()=>({schema:e,context:v,clientId:x,prepopulateStatus:i?.prepopulateStatus??m,nestingDepth:n,onAction:o??i?.onAction,getWorkflowState:s??i?.getWorkflowState,filterGroups:d,setFilterValue:E,getFilterGroup:P,dispatchAction:k}),[e,v,x,m,n,o,i?.onAction,s,i?.getWorkflowState,d,E,P,k]);return c.jsx(ny.Provider,{value:N,children:a})}function Lr(){const e=S.useContext(ny);if(!e)throw new Error("usePageContext must be used within PageContextProvider");return e}const sF=5,sy=1;function Fo(e){return Number.isFinite(e)?Math.min(sF,Math.max(sy,Math.round(e))):sy}function iF(e,t){const r=Fo(t),n=Array.from({length:r},()=>[]);return e.forEach((o,s)=>{const i=o.config,a=i.columnIndex!==void 0?Math.min(Math.max(0,i.columnIndex),r-1):s%r;n[a].push(o)}),n}function aF(e){return Number.isFinite(e)?Math.min(100,Math.max(0,Math.round(e))):0}function lF(e,t){const r=Math.max(1,t),n=Math.min(100,Math.max(0,Math.round(e))),o=Math.floor(n/r),s=n-o*r;return Array.from({length:r},(i,a)=>o+(a<s?1:0))}function iy(e){return lF(100,Fo(e))}function cF(e){const t=e.trim(),r=/^(\d+(?:\.\d+)?)\s*%?$/.exec(t);return r?aF(Number(r[1])):null}function ay(e,t){const r=Fo(t),n=[];for(let s=0;s<r;s++){const i=cF(e?.[s]??"");if(i===null)return iy(r);n.push(i)}return n.reduce((s,i)=>s+i,0)!==100?iy(r):n}function dF(e){return e==="sm"?"gap-2":e==="lg"?"gap-6":"gap-4"}function ly(e,t){return ay(t,Fo(e)).map(n=>`minmax(0, ${n}fr)`).join(" ")}function uF(e){return e.length?e.map(t=>`minmax(0, ${t}fr)`).join(" "):"minmax(0, 1fr)"}function fF(e,t,r,n){const o=Fo(t),s=iF(e,o),i=ay(r,o);if(!(n?.collapseEmpty!==!1))return{columns:s,gridTemplate:ly(o,r),sourceIndices:s.map((p,m)=>m)};const d=s.map((p,m)=>({colChildren:p,index:m,percent:i[m]??0})).filter(p=>p.colChildren.length>0);if(d.length===0||d.length===s.length)return{columns:s,gridTemplate:ly(o,r),sourceIndices:s.map((p,m)=>m)};const u=d.reduce((p,m)=>p+m.percent,0),l=d.map(p=>u>0?Math.round(p.percent/u*100):Math.round(100/d.length)),f=100-l.reduce((p,m)=>p+m,0);return f!==0&&l.length>0&&(l[0]+=f),{columns:d.map(p=>p.colChildren),gridTemplate:uF(l),sourceIndices:d.map(p=>p.index)}}function jc(e,t="solid"){return e?t==="dashed"?"rounded-md border border-dashed border-border":"rounded-md border border-border":""}function pF(e){return B(jc(e.showBorder,e.borderStyle??"solid"),e.showBorder&&"p-3")}function mF(e){return B(jc(e.showBorder,e.borderStyle??"solid"),e.showBorder&&"p-2")}function hF(e,t){return e.columnBorders?.[t]!==void 0?!!e.columnBorders[t]:!!e.showColumnBorders}function gF(e,t){const r=hF(e,t);return B(jc(r,e.borderStyle??"dashed"),r&&"p-2")}function yF(e){if(e)return{minHeight:`${e}vh`}}function bF({widget:e,renderChildren:t}){const r=e.config,[n,o]=S.useState(r.defaultCollapsed??!1);return c.jsxs("section",{className:B("space-y-4",pF(r)),"data-widget-id":e.id,children:[r.heading&&c.jsx("div",{className:"flex items-center gap-2",children:r.collapsible?c.jsx("button",{type:"button",className:"text-left text-lg font-semibold hover:underline",onClick:()=>o(s=>!s),children:r.heading}):c.jsx("h2",{className:"text-lg font-semibold",children:r.heading})}),r.showDivider&&c.jsx("hr",{className:"border-border"}),!n&&e.children?.length?c.jsx("div",{className:"space-y-4",children:t?.(e.children)}):null]})}function vF({widget:e,renderChildren:t}){const r=e.config,n=Fo(r.columns??2),o=r.collapseEmptyColumns!==!1,s=fF(e.children??[],n,r.columnWidths,{collapseEmpty:o});return c.jsx("div",{className:B("grid w-full min-w-0 items-stretch",dF(r.gap),mF(r)),style:{gridTemplateColumns:s.gridTemplate,...yF(r.minHeightPercent)},"data-widget-id":e.id,children:s.columns.map((i,a)=>{const d=s.sourceIndices[a]??a;return c.jsx("div",{className:B("flex min-h-[inherit] min-w-0 flex-col space-y-4 overflow-hidden",gF(r,d)),children:t?.(i)},d)})})}function wF({widget:e,renderChildren:t}){const r=e.config,n=r.variant==="outline"?"border bg-background":r.variant==="elevated"?"border bg-background shadow-md":"border bg-card";return c.jsxs("div",{className:B("rounded-lg p-4",n),"data-widget-id":e.id,children:[(r.title||r.subtitle)&&c.jsxs("div",{className:"mb-4",children:[r.title&&c.jsx("h3",{className:"font-semibold",children:r.title}),r.subtitle&&c.jsx("p",{className:"text-sm text-muted-foreground",children:r.subtitle})]}),e.children?.length?c.jsx("div",{className:"space-y-4",children:t?.(e.children)}):null]})}function cy(e,t){if(e.variable){const r=t[e.variable];return r!=null?String(r):e.fallback??e.text??""}return e.text??""}function SF({widget:e}){const t=e.config,{context:r}=Lr(),n=cy(t,r),o=t.level??2,s=t.align==="center"?"text-center":t.align==="right"?"text-right":"text-left",i=o===1?"text-3xl":o===2?"text-2xl":o===3?"text-xl":"text-lg";return c.jsx("div",{role:"heading","aria-level":o,className:B("font-semibold tracking-tight",i,s),"data-widget-id":e.id,children:n})}function xF({widget:e}){const t=e.config,{context:r}=Lr(),n=cy(t,r),o=t.preset==="caption"?"text-sm text-muted-foreground":t.preset==="small"?"text-xs text-muted-foreground":"text-base",s=t.align==="center"?"text-center":t.align==="right"?"text-right":"text-left";return c.jsx("p",{className:B(o,s),"data-widget-id":e.id,children:n})}function AF(e,t){return!e||typeof e!="string"?e:e.replace(/\{\{([^}]+)\}\}/g,(r,n)=>{const o=n.trim(),s=t[o];return s==null?"":String(s)})}function dy(e,t){const r={...e};for(const[n,o]of Object.entries(r))typeof o=="string"&&(r[n]=AF(o,t));return r}function CF(e,t){return e.replace(/\{\{([^}]+)\}\}/g,(r,n)=>{const o=t[n.trim()];return o!=null?String(o):""})}function uy(e,t,r,n){if(e.type==="navigate"){const o=CF(e.href,t);if(!o.trim())return;e.openIn==="new"?window.open(o,"_blank","noopener,noreferrer"):window.location.assign(o);return}if(e.type==="navigate_page"&&e.pageId){r({...e,params:e.params?dy(e.params,t):void 0},n,"click");return}if(e.type==="workflow"&&e.workflowId){r(e,n,"click");return}r(e,n,"click")}function EF({widget:e}){const t=e.config,{context:r,dispatchAction:n}=Lr();return c.jsx(Yt,{variant:t.variant??"default",size:t.size??"default","data-widget-id":e.id,onClick:()=>uy(t.action,r,n,e.id),children:t.label})}const NF={start:"justify-start",center:"justify-center",end:"justify-end","space-between":"justify-between"},_F={sm:"gap-2",md:"gap-3",lg:"gap-4"};function kF({widget:e}){const t=e.config,{context:r,dispatchAction:n}=Lr(),o=t.buttons??[];return c.jsx("div",{className:B("flex flex-wrap items-center",NF[t.align??"start"],_F[t.gap??"sm"],t.wrap===!1&&"flex-nowrap"),"data-widget-id":e.id,children:o.map(s=>c.jsx(Yt,{variant:s.variant??"outline",size:s.size??"default","data-widget-id":e.id,"data-button-id":s.id,onClick:()=>uy(s.action,r,n,e.id),children:s.label},s.id))})}function TF(e){const t=e.prepopulateApi;return!!(t?.enabled&&t.api?.path)}function FF(e,t){const r=Qe(e,t??"");return r===void 0?null:r}function fy(e,t){if(e.mode==="pageApi"&&e.dataSourceRef)return t[e.dataSourceRef];if(e.mode==="api")return e.api}function py({widgetId:e,dataSource:t,enabled:r=!0,page:n,pageSize:o,search:s}){const{schema:i,context:a,clientId:d,getFilterGroup:u,prepopulateStatus:l}=Lr(),f=S.useMemo(()=>t.filterGroupKey?u(t.filterGroupKey):{},[t.filterGroupKey,u]),p=t.mode==="context"&&TF(i),m=r&&(t.mode==="static"||(t.mode==="context"?!p||l!=="loading":!!d)),g=S.useMemo(()=>["page-ds",e,t,a,f,n,o,s,l],[e,t,a,f,n,o,s,l]);return gn.useQuery({queryKey:g,enabled:m,staleTime:fy(t,i.dataApis??{})?.staleTimeMs??3e4,queryFn:async()=>{if(t.mode==="static")return t.staticData;if(t.mode==="context")return FF(a,t.contextPath);const h=fy(t,i.dataApis??{});if(!h)throw new Error(`No API config for data source on widget ${e}`);const y={...a};if(t.requestBindings)for(const x of t.requestBindings){let E;x.source==="binding"?E=a[x.key]:x.source==="filter"&&(E=f[x.key]),E!==void 0&&(y[x.param]=E)}const v={...dy(y,a),...n!==void 0?{page:n,pageSize:o,search:s}:{}};return $c({clientId:d,api:h,context:v,filterState:f})}})}function zc(e,t){if(e==null)return"";if(!t||t.type==="none")return String(e);switch(t.type){case"number":{const r=Number(e);return Number.isNaN(r)?String(e):r.toFixed(t.decimals??0)}case"currency":{const r=Number(e);return Number.isNaN(r)?String(e):new Intl.NumberFormat(void 0,{style:"currency",currency:t.currency??"USD"}).format(r)}case"percent":{const r=Number(e);return Number.isNaN(r)?String(e):`${r.toFixed(t.decimals??0)}%`}case"date":{const r=new Date(String(e));return Number.isNaN(r.getTime())?String(e):r.toLocaleDateString(void 0,{...t.format?{}:{}})}case"template":return t.template.replace(/\{\{value\}\}/g,String(e));default:return String(e)}}function ws(e,t){const r=Qe(e,t.path);return r==null?t.fallback??r:t.formatter?zc(r,t.formatter):r}function PF(e,t){if(!t)return{};const r={};for(const[n,o]of Object.entries(t))o in e&&(r[n]=e[o]);return r}const OF={default:"border bg-card",success:"border border-green-200 bg-green-50 text-green-900",warning:"border border-amber-200 bg-amber-50 text-amber-900",danger:"border border-red-200 bg-red-50 text-red-900"},IF={rectangle:"rounded-lg",square:"aspect-square rounded-lg",circle:"aspect-square rounded-full"},MF={sm:"p-2 text-xs",md:"p-4 text-sm",lg:"p-6 text-base"},Uc={sm:"text-lg",md:"text-2xl",lg:"text-3xl"},LF={sm:"gap-2",md:"gap-3",lg:"gap-4"};function DF({title:e,value:t,trend:r,variant:n="default",shape:o="rectangle",size:s="md",layout:i="vertical",isLoading:a,isError:d}){const u=i==="horizontal";return c.jsxs("div",{className:B(OF[n??"default"],IF[o??"rectangle"],MF[s??"md"],u&&"flex items-center justify-between gap-3"),children:[c.jsxs("div",{className:B(u&&"min-w-0"),children:[e&&c.jsx("p",{className:B("font-medium text-muted-foreground",u?"text-sm":""),children:e}),r!=null&&r!==""&&!u&&c.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:String(r)})]}),a?c.jsx(Pn,{className:"my-2"}):d?c.jsx("p",{className:B("font-bold text-destructive",Uc[s??"md"]),children:"Error"}):c.jsx("p",{className:B("font-bold",u?Uc[s??"md"]:`mt-1 ${Uc[s??"md"]}`),children:String(t)}),u&&r!==null&&r!==void 0&&r!==""&&c.jsx("p",{className:"text-xs text-muted-foreground",children:String(r)})]})}function my({stat:e,widgetId:t}){const{data:r,isLoading:n,isError:o}=py({widgetId:t,dataSource:e.dataSource}),i=(()=>{if(r==null)return e.valueMapping.fallback??"—";if(e.dataSource.mode==="context"){const d=r;return e.valueMapping.formatter?zc(d,e.valueMapping.formatter):d}if(e.dataSource.mode==="static"){const d=e.valueMapping.path?.trim()||"value",u=ws(r,{...e.valueMapping,path:d});if(u!=null)return e.valueMapping.formatter?zc(u,e.valueMapping.formatter):u;if(typeof r=="object"&&r!==null&&!Array.isArray(r)){const l=r;if(l.value!==void 0&&l.value!==null)return l.value}return e.valueMapping.fallback??"—"}return ws(r,e.valueMapping)})(),a=e.trendMapping&&r!==void 0&&e.dataSource.mode!=="context"?ws(r,e.trendMapping):e.trendMapping&&e.dataSource.mode==="context"&&e.trendMapping.path?ws({value:r},e.trendMapping):null;return c.jsx(DF,{title:e.title,value:i,trend:a,variant:e.variant,shape:e.shape,size:e.size,layout:e.layout,isLoading:n,isError:o})}function BF({widget:e}){const t=e.config;return c.jsx("div",{"data-widget-id":e.id,children:c.jsx(my,{stat:t,widgetId:e.id})})}function $F({stat:e,widgetId:t}){return c.jsx(my,{stat:e,widgetId:`${t}-${e.id}`})}function jF({widget:e}){const t=e.config,r=t.stats??[],n=t.columns??1,o=t.direction==="horizontal";return c.jsx("div",{"data-widget-id":e.id,className:B(o?"flex flex-wrap":"grid",!o&&n===1&&"grid-cols-1",!o&&n===2&&"grid-cols-2",!o&&n===3&&"grid-cols-3",!o&&n===4&&"grid-cols-4",LF[t.gap??"md"]),children:r.map(s=>c.jsx($F,{stat:s,widgetId:e.id},s.id))})}function zF({widget:e}){const t=e.config,{setFilterValue:r}=Lr(),[n,o]=S.useState("");return S.useEffect(()=>{const s=t.debounceMs??300,i=setTimeout(()=>{r(t.filterGroupKey,"search",n)},s);return()=>clearTimeout(i)},[n,t.debounceMs,t.filterGroupKey,r]),c.jsx("input",{type:"search",className:"flex h-9 w-full max-w-sm rounded-md border border-input bg-background px-3 py-1 text-sm shadow-xs",placeholder:t.placeholder??"Search…",value:n,onChange:s=>o(s.target.value),"data-widget-id":e.id})}function UF(e,t){if(!e)return[];const r=t?Qe(e,t):e;if(Array.isArray(r))return r;if(typeof r=="object"&&r!==null){const n=r;if(Array.isArray(n.items))return n.items;if(Array.isArray(n.data))return n.data}return[]}function VF({widget:e}){const t=e.config,{dispatchAction:r}=Lr(),[n,o]=S.useState(1),[s,i]=S.useState(""),a=t.pagination?.pageSize??10,{data:d,isLoading:u,isError:l}=py({widgetId:e.id,dataSource:t.dataSource,page:n,pageSize:a,search:t.search?.enabled?s:void 0}),f=t.dataSource.mode==="pageApi"?void 0:t.dataSource.api?.itemsPath,p=UF(d,f??"data.items"),m=(g,h)=>{const y=t.dataSource.responseMapping.find(w=>w.target===h);return y?ws(g,y):Qe(g,h)??""};return c.jsxs("div",{className:"space-y-3","data-widget-id":e.id,children:[t.search?.enabled&&c.jsx("input",{type:"search",className:"flex h-9 w-full max-w-sm rounded-md border border-input bg-background px-3 py-1 text-sm",placeholder:t.search.placeholder??"Search…",value:s,onChange:g=>{i(g.target.value),o(1)}}),c.jsx("div",{className:"overflow-x-auto rounded-md border",children:c.jsxs("table",{className:"w-full text-sm",children:[c.jsx("thead",{children:c.jsx("tr",{className:"border-b bg-muted/50",children:t.columns.map(g=>c.jsx("th",{className:B("px-3 py-2 text-left font-medium",g.align==="center"&&"text-center",g.align==="right"&&"text-right"),style:g.width?{width:g.width}:void 0,children:g.header},g.id))})}),c.jsx("tbody",{children:u?c.jsx("tr",{children:c.jsx("td",{colSpan:t.columns.length,className:"px-3 py-8 text-center",children:c.jsx(Pn,{})})}):l?c.jsx("tr",{children:c.jsx("td",{colSpan:t.columns.length,className:"px-3 py-8 text-center text-destructive",children:"Failed to load data"})}):p.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:t.columns.length,className:"px-3 py-8 text-center text-muted-foreground",children:t.emptyMessage??"No data"})}):p.map((g,h)=>c.jsx("tr",{className:"cursor-pointer border-b hover:bg-muted/30",onClick:()=>{r({type:"emit",eventName:"row_click",payload:{row:g}},e.id,"row_click")},children:t.columns.map(y=>c.jsx("td",{className:B("px-3 py-2",y.align==="center"&&"text-center",y.align==="right"&&"text-right"),children:String(m(g,y.field))},y.id))},h))})]})}),t.pagination?.enabled&&c.jsxs("div",{className:"flex items-center justify-between text-sm",children:[c.jsxs("span",{className:"text-muted-foreground",children:["Page ",n]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{type:"button",className:"rounded border px-2 py-1 disabled:opacity-50",disabled:n<=1,onClick:()=>o(g=>Math.max(1,g-1)),children:"Previous"}),c.jsx("button",{type:"button",className:"rounded border px-2 py-1",disabled:p.length<a,onClick:()=>o(g=>g+1),children:"Next"})]})]})]})}const HF=75;function WF(e){return e??HF}function Vc({scrollBehavior:e="page",maxHeightPercent:t,children:r,className:n}){if(e!=="contained")return c.jsx(c.Fragment,{children:r});const o=WF(t);return c.jsx("div",{className:B("min-w-0 overflow-y-auto overflow-x-hidden",n),style:{maxHeight:`${o}vh`},"data-form-embed-scroll":"contained",children:r})}function RF(e,t,r){return["embedded-form",e,t,r??"latest"]}async function GF(e,t){try{const r=await dn.get(`/api/form-builder/form-layouts/form/${e}`,{params:{clientId:t}});let n=r.data?.data??r.data;for(;n&&typeof n=="object"&&!Array.isArray(n)&&n.data!=null&&typeof n.data=="object"&&!("rows"in n)&&!("columns"in n)&&!("formDefinitionId"in n);)n=n.data;return!n||typeof n!="object"||Array.isArray(n)||!("rows"in n)&&!("columns"in n)&&!("formDefinitionId"in n)?null:n}catch{return null}}async function KF(e,t,r){const n=r!==void 0?`/api/form-builder/forms/${e}/render?version=${r}`:`/api/form-builder/forms/${e}/render`,o=await dn.get(n,{params:{clientId:t}}),i=o.data?.data??o.data,a=i.form??i,d=i.fields??a.fields??[];let u=i.layout??a.layout??null;(!u||typeof u.columns!="number")&&(u=await GF(e,t));const l=i.rules??a.rules??[],f=ms(a,d,u,l),p=_s({config:f.config,layout:f.layout},Ns(u))??Ns(u);return{schema:f,gridLayout:p}}const qF=300*1e3;function hy({formId:e,mode:t="fill",contextFieldMapping:r,pageContext:n,clientId:o,formVersion:s,scrollBehavior:i,maxHeightPercent:a}){const{data:d,isLoading:u,isError:l,error:f}=gn.useQuery({queryKey:RF(e,o,s),queryFn:()=>KF(e,o,s),staleTime:qF}),p=S.useMemo(()=>PF(n,r),[n,r]);return u?c.jsx(Vc,{scrollBehavior:i,maxHeightPercent:a,children:c.jsx(Pn,{})}):l?c.jsx(Vc,{scrollBehavior:i,maxHeightPercent:a,children:c.jsx("p",{className:"text-sm text-destructive",children:f instanceof Error?f.message:"Failed to load form"})}):d?.schema?c.jsx(Vc,{scrollBehavior:i,maxHeightPercent:a,children:c.jsx(Mc,{schema:d.schema,mode:t,gridLayout:d.gridLayout,initialValues:p,submissionContext:n})}):null}function YF({widget:e}){const t=e.config,{context:r,clientId:n}=Lr();return t.formId?c.jsx(hy,{formId:t.formId,mode:t.mode??"fill",contextFieldMapping:t.contextFieldMapping,pageContext:r,clientId:n,scrollBehavior:t.scrollBehavior,maxHeightPercent:t.maxHeightPercent}):c.jsx("p",{className:"text-sm text-muted-foreground",children:"No form configured"})}function XF({widget:e}){const t=e.config,{context:r,getWorkflowState:n,clientId:o}=Lr(),s=String(r.moduleId??"");if(!n)return c.jsxs("div",{className:"rounded-md border border-dashed p-4 text-sm text-muted-foreground","data-widget-id":e.id,children:["Workflow embed requires ",c.jsx("code",{className:"text-xs",children:"getWorkflowState"})," on PageRenderer. Workflow ID: ",t.workflowId]});if(!s)return c.jsx("p",{className:"text-sm text-destructive","data-widget-id":e.id,children:"moduleId required in page context for workflow embed"});const i={};if(t.contextVariableMapping)for(const[a,d]of Object.entries(t.contextVariableMapping)){const u=r[d];u!=null&&(i[a]=String(u))}return c.jsx(Yg,{getWorkflowState:n,moduleId:s,tenantId:r.tenantId?String(r.tenantId):void 0,clientId:o||void 0,submissionContext:i})}function JF({widget:e}){const t=e.config,{schema:r,dispatchAction:n}=Lr(),o=t.previousPage??r.navigation?.previousPage,s=t.nextPage??r.navigation?.nextPage,i=t.showPrevious!==!1&&!!o,a=t.showNext!==!1&&!!s,d=t.showBreadcrumbs&&r.navigation?.breadcrumbs?.length,u=t.align==="center"?"justify-center":t.align==="right"?"justify-end":t.align==="space-between"?"justify-between":"justify-start",l=f=>{n({type:"navigate_page",pageId:f.pageId},e.id,"click")};return c.jsxs("nav",{className:"space-y-3","data-widget-id":e.id,children:[d&&c.jsx("ol",{className:"flex flex-wrap items-center gap-1 text-sm text-muted-foreground",children:r.navigation.breadcrumbs.map((f,p)=>c.jsxs("li",{className:"flex items-center gap-1",children:[p>0&&c.jsx("span",{children:"/"}),f.href?c.jsx("a",{href:f.href,className:"hover:underline",children:f.label}):c.jsx("span",{children:f.label})]},p))}),c.jsxs("div",{className:B("flex items-center gap-2",u),children:[i&&o&&c.jsx(Yt,{variant:"outline",size:"sm",onClick:()=>l(o),children:o.label??"Previous"}),a&&s&&c.jsx(Yt,{variant:"default",size:"sm",onClick:()=>l(s),children:s.label??"Next"})]})]})}function QF(e,t){return e?.length?e.filter(r=>r.config.tabId===t):[]}const ZF=1;function eP(e){switch(e){case"pills":return"bg-transparent gap-1 p-0 h-auto";case"underline":return"bg-transparent rounded-none border-b p-0 h-auto w-full justify-start gap-4";default:return""}}function tP(e){switch(e){case"pills":return"rounded-full data-[state=active]:bg-primary data-[state=active]:text-primary-foreground";case"underline":return"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:shadow-none bg-transparent";default:return""}}function rP(e,t,r){return e?new Set(r?[r]:[]):new Set(t.map(n=>n.id))}function nP({tab:e,shouldRender:t,pageContext:r,clientId:n}){return t?e.formId?c.jsx(hy,{formId:e.formId,mode:e.formMode??"fill",contextFieldMapping:e.contextFieldMapping,pageContext:r,clientId:n,scrollBehavior:e.scrollBehavior,maxHeightPercent:e.maxHeightPercent}):c.jsx("p",{className:"text-sm text-muted-foreground",children:"No form configured for this tab"}):null}function oP({tab:e,shouldLoad:t,shouldRender:r,nestingDepth:n,pageContext:o,clientId:s,onAction:i,getWorkflowState:a}){const d=Lr(),{data:u,isLoading:l,isError:f,error:p}=gn.useQuery({queryKey:["tab-page",e.pageId,e.pageVersion,s],enabled:t&&!!e.pageId,queryFn:async()=>Bc(e.pageId,s,e.pageVersion)});return r?n>=ZF?c.jsx("div",{className:"rounded-md border border-destructive/50 bg-destructive/5 p-4 text-sm text-destructive",children:"Nested page tabs not supported"}):e.pageId?l?c.jsx(Pn,{}):f?c.jsx("p",{className:"text-sm text-destructive",children:p instanceof Error?p.message:"Failed to load page"}):u?c.jsx(Hc,{page:u,context:o,nestingDepth:n+1,inheritContext:!0,onAction:i,getWorkflowState:a,parentContext:d}):null:c.jsx("p",{className:"text-sm text-muted-foreground",children:"No page configured for this tab"}):null}function sP({tab:e,widgetChildren:t,renderChildren:r}){const n=QF(t,e.id);return n.length===0?c.jsx("p",{className:"text-sm text-muted-foreground py-4",children:"No widgets in this tab"}):c.jsx(c.Fragment,{children:r?.(n)})}function iP({widget:e,renderChildren:t}){const r=e.config,{context:n,clientId:o,nestingDepth:s,onAction:i,getWorkflowState:a}=Lr(),d=r.tabs??[],u=r.defaultTabId??d[0]?.id??"",l=r.lazyLoad!==!1,[f,p]=S.useState(u),[m,g]=S.useState(()=>rP(l,d,u)),h=w=>{g(v=>new Set(v).add(w)),p(w)},y=S.useMemo(()=>!l,[l]);return d.length===0?c.jsx("p",{className:"text-sm text-muted-foreground","data-widget-id":e.id,children:"No tabs configured"}):c.jsxs(Rg,{value:f,onValueChange:h,className:"w-full","data-widget-id":e.id,children:[c.jsx(Gg,{className:B("mb-4",eP(r.variant)),children:d.map(w=>c.jsx(Kg,{value:w.id,disabled:w.disabled,className:tP(r.variant),children:w.label},w.id))}),d.map(w=>{const v=m.has(w.id),x=y||v,E=y||v;return c.jsxs(qg,{value:w.id,forceMount:y||void 0,className:B("mt-0",y&&"data-[state=inactive]:hidden"),children:[w.contentType==="widgets"&&E&&c.jsx(sP,{tab:w,widgetChildren:e.children??[],renderChildren:t}),w.contentType==="form"&&c.jsx(nP,{tab:w,shouldRender:x,pageContext:n,clientId:o}),w.contentType==="page"&&c.jsx(oP,{tab:w,shouldLoad:x,shouldRender:E,nestingDepth:s,pageContext:n,clientId:o,onAction:i,getWorkflowState:a})]},w.id)})]})}const aP={section:bF,columns:vF,card:wF,tab_group:iP,heading:SF,text:xF,button:EF,button_group:kF,stat_card:BF,stat_grid:jF,data_table:VF,search_filter:zF,form_embed:YF,workflow_embed:XF,page_nav:JF};function lP({widget:e}){return c.jsxs("div",{className:"rounded-md border border-dashed border-muted-foreground/40 bg-muted/20 p-3 text-sm text-muted-foreground","data-widget-id":e.id,"data-widget-type":e.type,children:["Unsupported widget: ",c.jsx("code",{className:"text-xs",children:e.type}),e.label&&c.jsxs("span",{className:"ml-1",children:["(",e.label,")"]})]})}function cP({widget:e,renderChildren:t}){const r=aP[e.type]??lP;return c.jsx(r,{widget:e,renderChildren:t})}function gy(e,t){return e.map(r=>c.jsx(cP,{widget:r,renderChildren:t},r.id))}function Hc({page:e,context:t={},onAction:r,chrome:n="none",className:o,nestingDepth:s=0,getWorkflowState:i,inheritContext:a=!1,parentContext:d}){const u=S.useMemo(()=>eF(e.schema),[e.schema]),l=p=>gy(p,l),f=c.jsxs("div",{className:B("studio-page-content min-h-0 min-w-0",JT(u),o),"data-page-id":e.id,"data-nesting-depth":s,children:[n==="minimal"&&u.meta?.title&&c.jsxs("header",{className:"mb-6 border-b pb-4",children:[c.jsx("h1",{className:"text-2xl font-semibold",children:u.meta.title}),u.meta.description&&c.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:u.meta.description})]}),c.jsx("div",{className:"space-y-6",children:gy(u.widgets,l)})]});return a&&d?f:c.jsx(oF,{schema:u,context:t,clientId:String(t.clientId??""),nestingDepth:s,onAction:r,getWorkflowState:i,parentContext:d,children:f})}function dP({clientId:e,tenantId:t,moduleId:r,featureId:n,pageId:o,routePath:s,routeParams:i={},isDefault:a,context:d={},version:u,chrome:l="none",onAction:f,getWorkflowState:p}){const m=S.useMemo(()=>({...i,...d,clientId:e,tenantId:t,moduleId:r,featureId:n}),[i,d,e,t,r,n]),{data:g,isLoading:h,isError:y,error:w}=gn.useQuery({queryKey:["page-resolve",e,t,r,n,o,s,a,u],queryFn:()=>ry({clientId:e,tenantId:t,moduleId:r,featureId:n,routePath:s,isDefault:a,version:u}),enabled:!o}),v=o??g?.pageId,x=u??g?.version,{data:E,isLoading:P,isError:k,error:N}=gn.useQuery({queryKey:["page-render",v,e,x],queryFn:()=>Bc(v,e,x),enabled:!!v});return!o&&h?c.jsx("div",{className:"flex items-center justify-center p-12",children:c.jsx(Pn,{})}):y?c.jsx("div",{className:"rounded-md border border-destructive/50 bg-destructive/5 p-4 text-sm text-destructive",children:w instanceof Error?w.message:"Failed to resolve page"}):v?P?c.jsx("div",{className:"flex items-center justify-center p-12",children:c.jsx(Pn,{})}):k||!E?c.jsx("div",{className:"rounded-md border border-destructive/50 bg-destructive/5 p-4 text-sm text-destructive",children:N instanceof Error?N.message:"Failed to load page"}):c.jsx(Hc,{page:E,context:m,chrome:l,nestingDepth:0,onAction:f,getWorkflowState:p}):c.jsx("div",{className:"rounded-md border p-4 text-sm text-muted-foreground",children:"No page found for the given scope or route."})}ge.FIELD_TYPE_REGISTRY=KT,ge.FORM_RENDERER_GRID_ROW_HEIGHT_DEFAULT=In,ge.FORM_RENDERER_ROOT_CLASS=ga,ge.FieldRenderer=un,ge.FormRenderer=Mc,ge.PageRenderer=Hc,ge.RendererFieldLayoutContext=_a,ge.StudioPageHost=dP,ge.WorkflowStepsView=Yg,ge.appearanceControlClasses=Bo,ge.appearanceHasExplicitVerticalIntent=kd,ge.appearanceTextareaClasses=vd,ge.backendToFormSchema=ms,ge.cellAlignmentClasses=Nb,ge.cellVerticalJustifyClassesForField=Eb,ge.effectiveWidthPercent=Ps,ge.executeDataSource=$c,ge.fetchPageRender=Bc,ge.fieldBlockBoxStyle=Cb,ge.fieldBlockBoxStyleForField=Nd,ge.fieldBlockHorizontalPlacementClass=xd,ge.fieldBlockHorizontalSelfClass=Ad,ge.fieldBlockHorizontalSelfClassForField=_d,ge.fieldBlockWidthStyle=Sa,ge.fieldBlockWidthStyleForField=Ed,ge.fieldGridShellFillsCellVertically=Is,ge.formBuilderHttp=dn,ge.formLayoutRecordToGridConfig=Ns,ge.getBusinessApiOrigin=Np,ge.getClientId=Tn,ge.getRendererHostAuthHeaders=Ml,ge.getRendererHostViewerContext=bC,ge.getRendererStore=ev,ge.gridCellFlexClasses=Sd,ge.gridCellFlexClassesForField=Na,ge.gridCellOuterFlexClasses=wd,ge.hasExplicitFieldBlockWidth=Cd,ge.isAsyncSearchFieldProperties=HT,ge.isIntrinsicWidthButtonField=to,ge.normalizeWorkflowFormSchema=Zk,ge.normalizeWorkflowFormToRendererSchema=Yi,ge.pageBuilderHttp=vs,ge.parseContentVerticalAlign=Aa,ge.parseMetadataJson=ys,ge.resetRendererHostAuth=yC,ge.resolveBusinessApiUrl=cn,ge.resolveFormGridLayout=_s,ge.resolvePage=ry,ge.resolvedGridCellVerticalJustifyClasses=jo,ge.resolvedHorizontalAlign=Fr,ge.resolvedVerticalAlign=$o,ge.resolvedVerticalAlignForField=Ea,ge.setBusinessApiOrigin=UA,ge.setFormBuilderAuthProvider=vC,ge.setPageBuilderAuthProvider=tF,ge.setRendererHostAuthHeaders=gC,ge.setRendererHostViewerContext=hC,ge.useFieldValidation=RT,ge.useFormRenderer=Vd,ge.useFormValidation=WT,ge.useRendererFieldLayout=zo,ge.useRendererHostAuthStore=Rn,Object.defineProperty(ge,Symbol.toStringTag,{value:"Module"})}));