iq-line-form-builder-renderer 1.2.3 → 1.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/form-renderer.es.js +587 -555
- package/dist/form-renderer.umd.js +4 -4
- package/dist/pages/systemAdmin/modules/formbuilder/components/fields/BillingGridField.d.ts.map +1 -1
- package/dist/pages/systemAdmin/modules/formbuilder/types/field.d.ts +19 -20
- package/dist/pages/systemAdmin/modules/formbuilder/types/field.d.ts.map +1 -1
- package/dist/pages/systemAdmin/modules/formbuilder/utils/billingGridTextStyle.d.ts +4 -1
- package/dist/pages/systemAdmin/modules/formbuilder/utils/billingGridTextStyle.d.ts.map +1 -1
- package/package.json +1 -1
|
@@ -43,10 +43,10 @@
|
|
|
43
43
|
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...r){const n=new this(t);return r.forEach(o=>n.set(o)),n}static accessor(t){const n=(this[op]=this[op]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=os(i);n[a]||(uA(o,i),n[a]=!0)}return R.isArray(t)?t.forEach(s):s(t),this}};mr.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),R.reduceDescriptors(mr.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}}),R.freezeMethods(mr);function Nl(e,t){const r=this||ns,n=t||r,o=mr.from(n.headers);let s=n.data;return R.forEach(e,function(a){s=a.call(r,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function sp(e){return!!(e&&e.__CANCEL__)}let ss=class extends qe{constructor(t,r,n){super(t??"canceled",qe.ERR_CANCELED,r,n),this.name="CanceledError",this.__CANCEL__=!0}};function ip(e,t,r){const n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new qe("Request failed with status code "+r.status,[qe.ERR_BAD_REQUEST,qe.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function fA(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function pA(e,t){e=e||10;const r=new Array(e),n=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(d){const u=Date.now(),l=n[s];i||(i=u),r[o]=d,n[o]=u;let f=s,p=0;for(;f!==o;)p+=r[f++],f=f%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),u-i<t)return;const m=l&&u-l;return m?Math.round(p*1e3/m):void 0}}function mA(e,t){let r=0,n=1e3/t,o,s;const i=(u,l=Date.now())=>{r=l,o=null,s&&(clearTimeout(s),s=null),e(...u)};return[(...u)=>{const l=Date.now(),f=l-r;f>=n?i(u,l):(o=u,s||(s=setTimeout(()=>{s=null,i(o)},n-f)))},()=>o&&i(o)]}const xi=(e,t,r=3)=>{let n=0;const o=pA(50,250);return mA(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,d=i-n,u=o(d),l=i<=a;n=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:d,rate:u||void 0,estimated:u&&a&&l?(a-i)/u:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(f)},r)},ap=(e,t)=>{const r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},lp=e=>(...t)=>R.asap(()=>e(...t)),hA=nr.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,nr.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(nr.origin),nr.navigator&&/(msie|trident)/i.test(nr.navigator.userAgent)):()=>!0,gA=nr.hasStandardBrowserEnv?{write(e,t,r,n,o,s,i){if(typeof document>"u")return;const a=[`${e}=${encodeURIComponent(t)}`];R.isNumber(r)&&a.push(`expires=${new Date(r).toUTCString()}`),R.isString(n)&&a.push(`path=${n}`),R.isString(o)&&a.push(`domain=${o}`),s===!0&&a.push("secure"),R.isString(i)&&a.push(`SameSite=${i}`),document.cookie=a.join("; ")},read(e){if(typeof document>"u")return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function yA(e){return typeof e!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function bA(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function cp(e,t,r){let n=!yA(t);return e&&(n||r==!1)?bA(e,t):t}const dp=e=>e instanceof mr?{...e}:e;function Hn(e,t){t=t||{};const r={};function n(u,l,f,p){return R.isPlainObject(u)&&R.isPlainObject(l)?R.merge.call({caseless:p},u,l):R.isPlainObject(l)?R.merge({},l):R.isArray(l)?l.slice():l}function o(u,l,f,p){if(R.isUndefined(l)){if(!R.isUndefined(u))return n(void 0,u,f,p)}else return n(u,l,f,p)}function s(u,l){if(!R.isUndefined(l))return n(void 0,l)}function i(u,l){if(R.isUndefined(l)){if(!R.isUndefined(u))return n(void 0,u)}else return n(void 0,l)}function a(u,l,f){if(f in t)return n(u,l);if(f in e)return n(void 0,u)}const d={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(u,l,f)=>o(dp(u),dp(l),f,!0)};return R.forEach(Object.keys({...e,...t}),function(l){if(l==="__proto__"||l==="constructor"||l==="prototype")return;const f=R.hasOwnProp(d,l)?d[l]:o,p=f(e[l],t[l],l);R.isUndefined(p)&&f!==a||(r[l]=p)}),r}const up=e=>{const t=Hn({},e);let{data:r,withXSRFToken:n,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=mr.from(i),t.url=tp(cp(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),R.isFormData(r)){if(nr.hasStandardBrowserEnv||nr.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(R.isFunction(r.getHeaders)){const d=r.getHeaders(),u=["content-type","content-length"];Object.entries(d).forEach(([l,f])=>{u.includes(l.toLowerCase())&&i.set(l,f)})}}if(nr.hasStandardBrowserEnv&&(n&&R.isFunction(n)&&(n=n(t)),n||n!==!1&&hA(t.url))){const d=o&&s&&gA.read(s);d&&i.set(o,d)}return t},vA=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(r,n){const o=up(e);let s=o.data;const i=mr.from(o.headers).normalize();let{responseType:a,onUploadProgress:d,onDownloadProgress:u}=o,l,f,p,m,g;function h(){m&&m(),g&&g(),o.cancelToken&&o.cancelToken.unsubscribe(l),o.signal&&o.signal.removeEventListener("abort",l)}let y=new XMLHttpRequest;y.open(o.method.toUpperCase(),o.url,!0),y.timeout=o.timeout;function v(){if(!y)return;const x=mr.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),P={data:!a||a==="text"||a==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:x,config:e,request:y};ip(function(N){r(N),h()},function(N){n(N),h()},P),y=null}"onloadend"in y?y.onloadend=v:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(v)},y.onabort=function(){y&&(n(new qe("Request aborted",qe.ECONNABORTED,e,y)),y=null)},y.onerror=function(E){const P=E&&E.message?E.message:"Network Error",C=new qe(P,qe.ERR_NETWORK,e,y);C.event=E||null,n(C),y=null},y.ontimeout=function(){let E=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const P=o.transitional||xl;o.timeoutErrorMessage&&(E=o.timeoutErrorMessage),n(new qe(E,P.clarifyTimeoutError?qe.ETIMEDOUT:qe.ECONNABORTED,e,y)),y=null},s===void 0&&i.setContentType(null),"setRequestHeader"in y&&R.forEach(i.toJSON(),function(E,P){y.setRequestHeader(P,E)}),R.isUndefined(o.withCredentials)||(y.withCredentials=!!o.withCredentials),a&&a!=="json"&&(y.responseType=o.responseType),u&&([p,g]=xi(u,!0),y.addEventListener("progress",p)),d&&y.upload&&([f,m]=xi(d),y.upload.addEventListener("progress",f),y.upload.addEventListener("loadend",m)),(o.cancelToken||o.signal)&&(l=x=>{y&&(n(!x||x.type?new ss(null,e,y):x),y.abort(),y=null)},o.cancelToken&&o.cancelToken.subscribe(l),o.signal&&(o.signal.aborted?l():o.signal.addEventListener("abort",l)));const w=fA(o.url);if(w&&nr.protocols.indexOf(w)===-1){n(new qe("Unsupported protocol "+w+":",qe.ERR_BAD_REQUEST,e));return}y.send(s||null)})},wA=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let n=new AbortController,o;const s=function(u){if(!o){o=!0,a();const l=u instanceof Error?u:this.reason;n.abort(l instanceof qe?l:new ss(l instanceof Error?l.message:l))}};let i=t&&setTimeout(()=>{i=null,s(new qe(`timeout of ${t}ms exceeded`,qe.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(u=>{u.unsubscribe?u.unsubscribe(s):u.removeEventListener("abort",s)}),e=null)};e.forEach(u=>u.addEventListener("abort",s));const{signal:d}=n;return d.unsubscribe=()=>R.asap(a),d}},SA=function*(e,t){let r=e.byteLength;if(r<t){yield e;return}let n=0,o;for(;n<r;)o=n+t,yield e.slice(n,o),n=o},xA=async function*(e,t){for await(const r of AA(e))yield*SA(r,t)},AA=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:r,value:n}=await t.read();if(r)break;yield n}}finally{await t.cancel()}},fp=(e,t,r,n)=>{const o=xA(e,t);let s=0,i,a=d=>{i||(i=!0,n&&n(d))};return new ReadableStream({async pull(d){try{const{done:u,value:l}=await o.next();if(u){a(),d.close();return}let f=l.byteLength;if(r){let p=s+=f;r(p)}d.enqueue(new Uint8Array(l))}catch(u){throw a(u),u}},cancel(d){return a(d),o.return()}},{highWaterMark:2})},pp=64*1024,{isFunction:Ai}=R,CA=(({Request:e,Response:t})=>({Request:e,Response:t}))(R.global),{ReadableStream:mp,TextEncoder:hp}=R.global,gp=(e,...t)=>{try{return!!e(...t)}catch{return!1}},EA=e=>{e=R.merge.call({skipUndefined:!0},CA,e);const{fetch:t,Request:r,Response:n}=e,o=t?Ai(t):typeof fetch=="function",s=Ai(r),i=Ai(n);if(!o)return!1;const a=o&&Ai(mp),d=o&&(typeof hp=="function"?(g=>h=>g.encode(h))(new hp):async g=>new Uint8Array(await new r(g).arrayBuffer())),u=s&&a&&gp(()=>{let g=!1;const h=new mp,y=new r(nr.origin,{body:h,method:"POST",get duplex(){return g=!0,"half"}}).headers.has("Content-Type");return h.cancel(),g&&!y}),l=i&&a&&gp(()=>R.isReadableStream(new n("").body)),f={stream:l&&(g=>g.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(g=>{!f[g]&&(f[g]=(h,y)=>{let v=h&&h[g];if(v)return v.call(h);throw new qe(`Response type '${g}' is not supported`,qe.ERR_NOT_SUPPORT,y)})});const p=async g=>{if(g==null)return 0;if(R.isBlob(g))return g.size;if(R.isSpecCompliantForm(g))return(await new r(nr.origin,{method:"POST",body:g}).arrayBuffer()).byteLength;if(R.isArrayBufferView(g)||R.isArrayBuffer(g))return g.byteLength;if(R.isURLSearchParams(g)&&(g=g+""),R.isString(g))return(await d(g)).byteLength},m=async(g,h)=>{const y=R.toFiniteNumber(g.getContentLength());return y??p(h)};return async g=>{let{url:h,method:y,data:v,signal:w,cancelToken:x,timeout:E,onDownloadProgress:P,onUploadProgress:C,responseType:N,headers:_,withCredentials:A="same-origin",fetchOptions:I}=up(g),T=t||fetch;N=N?(N+"").toLowerCase():"text";let W=wA([w,x&&x.toAbortSignal()],E),J=null;const O=W&&W.unsubscribe&&(()=>{W.unsubscribe()});let j;try{if(C&&u&&y!=="get"&&y!=="head"&&(j=await m(_,v))!==0){let ie=new r(h,{method:"POST",body:v,duplex:"half"}),V;if(R.isFormData(v)&&(V=ie.headers.get("content-type"))&&_.setContentType(V),ie.body){const[K,X]=ap(j,xi(lp(C)));v=fp(ie.body,pp,K,X)}}R.isString(A)||(A=A?"include":"omit");const M=s&&"credentials"in r.prototype,D={...I,signal:W,method:y.toUpperCase(),headers:_.normalize().toJSON(),body:v,duplex:"half",credentials:M?A:void 0};J=s&&new r(h,D);let L=await(s?T(J,I):T(h,D));const U=l&&(N==="stream"||N==="response");if(l&&(P||U&&O)){const ie={};["status","statusText","headers"].forEach(ce=>{ie[ce]=L[ce]});const V=R.toFiniteNumber(L.headers.get("content-length")),[K,X]=P&&ap(V,xi(lp(P),!0))||[];L=new n(fp(L.body,pp,K,()=>{X&&X(),O&&O()}),ie)}N=N||"text";let $=await f[R.findKey(f,N)||"text"](L,g);return!U&&O&&O(),await new Promise((ie,V)=>{ip(ie,V,{data:$,headers:mr.from(L.headers),status:L.status,statusText:L.statusText,config:g,request:J})})}catch(M){throw O&&O(),M&&M.name==="TypeError"&&/Load failed|fetch/i.test(M.message)?Object.assign(new qe("Network Error",qe.ERR_NETWORK,g,J,M&&M.response),{cause:M.cause||M}):qe.from(M,M&&M.code,g,J,M&&M.response)}}},NA=new Map,yp=e=>{let t=e&&e.env||{};const{fetch:r,Request:n,Response:o}=t,s=[n,o,r];let i=s.length,a=i,d,u,l=NA;for(;a--;)d=s[a],u=l.get(d),u===void 0&&l.set(d,u=a?new Map:EA(t)),l=u;return u};yp();const _l={http:q0,xhr:vA,fetch:{get:yp}};R.forEach(_l,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const bp=e=>`- ${e}`,_A=e=>R.isFunction(e)||e===null||e===!1;function kA(e,t){e=R.isArray(e)?e:[e];const{length:r}=e;let n,o;const s={};for(let i=0;i<r;i++){n=e[i];let a;if(o=n,!_A(n)&&(o=_l[(a=String(n)).toLowerCase()],o===void 0))throw new qe(`Unknown adapter '${a}'`);if(o&&(R.isFunction(o)||(o=o.get(t))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([d,u])=>`adapter ${d} `+(u===!1?"is not supported by the environment":"is not available in the build"));let a=r?i.length>1?`since :
|
|
44
44
|
`+i.map(bp).join(`
|
|
45
45
|
`):" "+bp(i[0]):"as no adapter specified";throw new qe("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o}const vp={getAdapter:kA,adapters:_l};function kl(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ss(null,e)}function wp(e){return kl(e),e.headers=mr.from(e.headers),e.data=Nl.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),vp.getAdapter(e.adapter||ns.adapter,e)(e).then(function(n){return kl(e),n.data=Nl.call(e,e.transformResponse,n),n.headers=mr.from(n.headers),n},function(n){return sp(n)||(kl(e),n&&n.response&&(n.response.data=Nl.call(e,e.transformResponse,n.response),n.response.headers=mr.from(n.response.headers))),Promise.reject(n)})}const Sp="1.14.0",Ci={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Ci[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const xp={};Ci.transitional=function(t,r,n){function o(s,i){return"[Axios v"+Sp+"] Transitional option '"+s+"'"+i+(n?". "+n:"")}return(s,i,a)=>{if(t===!1)throw new qe(o(i," has been removed"+(r?" in "+r:"")),qe.ERR_DEPRECATED);return r&&!xp[i]&&(xp[i]=!0,console.warn(o(i," has been deprecated since v"+r+" and will be removed in the near future"))),t?t(s,i,a):!0}},Ci.spelling=function(t){return(r,n)=>(console.warn(`${n} is likely a misspelling of ${t}`),!0)};function TA(e,t,r){if(typeof e!="object")throw new qe("options must be an object",qe.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let o=n.length;for(;o-- >0;){const s=n[o],i=t[s];if(i){const a=e[s],d=a===void 0||i(a,s,e);if(d!==!0)throw new qe("option "+s+" must be "+d,qe.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new qe("Unknown option "+s,qe.ERR_BAD_OPTION)}}const Ei={assertOptions:TA,validators:Ci},Or=Ei.validators;let Wn=class{constructor(t){this.defaults=t||{},this.interceptors={request:new rp,response:new rp}}async request(t,r){try{return await this._request(t,r)}catch(n){if(n instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{n.stack?s&&!String(n.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(n.stack+=`
|
|
46
|
-
`+s):n.stack=s}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=Hn(this.defaults,r);const{transitional:n,paramsSerializer:o,headers:s}=r;n!==void 0&&Ei.assertOptions(n,{silentJSONParsing:Or.transitional(Or.boolean),forcedJSONParsing:Or.transitional(Or.boolean),clarifyTimeoutError:Or.transitional(Or.boolean),legacyInterceptorReqResOrdering:Or.transitional(Or.boolean)},!1),o!=null&&(R.isFunction(o)?r.paramsSerializer={serialize:o}:Ei.assertOptions(o,{encode:Or.function,serialize:Or.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Ei.assertOptions(r,{baseUrl:Or.spelling("baseURL"),withXsrfToken:Or.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let i=s&&R.merge(s.common,s[r.method]);s&&R.forEach(["delete","get","head","post","put","patch","common"],g=>{delete s[g]}),r.headers=mr.concat(i,s);const a=[];let d=!0;this.interceptors.request.forEach(function(h){if(typeof h.runWhen=="function"&&h.runWhen(r)===!1)return;d=d&&h.synchronous;const y=r.transitional||xl;y&&y.legacyInterceptorReqResOrdering?a.unshift(h.fulfilled,h.rejected):a.push(h.fulfilled,h.rejected)});const u=[];this.interceptors.response.forEach(function(h){u.push(h.fulfilled,h.rejected)});let l,f=0,p;if(!d){const g=[wp.bind(this),void 0];for(g.unshift(...a),g.push(...u),p=g.length,l=Promise.resolve(r);f<p;)l=l.then(g[f++],g[f++]);return l}p=a.length;let m=r;for(;f<p;){const g=a[f++],h=a[f++];try{m=g(m)}catch(y){h.call(this,y);break}}try{l=wp.call(this,m)}catch(g){return Promise.reject(g)}for(f=0,p=u.length;f<p;)l=l.then(u[f++],u[f++]);return l}getUri(t){t=Hn(this.defaults,t);const r=cp(t.baseURL,t.url,t.allowAbsoluteUrls);return tp(r,t.params,t.paramsSerializer)}};R.forEach(["delete","get","head","options"],function(t){Wn.prototype[t]=function(r,n){return this.request(Hn(n||{},{method:t,url:r,data:(n||{}).data}))}}),R.forEach(["post","put","patch"],function(t){function r(n){return function(s,i,a){return this.request(Hn(a||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Wn.prototype[t]=r(),Wn.prototype[t+"Form"]=r(!0)});let FA=class Fy{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(s){r=s});const n=this;this.promise.then(o=>{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](o);n._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{n.subscribe(a),s=a}).then(o);return i.cancel=function(){n.unsubscribe(s)},i},t(function(s,i,a){n.reason||(n.reason=new ss(s,i,a),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new Fy(function(o){t=o}),cancel:t}}};function PA(e){return function(r){return e.apply(null,r)}}function OA(e){return R.isObject(e)&&e.isAxiosError===!0}const Tl={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Tl).forEach(([e,t])=>{Tl[t]=e});function Ap(e){const t=new Wn(e),r=Uf(Wn.prototype.request,t);return R.extend(r,Wn.prototype,t,{allOwnKeys:!0}),R.extend(r,t,null,{allOwnKeys:!0}),r.create=function(o){return Ap(Hn(e,o))},r}const _t=Ap(ns);_t.Axios=Wn,_t.CanceledError=ss,_t.CancelToken=FA,_t.isCancel=sp,_t.VERSION=Sp,_t.toFormData=wi,_t.AxiosError=qe,_t.Cancel=_t.CanceledError,_t.all=function(t){return Promise.all(t)},_t.spread=PA,_t.isAxiosError=OA,_t.mergeConfig=Hn,_t.AxiosHeaders=mr,_t.formToJSON=e=>np(R.isHTMLForm(e)?new FormData(e):e),_t.getAdapter=vp.getAdapter,_t.HttpStatusCode=Tl,_t.default=_t;const{Axios:LP,AxiosError:IA,CanceledError:DP,isCancel:BP,CancelToken:$P,VERSION:jP,all:zP,Cancel:UP,isAxiosError:VP,spread:HP,toFormData:WP,AxiosHeaders:RP,HttpStatusCode:GP,formToJSON:KP,getAdapter:qP,mergeConfig:YP}=_t;function or(e,t){if(!t||t.trim()===""||e==null)return;const r=t.split(".").filter(Boolean);let n=e;for(const o of r){if(n==null)return;n=n[o]}return n}function MA(e){const t={array:[],pathPrefixToStrip:""};function r(a,d){if(a===null||typeof a!="object")return null;if(Array.isArray(a)&&a.length>0)return{array:a,fullPath:d};const u=Object.keys(a);for(const l of u){const f=a[l],p=d?`${d}.${l}`:l;if(Array.isArray(f)&&f.length>0)return{array:f,fullPath:p};if(f!==null&&typeof f=="object"){const m=r(f,p);if(m)return m}}return null}const n=r(e,"");if(!n)return t;const{array:o,fullPath:s}=n,i=s?`data.${s}.`:"";return{array:o,pathPrefixToStrip:i}}function LA(e){return e.length>=4&&Array.isArray(e[3])&&e[3].length===0}function DA(e,t,r){if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"){const s=String(e);return{label:s,value:s,disabled:!1}}if(e==null)return{label:"",value:"",disabled:!0};if(typeof e!="object"||Array.isArray(e)){const s=Array.isArray(e)?"":String(e);return{label:s,value:s,disabled:!1}}let n,o;if(t){const s=t.includes(".")?or(e,t):e[t];n=String(s!==void 0?s:e.label??e.name??e.title??e.text??e.username??e.email??e.value??e.id??"")}else n=String(e.label??e.name??e.title??e.text??e.username??e.email??e.value??e.id??"");if(r){const s=r.includes(".")?or(e,r):e[r];o=String(s!==void 0?s:e.value??e.id??e.key??e.email??e.username??e.label??e.name??"")}else o=String(e.value??e.id??e.key??e.email??e.username??e.label??e.name??"");return{label:String(n??""),value:String(o??""),disabled:!!e.disabled}}function Fl(e,t,r){if(!e)return[];if(Array.isArray(e)){if(e.length===0)return[];if(LA(e))return[];const n=e.filter(o=>o!=null);return n.length===0?[]:n.every(o=>typeof o=="string")?n.map(o=>({label:o,value:o,disabled:!1})):n.map(o=>DA(o,t,r))}if(typeof e=="object"){const{array:n,pathPrefixToStrip:o}=MA(e);if(Array.isArray(n)&&n.length>0){const s=d=>!d||!d.trim()||!o?d:d.startsWith(o)?d.substring(o.length).replace(/^\.+/,"")||void 0:d,i=s(t),a=s(r);return Fl(n,i,a)}}return[]}function BA(e){return!Array.isArray(e)||e.length===0?[]:e.filter(t=>t!=null).map((t,r)=>{if(typeof t=="string")return{label:t,value:t};if(typeof t=="object"&&t!==null){const n=t.label||t.value||String(t),o=t.value||t.label||String(t);return!n&&!o?{label:`Option ${r+1}`,value:String(r)}:{label:String(n),value:String(o),disabled:t.disabled||!1}}return{label:String(t),value:String(t)}})}function $A(e){return Array.isArray(e)&&e.length>=4&&Array.isArray(e[3])&&e[3].length>0&&Array.isArray(e[3][0])}function jA(e,t,r){if(!e)return[];try{const o=new URL(e).searchParams.get(t);return o?o.split(r).map(s=>s.trim()).filter(Boolean):[]}catch{const n=e.indexOf("?");if(n<0)return[];const o=e.slice(n+1);try{const i=new URLSearchParams(o).get(t);return i?i.split(r).map(a=>a.trim()).filter(Boolean):[]}catch{return[]}}}function Cp(e){const{response:t,sourceUrl:r,rowsIndex:n,rowsPath:o,columns:s,columnsQueryParam:i="sf",columnsQueryParamSeparator:a=","}=e;let d;if(o&&o.trim()?d=or(t,o):typeof n=="number"?d=t?.[n]:d=t,!Array.isArray(d)||d.length===0)return[];const u=d.filter(p=>Array.isArray(p));if(u.length===0)return Array.isArray(d[0])?[]:null;if(!Array.isArray(u[0]))return null;const l=jA(r,i,a),f=l.length>0?l:Array.isArray(s)&&s.length>0?s:[];return u.map(p=>{const m={};return(f.length>0?f:Array.from({length:p.length},(h,y)=>`col${y}`)).forEach((h,y)=>{m[h]=p[y]}),m})}function zA(e){const{rows:t,apiLabelField:r,apiLabelFields:n,apiLabelSeparator:o,apiValueField:s}=e;if(!Array.isArray(t)||t.length===0)return[];const i=t.filter(f=>f!=null&&typeof f=="object"&&!Array.isArray(f));if(i.length===0)return[];const a=Array.isArray(n)?n.filter(Boolean):[],d=o??" - ",u=f=>{if(r){const p=r.includes(".")?or(f,r):f?.[r];if(p!=null&&String(p).trim()!=="")return String(p)}return String(f?.label??f?.name??f?.title??f?.text??f?.username??f?.email??f?.value??f?.id??f)},l=(f,p)=>{if(s){const m=s.includes(".")?or(f,s):f?.[s];if(m!=null)return String(m)}return String(f?.value??f?.id??f?.key??f?.email??f?.username??f?.label??f?.name??p??f)};return i.map(f=>{let p="";a.length>0&&(p=a.map(h=>or(f,h)).filter(h=>h!=null&&String(h).trim()!=="").map(h=>String(h)).join(d)),p||(p=u(f));const m=l(f,p);return{label:typeof p=="string"?p:String(p??""),value:typeof m=="string"?m:String(m??""),disabled:!!f?.disabled}})}let Ep=null;function UA(e){Ep=e}function Np(){return(Ep?.()??"").replace(/\/+$/,"")}function cn(e){const t=typeof e=="string"?e.trim():"";if(!t||/^https?:\/\//i.test(t))return t;const r=Np();return r?t.startsWith("/")?`${r}${t}`:`${r}/${t}`:t}function _p({field:e,formValues:t={},submissionContext:r}){const n=e.properties,o=n?.apiEndpoint?{apiEndpoint:n.apiEndpoint,apiMethod:n.apiMethod,apiKey:n.apiKey,apiRealtime:n.apiRealtime,apiAutoDetect:n.apiAutoDetect,apiLabelField:n.apiLabelField,apiValueField:n.apiValueField,apiQueryParams:n.apiQueryParams,apiClientFilter:n.apiClientFilter,valueSource:n.valueSource,optionsSource:n.optionsSource}:null,s=e.apidata||null,i=o||s,[a,d]=S.useState([]),[u,l]=S.useState([]),[f,p]=S.useState([]),[m,g]=S.useState(!1),[h,y]=S.useState(null),v=!!(i?.apiEndpoint&&(i?.valueSource==="api"||i?.optionsSource==="api"||n?.valueSource==="api"||n?.optionsSource==="api")),w=e.options||n?.options||[],x=S.useMemo(()=>BA(Array.isArray(w)?w:[]),[w]),E=S.useMemo(()=>{const I=i?.apiEndpoint||n?.apiEndpoint||"",T=i?.apiQueryParams||n?.apiQueryParams;return $s(I,T)},[i?.apiEndpoint,n?.apiEndpoint,i?.apiQueryParams,n?.apiQueryParams]),P=S.useMemo(()=>{const I=new Set;for(const W of n?.dependentFields??[])typeof W=="string"&&W.trim()&&I.add(W.trim());const T=i?.apiClientFilter?.matchField?.trim()||n?.apiClientFilter?.matchField?.trim();return T&&I.add(T),[...I]},[n?.dependentFields,i?.apiClientFilter?.matchField,n?.apiClientFilter?.matchField]),C=S.useMemo(()=>{const I=new Set([...E,...P]);if(I.size===0)return null;const T={};return I.forEach(W=>{T[W]=t[W]}),JSON.stringify(T)},[E,P,t]),N=S.useMemo(()=>JSON.stringify(r||{}),[r]),_=S.useMemo(()=>{const I=new Set;e.name?.trim()&&I.add(e.name.trim());const T=e.key;return typeof T=="string"&&T.trim()&&I.add(T.trim()),[...I]},[e.name,e.key]);return S.useEffect(()=>{const I=i?.apiEndpoint;if(!v||!I){d([]);return}let T=!1;return(async()=>{a.length===0&&g(!0),y(null);try{const O=i?.apiMethod||n?.apiMethod||"GET",j=i?.apiRealtime||n?.apiRealtime,M=i?.apiQueryParams||n?.apiQueryParams||{},D=zd({apiEndpoint:I,apiMethod:O,apiQueryParams:M,formValues:t,submissionContext:r,apiRealtime:j,additionalRequiredFieldNames:P,excludeFormFieldNames:_});if(D.blocked){T||(d([]),g(!1));return}const L={"Content-Type":"application/json"},U=i?.apiKey||n?.apiKey;U&&(L["X-CSCAPI-KEY"]=U);const $={method:O.toLowerCase(),url:cn(D.url),headers:L};D.postBodyBase!=null&&($.data=D.postBodyBase);const ie=await _t($),V=i?.apiLabelField||n?.apiLabelField,K=i?.apiValueField||n?.apiValueField,X=ie.data;let ce=[];Array.isArray(X)?ce=X:X?.data&&(Array.isArray(X.data)?ce=X.data:X.data?.data&&Array.isArray(X.data.data)?ce=X.data.data:X.data.districts?ce=X.data.districts:X.data.states?ce=X.data.states:X.data.cities&&(ce=X.data.cities)),p(ce);const ne=Fl(ie.data,V,K);l(ne);const G=i?.apiClientFilter||n?.apiClientFilter;let ee=ne;if(G?.filterField&&G?.matchField){const Pe=t[G.matchField];Pe!=null?ee=ne.filter(oe=>{const re=ce.find(de=>String(or(de,K||"code"))===String(oe.value));if(!re)return!1;const be=or(re,G.filterField);return String(be)===String(Pe)}):ee=[]}T||d(ee)}catch(O){if(T)return;let j="Failed to load options";if(O.response){const M=O.response.data;O.response.status===404?j="API endpoint not found.":O.response.status===401?j="Authentication failed.":typeof M=="string"?j=M:M&&typeof M=="object"&&(j=M.error||M.message||M.detail||j)}else O.message&&(j=String(O.message));y(j),a.length===0&&d([])}finally{T||g(!1)}})(),()=>{T=!0}},[v,i?.apiEndpoint,i?.apiMethod,n?.apiEndpoint,n?.apiMethod,C,P,_,N]),S.useEffect(()=>{const I=i?.apiClientFilter||n?.apiClientFilter;if(!v||!I||f.length===0)return;const T=t[I.matchField],W=i?.apiValueField||n?.apiValueField;if(T==null){d([]);return}const J=u.filter(O=>{const j=f.find(D=>String(or(D,W||"code"))===String(O.value));if(!j)return!1;const M=or(j,I.filterField);return String(M)===String(T)});d(J)},[v,i?.apiClientFilter?.matchField,n?.apiClientFilter?.matchField,i?.apiClientFilter?.filterField,n?.apiClientFilter?.filterField,i?.apiValueField,n?.apiValueField,t[i?.apiClientFilter?.matchField||n?.apiClientFilter?.matchField||""],u,f]),{options:v?a:x,isLoadingOptions:m,optionsError:h}}const kp=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a,formValues:d={},submissionContext:u,excludedOptionValues:l,isPrepopulateTarget:f=!1})=>{const p=e.properties,m=p?.apiEndpoint?{apiEndpoint:p.apiEndpoint,valueSource:p.valueSource,optionsSource:p.optionsSource}:null,g=e.apidata||null,h=m||g,y=!!(h?.apiEndpoint&&(h?.valueSource==="api"||h?.optionsSource==="api"||p?.valueSource==="api"||p?.optionsSource==="api")),{options:v,isLoadingOptions:w,optionsError:x}=_p({field:e,formValues:d,submissionContext:u}),E=l?.length?new Set(l.map(String)):null,P=E?v.filter($=>!E.has(String($.value??$.label??""))):v,C="__clear__",N=t!=null&&String(t).trim()!=="",_=N?P.some($=>String($.value??$.label??"")===String(t)):!1,A=S.useMemo(()=>{if(!N||_)return P;const $=String(t);return[{label:$,value:$},...P]},[P,N,_,t]),I=N?String(t):void 0,T=`${ht(e)}-${I??"empty"}`,W=S.useCallback($=>{r($===C?"":$),n?.()},[r,n]),J=e.appearance?.size||"md",O={sm:"h-8 text-sm",md:"h-10",lg:"h-12 text-lg"},j=e.placeholder||"Select an option",M=p?.apiClientFilter?.matchField?.trim()||h?.apiClientFilter?.matchField?.trim(),D=y&&M&&(d[M]===void 0||d[M]===null||d[M]===""),L=w?"Loading options...":D?`Select ${M} first`:l?.length?"No available options":y?"No options available from API":"No options available";return y&&f&&w?c.jsx(Et,{field:e,error:o||x||void 0,isRequired:i,className:a,children:c.jsxs("div",{role:"status","aria-label":"Loading options",className:B("flex items-center justify-center gap-2 w-full min-w-0 rounded-md border border-input bg-muted/50 text-muted-foreground",O[J],e.appearance?.className),children:[c.jsx(Ro,{className:"h-4 w-4 animate-spin shrink-0"}),c.jsx("span",{className:"truncate",children:"Loading..."})]})}):c.jsx(Et,{field:e,error:o||x||void 0,isRequired:i,className:a,children:c.jsxs(t0,{value:I,onValueChange:W,disabled:s||e.disabled||w&&P.length===0,children:[c.jsx(n0,{id:ht(e),"aria-describedby":jt(e,!!o||!!x),"aria-invalid":Jt(!!o||!!x),"aria-required":i,className:B("w-full min-w-0",O[J],o&&"border-destructive focus-visible:ring-destructive",x&&"border-destructive focus-visible:ring-destructive",e.appearance?.className),children:c.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[w&&c.jsx(Ro,{className:"h-4 w-4 animate-spin text-muted-foreground shrink-0"}),P.length===0&&l?.length&&!N?c.jsx("span",{className:"text-muted-foreground truncate",children:"No available options"}):N?c.jsx(r0,{placeholder:j}):c.jsx("span",{className:"text-muted-foreground truncate",children:j})]})}),c.jsx(o0,{children:A.length===0?c.jsx(gl,{value:"__no_options__",disabled:!0,children:L}):c.jsxs(c.Fragment,{children:[N?c.jsx(gl,{value:C,children:j}):null,A.map(($,ie)=>{const V=String($.value??$.label??ie);if(V===C)return null;const K=$.label||$.value||String($);return c.jsx(gl,{value:V,disabled:$.disabled||!1,children:K},V)})]})})]},T)})},Tp=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Fp=Jc,Pp=(e,t)=>r=>{var n;if(t?.variants==null)return Fp(e,r?.class,r?.className);const{variants:o,defaultVariants:s}=t,i=Object.keys(o).map(u=>{const l=r?.[u],f=s?.[u];if(l===null)return null;const p=Tp(l)||Tp(f);return o[u][p]}),a=r&&Object.entries(r).reduce((u,l)=>{let[f,p]=l;return p===void 0||(u[f]=p),u},{}),d=t==null||(n=t.compoundVariants)===null||n===void 0?void 0:n.reduce((u,l)=>{let{class:f,className:p,...m}=l;return Object.entries(m).every(g=>{let[h,y]=g;return Array.isArray(y)?y.includes({...s,...a}[h]):{...s,...a}[h]===y})?[...u,f,p]:u},[]);return Fp(e,i,d,r?.class,r?.className)},VA=Pp("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all cursor-pointer disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",destructive:"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}});function Yt({className:e,variant:t,size:r,asChild:n=!1,...o}){const s=n?qd:"button";return c.jsx(s,{"data-slot":"button",className:B(VA({variant:t,size:r,className:e})),...o})}function HA(e,t){return b.useReducer((r,n)=>t[r][n]??r,e)}var xr=e=>{const{present:t,children:r}=e,n=WA(t),o=typeof r=="function"?r({present:n.isPresent}):b.Children.only(r),s=Ze(n.ref,RA(o));return typeof r=="function"||n.isPresent?b.cloneElement(o,{ref:s}):null};xr.displayName="Presence";function WA(e){const[t,r]=b.useState(),n=b.useRef(null),o=b.useRef(e),s=b.useRef("none"),i=e?"mounted":"unmounted",[a,d]=HA(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{const u=Ni(n.current);s.current=a==="mounted"?u:"none"},[a]),Qt(()=>{const u=n.current,l=o.current;if(l!==e){const p=s.current,m=Ni(u);e?d("MOUNT"):m==="none"||u?.display==="none"?d("UNMOUNT"):d(l&&p!==m?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,d]),Qt(()=>{if(t){let u;const l=t.ownerDocument.defaultView??window,f=m=>{const h=Ni(n.current).includes(CSS.escape(m.animationName));if(m.target===t&&h&&(d("ANIMATION_END"),!o.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",u=l.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},p=m=>{m.target===t&&(s.current=Ni(n.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{l.clearTimeout(u),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:b.useCallback(u=>{n.current=u?getComputedStyle(u):null,r(u)},[])}}function Ni(e){return e?.animationName||"none"}function RA(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}function GA(e){const t=KA(e),r=b.forwardRef((n,o)=>{const{children:s,...i}=n,a=b.Children.toArray(s),d=a.find(YA);if(d){const u=d.props.children,l=a.map(f=>f===d?b.Children.count(u)>1?b.Children.only(null):b.isValidElement(u)?u.props.children:null:f);return c.jsx(t,{...i,ref:o,children:b.isValidElement(u)?b.cloneElement(u,void 0,l):null})}return c.jsx(t,{...i,ref:o,children:s})});return r.displayName=`${e}.Slot`,r}function KA(e){const t=b.forwardRef((r,n)=>{const{children:o,...s}=r;if(b.isValidElement(o)){const i=JA(o),a=XA(s,o.props);return o.type!==b.Fragment&&(a.ref=n?Bn(n,i):i),b.cloneElement(o,a)}return b.Children.count(o)>1?b.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var qA=Symbol("radix.slottable");function YA(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===qA}function XA(e,t){const r={...t};for(const n in t){const o=e[n],s=t[n];/^on[A-Z]/.test(n)?o&&s?r[n]=(...a)=>{const d=s(...a);return o(...a),d}:o&&(r[n]=o):n==="style"?r[n]={...o,...s}:n==="className"&&(r[n]=[o,s].filter(Boolean).join(" "))}return{...e,...r}}function JA(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var _i="Popover",[Op]=vr(_i,[ri]),is=ri(),[QA,kn]=Op(_i),Ip=e=>{const{__scopePopover:t,children:r,open:n,defaultOpen:o,onOpenChange:s,modal:i=!1}=e,a=is(t),d=b.useRef(null),[u,l]=b.useState(!1),[f,p]=Zr({prop:n,defaultProp:o??!1,onChange:s,caller:_i});return c.jsx(Ju,{...a,children:c.jsx(QA,{scope:t,contentId:on(),triggerRef:d,open:f,onOpenChange:p,onOpenToggle:b.useCallback(()=>p(m=>!m),[p]),hasCustomAnchor:u,onCustomAnchorAdd:b.useCallback(()=>l(!0),[]),onCustomAnchorRemove:b.useCallback(()=>l(!1),[]),modal:i,children:r})})};Ip.displayName=_i;var Mp="PopoverAnchor",Lp=b.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,o=kn(Mp,r),s=is(r),{onCustomAnchorAdd:i,onCustomAnchorRemove:a}=o;return b.useEffect(()=>(i(),()=>a()),[i,a]),c.jsx(nl,{...s,...n,ref:t})});Lp.displayName=Mp;var Dp="PopoverTrigger",Bp=b.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,o=kn(Dp,r),s=is(r),i=Ze(t,o.triggerRef),a=c.jsx(Be.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Vp(o.open),...n,ref:i,onClick:Me(e.onClick,o.onOpenToggle)});return o.hasCustomAnchor?a:c.jsx(nl,{asChild:!0,...s,children:a})});Bp.displayName=Dp;var Pl="PopoverPortal",[ZA,eC]=Op(Pl,{forceMount:void 0}),$p=e=>{const{__scopePopover:t,forceMount:r,children:n,container:o}=e,s=kn(Pl,t);return c.jsx(ZA,{scope:t,forceMount:r,children:c.jsx(xr,{present:r||s.open,children:c.jsx(ni,{asChild:!0,container:o,children:n})})})};$p.displayName=Pl;var ho="PopoverContent",jp=b.forwardRef((e,t)=>{const r=eC(ho,e.__scopePopover),{forceMount:n=r.forceMount,...o}=e,s=kn(ho,e.__scopePopover);return c.jsx(xr,{present:n||s.open,children:s.modal?c.jsx(rC,{...o,ref:t}):c.jsx(nC,{...o,ref:t})})});jp.displayName=ho;var tC=GA("PopoverContent.RemoveScroll"),rC=b.forwardRef((e,t)=>{const r=kn(ho,e.__scopePopover),n=b.useRef(null),o=Ze(t,n),s=b.useRef(!1);return b.useEffect(()=>{const i=n.current;if(i)return sl(i)},[]),c.jsx(ui,{as:tC,allowPinchZoom:!0,children:c.jsx(zp,{...e,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Me(e.onCloseAutoFocus,i=>{i.preventDefault(),s.current||r.triggerRef.current?.focus()}),onPointerDownOutside:Me(e.onPointerDownOutside,i=>{const a=i.detail.originalEvent,d=a.button===0&&a.ctrlKey===!0,u=a.button===2||d;s.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:Me(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1})})})}),nC=b.forwardRef((e,t)=>{const r=kn(ho,e.__scopePopover),n=b.useRef(!1),o=b.useRef(!1);return c.jsx(zp,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{e.onCloseAutoFocus?.(s),s.defaultPrevented||(n.current||r.triggerRef.current?.focus(),s.preventDefault()),n.current=!1,o.current=!1},onInteractOutside:s=>{e.onInteractOutside?.(s),s.defaultPrevented||(n.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;r.triggerRef.current?.contains(i)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),zp=b.forwardRef((e,t)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:o,onCloseAutoFocus:s,disableOutsidePointerEvents:i,onEscapeKeyDown:a,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:l,...f}=e,p=kn(ho,r),m=is(r);return za(),c.jsx(Rs,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:o,onUnmountAutoFocus:s,children:c.jsx(Ws,{asChild:!0,disableOutsidePointerEvents:i,onInteractOutside:l,onEscapeKeyDown:a,onPointerDownOutside:d,onFocusOutside:u,onDismiss:()=>p.onOpenChange(!1),children:c.jsx(Qu,{"data-state":Vp(p.open),role:"dialog",id:p.contentId,...m,...f,ref:t,style:{...f.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),Up="PopoverClose",oC=b.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,o=kn(Up,r);return c.jsx(Be.button,{type:"button",...n,ref:t,onClick:Me(e.onClick,()=>o.onOpenChange(!1))})});oC.displayName=Up;var sC="PopoverArrow",iC=b.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,o=is(r);return c.jsx(Zu,{...o,...n,ref:t})});iC.displayName=sC;function Vp(e){return e?"open":"closed"}var aC=Ip,lC=Lp,cC=Bp,dC=$p,uC=jp;function Ol({...e}){return c.jsx(aC,{"data-slot":"popover",...e})}function Hp({...e}){return c.jsx(cC,{"data-slot":"popover-trigger",...e})}function Il({className:e,align:t="center",sideOffset:r=4,...n}){return c.jsx(dC,{children:c.jsx(uC,{"data-slot":"popover-content",align:t,sideOffset:r,className:B("bg-popover text-popover-foreground 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 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden pointer-events-auto",e),...n})})}function fC({...e}){return c.jsx(lC,{"data-slot":"popover-anchor",...e})}const Wp={};function Tn(){const e=Wp?.VITE_CLIENT_ID?.trim()||Wp?.VITE_DEFAULT_CLIENT_ID?.trim()||null;return(typeof localStorage<"u"?localStorage.getItem("clientId"):null)||(typeof sessionStorage<"u"?sessionStorage.getItem("clientId"):null)||(typeof window<"u"?new URLSearchParams(window.location.search).get("clientId"):null)||e}function pC(e){return!e||typeof e!="object"?!1:e.userId!=null&&String(e.userId)!==""||e.userType!=null&&String(e.userType)!==""||e.role!=null&&String(e.role)!==""}function mC(e){if(!e||typeof e!="object")return;const t={};for(const[r,n]of Object.entries(e))n!==void 0&&n!==""&&(t[r]=n);return Object.keys(t).length>0?t:void 0}const Rn=Pd(e=>({viewerContext:void 0,authHeaders:void 0,_setViewerContext:t=>e({viewerContext:pC(t)?t:void 0}),_setAuthHeaders:t=>e({authHeaders:mC(t)}),_reset:()=>e({viewerContext:void 0,authHeaders:void 0})}));function hC(e){Rn.getState()._setViewerContext(e)}function gC(e){Rn.getState()._setAuthHeaders(e)}function yC(){Rn.getState()._reset()}function bC(){return Rn.getState().viewerContext}function Ml(){return Rn.getState().authHeaders}const Rp={};let Gp=null;function vC(e){Gp=e}function wC(){return(Rp?.VITE_API_BASE_URL?.trim()||Rp?.VITE_API_URL?.trim()||"").replace(/\/$/,"")}const dn=_t.create({baseURL:wC()});dn.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=Gp?.();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});function Kp(e){return JSON.stringify(e).slice(1,-1)}function qp(e){const t=e.asyncSearchValueObjectKeys;return Array.isArray(t)?t.map(r=>typeof r=="string"?r.trim():"").filter(Boolean):[]}function SC(e){return e.asyncSearchValueMode==="object"&&qp(e).length>0}function xC(e,t){const r={};for(const n of t){const o=n.trim();if(!o)continue;const s=or(e,o);s==null||typeof s=="object"?r[o]="":r[o]=String(s)}return r}function AC(e,t){const r=t.mode??"debounce",n=Math.max(0,t.intervalMs??300),[o,s]=S.useState(()=>r==="throttle"?e:""),i=S.useRef(0),a=S.useRef(void 0);return S.useEffect(()=>{if(e===""){a.current&&clearTimeout(a.current),s("");return}if(r==="debounce"){const l=setTimeout(()=>s(e),n);return()=>clearTimeout(l)}const d=Date.now(),u=d-i.current;return u>=n?(i.current=d,s(e),()=>{a.current&&clearTimeout(a.current)}):(a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i.current=Date.now(),s(e),a.current=void 0},n-u),()=>{a.current&&clearTimeout(a.current)})},[e,r,n]),o}function Ll(e,t){if(e==null||e==="")return"";if(t&&typeof e=="object"&&!Array.isArray(e)){const r=e,o=Object.keys(r).sort().map(s=>[s,r[s]??""]);return`O:${JSON.stringify(o)}`}return typeof e=="string"?`S:${e}`:""}function Dl(e,t){return e==null||e===""?!0:t&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).length===0:!1}function CC(e,t,r){return t.trim()!==""?!0:e==null||e===""?!1:r&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).length>0:typeof e=="string"&&e.length>0}function EC(e){if(_t.isAxiosError(e)){const t=e.response?.status,r=e.response?.data;if(t===404)return"Search endpoint not found.";if(t===401)return"Authentication failed.";if(r&&typeof r=="object"){const n=r,o=n.error??n.message??n.detail??n.explanation;if(typeof o=="string")return o}if(typeof r=="string")return r;if(t)return`Request failed (${t})`}return e instanceof Error?e.message:"Search failed"}function NC(e){if(e==null)return[];if(Array.isArray(e))return e;const t=e;if(!t?.data)return[];const r=t.data;return Array.isArray(r)?r:r?.data&&Array.isArray(r.data)?r.data:Array.isArray(r?.districts)?r.districts:Array.isArray(r?.states)?r.states:Array.isArray(r?.cities)?r.cities:[]}function Yp(e,t){return typeof t=="number"&&t>0?e.slice(0,t):e}function Bl(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.label=="string"&&t.value!==null&&t.value!==void 0}const Xp=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d,formValues:u={},submissionContext:l})=>{const f=e.properties||{},p=SC(f),m=f.apiEndpoint?.trim()||"",g=f.apiRealtime===!0,h=(f.apiMethod||"GET").toUpperCase()==="POST"?"POST":"GET",y=f.searchInBody===!0,v=h==="POST"||h==="GET"&&y,w=f.searchStrategy??f.searchSchedule??"debounce",x=f.searchIntervalMs??f.intervalMs??300,E=f.minQueryLength??0,P=f.maxResults,C=f.searchQueryParam||"q",N=f.clearable!==!1,_=u,[A,I]=S.useState(()=>Dl(t,p)?"":p&&typeof t=="object"&&t!==null&&!Array.isArray(t)?f.initialDisplayLabel||"":f.initialDisplayLabel||String(t)),[T,W]=S.useState(!1),[J,O]=S.useState([]),[j,M]=S.useState([]),[D,L]=S.useState([]),[U,$]=S.useState(!1),[ie,V]=S.useState(null),[K,X]=S.useState(-1),ce=S.useRef(Ll(t,p)),ne=S.useRef(Dl(t,p)?"":p&&typeof t=="object"&&t!==null&&!Array.isArray(t)?f.initialDisplayLabel||"":f.initialDisplayLabel||String(t??"")),G=S.useRef(void 0),ee=S.useRef(0),Pe=S.useRef(null),oe=AC(A,{mode:w,intervalMs:x}),re=S.useMemo(()=>J.filter(Bl),[J]);S.useEffect(()=>{if(re.length===0){K!==-1&&X(-1);return}(K<0||K>=re.length)&&X(0)},[K,re.length]);const be=S.useMemo(()=>{const te=$s(m,f.apiQueryParams),pe=new Set(te);for(const We of f.dependentFields||[])We&&pe.add(We);return pe},[m,f.apiQueryParams,f.dependentFields]),de=S.useMemo(()=>{if(be.size===0)return null;const te={};return be.forEach(pe=>{te[pe]=_[pe]}),JSON.stringify(te)},[be,_]),ot=S.useMemo(()=>JSON.stringify(u),[u]),Se=S.useMemo(()=>JSON.stringify(l||{}),[l]);S.useEffect(()=>{const te=Ll(t,p);if(te===ce.current)return;if(ce.current=te,Dl(t,p)){ne.current="",I(""),O([]),M([]),L([]),V(null),W(!1);return}const pe=f.initialDisplayLabel||(!p&&typeof t=="string"?t:"");ne.current=pe,I(pe)},[t,f.initialDisplayLabel,p]),S.useEffect(()=>{if(!m){O([]),M([]),L([]),$(!1);return}if(i||s||e.disabled){O([]),M([]),L([]),$(!1);return}const te=oe;if(te.length<E){O([]),M([]),L([]),$(!1),V(null);return}const pe=zd({apiEndpoint:m,apiMethod:h,apiQueryParams:f.apiQueryParams,formValues:_,submissionContext:l,apiRealtime:g,additionalRequiredFieldNames:f.dependentFields});if(pe.blocked){O([]),M([]),L([]),$(!1),V(null);return}Pe.current?.abort();const We=new AbortController;Pe.current=We;const Pt=++ee.current;return(async()=>{$(!0),V(null);const Te=cn(pe.url),Xe={};v&&(Xe["Content-Type"]="application/json"),f.apiKey&&(Xe["X-CSCAPI-KEY"]=f.apiKey);try{let Ue;if(!v)Ue=(await dn.get(Te,{params:{[C]:te},signal:We.signal,headers:Object.keys(Xe).length?Xe:void 0})).data;else{let It={};pe.postBodyBase&&Object.keys(pe.postBodyBase).length>0?It={...pe.postBodyBase}:g&&Object.keys(_).length>0&&(It={..._});let Er=It;if(f.searchBodyTemplate?.trim()){let sr=f.searchBodyTemplate.replace(/\{\{query\}\}/g,()=>Kp(te)).replace(/\{query\}/g,()=>Kp(te));sr=Wb(sr,_,l,g);const fn=JSON.parse(sr);Er={...It,...fn}}else Er={...It,[C]:te};Ue=(await dn.post(Te,Er,{signal:We.signal,headers:Object.keys(Xe).length?Xe:void 0})).data}if(Pt!==ee.current)return;const ft=f.apiResultsFormat,St=f.apiResultsConfig,xt=ft==="clinicaltables_v3",ze=$A(Ue),pt=xt||ft===void 0&&ze,At=ft==="tuple_array";let Ut=null;pt?Ut=Cp({response:Ue,sourceUrl:Te,rowsIndex:St?.rowsIndex??3,rowsPath:St?.rowsPath,columns:St?.columns,columnsQueryParam:St?.columnsQueryParam??"sf",columnsQueryParamSeparator:St?.columnsQueryParamSeparator??","}):At&&(Ut=Cp({response:Ue,sourceUrl:Te,rowsIndex:St?.rowsIndex,rowsPath:St?.rowsPath,columns:St?.columns,columnsQueryParam:St?.columnsQueryParam,columnsQueryParamSeparator:St?.columnsQueryParamSeparator}));const ur=NC(Ue),Ar=Ut!==null,Vt=Ut&&Array.isArray(Ut)?Ut:Array.isArray(ur)&&ur.every(It=>It&&typeof It=="object"&&!Array.isArray(It))?ur:null;L(Vt??ur);const Po=Array.isArray(f.apiLabelFields)&&f.apiLabelFields.length>0,Xn=Vt&&(Ar||Po)?zA({rows:Vt,apiLabelField:f.apiLabelField,apiLabelFields:f.apiLabelFields,apiLabelSeparator:f.apiLabelSeparator,apiValueField:f.apiValueField}):Fl(Ue,f.apiLabelField,f.apiValueField);M(Xn);const Ct=f.apiClientFilter;let Cr=Xn;if(Ct?.filterField&&Ct?.matchField){const It=_[Ct.matchField];if(It!=null){const Er=f.apiValueField;Cr=Xn.filter(er=>{const fn=(Vt??ur).find(kt=>String(or(kt,Er||"code"))===String(er.value));if(!fn)return!1;const yr=or(fn,Ct.filterField);return String(yr)===String(It)})}else Cr=[]}const Jn=Yp(Cr,P).filter(Bl);O(Jn),X(Jn.length>0?0:-1)}catch(Ue){if(_t.isCancel(Ue)||Ue?.code==="ERR_CANCELED"||Pt!==ee.current)return;O([]),M([]),L([]),V(EC(Ue)),X(-1)}finally{Pt===ee.current&&$(!1)}})(),()=>{We.abort()}},[oe,m,h,y,v,C,E,P,f.apiKey,f.searchBodyTemplate,f.apiLabelField,f.apiLabelFields,f.apiLabelSeparator,f.apiValueField,f.apiQueryParams,f.apiClientFilter,f.apiResultsFormat,f.apiResultsConfig,f.dependentFields,g,_,l,i,s,e.disabled,de,ot,Se]),S.useEffect(()=>{const te=f.apiClientFilter;if(!te||D.length===0||j.length===0)return;const pe=_[te.matchField],We=f.apiValueField;if(pe==null){O([]);return}const Pt=j.filter(Te=>{const Xe=D.find(ft=>String(or(ft,We||"code"))===String(Te.value));if(!Xe)return!1;const Ue=or(Xe,te.filterField);return String(Ue)===String(pe)}),je=Yp(Pt,P).filter(Bl);O(je),X(je.length>0?0:-1)},[f.apiClientFilter,f.apiValueField,_,P,j,D]);const xe=s||e.disabled,ae=i||e.readOnly,ve=S.useCallback(te=>{const pe=te.target.value;ae||xe||(ce.current&&ne.current&&pe!==ne.current&&(ce.current="",ne.current="",r(p?null:"")),I(pe),W(!0),X(-1))},[xe,ae,p,r]),Ye=S.useCallback(te=>{const pe=typeof te?.label=="string"?te.label:String(te?.value??""),We=f.apiValueField||"code";if(p){const Pt=qp(f),je=D.find(Te=>String(or(Te,We))===String(te.value));if(je&&typeof je=="object"&&!Array.isArray(je)&&Pt.length>0){const Te=xC(je,Pt);ce.current=Ll(Te,!0),ne.current=pe,r(Te),I(pe)}else ce.current=`S:${String(te.value)}`,ne.current=pe,r(String(te.value)),I(pe)}else ce.current=`S:${String(te.value)}`,ne.current=pe,r(String(te.value)),I(pe);G.current&&clearTimeout(G.current),W(!1),X(-1),n?.()},[p,n,r,f,D]),ct=S.useCallback(te=>{te.preventDefault(),te.stopPropagation(),!(xe||ae)&&(ce.current="",ne.current="",r(p?null:""),I(""),O([]),M([]),L([]),V(null),W(!1),n?.())},[xe,ae,p,r,n]),Ge=S.useMemo(()=>T&&!ae&&(U||!!ie||re.length>0||oe.length>=E&&!U),[T,ae,U,ie,re.length,oe,E]),Kt=S.useCallback(te=>{if(!(ae||xe))if(te.key==="ArrowDown")te.preventDefault(),W(!0),X(pe=>re.length===0?-1:(pe+1)%re.length);else if(te.key==="ArrowUp")te.preventDefault(),W(!0),X(pe=>re.length===0?-1:pe<=0?re.length-1:pe-1);else if(te.key==="Enter"){const pe=K>=0?re[K]:void 0;Ge&&pe&&!pe.disabled&&(te.preventDefault(),Ye(pe))}else te.key==="Escape"&&W(!1)},[xe,ae,K,Ge,re,Ye]),Je=e.appearance?.size||"md",q={sm:"h-8 text-sm",md:"h-10",lg:"h-12 text-lg"},$e=ht(e),gt=jt(e,!!(o||ie)),Oe=oe.length>=E&&!U&&!ie&&re.length===0;return c.jsx(Et,{field:e,error:o||ie||void 0,isRequired:a,className:d,children:c.jsxs(Ol,{open:Ge,onOpenChange:te=>{te||W(!1)},children:[c.jsx(fC,{asChild:!0,children:c.jsxs("div",{className:"relative flex w-full min-w-0 items-center gap-1",children:[c.jsx(wn,{id:$e,role:"combobox","aria-expanded":Ge,"aria-autocomplete":"list","aria-controls":Ge?`${$e}-listbox`:void 0,"aria-activedescendant":K>=0?`${$e}-opt-${K}`:void 0,value:A,onChange:ve,onKeyDown:Kt,onFocus:()=>{G.current&&clearTimeout(G.current),!ae&&!xe&&W(!0)},onBlur:()=>{G.current=setTimeout(()=>{W(!1),n?.()},150)},placeholder:e.placeholder||"Search…",disabled:xe,readOnly:ae,"aria-describedby":gt,"aria-invalid":Jt(!!(o||ie)),"aria-required":a,className:B("pr-20",q[Je],(o||ie)&&"border-destructive focus-visible:ring-destructive",e.appearance?.className)}),c.jsxs("div",{className:"pointer-events-none absolute right-1 top-1/2 flex -translate-y-1/2 items-center gap-0.5",children:[U&&c.jsx(Ro,{className:"pointer-events-none h-4 w-4 animate-spin text-muted-foreground"}),N&&CC(t,A,p)&&!xe&&!ae&&c.jsx(Yt,{type:"button",variant:"ghost",size:"icon",className:"pointer-events-auto h-8 w-8 shrink-0",onMouseDown:te=>te.preventDefault(),onClick:ct,"aria-label":"Clear",children:c.jsx(Ko,{className:"h-4 w-4"})})]})]})}),c.jsx(Il,{className:"p-0 w-[var(--radix-popover-trigger-width)] min-w-[12rem] overflow-hidden",align:"start",onOpenAutoFocus:te=>te.preventDefault(),onCloseAutoFocus:te=>te.preventDefault(),children:c.jsx("div",{id:`${$e}-listbox`,role:"listbox",children:ie?c.jsx("div",{className:"px-3 py-2 text-sm text-destructive",children:ie}):U?c.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground",children:[c.jsx(Ro,{className:"h-4 w-4 animate-spin shrink-0"}),"Loading…"]}):Oe?c.jsx("ul",{className:"py-1","aria-label":"Search results",children:c.jsx("li",{role:"option","aria-disabled":!0,className:"cursor-default select-none px-3 py-2 text-sm text-muted-foreground",onMouseDown:te=>te.preventDefault(),children:"No results found"})}):c.jsx("ul",{className:"max-h-60 overflow-y-auto overscroll-contain py-1","aria-label":"Search results",children:re.map((te,pe)=>c.jsx("li",{id:`${$e}-opt-${pe}`,role:"option","aria-selected":K===pe,className:B(te.disabled?"cursor-not-allowed opacity-60":"cursor-pointer","px-3 py-2 text-sm",K===pe&&"bg-accent text-accent-foreground"),onMouseEnter:()=>X(pe),onMouseDown:We=>We.preventDefault(),onClick:()=>{te.disabled||Ye(te)},children:te.label},`${te.value}-${pe}`))})})})]})})};var ki="Checkbox",[_C]=vr(ki),[kC,$l]=_C(ki);function TC(e){const{__scopeCheckbox:t,checked:r,children:n,defaultChecked:o,disabled:s,form:i,name:a,onCheckedChange:d,required:u,value:l="on",internal_do_not_use_render:f}=e,[p,m]=Zr({prop:r,defaultProp:o??!1,onChange:d,caller:ki}),[g,h]=b.useState(null),[y,v]=b.useState(null),w=b.useRef(!1),x=g?!!i||!!g.closest("form"):!0,E={checked:p,disabled:s,setChecked:m,control:g,setControl:h,name:a,form:i,value:l,hasConsumerStoppedPropagationRef:w,required:u,defaultChecked:Fn(o)?!1:o,isFormControl:x,bubbleInput:y,setBubbleInput:v};return c.jsx(kC,{scope:t,...E,children:FC(f)?f(E):n})}var Jp="CheckboxTrigger",Qp=b.forwardRef(({__scopeCheckbox:e,onKeyDown:t,onClick:r,...n},o)=>{const{control:s,value:i,disabled:a,checked:d,required:u,setControl:l,setChecked:f,hasConsumerStoppedPropagationRef:p,isFormControl:m,bubbleInput:g}=$l(Jp,e),h=Ze(o,l),y=b.useRef(d);return b.useEffect(()=>{const v=s?.form;if(v){const w=()=>f(y.current);return v.addEventListener("reset",w),()=>v.removeEventListener("reset",w)}},[s,f]),c.jsx(Be.button,{type:"button",role:"checkbox","aria-checked":Fn(d)?"mixed":d,"aria-required":u,"data-state":om(d),"data-disabled":a?"":void 0,disabled:a,value:i,...n,ref:h,onKeyDown:Me(t,v=>{v.key==="Enter"&&v.preventDefault()}),onClick:Me(r,v=>{f(w=>Fn(w)?!0:!w),g&&m&&(p.current=v.isPropagationStopped(),p.current||v.stopPropagation())})})});Qp.displayName=Jp;var Zp=b.forwardRef((e,t)=>{const{__scopeCheckbox:r,name:n,checked:o,defaultChecked:s,required:i,disabled:a,value:d,onCheckedChange:u,form:l,...f}=e;return c.jsx(TC,{__scopeCheckbox:r,checked:o,defaultChecked:s,disabled:a,required:i,onCheckedChange:u,name:n,form:l,value:d,internal_do_not_use_render:({isFormControl:p})=>c.jsxs(c.Fragment,{children:[c.jsx(Qp,{...f,ref:t,__scopeCheckbox:r}),p&&c.jsx(nm,{__scopeCheckbox:r})]})})});Zp.displayName=ki;var em="CheckboxIndicator",tm=b.forwardRef((e,t)=>{const{__scopeCheckbox:r,forceMount:n,...o}=e,s=$l(em,r);return c.jsx(xr,{present:n||Fn(s.checked)||s.checked===!0,children:c.jsx(Be.span,{"data-state":om(s.checked),"data-disabled":s.disabled?"":void 0,...o,ref:t,style:{pointerEvents:"none",...e.style}})})});tm.displayName=em;var rm="CheckboxBubbleInput",nm=b.forwardRef(({__scopeCheckbox:e,...t},r)=>{const{control:n,hasConsumerStoppedPropagationRef:o,checked:s,defaultChecked:i,required:a,disabled:d,name:u,value:l,form:f,bubbleInput:p,setBubbleInput:m}=$l(rm,e),g=Ze(r,m),h=Qo(s),y=Jo(n);b.useEffect(()=>{const w=p;if(!w)return;const x=window.HTMLInputElement.prototype,P=Object.getOwnPropertyDescriptor(x,"checked").set,C=!o.current;if(h!==s&&P){const N=new Event("click",{bubbles:C});w.indeterminate=Fn(s),P.call(w,Fn(s)?!1:s),w.dispatchEvent(N)}},[p,h,s,o]);const v=b.useRef(Fn(s)?!1:s);return c.jsx(Be.input,{type:"checkbox","aria-hidden":!0,defaultChecked:i??v.current,required:a,disabled:d,name:u,value:l,form:f,...t,tabIndex:-1,ref:g,style:{...t.style,...y,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});nm.displayName=rm;function FC(e){return typeof e=="function"}function Fn(e){return e==="indeterminate"}function om(e){return Fn(e)?"indeterminate":e?"checked":"unchecked"}function Ti({className:e,...t}){return c.jsx(Zp,{"data-slot":"checkbox",className:B("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:c.jsx(tm,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:c.jsx(Vs,{className:"size-3.5"})})})}const PC=Pp("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-destructive-foreground [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",warning:"border-transparent bg-orange-500 text-white [a&]:hover:bg-orange-600 focus-visible:ring-orange-500/20",success:"border-transparent bg-green-500 text-white [a&]:hover:bg-green-600 focus-visible:ring-green-500/20",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function OC({className:e,variant:t,asChild:r=!1,...n}){const o=r?qd:"span";return c.jsx(o,{"data-slot":"badge",className:B(PC({variant:t}),e),...n})}function IC(e,t){return b.useReducer((r,n)=>t[r][n]??r,e)}var jl="ScrollArea",[sm]=vr(jl),[MC,Ir]=sm(jl),im=b.forwardRef((e,t)=>{const{__scopeScrollArea:r,type:n="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,d]=b.useState(null),[u,l]=b.useState(null),[f,p]=b.useState(null),[m,g]=b.useState(null),[h,y]=b.useState(null),[v,w]=b.useState(0),[x,E]=b.useState(0),[P,C]=b.useState(!1),[N,_]=b.useState(!1),A=Ze(t,T=>d(T)),I=ro(o);return c.jsx(MC,{scope:r,type:n,dir:I,scrollHideDelay:s,scrollArea:a,viewport:u,onViewportChange:l,content:f,onContentChange:p,scrollbarX:m,onScrollbarXChange:g,scrollbarXEnabled:P,onScrollbarXEnabledChange:C,scrollbarY:h,onScrollbarYChange:y,scrollbarYEnabled:N,onScrollbarYEnabledChange:_,onCornerWidthChange:w,onCornerHeightChange:E,children:c.jsx(Be.div,{dir:I,...i,ref:A,style:{position:"relative","--radix-scroll-area-corner-width":v+"px","--radix-scroll-area-corner-height":x+"px",...e.style}})})});im.displayName=jl;var am="ScrollAreaViewport",lm=b.forwardRef((e,t)=>{const{__scopeScrollArea:r,children:n,nonce:o,...s}=e,i=Ir(am,r),a=b.useRef(null),d=Ze(t,a,i.onViewportChange);return c.jsxs(c.Fragment,{children:[c.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),c.jsx(Be.div,{"data-radix-scroll-area-viewport":"",...s,ref:d,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:c.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:n})})]})});lm.displayName=am;var tn="ScrollAreaScrollbar",cm=b.forwardRef((e,t)=>{const{forceMount:r,...n}=e,o=Ir(tn,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return b.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?c.jsx(LC,{...n,ref:t,forceMount:r}):o.type==="scroll"?c.jsx(DC,{...n,ref:t,forceMount:r}):o.type==="auto"?c.jsx(dm,{...n,ref:t,forceMount:r}):o.type==="always"?c.jsx(zl,{...n,ref:t}):null});cm.displayName=tn;var LC=b.forwardRef((e,t)=>{const{forceMount:r,...n}=e,o=Ir(tn,e.__scopeScrollArea),[s,i]=b.useState(!1);return b.useEffect(()=>{const a=o.scrollArea;let d=0;if(a){const u=()=>{window.clearTimeout(d),i(!0)},l=()=>{d=window.setTimeout(()=>i(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",u),a.addEventListener("pointerleave",l),()=>{window.clearTimeout(d),a.removeEventListener("pointerenter",u),a.removeEventListener("pointerleave",l)}}},[o.scrollArea,o.scrollHideDelay]),c.jsx(xr,{present:r||s,children:c.jsx(dm,{"data-state":s?"visible":"hidden",...n,ref:t})})}),DC=b.forwardRef((e,t)=>{const{forceMount:r,...n}=e,o=Ir(tn,e.__scopeScrollArea),s=e.orientation==="horizontal",i=Ii(()=>d("SCROLL_END"),100),[a,d]=IC("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return b.useEffect(()=>{if(a==="idle"){const u=window.setTimeout(()=>d("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(u)}},[a,o.scrollHideDelay,d]),b.useEffect(()=>{const u=o.viewport,l=s?"scrollLeft":"scrollTop";if(u){let f=u[l];const p=()=>{const m=u[l];f!==m&&(d("SCROLL"),i()),f=m};return u.addEventListener("scroll",p),()=>u.removeEventListener("scroll",p)}},[o.viewport,s,d,i]),c.jsx(xr,{present:r||a!=="hidden",children:c.jsx(zl,{"data-state":a==="hidden"?"hidden":"visible",...n,ref:t,onPointerEnter:Me(e.onPointerEnter,()=>d("POINTER_ENTER")),onPointerLeave:Me(e.onPointerLeave,()=>d("POINTER_LEAVE"))})})}),dm=b.forwardRef((e,t)=>{const r=Ir(tn,e.__scopeScrollArea),{forceMount:n,...o}=e,[s,i]=b.useState(!1),a=e.orientation==="horizontal",d=Ii(()=>{if(r.viewport){const u=r.viewport.offsetWidth<r.viewport.scrollWidth,l=r.viewport.offsetHeight<r.viewport.scrollHeight;i(a?u:l)}},10);return go(r.viewport,d),go(r.content,d),c.jsx(xr,{present:n||s,children:c.jsx(zl,{"data-state":s?"visible":"hidden",...o,ref:t})})}),zl=b.forwardRef((e,t)=>{const{orientation:r="vertical",...n}=e,o=Ir(tn,e.__scopeScrollArea),s=b.useRef(null),i=b.useRef(0),[a,d]=b.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),u=hm(a.viewport,a.content),l={...n,sizes:a,onSizesChange:d,hasThumb:u>0&&u<1,onThumbChange:p=>s.current=p,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:p=>i.current=p};function f(p,m){return VC(p,i.current,a,m)}return r==="horizontal"?c.jsx(BC,{...l,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const p=o.viewport.scrollLeft,m=gm(p,a,o.dir);s.current.style.transform=`translate3d(${m}px, 0, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollLeft=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollLeft=f(p,o.dir))}}):r==="vertical"?c.jsx($C,{...l,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const p=o.viewport.scrollTop,m=gm(p,a);s.current.style.transform=`translate3d(0, ${m}px, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollTop=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollTop=f(p))}}):null}),BC=b.forwardRef((e,t)=>{const{sizes:r,onSizesChange:n,...o}=e,s=Ir(tn,e.__scopeScrollArea),[i,a]=b.useState(),d=b.useRef(null),u=Ze(t,d,s.onScrollbarXChange);return b.useEffect(()=>{d.current&&a(getComputedStyle(d.current))},[d]),c.jsx(fm,{"data-orientation":"horizontal",...o,ref:u,sizes:r,style:{bottom:0,left:s.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:s.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Oi(r)+"px",...e.style},onThumbPointerDown:l=>e.onThumbPointerDown(l.x),onDragScroll:l=>e.onDragScroll(l.x),onWheelScroll:(l,f)=>{if(s.viewport){const p=s.viewport.scrollLeft+l.deltaX;e.onWheelScroll(p),bm(p,f)&&l.preventDefault()}},onResize:()=>{d.current&&s.viewport&&i&&n({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:d.current.clientWidth,paddingStart:Pi(i.paddingLeft),paddingEnd:Pi(i.paddingRight)}})}})}),$C=b.forwardRef((e,t)=>{const{sizes:r,onSizesChange:n,...o}=e,s=Ir(tn,e.__scopeScrollArea),[i,a]=b.useState(),d=b.useRef(null),u=Ze(t,d,s.onScrollbarYChange);return b.useEffect(()=>{d.current&&a(getComputedStyle(d.current))},[d]),c.jsx(fm,{"data-orientation":"vertical",...o,ref:u,sizes:r,style:{top:0,right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Oi(r)+"px",...e.style},onThumbPointerDown:l=>e.onThumbPointerDown(l.y),onDragScroll:l=>e.onDragScroll(l.y),onWheelScroll:(l,f)=>{if(s.viewport){const p=s.viewport.scrollTop+l.deltaY;e.onWheelScroll(p),bm(p,f)&&l.preventDefault()}},onResize:()=>{d.current&&s.viewport&&i&&n({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:d.current.clientHeight,paddingStart:Pi(i.paddingTop),paddingEnd:Pi(i.paddingBottom)}})}})}),[jC,um]=sm(tn),fm=b.forwardRef((e,t)=>{const{__scopeScrollArea:r,sizes:n,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:d,onDragScroll:u,onWheelScroll:l,onResize:f,...p}=e,m=Ir(tn,r),[g,h]=b.useState(null),y=Ze(t,A=>h(A)),v=b.useRef(null),w=b.useRef(""),x=m.viewport,E=n.content-n.viewport,P=ar(l),C=ar(d),N=Ii(f,10);function _(A){if(v.current){const I=A.clientX-v.current.left,T=A.clientY-v.current.top;u({x:I,y:T})}}return b.useEffect(()=>{const A=I=>{const T=I.target;g?.contains(T)&&P(I,E)};return document.addEventListener("wheel",A,{passive:!1}),()=>document.removeEventListener("wheel",A,{passive:!1})},[x,g,E,P]),b.useEffect(C,[n,C]),go(g,N),go(m.content,N),c.jsx(jC,{scope:r,scrollbar:g,hasThumb:o,onThumbChange:ar(s),onThumbPointerUp:ar(i),onThumbPositionChange:C,onThumbPointerDown:ar(a),children:c.jsx(Be.div,{...p,ref:y,style:{position:"absolute",...p.style},onPointerDown:Me(e.onPointerDown,A=>{A.button===0&&(A.target.setPointerCapture(A.pointerId),v.current=g.getBoundingClientRect(),w.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",m.viewport&&(m.viewport.style.scrollBehavior="auto"),_(A))}),onPointerMove:Me(e.onPointerMove,_),onPointerUp:Me(e.onPointerUp,A=>{const I=A.target;I.hasPointerCapture(A.pointerId)&&I.releasePointerCapture(A.pointerId),document.body.style.webkitUserSelect=w.current,m.viewport&&(m.viewport.style.scrollBehavior=""),v.current=null})})})}),Fi="ScrollAreaThumb",pm=b.forwardRef((e,t)=>{const{forceMount:r,...n}=e,o=um(Fi,e.__scopeScrollArea);return c.jsx(xr,{present:r||o.hasThumb,children:c.jsx(zC,{ref:t,...n})})}),zC=b.forwardRef((e,t)=>{const{__scopeScrollArea:r,style:n,...o}=e,s=Ir(Fi,r),i=um(Fi,r),{onThumbPositionChange:a}=i,d=Ze(t,f=>i.onThumbChange(f)),u=b.useRef(void 0),l=Ii(()=>{u.current&&(u.current(),u.current=void 0)},100);return b.useEffect(()=>{const f=s.viewport;if(f){const p=()=>{if(l(),!u.current){const m=HC(f,a);u.current=m,a()}};return a(),f.addEventListener("scroll",p),()=>f.removeEventListener("scroll",p)}},[s.viewport,l,a]),c.jsx(Be.div,{"data-state":i.hasThumb?"visible":"hidden",...o,ref:d,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...n},onPointerDownCapture:Me(e.onPointerDownCapture,f=>{const m=f.target.getBoundingClientRect(),g=f.clientX-m.left,h=f.clientY-m.top;i.onThumbPointerDown({x:g,y:h})}),onPointerUp:Me(e.onPointerUp,i.onThumbPointerUp)})});pm.displayName=Fi;var Ul="ScrollAreaCorner",mm=b.forwardRef((e,t)=>{const r=Ir(Ul,e.__scopeScrollArea),n=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&n?c.jsx(UC,{...e,ref:t}):null});mm.displayName=Ul;var UC=b.forwardRef((e,t)=>{const{__scopeScrollArea:r,...n}=e,o=Ir(Ul,r),[s,i]=b.useState(0),[a,d]=b.useState(0),u=!!(s&&a);return go(o.scrollbarX,()=>{const l=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(l),d(l)}),go(o.scrollbarY,()=>{const l=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(l),i(l)}),u?c.jsx(Be.div,{...n,ref:t,style:{width:s,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function Pi(e){return e?parseInt(e,10):0}function hm(e,t){const r=e/t;return isNaN(r)?0:r}function Oi(e){const t=hm(e.viewport,e.content),r=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,n=(e.scrollbar.size-r)*t;return Math.max(n,18)}function VC(e,t,r,n="ltr"){const o=Oi(r),s=o/2,i=t||s,a=o-i,d=r.scrollbar.paddingStart+i,u=r.scrollbar.size-r.scrollbar.paddingEnd-a,l=r.content-r.viewport,f=n==="ltr"?[0,l]:[l*-1,0];return ym([d,u],f)(e)}function gm(e,t,r="ltr"){const n=Oi(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,s=t.scrollbar.size-o,i=t.content-t.viewport,a=s-n,d=r==="ltr"?[0,i]:[i*-1,0],u=qo(e,d);return ym([0,i],[0,a])(u)}function ym(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 bm(e,t){return e>0&&e<t}var HC=(e,t=()=>{})=>{let r={left:e.scrollLeft,top:e.scrollTop},n=0;return(function o(){const s={left:e.scrollLeft,top:e.scrollTop},i=r.left!==s.left,a=r.top!==s.top;(i||a)&&t(),r=s,n=window.requestAnimationFrame(o)})(),()=>window.cancelAnimationFrame(n)};function Ii(e,t){const r=ar(e),n=b.useRef(0);return b.useEffect(()=>()=>window.clearTimeout(n.current),[]),b.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(r,t)},[r,t])}function go(e,t){const r=ar(t);Qt(()=>{let n=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(n),n=window.requestAnimationFrame(r)});return o.observe(e),()=>{window.cancelAnimationFrame(n),o.unobserve(e)}}},[e,r])}var WC=im,RC=lm,GC=mm;function KC({className:e,children:t,...r}){return c.jsxs(WC,{"data-slot":"scroll-area",className:B("relative",e),...r,children:[c.jsx(RC,{"data-slot":"scroll-area-viewport",className:"focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1",children:t}),c.jsx(qC,{}),c.jsx(GC,{})]})}function qC({className:e,orientation:t="vertical",...r}){return c.jsx(cm,{"data-slot":"scroll-area-scrollbar",orientation:t,className:B("flex touch-none p-px transition-colors select-none",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent",e),...r,children:c.jsx(pm,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const vm=({field:e,value:t=[],onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a,formValues:d={},submissionContext:u,excludedOptionValues:l})=>{const{options:f,isLoadingOptions:p,optionsError:m}=_p({field:e,formValues:d,submissionContext:u}),g=l?.length?new Set(l.map(String)):null,h=g?f.filter(N=>!g.has(String(N.value??N.label??""))):f,y=Array.isArray(t)?t:[],v=y.map(N=>h.find(_=>String(_.value)===String(N))).filter(Boolean),w=S.useCallback(N=>{const _=y.includes(N)?y.filter(A=>A!==N):[...y,N];r(_),n?.()},[y,r,n]),x=S.useCallback(N=>{r(y.filter(_=>_!==N)),n?.()},[y,r,n]),E=e.appearance?.size||"md",P={sm:"h-8 text-sm",md:"h-10",lg:"h-12 text-lg"},C=v.length>0?`${v.length} selected`:h.length===0&&l?.length?"No available options":e.placeholder||"Select options";return c.jsxs(Et,{field:e,error:o||m||void 0,isRequired:i,className:a,children:[c.jsxs(Ol,{children:[c.jsx(Hp,{asChild:!0,children:c.jsxs(Yt,{type:"button",variant:"outline",role:"combobox","aria-expanded":void 0,"aria-haspopup":"listbox","aria-multiselectable":"true","aria-describedby":jt(e,!!o||!!m),"aria-invalid":Jt(!!o||!!m),"aria-required":i,id:ht(e),disabled:s||e.disabled||p,className:B("w-full min-w-0 justify-between font-normal",P[E],o&&"border-destructive focus-visible:ring-destructive",m&&"border-destructive focus-visible:ring-destructive",e.appearance?.className),children:[c.jsx("span",{className:"truncate",children:C}),c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[p&&c.jsx(Ro,{className:"h-4 w-4 animate-spin text-muted-foreground"}),c.jsx(Wo,{className:"h-4 w-4 opacity-50"})]})]})}),c.jsx(Il,{className:"w-[var(--radix-popover-trigger-width)] p-0 overflow-hidden",align:"start",children:c.jsx(KC,{className:"h-60 overflow-hidden rounded-md",children:c.jsx("ul",{role:"listbox","aria-multiselectable":"true","aria-label":e.label||e.name||"Options",className:"p-1",children:h.length===0?c.jsx("li",{className:"px-2 py-3 text-sm text-muted-foreground text-center",children:p?"Loading options...":l?.length?"No available options":"No options available"}):h.map(N=>{const _=String(N.value||N.label),A=N.label||N.value||_,I=y.includes(_);return c.jsxs("li",{role:"option","aria-selected":I,className:"flex items-center gap-2 rounded-sm px-2 py-1.5 cursor-pointer hover:bg-accent focus:bg-accent outline-none",onClick:()=>!N.disabled&&w(_),onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),N.disabled||w(_))},children:[c.jsx(Ti,{checked:I,disabled:N.disabled,onCheckedChange:()=>!N.disabled&&w(_),onClick:T=>T.stopPropagation(),"aria-hidden":!0,className:"pointer-events-none"}),c.jsx("span",{className:"flex-1 truncate text-sm",children:A})]},_)})})})})]}),v.length>0&&c.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",role:"list","aria-label":"Selected options",children:v.map(N=>{const _=String(N.value||N.label),A=N.label||N.value||_;return c.jsxs(OC,{variant:"secondary",className:"pl-2 pr-1 py-0.5 text-xs font-normal gap-1",children:[c.jsx("span",{className:"truncate max-w-[120px]",children:A}),c.jsx("button",{type:"button","aria-label":`Remove ${A}`,className:"rounded-full p-0.5 hover:bg-muted focus:outline-none focus:ring-2 focus:ring-ring",onClick:()=>x(_),tabIndex:-1,children:c.jsx(Ko,{className:"h-3 w-3"})})]},_)})})]})},wm=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a})=>{const d=S.useCallback(u=>{r(u===!0),n?.()},[r,n]);return c.jsxs("div",{className:B("space-y-2",a),children:[c.jsxs("div",{className:"flex items-start space-x-3",children:[c.jsx(Ti,{id:ht(e),checked:t||!1,onCheckedChange:d,disabled:s||e.disabled,"aria-describedby":jt(e,!!o),"aria-required":i,className:B(o&&"border-destructive")}),c.jsxs("div",{className:"grid gap-1.5 leading-none",children:[c.jsxs(Sn,{id:zs(e),htmlFor:ht(e),className:B("text-sm font-medium cursor-pointer",o&&"text-destructive"),children:[e.label,i&&c.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.description&&!o&&c.jsx("p",{id:Vo(e),className:"text-xs text-muted-foreground",children:e.description})]})]}),o&&c.jsx("p",{id:Ho(e),className:"text-xs text-destructive",role:"alert",children:o})]})};var Mi="Switch",[YC]=vr(Mi),[XC,JC]=YC(Mi),Sm=b.forwardRef((e,t)=>{const{__scopeSwitch:r,name:n,checked:o,defaultChecked:s,required:i,disabled:a,value:d="on",onCheckedChange:u,form:l,...f}=e,[p,m]=b.useState(null),g=Ze(t,x=>m(x)),h=b.useRef(!1),y=p?l||!!p.closest("form"):!0,[v,w]=Zr({prop:o,defaultProp:s??!1,onChange:u,caller:Mi});return c.jsxs(XC,{scope:r,checked:v,disabled:a,children:[c.jsx(Be.button,{type:"button",role:"switch","aria-checked":v,"aria-required":i,"data-state":Em(v),"data-disabled":a?"":void 0,disabled:a,value:d,...f,ref:g,onClick:Me(e.onClick,x=>{w(E=>!E),y&&(h.current=x.isPropagationStopped(),h.current||x.stopPropagation())})}),y&&c.jsx(Cm,{control:p,bubbles:!h.current,name:n,value:d,checked:v,required:i,disabled:a,form:l,style:{transform:"translateX(-100%)"}})]})});Sm.displayName=Mi;var xm="SwitchThumb",Am=b.forwardRef((e,t)=>{const{__scopeSwitch:r,...n}=e,o=JC(xm,r);return c.jsx(Be.span,{"data-state":Em(o.checked),"data-disabled":o.disabled?"":void 0,...n,ref:t})});Am.displayName=xm;var QC="SwitchBubbleInput",Cm=b.forwardRef(({__scopeSwitch:e,control:t,checked:r,bubbles:n=!0,...o},s)=>{const i=b.useRef(null),a=Ze(i,s),d=Qo(r),u=Jo(t);return b.useEffect(()=>{const l=i.current;if(!l)return;const f=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(f,"checked").set;if(d!==r&&m){const g=new Event("click",{bubbles:n});m.call(l,r),l.dispatchEvent(g)}},[d,r,n]),c.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:r,...o,tabIndex:-1,ref:a,style:{...o.style,...u,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Cm.displayName=QC;function Em(e){return e?"checked":"unchecked"}var ZC=Sm,eE=Am;function Nm({className:e,...t}){return c.jsx(ZC,{"data-slot":"switch",className:B("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:c.jsx(eE,{"data-slot":"switch-thumb",className:B("bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}const tE=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a})=>{const d=e.properties;let u=null;if(e.metadata)try{u=typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata}catch{}const l=u?.onValue??d?.onValue??"On",f=u?.offValue??d?.offValue??"Off",p=u?.onText??d?.onText??l,m=u?.offText??d?.offText??f,g=S.useMemo(()=>{const y=t??e.defaultValue??f;return String(y)===String(l)},[t,e.defaultValue,f,l]),h=S.useCallback(y=>{r(y?l:f),n?.()},[r,n,l,f]);return c.jsxs("div",{className:B("space-y-2",a),children:[c.jsxs("div",{className:"space-y-2",children:[e.label&&c.jsxs(Sn,{id:zs(e),htmlFor:ht(e),className:B("text-sm font-medium block",o&&"text-destructive"),children:[e.label,i&&c.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.description&&!o&&c.jsx("p",{id:Vo(e),className:"text-xs text-muted-foreground",children:e.description}),c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(Nm,{id:ht(e),checked:g,onCheckedChange:h,disabled:s||e.disabled,"aria-describedby":jt(e,!!o),"aria-required":i,className:B(o&&"opacity-50")}),c.jsx("span",{className:"text-sm text-foreground font-medium",children:g?p:m})]})]}),o&&c.jsx("p",{id:Ho(e),className:"text-xs text-destructive",role:"alert",children:o})]})};var Vl="rovingFocusGroup.onEntryFocus",rE={bubbles:!1,cancelable:!0},as="RovingFocusGroup",[Hl,_m,nE]=Ba(as),[oE,Li]=vr(as,[nE]),[sE,iE]=oE(as),km=b.forwardRef((e,t)=>c.jsx(Hl.Provider,{scope:e.__scopeRovingFocusGroup,children:c.jsx(Hl.Slot,{scope:e.__scopeRovingFocusGroup,children:c.jsx(aE,{...e,ref:t})})}));km.displayName=as;var aE=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,orientation:n,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:d,onEntryFocus:u,preventScrollOnEntryFocus:l=!1,...f}=e,p=b.useRef(null),m=Ze(t,p),g=ro(s),[h,y]=Zr({prop:i,defaultProp:a??null,onChange:d,caller:as}),[v,w]=b.useState(!1),x=ar(u),E=_m(r),P=b.useRef(!1),[C,N]=b.useState(0);return b.useEffect(()=>{const _=p.current;if(_)return _.addEventListener(Vl,x),()=>_.removeEventListener(Vl,x)},[x]),c.jsx(sE,{scope:r,orientation:n,dir:g,loop:o,currentTabStopId:h,onItemFocus:b.useCallback(_=>y(_),[y]),onItemShiftTab:b.useCallback(()=>w(!0),[]),onFocusableItemAdd:b.useCallback(()=>N(_=>_+1),[]),onFocusableItemRemove:b.useCallback(()=>N(_=>_-1),[]),children:c.jsx(Be.div,{tabIndex:v||C===0?-1:0,"data-orientation":n,...f,ref:m,style:{outline:"none",...e.style},onMouseDown:Me(e.onMouseDown,()=>{P.current=!0}),onFocus:Me(e.onFocus,_=>{const A=!P.current;if(_.target===_.currentTarget&&A&&!v){const I=new CustomEvent(Vl,rE);if(_.currentTarget.dispatchEvent(I),!I.defaultPrevented){const T=E().filter(M=>M.focusable),W=T.find(M=>M.active),J=T.find(M=>M.id===h),j=[W,J,...T].filter(Boolean).map(M=>M.ref.current);Pm(j,l)}}P.current=!1}),onBlur:Me(e.onBlur,()=>w(!1))})})}),Tm="RovingFocusGroupItem",Fm=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,focusable:n=!0,active:o=!1,tabStopId:s,children:i,...a}=e,d=on(),u=s||d,l=iE(Tm,r),f=l.currentTabStopId===u,p=_m(r),{onFocusableItemAdd:m,onFocusableItemRemove:g,currentTabStopId:h}=l;return b.useEffect(()=>{if(n)return m(),()=>g()},[n,m,g]),c.jsx(Hl.ItemSlot,{scope:r,id:u,focusable:n,active:o,children:c.jsx(Be.span,{tabIndex:f?0:-1,"data-orientation":l.orientation,...a,ref:t,onMouseDown:Me(e.onMouseDown,y=>{n?l.onItemFocus(u):y.preventDefault()}),onFocus:Me(e.onFocus,()=>l.onItemFocus(u)),onKeyDown:Me(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){l.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const v=dE(y,l.orientation,l.dir);if(v!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let x=p().filter(E=>E.focusable).map(E=>E.ref.current);if(v==="last")x.reverse();else if(v==="prev"||v==="next"){v==="prev"&&x.reverse();const E=x.indexOf(y.currentTarget);x=l.loop?uE(x,E+1):x.slice(E+1)}setTimeout(()=>Pm(x))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:h!=null}):i})})});Fm.displayName=Tm;var lE={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cE(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function dE(e,t,r){const n=cE(e.key,r);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return lE[n]}function Pm(e,t=!1){const r=document.activeElement;for(const n of e)if(n===r||(n.focus({preventScroll:t}),document.activeElement!==r))return}function uE(e,t){return e.map((r,n)=>e[(t+n)%e.length])}var Om=km,Im=Fm,Wl="Radio",[fE,Mm]=vr(Wl),[pE,mE]=fE(Wl),Lm=b.forwardRef((e,t)=>{const{__scopeRadio:r,name:n,checked:o=!1,required:s,disabled:i,value:a="on",onCheck:d,form:u,...l}=e,[f,p]=b.useState(null),m=Ze(t,y=>p(y)),g=b.useRef(!1),h=f?u||!!f.closest("form"):!0;return c.jsxs(pE,{scope:r,checked:o,disabled:i,children:[c.jsx(Be.button,{type:"button",role:"radio","aria-checked":o,"data-state":jm(o),"data-disabled":i?"":void 0,disabled:i,value:a,...l,ref:m,onClick:Me(e.onClick,y=>{o||d?.(),h&&(g.current=y.isPropagationStopped(),g.current||y.stopPropagation())})}),h&&c.jsx($m,{control:f,bubbles:!g.current,name:n,value:a,checked:o,required:s,disabled:i,form:u,style:{transform:"translateX(-100%)"}})]})});Lm.displayName=Wl;var Dm="RadioIndicator",Bm=b.forwardRef((e,t)=>{const{__scopeRadio:r,forceMount:n,...o}=e,s=mE(Dm,r);return c.jsx(xr,{present:n||s.checked,children:c.jsx(Be.span,{"data-state":jm(s.checked),"data-disabled":s.disabled?"":void 0,...o,ref:t})})});Bm.displayName=Dm;var hE="RadioBubbleInput",$m=b.forwardRef(({__scopeRadio:e,control:t,checked:r,bubbles:n=!0,...o},s)=>{const i=b.useRef(null),a=Ze(i,s),d=Qo(r),u=Jo(t);return b.useEffect(()=>{const l=i.current;if(!l)return;const f=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(f,"checked").set;if(d!==r&&m){const g=new Event("click",{bubbles:n});m.call(l,r),l.dispatchEvent(g)}},[d,r,n]),c.jsx(Be.input,{type:"radio","aria-hidden":!0,defaultChecked:r,...o,tabIndex:-1,ref:a,style:{...o.style,...u,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});$m.displayName=hE;function jm(e){return e?"checked":"unchecked"}var gE=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Di="RadioGroup",[yE]=vr(Di,[Li,Mm]),zm=Li(),Um=Mm(),[bE,vE]=yE(Di),Vm=b.forwardRef((e,t)=>{const{__scopeRadioGroup:r,name:n,defaultValue:o,value:s,required:i=!1,disabled:a=!1,orientation:d,dir:u,loop:l=!0,onValueChange:f,...p}=e,m=zm(r),g=ro(u),[h,y]=Zr({prop:s,defaultProp:o??null,onChange:f,caller:Di});return c.jsx(bE,{scope:r,name:n,required:i,disabled:a,value:h,onValueChange:y,children:c.jsx(Om,{asChild:!0,...m,orientation:d,dir:g,loop:l,children:c.jsx(Be.div,{role:"radiogroup","aria-required":i,"aria-orientation":d,"data-disabled":a?"":void 0,dir:g,...p,ref:t})})})});Vm.displayName=Di;var Hm="RadioGroupItem",Wm=b.forwardRef((e,t)=>{const{__scopeRadioGroup:r,disabled:n,...o}=e,s=vE(Hm,r),i=s.disabled||n,a=zm(r),d=Um(r),u=b.useRef(null),l=Ze(t,u),f=s.value===o.value,p=b.useRef(!1);return b.useEffect(()=>{const m=h=>{gE.includes(h.key)&&(p.current=!0)},g=()=>p.current=!1;return document.addEventListener("keydown",m),document.addEventListener("keyup",g),()=>{document.removeEventListener("keydown",m),document.removeEventListener("keyup",g)}},[]),c.jsx(Im,{asChild:!0,...a,focusable:!i,active:f,children:c.jsx(Lm,{disabled:i,required:s.required,checked:f,...d,...o,name:s.name,ref:l,onCheck:()=>s.onValueChange(o.value),onKeyDown:Me(m=>{m.key==="Enter"&&m.preventDefault()}),onFocus:Me(o.onFocus,()=>{p.current&&u.current?.click()})})})});Wm.displayName=Hm;var wE="RadioGroupIndicator",Rm=b.forwardRef((e,t)=>{const{__scopeRadioGroup:r,...n}=e,o=Um(r);return c.jsx(Bm,{...o,...n,ref:t})});Rm.displayName=wE;var SE=Vm,xE=Wm,AE=Rm;function CE({className:e,...t}){return c.jsx(SE,{"data-slot":"radio-group",className:B("grid gap-3",e),...t})}function EE({className:e,...t}){return c.jsx(xE,{"data-slot":"radio-group-item",className:B("border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:c.jsx(AE,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:c.jsx(eu,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}const Gm=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a,excludedOptionValues:d})=>{const u=e.properties,l=Array.isArray(u?.options)&&u.options.length>0?u.options:Array.isArray(e.options)?e.options:[],f=d?.length?new Set(d.map(String)):null,p=f?l.filter(g=>!f.has(String(g.value??g.label??""))):l,m=S.useCallback(g=>{r(g),n?.()},[r,n]);return c.jsx(Et,{field:e,error:o,isRequired:i,className:a,children:c.jsx(CE,{value:t||"",onValueChange:m,disabled:s||e.disabled||p.length===0,className:"flex flex-col space-y-2","aria-required":i,children:p.length===0?c.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"No available options"}):p.map(g=>c.jsxs("div",{className:"flex items-center space-x-3",children:[c.jsx(EE,{id:`${ht(e)}-${g.value}`,value:g.value,disabled:g.disabled,className:B(o&&"border-destructive")}),c.jsxs(Sn,{htmlFor:`${ht(e)}-${g.value}`,className:B("text-sm font-normal cursor-pointer",g.disabled&&"text-muted-foreground cursor-not-allowed"),children:[g.label,g.description&&c.jsx("span",{className:"block text-xs text-muted-foreground",children:g.description})]})]},g.value))})})},Km=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d})=>{const u=e.properties,l=S.useCallback(E=>{r(E.target.value)},[r]),f=E=>{if(E)return E==="today"?new Date().toISOString().split("T")[0]:E},p=f(u?.minDate),m=f(u?.maxDate),h=(()=>{switch(e.type){case"time":return"time";case"datetime":return"datetime-local";case"daterange":return"date";default:return"date"}})(),y=e.appearance?.size||"md",v={sm:"h-8 text-sm",md:"h-10",lg:"h-12 text-lg"},w=e.appearance?.labelPlacement||"top",x=!e.appearance?.hideLabel&&e.label;return c.jsxs("div",{className:B("space-y-2 w-fit",w==="left"&&"flex items-start gap-4",d),children:[x&&c.jsxs(Sn,{id:zs(e),htmlFor:ht(e),className:B("text-sm font-medium",w==="left"&&"w-32 pt-2 text-right",o&&"text-destructive"),children:[e.label,a&&c.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),c.jsxs("div",{className:"w-fit",children:[c.jsxs("div",{className:"relative w-fit max-w-full",children:[c.jsx(Ev,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),c.jsx(wn,{id:ht(e),type:h,value:t||"",onChange:l,onBlur:n,disabled:s||e.disabled,readOnly:i||e.readOnly,min:p,max:m,"aria-describedby":jt(e,!!o),"aria-invalid":Jt(!!o),"aria-required":a,className:B(v[y],"pl-10 w-fit",o&&"border-destructive focus-visible:ring-destructive",e.appearance?.className)})]}),e.description&&!o&&c.jsx("p",{id:Vo(e),className:"mt-1.5 text-xs text-muted-foreground",children:e.description}),o&&c.jsx("p",{id:Ho(e),className:"mt-1.5 text-xs text-destructive",role:"alert",children:o})]})]})};function yo(e){if(e===0)return"0 Bytes";const t=1024,r=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,n)).toFixed(2))+" "+r[n]}function Rl(e,t){return e===1&&t===1}const qm=/\.(jpg|jpeg|png|gif|webp|bmp|svg)(\?|$)/i;function Gl(e){return e.type.startsWith("image/")?!0:qm.test(e.name)}function Bi(e){try{const t=e.split("?")[0];return qm.test(t)}catch{return!1}}function Kl({items:e,maxFiles:t,disabled:r,objectUrls:n,failedUrlKeys:o,onImageUrlError:s,onRemove:i,onOpenUrl:a,resolveOpenUrl:d,addSlot:u,className:l}){const f=S.useCallback(p=>{try{return p.split("?")[0].split("/").filter(Boolean).pop()||p}catch{return p}},[]);return c.jsxs("div",{"data-file-like-strip":!0,"data-remove-in-dropzone":!0,className:B("relative w-full h-full flex items-center gap-1 min-h-0 overflow-x-auto",l),children:[e.map((p,m)=>{const g=p instanceof File,h=!g&&p&&"url"in p?p:null,y=h?.url??"",v=`${m}-${y}`,w=h&&o.has(y),x=g?n[m]??null:h&&Bi(y)&&!w?y:null,E=g&&Gl(p)&&!!x||!!h&&Bi(y)&&!w&&!!x,P=g?p.name:h?h.name??f(y):"",C=d?.(m,p),N=h&&y||C||"",_=!!a&&!!N;return c.jsxs("div",{className:"relative h-[56px] w-[56px] min-w-[56px] flex-shrink-0 rounded overflow-hidden border border-border/60 bg-muted/30",children:[E&&x?c.jsx("img",{src:x,alt:"",className:"absolute inset-0 h-full w-full object-cover",onError:()=>{h&&s(y)}}):c.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-muted/40",children:c.jsx(ru,{className:"h-7 w-7 text-muted-foreground","aria-hidden":!0})}),c.jsxs("div",{className:"absolute top-0.5 right-0.5 z-10 flex items-center gap-0.5",children:[_&&c.jsx("button",{type:"button",onClick:A=>{A.preventDefault(),A.stopPropagation(),a(N)},disabled:r,className:"inline-flex h-5 w-5 items-center justify-center rounded bg-background/90 text-foreground hover:bg-background focus:outline-none focus:ring-2 focus:ring-primary","aria-label":"Open file",title:"Open file",children:c.jsx(tu,{className:"h-3 w-3","aria-hidden":!0})}),c.jsx("button",{type:"button",onClick:A=>{A.preventDefault(),A.stopPropagation(),i(m)},disabled:r,className:"inline-flex h-5 w-5 items-center justify-center rounded bg-background/90 text-destructive hover:bg-background focus:outline-none focus:ring-2 focus:ring-destructive","aria-label":"Remove file",title:"Remove file",children:c.jsx(Ko,{className:"h-3 w-3","aria-hidden":!0})})]}),!E&&P&&c.jsx("span",{className:"sr-only",children:P})]},v+(g?p.name+p.size:""))}),u]})}function ql(e){const[t,r]=S.useState([]);return S.useEffect(()=>{const n=e.map(o=>o instanceof File&&Gl(o)?URL.createObjectURL(o):null);return r(n),()=>{n.forEach(o=>{o&&URL.revokeObjectURL(o)})}},[e]),t}function Yl({item:e,objectUrl:t,failedUrlKeys:r,onImageUrlError:n,onRemove:o,onOpenUrl:s,openTarget:i,disabled:a}){const d=S.useCallback(w=>{try{return w.split("?")[0].split("/").filter(Boolean).pop()||w}catch{return w}},[]),u=e instanceof File,l=!u&&e&&"url"in e?e:null,f=l?.url??"",p=l&&r.has(f),m=u?t:l&&Bi(f)&&!p?f:null,g=u&&Gl(e)&&!!m||!!l&&Bi(f)&&!p&&!!m,h=u?e.name:l?l.name??d(f):"",y=(i?.trim()||f||"").trim(),v=!!s&&!!y;return c.jsxs("div",{"data-file-like-full-bleed":!0,"data-remove-in-dropzone":!0,className:"relative h-full w-full min-h-[58px] min-w-0 flex items-center justify-center",children:[g&&m?c.jsx("img",{src:m,alt:"",className:"absolute inset-0 h-full w-full rounded object-cover",onError:()=>{l&&n(f)}}):c.jsx("div",{className:"absolute inset-0 flex items-center justify-center rounded bg-muted/40",children:c.jsx(ru,{className:"h-8 w-8 text-muted-foreground","aria-hidden":!0})}),c.jsxs("div",{className:"absolute top-1 right-1 z-10 flex items-center gap-1",children:[v&&y&&c.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),w.stopPropagation(),s(y)},disabled:a,className:"inline-flex h-6 w-6 items-center justify-center rounded bg-background/85 text-foreground hover:bg-background focus:outline-none focus:ring-2 focus:ring-primary","aria-label":"Open file",title:"Open file",children:c.jsx(tu,{className:"h-3.5 w-3.5","aria-hidden":!0})}),c.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),w.stopPropagation(),o()},disabled:a,className:"inline-flex h-6 w-6 items-center justify-center rounded bg-background/85 text-destructive hover:bg-background focus:outline-none focus:ring-2 focus:ring-destructive","aria-label":"Remove file",title:"Remove file",children:c.jsx(Ko,{className:"h-3.5 w-3.5","aria-hidden":!0})})]}),!g&&h&&c.jsx("p",{className:"sr-only",children:h})]})}const NE=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a,buttonResponses:d})=>{const{gridStretch:u}=zo(),l=u&&Is(e),f=e.properties,p=S.useRef(null),[m,g]=S.useState(!1),[h,y]=S.useState(),[v,w]=S.useState(()=>new Set),[x,E]=S.useState(0),P=e.metadata?typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata:null,C=Ms(e),N=S.useMemo(()=>Ls(t),[t]),[_,A]=S.useState(null);S.useEffect(()=>{A(null)},[t,x]);const I=_??N,T=ql(I),W=e.validation?.find(Se=>Se.type==="fileSize"),J=e.validation?.find(Se=>Se.type==="fileType"),O=W?.value?W.value:f?.maxSize??P?.maxSize??10*1024*1024,j=J?.value?J.value:f?.accept??P?.accept??[],M=Array.isArray(j)?j.join(","):"",D=()=>{I.length>=C||p.current?.click()},L=S.useCallback(Se=>{if(W){const xe=Yr(Se,W);if(xe!==!0)return typeof xe=="string"?xe:"File size exceeds the maximum allowed size"}else if(Se.size>O)return`File size must be less than ${yo(O)}`;if(J){const xe=Yr(Se,J);if(xe!==!0)return typeof xe=="string"?xe:"File type is not allowed"}return null},[W,J,O]),U=S.useCallback(Se=>{const xe=ka(Se,C);r(xe),n?.()},[r,n,C]),$=S.useCallback(Se=>{y(void 0);const xe=Array.from(Se),ae=[...I];let ve=null;for(const Ye of xe){if(ae.length>=C)break;const ct=L(Ye);if(ct){ve||(ve=ct);continue}ae.push(Ye)}if(ve&&ae.length===I.length){y(ve);return}ve&&y(ve),A(ae),U(ae)},[I,C,L,U]),ie=S.useCallback(Se=>{const xe=Se.target.files;xe&&xe.length>0&&$(xe),p.current&&(p.current.value="")},[$]),V=S.useCallback(Se=>{if(s)return;const xe=I.filter((ae,ve)=>ve!==Se);E(ae=>ae+1),A(xe),U(xe)},[s,I,U]),K=Se=>{Se.preventDefault(),g(!0)},X=()=>{g(!1)},ce=Se=>{Se.preventDefault(),g(!1),Se.dataTransfer.files?.length&&$(Se.dataTransfer.files)},ne=o||h,G=[];(W||O)&&G.push(`Max size: ${yo(O)}`),J&&j.length>0&&G.push(`Allowed types: ${j.join(", ")}`),C>1&&G.push(`Up to ${C} files`);const ee=e.appearance?.hideLabel??!1,Pe=S.useMemo(()=>{if(!d)return null;const Se=Object.values(d);for(let xe=Se.length-1;xe>=0;xe-=1){const ae=Se[xe],ve=typeof ae?.status=="string"?ae.status.toLowerCase():null;if(ve&&ve!=="success")continue;const Ye=ae?.code;if(typeof Ye=="number"&&(Ye<200||Ye>=300))continue;const ct=ae?.data,Ge=ct?.file_url||ct?.fileUrl||ae?.file_url||ae?.fileUrl;if(typeof Ge=="string"&&Ge.trim())return Ge}return null},[d]),oe=S.useCallback(Se=>{window.open(Se,"_blank","noopener,noreferrer")},[]),re=S.useCallback(Se=>{w(xe=>new Set(xe).add(Se))},[]),be=I.length===0,de=I.length<C,ot=Rl(C,I.length);return c.jsx(Et,{field:e,error:ne,isRequired:i,className:B(a,"!space-y-0"),hideLabel:ee,children:c.jsx("div",{className:B("min-h-[70px] min-w-0 w-full flex flex-col",l?"flex-1 h-full":"h-[70px]"),children:c.jsxs("div",{onClick:Se=>{Se.target.closest("[data-remove-in-dropzone]")||Se.target.closest("[data-no-open-picker]")||D()},onDragOver:K,onDragLeave:X,onDrop:ce,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-primary bg-primary/10",ne&&"border-destructive",s&&"opacity-50 cursor-not-allowed",!de&&I.length>0&&"cursor-default"),children:[c.jsx("input",{ref:p,id:ht(e),type:"file",accept:M,multiple:C>1,onChange:ie,disabled:s||e.disabled||!de,className:"hidden","aria-describedby":jt(e,!!ne),"aria-invalid":Jt(!!ne),"aria-required":i}),be?c.jsxs(c.Fragment,{children:[c.jsx(Hs,{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:"Drag & drop or click"}),G.length>0&&c.jsx("p",{className:"text-[10px] text-muted-foreground line-clamp-1",children:G.join(" • ")})]}):ot?c.jsx(Yl,{item:I[0],objectUrl:T[0]??null,failedUrlKeys:v,onImageUrlError:re,onRemove:()=>V(0),onOpenUrl:oe,openTarget:I[0]instanceof File?Pe:void 0,disabled:s||e.disabled}):c.jsx(Kl,{items:I,maxFiles:C,disabled:s,objectUrls:T,failedUrlKeys:v,onImageUrlError:re,onRemove:V,resolveOpenUrl:(Se,xe)=>xe instanceof File&&I.length===1&&Pe?.trim()?Pe.trim():null,onOpenUrl:Se=>{Se?.trim()&&oe(Se.trim())},addSlot:de?c.jsxs("button",{type:"button","data-no-open-picker":!0,onClick:Se=>{Se.stopPropagation(),p.current?.click()},disabled:s||e.disabled,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(Hs,{className:"h-4 w-4 mb-0.5","aria-hidden":!0}),"Add"]}):void 0})]})})})};function _E(e){const t=kE(e),r=b.forwardRef((n,o)=>{const{children:s,...i}=n,a=b.Children.toArray(s),d=a.find(FE);if(d){const u=d.props.children,l=a.map(f=>f===d?b.Children.count(u)>1?b.Children.only(null):b.isValidElement(u)?u.props.children:null:f);return c.jsx(t,{...i,ref:o,children:b.isValidElement(u)?b.cloneElement(u,void 0,l):null})}return c.jsx(t,{...i,ref:o,children:s})});return r.displayName=`${e}.Slot`,r}function kE(e){const t=b.forwardRef((r,n)=>{const{children:o,...s}=r;if(b.isValidElement(o)){const i=OE(o),a=PE(s,o.props);return o.type!==b.Fragment&&(a.ref=n?Bn(n,i):i),b.cloneElement(o,a)}return b.Children.count(o)>1?b.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var TE=Symbol("radix.slottable");function FE(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===TE}function PE(e,t){const r={...t};for(const n in t){const o=e[n],s=t[n];/^on[A-Z]/.test(n)?o&&s?r[n]=(...a)=>{const d=s(...a);return o(...a),d}:o&&(r[n]=o):n==="style"?r[n]={...o,...s}:n==="className"&&(r[n]=[o,s].filter(Boolean).join(" "))}return{...e,...r}}function OE(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var $i="Dialog",[Ym]=vr($i),[IE,Rr]=Ym($i),Xm=e=>{const{__scopeDialog:t,children:r,open:n,defaultOpen:o,onOpenChange:s,modal:i=!0}=e,a=b.useRef(null),d=b.useRef(null),[u,l]=Zr({prop:n,defaultProp:o??!1,onChange:s,caller:$i});return c.jsx(IE,{scope:t,triggerRef:a,contentRef:d,contentId:on(),titleId:on(),descriptionId:on(),open:u,onOpenChange:l,onOpenToggle:b.useCallback(()=>l(f=>!f),[l]),modal:i,children:r})};Xm.displayName=$i;var Jm="DialogTrigger",ME=b.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,o=Rr(Jm,r),s=Ze(t,o.triggerRef);return c.jsx(Be.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ql(o.open),...n,ref:s,onClick:Me(e.onClick,o.onOpenToggle)})});ME.displayName=Jm;var Xl="DialogPortal",[LE,Qm]=Ym(Xl,{forceMount:void 0}),Zm=e=>{const{__scopeDialog:t,forceMount:r,children:n,container:o}=e,s=Rr(Xl,t);return c.jsx(LE,{scope:t,forceMount:r,children:b.Children.map(n,i=>c.jsx(xr,{present:r||s.open,children:c.jsx(ni,{asChild:!0,container:o,children:i})}))})};Zm.displayName=Xl;var ji="DialogOverlay",eh=b.forwardRef((e,t)=>{const r=Qm(ji,e.__scopeDialog),{forceMount:n=r.forceMount,...o}=e,s=Rr(ji,e.__scopeDialog);return s.modal?c.jsx(xr,{present:n||s.open,children:c.jsx(BE,{...o,ref:t})}):null});eh.displayName=ji;var DE=_E("DialogOverlay.RemoveScroll"),BE=b.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,o=Rr(ji,r);return c.jsx(ui,{as:DE,allowPinchZoom:!0,shards:[o.contentRef],children:c.jsx(Be.div,{"data-state":Ql(o.open),...n,ref:t,style:{pointerEvents:"auto",...n.style}})})}),Gn="DialogContent",th=b.forwardRef((e,t)=>{const r=Qm(Gn,e.__scopeDialog),{forceMount:n=r.forceMount,...o}=e,s=Rr(Gn,e.__scopeDialog);return c.jsx(xr,{present:n||s.open,children:s.modal?c.jsx($E,{...o,ref:t}):c.jsx(jE,{...o,ref:t})})});th.displayName=Gn;var $E=b.forwardRef((e,t)=>{const r=Rr(Gn,e.__scopeDialog),n=b.useRef(null),o=Ze(t,r.contentRef,n);return b.useEffect(()=>{const s=n.current;if(s)return sl(s)},[]),c.jsx(rh,{...e,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Me(e.onCloseAutoFocus,s=>{s.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:Me(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,a=i.button===0&&i.ctrlKey===!0;(i.button===2||a)&&s.preventDefault()}),onFocusOutside:Me(e.onFocusOutside,s=>s.preventDefault())})}),jE=b.forwardRef((e,t)=>{const r=Rr(Gn,e.__scopeDialog),n=b.useRef(!1),o=b.useRef(!1);return c.jsx(rh,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{e.onCloseAutoFocus?.(s),s.defaultPrevented||(n.current||r.triggerRef.current?.focus(),s.preventDefault()),n.current=!1,o.current=!1},onInteractOutside:s=>{e.onInteractOutside?.(s),s.defaultPrevented||(n.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;r.triggerRef.current?.contains(i)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),rh=b.forwardRef((e,t)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:o,onCloseAutoFocus:s,...i}=e,a=Rr(Gn,r),d=b.useRef(null),u=Ze(t,d);return za(),c.jsxs(c.Fragment,{children:[c.jsx(Rs,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:o,onUnmountAutoFocus:s,children:c.jsx(Ws,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":Ql(a.open),...i,ref:u,onDismiss:()=>a.onOpenChange(!1)})}),c.jsxs(c.Fragment,{children:[c.jsx(UE,{titleId:a.titleId}),c.jsx(HE,{contentRef:d,descriptionId:a.descriptionId})]})]})}),Jl="DialogTitle",nh=b.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,o=Rr(Jl,r);return c.jsx(Be.h2,{id:o.titleId,...n,ref:t})});nh.displayName=Jl;var oh="DialogDescription",zE=b.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,o=Rr(oh,r);return c.jsx(Be.p,{id:o.descriptionId,...n,ref:t})});zE.displayName=oh;var sh="DialogClose",ih=b.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,o=Rr(sh,r);return c.jsx(Be.button,{type:"button",...n,ref:t,onClick:Me(e.onClick,()=>o.onOpenChange(!1))})});ih.displayName=sh;function Ql(e){return e?"open":"closed"}var ah="DialogTitleWarning",[XP,lh]=Ov(ah,{contentName:Gn,titleName:Jl,docsSlug:"dialog"}),UE=({titleId:e})=>{const t=lh(ah),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
46
|
+
`+s):n.stack=s}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=Hn(this.defaults,r);const{transitional:n,paramsSerializer:o,headers:s}=r;n!==void 0&&Ei.assertOptions(n,{silentJSONParsing:Or.transitional(Or.boolean),forcedJSONParsing:Or.transitional(Or.boolean),clarifyTimeoutError:Or.transitional(Or.boolean),legacyInterceptorReqResOrdering:Or.transitional(Or.boolean)},!1),o!=null&&(R.isFunction(o)?r.paramsSerializer={serialize:o}:Ei.assertOptions(o,{encode:Or.function,serialize:Or.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Ei.assertOptions(r,{baseUrl:Or.spelling("baseURL"),withXsrfToken:Or.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let i=s&&R.merge(s.common,s[r.method]);s&&R.forEach(["delete","get","head","post","put","patch","common"],g=>{delete s[g]}),r.headers=mr.concat(i,s);const a=[];let d=!0;this.interceptors.request.forEach(function(h){if(typeof h.runWhen=="function"&&h.runWhen(r)===!1)return;d=d&&h.synchronous;const y=r.transitional||xl;y&&y.legacyInterceptorReqResOrdering?a.unshift(h.fulfilled,h.rejected):a.push(h.fulfilled,h.rejected)});const u=[];this.interceptors.response.forEach(function(h){u.push(h.fulfilled,h.rejected)});let l,f=0,p;if(!d){const g=[wp.bind(this),void 0];for(g.unshift(...a),g.push(...u),p=g.length,l=Promise.resolve(r);f<p;)l=l.then(g[f++],g[f++]);return l}p=a.length;let m=r;for(;f<p;){const g=a[f++],h=a[f++];try{m=g(m)}catch(y){h.call(this,y);break}}try{l=wp.call(this,m)}catch(g){return Promise.reject(g)}for(f=0,p=u.length;f<p;)l=l.then(u[f++],u[f++]);return l}getUri(t){t=Hn(this.defaults,t);const r=cp(t.baseURL,t.url,t.allowAbsoluteUrls);return tp(r,t.params,t.paramsSerializer)}};R.forEach(["delete","get","head","options"],function(t){Wn.prototype[t]=function(r,n){return this.request(Hn(n||{},{method:t,url:r,data:(n||{}).data}))}}),R.forEach(["post","put","patch"],function(t){function r(n){return function(s,i,a){return this.request(Hn(a||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Wn.prototype[t]=r(),Wn.prototype[t+"Form"]=r(!0)});let FA=class Fy{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(s){r=s});const n=this;this.promise.then(o=>{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](o);n._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{n.subscribe(a),s=a}).then(o);return i.cancel=function(){n.unsubscribe(s)},i},t(function(s,i,a){n.reason||(n.reason=new ss(s,i,a),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new Fy(function(o){t=o}),cancel:t}}};function PA(e){return function(r){return e.apply(null,r)}}function OA(e){return R.isObject(e)&&e.isAxiosError===!0}const Tl={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Tl).forEach(([e,t])=>{Tl[t]=e});function Ap(e){const t=new Wn(e),r=Uf(Wn.prototype.request,t);return R.extend(r,Wn.prototype,t,{allOwnKeys:!0}),R.extend(r,t,null,{allOwnKeys:!0}),r.create=function(o){return Ap(Hn(e,o))},r}const _t=Ap(ns);_t.Axios=Wn,_t.CanceledError=ss,_t.CancelToken=FA,_t.isCancel=sp,_t.VERSION=Sp,_t.toFormData=wi,_t.AxiosError=qe,_t.Cancel=_t.CanceledError,_t.all=function(t){return Promise.all(t)},_t.spread=PA,_t.isAxiosError=OA,_t.mergeConfig=Hn,_t.AxiosHeaders=mr,_t.formToJSON=e=>np(R.isHTMLForm(e)?new FormData(e):e),_t.getAdapter=vp.getAdapter,_t.HttpStatusCode=Tl,_t.default=_t;const{Axios:$P,AxiosError:IA,CanceledError:jP,isCancel:zP,CancelToken:UP,VERSION:VP,all:HP,Cancel:WP,isAxiosError:RP,spread:GP,toFormData:KP,AxiosHeaders:qP,HttpStatusCode:YP,formToJSON:XP,getAdapter:JP,mergeConfig:QP}=_t;function or(e,t){if(!t||t.trim()===""||e==null)return;const r=t.split(".").filter(Boolean);let n=e;for(const o of r){if(n==null)return;n=n[o]}return n}function MA(e){const t={array:[],pathPrefixToStrip:""};function r(a,d){if(a===null||typeof a!="object")return null;if(Array.isArray(a)&&a.length>0)return{array:a,fullPath:d};const u=Object.keys(a);for(const l of u){const f=a[l],p=d?`${d}.${l}`:l;if(Array.isArray(f)&&f.length>0)return{array:f,fullPath:p};if(f!==null&&typeof f=="object"){const m=r(f,p);if(m)return m}}return null}const n=r(e,"");if(!n)return t;const{array:o,fullPath:s}=n,i=s?`data.${s}.`:"";return{array:o,pathPrefixToStrip:i}}function LA(e){return e.length>=4&&Array.isArray(e[3])&&e[3].length===0}function DA(e,t,r){if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"){const s=String(e);return{label:s,value:s,disabled:!1}}if(e==null)return{label:"",value:"",disabled:!0};if(typeof e!="object"||Array.isArray(e)){const s=Array.isArray(e)?"":String(e);return{label:s,value:s,disabled:!1}}let n,o;if(t){const s=t.includes(".")?or(e,t):e[t];n=String(s!==void 0?s:e.label??e.name??e.title??e.text??e.username??e.email??e.value??e.id??"")}else n=String(e.label??e.name??e.title??e.text??e.username??e.email??e.value??e.id??"");if(r){const s=r.includes(".")?or(e,r):e[r];o=String(s!==void 0?s:e.value??e.id??e.key??e.email??e.username??e.label??e.name??"")}else o=String(e.value??e.id??e.key??e.email??e.username??e.label??e.name??"");return{label:String(n??""),value:String(o??""),disabled:!!e.disabled}}function Fl(e,t,r){if(!e)return[];if(Array.isArray(e)){if(e.length===0)return[];if(LA(e))return[];const n=e.filter(o=>o!=null);return n.length===0?[]:n.every(o=>typeof o=="string")?n.map(o=>({label:o,value:o,disabled:!1})):n.map(o=>DA(o,t,r))}if(typeof e=="object"){const{array:n,pathPrefixToStrip:o}=MA(e);if(Array.isArray(n)&&n.length>0){const s=d=>!d||!d.trim()||!o?d:d.startsWith(o)?d.substring(o.length).replace(/^\.+/,"")||void 0:d,i=s(t),a=s(r);return Fl(n,i,a)}}return[]}function BA(e){return!Array.isArray(e)||e.length===0?[]:e.filter(t=>t!=null).map((t,r)=>{if(typeof t=="string")return{label:t,value:t};if(typeof t=="object"&&t!==null){const n=t.label||t.value||String(t),o=t.value||t.label||String(t);return!n&&!o?{label:`Option ${r+1}`,value:String(r)}:{label:String(n),value:String(o),disabled:t.disabled||!1}}return{label:String(t),value:String(t)}})}function $A(e){return Array.isArray(e)&&e.length>=4&&Array.isArray(e[3])&&e[3].length>0&&Array.isArray(e[3][0])}function jA(e,t,r){if(!e)return[];try{const o=new URL(e).searchParams.get(t);return o?o.split(r).map(s=>s.trim()).filter(Boolean):[]}catch{const n=e.indexOf("?");if(n<0)return[];const o=e.slice(n+1);try{const i=new URLSearchParams(o).get(t);return i?i.split(r).map(a=>a.trim()).filter(Boolean):[]}catch{return[]}}}function Cp(e){const{response:t,sourceUrl:r,rowsIndex:n,rowsPath:o,columns:s,columnsQueryParam:i="sf",columnsQueryParamSeparator:a=","}=e;let d;if(o&&o.trim()?d=or(t,o):typeof n=="number"?d=t?.[n]:d=t,!Array.isArray(d)||d.length===0)return[];const u=d.filter(p=>Array.isArray(p));if(u.length===0)return Array.isArray(d[0])?[]:null;if(!Array.isArray(u[0]))return null;const l=jA(r,i,a),f=l.length>0?l:Array.isArray(s)&&s.length>0?s:[];return u.map(p=>{const m={};return(f.length>0?f:Array.from({length:p.length},(h,y)=>`col${y}`)).forEach((h,y)=>{m[h]=p[y]}),m})}function zA(e){const{rows:t,apiLabelField:r,apiLabelFields:n,apiLabelSeparator:o,apiValueField:s}=e;if(!Array.isArray(t)||t.length===0)return[];const i=t.filter(f=>f!=null&&typeof f=="object"&&!Array.isArray(f));if(i.length===0)return[];const a=Array.isArray(n)?n.filter(Boolean):[],d=o??" - ",u=f=>{if(r){const p=r.includes(".")?or(f,r):f?.[r];if(p!=null&&String(p).trim()!=="")return String(p)}return String(f?.label??f?.name??f?.title??f?.text??f?.username??f?.email??f?.value??f?.id??f)},l=(f,p)=>{if(s){const m=s.includes(".")?or(f,s):f?.[s];if(m!=null)return String(m)}return String(f?.value??f?.id??f?.key??f?.email??f?.username??f?.label??f?.name??p??f)};return i.map(f=>{let p="";a.length>0&&(p=a.map(h=>or(f,h)).filter(h=>h!=null&&String(h).trim()!=="").map(h=>String(h)).join(d)),p||(p=u(f));const m=l(f,p);return{label:typeof p=="string"?p:String(p??""),value:typeof m=="string"?m:String(m??""),disabled:!!f?.disabled}})}let Ep=null;function UA(e){Ep=e}function Np(){return(Ep?.()??"").replace(/\/+$/,"")}function cn(e){const t=typeof e=="string"?e.trim():"";if(!t||/^https?:\/\//i.test(t))return t;const r=Np();return r?t.startsWith("/")?`${r}${t}`:`${r}/${t}`:t}function _p({field:e,formValues:t={},submissionContext:r}){const n=e.properties,o=n?.apiEndpoint?{apiEndpoint:n.apiEndpoint,apiMethod:n.apiMethod,apiKey:n.apiKey,apiRealtime:n.apiRealtime,apiAutoDetect:n.apiAutoDetect,apiLabelField:n.apiLabelField,apiValueField:n.apiValueField,apiQueryParams:n.apiQueryParams,apiClientFilter:n.apiClientFilter,valueSource:n.valueSource,optionsSource:n.optionsSource}:null,s=e.apidata||null,i=o||s,[a,d]=S.useState([]),[u,l]=S.useState([]),[f,p]=S.useState([]),[m,g]=S.useState(!1),[h,y]=S.useState(null),v=!!(i?.apiEndpoint&&(i?.valueSource==="api"||i?.optionsSource==="api"||n?.valueSource==="api"||n?.optionsSource==="api")),w=e.options||n?.options||[],x=S.useMemo(()=>BA(Array.isArray(w)?w:[]),[w]),E=S.useMemo(()=>{const I=i?.apiEndpoint||n?.apiEndpoint||"",T=i?.apiQueryParams||n?.apiQueryParams;return $s(I,T)},[i?.apiEndpoint,n?.apiEndpoint,i?.apiQueryParams,n?.apiQueryParams]),P=S.useMemo(()=>{const I=new Set;for(const W of n?.dependentFields??[])typeof W=="string"&&W.trim()&&I.add(W.trim());const T=i?.apiClientFilter?.matchField?.trim()||n?.apiClientFilter?.matchField?.trim();return T&&I.add(T),[...I]},[n?.dependentFields,i?.apiClientFilter?.matchField,n?.apiClientFilter?.matchField]),C=S.useMemo(()=>{const I=new Set([...E,...P]);if(I.size===0)return null;const T={};return I.forEach(W=>{T[W]=t[W]}),JSON.stringify(T)},[E,P,t]),N=S.useMemo(()=>JSON.stringify(r||{}),[r]),_=S.useMemo(()=>{const I=new Set;e.name?.trim()&&I.add(e.name.trim());const T=e.key;return typeof T=="string"&&T.trim()&&I.add(T.trim()),[...I]},[e.name,e.key]);return S.useEffect(()=>{const I=i?.apiEndpoint;if(!v||!I){d([]);return}let T=!1;return(async()=>{a.length===0&&g(!0),y(null);try{const O=i?.apiMethod||n?.apiMethod||"GET",j=i?.apiRealtime||n?.apiRealtime,M=i?.apiQueryParams||n?.apiQueryParams||{},D=zd({apiEndpoint:I,apiMethod:O,apiQueryParams:M,formValues:t,submissionContext:r,apiRealtime:j,additionalRequiredFieldNames:P,excludeFormFieldNames:_});if(D.blocked){T||(d([]),g(!1));return}const L={"Content-Type":"application/json"},U=i?.apiKey||n?.apiKey;U&&(L["X-CSCAPI-KEY"]=U);const $={method:O.toLowerCase(),url:cn(D.url),headers:L};D.postBodyBase!=null&&($.data=D.postBodyBase);const ie=await _t($),V=i?.apiLabelField||n?.apiLabelField,K=i?.apiValueField||n?.apiValueField,X=ie.data;let ce=[];Array.isArray(X)?ce=X:X?.data&&(Array.isArray(X.data)?ce=X.data:X.data?.data&&Array.isArray(X.data.data)?ce=X.data.data:X.data.districts?ce=X.data.districts:X.data.states?ce=X.data.states:X.data.cities&&(ce=X.data.cities)),p(ce);const ne=Fl(ie.data,V,K);l(ne);const G=i?.apiClientFilter||n?.apiClientFilter;let ee=ne;if(G?.filterField&&G?.matchField){const Pe=t[G.matchField];Pe!=null?ee=ne.filter(oe=>{const re=ce.find(de=>String(or(de,K||"code"))===String(oe.value));if(!re)return!1;const be=or(re,G.filterField);return String(be)===String(Pe)}):ee=[]}T||d(ee)}catch(O){if(T)return;let j="Failed to load options";if(O.response){const M=O.response.data;O.response.status===404?j="API endpoint not found.":O.response.status===401?j="Authentication failed.":typeof M=="string"?j=M:M&&typeof M=="object"&&(j=M.error||M.message||M.detail||j)}else O.message&&(j=String(O.message));y(j),a.length===0&&d([])}finally{T||g(!1)}})(),()=>{T=!0}},[v,i?.apiEndpoint,i?.apiMethod,n?.apiEndpoint,n?.apiMethod,C,P,_,N]),S.useEffect(()=>{const I=i?.apiClientFilter||n?.apiClientFilter;if(!v||!I||f.length===0)return;const T=t[I.matchField],W=i?.apiValueField||n?.apiValueField;if(T==null){d([]);return}const J=u.filter(O=>{const j=f.find(D=>String(or(D,W||"code"))===String(O.value));if(!j)return!1;const M=or(j,I.filterField);return String(M)===String(T)});d(J)},[v,i?.apiClientFilter?.matchField,n?.apiClientFilter?.matchField,i?.apiClientFilter?.filterField,n?.apiClientFilter?.filterField,i?.apiValueField,n?.apiValueField,t[i?.apiClientFilter?.matchField||n?.apiClientFilter?.matchField||""],u,f]),{options:v?a:x,isLoadingOptions:m,optionsError:h}}const kp=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a,formValues:d={},submissionContext:u,excludedOptionValues:l,isPrepopulateTarget:f=!1})=>{const p=e.properties,m=p?.apiEndpoint?{apiEndpoint:p.apiEndpoint,valueSource:p.valueSource,optionsSource:p.optionsSource}:null,g=e.apidata||null,h=m||g,y=!!(h?.apiEndpoint&&(h?.valueSource==="api"||h?.optionsSource==="api"||p?.valueSource==="api"||p?.optionsSource==="api")),{options:v,isLoadingOptions:w,optionsError:x}=_p({field:e,formValues:d,submissionContext:u}),E=l?.length?new Set(l.map(String)):null,P=E?v.filter($=>!E.has(String($.value??$.label??""))):v,C="__clear__",N=t!=null&&String(t).trim()!=="",_=N?P.some($=>String($.value??$.label??"")===String(t)):!1,A=S.useMemo(()=>{if(!N||_)return P;const $=String(t);return[{label:$,value:$},...P]},[P,N,_,t]),I=N?String(t):void 0,T=`${ht(e)}-${I??"empty"}`,W=S.useCallback($=>{r($===C?"":$),n?.()},[r,n]),J=e.appearance?.size||"md",O={sm:"h-8 text-sm",md:"h-10",lg:"h-12 text-lg"},j=e.placeholder||"Select an option",M=p?.apiClientFilter?.matchField?.trim()||h?.apiClientFilter?.matchField?.trim(),D=y&&M&&(d[M]===void 0||d[M]===null||d[M]===""),L=w?"Loading options...":D?`Select ${M} first`:l?.length?"No available options":y?"No options available from API":"No options available";return y&&f&&w?c.jsx(Et,{field:e,error:o||x||void 0,isRequired:i,className:a,children:c.jsxs("div",{role:"status","aria-label":"Loading options",className:B("flex items-center justify-center gap-2 w-full min-w-0 rounded-md border border-input bg-muted/50 text-muted-foreground",O[J],e.appearance?.className),children:[c.jsx(Ro,{className:"h-4 w-4 animate-spin shrink-0"}),c.jsx("span",{className:"truncate",children:"Loading..."})]})}):c.jsx(Et,{field:e,error:o||x||void 0,isRequired:i,className:a,children:c.jsxs(t0,{value:I,onValueChange:W,disabled:s||e.disabled||w&&P.length===0,children:[c.jsx(n0,{id:ht(e),"aria-describedby":jt(e,!!o||!!x),"aria-invalid":Jt(!!o||!!x),"aria-required":i,className:B("w-full min-w-0",O[J],o&&"border-destructive focus-visible:ring-destructive",x&&"border-destructive focus-visible:ring-destructive",e.appearance?.className),children:c.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[w&&c.jsx(Ro,{className:"h-4 w-4 animate-spin text-muted-foreground shrink-0"}),P.length===0&&l?.length&&!N?c.jsx("span",{className:"text-muted-foreground truncate",children:"No available options"}):N?c.jsx(r0,{placeholder:j}):c.jsx("span",{className:"text-muted-foreground truncate",children:j})]})}),c.jsx(o0,{children:A.length===0?c.jsx(gl,{value:"__no_options__",disabled:!0,children:L}):c.jsxs(c.Fragment,{children:[N?c.jsx(gl,{value:C,children:j}):null,A.map(($,ie)=>{const V=String($.value??$.label??ie);if(V===C)return null;const K=$.label||$.value||String($);return c.jsx(gl,{value:V,disabled:$.disabled||!1,children:K},V)})]})})]},T)})},Tp=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Fp=Jc,Pp=(e,t)=>r=>{var n;if(t?.variants==null)return Fp(e,r?.class,r?.className);const{variants:o,defaultVariants:s}=t,i=Object.keys(o).map(u=>{const l=r?.[u],f=s?.[u];if(l===null)return null;const p=Tp(l)||Tp(f);return o[u][p]}),a=r&&Object.entries(r).reduce((u,l)=>{let[f,p]=l;return p===void 0||(u[f]=p),u},{}),d=t==null||(n=t.compoundVariants)===null||n===void 0?void 0:n.reduce((u,l)=>{let{class:f,className:p,...m}=l;return Object.entries(m).every(g=>{let[h,y]=g;return Array.isArray(y)?y.includes({...s,...a}[h]):{...s,...a}[h]===y})?[...u,f,p]:u},[]);return Fp(e,i,d,r?.class,r?.className)},VA=Pp("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all cursor-pointer disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",destructive:"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}});function Yt({className:e,variant:t,size:r,asChild:n=!1,...o}){const s=n?qd:"button";return c.jsx(s,{"data-slot":"button",className:B(VA({variant:t,size:r,className:e})),...o})}function HA(e,t){return b.useReducer((r,n)=>t[r][n]??r,e)}var xr=e=>{const{present:t,children:r}=e,n=WA(t),o=typeof r=="function"?r({present:n.isPresent}):b.Children.only(r),s=Ze(n.ref,RA(o));return typeof r=="function"||n.isPresent?b.cloneElement(o,{ref:s}):null};xr.displayName="Presence";function WA(e){const[t,r]=b.useState(),n=b.useRef(null),o=b.useRef(e),s=b.useRef("none"),i=e?"mounted":"unmounted",[a,d]=HA(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{const u=Ni(n.current);s.current=a==="mounted"?u:"none"},[a]),Qt(()=>{const u=n.current,l=o.current;if(l!==e){const p=s.current,m=Ni(u);e?d("MOUNT"):m==="none"||u?.display==="none"?d("UNMOUNT"):d(l&&p!==m?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,d]),Qt(()=>{if(t){let u;const l=t.ownerDocument.defaultView??window,f=m=>{const h=Ni(n.current).includes(CSS.escape(m.animationName));if(m.target===t&&h&&(d("ANIMATION_END"),!o.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",u=l.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},p=m=>{m.target===t&&(s.current=Ni(n.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{l.clearTimeout(u),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:b.useCallback(u=>{n.current=u?getComputedStyle(u):null,r(u)},[])}}function Ni(e){return e?.animationName||"none"}function RA(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}function GA(e){const t=KA(e),r=b.forwardRef((n,o)=>{const{children:s,...i}=n,a=b.Children.toArray(s),d=a.find(YA);if(d){const u=d.props.children,l=a.map(f=>f===d?b.Children.count(u)>1?b.Children.only(null):b.isValidElement(u)?u.props.children:null:f);return c.jsx(t,{...i,ref:o,children:b.isValidElement(u)?b.cloneElement(u,void 0,l):null})}return c.jsx(t,{...i,ref:o,children:s})});return r.displayName=`${e}.Slot`,r}function KA(e){const t=b.forwardRef((r,n)=>{const{children:o,...s}=r;if(b.isValidElement(o)){const i=JA(o),a=XA(s,o.props);return o.type!==b.Fragment&&(a.ref=n?Bn(n,i):i),b.cloneElement(o,a)}return b.Children.count(o)>1?b.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var qA=Symbol("radix.slottable");function YA(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===qA}function XA(e,t){const r={...t};for(const n in t){const o=e[n],s=t[n];/^on[A-Z]/.test(n)?o&&s?r[n]=(...a)=>{const d=s(...a);return o(...a),d}:o&&(r[n]=o):n==="style"?r[n]={...o,...s}:n==="className"&&(r[n]=[o,s].filter(Boolean).join(" "))}return{...e,...r}}function JA(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var _i="Popover",[Op]=vr(_i,[ri]),is=ri(),[QA,kn]=Op(_i),Ip=e=>{const{__scopePopover:t,children:r,open:n,defaultOpen:o,onOpenChange:s,modal:i=!1}=e,a=is(t),d=b.useRef(null),[u,l]=b.useState(!1),[f,p]=Zr({prop:n,defaultProp:o??!1,onChange:s,caller:_i});return c.jsx(Ju,{...a,children:c.jsx(QA,{scope:t,contentId:on(),triggerRef:d,open:f,onOpenChange:p,onOpenToggle:b.useCallback(()=>p(m=>!m),[p]),hasCustomAnchor:u,onCustomAnchorAdd:b.useCallback(()=>l(!0),[]),onCustomAnchorRemove:b.useCallback(()=>l(!1),[]),modal:i,children:r})})};Ip.displayName=_i;var Mp="PopoverAnchor",Lp=b.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,o=kn(Mp,r),s=is(r),{onCustomAnchorAdd:i,onCustomAnchorRemove:a}=o;return b.useEffect(()=>(i(),()=>a()),[i,a]),c.jsx(nl,{...s,...n,ref:t})});Lp.displayName=Mp;var Dp="PopoverTrigger",Bp=b.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,o=kn(Dp,r),s=is(r),i=Ze(t,o.triggerRef),a=c.jsx(Be.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Vp(o.open),...n,ref:i,onClick:Me(e.onClick,o.onOpenToggle)});return o.hasCustomAnchor?a:c.jsx(nl,{asChild:!0,...s,children:a})});Bp.displayName=Dp;var Pl="PopoverPortal",[ZA,eC]=Op(Pl,{forceMount:void 0}),$p=e=>{const{__scopePopover:t,forceMount:r,children:n,container:o}=e,s=kn(Pl,t);return c.jsx(ZA,{scope:t,forceMount:r,children:c.jsx(xr,{present:r||s.open,children:c.jsx(ni,{asChild:!0,container:o,children:n})})})};$p.displayName=Pl;var ho="PopoverContent",jp=b.forwardRef((e,t)=>{const r=eC(ho,e.__scopePopover),{forceMount:n=r.forceMount,...o}=e,s=kn(ho,e.__scopePopover);return c.jsx(xr,{present:n||s.open,children:s.modal?c.jsx(rC,{...o,ref:t}):c.jsx(nC,{...o,ref:t})})});jp.displayName=ho;var tC=GA("PopoverContent.RemoveScroll"),rC=b.forwardRef((e,t)=>{const r=kn(ho,e.__scopePopover),n=b.useRef(null),o=Ze(t,n),s=b.useRef(!1);return b.useEffect(()=>{const i=n.current;if(i)return sl(i)},[]),c.jsx(ui,{as:tC,allowPinchZoom:!0,children:c.jsx(zp,{...e,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Me(e.onCloseAutoFocus,i=>{i.preventDefault(),s.current||r.triggerRef.current?.focus()}),onPointerDownOutside:Me(e.onPointerDownOutside,i=>{const a=i.detail.originalEvent,d=a.button===0&&a.ctrlKey===!0,u=a.button===2||d;s.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:Me(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1})})})}),nC=b.forwardRef((e,t)=>{const r=kn(ho,e.__scopePopover),n=b.useRef(!1),o=b.useRef(!1);return c.jsx(zp,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{e.onCloseAutoFocus?.(s),s.defaultPrevented||(n.current||r.triggerRef.current?.focus(),s.preventDefault()),n.current=!1,o.current=!1},onInteractOutside:s=>{e.onInteractOutside?.(s),s.defaultPrevented||(n.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;r.triggerRef.current?.contains(i)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),zp=b.forwardRef((e,t)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:o,onCloseAutoFocus:s,disableOutsidePointerEvents:i,onEscapeKeyDown:a,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:l,...f}=e,p=kn(ho,r),m=is(r);return za(),c.jsx(Rs,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:o,onUnmountAutoFocus:s,children:c.jsx(Ws,{asChild:!0,disableOutsidePointerEvents:i,onInteractOutside:l,onEscapeKeyDown:a,onPointerDownOutside:d,onFocusOutside:u,onDismiss:()=>p.onOpenChange(!1),children:c.jsx(Qu,{"data-state":Vp(p.open),role:"dialog",id:p.contentId,...m,...f,ref:t,style:{...f.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),Up="PopoverClose",oC=b.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,o=kn(Up,r);return c.jsx(Be.button,{type:"button",...n,ref:t,onClick:Me(e.onClick,()=>o.onOpenChange(!1))})});oC.displayName=Up;var sC="PopoverArrow",iC=b.forwardRef((e,t)=>{const{__scopePopover:r,...n}=e,o=is(r);return c.jsx(Zu,{...o,...n,ref:t})});iC.displayName=sC;function Vp(e){return e?"open":"closed"}var aC=Ip,lC=Lp,cC=Bp,dC=$p,uC=jp;function Ol({...e}){return c.jsx(aC,{"data-slot":"popover",...e})}function Hp({...e}){return c.jsx(cC,{"data-slot":"popover-trigger",...e})}function Il({className:e,align:t="center",sideOffset:r=4,...n}){return c.jsx(dC,{children:c.jsx(uC,{"data-slot":"popover-content",align:t,sideOffset:r,className:B("bg-popover text-popover-foreground 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 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden pointer-events-auto",e),...n})})}function fC({...e}){return c.jsx(lC,{"data-slot":"popover-anchor",...e})}const Wp={};function Tn(){const e=Wp?.VITE_CLIENT_ID?.trim()||Wp?.VITE_DEFAULT_CLIENT_ID?.trim()||null;return(typeof localStorage<"u"?localStorage.getItem("clientId"):null)||(typeof sessionStorage<"u"?sessionStorage.getItem("clientId"):null)||(typeof window<"u"?new URLSearchParams(window.location.search).get("clientId"):null)||e}function pC(e){return!e||typeof e!="object"?!1:e.userId!=null&&String(e.userId)!==""||e.userType!=null&&String(e.userType)!==""||e.role!=null&&String(e.role)!==""}function mC(e){if(!e||typeof e!="object")return;const t={};for(const[r,n]of Object.entries(e))n!==void 0&&n!==""&&(t[r]=n);return Object.keys(t).length>0?t:void 0}const Rn=Pd(e=>({viewerContext:void 0,authHeaders:void 0,_setViewerContext:t=>e({viewerContext:pC(t)?t:void 0}),_setAuthHeaders:t=>e({authHeaders:mC(t)}),_reset:()=>e({viewerContext:void 0,authHeaders:void 0})}));function hC(e){Rn.getState()._setViewerContext(e)}function gC(e){Rn.getState()._setAuthHeaders(e)}function yC(){Rn.getState()._reset()}function bC(){return Rn.getState().viewerContext}function Ml(){return Rn.getState().authHeaders}const Rp={};let Gp=null;function vC(e){Gp=e}function wC(){return(Rp?.VITE_API_BASE_URL?.trim()||Rp?.VITE_API_URL?.trim()||"").replace(/\/$/,"")}const dn=_t.create({baseURL:wC()});dn.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=Gp?.();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});function Kp(e){return JSON.stringify(e).slice(1,-1)}function qp(e){const t=e.asyncSearchValueObjectKeys;return Array.isArray(t)?t.map(r=>typeof r=="string"?r.trim():"").filter(Boolean):[]}function SC(e){return e.asyncSearchValueMode==="object"&&qp(e).length>0}function xC(e,t){const r={};for(const n of t){const o=n.trim();if(!o)continue;const s=or(e,o);s==null||typeof s=="object"?r[o]="":r[o]=String(s)}return r}function AC(e,t){const r=t.mode??"debounce",n=Math.max(0,t.intervalMs??300),[o,s]=S.useState(()=>r==="throttle"?e:""),i=S.useRef(0),a=S.useRef(void 0);return S.useEffect(()=>{if(e===""){a.current&&clearTimeout(a.current),s("");return}if(r==="debounce"){const l=setTimeout(()=>s(e),n);return()=>clearTimeout(l)}const d=Date.now(),u=d-i.current;return u>=n?(i.current=d,s(e),()=>{a.current&&clearTimeout(a.current)}):(a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i.current=Date.now(),s(e),a.current=void 0},n-u),()=>{a.current&&clearTimeout(a.current)})},[e,r,n]),o}function Ll(e,t){if(e==null||e==="")return"";if(t&&typeof e=="object"&&!Array.isArray(e)){const r=e,o=Object.keys(r).sort().map(s=>[s,r[s]??""]);return`O:${JSON.stringify(o)}`}return typeof e=="string"?`S:${e}`:""}function Dl(e,t){return e==null||e===""?!0:t&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).length===0:!1}function CC(e,t,r){return t.trim()!==""?!0:e==null||e===""?!1:r&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).length>0:typeof e=="string"&&e.length>0}function EC(e){if(_t.isAxiosError(e)){const t=e.response?.status,r=e.response?.data;if(t===404)return"Search endpoint not found.";if(t===401)return"Authentication failed.";if(r&&typeof r=="object"){const n=r,o=n.error??n.message??n.detail??n.explanation;if(typeof o=="string")return o}if(typeof r=="string")return r;if(t)return`Request failed (${t})`}return e instanceof Error?e.message:"Search failed"}function NC(e){if(e==null)return[];if(Array.isArray(e))return e;const t=e;if(!t?.data)return[];const r=t.data;return Array.isArray(r)?r:r?.data&&Array.isArray(r.data)?r.data:Array.isArray(r?.districts)?r.districts:Array.isArray(r?.states)?r.states:Array.isArray(r?.cities)?r.cities:[]}function Yp(e,t){return typeof t=="number"&&t>0?e.slice(0,t):e}function Bl(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.label=="string"&&t.value!==null&&t.value!==void 0}const Xp=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d,formValues:u={},submissionContext:l})=>{const f=e.properties||{},p=SC(f),m=f.apiEndpoint?.trim()||"",g=f.apiRealtime===!0,h=(f.apiMethod||"GET").toUpperCase()==="POST"?"POST":"GET",y=f.searchInBody===!0,v=h==="POST"||h==="GET"&&y,w=f.searchStrategy??f.searchSchedule??"debounce",x=f.searchIntervalMs??f.intervalMs??300,E=f.minQueryLength??0,P=f.maxResults,C=f.searchQueryParam||"q",N=f.clearable!==!1,_=u,[A,I]=S.useState(()=>Dl(t,p)?"":p&&typeof t=="object"&&t!==null&&!Array.isArray(t)?f.initialDisplayLabel||"":f.initialDisplayLabel||String(t)),[T,W]=S.useState(!1),[J,O]=S.useState([]),[j,M]=S.useState([]),[D,L]=S.useState([]),[U,$]=S.useState(!1),[ie,V]=S.useState(null),[K,X]=S.useState(-1),ce=S.useRef(Ll(t,p)),ne=S.useRef(Dl(t,p)?"":p&&typeof t=="object"&&t!==null&&!Array.isArray(t)?f.initialDisplayLabel||"":f.initialDisplayLabel||String(t??"")),G=S.useRef(void 0),ee=S.useRef(0),Pe=S.useRef(null),oe=AC(A,{mode:w,intervalMs:x}),re=S.useMemo(()=>J.filter(Bl),[J]);S.useEffect(()=>{if(re.length===0){K!==-1&&X(-1);return}(K<0||K>=re.length)&&X(0)},[K,re.length]);const be=S.useMemo(()=>{const te=$s(m,f.apiQueryParams),pe=new Set(te);for(const We of f.dependentFields||[])We&&pe.add(We);return pe},[m,f.apiQueryParams,f.dependentFields]),de=S.useMemo(()=>{if(be.size===0)return null;const te={};return be.forEach(pe=>{te[pe]=_[pe]}),JSON.stringify(te)},[be,_]),ot=S.useMemo(()=>JSON.stringify(u),[u]),Se=S.useMemo(()=>JSON.stringify(l||{}),[l]);S.useEffect(()=>{const te=Ll(t,p);if(te===ce.current)return;if(ce.current=te,Dl(t,p)){ne.current="",I(""),O([]),M([]),L([]),V(null),W(!1);return}const pe=f.initialDisplayLabel||(!p&&typeof t=="string"?t:"");ne.current=pe,I(pe)},[t,f.initialDisplayLabel,p]),S.useEffect(()=>{if(!m){O([]),M([]),L([]),$(!1);return}if(i||s||e.disabled){O([]),M([]),L([]),$(!1);return}const te=oe;if(te.length<E){O([]),M([]),L([]),$(!1),V(null);return}const pe=zd({apiEndpoint:m,apiMethod:h,apiQueryParams:f.apiQueryParams,formValues:_,submissionContext:l,apiRealtime:g,additionalRequiredFieldNames:f.dependentFields});if(pe.blocked){O([]),M([]),L([]),$(!1),V(null);return}Pe.current?.abort();const We=new AbortController;Pe.current=We;const Pt=++ee.current;return(async()=>{$(!0),V(null);const Te=cn(pe.url),Xe={};v&&(Xe["Content-Type"]="application/json"),f.apiKey&&(Xe["X-CSCAPI-KEY"]=f.apiKey);try{let Ue;if(!v)Ue=(await dn.get(Te,{params:{[C]:te},signal:We.signal,headers:Object.keys(Xe).length?Xe:void 0})).data;else{let It={};pe.postBodyBase&&Object.keys(pe.postBodyBase).length>0?It={...pe.postBodyBase}:g&&Object.keys(_).length>0&&(It={..._});let Er=It;if(f.searchBodyTemplate?.trim()){let sr=f.searchBodyTemplate.replace(/\{\{query\}\}/g,()=>Kp(te)).replace(/\{query\}/g,()=>Kp(te));sr=Wb(sr,_,l,g);const fn=JSON.parse(sr);Er={...It,...fn}}else Er={...It,[C]:te};Ue=(await dn.post(Te,Er,{signal:We.signal,headers:Object.keys(Xe).length?Xe:void 0})).data}if(Pt!==ee.current)return;const ft=f.apiResultsFormat,St=f.apiResultsConfig,xt=ft==="clinicaltables_v3",ze=$A(Ue),pt=xt||ft===void 0&&ze,At=ft==="tuple_array";let Ut=null;pt?Ut=Cp({response:Ue,sourceUrl:Te,rowsIndex:St?.rowsIndex??3,rowsPath:St?.rowsPath,columns:St?.columns,columnsQueryParam:St?.columnsQueryParam??"sf",columnsQueryParamSeparator:St?.columnsQueryParamSeparator??","}):At&&(Ut=Cp({response:Ue,sourceUrl:Te,rowsIndex:St?.rowsIndex,rowsPath:St?.rowsPath,columns:St?.columns,columnsQueryParam:St?.columnsQueryParam,columnsQueryParamSeparator:St?.columnsQueryParamSeparator}));const ur=NC(Ue),Ar=Ut!==null,Vt=Ut&&Array.isArray(Ut)?Ut:Array.isArray(ur)&&ur.every(It=>It&&typeof It=="object"&&!Array.isArray(It))?ur:null;L(Vt??ur);const Po=Array.isArray(f.apiLabelFields)&&f.apiLabelFields.length>0,Xn=Vt&&(Ar||Po)?zA({rows:Vt,apiLabelField:f.apiLabelField,apiLabelFields:f.apiLabelFields,apiLabelSeparator:f.apiLabelSeparator,apiValueField:f.apiValueField}):Fl(Ue,f.apiLabelField,f.apiValueField);M(Xn);const Ct=f.apiClientFilter;let Cr=Xn;if(Ct?.filterField&&Ct?.matchField){const It=_[Ct.matchField];if(It!=null){const Er=f.apiValueField;Cr=Xn.filter(er=>{const fn=(Vt??ur).find(kt=>String(or(kt,Er||"code"))===String(er.value));if(!fn)return!1;const yr=or(fn,Ct.filterField);return String(yr)===String(It)})}else Cr=[]}const Jn=Yp(Cr,P).filter(Bl);O(Jn),X(Jn.length>0?0:-1)}catch(Ue){if(_t.isCancel(Ue)||Ue?.code==="ERR_CANCELED"||Pt!==ee.current)return;O([]),M([]),L([]),V(EC(Ue)),X(-1)}finally{Pt===ee.current&&$(!1)}})(),()=>{We.abort()}},[oe,m,h,y,v,C,E,P,f.apiKey,f.searchBodyTemplate,f.apiLabelField,f.apiLabelFields,f.apiLabelSeparator,f.apiValueField,f.apiQueryParams,f.apiClientFilter,f.apiResultsFormat,f.apiResultsConfig,f.dependentFields,g,_,l,i,s,e.disabled,de,ot,Se]),S.useEffect(()=>{const te=f.apiClientFilter;if(!te||D.length===0||j.length===0)return;const pe=_[te.matchField],We=f.apiValueField;if(pe==null){O([]);return}const Pt=j.filter(Te=>{const Xe=D.find(ft=>String(or(ft,We||"code"))===String(Te.value));if(!Xe)return!1;const Ue=or(Xe,te.filterField);return String(Ue)===String(pe)}),je=Yp(Pt,P).filter(Bl);O(je),X(je.length>0?0:-1)},[f.apiClientFilter,f.apiValueField,_,P,j,D]);const xe=s||e.disabled,ae=i||e.readOnly,ve=S.useCallback(te=>{const pe=te.target.value;ae||xe||(ce.current&&ne.current&&pe!==ne.current&&(ce.current="",ne.current="",r(p?null:"")),I(pe),W(!0),X(-1))},[xe,ae,p,r]),Ye=S.useCallback(te=>{const pe=typeof te?.label=="string"?te.label:String(te?.value??""),We=f.apiValueField||"code";if(p){const Pt=qp(f),je=D.find(Te=>String(or(Te,We))===String(te.value));if(je&&typeof je=="object"&&!Array.isArray(je)&&Pt.length>0){const Te=xC(je,Pt);ce.current=Ll(Te,!0),ne.current=pe,r(Te),I(pe)}else ce.current=`S:${String(te.value)}`,ne.current=pe,r(String(te.value)),I(pe)}else ce.current=`S:${String(te.value)}`,ne.current=pe,r(String(te.value)),I(pe);G.current&&clearTimeout(G.current),W(!1),X(-1),n?.()},[p,n,r,f,D]),ct=S.useCallback(te=>{te.preventDefault(),te.stopPropagation(),!(xe||ae)&&(ce.current="",ne.current="",r(p?null:""),I(""),O([]),M([]),L([]),V(null),W(!1),n?.())},[xe,ae,p,r,n]),Ge=S.useMemo(()=>T&&!ae&&(U||!!ie||re.length>0||oe.length>=E&&!U),[T,ae,U,ie,re.length,oe,E]),Kt=S.useCallback(te=>{if(!(ae||xe))if(te.key==="ArrowDown")te.preventDefault(),W(!0),X(pe=>re.length===0?-1:(pe+1)%re.length);else if(te.key==="ArrowUp")te.preventDefault(),W(!0),X(pe=>re.length===0?-1:pe<=0?re.length-1:pe-1);else if(te.key==="Enter"){const pe=K>=0?re[K]:void 0;Ge&&pe&&!pe.disabled&&(te.preventDefault(),Ye(pe))}else te.key==="Escape"&&W(!1)},[xe,ae,K,Ge,re,Ye]),Je=e.appearance?.size||"md",q={sm:"h-8 text-sm",md:"h-10",lg:"h-12 text-lg"},$e=ht(e),gt=jt(e,!!(o||ie)),Oe=oe.length>=E&&!U&&!ie&&re.length===0;return c.jsx(Et,{field:e,error:o||ie||void 0,isRequired:a,className:d,children:c.jsxs(Ol,{open:Ge,onOpenChange:te=>{te||W(!1)},children:[c.jsx(fC,{asChild:!0,children:c.jsxs("div",{className:"relative flex w-full min-w-0 items-center gap-1",children:[c.jsx(wn,{id:$e,role:"combobox","aria-expanded":Ge,"aria-autocomplete":"list","aria-controls":Ge?`${$e}-listbox`:void 0,"aria-activedescendant":K>=0?`${$e}-opt-${K}`:void 0,value:A,onChange:ve,onKeyDown:Kt,onFocus:()=>{G.current&&clearTimeout(G.current),!ae&&!xe&&W(!0)},onBlur:()=>{G.current=setTimeout(()=>{W(!1),n?.()},150)},placeholder:e.placeholder||"Search…",disabled:xe,readOnly:ae,"aria-describedby":gt,"aria-invalid":Jt(!!(o||ie)),"aria-required":a,className:B("pr-20",q[Je],(o||ie)&&"border-destructive focus-visible:ring-destructive",e.appearance?.className)}),c.jsxs("div",{className:"pointer-events-none absolute right-1 top-1/2 flex -translate-y-1/2 items-center gap-0.5",children:[U&&c.jsx(Ro,{className:"pointer-events-none h-4 w-4 animate-spin text-muted-foreground"}),N&&CC(t,A,p)&&!xe&&!ae&&c.jsx(Yt,{type:"button",variant:"ghost",size:"icon",className:"pointer-events-auto h-8 w-8 shrink-0",onMouseDown:te=>te.preventDefault(),onClick:ct,"aria-label":"Clear",children:c.jsx(Ko,{className:"h-4 w-4"})})]})]})}),c.jsx(Il,{className:"p-0 w-[var(--radix-popover-trigger-width)] min-w-[12rem] overflow-hidden",align:"start",onOpenAutoFocus:te=>te.preventDefault(),onCloseAutoFocus:te=>te.preventDefault(),children:c.jsx("div",{id:`${$e}-listbox`,role:"listbox",children:ie?c.jsx("div",{className:"px-3 py-2 text-sm text-destructive",children:ie}):U?c.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground",children:[c.jsx(Ro,{className:"h-4 w-4 animate-spin shrink-0"}),"Loading…"]}):Oe?c.jsx("ul",{className:"py-1","aria-label":"Search results",children:c.jsx("li",{role:"option","aria-disabled":!0,className:"cursor-default select-none px-3 py-2 text-sm text-muted-foreground",onMouseDown:te=>te.preventDefault(),children:"No results found"})}):c.jsx("ul",{className:"max-h-60 overflow-y-auto overscroll-contain py-1","aria-label":"Search results",children:re.map((te,pe)=>c.jsx("li",{id:`${$e}-opt-${pe}`,role:"option","aria-selected":K===pe,className:B(te.disabled?"cursor-not-allowed opacity-60":"cursor-pointer","px-3 py-2 text-sm",K===pe&&"bg-accent text-accent-foreground"),onMouseEnter:()=>X(pe),onMouseDown:We=>We.preventDefault(),onClick:()=>{te.disabled||Ye(te)},children:te.label},`${te.value}-${pe}`))})})})]})})};var ki="Checkbox",[_C]=vr(ki),[kC,$l]=_C(ki);function TC(e){const{__scopeCheckbox:t,checked:r,children:n,defaultChecked:o,disabled:s,form:i,name:a,onCheckedChange:d,required:u,value:l="on",internal_do_not_use_render:f}=e,[p,m]=Zr({prop:r,defaultProp:o??!1,onChange:d,caller:ki}),[g,h]=b.useState(null),[y,v]=b.useState(null),w=b.useRef(!1),x=g?!!i||!!g.closest("form"):!0,E={checked:p,disabled:s,setChecked:m,control:g,setControl:h,name:a,form:i,value:l,hasConsumerStoppedPropagationRef:w,required:u,defaultChecked:Fn(o)?!1:o,isFormControl:x,bubbleInput:y,setBubbleInput:v};return c.jsx(kC,{scope:t,...E,children:FC(f)?f(E):n})}var Jp="CheckboxTrigger",Qp=b.forwardRef(({__scopeCheckbox:e,onKeyDown:t,onClick:r,...n},o)=>{const{control:s,value:i,disabled:a,checked:d,required:u,setControl:l,setChecked:f,hasConsumerStoppedPropagationRef:p,isFormControl:m,bubbleInput:g}=$l(Jp,e),h=Ze(o,l),y=b.useRef(d);return b.useEffect(()=>{const v=s?.form;if(v){const w=()=>f(y.current);return v.addEventListener("reset",w),()=>v.removeEventListener("reset",w)}},[s,f]),c.jsx(Be.button,{type:"button",role:"checkbox","aria-checked":Fn(d)?"mixed":d,"aria-required":u,"data-state":om(d),"data-disabled":a?"":void 0,disabled:a,value:i,...n,ref:h,onKeyDown:Me(t,v=>{v.key==="Enter"&&v.preventDefault()}),onClick:Me(r,v=>{f(w=>Fn(w)?!0:!w),g&&m&&(p.current=v.isPropagationStopped(),p.current||v.stopPropagation())})})});Qp.displayName=Jp;var Zp=b.forwardRef((e,t)=>{const{__scopeCheckbox:r,name:n,checked:o,defaultChecked:s,required:i,disabled:a,value:d,onCheckedChange:u,form:l,...f}=e;return c.jsx(TC,{__scopeCheckbox:r,checked:o,defaultChecked:s,disabled:a,required:i,onCheckedChange:u,name:n,form:l,value:d,internal_do_not_use_render:({isFormControl:p})=>c.jsxs(c.Fragment,{children:[c.jsx(Qp,{...f,ref:t,__scopeCheckbox:r}),p&&c.jsx(nm,{__scopeCheckbox:r})]})})});Zp.displayName=ki;var em="CheckboxIndicator",tm=b.forwardRef((e,t)=>{const{__scopeCheckbox:r,forceMount:n,...o}=e,s=$l(em,r);return c.jsx(xr,{present:n||Fn(s.checked)||s.checked===!0,children:c.jsx(Be.span,{"data-state":om(s.checked),"data-disabled":s.disabled?"":void 0,...o,ref:t,style:{pointerEvents:"none",...e.style}})})});tm.displayName=em;var rm="CheckboxBubbleInput",nm=b.forwardRef(({__scopeCheckbox:e,...t},r)=>{const{control:n,hasConsumerStoppedPropagationRef:o,checked:s,defaultChecked:i,required:a,disabled:d,name:u,value:l,form:f,bubbleInput:p,setBubbleInput:m}=$l(rm,e),g=Ze(r,m),h=Qo(s),y=Jo(n);b.useEffect(()=>{const w=p;if(!w)return;const x=window.HTMLInputElement.prototype,P=Object.getOwnPropertyDescriptor(x,"checked").set,C=!o.current;if(h!==s&&P){const N=new Event("click",{bubbles:C});w.indeterminate=Fn(s),P.call(w,Fn(s)?!1:s),w.dispatchEvent(N)}},[p,h,s,o]);const v=b.useRef(Fn(s)?!1:s);return c.jsx(Be.input,{type:"checkbox","aria-hidden":!0,defaultChecked:i??v.current,required:a,disabled:d,name:u,value:l,form:f,...t,tabIndex:-1,ref:g,style:{...t.style,...y,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});nm.displayName=rm;function FC(e){return typeof e=="function"}function Fn(e){return e==="indeterminate"}function om(e){return Fn(e)?"indeterminate":e?"checked":"unchecked"}function Ti({className:e,...t}){return c.jsx(Zp,{"data-slot":"checkbox",className:B("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:c.jsx(tm,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:c.jsx(Vs,{className:"size-3.5"})})})}const PC=Pp("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-destructive-foreground [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",warning:"border-transparent bg-orange-500 text-white [a&]:hover:bg-orange-600 focus-visible:ring-orange-500/20",success:"border-transparent bg-green-500 text-white [a&]:hover:bg-green-600 focus-visible:ring-green-500/20",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function OC({className:e,variant:t,asChild:r=!1,...n}){const o=r?qd:"span";return c.jsx(o,{"data-slot":"badge",className:B(PC({variant:t}),e),...n})}function IC(e,t){return b.useReducer((r,n)=>t[r][n]??r,e)}var jl="ScrollArea",[sm]=vr(jl),[MC,Ir]=sm(jl),im=b.forwardRef((e,t)=>{const{__scopeScrollArea:r,type:n="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,d]=b.useState(null),[u,l]=b.useState(null),[f,p]=b.useState(null),[m,g]=b.useState(null),[h,y]=b.useState(null),[v,w]=b.useState(0),[x,E]=b.useState(0),[P,C]=b.useState(!1),[N,_]=b.useState(!1),A=Ze(t,T=>d(T)),I=ro(o);return c.jsx(MC,{scope:r,type:n,dir:I,scrollHideDelay:s,scrollArea:a,viewport:u,onViewportChange:l,content:f,onContentChange:p,scrollbarX:m,onScrollbarXChange:g,scrollbarXEnabled:P,onScrollbarXEnabledChange:C,scrollbarY:h,onScrollbarYChange:y,scrollbarYEnabled:N,onScrollbarYEnabledChange:_,onCornerWidthChange:w,onCornerHeightChange:E,children:c.jsx(Be.div,{dir:I,...i,ref:A,style:{position:"relative","--radix-scroll-area-corner-width":v+"px","--radix-scroll-area-corner-height":x+"px",...e.style}})})});im.displayName=jl;var am="ScrollAreaViewport",lm=b.forwardRef((e,t)=>{const{__scopeScrollArea:r,children:n,nonce:o,...s}=e,i=Ir(am,r),a=b.useRef(null),d=Ze(t,a,i.onViewportChange);return c.jsxs(c.Fragment,{children:[c.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),c.jsx(Be.div,{"data-radix-scroll-area-viewport":"",...s,ref:d,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:c.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:n})})]})});lm.displayName=am;var tn="ScrollAreaScrollbar",cm=b.forwardRef((e,t)=>{const{forceMount:r,...n}=e,o=Ir(tn,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return b.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?c.jsx(LC,{...n,ref:t,forceMount:r}):o.type==="scroll"?c.jsx(DC,{...n,ref:t,forceMount:r}):o.type==="auto"?c.jsx(dm,{...n,ref:t,forceMount:r}):o.type==="always"?c.jsx(zl,{...n,ref:t}):null});cm.displayName=tn;var LC=b.forwardRef((e,t)=>{const{forceMount:r,...n}=e,o=Ir(tn,e.__scopeScrollArea),[s,i]=b.useState(!1);return b.useEffect(()=>{const a=o.scrollArea;let d=0;if(a){const u=()=>{window.clearTimeout(d),i(!0)},l=()=>{d=window.setTimeout(()=>i(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",u),a.addEventListener("pointerleave",l),()=>{window.clearTimeout(d),a.removeEventListener("pointerenter",u),a.removeEventListener("pointerleave",l)}}},[o.scrollArea,o.scrollHideDelay]),c.jsx(xr,{present:r||s,children:c.jsx(dm,{"data-state":s?"visible":"hidden",...n,ref:t})})}),DC=b.forwardRef((e,t)=>{const{forceMount:r,...n}=e,o=Ir(tn,e.__scopeScrollArea),s=e.orientation==="horizontal",i=Ii(()=>d("SCROLL_END"),100),[a,d]=IC("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return b.useEffect(()=>{if(a==="idle"){const u=window.setTimeout(()=>d("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(u)}},[a,o.scrollHideDelay,d]),b.useEffect(()=>{const u=o.viewport,l=s?"scrollLeft":"scrollTop";if(u){let f=u[l];const p=()=>{const m=u[l];f!==m&&(d("SCROLL"),i()),f=m};return u.addEventListener("scroll",p),()=>u.removeEventListener("scroll",p)}},[o.viewport,s,d,i]),c.jsx(xr,{present:r||a!=="hidden",children:c.jsx(zl,{"data-state":a==="hidden"?"hidden":"visible",...n,ref:t,onPointerEnter:Me(e.onPointerEnter,()=>d("POINTER_ENTER")),onPointerLeave:Me(e.onPointerLeave,()=>d("POINTER_LEAVE"))})})}),dm=b.forwardRef((e,t)=>{const r=Ir(tn,e.__scopeScrollArea),{forceMount:n,...o}=e,[s,i]=b.useState(!1),a=e.orientation==="horizontal",d=Ii(()=>{if(r.viewport){const u=r.viewport.offsetWidth<r.viewport.scrollWidth,l=r.viewport.offsetHeight<r.viewport.scrollHeight;i(a?u:l)}},10);return go(r.viewport,d),go(r.content,d),c.jsx(xr,{present:n||s,children:c.jsx(zl,{"data-state":s?"visible":"hidden",...o,ref:t})})}),zl=b.forwardRef((e,t)=>{const{orientation:r="vertical",...n}=e,o=Ir(tn,e.__scopeScrollArea),s=b.useRef(null),i=b.useRef(0),[a,d]=b.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),u=hm(a.viewport,a.content),l={...n,sizes:a,onSizesChange:d,hasThumb:u>0&&u<1,onThumbChange:p=>s.current=p,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:p=>i.current=p};function f(p,m){return VC(p,i.current,a,m)}return r==="horizontal"?c.jsx(BC,{...l,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const p=o.viewport.scrollLeft,m=gm(p,a,o.dir);s.current.style.transform=`translate3d(${m}px, 0, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollLeft=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollLeft=f(p,o.dir))}}):r==="vertical"?c.jsx($C,{...l,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const p=o.viewport.scrollTop,m=gm(p,a);s.current.style.transform=`translate3d(0, ${m}px, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollTop=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollTop=f(p))}}):null}),BC=b.forwardRef((e,t)=>{const{sizes:r,onSizesChange:n,...o}=e,s=Ir(tn,e.__scopeScrollArea),[i,a]=b.useState(),d=b.useRef(null),u=Ze(t,d,s.onScrollbarXChange);return b.useEffect(()=>{d.current&&a(getComputedStyle(d.current))},[d]),c.jsx(fm,{"data-orientation":"horizontal",...o,ref:u,sizes:r,style:{bottom:0,left:s.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:s.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Oi(r)+"px",...e.style},onThumbPointerDown:l=>e.onThumbPointerDown(l.x),onDragScroll:l=>e.onDragScroll(l.x),onWheelScroll:(l,f)=>{if(s.viewport){const p=s.viewport.scrollLeft+l.deltaX;e.onWheelScroll(p),bm(p,f)&&l.preventDefault()}},onResize:()=>{d.current&&s.viewport&&i&&n({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:d.current.clientWidth,paddingStart:Pi(i.paddingLeft),paddingEnd:Pi(i.paddingRight)}})}})}),$C=b.forwardRef((e,t)=>{const{sizes:r,onSizesChange:n,...o}=e,s=Ir(tn,e.__scopeScrollArea),[i,a]=b.useState(),d=b.useRef(null),u=Ze(t,d,s.onScrollbarYChange);return b.useEffect(()=>{d.current&&a(getComputedStyle(d.current))},[d]),c.jsx(fm,{"data-orientation":"vertical",...o,ref:u,sizes:r,style:{top:0,right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Oi(r)+"px",...e.style},onThumbPointerDown:l=>e.onThumbPointerDown(l.y),onDragScroll:l=>e.onDragScroll(l.y),onWheelScroll:(l,f)=>{if(s.viewport){const p=s.viewport.scrollTop+l.deltaY;e.onWheelScroll(p),bm(p,f)&&l.preventDefault()}},onResize:()=>{d.current&&s.viewport&&i&&n({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:d.current.clientHeight,paddingStart:Pi(i.paddingTop),paddingEnd:Pi(i.paddingBottom)}})}})}),[jC,um]=sm(tn),fm=b.forwardRef((e,t)=>{const{__scopeScrollArea:r,sizes:n,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:d,onDragScroll:u,onWheelScroll:l,onResize:f,...p}=e,m=Ir(tn,r),[g,h]=b.useState(null),y=Ze(t,A=>h(A)),v=b.useRef(null),w=b.useRef(""),x=m.viewport,E=n.content-n.viewport,P=ar(l),C=ar(d),N=Ii(f,10);function _(A){if(v.current){const I=A.clientX-v.current.left,T=A.clientY-v.current.top;u({x:I,y:T})}}return b.useEffect(()=>{const A=I=>{const T=I.target;g?.contains(T)&&P(I,E)};return document.addEventListener("wheel",A,{passive:!1}),()=>document.removeEventListener("wheel",A,{passive:!1})},[x,g,E,P]),b.useEffect(C,[n,C]),go(g,N),go(m.content,N),c.jsx(jC,{scope:r,scrollbar:g,hasThumb:o,onThumbChange:ar(s),onThumbPointerUp:ar(i),onThumbPositionChange:C,onThumbPointerDown:ar(a),children:c.jsx(Be.div,{...p,ref:y,style:{position:"absolute",...p.style},onPointerDown:Me(e.onPointerDown,A=>{A.button===0&&(A.target.setPointerCapture(A.pointerId),v.current=g.getBoundingClientRect(),w.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",m.viewport&&(m.viewport.style.scrollBehavior="auto"),_(A))}),onPointerMove:Me(e.onPointerMove,_),onPointerUp:Me(e.onPointerUp,A=>{const I=A.target;I.hasPointerCapture(A.pointerId)&&I.releasePointerCapture(A.pointerId),document.body.style.webkitUserSelect=w.current,m.viewport&&(m.viewport.style.scrollBehavior=""),v.current=null})})})}),Fi="ScrollAreaThumb",pm=b.forwardRef((e,t)=>{const{forceMount:r,...n}=e,o=um(Fi,e.__scopeScrollArea);return c.jsx(xr,{present:r||o.hasThumb,children:c.jsx(zC,{ref:t,...n})})}),zC=b.forwardRef((e,t)=>{const{__scopeScrollArea:r,style:n,...o}=e,s=Ir(Fi,r),i=um(Fi,r),{onThumbPositionChange:a}=i,d=Ze(t,f=>i.onThumbChange(f)),u=b.useRef(void 0),l=Ii(()=>{u.current&&(u.current(),u.current=void 0)},100);return b.useEffect(()=>{const f=s.viewport;if(f){const p=()=>{if(l(),!u.current){const m=HC(f,a);u.current=m,a()}};return a(),f.addEventListener("scroll",p),()=>f.removeEventListener("scroll",p)}},[s.viewport,l,a]),c.jsx(Be.div,{"data-state":i.hasThumb?"visible":"hidden",...o,ref:d,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...n},onPointerDownCapture:Me(e.onPointerDownCapture,f=>{const m=f.target.getBoundingClientRect(),g=f.clientX-m.left,h=f.clientY-m.top;i.onThumbPointerDown({x:g,y:h})}),onPointerUp:Me(e.onPointerUp,i.onThumbPointerUp)})});pm.displayName=Fi;var Ul="ScrollAreaCorner",mm=b.forwardRef((e,t)=>{const r=Ir(Ul,e.__scopeScrollArea),n=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&n?c.jsx(UC,{...e,ref:t}):null});mm.displayName=Ul;var UC=b.forwardRef((e,t)=>{const{__scopeScrollArea:r,...n}=e,o=Ir(Ul,r),[s,i]=b.useState(0),[a,d]=b.useState(0),u=!!(s&&a);return go(o.scrollbarX,()=>{const l=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(l),d(l)}),go(o.scrollbarY,()=>{const l=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(l),i(l)}),u?c.jsx(Be.div,{...n,ref:t,style:{width:s,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function Pi(e){return e?parseInt(e,10):0}function hm(e,t){const r=e/t;return isNaN(r)?0:r}function Oi(e){const t=hm(e.viewport,e.content),r=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,n=(e.scrollbar.size-r)*t;return Math.max(n,18)}function VC(e,t,r,n="ltr"){const o=Oi(r),s=o/2,i=t||s,a=o-i,d=r.scrollbar.paddingStart+i,u=r.scrollbar.size-r.scrollbar.paddingEnd-a,l=r.content-r.viewport,f=n==="ltr"?[0,l]:[l*-1,0];return ym([d,u],f)(e)}function gm(e,t,r="ltr"){const n=Oi(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,s=t.scrollbar.size-o,i=t.content-t.viewport,a=s-n,d=r==="ltr"?[0,i]:[i*-1,0],u=qo(e,d);return ym([0,i],[0,a])(u)}function ym(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 bm(e,t){return e>0&&e<t}var HC=(e,t=()=>{})=>{let r={left:e.scrollLeft,top:e.scrollTop},n=0;return(function o(){const s={left:e.scrollLeft,top:e.scrollTop},i=r.left!==s.left,a=r.top!==s.top;(i||a)&&t(),r=s,n=window.requestAnimationFrame(o)})(),()=>window.cancelAnimationFrame(n)};function Ii(e,t){const r=ar(e),n=b.useRef(0);return b.useEffect(()=>()=>window.clearTimeout(n.current),[]),b.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(r,t)},[r,t])}function go(e,t){const r=ar(t);Qt(()=>{let n=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(n),n=window.requestAnimationFrame(r)});return o.observe(e),()=>{window.cancelAnimationFrame(n),o.unobserve(e)}}},[e,r])}var WC=im,RC=lm,GC=mm;function KC({className:e,children:t,...r}){return c.jsxs(WC,{"data-slot":"scroll-area",className:B("relative",e),...r,children:[c.jsx(RC,{"data-slot":"scroll-area-viewport",className:"focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1",children:t}),c.jsx(qC,{}),c.jsx(GC,{})]})}function qC({className:e,orientation:t="vertical",...r}){return c.jsx(cm,{"data-slot":"scroll-area-scrollbar",orientation:t,className:B("flex touch-none p-px transition-colors select-none",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent",e),...r,children:c.jsx(pm,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const vm=({field:e,value:t=[],onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a,formValues:d={},submissionContext:u,excludedOptionValues:l})=>{const{options:f,isLoadingOptions:p,optionsError:m}=_p({field:e,formValues:d,submissionContext:u}),g=l?.length?new Set(l.map(String)):null,h=g?f.filter(N=>!g.has(String(N.value??N.label??""))):f,y=Array.isArray(t)?t:[],v=y.map(N=>h.find(_=>String(_.value)===String(N))).filter(Boolean),w=S.useCallback(N=>{const _=y.includes(N)?y.filter(A=>A!==N):[...y,N];r(_),n?.()},[y,r,n]),x=S.useCallback(N=>{r(y.filter(_=>_!==N)),n?.()},[y,r,n]),E=e.appearance?.size||"md",P={sm:"h-8 text-sm",md:"h-10",lg:"h-12 text-lg"},C=v.length>0?`${v.length} selected`:h.length===0&&l?.length?"No available options":e.placeholder||"Select options";return c.jsxs(Et,{field:e,error:o||m||void 0,isRequired:i,className:a,children:[c.jsxs(Ol,{children:[c.jsx(Hp,{asChild:!0,children:c.jsxs(Yt,{type:"button",variant:"outline",role:"combobox","aria-expanded":void 0,"aria-haspopup":"listbox","aria-multiselectable":"true","aria-describedby":jt(e,!!o||!!m),"aria-invalid":Jt(!!o||!!m),"aria-required":i,id:ht(e),disabled:s||e.disabled||p,className:B("w-full min-w-0 justify-between font-normal",P[E],o&&"border-destructive focus-visible:ring-destructive",m&&"border-destructive focus-visible:ring-destructive",e.appearance?.className),children:[c.jsx("span",{className:"truncate",children:C}),c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[p&&c.jsx(Ro,{className:"h-4 w-4 animate-spin text-muted-foreground"}),c.jsx(Wo,{className:"h-4 w-4 opacity-50"})]})]})}),c.jsx(Il,{className:"w-[var(--radix-popover-trigger-width)] p-0 overflow-hidden",align:"start",children:c.jsx(KC,{className:"h-60 overflow-hidden rounded-md",children:c.jsx("ul",{role:"listbox","aria-multiselectable":"true","aria-label":e.label||e.name||"Options",className:"p-1",children:h.length===0?c.jsx("li",{className:"px-2 py-3 text-sm text-muted-foreground text-center",children:p?"Loading options...":l?.length?"No available options":"No options available"}):h.map(N=>{const _=String(N.value||N.label),A=N.label||N.value||_,I=y.includes(_);return c.jsxs("li",{role:"option","aria-selected":I,className:"flex items-center gap-2 rounded-sm px-2 py-1.5 cursor-pointer hover:bg-accent focus:bg-accent outline-none",onClick:()=>!N.disabled&&w(_),onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),N.disabled||w(_))},children:[c.jsx(Ti,{checked:I,disabled:N.disabled,onCheckedChange:()=>!N.disabled&&w(_),onClick:T=>T.stopPropagation(),"aria-hidden":!0,className:"pointer-events-none"}),c.jsx("span",{className:"flex-1 truncate text-sm",children:A})]},_)})})})})]}),v.length>0&&c.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",role:"list","aria-label":"Selected options",children:v.map(N=>{const _=String(N.value||N.label),A=N.label||N.value||_;return c.jsxs(OC,{variant:"secondary",className:"pl-2 pr-1 py-0.5 text-xs font-normal gap-1",children:[c.jsx("span",{className:"truncate max-w-[120px]",children:A}),c.jsx("button",{type:"button","aria-label":`Remove ${A}`,className:"rounded-full p-0.5 hover:bg-muted focus:outline-none focus:ring-2 focus:ring-ring",onClick:()=>x(_),tabIndex:-1,children:c.jsx(Ko,{className:"h-3 w-3"})})]},_)})})]})},wm=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a})=>{const d=S.useCallback(u=>{r(u===!0),n?.()},[r,n]);return c.jsxs("div",{className:B("space-y-2",a),children:[c.jsxs("div",{className:"flex items-start space-x-3",children:[c.jsx(Ti,{id:ht(e),checked:t||!1,onCheckedChange:d,disabled:s||e.disabled,"aria-describedby":jt(e,!!o),"aria-required":i,className:B(o&&"border-destructive")}),c.jsxs("div",{className:"grid gap-1.5 leading-none",children:[c.jsxs(Sn,{id:zs(e),htmlFor:ht(e),className:B("text-sm font-medium cursor-pointer",o&&"text-destructive"),children:[e.label,i&&c.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.description&&!o&&c.jsx("p",{id:Vo(e),className:"text-xs text-muted-foreground",children:e.description})]})]}),o&&c.jsx("p",{id:Ho(e),className:"text-xs text-destructive",role:"alert",children:o})]})};var Mi="Switch",[YC]=vr(Mi),[XC,JC]=YC(Mi),Sm=b.forwardRef((e,t)=>{const{__scopeSwitch:r,name:n,checked:o,defaultChecked:s,required:i,disabled:a,value:d="on",onCheckedChange:u,form:l,...f}=e,[p,m]=b.useState(null),g=Ze(t,x=>m(x)),h=b.useRef(!1),y=p?l||!!p.closest("form"):!0,[v,w]=Zr({prop:o,defaultProp:s??!1,onChange:u,caller:Mi});return c.jsxs(XC,{scope:r,checked:v,disabled:a,children:[c.jsx(Be.button,{type:"button",role:"switch","aria-checked":v,"aria-required":i,"data-state":Em(v),"data-disabled":a?"":void 0,disabled:a,value:d,...f,ref:g,onClick:Me(e.onClick,x=>{w(E=>!E),y&&(h.current=x.isPropagationStopped(),h.current||x.stopPropagation())})}),y&&c.jsx(Cm,{control:p,bubbles:!h.current,name:n,value:d,checked:v,required:i,disabled:a,form:l,style:{transform:"translateX(-100%)"}})]})});Sm.displayName=Mi;var xm="SwitchThumb",Am=b.forwardRef((e,t)=>{const{__scopeSwitch:r,...n}=e,o=JC(xm,r);return c.jsx(Be.span,{"data-state":Em(o.checked),"data-disabled":o.disabled?"":void 0,...n,ref:t})});Am.displayName=xm;var QC="SwitchBubbleInput",Cm=b.forwardRef(({__scopeSwitch:e,control:t,checked:r,bubbles:n=!0,...o},s)=>{const i=b.useRef(null),a=Ze(i,s),d=Qo(r),u=Jo(t);return b.useEffect(()=>{const l=i.current;if(!l)return;const f=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(f,"checked").set;if(d!==r&&m){const g=new Event("click",{bubbles:n});m.call(l,r),l.dispatchEvent(g)}},[d,r,n]),c.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:r,...o,tabIndex:-1,ref:a,style:{...o.style,...u,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Cm.displayName=QC;function Em(e){return e?"checked":"unchecked"}var ZC=Sm,eE=Am;function Nm({className:e,...t}){return c.jsx(ZC,{"data-slot":"switch",className:B("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:c.jsx(eE,{"data-slot":"switch-thumb",className:B("bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}const tE=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a})=>{const d=e.properties;let u=null;if(e.metadata)try{u=typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata}catch{}const l=u?.onValue??d?.onValue??"On",f=u?.offValue??d?.offValue??"Off",p=u?.onText??d?.onText??l,m=u?.offText??d?.offText??f,g=S.useMemo(()=>{const y=t??e.defaultValue??f;return String(y)===String(l)},[t,e.defaultValue,f,l]),h=S.useCallback(y=>{r(y?l:f),n?.()},[r,n,l,f]);return c.jsxs("div",{className:B("space-y-2",a),children:[c.jsxs("div",{className:"space-y-2",children:[e.label&&c.jsxs(Sn,{id:zs(e),htmlFor:ht(e),className:B("text-sm font-medium block",o&&"text-destructive"),children:[e.label,i&&c.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.description&&!o&&c.jsx("p",{id:Vo(e),className:"text-xs text-muted-foreground",children:e.description}),c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(Nm,{id:ht(e),checked:g,onCheckedChange:h,disabled:s||e.disabled,"aria-describedby":jt(e,!!o),"aria-required":i,className:B(o&&"opacity-50")}),c.jsx("span",{className:"text-sm text-foreground font-medium",children:g?p:m})]})]}),o&&c.jsx("p",{id:Ho(e),className:"text-xs text-destructive",role:"alert",children:o})]})};var Vl="rovingFocusGroup.onEntryFocus",rE={bubbles:!1,cancelable:!0},as="RovingFocusGroup",[Hl,_m,nE]=Ba(as),[oE,Li]=vr(as,[nE]),[sE,iE]=oE(as),km=b.forwardRef((e,t)=>c.jsx(Hl.Provider,{scope:e.__scopeRovingFocusGroup,children:c.jsx(Hl.Slot,{scope:e.__scopeRovingFocusGroup,children:c.jsx(aE,{...e,ref:t})})}));km.displayName=as;var aE=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,orientation:n,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:d,onEntryFocus:u,preventScrollOnEntryFocus:l=!1,...f}=e,p=b.useRef(null),m=Ze(t,p),g=ro(s),[h,y]=Zr({prop:i,defaultProp:a??null,onChange:d,caller:as}),[v,w]=b.useState(!1),x=ar(u),E=_m(r),P=b.useRef(!1),[C,N]=b.useState(0);return b.useEffect(()=>{const _=p.current;if(_)return _.addEventListener(Vl,x),()=>_.removeEventListener(Vl,x)},[x]),c.jsx(sE,{scope:r,orientation:n,dir:g,loop:o,currentTabStopId:h,onItemFocus:b.useCallback(_=>y(_),[y]),onItemShiftTab:b.useCallback(()=>w(!0),[]),onFocusableItemAdd:b.useCallback(()=>N(_=>_+1),[]),onFocusableItemRemove:b.useCallback(()=>N(_=>_-1),[]),children:c.jsx(Be.div,{tabIndex:v||C===0?-1:0,"data-orientation":n,...f,ref:m,style:{outline:"none",...e.style},onMouseDown:Me(e.onMouseDown,()=>{P.current=!0}),onFocus:Me(e.onFocus,_=>{const A=!P.current;if(_.target===_.currentTarget&&A&&!v){const I=new CustomEvent(Vl,rE);if(_.currentTarget.dispatchEvent(I),!I.defaultPrevented){const T=E().filter(M=>M.focusable),W=T.find(M=>M.active),J=T.find(M=>M.id===h),j=[W,J,...T].filter(Boolean).map(M=>M.ref.current);Pm(j,l)}}P.current=!1}),onBlur:Me(e.onBlur,()=>w(!1))})})}),Tm="RovingFocusGroupItem",Fm=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:r,focusable:n=!0,active:o=!1,tabStopId:s,children:i,...a}=e,d=on(),u=s||d,l=iE(Tm,r),f=l.currentTabStopId===u,p=_m(r),{onFocusableItemAdd:m,onFocusableItemRemove:g,currentTabStopId:h}=l;return b.useEffect(()=>{if(n)return m(),()=>g()},[n,m,g]),c.jsx(Hl.ItemSlot,{scope:r,id:u,focusable:n,active:o,children:c.jsx(Be.span,{tabIndex:f?0:-1,"data-orientation":l.orientation,...a,ref:t,onMouseDown:Me(e.onMouseDown,y=>{n?l.onItemFocus(u):y.preventDefault()}),onFocus:Me(e.onFocus,()=>l.onItemFocus(u)),onKeyDown:Me(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){l.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const v=dE(y,l.orientation,l.dir);if(v!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let x=p().filter(E=>E.focusable).map(E=>E.ref.current);if(v==="last")x.reverse();else if(v==="prev"||v==="next"){v==="prev"&&x.reverse();const E=x.indexOf(y.currentTarget);x=l.loop?uE(x,E+1):x.slice(E+1)}setTimeout(()=>Pm(x))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:h!=null}):i})})});Fm.displayName=Tm;var lE={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cE(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function dE(e,t,r){const n=cE(e.key,r);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return lE[n]}function Pm(e,t=!1){const r=document.activeElement;for(const n of e)if(n===r||(n.focus({preventScroll:t}),document.activeElement!==r))return}function uE(e,t){return e.map((r,n)=>e[(t+n)%e.length])}var Om=km,Im=Fm,Wl="Radio",[fE,Mm]=vr(Wl),[pE,mE]=fE(Wl),Lm=b.forwardRef((e,t)=>{const{__scopeRadio:r,name:n,checked:o=!1,required:s,disabled:i,value:a="on",onCheck:d,form:u,...l}=e,[f,p]=b.useState(null),m=Ze(t,y=>p(y)),g=b.useRef(!1),h=f?u||!!f.closest("form"):!0;return c.jsxs(pE,{scope:r,checked:o,disabled:i,children:[c.jsx(Be.button,{type:"button",role:"radio","aria-checked":o,"data-state":jm(o),"data-disabled":i?"":void 0,disabled:i,value:a,...l,ref:m,onClick:Me(e.onClick,y=>{o||d?.(),h&&(g.current=y.isPropagationStopped(),g.current||y.stopPropagation())})}),h&&c.jsx($m,{control:f,bubbles:!g.current,name:n,value:a,checked:o,required:s,disabled:i,form:u,style:{transform:"translateX(-100%)"}})]})});Lm.displayName=Wl;var Dm="RadioIndicator",Bm=b.forwardRef((e,t)=>{const{__scopeRadio:r,forceMount:n,...o}=e,s=mE(Dm,r);return c.jsx(xr,{present:n||s.checked,children:c.jsx(Be.span,{"data-state":jm(s.checked),"data-disabled":s.disabled?"":void 0,...o,ref:t})})});Bm.displayName=Dm;var hE="RadioBubbleInput",$m=b.forwardRef(({__scopeRadio:e,control:t,checked:r,bubbles:n=!0,...o},s)=>{const i=b.useRef(null),a=Ze(i,s),d=Qo(r),u=Jo(t);return b.useEffect(()=>{const l=i.current;if(!l)return;const f=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(f,"checked").set;if(d!==r&&m){const g=new Event("click",{bubbles:n});m.call(l,r),l.dispatchEvent(g)}},[d,r,n]),c.jsx(Be.input,{type:"radio","aria-hidden":!0,defaultChecked:r,...o,tabIndex:-1,ref:a,style:{...o.style,...u,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});$m.displayName=hE;function jm(e){return e?"checked":"unchecked"}var gE=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Di="RadioGroup",[yE]=vr(Di,[Li,Mm]),zm=Li(),Um=Mm(),[bE,vE]=yE(Di),Vm=b.forwardRef((e,t)=>{const{__scopeRadioGroup:r,name:n,defaultValue:o,value:s,required:i=!1,disabled:a=!1,orientation:d,dir:u,loop:l=!0,onValueChange:f,...p}=e,m=zm(r),g=ro(u),[h,y]=Zr({prop:s,defaultProp:o??null,onChange:f,caller:Di});return c.jsx(bE,{scope:r,name:n,required:i,disabled:a,value:h,onValueChange:y,children:c.jsx(Om,{asChild:!0,...m,orientation:d,dir:g,loop:l,children:c.jsx(Be.div,{role:"radiogroup","aria-required":i,"aria-orientation":d,"data-disabled":a?"":void 0,dir:g,...p,ref:t})})})});Vm.displayName=Di;var Hm="RadioGroupItem",Wm=b.forwardRef((e,t)=>{const{__scopeRadioGroup:r,disabled:n,...o}=e,s=vE(Hm,r),i=s.disabled||n,a=zm(r),d=Um(r),u=b.useRef(null),l=Ze(t,u),f=s.value===o.value,p=b.useRef(!1);return b.useEffect(()=>{const m=h=>{gE.includes(h.key)&&(p.current=!0)},g=()=>p.current=!1;return document.addEventListener("keydown",m),document.addEventListener("keyup",g),()=>{document.removeEventListener("keydown",m),document.removeEventListener("keyup",g)}},[]),c.jsx(Im,{asChild:!0,...a,focusable:!i,active:f,children:c.jsx(Lm,{disabled:i,required:s.required,checked:f,...d,...o,name:s.name,ref:l,onCheck:()=>s.onValueChange(o.value),onKeyDown:Me(m=>{m.key==="Enter"&&m.preventDefault()}),onFocus:Me(o.onFocus,()=>{p.current&&u.current?.click()})})})});Wm.displayName=Hm;var wE="RadioGroupIndicator",Rm=b.forwardRef((e,t)=>{const{__scopeRadioGroup:r,...n}=e,o=Um(r);return c.jsx(Bm,{...o,...n,ref:t})});Rm.displayName=wE;var SE=Vm,xE=Wm,AE=Rm;function CE({className:e,...t}){return c.jsx(SE,{"data-slot":"radio-group",className:B("grid gap-3",e),...t})}function EE({className:e,...t}){return c.jsx(xE,{"data-slot":"radio-group-item",className:B("border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:c.jsx(AE,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:c.jsx(eu,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}const Gm=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a,excludedOptionValues:d})=>{const u=e.properties,l=Array.isArray(u?.options)&&u.options.length>0?u.options:Array.isArray(e.options)?e.options:[],f=d?.length?new Set(d.map(String)):null,p=f?l.filter(g=>!f.has(String(g.value??g.label??""))):l,m=S.useCallback(g=>{r(g),n?.()},[r,n]);return c.jsx(Et,{field:e,error:o,isRequired:i,className:a,children:c.jsx(CE,{value:t||"",onValueChange:m,disabled:s||e.disabled||p.length===0,className:"flex flex-col space-y-2","aria-required":i,children:p.length===0?c.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"No available options"}):p.map(g=>c.jsxs("div",{className:"flex items-center space-x-3",children:[c.jsx(EE,{id:`${ht(e)}-${g.value}`,value:g.value,disabled:g.disabled,className:B(o&&"border-destructive")}),c.jsxs(Sn,{htmlFor:`${ht(e)}-${g.value}`,className:B("text-sm font-normal cursor-pointer",g.disabled&&"text-muted-foreground cursor-not-allowed"),children:[g.label,g.description&&c.jsx("span",{className:"block text-xs text-muted-foreground",children:g.description})]})]},g.value))})})},Km=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,readOnly:i,isRequired:a,className:d})=>{const u=e.properties,l=S.useCallback(E=>{r(E.target.value)},[r]),f=E=>{if(E)return E==="today"?new Date().toISOString().split("T")[0]:E},p=f(u?.minDate),m=f(u?.maxDate),h=(()=>{switch(e.type){case"time":return"time";case"datetime":return"datetime-local";case"daterange":return"date";default:return"date"}})(),y=e.appearance?.size||"md",v={sm:"h-8 text-sm",md:"h-10",lg:"h-12 text-lg"},w=e.appearance?.labelPlacement||"top",x=!e.appearance?.hideLabel&&e.label;return c.jsxs("div",{className:B("space-y-2 w-fit",w==="left"&&"flex items-start gap-4",d),children:[x&&c.jsxs(Sn,{id:zs(e),htmlFor:ht(e),className:B("text-sm font-medium",w==="left"&&"w-32 pt-2 text-right",o&&"text-destructive"),children:[e.label,a&&c.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),c.jsxs("div",{className:"w-fit",children:[c.jsxs("div",{className:"relative w-fit max-w-full",children:[c.jsx(Ev,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),c.jsx(wn,{id:ht(e),type:h,value:t||"",onChange:l,onBlur:n,disabled:s||e.disabled,readOnly:i||e.readOnly,min:p,max:m,"aria-describedby":jt(e,!!o),"aria-invalid":Jt(!!o),"aria-required":a,className:B(v[y],"pl-10 w-fit",o&&"border-destructive focus-visible:ring-destructive",e.appearance?.className)})]}),e.description&&!o&&c.jsx("p",{id:Vo(e),className:"mt-1.5 text-xs text-muted-foreground",children:e.description}),o&&c.jsx("p",{id:Ho(e),className:"mt-1.5 text-xs text-destructive",role:"alert",children:o})]})]})};function yo(e){if(e===0)return"0 Bytes";const t=1024,r=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,n)).toFixed(2))+" "+r[n]}function Rl(e,t){return e===1&&t===1}const qm=/\.(jpg|jpeg|png|gif|webp|bmp|svg)(\?|$)/i;function Gl(e){return e.type.startsWith("image/")?!0:qm.test(e.name)}function Bi(e){try{const t=e.split("?")[0];return qm.test(t)}catch{return!1}}function Kl({items:e,maxFiles:t,disabled:r,objectUrls:n,failedUrlKeys:o,onImageUrlError:s,onRemove:i,onOpenUrl:a,resolveOpenUrl:d,addSlot:u,className:l}){const f=S.useCallback(p=>{try{return p.split("?")[0].split("/").filter(Boolean).pop()||p}catch{return p}},[]);return c.jsxs("div",{"data-file-like-strip":!0,"data-remove-in-dropzone":!0,className:B("relative w-full h-full flex items-center gap-1 min-h-0 overflow-x-auto",l),children:[e.map((p,m)=>{const g=p instanceof File,h=!g&&p&&"url"in p?p:null,y=h?.url??"",v=`${m}-${y}`,w=h&&o.has(y),x=g?n[m]??null:h&&Bi(y)&&!w?y:null,E=g&&Gl(p)&&!!x||!!h&&Bi(y)&&!w&&!!x,P=g?p.name:h?h.name??f(y):"",C=d?.(m,p),N=h&&y||C||"",_=!!a&&!!N;return c.jsxs("div",{className:"relative h-[56px] w-[56px] min-w-[56px] flex-shrink-0 rounded overflow-hidden border border-border/60 bg-muted/30",children:[E&&x?c.jsx("img",{src:x,alt:"",className:"absolute inset-0 h-full w-full object-cover",onError:()=>{h&&s(y)}}):c.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-muted/40",children:c.jsx(ru,{className:"h-7 w-7 text-muted-foreground","aria-hidden":!0})}),c.jsxs("div",{className:"absolute top-0.5 right-0.5 z-10 flex items-center gap-0.5",children:[_&&c.jsx("button",{type:"button",onClick:A=>{A.preventDefault(),A.stopPropagation(),a(N)},disabled:r,className:"inline-flex h-5 w-5 items-center justify-center rounded bg-background/90 text-foreground hover:bg-background focus:outline-none focus:ring-2 focus:ring-primary","aria-label":"Open file",title:"Open file",children:c.jsx(tu,{className:"h-3 w-3","aria-hidden":!0})}),c.jsx("button",{type:"button",onClick:A=>{A.preventDefault(),A.stopPropagation(),i(m)},disabled:r,className:"inline-flex h-5 w-5 items-center justify-center rounded bg-background/90 text-destructive hover:bg-background focus:outline-none focus:ring-2 focus:ring-destructive","aria-label":"Remove file",title:"Remove file",children:c.jsx(Ko,{className:"h-3 w-3","aria-hidden":!0})})]}),!E&&P&&c.jsx("span",{className:"sr-only",children:P})]},v+(g?p.name+p.size:""))}),u]})}function ql(e){const[t,r]=S.useState([]);return S.useEffect(()=>{const n=e.map(o=>o instanceof File&&Gl(o)?URL.createObjectURL(o):null);return r(n),()=>{n.forEach(o=>{o&&URL.revokeObjectURL(o)})}},[e]),t}function Yl({item:e,objectUrl:t,failedUrlKeys:r,onImageUrlError:n,onRemove:o,onOpenUrl:s,openTarget:i,disabled:a}){const d=S.useCallback(w=>{try{return w.split("?")[0].split("/").filter(Boolean).pop()||w}catch{return w}},[]),u=e instanceof File,l=!u&&e&&"url"in e?e:null,f=l?.url??"",p=l&&r.has(f),m=u?t:l&&Bi(f)&&!p?f:null,g=u&&Gl(e)&&!!m||!!l&&Bi(f)&&!p&&!!m,h=u?e.name:l?l.name??d(f):"",y=(i?.trim()||f||"").trim(),v=!!s&&!!y;return c.jsxs("div",{"data-file-like-full-bleed":!0,"data-remove-in-dropzone":!0,className:"relative h-full w-full min-h-[58px] min-w-0 flex items-center justify-center",children:[g&&m?c.jsx("img",{src:m,alt:"",className:"absolute inset-0 h-full w-full rounded object-cover",onError:()=>{l&&n(f)}}):c.jsx("div",{className:"absolute inset-0 flex items-center justify-center rounded bg-muted/40",children:c.jsx(ru,{className:"h-8 w-8 text-muted-foreground","aria-hidden":!0})}),c.jsxs("div",{className:"absolute top-1 right-1 z-10 flex items-center gap-1",children:[v&&y&&c.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),w.stopPropagation(),s(y)},disabled:a,className:"inline-flex h-6 w-6 items-center justify-center rounded bg-background/85 text-foreground hover:bg-background focus:outline-none focus:ring-2 focus:ring-primary","aria-label":"Open file",title:"Open file",children:c.jsx(tu,{className:"h-3.5 w-3.5","aria-hidden":!0})}),c.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),w.stopPropagation(),o()},disabled:a,className:"inline-flex h-6 w-6 items-center justify-center rounded bg-background/85 text-destructive hover:bg-background focus:outline-none focus:ring-2 focus:ring-destructive","aria-label":"Remove file",title:"Remove file",children:c.jsx(Ko,{className:"h-3.5 w-3.5","aria-hidden":!0})})]}),!g&&h&&c.jsx("p",{className:"sr-only",children:h})]})}const NE=({field:e,value:t,onChange:r,onBlur:n,error:o,disabled:s,isRequired:i,className:a,buttonResponses:d})=>{const{gridStretch:u}=zo(),l=u&&Is(e),f=e.properties,p=S.useRef(null),[m,g]=S.useState(!1),[h,y]=S.useState(),[v,w]=S.useState(()=>new Set),[x,E]=S.useState(0),P=e.metadata?typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata:null,C=Ms(e),N=S.useMemo(()=>Ls(t),[t]),[_,A]=S.useState(null);S.useEffect(()=>{A(null)},[t,x]);const I=_??N,T=ql(I),W=e.validation?.find(Se=>Se.type==="fileSize"),J=e.validation?.find(Se=>Se.type==="fileType"),O=W?.value?W.value:f?.maxSize??P?.maxSize??10*1024*1024,j=J?.value?J.value:f?.accept??P?.accept??[],M=Array.isArray(j)?j.join(","):"",D=()=>{I.length>=C||p.current?.click()},L=S.useCallback(Se=>{if(W){const xe=Yr(Se,W);if(xe!==!0)return typeof xe=="string"?xe:"File size exceeds the maximum allowed size"}else if(Se.size>O)return`File size must be less than ${yo(O)}`;if(J){const xe=Yr(Se,J);if(xe!==!0)return typeof xe=="string"?xe:"File type is not allowed"}return null},[W,J,O]),U=S.useCallback(Se=>{const xe=ka(Se,C);r(xe),n?.()},[r,n,C]),$=S.useCallback(Se=>{y(void 0);const xe=Array.from(Se),ae=[...I];let ve=null;for(const Ye of xe){if(ae.length>=C)break;const ct=L(Ye);if(ct){ve||(ve=ct);continue}ae.push(Ye)}if(ve&&ae.length===I.length){y(ve);return}ve&&y(ve),A(ae),U(ae)},[I,C,L,U]),ie=S.useCallback(Se=>{const xe=Se.target.files;xe&&xe.length>0&&$(xe),p.current&&(p.current.value="")},[$]),V=S.useCallback(Se=>{if(s)return;const xe=I.filter((ae,ve)=>ve!==Se);E(ae=>ae+1),A(xe),U(xe)},[s,I,U]),K=Se=>{Se.preventDefault(),g(!0)},X=()=>{g(!1)},ce=Se=>{Se.preventDefault(),g(!1),Se.dataTransfer.files?.length&&$(Se.dataTransfer.files)},ne=o||h,G=[];(W||O)&&G.push(`Max size: ${yo(O)}`),J&&j.length>0&&G.push(`Allowed types: ${j.join(", ")}`),C>1&&G.push(`Up to ${C} files`);const ee=e.appearance?.hideLabel??!1,Pe=S.useMemo(()=>{if(!d)return null;const Se=Object.values(d);for(let xe=Se.length-1;xe>=0;xe-=1){const ae=Se[xe],ve=typeof ae?.status=="string"?ae.status.toLowerCase():null;if(ve&&ve!=="success")continue;const Ye=ae?.code;if(typeof Ye=="number"&&(Ye<200||Ye>=300))continue;const ct=ae?.data,Ge=ct?.file_url||ct?.fileUrl||ae?.file_url||ae?.fileUrl;if(typeof Ge=="string"&&Ge.trim())return Ge}return null},[d]),oe=S.useCallback(Se=>{window.open(Se,"_blank","noopener,noreferrer")},[]),re=S.useCallback(Se=>{w(xe=>new Set(xe).add(Se))},[]),be=I.length===0,de=I.length<C,ot=Rl(C,I.length);return c.jsx(Et,{field:e,error:ne,isRequired:i,className:B(a,"!space-y-0"),hideLabel:ee,children:c.jsx("div",{className:B("min-h-[70px] min-w-0 w-full flex flex-col",l?"flex-1 h-full":"h-[70px]"),children:c.jsxs("div",{onClick:Se=>{Se.target.closest("[data-remove-in-dropzone]")||Se.target.closest("[data-no-open-picker]")||D()},onDragOver:K,onDragLeave:X,onDrop:ce,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-primary bg-primary/10",ne&&"border-destructive",s&&"opacity-50 cursor-not-allowed",!de&&I.length>0&&"cursor-default"),children:[c.jsx("input",{ref:p,id:ht(e),type:"file",accept:M,multiple:C>1,onChange:ie,disabled:s||e.disabled||!de,className:"hidden","aria-describedby":jt(e,!!ne),"aria-invalid":Jt(!!ne),"aria-required":i}),be?c.jsxs(c.Fragment,{children:[c.jsx(Hs,{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:"Drag & drop or click"}),G.length>0&&c.jsx("p",{className:"text-[10px] text-muted-foreground line-clamp-1",children:G.join(" • ")})]}):ot?c.jsx(Yl,{item:I[0],objectUrl:T[0]??null,failedUrlKeys:v,onImageUrlError:re,onRemove:()=>V(0),onOpenUrl:oe,openTarget:I[0]instanceof File?Pe:void 0,disabled:s||e.disabled}):c.jsx(Kl,{items:I,maxFiles:C,disabled:s,objectUrls:T,failedUrlKeys:v,onImageUrlError:re,onRemove:V,resolveOpenUrl:(Se,xe)=>xe instanceof File&&I.length===1&&Pe?.trim()?Pe.trim():null,onOpenUrl:Se=>{Se?.trim()&&oe(Se.trim())},addSlot:de?c.jsxs("button",{type:"button","data-no-open-picker":!0,onClick:Se=>{Se.stopPropagation(),p.current?.click()},disabled:s||e.disabled,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(Hs,{className:"h-4 w-4 mb-0.5","aria-hidden":!0}),"Add"]}):void 0})]})})})};function _E(e){const t=kE(e),r=b.forwardRef((n,o)=>{const{children:s,...i}=n,a=b.Children.toArray(s),d=a.find(FE);if(d){const u=d.props.children,l=a.map(f=>f===d?b.Children.count(u)>1?b.Children.only(null):b.isValidElement(u)?u.props.children:null:f);return c.jsx(t,{...i,ref:o,children:b.isValidElement(u)?b.cloneElement(u,void 0,l):null})}return c.jsx(t,{...i,ref:o,children:s})});return r.displayName=`${e}.Slot`,r}function kE(e){const t=b.forwardRef((r,n)=>{const{children:o,...s}=r;if(b.isValidElement(o)){const i=OE(o),a=PE(s,o.props);return o.type!==b.Fragment&&(a.ref=n?Bn(n,i):i),b.cloneElement(o,a)}return b.Children.count(o)>1?b.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var TE=Symbol("radix.slottable");function FE(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===TE}function PE(e,t){const r={...t};for(const n in t){const o=e[n],s=t[n];/^on[A-Z]/.test(n)?o&&s?r[n]=(...a)=>{const d=s(...a);return o(...a),d}:o&&(r[n]=o):n==="style"?r[n]={...o,...s}:n==="className"&&(r[n]=[o,s].filter(Boolean).join(" "))}return{...e,...r}}function OE(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var $i="Dialog",[Ym]=vr($i),[IE,Rr]=Ym($i),Xm=e=>{const{__scopeDialog:t,children:r,open:n,defaultOpen:o,onOpenChange:s,modal:i=!0}=e,a=b.useRef(null),d=b.useRef(null),[u,l]=Zr({prop:n,defaultProp:o??!1,onChange:s,caller:$i});return c.jsx(IE,{scope:t,triggerRef:a,contentRef:d,contentId:on(),titleId:on(),descriptionId:on(),open:u,onOpenChange:l,onOpenToggle:b.useCallback(()=>l(f=>!f),[l]),modal:i,children:r})};Xm.displayName=$i;var Jm="DialogTrigger",ME=b.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,o=Rr(Jm,r),s=Ze(t,o.triggerRef);return c.jsx(Be.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ql(o.open),...n,ref:s,onClick:Me(e.onClick,o.onOpenToggle)})});ME.displayName=Jm;var Xl="DialogPortal",[LE,Qm]=Ym(Xl,{forceMount:void 0}),Zm=e=>{const{__scopeDialog:t,forceMount:r,children:n,container:o}=e,s=Rr(Xl,t);return c.jsx(LE,{scope:t,forceMount:r,children:b.Children.map(n,i=>c.jsx(xr,{present:r||s.open,children:c.jsx(ni,{asChild:!0,container:o,children:i})}))})};Zm.displayName=Xl;var ji="DialogOverlay",eh=b.forwardRef((e,t)=>{const r=Qm(ji,e.__scopeDialog),{forceMount:n=r.forceMount,...o}=e,s=Rr(ji,e.__scopeDialog);return s.modal?c.jsx(xr,{present:n||s.open,children:c.jsx(BE,{...o,ref:t})}):null});eh.displayName=ji;var DE=_E("DialogOverlay.RemoveScroll"),BE=b.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,o=Rr(ji,r);return c.jsx(ui,{as:DE,allowPinchZoom:!0,shards:[o.contentRef],children:c.jsx(Be.div,{"data-state":Ql(o.open),...n,ref:t,style:{pointerEvents:"auto",...n.style}})})}),Gn="DialogContent",th=b.forwardRef((e,t)=>{const r=Qm(Gn,e.__scopeDialog),{forceMount:n=r.forceMount,...o}=e,s=Rr(Gn,e.__scopeDialog);return c.jsx(xr,{present:n||s.open,children:s.modal?c.jsx($E,{...o,ref:t}):c.jsx(jE,{...o,ref:t})})});th.displayName=Gn;var $E=b.forwardRef((e,t)=>{const r=Rr(Gn,e.__scopeDialog),n=b.useRef(null),o=Ze(t,r.contentRef,n);return b.useEffect(()=>{const s=n.current;if(s)return sl(s)},[]),c.jsx(rh,{...e,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Me(e.onCloseAutoFocus,s=>{s.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:Me(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,a=i.button===0&&i.ctrlKey===!0;(i.button===2||a)&&s.preventDefault()}),onFocusOutside:Me(e.onFocusOutside,s=>s.preventDefault())})}),jE=b.forwardRef((e,t)=>{const r=Rr(Gn,e.__scopeDialog),n=b.useRef(!1),o=b.useRef(!1);return c.jsx(rh,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{e.onCloseAutoFocus?.(s),s.defaultPrevented||(n.current||r.triggerRef.current?.focus(),s.preventDefault()),n.current=!1,o.current=!1},onInteractOutside:s=>{e.onInteractOutside?.(s),s.defaultPrevented||(n.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;r.triggerRef.current?.contains(i)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),rh=b.forwardRef((e,t)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:o,onCloseAutoFocus:s,...i}=e,a=Rr(Gn,r),d=b.useRef(null),u=Ze(t,d);return za(),c.jsxs(c.Fragment,{children:[c.jsx(Rs,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:o,onUnmountAutoFocus:s,children:c.jsx(Ws,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":Ql(a.open),...i,ref:u,onDismiss:()=>a.onOpenChange(!1)})}),c.jsxs(c.Fragment,{children:[c.jsx(UE,{titleId:a.titleId}),c.jsx(HE,{contentRef:d,descriptionId:a.descriptionId})]})]})}),Jl="DialogTitle",nh=b.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,o=Rr(Jl,r);return c.jsx(Be.h2,{id:o.titleId,...n,ref:t})});nh.displayName=Jl;var oh="DialogDescription",zE=b.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,o=Rr(oh,r);return c.jsx(Be.p,{id:o.descriptionId,...n,ref:t})});zE.displayName=oh;var sh="DialogClose",ih=b.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,o=Rr(sh,r);return c.jsx(Be.button,{type:"button",...n,ref:t,onClick:Me(e.onClick,()=>o.onOpenChange(!1))})});ih.displayName=sh;function Ql(e){return e?"open":"closed"}var ah="DialogTitleWarning",[ZP,lh]=Ov(ah,{contentName:Gn,titleName:Jl,docsSlug:"dialog"}),UE=({titleId:e})=>{const t=lh(ah),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
47
47
|
|
|
48
48
|
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
49
49
|
|
|
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(C=>C.stop()),u.current=null),h()},[h]);S.useEffect(()=>{if(!e){y(),p(null),g(!1);return}if(s)return;let C=!1;return p(null),g(!0),nN().then(N=>{if(C){N.getTracks().forEach(_=>_.stop());return}u.current=N,g(!1)}).catch(N=>{if(C)return;g(!1);const _=N instanceof Error?N.message:"Could not access camera";p(_)}),()=>{C=!0,u.current&&(u.current.getTracks().forEach(N=>N.stop()),u.current=null),h()}},[e,s,y,h]);const v=S.useCallback(C=>{a.current=C,C&&u.current&&e&&!f&&!m&&(C.srcObject=u.current,ch(C))},[e,f,m]);S.useLayoutEffect(()=>{if(!e||f||m||!u.current)return;let C=!1,N=0;const _=()=>{if(C)return;const I=a.current;!I||!u.current||(I.srcObject=u.current,ch(I))};_();const A=requestAnimationFrame(()=>{_(),N=requestAnimationFrame(_)});return()=>{C=!0,cancelAnimationFrame(A),cancelAnimationFrame(N),h()}},[e,f,m,h]);const w=S.useCallback(()=>{y(),p(null),g(!1),t(!1),l.current&&(l.current.value="")},[y,t]),x=S.useCallback(()=>{const C=a.current,N=d.current;if(!C||!N||!u.current||C.readyState<2)return;const _=C.videoWidth,A=C.videoHeight;if(_===0||A===0)return;N.width=_,N.height=A;const I=N.getContext("2d");I&&(I.drawImage(C,0,0),N.toBlob(T=>{if(!T)return;const W=new File([T],`camera-capture-${Date.now()}.jpg`,{type:"image/jpeg",lastModified:Date.now()}),J=n(W);if(J){i?.(J);return}i?.(void 0),r(W),w()},"image/jpeg",.92))},[r,n,w,i]),E=S.useCallback(C=>{const N=C.target.files?.[0];if(!N)return;const _=n(N);if(_){i?.(_);return}i?.(void 0),r(N),w(),l.current&&(l.current.value="")},[r,n,w,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:C=>{C||w()},children:c.jsxs(ZE,{className:"sm:max-w-md",showCloseButton:!0,onPointerDownOutside:C=>C.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:v,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:w,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"),v=e.metadata?typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata:null,w=e.validation?.find(K=>K.type==="fileSize"),x=e.validation?.find(K=>K.type==="fileType"),E=w?.value!=null?w.value:d?.maxSize??v?.maxSize??5*1024*1024,P=x?.value!=null?x.value:d?.accept??v?.accept??["image/*"],C=P.join(",")||"image/*",N=Ms(e),_=S.useCallback(K=>{if(w){const X=Yr(K,w);if(X!==!0)return typeof X=="string"?X:"File size exceeds the maximum allowed size"}else if(K.size>E)return`File size must be less than ${yo(E)}`;if(x){const X=Yr(K,x);if(X!==!0)return typeof X=="string"?X:"File type is not allowed"}return null},[w,x,E]),A=S.useMemo(()=>Ls(t),[t]),I=ql(A),T=S.useCallback(K=>{const X=ka(K,N);r(X),n?.()},[r,n,N]),W=S.useCallback(K=>{const X=_(K);if(X){l(X);return}l(void 0);const ce=[...A];ce.length>=N||(ce.push(K),T(ce),y("none"))},[A,N,_,T]),J=S.useCallback(K=>{const X=A.filter((ce,ne)=>ne!==K);T(X)},[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=[];(w||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(X=>new Set(X).add(K)),onRemove:()=>J(0),onOpenUrl:U,disabled:s}):c.jsx(Kl,{items:A,maxFiles:N,disabled:s,objectUrls:I,failedUrlKeys:m,onImageUrlError:K=>g(X=>new Set(X).add(K)),onRemove:J,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:_,accept:C,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),[v,w]=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"),C=E?.value?E.value:u?.maxSize??x?.maxSize??5*1024*1024,N=P?.value?P.value:u?.accept??x?.accept??["image/*"],_=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>C)return`File size must be less than ${yo(C)}`;if(P){const re=Yr(oe,P);if(re!==!0)return typeof re=="string"?re:"File type is not allowed"}return null},[E,P,C]),T=S.useMemo(()=>Ls(t),[t]),W=ql(T),J=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),J(be),w("none")},[T,A,I,J]),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=>{J(T.filter((re,be)=>be!==oe))},[T,J]),D=S.useCallback(()=>{s||T.length>=A||m||(p(void 0),w("file"),l.current?.click())},[s,T.length,A,m]),L=S.useCallback(()=>{s||T.length>=A||(p(void 0),w("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),J(be),w("none"))},[T,A,I,J]),$=S.useCallback(oe=>{g(oe),oe||w("none")},[]),ie=o||f,V=e.appearance?.hideLabel??!1,K=[];(E||C)&&K.push(`Max size: ${yo(C)}`),P&&N.length>0&&K.push(`Allowed: ${N.join(", ")}`),A>1&&K.push(`Up to ${A} photos`);const X=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:_,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?X: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&&X?X:null,onOpenUrl:oe=>{oe?.trim()&&ce(oe.trim())},addSlot:Pe})]})}),c.jsx(dh,{open:m,onOpenChange:$,onCaptured:U,validateFile:I,accept:_,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:v,extraSubmitPayload:w,buttonResponses:x,onButtonApiResponse:E,onValidateForm:P,getValidationErrors:C,allFields:N,onSubmittingChange:_,scopedFormValues:A,scopedFieldNameMap:I,prepopulateResponse:T=null,formSections:W,submitPayload:J})=>{const{gridStretch:O}=zo(),[j,M]=S.useState(!1),D=e.properties,L=ha.useParams(),U=S.useMemo(()=>({...h,...w}),[h,w]),$=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,X=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&&C)try{const q=C();$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),_?.(!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),_?.(!1)}return}if(l){if(!await re())return;M(!0),_?.(!0);try{await l(),E?.(e.name,{status:"success"})}finally{M(!1),_?.(!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"||!X)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,J),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}),w&&typeof w=="object"&&Object.entries(w).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"&&X)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(X,$,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??X??"",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 v?.(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 v=cs(y),w=y.label||v,x=i||!a?!0:a.visibility[v]!==!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}-${v}`,className:"text-xs font-normal truncate",children:w}),c.jsx(Nm,{id:`ui-section-${e.id}-${v}`,checked:x,disabled:i||!a||!!g,onCheckedChange:E=>{!a||i||a.setSectionVisible(v,!!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,v=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(v,"h-6 w-6"),onClick:()=>p(h+1),onMouseEnter:()=>m()},h):c.jsx(ou,{className:B(v,"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),v=b.useRef(0),x=i==="horizontal"?MN:LN,[E=[],P]=Zr({prop:l,defaultProp:u,onChange:T=>{[...y.current][v.current]?.focus(),f(T)}}),C=b.useRef(E);function N(T){const W=zN(E,T);I(T,W)}function _(T){I(T,v.current)}function A(){const T=C.current[v.current];E[v.current]!==T&&p(E)}function I(T,W,{commit:J}={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)){v.current=L.indexOf(M);const U=String(L)!==String(D);return U&&J&&p(L),U?L:D}else return D})}return c.jsx(IN,{scope:e.__scopeSlider,name:r,disabled:a,min:n,max:o,valueIndexToChangeRef:v,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||(C.current=E)}),min:n,max:o,inverted:m,onSlideStart:a?void 0:N,onSlideMove:a?void 0:_,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=v.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",v=y&&!s||!y&&s;function w(x){const E=g.current||f.getBoundingClientRect(),P=[0,E.width],N=ic(P,v?[r,n]:[n,r]);return g.current=E,N(x-E.left)}return c.jsx(Nh,{scope:e.__scopeSlider,startEdge:v?"left":"right",endEdge:v?"right":"left",direction:v?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=w(x.clientX);i?.(E)},onSlideMove:x=>{const E=w(x.clientX);a?.(E)},onSlideEnd:()=>{g.current=void 0,d?.()},onStepKeyDown:x=>{const P=Ah[v?"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(),v=[0,y.height],x=ic(v,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 v=Ah[m?"from-bottom":"from-top"].includes(h.key);d?.({event:h,direction:v?-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,w=>u(w)),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],v=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}% + ${v}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=v=>{s||i||e.disabled||e.readOnly||(r(v[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((v,w)=>c.jsx("span",{className:"text-center",children:v.label},w))})]})})},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(v=>{if(p)return;f(!0);const w=u.current;if(!w)return;const x=w.getContext("2d");if(!x)return;const E=w.getBoundingClientRect(),P="touches"in v?v.touches[0].clientX-E.left:v.clientX-E.left,C="touches"in v?v.touches[0].clientY-E.top:v.clientY-E.top;x.beginPath(),x.moveTo(P,C)},[p]),g=S.useCallback(v=>{if(!l||p)return;const w=u.current;if(!w)return;const x=w.getContext("2d");if(!x)return;const E=w.getBoundingClientRect(),P="touches"in v?v.touches[0].clientX-E.left:v.clientX-E.left,C="touches"in v?v.touches[0].clientY-E.top:v.clientY-E.top;x.lineWidth=2,x.lineCap="round",x.strokeStyle="#000",x.lineTo(P,C),x.stroke(),x.beginPath(),x.moveTo(P,C)},[l,p]),h=S.useCallback(()=>{if(!l)return;f(!1);const v=u.current;if(!v)return;const w=v.toDataURL();r(w),n?.()},[l,r,n]),y=S.useCallback(()=>{const v=u.current;if(!v||p)return;const w=v.getContext("2d");w&&(w.clearRect(0,0,v.width,v.height),r(null),n?.())},[p,r,n]);return S.useEffect(()=>{const v=u.current;if(v&&(v.width=v.offsetWidth,v.height=200,t)){const w=new Image;w.onload=()=>{const x=v.getContext("2d");x&&x.drawImage(w,0,0)},w.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,v=!u&&p?.allowDeleteRow!==!1,w=s===!1&&i===!1?!1:s||e.disabled||i||e.readOnly,x=t||[],E=y&&x.length<h,P=v&&x.length>g,C=S.useCallback(()=>{if(!E||w)return;const O={};m.forEach(j=>{O[j.name]=j.defaultValue??""}),r([...x,O]),n?.()},[x,m,E,w,r,n]),N=S.useCallback(O=>{if(!P||w)return;const j=x.filter((M,D)=>D!==O);r(j),n?.()},[x,P,w,r,n]),_=S.useCallback((O,j,M)=>{if(w)return;const D=[...x];D[O]||(D[O]={}),D[O][j]=M,r(D),n?.()},[x,w,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",J=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",w&&"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(J,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)),v&&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+(v?1:0),className:B(J,"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)},X=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:X(ie),onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,className:"w-full"});case"number":return c.jsx(Xd,{field:U,value:ie??null,onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,className:"w-full"});case"email":return c.jsx(su,{field:U,value:X(ie),onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,className:"w-full"});case"phone":case"aadhaar":return c.jsx(iu,{field:U,value:X(ie),onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,className:"w-full"});case"textarea":return c.jsx(au,{field:U,value:X(ie),onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,className:"w-full"});case"select":return c.jsx(kp,{field:U,value:typeof ie=="string"?ie:X(ie),onChange:G=>_(j,L.name,G),disabled:w,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=>_(j,L.name,ee),disabled:w,className:"w-full",formValues:D,submissionContext:f})}case"asyncsearch":return c.jsx(Xp,{field:U,value:ie,onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,className:"w-full",formValues:D,submissionContext:f});case"checkbox":return c.jsx(wm,{field:U,value:ie||!1,onChange:G=>_(j,L.name,G),disabled:w,className:"w-full"});case"radio":case"checkboxgroup":return c.jsx(Gm,{field:U,value:typeof ie=="string"?ie:X(ie),onChange:G=>_(j,L.name,G),disabled:w,className:"w-full"});case"date":case"time":case"datetime":case"daterange":return c.jsx(Km,{field:U,value:typeof ie=="string"?ie:X(ie),onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,className:"w-full"});default:return c.jsx(Da,{field:U,value:X(ie),onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,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)}),v&&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||w,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:C,disabled:w,className:"w-full",children:[c.jsx(nu,{className:"h-4 w-4 mr-2"}),"Add Row"]})})]})})};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 e_(e){const t=e.replace(/[^\d.-]/g,"");if(t===""||t==="-"||t===".")return null;const r=parseFloat(t);return Number.isNaN(r)?null:r}function t_(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 r_(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(r_(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 n_(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 o_=new Set(["all_items_summary","invoice_discount","grand_total"]);function s_(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"&&!o_.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 i_(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 a_(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")=>s_(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=i_(e,n,o.key);if(s?.kind==="formula"){const i=a_(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 l_(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:n_(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 c_(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 d_(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 u_(e){const t=e?.color?.trim();return t?{color:t}:{}}function fc(e){return{className:zh(e),style:u_(e)}}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 f_(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 p_=({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,_,A,I,T)=>{if(m)return;const W=T==="number"?e_(I):I===""?null:I,J=l_(u,g,N,_,A,W);r(J)},[m,g,r,u]),y=(N,_,A,I,T,W)=>{const J=l.find(U=>U.key===T),O=Vh(u,N,_,T),j=pc(Uh(O,J)),M=lc(W,O,J),D=f_(u,N,_),L=D?.kind==="static"?D.row.labelStyle:D?.kind==="dynamic"?D.block.labelStyle:void 0;if(O?.kind==="label"){const U=fc(L);return c.jsx("span",{className:B(U.className||"font-medium",j,!L?.color&&"text-foreground"),style:U.style,children:I??p})}if(O?.kind==="input"&&!m){const U=M==null||M===""?"":String(M);return c.jsx(wn,{type:"text",inputMode:O.inputType==="number"?"decimal":"text",value:U,onChange:$=>h(A,N,T,$.target.value,O.inputType),onBlur:n,className:B("h-8 text-sm border-0 shadow-none focus-visible:ring-1 bg-transparent",j),disabled:m})}if(O?.kind==="currency"){const U=Bh(O);if(U==="static"){const ie=O.value!==void 0&&O.value!==""?lc(null,{...O,mode:"static"},J):M;return c.jsx("span",{className:B("tabular-nums",j),children:Dh(ie,{currencySymbol:f,emptyDisplay:p})})}if(U==="api"||m)return c.jsx("span",{className:B("tabular-nums",j),children:Dh(M,{currencySymbol:f,emptyDisplay:p})});const $=t_(M);return c.jsxs("div",{className:B("flex w-full items-center gap-0.5",j==="text-center"&&"justify-center",j==="text-right"&&"justify-end",j==="text-left"&&"justify-start"),children:[c.jsx("span",{className:"shrink-0 text-sm tabular-nums text-foreground",children:f}),c.jsx(wn,{type:"text",inputMode:"decimal",value:$,onChange:ie=>h(A,N,T,ie.target.value,"number"),onBlur:n,className:"h-8 min-w-[2ch] max-w-full flex-1 border-0 bg-transparent text-sm tabular-nums shadow-none focus-visible:ring-1",disabled:m})]})}return O?.kind==="static"?c.jsx("span",{className:B("text-muted-foreground",j),children:O.value}):c.jsx("span",{className:B(j),children:Lh(M,J,{currencySymbol:f,emptyDisplay:p})})},v=u.gridTitle?.trim()??"",w=Math.max(1,e.position?.rowSpan??1),x=Math.max(1,e.position?.columnSpan??1),E=Math.max(g.rows.length,1),P=w>=3?"py-4":w>=2?"py-3":"py-2",C=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:[v?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:v}):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 _=fc(N.headerStyle);return c.jsx("th",{className:B(C,P,"text-xs uppercase tracking-wider whitespace-nowrap",pc(N.align),_.className||"font-semibold text-muted-foreground"),style:_.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(C,"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(_=>{const A=Vh(u,N.slotId,N.rowKind,_.key),I=Uh(A,_);return c.jsx("td",{className:B(C,P,"align-middle whitespace-nowrap",pc(I)),children:y(N.slotId,N.rowKind,N.rowInstanceId,N.label,_.key,N.values[_.key])},_.id)})},`${N.slotId}-${N.rowInstanceId}`))})]})})]})})};function mc(e,t,r){return d_(e,t,r)}const m_=({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(),v=f.showCurrentIndicator!==!1,[w,x]=S.useState(null),[E,P]=S.useState(!1),[C,N]=S.useState(null),_=ha.useParams(),A=S.useRef(i),I=S.useRef(a),T=S.useRef(d),W=S.useRef(_);A.current=i,I.current=a,T.current=d,W.current=_;const J=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(),X=await fetch(V,{method:K,headers:K==="POST"?{"Content-Type":"application/json"}:void 0});if(!X.ok)throw new Error(`HTTP ${X.status}`);const ce=await X.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&&J()},[p,u,J]);const O=p==="api"?w: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||C||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),$=v&&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 h_(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 g_=({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 v=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:v.length,contextListSample:v.length>0?v.slice(0,2):[]});const[w,x]=S.useState(()=>v.length>0?v:Array.isArray(t)?t:[]);S.useEffect(()=>{if(v.length>0){console.log("[SelectableList] Step 3: sync fullList from context",{fieldName:e.name,contextListLength:v.length}),x(v);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})},[v,t]);const E=S.useMemo(()=>{const T=Array.isArray(t)?t:[];return new Set(T.map(J=>So(J,p)))},[t,p]),P=w.length>0&&w.every(T=>E.has(So(T,p))),C=w.some(T=>E.has(So(T,p))),N=S.useCallback((T,W)=>{const J=So(T,p),O=Array.isArray(t)?t:[];W?E.has(J)||r([...O,T]):r(O.filter(j=>So(j,p)!==J)),n?.()},[t,p,E,r,n]),_=S.useCallback(T=>{r(T===!0?[...w]:[]),n?.()},[w,r,n]),A=w.length>0?w:Array.isArray(t)?t:[],I=s||e.disabled;return console.log("[SelectableList] Data in list",{fieldName:e.name,listLength:A.length,listSource:w.length>0?"fullList":"value",valueLength:Array.isArray(t)?t.length:0,fullListLength:w.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:C?"indeterminate":!1,onCheckedChange:_,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([...w]),n?.()},children:"Select all"}),c.jsx(Yt,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I||!C,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 J=So(T,p),O=E.has(J),j=`${ht(e)}-${W}-${J}`;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:h_(T,f,m,g)})]},J)})})]}),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 y_=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],b_=y_.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}},{}),v_="Separator",Wh="horizontal",w_=["horizontal","vertical"],Rh=b.forwardRef((e,t)=>{const{decorative:r,orientation:n=Wh,...o}=e,s=S_(n)?n:Wh,a=r?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return c.jsx(b_.div,{"data-orientation":s,...a,...o,ref:t})});Rh.displayName=v_;function S_(e){return w_.includes(e)}var x_=Rh;function gc({className:e,orientation:t="horizontal",decorative:r=!0,...n}){return c.jsx(x_,{"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 A_=({field:e,className:t})=>c.jsx("div",{className:B("py-2",t),children:c.jsx(gc,{})}),C_={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"},E_=({field:e,className:t})=>{const r=e.properties,n=r?.headingLevel??"h3",o=r?.showHorizontalLine??!0,s=C_[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"})]})},N_={"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"},__={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"},k_=({field:e,className:t})=>{const r=e.properties,n=r?.position??"top-left",o=r?.headingLevel??"h3",s=r?.showHorizontalLine??!0,i=N_[n],a=__[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"})]})},T_=({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 F_(e){if(Array.isArray(e))return e}function P_(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 O_(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
51
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function I_(e,t){return F_(e)||P_(e,t)||M_(e,t)||O_()}function M_(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,L_=Object.isFrozen,D_=Object.getPrototypeOf,B_=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),$_=zt(Array.prototype.lastIndexOf),Xh=zt(Array.prototype.pop),Co=zt(Array.prototype.push),j_=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),z_=zt(String.prototype.trim),U_=zt(Number.prototype.toString),V_=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=H_(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 H_(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&&(L_(t)||(t[n]=s),o=s)}e[o]=!0}return e}function W_(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=I_(n,2);const o=r[0],s=r[1];Ot(e,o)&&(cr(s)?t[o]=W_(s):s&&typeof s=="object"&&s.constructor===Object?t[o]=hr(s):t[o]=s)}return t}function R_(e){switch(typeof e){case"string":return e;case"number":return U_(e);case"boolean":return V_(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=B_(e,t);if(n){if(n.get)return zt(n.get);if(typeof n.value=="function")return zt(n.value)}e=D_(e)}function r(){return null}return r}function G_(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"]),K_=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"]),q_=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"]),Y_=Mr(/{{[\w\W]*|^[\w\W]*}}/g),X_=Mr(/<%[\w\W]*|^[\w\W]*%>/g),J_=Mr(/\${[\w\W]*/g),Q_=Mr(/^data-[\-\w.\u00B7-\uFFFF]+$/),Z_=Mr(/^aria-[\-\w]+$/),sg=Mr(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ek=Mr(/^(?:\w+script|data):/i),tk=Mr(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),rk=Mr(/^html$/i),nk=Mr(/^[a-z][.\w]*(-[.\w]+)+$/i),No={element:1,text:3,progressingInstruction:7,comment:8,document:9},ok=function(){return typeof window>"u"?null:window},sk=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]:ok();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"),v=Kn(h,"remove"),w=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 C,N="";const _=r,A=_.implementation,I=_.createNodeIterator,T=_.createDocumentFragment,W=_.getElementsByTagName,J=n.importNode;let O=ig();t.isSupported=typeof Kh=="function"&&typeof E=="function"&&A&&A.createHTMLDocument!==void 0;const j=Y_,M=X_,D=J_,L=Q_,U=Z_,$=ek,ie=tk,V=nk;let K=sg,X=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,X=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=G_(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&&(X=nt({},rg),ne=xo(null),pe.html===!0&&(nt(X,tg),nt(ne,ng)),pe.svg===!0&&(nt(X,wc),nt(ne,Ac),nt(ne,Gi)),pe.svgFilters===!0&&(nt(X,Sc),nt(ne,Ac),nt(ne,Gi)),pe.mathMl===!0&&(nt(X,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)&&(X===ce&&(X=hr(X)),nt(X,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&&(X["#text"]=!0),ve&&nt(X,["html","head","body"]),X.table&&(nt(X,["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.');C=F.TRUSTED_TYPES_POLICY,N=C.createHTML("")}else C===void 0&&(C=sk(g,o)),C!==null&&typeof N=="string"&&(N=C.createHTML(""));lr&&lr(F),Cr=F},er=nt({},[...wc,...Sc,...K_]),sr=nt({},[...xc,...q_]),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{v(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=C?C.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:X}),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))&&!X[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,w(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:z_(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(C&&typeof g=="object"&&typeof g.getAttributeType=="function"&&!Mt)switch(g.getAttributeType(ta,ir)){case"TrustedHTML":{Lt=C.createHTML(Lt);break}case"TrustedScriptURL":{Lt=C.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=R_(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(!X[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 C&&Je?C.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=J.call(n,Tt,!0)),Tt}let Mt=ve?Y.outerHTML:Y.innerHTML;return ve&&X["!doctype"]&&Y.ownerDocument&&Y.ownerDocument.doctype&&Y.ownerDocument.doctype.name&&Zt(rk,Y.ownerDocument.doctype.name)&&(Mt="<!DOCTYPE "+Y.ownerDocument.doctype.name+`>
|
|
52
|
-
`+Mt),xe&&Ao([j,M,D],$r=>{Mt=Eo(Mt,$r," ")}),C&&Je?C.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=$_(O[Ee],F);return Y===-1?void 0:j_(O[Ee],Y,1)[0]}return Xh(O[Ee])},t.removeHooks=function(Ee){O[Ee]=[]},t.removeAllHooks=function(){O=ig()},t}var ik=ag();const ak=["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"],lk=["href","target","rel","src","alt","title","class","style","colspan","rowspan"];function ck(e){return e?ik.sanitize(e,{ALLOWED_TAGS:[...ak],ALLOWED_ATTR:[...lk],ALLOW_DATA_ATTR:!1}):""}function dk(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 uk(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 fk(e){const t=qn(e);return t.textContent!==void 0?t.textContent:e.label??""}function pk(e){return qn(e).textContent===void 0||e.appearance?.hideLabel?!1:!!e.label?.trim()}function mk(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=dk(d,a,!0);return uk(u)}const hk=/\{api:[^}]+\}/,gk=/\{labelapi:[^}]+\}/;function Ec(e){return hk.test(e)}function Nc(e){return gk.test(e)}function yk(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 bk(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 vk(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function fg(e){return e.map(t=>{if(t.type==="text")return vk(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 wk(e){return e?fg(_c(e)):""}function Sk(e,t){return e?t==="markdown-lite"?wk(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 xk="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??mk(o),i=o.inlineFormat??"none";if(s==="paragraph"){const d=ck(Sk(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),xk);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=bk(r,o);return S.createElement(a,{className:ug(r,o)},mg(e,i))}function Ak(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 Ck(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 Ek=({field:e,className:t,formValues:r,urlParams:n,submissionContext:o,buttonResponses:s,prepopulateResponse:i,prepopulateLoading:a=!1})=>{const d=qn(e),u=S.useMemo(()=>Ak(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]),v=S.useCallback(async()=>{if(!u){f(void 0),h(null),m(!1);return}m(!0),h(null);try{const W=await Ck(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&&v()},[y,v]);const w=d.textAlign==="center"?"items-center":d.textAlign==="right"?"items-end":d.textAlign==="justify"?"items-stretch":"items-start",x=fk(e),E=pk(e),P=E&&e.label?e.label:"",C=e.description??"",N=yk({bodyTemplate:x,captionTemplate:P,descriptionTemplate:C,prepopulateLoading:a,labelApiConfigPresent:u!=null,labelApiLoading:p,labelApiResponse:l,labelApiError:g}),_={formValues:r??{},urlParams:n??{},submissionContext:o,buttonResponses:s,prepopulateResponse:i,labelApiResponse:l},A=x?Cc(x,_):"",I=E&&e.label?Cc(e.label,_):"",T=C?Cc(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",w,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:v,buttonResponses:w,onButtonApiResponse:x,onValidateForm:E,getValidationErrors:P,allFields:C,onSubmittingChange:N,onAddMore:_,scopedFormValues:A,scopedFieldNameMap:I,excludedOptionValues:T,prepopulateMappedFieldNames:W,fieldValueKey:J,hideTableRowControls:O=!1,urlParams:j={},prepopulateResponse:M=null,prepopulateLoading:D=!1,formSections:L,submitPayload:U})=>{switch(e.type){case"divider":return c.jsx(A_,{field:e,className:d});case"header":return c.jsx(E_,{field:e,className:d});case"sectionHeading":return c.jsx(k_,{field:e,className:d});case"spacer":return c.jsx(T_,{field:e,className:d});case"textLabel":return c.jsx(Ek,{field:e,className:d,formValues:u,urlParams:j,submissionContext:l,buttonResponses:w,prepopulateResponse:M??void 0,prepopulateLoading:D});case"status":return c.jsx(m_,{field:e,value:t??null,error:r,disabled:s,isRequired:a,className:d,formValues:u,submissionContext:l,extraSubmitPayload:v,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 $=J??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(g_,{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:w});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:w});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(p_,{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:w,onButtonApiResponse:x,bffSubmitApi:h,onBffSubmitResult:y,extraSubmitPayload:v,onValidateForm:E,getValidationErrors:P,allFields:C,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:w,onButtonApiResponse:x});case"addmore":return c.jsx(xN,{field:e,error:r,disabled:s,readOnly:i,isRequired:a,className:d,onAddMore:()=>_?.(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]})})}},Nk=({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 _k(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 kk{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=_k(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 Tk=new kk;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 Fk={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."},Pk=300;function Ok(){return{...Fk}}function Ik(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 Mk(e){const t=Ok();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(X=>X.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 X=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,...X&&{target:X}}]),(!K.then||!Array.isArray(K.then)||K.then.length===0)&&V.action&&(K.then=[{action:V.action,...X&&{target:X}}]),K.then&&Array.isArray(K.then)&&X&&(K.then=K.then.map(ne=>!ne.target&&X?{...ne,target:X}:ne));const ce=V.conditionExpression||JSON.stringify(K);if(y.has(ce))return;y.add(ce),h.push(K)}catch{}});const w=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:C,hidden:N,..._}=p,A={};_.hideLabel!==void 0&&(A.hideLabel=_.hideLabel),_.labelPosition!==void 0&&(A.labelPlacement=_.labelPosition),_.size!==void 0&&(A.size=_.size),_.customClass!==void 0&&(A.className=_.customClass);const{labelPosition:I,size:T,customClass:W,visibility:J,...O}=_,j=Object.keys(O).length>0?O:void 0,M=Object.keys(A).length>0?A:void 0,D=l.visibility??p?.visibility??J;let L=Ik(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:w,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=Mk(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 Lk=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,Lk)}function Dk(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 Bk(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 $k(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 jk(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 zk(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 Uk(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 Vk(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 Hk(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 Wk(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=Vk(r,n),l=Hk(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 Rk(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(Uk(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))||Gk(r))}function Gk(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(Rk(o))return o;const i=Wk(o,s);return i!==o&&(r=!0),i});return r?{...e,fields:n}:e}function Kk(e){return Yi(e)}const qk=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"&&qk.has(r.trim().toUpperCase()))}function Yk(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 Xk(e,t){const r=Yk(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 Jk(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 Qk(e){return Jk(e).some(t=>t.toLowerCase().includes("payment"))}function Zk(e){const t=e.properties,r=e.metadata;return!!(t?.mergeSuccessDataIdAsPaymentId||r?.mergeSuccessDataIdAsPaymentId)}function eT(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(Zk(t)||n!=null&&typeof n=="object"&&!Array.isArray(n)&&Pc(n)||Qk(t))return r}const tT=new Set(["section","group","columns","divider","header","sectionHeading","spacer","addmore","textLabel","customizeSections"]);function rT(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 nT(e,t){const r=e.properties,n=Array.isArray(r?.linkedFieldNames)?r.linkedFieldNames:[],o=rT(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 oT(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=nT(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||tT.has(i.type)?!1:s.has(a)})}function sT(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 iT(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 aT(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}=aT(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 lT(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 cT(e,t){return e.maxRow+1+t*e.blockHeight}function dT(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(w=>o.get(w)).filter(w=>!!w);if(d.length===0)continue;const u=d.filter(w=>!Ng(w,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 v=!1;for(let w=f;w<=f+m-1;w++){for(let x=p;x<=p+g-1;x++){const E=`${w}-${x}`;if(i.has(E)){v=!0;break}y.add(E)}if(v)break}if(!v){for(const w of y)i.add(w);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 uT(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:v,rowSpan:w,colSpan:x}=h,E=`${y}-${v}`;for(let N=y;N<=y+w-1;N++)for(let _=v;_<=v+x-1;_++)a.add(`${N}-${_}`);const P=l,C=bs(f,m+1);d.set(E,{anchorRow:y,anchorCol:v,rowSpan:w,colSpan:x,run:P,legend:C,renderFields:Oc(g),addMoreMeta:{addMoreFieldName:u.addMoreFieldName,blockId:p,blockIndex:m}})})}return{anchorsByOrigin:d,coveredCells:a}}function fT(e,t,r,n){const o=`${e}-${t}`;return r.has(o)?!n.get(o):!1}function pT(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 mT(e,t,r,n){return!(!n||r.run.section.collapsible!==!0||e===r.anchorRow&&t===r.anchorCol)}function hT(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 gT(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 yT(e,t){return new Map([...e,...t])}function bT(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 vT=2*6e4,kg=50;class wT{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 ST(e){return(e??"").trim()||"default"}function Tg(e){const t=ST(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 wT(vT);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:v,getViewerContext:w,hideTableRowControls:x=!1,themeVars:E,dark:P=!1,omitRootWrapper:C=!1})=>{const N=Rn(k=>k.viewerContext),_=S.useMemo(()=>{if(v!==void 0)return v;const k=w?.();return k!==void 0?k:N},[v,w,N]),[A,I]=S.useState(e||null),[T,W]=S.useState(!!t&&!e),[J,O]=S.useState(null),j=e?.BFF_submit_api??J,[M,D]=S.useState(!1),[L,U]=S.useState({}),[$,ie]=S.useState({}),[V,K]=S.useState({}),[X,ce]=S.useState({}),[ne,G]=S.useState({}),[ee,Pe]=S.useState(null),oe=ha.useParams(),re=Nt(k=>k.setValues),be=Nt(k=>k.setSubmitting),de=Nt(k=>k.formDisabled),ot=Nt(k=>k.visibleFields),Se=Nt(k=>k.requiredFields),xe=Nt(k=>k.updateVisibility),ae=Nt(k=>k.updateRequired),ve=Nt(k=>k.setFieldError),Ye=S.useRef(!1),ct=S.useRef(void 0),Ge=S.useMemo(()=>{if(!e)return null;const k=e;if(k.form&&Array.isArray(k.form.fields))try{return ms(k.form,k.form.fields,k.form.layout||null,k.form.rules||[])}catch{return e}if(Array.isArray(k.fields)&&k.fields.some(z=>typeof z.metadata=="string"&&z.metadata.startsWith("{")||z.fieldType&&!z.type))try{const z={id:k.id||k._id||"temp",name:k.name||"Form",version:k.version??1,status:k.status||"draft",createdAt:k.createdAt||new Date().toISOString(),updatedAt:k.updatedAt||new Date().toISOString(),createdBy:k.createdBy||"system",category:k.category||"",moduleId:k.moduleId,tenantId:k.tenantId,featureId:k.featureId,isDefault:k.isDefault||!1};return ms(z,k.fields,k.layout||null,k.rules||[])}catch{return e}return e},[e]);S.useEffect(()=>{if(e){const k=e;k.BFF_submit_api&&O(k.BFF_submit_api)}},[e]);const Kt=S.useMemo(()=>{const k=Ge||A,H=k?Yi(k):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 k=(Tn()??"").trim()||"default",H=Pg({scope:k,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:k})=>{if(!t)return;const H=t;k||W(!0);try{const z=await Tk.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{k||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 k=>{const H=q?.fields?.length?tc(k,q.fields):k,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(k=>k.readOnlyFields),Cr=Nt(k=>k.editableFields),Jn=S.useCallback(k=>Ct.has(k),[Ct]),It=S.useCallback(k=>Cr.has(k),[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 k=q.config?.prepopulateApi,H=!!(k?.fieldMapping&&Object.keys(k?.fieldMapping??{}).length>0),z=(q.config?.prepopulateResponseRules?.length??0)>0;if(!k?.enabled||!k.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(k.apiEndpoint));if(k.apiQueryParams?.length){const se=new URLSearchParams;k.apiQueryParams.forEach(({key:Ie,value:me})=>se.append(Ie,Ne(me))),De=`${De}${De.includes("?")?"&":"?"}${se.toString()}`}const at={};k.apiHeaders?.forEach(({key:se,value:Ie})=>{se.trim()&&(at[se]=Ne(Ie))}),at["Content-Type"]=at["Content-Type"]??"application/json";let Ht;if(k.apiMethod==="POST"&&k.apiBodyFields?.length){const se={};k.apiBodyFields.forEach(({key:Ie,value:me})=>{Ie.trim()&&(se[Ie]=Ne(me))}),Ht=JSON.stringify(se)}const Le=await fetch(De,{method:k.apiMethod,headers:at,body:k.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(k?.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]=c_(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=k.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=k.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),aP=ut&&ut[ma]||ma,Kc=Ft[aP];if(Kc==null)continue;const lP=`${ma}__addmore__${se}__${ue[bt]}`;lt[lP]=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=Xk(Ve,{treatFirstItemIdAsPaymentId:k?.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((k,H)=>er||!!H&&!It(k)||Jn(k)&&!It(k),[er,It,Jn]),fn=q.fields.filter(k=>!k.parentId),kt=[...Er?ft:fn.length>0?fn:q.fields].filter(k=>!(!k||typeof k!="object"||!k.name&&!k.key)).sort((k,H)=>{const z=typeof k.position?.order=="number"?k.position.order:typeof k.positionOrder=="number"?k.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 k.position?.column=="number"?k.position.column:1,le=typeof H.position?.column=="number"?H.position.column:1;return Q-le}),Ss=S.useCallback(k=>{const H=Nt.getState().errors,z=Object.keys(H).find(Z=>k.includes(Z));z&&requestAnimationFrame(()=>{document.querySelector(`[data-field-name="${z}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})})},[]),Nr=async k=>{if(k?.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(k);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((k,H)=>{const z=q.fields.find(Q=>Q.type==="button"&&(Q.name===k||Q.key===k)),Z=eT(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,[k]: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(C)return;const k=q.config?.theme?.cssVariables;if(!(!k&&!E))return{...k??{},...E??{}}},[C,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(k=>{if(!_)return!0;const H=k.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&&_.userId!=null&&le.includes(_.userId))return!1;if(Q.length>0&&_.userId!=null&&Q.includes(_.userId))return!0;const Ce=z!=null&&z!==""&&_.userType!=null&&_.userType!==z,Ne=Z!=null&&Z!==""&&_.role!=null&&_.role!==Z,De=Q.length>0&&(_.userId==null||!Q.includes(_.userId));return!(Ce||Ne||De)},[_]),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((k,H)=>{Oo(z=>z[k]===H?z:{...z,[k]:H})},[]),ta=S.useMemo(()=>({visibility:ir,setSectionVisible:Lt,fieldToHeading:Mt,allFields:q.fields}),[ir,Lt,Mt,q.fields]),et=S.useCallback(k=>k.name||k.key||k.id,[]),Tr=k=>{if(!wt(k))return!1;const H=k.name||k.key||k.id;if(!wh(H,k.type,ir,Mt))return!1;const z=k.hidden===!0;return Ar(H)||!z&&H},yy=S.useCallback(k=>{const H=q.fields.find(Z=>et(Z)===k);if(H)return H.type;const z=vh(k);return q.fields.find(Z=>et(Z)===z)?.type},[q.fields,et]),ra=S.useCallback(k=>wh(k,yy(k),ir,Mt),[ir,Mt,yy]),pn=S.useCallback(k=>ra(k)?Po(k):!1,[ra,Po]);S.useEffect(()=>{const{visibleFields:k,requiredFields:H,errors:z}=Nt.getState(),Z=new Set(k),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(k=>{let H=k;if(k.type==="table"){const Z=k.properties?.columns;if(Array.isArray(Z)&&Z.length>0){const Q=Z.filter(le=>wt(le));H={...k,properties:{...k.properties,columns:Q}}}}const z=sT(H,Dt,et);return z?{...H,label:Cg(z,0)}:H},[wt,Dt,et]),mn=S.useCallback(k=>Eg(k,q.fields,Dt,et),[q.fields,Dt,et]),Gr=S.useCallback((k,H,z)=>`${k}__addmore__${H}__${z}`,[]),na=S.useCallback((k,H)=>`${k}__${H??"base"}`,[]),oa=S.useCallback((k,H)=>{const z=na(k.id,H);return X[z]??k.defaultCollapsed??!1},[X,na]),Wc=S.useCallback((k,H,z)=>{const Z=na(k,H);ce(Q=>Q[Z]===z?Q:{...Q,[Z]:z})},[na]),sa=S.useMemo(()=>{const k=[],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()!==""&&k.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()!==""&&k.push(String(we))}}return k},[q.fields,V,$,ne,L.documentId,et,mn,Gr]);S.useEffect(()=>{U(k=>{const H={...k,document_ids:sa},z=k.document_ids;return Array.isArray(z)&&z.length===sa.length&&sa.every((Z,Q)=>z[Q]===Z)?k:H})},[sa]);const ia=S.useCallback((k,H,z,Z)=>{for(const Q of z){const le=et(Q),Ce=Gr(le,k,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(k=>{const H=et(k);if(!H)return;if(mn(k).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((k,H)=>{K(z=>{const Z=z[k]||[],Q=Z.filter(le=>le!==H);if(Q.length===Z.length)return z;if(Q.length===0){const le={...z};return delete le[k],le}return{...z,[k]:Q}})},[]),la=S.useMemo(()=>kt.filter(k=>!k.parentId),[kt]),On=S.useMemo(()=>{const k=[];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=lT(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;k.push({addMoreFieldName:Z,baseOrder:Q,blockHeight:Ve,blockIds:le,linkedFields:Ce,insertedRows:we,templateFieldNames:De,templateBounds:at})}),k},[kt,la,Y,et,V,mn,Dt]),As=S.useMemo(()=>({}),[]),ca=S.useMemo(()=>On.length===0?kt:kt.map(k=>{const H=k.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?k:{...k,position:{...k.position,order:H+z}}}),[kt,On]),da=S.useCallback(k=>{const H={};return Object.entries($).forEach(([z,Z])=>{const Q=k[z];Q&&(H[Q]=Z)}),H},[$]),Io=S.useMemo(()=>{const k=[],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?cT(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)])}k.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:k,scopeByFieldName:H}},[On,ne,et,Gr,Oe,da,q.fields]),Cs=S.useMemo(()=>[...ca,...Io.clonedFields].sort((k,H)=>{const z=k.position?.order??0,Z=H.position?.order??0;if(z!==Z)return z-Z;const Q=k.position?.column??1,le=H.position?.column??1;if(Q!==le)return Q-le;const Ce=ko(k.position)??0,Ne=ko(H.position)??0;return Ce!==Ne?Ce-Ne:String(k.id).localeCompare(String(H.id))}),[ca,Io.clonedFields]),Mo=S.useMemo(()=>Dk(Cs.filter(k=>!k.parentId),Tr),[Cs,Tr]),Rc=S.useCallback((k,H)=>Mo.some(z=>Bk(k,H,z,Y)),[Mo,Y]);Mo.length===0||Math.max(...Mo.map(k=>(k[0]?.position?.order??0)+gs(k,Y).rowSpan));const ua=S.useMemo(()=>iT(Dt,Oc(kt.filter(k=>!k.parentId)),et),[Dt,kt,et]),{anchorsByOrigin:by,coveredCells:vy}=S.useMemo(()=>dT(ua,ca,et,Y),[ua,ca,et,Y]),{anchorsByOrigin:wy,coveredCells:Sy}=S.useMemo(()=>uT(On.map(k=>({addMoreFieldName:k.addMoreFieldName,blockIds:k.blockIds,linkedFields:k.linkedFields,templateFieldNames:k.templateFieldNames})),Dt,Io.clonedFields,la,Y,et,vy),[On,Dt,Io.clonedFields,la,Y,et,vy]),hn=S.useMemo(()=>yT(by,wy),[by,wy]),xy=S.useMemo(()=>Sy,[Sy]),Ay=String(Tt).endsWith("px")?Tt:In,Cy=S.useCallback((k,H)=>{for(let z=0;z<Y;z++){if(z>=H.anchorCol&&z<H.anchorCol+H.colSpan)continue;if(As[`${k}-${z}`]||hn.get(`${k}-${z}`)||vg(k,z,Cs,Tr).length>0||Rc(k,z))return!0}return!1},[Y,As,hn,Cs,Tr,Rc]),Ey=S.useMemo(()=>hT(hn,k=>{const H=k.run.section;return H.collapsible?oa(H,k.addMoreMeta?.blockId):!1},Cy),[hn,oa,Cy]),Ny=S.useMemo(()=>{const k=[];for(const H of Object.keys(As)){const z=Number(H.split("-")[0]);Number.isNaN(z)||k.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++)k.push(z);return $k(Mo,Y,k)},[Mo,Y,As,hn,Tr]),{originalToDisplayRow:fa,displayRowCount:nP,sortedOccupiedRows:oP}=S.useMemo(()=>{const k=jk(Ny);return{originalToDisplayRow:k.originalToDisplay,displayRowCount:k.displayRowCount,sortedOccupiedRows:k.sortedOriginalRows}},[Ny]),_y=Math.max(nP,1),Gc=S.useCallback((k,H=1)=>zk(k,H,fa),[fa]),ky=S.useMemo(()=>{const k=new Set;for(const H of Ey){const z=fa.get(H);z!==void 0&&k.add(z)}return k},[Ey,fa]),sP=S.useMemo(()=>gT(_y,Ay,ky),[_y,Ay,ky]),iP=S.useMemo(()=>bT(kt.filter(k=>!k.parentId&&Tr(k)),ua,et),[kt,ua,et,Tr]),pa=S.useCallback(k=>{if(F)return null;const H=et(k),z=V[H]||[];if(z.length===0)return null;const Z=mn(k);if(Z.length===0)return null;const Q=oT(k,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=k.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},`${k.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:C?B("relative",d):B(ga,P&&"dark",d),style:xs,"data-form-renderer":C?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(Nk,{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:sP,gridTemplateColumns:`repeat(${Y}, 1fr)`,rowGap:he,columnGap:st},"data-form-renderer":"grid",children:oP.map(k=>Array.from({length:Y},(H,z)=>{const Z=Gc(k);if(!Z)return null;if(Rc(k,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-${k}-${z}`);if(fT(k,z,xy,hn)){const we=pT(k,z,hn);return we&&mT(k,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-${k}-${z}`)}const Q=hn.get(`${k}-${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}-${k}-${z}-${Ae?.blockId??"base"}`)}const le=vg(k,z,Cs,Tr).filter(we=>!(et(we)?.includes("__addmore__")&&xy.has(`${k}-${z}`)));if(le.length===0){const we=As[`${k}-${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-${k}-${z}`)}return c.jsx("div",{className:"min-w-0",style:{pointerEvents:"none"},"data-form-renderer":"grid-cell","data-form-renderer-empty":!0},`empty-${k}-${z}`)}const Ce=le[0],{rowSpan:Ne,columnSpan:De}=gs(le,Y),at=Gc(k,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(k=>{if(!Tr(k))return null;const H=iP.find(Z=>Z.kind==="border"&&Z.fields.some(Q=>Q.id===k.id));if(H)return H.fields[0]?.id!==k.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}-${k.id}`);if(!k.parentId){const Z=kt.filter(le=>!le.parentId&&Tr(le)&&qi(le)===qi(k)),Q=Tc(Z).slice(0,2);if(Q.length>1&&Q[0].id!==k.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(k.type==="section"){const Z=q.fields.filter(Q=>Q.parentId===k.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:k,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})},k.id)}const z=k.name||k.key||k.id;return c.jsxs("div",{"data-field-name":z,"data-form-renderer":"field-wrapper",style:xn(k),children:[c.jsx(un,{field:Qn(k),value:Oe[z],error:pe[z]||je>0?te[z]:void 0,onChange:Z=>xt(z,Z),onBlur:()=>ze(z),disabled:(k.type==="table"||k.type==="billingGrid")&&a==="fill"?!1:de||!Vt(z)||er||!!k.disabled,readOnly:(k.type==="table"||k.type==="billingGrid")&&a==="fill"?!1:sr(z,!!k.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}),k.type==="addmore"&&pa(k)]},k.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 xT(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 J=W.startsWith(".")?W:`.${W}`;T.push(J),J===".csv"?T.push("text/csv"):J===".xls"?T.push("application/vnd.ms-excel"):J===".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 J=t[W];return J!==void 0?String(J):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,v=Mg(y.position),w=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 v.column=="number"?v.column:typeof y.positionColumn=="number"?y.positionColumn:1,columnSpan:typeof v.columnSpan=="number"?v.columnSpan:typeof v.width=="number"?v.width:typeof y.positionWidth=="number"?y.positionWidth:1,rowSpan:typeof v.rowSpan=="number"?v.rowSpan:typeof y.positionRowSpan=="number"?y.positionRowSpan:1},C=ko(v,{cellSlotIndex:y.cellSlotIndex??x.cellSlotIndex,stackSlot:w.stackSlot??x.stackSlot});typeof C=="number"&&(P.cellSlot=C);const N=v.cellGroupId??x.cellGroupId;typeof N=="string"&&(P.cellGroupId=N);const _=hs(v)??hs(x)??(w.stackDirection==="horizontal"||x.stackDirection==="horizontal"?"row":w.stackDirection==="vertical"||x.stackDirection==="vertical"?"stack":void 0);return(_==="row"||_==="stack")&&(P.sharedCellLayout=_),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",[AT]=vr(Xi,[Li]),Lg=Li(),[CT,Dc]=AT(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(CT,{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 ET=Dg,NT=$g,_T=zg,kT=Vg;function Rg({className:e,...t}){return c.jsx(ET,{"data-slot":"tabs",className:B("flex flex-col gap-2",e),...t})}function Gg({className:e,...t}){return c.jsx(NT,{"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(_T,{"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(kT,{"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 TT({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 FT(){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 PT=3e4,OT=10*6e4,IT=9e4,MT=15*6e4;function LT(e){return e!=null&&"on_success"in e&&e.on_success!=null}function DT(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 v=gn.useQueryClient(),w=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([]),[C,N]=S.useState(null),[_,A]=S.useState(null),[I,T]=S.useState(null),[W,J]=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??"",w[0],w[1],w[2]],queryFn:()=>e({...x,featureId:a}),staleTime:PT,gcTime:OT}),$=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(!C)return;const ae=E.find(Ye=>Ye.step_id===C),ve=O.current===C;return ae?.feature_id??(ve?D.current:void 0)??void 0},[C,E]),K=gn.useQuery({queryKey:["workflow-step",t,V??"",r??"",w[0],w[1],w[2]],queryFn:()=>e({...x,featureId:V}),enabled:!!V,staleTime:IT,gcTime:MT,refetchOnWindowFocus:!0,refetchOnReconnect:!0}),X=K.isPending,ce=K.error?K.error instanceof Error?K.error.message:"Failed to load form":null;S.useEffect(()=>{!K.data||O.current===C||(A(K.data),T(null),O.current=null,D.current=null)},[K.data,C]),S.useEffect(()=>{T(ce)},[ce]),S.useEffect(()=>{V===void 0&&O.current!==C&&(A(null),T(null),O.current=null,D.current=null)},[V,C]);const ne=S.useMemo(()=>{const ae=_?.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:xT(_,n)},[_,n,r]),G=S.useMemo(()=>{const ae=_?.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}},[_?.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(()=>{v.invalidateQueries({queryKey:["workflow-steps",t]}),v.invalidateQueries({queryKey:["workflow-step",t]})},[v,t]),be=S.useCallback(ae=>{if(LT(ae)){const Ge=ae.on_success,Kt=Ge?.action;if(Kt==="redirect"&&Ge?.redirect_url){const Je=DT(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;v.removeQueries({queryKey:["workflow-step",t,$e,r??"",w[0],w[1],w[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)},[v,t,r,i,p,E,n,w,re]),de=S.useCallback(async ae=>_?.BFF_submit_api?(i?.(),{success:!0,message:"Saved successfully"}):{success:!1,message:"Submit not configured"},[_?.BFF_submit_api,i]),ot=S.useCallback((ae,ve)=>{},[]),Se=S.useCallback(ae=>{},[]);if($)return c.jsx(TT,{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=_?.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:C??"",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!==C?null:X?c.jsx(FT,{}):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&&!_?.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!==C||M.current!==(ee?.id??null);if(C&&ee&&ve){j.current=C,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:C??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&&J(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 BT(e){return typeof e=="object"&&e!==null&&"apiEndpoint"in e}function $T({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 v=e.fields.find(w=>w.id===h);return v?.parentId?g(v.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 jT({field:e,value:t,allValues:r,validateOnChange:n=!1,validateOnBlur:o=!0,debounceMs:s=Pk}){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 v;for(const w of e.validation){const x=Yr(t,w,r);if(typeof x=="string"){v=x;break}}return a(v),u(!1),v},[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(v=>{a(v)},[]);return{error:i,isValidating:d,validate:p,handleBlur:g,clearError:h,setCustomError:y}}const Xg="—";function Xt(){return{kind:"static",value:Xg}}function zT(){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 UT={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:zT()}},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 VT(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 HT(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 WT(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 RT(e){const t=Qg(e.container,e.layout);return B(WT(e.layout),HT(t.maxWidth,e.layout),VT(t.padding),t.showBorder&&"rounded-lg border border-border")}const Ji=1;function GT(){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 KT(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 qT(e){const t=e;return!t||typeof t!="object"?GT():(t.version!==Ji&&(t.version=Ji),KT(t))}const ey={};let ty=null;function YT(e){ty=e}function XT(){return(ey?.VITE_API_BASE_URL?.trim()||ey?.VITE_API_URL?.trim()||"").replace(/\/$/,"")}const vs=_t.create({baseURL:XT()});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 JT(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 QT({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=S.useRef(null),g=String(r??t.clientId??i?.clientId??""),h=JSON.stringify(t);S.useEffect(()=>{if(i)return;const C=e.prepopulateApi;if(!C?.enabled||!C.api?.path||!g){p({}),m.current=null;return}const N=JSON.stringify({path:C.api.path,method:C.api.method,mapping:C.contextMapping,bindings:e.dataBindings,context:h});if(m.current===N)return;let _=!1;return m.current=N,(async()=>{try{const A=oy(e.dataBindings??[],t),I={...t,...A},T=await $c({clientId:g,api:C.api,context:I});if(_)return;const W=JT(T,C.contextMapping);p({...W,prepopulateResponse:T})}catch{_||p({})}})(),()=>{_=!0}},[i,e.prepopulateApi,e.dataBindings,h,g]);const y=S.useMemo(()=>{if(i)return{...i.context,...t};const C=oy(e.dataBindings??[],t);return{...t,...C,...f}},[i,t,e.dataBindings,f]),v=String(r??y.clientId??i?.clientId??""),w=S.useCallback((C,N,_)=>{u(A=>({...A,[C]:{...A[C]??{},[N]:_}}))},[]),x=S.useCallback(C=>l.current[C]??{},[]),E=S.useCallback((C,N,_,A)=>{(o??i?.onAction)?.({...C,sourceWidgetId:N,event:_,payload:A})},[o,i?.onAction]),P=S.useMemo(()=>({schema:e,context:y,clientId:v,nestingDepth:n,onAction:o??i?.onAction,getWorkflowState:s??i?.getWorkflowState,filterGroups:d,setFilterValue:w,getFilterGroup:x,dispatchAction:E}),[e,y,v,n,o,i?.onAction,s,i?.getWorkflowState,d,w,x,E]);return c.jsx(ny.Provider,{value:P,children:a})}function Lr(){const e=S.useContext(ny);if(!e)throw new Error("usePageContext must be used within PageContextProvider");return e}const ZT=5,sy=1;function Fo(e){return Number.isFinite(e)?Math.min(ZT,Math.max(sy,Math.round(e))):sy}function eF(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 tF(e){return Number.isFinite(e)?Math.min(100,Math.max(0,Math.round(e))):0}function rF(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 rF(100,Fo(e))}function nF(e){const t=e.trim(),r=/^(\d+(?:\.\d+)?)\s*%?$/.exec(t);return r?tF(Number(r[1])):null}function ay(e,t){const r=Fo(t),n=[];for(let s=0;s<r;s++){const i=nF(e?.[s]??"");if(i===null)return iy(r);n.push(i)}return n.reduce((s,i)=>s+i,0)!==100?iy(r):n}function oF(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 sF(e){return e.length?e.map(t=>`minmax(0, ${t}fr)`).join(" "):"minmax(0, 1fr)"}function iF(e,t,r,n){const o=Fo(t),s=eF(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:sF(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 aF(e){return B(jc(e.showBorder,e.borderStyle??"solid"),e.showBorder&&"p-3")}function lF(e){return B(jc(e.showBorder,e.borderStyle??"solid"),e.showBorder&&"p-2")}function cF(e,t){return e.columnBorders?.[t]!==void 0?!!e.columnBorders[t]:!!e.showColumnBorders}function dF(e,t){const r=cF(e,t);return B(jc(r,e.borderStyle??"dashed"),r&&"p-2")}function uF(e){if(e)return{minHeight:`${e}vh`}}function fF({widget:e,renderChildren:t}){const r=e.config,[n,o]=S.useState(r.defaultCollapsed??!1);return c.jsxs("section",{className:B("space-y-4",aF(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 pF({widget:e,renderChildren:t}){const r=e.config,n=Fo(r.columns??2),o=r.collapseEmptyColumns!==!1,s=iF(e.children??[],n,r.columnWidths,{collapseEmpty:o});return c.jsx("div",{className:B("grid w-full min-w-0 items-stretch",oF(r.gap),lF(r)),style:{gridTemplateColumns:s.gridTemplate,...uF(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",dF(r,d)),children:t?.(i)},d)})})}function mF({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 hF({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 gF({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 yF(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]=yF(o,t));return r}function bF(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=bF(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 vF({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 wF={start:"justify-start",center:"justify-center",end:"justify-end","space-between":"justify-between"},SF={sm:"gap-2",md:"gap-3",lg:"gap-4"};function xF({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",wF[t.align??"start"],SF[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 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}=Lr(),l=S.useMemo(()=>t.filterGroupKey?u(t.filterGroupKey):{},[t.filterGroupKey,u]),f=S.useMemo(()=>["page-ds",e,t,a,l,n,o,s],[e,t,a,l,n,o,s]);return gn.useQuery({queryKey:f,enabled:r&&(!!d||t.mode==="static"),staleTime:fy(t,i.dataApis??{})?.staleTimeMs??3e4,queryFn:async()=>{if(t.mode==="static")return t.staticData;if(t.mode==="context")return Qe(a,t.contextPath??"");const p=fy(t,i.dataApis??{});if(!p)throw new Error(`No API config for data source on widget ${e}`);const m={...a};if(t.requestBindings)for(const y of t.requestBindings){let v;y.source==="binding"?v=a[y.key]:y.source==="filter"&&(v=l[y.key]),v!==void 0&&(m[y.param]=v)}const h={...dy(m,a),...n!==void 0?{page:n,pageSize:o,search:s}:{}};return $c({clientId:d,api:p,context:h,filterState:l})}})}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 AF(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 CF={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"},EF={rectangle:"rounded-lg",square:"aspect-square rounded-lg",circle:"aspect-square rounded-full"},NF={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"},_F={sm:"gap-2",md:"gap-3",lg:"gap-4"};function kF({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(CF[n??"default"],EF[o??"rectangle"],NF[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(kF,{title:e.title,value:i,trend:a,variant:e.variant,shape:e.shape,size:e.size,layout:e.layout,isLoading:n,isError:o})}function TF({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 FF({stat:e,widgetId:t}){return c.jsx(my,{stat:e,widgetId:`${t}-${e.id}`})}function PF({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",_F[t.gap??"md"]),children:r.map(s=>c.jsx(FF,{stat:s,widgetId:e.id},s.id))})}function OF({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 IF(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 MF({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=IF(d,f??"data.items"),m=(g,h)=>{const y=t.dataSource.responseMapping.find(v=>v.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 LF=75;function DF(e){return e??LF}function Vc({scrollBehavior:e="page",maxHeightPercent:t,children:r,className:n}){if(e!=="contained")return c.jsx(c.Fragment,{children:r});const o=DF(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 BF(e,t,r){return["embedded-form",e,t,r??"latest"]}async function $F(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 jF(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 $F(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 zF=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:BF(e,o,s),queryFn:()=>jF(e,o,s),staleTime:zF}),p=S.useMemo(()=>AF(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 UF({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 VF({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 HF({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 WF(e,t){return e?.length?e.filter(r=>r.config.tabId===t):[]}const RF=1;function GF(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 KF(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 qF(e,t,r){return e?new Set(r?[r]:[]):new Set(t.map(n=>n.id))}function YF({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 XF({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>=RF?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 JF({tab:e,widgetChildren:t,renderChildren:r}){const n=WF(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 QF({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(()=>qF(l,d,u)),h=v=>{g(w=>new Set(w).add(v)),p(v)},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",GF(r.variant)),children:d.map(v=>c.jsx(Kg,{value:v.id,disabled:v.disabled,className:KF(r.variant),children:v.label},v.id))}),d.map(v=>{const w=m.has(v.id),x=y||w,E=y||w;return c.jsxs(qg,{value:v.id,forceMount:y||void 0,className:B("mt-0",y&&"data-[state=inactive]:hidden"),children:[v.contentType==="widgets"&&E&&c.jsx(JF,{tab:v,widgetChildren:e.children??[],renderChildren:t}),v.contentType==="form"&&c.jsx(YF,{tab:v,shouldRender:x,pageContext:n,clientId:o}),v.contentType==="page"&&c.jsx(XF,{tab:v,shouldLoad:x,shouldRender:E,nestingDepth:s,pageContext:n,clientId:o,onAction:i,getWorkflowState:a})]},v.id)})]})}const ZF={section:fF,columns:pF,card:mF,tab_group:QF,heading:hF,text:gF,button:vF,button_group:xF,stat_card:TF,stat_grid:PF,data_table:MF,search_filter:OF,form_embed:UF,workflow_embed:VF,page_nav:HF};function eP({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 tP({widget:e,renderChildren:t}){const r=ZF[e.type]??eP;return c.jsx(r,{widget:e,renderChildren:t})}function gy(e,t){return e.map(r=>c.jsx(tP,{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(()=>qT(e.schema),[e.schema]),l=p=>gy(p,l),f=c.jsxs("div",{className:B("studio-page-content min-h-0 min-w-0",RT(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(QT,{schema:u,context:t,clientId:String(t.clientId??""),nestingDepth:s,onAction:r,getWorkflowState:i,parentContext:d,children:f})}function rP({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:v}=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}),w=o??g?.pageId,x=u??g?.version,{data:E,isLoading:P,isError:C,error:N}=gn.useQuery({queryKey:["page-render",w,e,x],queryFn:()=>Bc(w,e,x),enabled:!!w});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:v instanceof Error?v.message:"Failed to resolve page"}):w?P?c.jsx("div",{className:"flex items-center justify-center p-12",children:c.jsx(Pn,{})}):C||!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=UT,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=rP,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=BT,ge.isIntrinsicWidthButtonField=to,ge.normalizeWorkflowFormSchema=Kk,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=YT,ge.setRendererHostAuthHeaders=gC,ge.setRendererHostViewerContext=hC,ge.useFieldValidation=jT,ge.useFormRenderer=Vd,ge.useFormValidation=$T,ge.useRendererFieldLayout=zo,ge.useRendererHostAuthStore=Rn,Object.defineProperty(ge,Symbol.toStringTag,{value:"Module"})}));
|
|
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(C=>C.stop()),u.current=null),h()},[h]);S.useEffect(()=>{if(!e){y(),p(null),g(!1);return}if(s)return;let C=!1;return p(null),g(!0),nN().then(N=>{if(C){N.getTracks().forEach(_=>_.stop());return}u.current=N,g(!1)}).catch(N=>{if(C)return;g(!1);const _=N instanceof Error?N.message:"Could not access camera";p(_)}),()=>{C=!0,u.current&&(u.current.getTracks().forEach(N=>N.stop()),u.current=null),h()}},[e,s,y,h]);const v=S.useCallback(C=>{a.current=C,C&&u.current&&e&&!f&&!m&&(C.srcObject=u.current,ch(C))},[e,f,m]);S.useLayoutEffect(()=>{if(!e||f||m||!u.current)return;let C=!1,N=0;const _=()=>{if(C)return;const I=a.current;!I||!u.current||(I.srcObject=u.current,ch(I))};_();const A=requestAnimationFrame(()=>{_(),N=requestAnimationFrame(_)});return()=>{C=!0,cancelAnimationFrame(A),cancelAnimationFrame(N),h()}},[e,f,m,h]);const w=S.useCallback(()=>{y(),p(null),g(!1),t(!1),l.current&&(l.current.value="")},[y,t]),x=S.useCallback(()=>{const C=a.current,N=d.current;if(!C||!N||!u.current||C.readyState<2)return;const _=C.videoWidth,A=C.videoHeight;if(_===0||A===0)return;N.width=_,N.height=A;const I=N.getContext("2d");I&&(I.drawImage(C,0,0),N.toBlob(T=>{if(!T)return;const W=new File([T],`camera-capture-${Date.now()}.jpg`,{type:"image/jpeg",lastModified:Date.now()}),J=n(W);if(J){i?.(J);return}i?.(void 0),r(W),w()},"image/jpeg",.92))},[r,n,w,i]),E=S.useCallback(C=>{const N=C.target.files?.[0];if(!N)return;const _=n(N);if(_){i?.(_);return}i?.(void 0),r(N),w(),l.current&&(l.current.value="")},[r,n,w,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:C=>{C||w()},children:c.jsxs(ZE,{className:"sm:max-w-md",showCloseButton:!0,onPointerDownOutside:C=>C.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:v,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:w,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"),v=e.metadata?typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata:null,w=e.validation?.find(K=>K.type==="fileSize"),x=e.validation?.find(K=>K.type==="fileType"),E=w?.value!=null?w.value:d?.maxSize??v?.maxSize??5*1024*1024,P=x?.value!=null?x.value:d?.accept??v?.accept??["image/*"],C=P.join(",")||"image/*",N=Ms(e),_=S.useCallback(K=>{if(w){const X=Yr(K,w);if(X!==!0)return typeof X=="string"?X:"File size exceeds the maximum allowed size"}else if(K.size>E)return`File size must be less than ${yo(E)}`;if(x){const X=Yr(K,x);if(X!==!0)return typeof X=="string"?X:"File type is not allowed"}return null},[w,x,E]),A=S.useMemo(()=>Ls(t),[t]),I=ql(A),T=S.useCallback(K=>{const X=ka(K,N);r(X),n?.()},[r,n,N]),W=S.useCallback(K=>{const X=_(K);if(X){l(X);return}l(void 0);const ce=[...A];ce.length>=N||(ce.push(K),T(ce),y("none"))},[A,N,_,T]),J=S.useCallback(K=>{const X=A.filter((ce,ne)=>ne!==K);T(X)},[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=[];(w||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(X=>new Set(X).add(K)),onRemove:()=>J(0),onOpenUrl:U,disabled:s}):c.jsx(Kl,{items:A,maxFiles:N,disabled:s,objectUrls:I,failedUrlKeys:m,onImageUrlError:K=>g(X=>new Set(X).add(K)),onRemove:J,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:_,accept:C,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),[v,w]=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"),C=E?.value?E.value:u?.maxSize??x?.maxSize??5*1024*1024,N=P?.value?P.value:u?.accept??x?.accept??["image/*"],_=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>C)return`File size must be less than ${yo(C)}`;if(P){const re=Yr(oe,P);if(re!==!0)return typeof re=="string"?re:"File type is not allowed"}return null},[E,P,C]),T=S.useMemo(()=>Ls(t),[t]),W=ql(T),J=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),J(be),w("none")},[T,A,I,J]),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=>{J(T.filter((re,be)=>be!==oe))},[T,J]),D=S.useCallback(()=>{s||T.length>=A||m||(p(void 0),w("file"),l.current?.click())},[s,T.length,A,m]),L=S.useCallback(()=>{s||T.length>=A||(p(void 0),w("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),J(be),w("none"))},[T,A,I,J]),$=S.useCallback(oe=>{g(oe),oe||w("none")},[]),ie=o||f,V=e.appearance?.hideLabel??!1,K=[];(E||C)&&K.push(`Max size: ${yo(C)}`),P&&N.length>0&&K.push(`Allowed: ${N.join(", ")}`),A>1&&K.push(`Up to ${A} photos`);const X=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:_,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?X: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&&X?X:null,onOpenUrl:oe=>{oe?.trim()&&ce(oe.trim())},addSlot:Pe})]})}),c.jsx(dh,{open:m,onOpenChange:$,onCaptured:U,validateFile:I,accept:_,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:v,extraSubmitPayload:w,buttonResponses:x,onButtonApiResponse:E,onValidateForm:P,getValidationErrors:C,allFields:N,onSubmittingChange:_,scopedFormValues:A,scopedFieldNameMap:I,prepopulateResponse:T=null,formSections:W,submitPayload:J})=>{const{gridStretch:O}=zo(),[j,M]=S.useState(!1),D=e.properties,L=ha.useParams(),U=S.useMemo(()=>({...h,...w}),[h,w]),$=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,X=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&&C)try{const q=C();$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),_?.(!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),_?.(!1)}return}if(l){if(!await re())return;M(!0),_?.(!0);try{await l(),E?.(e.name,{status:"success"})}finally{M(!1),_?.(!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"||!X)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,J),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}),w&&typeof w=="object"&&Object.entries(w).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"&&X)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(X,$,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??X??"",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 v?.(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 v=cs(y),w=y.label||v,x=i||!a?!0:a.visibility[v]!==!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}-${v}`,className:"text-xs font-normal truncate",children:w}),c.jsx(Nm,{id:`ui-section-${e.id}-${v}`,checked:x,disabled:i||!a||!!g,onCheckedChange:E=>{!a||i||a.setSectionVisible(v,!!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,v=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(v,"h-6 w-6"),onClick:()=>p(h+1),onMouseEnter:()=>m()},h):c.jsx(ou,{className:B(v,"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),v=b.useRef(0),x=i==="horizontal"?MN:LN,[E=[],P]=Zr({prop:l,defaultProp:u,onChange:T=>{[...y.current][v.current]?.focus(),f(T)}}),C=b.useRef(E);function N(T){const W=zN(E,T);I(T,W)}function _(T){I(T,v.current)}function A(){const T=C.current[v.current];E[v.current]!==T&&p(E)}function I(T,W,{commit:J}={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)){v.current=L.indexOf(M);const U=String(L)!==String(D);return U&&J&&p(L),U?L:D}else return D})}return c.jsx(IN,{scope:e.__scopeSlider,name:r,disabled:a,min:n,max:o,valueIndexToChangeRef:v,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||(C.current=E)}),min:n,max:o,inverted:m,onSlideStart:a?void 0:N,onSlideMove:a?void 0:_,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=v.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",v=y&&!s||!y&&s;function w(x){const E=g.current||f.getBoundingClientRect(),P=[0,E.width],N=ic(P,v?[r,n]:[n,r]);return g.current=E,N(x-E.left)}return c.jsx(Nh,{scope:e.__scopeSlider,startEdge:v?"left":"right",endEdge:v?"right":"left",direction:v?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=w(x.clientX);i?.(E)},onSlideMove:x=>{const E=w(x.clientX);a?.(E)},onSlideEnd:()=>{g.current=void 0,d?.()},onStepKeyDown:x=>{const P=Ah[v?"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(),v=[0,y.height],x=ic(v,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 v=Ah[m?"from-bottom":"from-top"].includes(h.key);d?.({event:h,direction:v?-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,w=>u(w)),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],v=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}% + ${v}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=v=>{s||i||e.disabled||e.readOnly||(r(v[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((v,w)=>c.jsx("span",{className:"text-center",children:v.label},w))})]})})},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(v=>{if(p)return;f(!0);const w=u.current;if(!w)return;const x=w.getContext("2d");if(!x)return;const E=w.getBoundingClientRect(),P="touches"in v?v.touches[0].clientX-E.left:v.clientX-E.left,C="touches"in v?v.touches[0].clientY-E.top:v.clientY-E.top;x.beginPath(),x.moveTo(P,C)},[p]),g=S.useCallback(v=>{if(!l||p)return;const w=u.current;if(!w)return;const x=w.getContext("2d");if(!x)return;const E=w.getBoundingClientRect(),P="touches"in v?v.touches[0].clientX-E.left:v.clientX-E.left,C="touches"in v?v.touches[0].clientY-E.top:v.clientY-E.top;x.lineWidth=2,x.lineCap="round",x.strokeStyle="#000",x.lineTo(P,C),x.stroke(),x.beginPath(),x.moveTo(P,C)},[l,p]),h=S.useCallback(()=>{if(!l)return;f(!1);const v=u.current;if(!v)return;const w=v.toDataURL();r(w),n?.()},[l,r,n]),y=S.useCallback(()=>{const v=u.current;if(!v||p)return;const w=v.getContext("2d");w&&(w.clearRect(0,0,v.width,v.height),r(null),n?.())},[p,r,n]);return S.useEffect(()=>{const v=u.current;if(v&&(v.width=v.offsetWidth,v.height=200,t)){const w=new Image;w.onload=()=>{const x=v.getContext("2d");x&&x.drawImage(w,0,0)},w.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,v=!u&&p?.allowDeleteRow!==!1,w=s===!1&&i===!1?!1:s||e.disabled||i||e.readOnly,x=t||[],E=y&&x.length<h,P=v&&x.length>g,C=S.useCallback(()=>{if(!E||w)return;const O={};m.forEach(j=>{O[j.name]=j.defaultValue??""}),r([...x,O]),n?.()},[x,m,E,w,r,n]),N=S.useCallback(O=>{if(!P||w)return;const j=x.filter((M,D)=>D!==O);r(j),n?.()},[x,P,w,r,n]),_=S.useCallback((O,j,M)=>{if(w)return;const D=[...x];D[O]||(D[O]={}),D[O][j]=M,r(D),n?.()},[x,w,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",J=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",w&&"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(J,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)),v&&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+(v?1:0),className:B(J,"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)},X=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:X(ie),onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,className:"w-full"});case"number":return c.jsx(Xd,{field:U,value:ie??null,onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,className:"w-full"});case"email":return c.jsx(su,{field:U,value:X(ie),onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,className:"w-full"});case"phone":case"aadhaar":return c.jsx(iu,{field:U,value:X(ie),onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,className:"w-full"});case"textarea":return c.jsx(au,{field:U,value:X(ie),onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,className:"w-full"});case"select":return c.jsx(kp,{field:U,value:typeof ie=="string"?ie:X(ie),onChange:G=>_(j,L.name,G),disabled:w,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=>_(j,L.name,ee),disabled:w,className:"w-full",formValues:D,submissionContext:f})}case"asyncsearch":return c.jsx(Xp,{field:U,value:ie,onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,className:"w-full",formValues:D,submissionContext:f});case"checkbox":return c.jsx(wm,{field:U,value:ie||!1,onChange:G=>_(j,L.name,G),disabled:w,className:"w-full"});case"radio":case"checkboxgroup":return c.jsx(Gm,{field:U,value:typeof ie=="string"?ie:X(ie),onChange:G=>_(j,L.name,G),disabled:w,className:"w-full"});case"date":case"time":case"datetime":case"daterange":return c.jsx(Km,{field:U,value:typeof ie=="string"?ie:X(ie),onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,className:"w-full"});default:return c.jsx(Da,{field:U,value:X(ie),onChange:G=>_(j,L.name,G),disabled:w,readOnly:w,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)}),v&&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||w,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:C,disabled:w,className:"w-full",children:[c.jsx(nu,{className:"h-4 w-4 mr-2"}),"Add Row"]})})]})})};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 e_(e){const t=e.replace(/[^\d.-]/g,"");if(t===""||t==="-"||t===".")return null;const r=parseFloat(t);return Number.isNaN(r)?null:r}function t_(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 r_(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(r_(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 n_(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 o_=new Set(["all_items_summary","invoice_discount","grand_total"]);function s_(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"&&!o_.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 i_(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 a_(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")=>s_(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=i_(e,n,o.key);if(s?.kind==="formula"){const i=a_(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 l_(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:n_(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 c_(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 d_(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 u_(e){const t=e?.color?.trim();return t?{color:t}:{}}function fc(e){return{className:zh(e),style:u_(e)}}function f_(e){return e?!!(e.fontSize||e.bold||e.italic||e.underline||e.color?.trim()):!1}function p_(e,t){if(!e&&!t)return;const r={...e,...t};return f_(r)?r:void 0}function m_(e,t){const r=e?.kind==="label"?p_(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 h_(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 g_=({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,_,A,I,T)=>{if(m)return;const W=T==="number"?e_(I):I===""?null:I,J=l_(u,g,N,_,A,W);r(J)},[m,g,r,u]),y=(N,_,A,I,T,W)=>{const J=l.find($=>$.key===T),O=Vh(u,N,_,T),j=pc(Uh(O,J)),M=lc(W,O,J),D=h_(u,N,_),L=D?.kind==="static"?D.row.labelStyle:D?.kind==="dynamic"?D.block.labelStyle:void 0,U=m_(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("h-8 border-0 bg-transparent text-sm shadow-none focus-visible:ring-1",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"},J):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=t_(M);return c.jsxs("div",{className:B("flex w-full items-center gap-0.5",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:"h-8 min-w-[2ch] max-w-full flex-1 border-0 bg-transparent tabular-nums shadow-none focus-visible:ring-1",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,J,{currencySymbol:f,emptyDisplay:p})})},v=u.gridTitle?.trim()??"",w=Math.max(1,e.position?.rowSpan??1),x=Math.max(1,e.position?.columnSpan??1),E=Math.max(g.rows.length,1),P=w>=3?"py-4":w>=2?"py-3":"py-2",C=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:[v?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:v}):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 _=fc(N.headerStyle);return c.jsx("th",{className:B(C,P,"text-xs uppercase tracking-wider whitespace-nowrap",pc(N.align),_.className||"font-semibold text-muted-foreground"),style:_.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(C,"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(_=>{const A=Vh(u,N.slotId,N.rowKind,_.key),I=Uh(A,_);return c.jsx("td",{className:B(C,P,"align-middle whitespace-nowrap",pc(I)),children:y(N.slotId,N.rowKind,N.rowInstanceId,N.label,_.key,N.values[_.key])},_.id)})},`${N.slotId}-${N.rowInstanceId}`))})]})})]})})};function mc(e,t,r){return d_(e,t,r)}const y_=({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(),v=f.showCurrentIndicator!==!1,[w,x]=S.useState(null),[E,P]=S.useState(!1),[C,N]=S.useState(null),_=ha.useParams(),A=S.useRef(i),I=S.useRef(a),T=S.useRef(d),W=S.useRef(_);A.current=i,I.current=a,T.current=d,W.current=_;const J=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(),X=await fetch(V,{method:K,headers:K==="POST"?{"Content-Type":"application/json"}:void 0});if(!X.ok)throw new Error(`HTTP ${X.status}`);const ce=await X.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&&J()},[p,u,J]);const O=p==="api"?w: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||C||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),$=v&&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 b_(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 v_=({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 v=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:v.length,contextListSample:v.length>0?v.slice(0,2):[]});const[w,x]=S.useState(()=>v.length>0?v:Array.isArray(t)?t:[]);S.useEffect(()=>{if(v.length>0){console.log("[SelectableList] Step 3: sync fullList from context",{fieldName:e.name,contextListLength:v.length}),x(v);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})},[v,t]);const E=S.useMemo(()=>{const T=Array.isArray(t)?t:[];return new Set(T.map(J=>So(J,p)))},[t,p]),P=w.length>0&&w.every(T=>E.has(So(T,p))),C=w.some(T=>E.has(So(T,p))),N=S.useCallback((T,W)=>{const J=So(T,p),O=Array.isArray(t)?t:[];W?E.has(J)||r([...O,T]):r(O.filter(j=>So(j,p)!==J)),n?.()},[t,p,E,r,n]),_=S.useCallback(T=>{r(T===!0?[...w]:[]),n?.()},[w,r,n]),A=w.length>0?w:Array.isArray(t)?t:[],I=s||e.disabled;return console.log("[SelectableList] Data in list",{fieldName:e.name,listLength:A.length,listSource:w.length>0?"fullList":"value",valueLength:Array.isArray(t)?t.length:0,fullListLength:w.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:C?"indeterminate":!1,onCheckedChange:_,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([...w]),n?.()},children:"Select all"}),c.jsx(Yt,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",disabled:I||!C,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 J=So(T,p),O=E.has(J),j=`${ht(e)}-${W}-${J}`;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:b_(T,f,m,g)})]},J)})})]}),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 w_=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],S_=w_.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}},{}),x_="Separator",Wh="horizontal",A_=["horizontal","vertical"],Rh=b.forwardRef((e,t)=>{const{decorative:r,orientation:n=Wh,...o}=e,s=C_(n)?n:Wh,a=r?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return c.jsx(S_.div,{"data-orientation":s,...a,...o,ref:t})});Rh.displayName=x_;function C_(e){return A_.includes(e)}var E_=Rh;function gc({className:e,orientation:t="horizontal",decorative:r=!0,...n}){return c.jsx(E_,{"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 N_=({field:e,className:t})=>c.jsx("div",{className:B("py-2",t),children:c.jsx(gc,{})}),__={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"},k_=({field:e,className:t})=>{const r=e.properties,n=r?.headingLevel??"h3",o=r?.showHorizontalLine??!0,s=__[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"})]})},T_={"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"},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?.position??"top-left",o=r?.headingLevel??"h3",s=r?.showHorizontalLine??!0,i=T_[n],a=F_[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"})]})},O_=({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 I_(e){if(Array.isArray(e))return e}function M_(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 L_(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
51
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function D_(e,t){return I_(e)||M_(e,t)||B_(e,t)||L_()}function B_(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,$_=Object.isFrozen,j_=Object.getPrototypeOf,z_=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),U_=zt(Array.prototype.lastIndexOf),Xh=zt(Array.prototype.pop),Co=zt(Array.prototype.push),V_=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),H_=zt(String.prototype.trim),W_=zt(Number.prototype.toString),R_=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=G_(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 G_(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&&($_(t)||(t[n]=s),o=s)}e[o]=!0}return e}function K_(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=D_(n,2);const o=r[0],s=r[1];Ot(e,o)&&(cr(s)?t[o]=K_(s):s&&typeof s=="object"&&s.constructor===Object?t[o]=hr(s):t[o]=s)}return t}function q_(e){switch(typeof e){case"string":return e;case"number":return W_(e);case"boolean":return R_(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=z_(e,t);if(n){if(n.get)return zt(n.get);if(typeof n.value=="function")return zt(n.value)}e=j_(e)}function r(){return null}return r}function Y_(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"]),X_=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"]),J_=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"]),Q_=Mr(/{{[\w\W]*|^[\w\W]*}}/g),Z_=Mr(/<%[\w\W]*|^[\w\W]*%>/g),ek=Mr(/\${[\w\W]*/g),tk=Mr(/^data-[\-\w.\u00B7-\uFFFF]+$/),rk=Mr(/^aria-[\-\w]+$/),sg=Mr(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),nk=Mr(/^(?:\w+script|data):/i),ok=Mr(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),sk=Mr(/^html$/i),ik=Mr(/^[a-z][.\w]*(-[.\w]+)+$/i),No={element:1,text:3,progressingInstruction:7,comment:8,document:9},ak=function(){return typeof window>"u"?null:window},lk=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]:ak();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"),v=Kn(h,"remove"),w=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 C,N="";const _=r,A=_.implementation,I=_.createNodeIterator,T=_.createDocumentFragment,W=_.getElementsByTagName,J=n.importNode;let O=ig();t.isSupported=typeof Kh=="function"&&typeof E=="function"&&A&&A.createHTMLDocument!==void 0;const j=Q_,M=Z_,D=ek,L=tk,U=rk,$=nk,ie=ok,V=ik;let K=sg,X=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,X=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=Y_(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&&(X=nt({},rg),ne=xo(null),pe.html===!0&&(nt(X,tg),nt(ne,ng)),pe.svg===!0&&(nt(X,wc),nt(ne,Ac),nt(ne,Gi)),pe.svgFilters===!0&&(nt(X,Sc),nt(ne,Ac),nt(ne,Gi)),pe.mathMl===!0&&(nt(X,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)&&(X===ce&&(X=hr(X)),nt(X,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&&(X["#text"]=!0),ve&&nt(X,["html","head","body"]),X.table&&(nt(X,["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.');C=F.TRUSTED_TYPES_POLICY,N=C.createHTML("")}else C===void 0&&(C=lk(g,o)),C!==null&&typeof N=="string"&&(N=C.createHTML(""));lr&&lr(F),Cr=F},er=nt({},[...wc,...Sc,...X_]),sr=nt({},[...xc,...J_]),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{v(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=C?C.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:X}),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))&&!X[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,w(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:H_(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(C&&typeof g=="object"&&typeof g.getAttributeType=="function"&&!Mt)switch(g.getAttributeType(ta,ir)){case"TrustedHTML":{Lt=C.createHTML(Lt);break}case"TrustedScriptURL":{Lt=C.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=q_(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(!X[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 C&&Je?C.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=J.call(n,Tt,!0)),Tt}let Mt=ve?Y.outerHTML:Y.innerHTML;return ve&&X["!doctype"]&&Y.ownerDocument&&Y.ownerDocument.doctype&&Y.ownerDocument.doctype.name&&Zt(sk,Y.ownerDocument.doctype.name)&&(Mt="<!DOCTYPE "+Y.ownerDocument.doctype.name+`>
|
|
52
|
+
`+Mt),xe&&Ao([j,M,D],$r=>{Mt=Eo(Mt,$r," ")}),C&&Je?C.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=U_(O[Ee],F);return Y===-1?void 0:V_(O[Ee],Y,1)[0]}return Xh(O[Ee])},t.removeHooks=function(Ee){O[Ee]=[]},t.removeAllHooks=function(){O=ig()},t}var ck=ag();const dk=["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"],uk=["href","target","rel","src","alt","title","class","style","colspan","rowspan"];function fk(e){return e?ck.sanitize(e,{ALLOWED_TAGS:[...dk],ALLOWED_ATTR:[...uk],ALLOW_DATA_ATTR:!1}):""}function pk(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 mk(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 hk(e){const t=qn(e);return t.textContent!==void 0?t.textContent:e.label??""}function gk(e){return qn(e).textContent===void 0||e.appearance?.hideLabel?!1:!!e.label?.trim()}function yk(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=pk(d,a,!0);return mk(u)}const bk=/\{api:[^}]+\}/,vk=/\{labelapi:[^}]+\}/;function Ec(e){return bk.test(e)}function Nc(e){return vk.test(e)}function wk(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 Sk(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 xk(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function fg(e){return e.map(t=>{if(t.type==="text")return xk(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 Ak(e){return e?fg(_c(e)):""}function Ck(e,t){return e?t==="markdown-lite"?Ak(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 Ek="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??yk(o),i=o.inlineFormat??"none";if(s==="paragraph"){const d=fk(Ck(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),Ek);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=Sk(r,o);return S.createElement(a,{className:ug(r,o)},mg(e,i))}function Nk(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 _k(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 kk=({field:e,className:t,formValues:r,urlParams:n,submissionContext:o,buttonResponses:s,prepopulateResponse:i,prepopulateLoading:a=!1})=>{const d=qn(e),u=S.useMemo(()=>Nk(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]),v=S.useCallback(async()=>{if(!u){f(void 0),h(null),m(!1);return}m(!0),h(null);try{const W=await _k(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&&v()},[y,v]);const w=d.textAlign==="center"?"items-center":d.textAlign==="right"?"items-end":d.textAlign==="justify"?"items-stretch":"items-start",x=hk(e),E=gk(e),P=E&&e.label?e.label:"",C=e.description??"",N=wk({bodyTemplate:x,captionTemplate:P,descriptionTemplate:C,prepopulateLoading:a,labelApiConfigPresent:u!=null,labelApiLoading:p,labelApiResponse:l,labelApiError:g}),_={formValues:r??{},urlParams:n??{},submissionContext:o,buttonResponses:s,prepopulateResponse:i,labelApiResponse:l},A=x?Cc(x,_):"",I=E&&e.label?Cc(e.label,_):"",T=C?Cc(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",w,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:v,buttonResponses:w,onButtonApiResponse:x,onValidateForm:E,getValidationErrors:P,allFields:C,onSubmittingChange:N,onAddMore:_,scopedFormValues:A,scopedFieldNameMap:I,excludedOptionValues:T,prepopulateMappedFieldNames:W,fieldValueKey:J,hideTableRowControls:O=!1,urlParams:j={},prepopulateResponse:M=null,prepopulateLoading:D=!1,formSections:L,submitPayload:U})=>{switch(e.type){case"divider":return c.jsx(N_,{field:e,className:d});case"header":return c.jsx(k_,{field:e,className:d});case"sectionHeading":return c.jsx(P_,{field:e,className:d});case"spacer":return c.jsx(O_,{field:e,className:d});case"textLabel":return c.jsx(kk,{field:e,className:d,formValues:u,urlParams:j,submissionContext:l,buttonResponses:w,prepopulateResponse:M??void 0,prepopulateLoading:D});case"status":return c.jsx(y_,{field:e,value:t??null,error:r,disabled:s,isRequired:a,className:d,formValues:u,submissionContext:l,extraSubmitPayload:v,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 $=J??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(v_,{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:w});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:w});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(g_,{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:w,onButtonApiResponse:x,bffSubmitApi:h,onBffSubmitResult:y,extraSubmitPayload:v,onValidateForm:E,getValidationErrors:P,allFields:C,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:w,onButtonApiResponse:x});case"addmore":return c.jsx(xN,{field:e,error:r,disabled:s,readOnly:i,isRequired:a,className:d,onAddMore:()=>_?.(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]})})}},Tk=({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 Fk(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 Pk{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=Fk(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 Ok=new Pk;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 Ik={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."},Mk=300;function Lk(){return{...Ik}}function Dk(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 Bk(e){const t=Lk();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(X=>X.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 X=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,...X&&{target:X}}]),(!K.then||!Array.isArray(K.then)||K.then.length===0)&&V.action&&(K.then=[{action:V.action,...X&&{target:X}}]),K.then&&Array.isArray(K.then)&&X&&(K.then=K.then.map(ne=>!ne.target&&X?{...ne,target:X}:ne));const ce=V.conditionExpression||JSON.stringify(K);if(y.has(ce))return;y.add(ce),h.push(K)}catch{}});const w=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:C,hidden:N,..._}=p,A={};_.hideLabel!==void 0&&(A.hideLabel=_.hideLabel),_.labelPosition!==void 0&&(A.labelPlacement=_.labelPosition),_.size!==void 0&&(A.size=_.size),_.customClass!==void 0&&(A.className=_.customClass);const{labelPosition:I,size:T,customClass:W,visibility:J,...O}=_,j=Object.keys(O).length>0?O:void 0,M=Object.keys(A).length>0?A:void 0,D=l.visibility??p?.visibility??J;let L=Dk(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:w,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=Bk(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 $k=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,$k)}function jk(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 zk(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 Uk(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 Vk(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 Hk(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 Wk(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 Rk(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 Gk(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 Kk(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=Rk(r,n),l=Gk(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 qk(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(Wk(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))||Yk(r))}function Yk(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(qk(o))return o;const i=Kk(o,s);return i!==o&&(r=!0),i});return r?{...e,fields:n}:e}function Xk(e){return Yi(e)}const Jk=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"&&Jk.has(r.trim().toUpperCase()))}function Qk(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 Zk(e,t){const r=Qk(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 eT(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 tT(e){return eT(e).some(t=>t.toLowerCase().includes("payment"))}function rT(e){const t=e.properties,r=e.metadata;return!!(t?.mergeSuccessDataIdAsPaymentId||r?.mergeSuccessDataIdAsPaymentId)}function nT(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(rT(t)||n!=null&&typeof n=="object"&&!Array.isArray(n)&&Pc(n)||tT(t))return r}const oT=new Set(["section","group","columns","divider","header","sectionHeading","spacer","addmore","textLabel","customizeSections"]);function sT(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 iT(e,t){const r=e.properties,n=Array.isArray(r?.linkedFieldNames)?r.linkedFieldNames:[],o=sT(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 aT(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=iT(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||oT.has(i.type)?!1:s.has(a)})}function lT(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 cT(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 dT(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}=dT(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 uT(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 fT(e,t){return e.maxRow+1+t*e.blockHeight}function pT(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(w=>o.get(w)).filter(w=>!!w);if(d.length===0)continue;const u=d.filter(w=>!Ng(w,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 v=!1;for(let w=f;w<=f+m-1;w++){for(let x=p;x<=p+g-1;x++){const E=`${w}-${x}`;if(i.has(E)){v=!0;break}y.add(E)}if(v)break}if(!v){for(const w of y)i.add(w);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 mT(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:v,rowSpan:w,colSpan:x}=h,E=`${y}-${v}`;for(let N=y;N<=y+w-1;N++)for(let _=v;_<=v+x-1;_++)a.add(`${N}-${_}`);const P=l,C=bs(f,m+1);d.set(E,{anchorRow:y,anchorCol:v,rowSpan:w,colSpan:x,run:P,legend:C,renderFields:Oc(g),addMoreMeta:{addMoreFieldName:u.addMoreFieldName,blockId:p,blockIndex:m}})})}return{anchorsByOrigin:d,coveredCells:a}}function hT(e,t,r,n){const o=`${e}-${t}`;return r.has(o)?!n.get(o):!1}function gT(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 yT(e,t,r,n){return!(!n||r.run.section.collapsible!==!0||e===r.anchorRow&&t===r.anchorCol)}function bT(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 vT(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 wT(e,t){return new Map([...e,...t])}function ST(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 xT=2*6e4,kg=50;class AT{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 CT(e){return(e??"").trim()||"default"}function Tg(e){const t=CT(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 AT(xT);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:v,getViewerContext:w,hideTableRowControls:x=!1,themeVars:E,dark:P=!1,omitRootWrapper:C=!1})=>{const N=Rn(k=>k.viewerContext),_=S.useMemo(()=>{if(v!==void 0)return v;const k=w?.();return k!==void 0?k:N},[v,w,N]),[A,I]=S.useState(e||null),[T,W]=S.useState(!!t&&!e),[J,O]=S.useState(null),j=e?.BFF_submit_api??J,[M,D]=S.useState(!1),[L,U]=S.useState({}),[$,ie]=S.useState({}),[V,K]=S.useState({}),[X,ce]=S.useState({}),[ne,G]=S.useState({}),[ee,Pe]=S.useState(null),oe=ha.useParams(),re=Nt(k=>k.setValues),be=Nt(k=>k.setSubmitting),de=Nt(k=>k.formDisabled),ot=Nt(k=>k.visibleFields),Se=Nt(k=>k.requiredFields),xe=Nt(k=>k.updateVisibility),ae=Nt(k=>k.updateRequired),ve=Nt(k=>k.setFieldError),Ye=S.useRef(!1),ct=S.useRef(void 0),Ge=S.useMemo(()=>{if(!e)return null;const k=e;if(k.form&&Array.isArray(k.form.fields))try{return ms(k.form,k.form.fields,k.form.layout||null,k.form.rules||[])}catch{return e}if(Array.isArray(k.fields)&&k.fields.some(z=>typeof z.metadata=="string"&&z.metadata.startsWith("{")||z.fieldType&&!z.type))try{const z={id:k.id||k._id||"temp",name:k.name||"Form",version:k.version??1,status:k.status||"draft",createdAt:k.createdAt||new Date().toISOString(),updatedAt:k.updatedAt||new Date().toISOString(),createdBy:k.createdBy||"system",category:k.category||"",moduleId:k.moduleId,tenantId:k.tenantId,featureId:k.featureId,isDefault:k.isDefault||!1};return ms(z,k.fields,k.layout||null,k.rules||[])}catch{return e}return e},[e]);S.useEffect(()=>{if(e){const k=e;k.BFF_submit_api&&O(k.BFF_submit_api)}},[e]);const Kt=S.useMemo(()=>{const k=Ge||A,H=k?Yi(k):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 k=(Tn()??"").trim()||"default",H=Pg({scope:k,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:k})=>{if(!t)return;const H=t;k||W(!0);try{const z=await Ok.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{k||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 k=>{const H=q?.fields?.length?tc(k,q.fields):k,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(k=>k.readOnlyFields),Cr=Nt(k=>k.editableFields),Jn=S.useCallback(k=>Ct.has(k),[Ct]),It=S.useCallback(k=>Cr.has(k),[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 k=q.config?.prepopulateApi,H=!!(k?.fieldMapping&&Object.keys(k?.fieldMapping??{}).length>0),z=(q.config?.prepopulateResponseRules?.length??0)>0;if(!k?.enabled||!k.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(k.apiEndpoint));if(k.apiQueryParams?.length){const se=new URLSearchParams;k.apiQueryParams.forEach(({key:Ie,value:me})=>se.append(Ie,Ne(me))),De=`${De}${De.includes("?")?"&":"?"}${se.toString()}`}const at={};k.apiHeaders?.forEach(({key:se,value:Ie})=>{se.trim()&&(at[se]=Ne(Ie))}),at["Content-Type"]=at["Content-Type"]??"application/json";let Ht;if(k.apiMethod==="POST"&&k.apiBodyFields?.length){const se={};k.apiBodyFields.forEach(({key:Ie,value:me})=>{Ie.trim()&&(se[Ie]=Ne(me))}),Ht=JSON.stringify(se)}const Le=await fetch(De,{method:k.apiMethod,headers:at,body:k.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(k?.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]=c_(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=k.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=k.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),dP=ut&&ut[ma]||ma,Kc=Ft[dP];if(Kc==null)continue;const uP=`${ma}__addmore__${se}__${ue[bt]}`;lt[uP]=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=Zk(Ve,{treatFirstItemIdAsPaymentId:k?.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((k,H)=>er||!!H&&!It(k)||Jn(k)&&!It(k),[er,It,Jn]),fn=q.fields.filter(k=>!k.parentId),kt=[...Er?ft:fn.length>0?fn:q.fields].filter(k=>!(!k||typeof k!="object"||!k.name&&!k.key)).sort((k,H)=>{const z=typeof k.position?.order=="number"?k.position.order:typeof k.positionOrder=="number"?k.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 k.position?.column=="number"?k.position.column:1,le=typeof H.position?.column=="number"?H.position.column:1;return Q-le}),Ss=S.useCallback(k=>{const H=Nt.getState().errors,z=Object.keys(H).find(Z=>k.includes(Z));z&&requestAnimationFrame(()=>{document.querySelector(`[data-field-name="${z}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})})},[]),Nr=async k=>{if(k?.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(k);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((k,H)=>{const z=q.fields.find(Q=>Q.type==="button"&&(Q.name===k||Q.key===k)),Z=nT(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,[k]: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(C)return;const k=q.config?.theme?.cssVariables;if(!(!k&&!E))return{...k??{},...E??{}}},[C,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(k=>{if(!_)return!0;const H=k.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&&_.userId!=null&&le.includes(_.userId))return!1;if(Q.length>0&&_.userId!=null&&Q.includes(_.userId))return!0;const Ce=z!=null&&z!==""&&_.userType!=null&&_.userType!==z,Ne=Z!=null&&Z!==""&&_.role!=null&&_.role!==Z,De=Q.length>0&&(_.userId==null||!Q.includes(_.userId));return!(Ce||Ne||De)},[_]),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((k,H)=>{Oo(z=>z[k]===H?z:{...z,[k]:H})},[]),ta=S.useMemo(()=>({visibility:ir,setSectionVisible:Lt,fieldToHeading:Mt,allFields:q.fields}),[ir,Lt,Mt,q.fields]),et=S.useCallback(k=>k.name||k.key||k.id,[]),Tr=k=>{if(!wt(k))return!1;const H=k.name||k.key||k.id;if(!wh(H,k.type,ir,Mt))return!1;const z=k.hidden===!0;return Ar(H)||!z&&H},yy=S.useCallback(k=>{const H=q.fields.find(Z=>et(Z)===k);if(H)return H.type;const z=vh(k);return q.fields.find(Z=>et(Z)===z)?.type},[q.fields,et]),ra=S.useCallback(k=>wh(k,yy(k),ir,Mt),[ir,Mt,yy]),pn=S.useCallback(k=>ra(k)?Po(k):!1,[ra,Po]);S.useEffect(()=>{const{visibleFields:k,requiredFields:H,errors:z}=Nt.getState(),Z=new Set(k),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(k=>{let H=k;if(k.type==="table"){const Z=k.properties?.columns;if(Array.isArray(Z)&&Z.length>0){const Q=Z.filter(le=>wt(le));H={...k,properties:{...k.properties,columns:Q}}}}const z=lT(H,Dt,et);return z?{...H,label:Cg(z,0)}:H},[wt,Dt,et]),mn=S.useCallback(k=>Eg(k,q.fields,Dt,et),[q.fields,Dt,et]),Gr=S.useCallback((k,H,z)=>`${k}__addmore__${H}__${z}`,[]),na=S.useCallback((k,H)=>`${k}__${H??"base"}`,[]),oa=S.useCallback((k,H)=>{const z=na(k.id,H);return X[z]??k.defaultCollapsed??!1},[X,na]),Wc=S.useCallback((k,H,z)=>{const Z=na(k,H);ce(Q=>Q[Z]===z?Q:{...Q,[Z]:z})},[na]),sa=S.useMemo(()=>{const k=[],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()!==""&&k.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()!==""&&k.push(String(we))}}return k},[q.fields,V,$,ne,L.documentId,et,mn,Gr]);S.useEffect(()=>{U(k=>{const H={...k,document_ids:sa},z=k.document_ids;return Array.isArray(z)&&z.length===sa.length&&sa.every((Z,Q)=>z[Q]===Z)?k:H})},[sa]);const ia=S.useCallback((k,H,z,Z)=>{for(const Q of z){const le=et(Q),Ce=Gr(le,k,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(k=>{const H=et(k);if(!H)return;if(mn(k).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((k,H)=>{K(z=>{const Z=z[k]||[],Q=Z.filter(le=>le!==H);if(Q.length===Z.length)return z;if(Q.length===0){const le={...z};return delete le[k],le}return{...z,[k]:Q}})},[]),la=S.useMemo(()=>kt.filter(k=>!k.parentId),[kt]),On=S.useMemo(()=>{const k=[];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=uT(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;k.push({addMoreFieldName:Z,baseOrder:Q,blockHeight:Ve,blockIds:le,linkedFields:Ce,insertedRows:we,templateFieldNames:De,templateBounds:at})}),k},[kt,la,Y,et,V,mn,Dt]),As=S.useMemo(()=>({}),[]),ca=S.useMemo(()=>On.length===0?kt:kt.map(k=>{const H=k.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?k:{...k,position:{...k.position,order:H+z}}}),[kt,On]),da=S.useCallback(k=>{const H={};return Object.entries($).forEach(([z,Z])=>{const Q=k[z];Q&&(H[Q]=Z)}),H},[$]),Io=S.useMemo(()=>{const k=[],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?fT(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)])}k.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:k,scopeByFieldName:H}},[On,ne,et,Gr,Oe,da,q.fields]),Cs=S.useMemo(()=>[...ca,...Io.clonedFields].sort((k,H)=>{const z=k.position?.order??0,Z=H.position?.order??0;if(z!==Z)return z-Z;const Q=k.position?.column??1,le=H.position?.column??1;if(Q!==le)return Q-le;const Ce=ko(k.position)??0,Ne=ko(H.position)??0;return Ce!==Ne?Ce-Ne:String(k.id).localeCompare(String(H.id))}),[ca,Io.clonedFields]),Mo=S.useMemo(()=>jk(Cs.filter(k=>!k.parentId),Tr),[Cs,Tr]),Rc=S.useCallback((k,H)=>Mo.some(z=>zk(k,H,z,Y)),[Mo,Y]);Mo.length===0||Math.max(...Mo.map(k=>(k[0]?.position?.order??0)+gs(k,Y).rowSpan));const ua=S.useMemo(()=>cT(Dt,Oc(kt.filter(k=>!k.parentId)),et),[Dt,kt,et]),{anchorsByOrigin:by,coveredCells:vy}=S.useMemo(()=>pT(ua,ca,et,Y),[ua,ca,et,Y]),{anchorsByOrigin:wy,coveredCells:Sy}=S.useMemo(()=>mT(On.map(k=>({addMoreFieldName:k.addMoreFieldName,blockIds:k.blockIds,linkedFields:k.linkedFields,templateFieldNames:k.templateFieldNames})),Dt,Io.clonedFields,la,Y,et,vy),[On,Dt,Io.clonedFields,la,Y,et,vy]),hn=S.useMemo(()=>wT(by,wy),[by,wy]),xy=S.useMemo(()=>Sy,[Sy]),Ay=String(Tt).endsWith("px")?Tt:In,Cy=S.useCallback((k,H)=>{for(let z=0;z<Y;z++){if(z>=H.anchorCol&&z<H.anchorCol+H.colSpan)continue;if(As[`${k}-${z}`]||hn.get(`${k}-${z}`)||vg(k,z,Cs,Tr).length>0||Rc(k,z))return!0}return!1},[Y,As,hn,Cs,Tr,Rc]),Ey=S.useMemo(()=>bT(hn,k=>{const H=k.run.section;return H.collapsible?oa(H,k.addMoreMeta?.blockId):!1},Cy),[hn,oa,Cy]),Ny=S.useMemo(()=>{const k=[];for(const H of Object.keys(As)){const z=Number(H.split("-")[0]);Number.isNaN(z)||k.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++)k.push(z);return Uk(Mo,Y,k)},[Mo,Y,As,hn,Tr]),{originalToDisplayRow:fa,displayRowCount:iP,sortedOccupiedRows:aP}=S.useMemo(()=>{const k=Vk(Ny);return{originalToDisplayRow:k.originalToDisplay,displayRowCount:k.displayRowCount,sortedOccupiedRows:k.sortedOriginalRows}},[Ny]),_y=Math.max(iP,1),Gc=S.useCallback((k,H=1)=>Hk(k,H,fa),[fa]),ky=S.useMemo(()=>{const k=new Set;for(const H of Ey){const z=fa.get(H);z!==void 0&&k.add(z)}return k},[Ey,fa]),lP=S.useMemo(()=>vT(_y,Ay,ky),[_y,Ay,ky]),cP=S.useMemo(()=>ST(kt.filter(k=>!k.parentId&&Tr(k)),ua,et),[kt,ua,et,Tr]),pa=S.useCallback(k=>{if(F)return null;const H=et(k),z=V[H]||[];if(z.length===0)return null;const Z=mn(k);if(Z.length===0)return null;const Q=aT(k,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=k.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},`${k.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:C?B("relative",d):B(ga,P&&"dark",d),style:xs,"data-form-renderer":C?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(Tk,{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:lP,gridTemplateColumns:`repeat(${Y}, 1fr)`,rowGap:he,columnGap:st},"data-form-renderer":"grid",children:aP.map(k=>Array.from({length:Y},(H,z)=>{const Z=Gc(k);if(!Z)return null;if(Rc(k,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-${k}-${z}`);if(hT(k,z,xy,hn)){const we=gT(k,z,hn);return we&&yT(k,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-${k}-${z}`)}const Q=hn.get(`${k}-${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}-${k}-${z}-${Ae?.blockId??"base"}`)}const le=vg(k,z,Cs,Tr).filter(we=>!(et(we)?.includes("__addmore__")&&xy.has(`${k}-${z}`)));if(le.length===0){const we=As[`${k}-${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-${k}-${z}`)}return c.jsx("div",{className:"min-w-0",style:{pointerEvents:"none"},"data-form-renderer":"grid-cell","data-form-renderer-empty":!0},`empty-${k}-${z}`)}const Ce=le[0],{rowSpan:Ne,columnSpan:De}=gs(le,Y),at=Gc(k,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(k=>{if(!Tr(k))return null;const H=cP.find(Z=>Z.kind==="border"&&Z.fields.some(Q=>Q.id===k.id));if(H)return H.fields[0]?.id!==k.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}-${k.id}`);if(!k.parentId){const Z=kt.filter(le=>!le.parentId&&Tr(le)&&qi(le)===qi(k)),Q=Tc(Z).slice(0,2);if(Q.length>1&&Q[0].id!==k.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(k.type==="section"){const Z=q.fields.filter(Q=>Q.parentId===k.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:k,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})},k.id)}const z=k.name||k.key||k.id;return c.jsxs("div",{"data-field-name":z,"data-form-renderer":"field-wrapper",style:xn(k),children:[c.jsx(un,{field:Qn(k),value:Oe[z],error:pe[z]||je>0?te[z]:void 0,onChange:Z=>xt(z,Z),onBlur:()=>ze(z),disabled:(k.type==="table"||k.type==="billingGrid")&&a==="fill"?!1:de||!Vt(z)||er||!!k.disabled,readOnly:(k.type==="table"||k.type==="billingGrid")&&a==="fill"?!1:sr(z,!!k.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}),k.type==="addmore"&&pa(k)]},k.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 ET(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 J=W.startsWith(".")?W:`.${W}`;T.push(J),J===".csv"?T.push("text/csv"):J===".xls"?T.push("application/vnd.ms-excel"):J===".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 J=t[W];return J!==void 0?String(J):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,v=Mg(y.position),w=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 v.column=="number"?v.column:typeof y.positionColumn=="number"?y.positionColumn:1,columnSpan:typeof v.columnSpan=="number"?v.columnSpan:typeof v.width=="number"?v.width:typeof y.positionWidth=="number"?y.positionWidth:1,rowSpan:typeof v.rowSpan=="number"?v.rowSpan:typeof y.positionRowSpan=="number"?y.positionRowSpan:1},C=ko(v,{cellSlotIndex:y.cellSlotIndex??x.cellSlotIndex,stackSlot:w.stackSlot??x.stackSlot});typeof C=="number"&&(P.cellSlot=C);const N=v.cellGroupId??x.cellGroupId;typeof N=="string"&&(P.cellGroupId=N);const _=hs(v)??hs(x)??(w.stackDirection==="horizontal"||x.stackDirection==="horizontal"?"row":w.stackDirection==="vertical"||x.stackDirection==="vertical"?"stack":void 0);return(_==="row"||_==="stack")&&(P.sharedCellLayout=_),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",[NT]=vr(Xi,[Li]),Lg=Li(),[_T,Dc]=NT(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(_T,{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 kT=Dg,TT=$g,FT=zg,PT=Vg;function Rg({className:e,...t}){return c.jsx(kT,{"data-slot":"tabs",className:B("flex flex-col gap-2",e),...t})}function Gg({className:e,...t}){return c.jsx(TT,{"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(FT,{"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(PT,{"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 OT({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 IT(){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 MT=3e4,LT=10*6e4,DT=9e4,BT=15*6e4;function $T(e){return e!=null&&"on_success"in e&&e.on_success!=null}function jT(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 v=gn.useQueryClient(),w=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([]),[C,N]=S.useState(null),[_,A]=S.useState(null),[I,T]=S.useState(null),[W,J]=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??"",w[0],w[1],w[2]],queryFn:()=>e({...x,featureId:a}),staleTime:MT,gcTime:LT}),$=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(!C)return;const ae=E.find(Ye=>Ye.step_id===C),ve=O.current===C;return ae?.feature_id??(ve?D.current:void 0)??void 0},[C,E]),K=gn.useQuery({queryKey:["workflow-step",t,V??"",r??"",w[0],w[1],w[2]],queryFn:()=>e({...x,featureId:V}),enabled:!!V,staleTime:DT,gcTime:BT,refetchOnWindowFocus:!0,refetchOnReconnect:!0}),X=K.isPending,ce=K.error?K.error instanceof Error?K.error.message:"Failed to load form":null;S.useEffect(()=>{!K.data||O.current===C||(A(K.data),T(null),O.current=null,D.current=null)},[K.data,C]),S.useEffect(()=>{T(ce)},[ce]),S.useEffect(()=>{V===void 0&&O.current!==C&&(A(null),T(null),O.current=null,D.current=null)},[V,C]);const ne=S.useMemo(()=>{const ae=_?.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:ET(_,n)},[_,n,r]),G=S.useMemo(()=>{const ae=_?.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}},[_?.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(()=>{v.invalidateQueries({queryKey:["workflow-steps",t]}),v.invalidateQueries({queryKey:["workflow-step",t]})},[v,t]),be=S.useCallback(ae=>{if($T(ae)){const Ge=ae.on_success,Kt=Ge?.action;if(Kt==="redirect"&&Ge?.redirect_url){const Je=jT(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;v.removeQueries({queryKey:["workflow-step",t,$e,r??"",w[0],w[1],w[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)},[v,t,r,i,p,E,n,w,re]),de=S.useCallback(async ae=>_?.BFF_submit_api?(i?.(),{success:!0,message:"Saved successfully"}):{success:!1,message:"Submit not configured"},[_?.BFF_submit_api,i]),ot=S.useCallback((ae,ve)=>{},[]),Se=S.useCallback(ae=>{},[]);if($)return c.jsx(OT,{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=_?.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:C??"",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!==C?null:X?c.jsx(IT,{}):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&&!_?.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!==C||M.current!==(ee?.id??null);if(C&&ee&&ve){j.current=C,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:C??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&&J(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 zT(e){return typeof e=="object"&&e!==null&&"apiEndpoint"in e}function UT({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 v=e.fields.find(w=>w.id===h);return v?.parentId?g(v.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 VT({field:e,value:t,allValues:r,validateOnChange:n=!1,validateOnBlur:o=!0,debounceMs:s=Mk}){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 v;for(const w of e.validation){const x=Yr(t,w,r);if(typeof x=="string"){v=x;break}}return a(v),u(!1),v},[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(v=>{a(v)},[]);return{error:i,isValidating:d,validate:p,handleBlur:g,clearError:h,setCustomError:y}}const Xg="—";function Xt(){return{kind:"static",value:Xg}}function HT(){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 WT={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:HT()}},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 RT(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 GT(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 KT(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 qT(e){const t=Qg(e.container,e.layout);return B(KT(e.layout),GT(t.maxWidth,e.layout),RT(t.padding),t.showBorder&&"rounded-lg border border-border")}const Ji=1;function YT(){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 XT(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 JT(e){const t=e;return!t||typeof t!="object"?YT():(t.version!==Ji&&(t.version=Ji),XT(t))}const ey={};let ty=null;function QT(e){ty=e}function ZT(){return(ey?.VITE_API_BASE_URL?.trim()||ey?.VITE_API_URL?.trim()||"").replace(/\/$/,"")}const vs=_t.create({baseURL:ZT()});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 eF(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 tF({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=S.useRef(null),g=String(r??t.clientId??i?.clientId??""),h=JSON.stringify(t);S.useEffect(()=>{if(i)return;const C=e.prepopulateApi;if(!C?.enabled||!C.api?.path||!g){p({}),m.current=null;return}const N=JSON.stringify({path:C.api.path,method:C.api.method,mapping:C.contextMapping,bindings:e.dataBindings,context:h});if(m.current===N)return;let _=!1;return m.current=N,(async()=>{try{const A=oy(e.dataBindings??[],t),I={...t,...A},T=await $c({clientId:g,api:C.api,context:I});if(_)return;const W=eF(T,C.contextMapping);p({...W,prepopulateResponse:T})}catch{_||p({})}})(),()=>{_=!0}},[i,e.prepopulateApi,e.dataBindings,h,g]);const y=S.useMemo(()=>{if(i)return{...i.context,...t};const C=oy(e.dataBindings??[],t);return{...t,...C,...f}},[i,t,e.dataBindings,f]),v=String(r??y.clientId??i?.clientId??""),w=S.useCallback((C,N,_)=>{u(A=>({...A,[C]:{...A[C]??{},[N]:_}}))},[]),x=S.useCallback(C=>l.current[C]??{},[]),E=S.useCallback((C,N,_,A)=>{(o??i?.onAction)?.({...C,sourceWidgetId:N,event:_,payload:A})},[o,i?.onAction]),P=S.useMemo(()=>({schema:e,context:y,clientId:v,nestingDepth:n,onAction:o??i?.onAction,getWorkflowState:s??i?.getWorkflowState,filterGroups:d,setFilterValue:w,getFilterGroup:x,dispatchAction:E}),[e,y,v,n,o,i?.onAction,s,i?.getWorkflowState,d,w,x,E]);return c.jsx(ny.Provider,{value:P,children:a})}function Lr(){const e=S.useContext(ny);if(!e)throw new Error("usePageContext must be used within PageContextProvider");return e}const rF=5,sy=1;function Fo(e){return Number.isFinite(e)?Math.min(rF,Math.max(sy,Math.round(e))):sy}function nF(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 oF(e){return Number.isFinite(e)?Math.min(100,Math.max(0,Math.round(e))):0}function sF(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 sF(100,Fo(e))}function iF(e){const t=e.trim(),r=/^(\d+(?:\.\d+)?)\s*%?$/.exec(t);return r?oF(Number(r[1])):null}function ay(e,t){const r=Fo(t),n=[];for(let s=0;s<r;s++){const i=iF(e?.[s]??"");if(i===null)return iy(r);n.push(i)}return n.reduce((s,i)=>s+i,0)!==100?iy(r):n}function aF(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 lF(e){return e.length?e.map(t=>`minmax(0, ${t}fr)`).join(" "):"minmax(0, 1fr)"}function cF(e,t,r,n){const o=Fo(t),s=nF(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:lF(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 dF(e){return B(jc(e.showBorder,e.borderStyle??"solid"),e.showBorder&&"p-3")}function uF(e){return B(jc(e.showBorder,e.borderStyle??"solid"),e.showBorder&&"p-2")}function fF(e,t){return e.columnBorders?.[t]!==void 0?!!e.columnBorders[t]:!!e.showColumnBorders}function pF(e,t){const r=fF(e,t);return B(jc(r,e.borderStyle??"dashed"),r&&"p-2")}function mF(e){if(e)return{minHeight:`${e}vh`}}function hF({widget:e,renderChildren:t}){const r=e.config,[n,o]=S.useState(r.defaultCollapsed??!1);return c.jsxs("section",{className:B("space-y-4",dF(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 gF({widget:e,renderChildren:t}){const r=e.config,n=Fo(r.columns??2),o=r.collapseEmptyColumns!==!1,s=cF(e.children??[],n,r.columnWidths,{collapseEmpty:o});return c.jsx("div",{className:B("grid w-full min-w-0 items-stretch",aF(r.gap),uF(r)),style:{gridTemplateColumns:s.gridTemplate,...mF(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",pF(r,d)),children:t?.(i)},d)})})}function yF({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 bF({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 vF({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 wF(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]=wF(o,t));return r}function SF(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=SF(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 xF({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 AF={start:"justify-start",center:"justify-center",end:"justify-end","space-between":"justify-between"},CF={sm:"gap-2",md:"gap-3",lg:"gap-4"};function EF({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",AF[t.align??"start"],CF[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 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}=Lr(),l=S.useMemo(()=>t.filterGroupKey?u(t.filterGroupKey):{},[t.filterGroupKey,u]),f=S.useMemo(()=>["page-ds",e,t,a,l,n,o,s],[e,t,a,l,n,o,s]);return gn.useQuery({queryKey:f,enabled:r&&(!!d||t.mode==="static"),staleTime:fy(t,i.dataApis??{})?.staleTimeMs??3e4,queryFn:async()=>{if(t.mode==="static")return t.staticData;if(t.mode==="context")return Qe(a,t.contextPath??"");const p=fy(t,i.dataApis??{});if(!p)throw new Error(`No API config for data source on widget ${e}`);const m={...a};if(t.requestBindings)for(const y of t.requestBindings){let v;y.source==="binding"?v=a[y.key]:y.source==="filter"&&(v=l[y.key]),v!==void 0&&(m[y.param]=v)}const h={...dy(m,a),...n!==void 0?{page:n,pageSize:o,search:s}:{}};return $c({clientId:d,api:p,context:h,filterState:l})}})}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 NF(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 _F={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"},kF={rectangle:"rounded-lg",square:"aspect-square rounded-lg",circle:"aspect-square rounded-full"},TF={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"},FF={sm:"gap-2",md:"gap-3",lg:"gap-4"};function PF({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(_F[n??"default"],kF[o??"rectangle"],TF[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(PF,{title:e.title,value:i,trend:a,variant:e.variant,shape:e.shape,size:e.size,layout:e.layout,isLoading:n,isError:o})}function OF({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 IF({stat:e,widgetId:t}){return c.jsx(my,{stat:e,widgetId:`${t}-${e.id}`})}function MF({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",FF[t.gap??"md"]),children:r.map(s=>c.jsx(IF,{stat:s,widgetId:e.id},s.id))})}function LF({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 DF(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 BF({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=DF(d,f??"data.items"),m=(g,h)=>{const y=t.dataSource.responseMapping.find(v=>v.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 $F=75;function jF(e){return e??$F}function Vc({scrollBehavior:e="page",maxHeightPercent:t,children:r,className:n}){if(e!=="contained")return c.jsx(c.Fragment,{children:r});const o=jF(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 zF(e,t,r){return["embedded-form",e,t,r??"latest"]}async function UF(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 VF(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 UF(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 HF=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:zF(e,o,s),queryFn:()=>VF(e,o,s),staleTime:HF}),p=S.useMemo(()=>NF(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 WF({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 RF({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 GF({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 KF(e,t){return e?.length?e.filter(r=>r.config.tabId===t):[]}const qF=1;function YF(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 XF(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 JF(e,t,r){return e?new Set(r?[r]:[]):new Set(t.map(n=>n.id))}function QF({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 ZF({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>=qF?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 eP({tab:e,widgetChildren:t,renderChildren:r}){const n=KF(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 tP({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(()=>JF(l,d,u)),h=v=>{g(w=>new Set(w).add(v)),p(v)},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",YF(r.variant)),children:d.map(v=>c.jsx(Kg,{value:v.id,disabled:v.disabled,className:XF(r.variant),children:v.label},v.id))}),d.map(v=>{const w=m.has(v.id),x=y||w,E=y||w;return c.jsxs(qg,{value:v.id,forceMount:y||void 0,className:B("mt-0",y&&"data-[state=inactive]:hidden"),children:[v.contentType==="widgets"&&E&&c.jsx(eP,{tab:v,widgetChildren:e.children??[],renderChildren:t}),v.contentType==="form"&&c.jsx(QF,{tab:v,shouldRender:x,pageContext:n,clientId:o}),v.contentType==="page"&&c.jsx(ZF,{tab:v,shouldLoad:x,shouldRender:E,nestingDepth:s,pageContext:n,clientId:o,onAction:i,getWorkflowState:a})]},v.id)})]})}const rP={section:hF,columns:gF,card:yF,tab_group:tP,heading:bF,text:vF,button:xF,button_group:EF,stat_card:OF,stat_grid:MF,data_table:BF,search_filter:LF,form_embed:WF,workflow_embed:RF,page_nav:GF};function nP({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 oP({widget:e,renderChildren:t}){const r=rP[e.type]??nP;return c.jsx(r,{widget:e,renderChildren:t})}function gy(e,t){return e.map(r=>c.jsx(oP,{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(()=>JT(e.schema),[e.schema]),l=p=>gy(p,l),f=c.jsxs("div",{className:B("studio-page-content min-h-0 min-w-0",qT(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(tF,{schema:u,context:t,clientId:String(t.clientId??""),nestingDepth:s,onAction:r,getWorkflowState:i,parentContext:d,children:f})}function sP({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:v}=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}),w=o??g?.pageId,x=u??g?.version,{data:E,isLoading:P,isError:C,error:N}=gn.useQuery({queryKey:["page-render",w,e,x],queryFn:()=>Bc(w,e,x),enabled:!!w});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:v instanceof Error?v.message:"Failed to resolve page"}):w?P?c.jsx("div",{className:"flex items-center justify-center p-12",children:c.jsx(Pn,{})}):C||!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=WT,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=sP,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=zT,ge.isIntrinsicWidthButtonField=to,ge.normalizeWorkflowFormSchema=Xk,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=QT,ge.setRendererHostAuthHeaders=gC,ge.setRendererHostViewerContext=hC,ge.useFieldValidation=VT,ge.useFormRenderer=Vd,ge.useFormValidation=UT,ge.useRendererFieldLayout=zo,ge.useRendererHostAuthStore=Rn,Object.defineProperty(ge,Symbol.toStringTag,{value:"Module"})}));
|