teodor-new-chat-ui 4.3.6 → 4.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/context/reducers/MessageReducer.d.ts +3 -9
- package/dist/index.esm.js +7 -10
- package/dist/index.umd.js +2 -2
- package/dist/lib/historyUtils.d.ts +4 -15
- package/dist/types/api.d.ts +15 -18
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ChatMessage, StreamEvent } from "@/types/api";
|
|
1
|
+
import type { ChatMessage, StreamEvent, PendingInterrupt } from "@/types/api";
|
|
2
2
|
export type ReducerStreamEvent = Exclude<StreamEvent, {
|
|
3
3
|
type: "thread_info";
|
|
4
4
|
} | {
|
|
@@ -14,10 +14,7 @@ export interface MessagesState {
|
|
|
14
14
|
lastBranch: Extract<StreamEvent, {
|
|
15
15
|
type: "branch";
|
|
16
16
|
}> | null;
|
|
17
|
-
pendingInterrupt:
|
|
18
|
-
id: string;
|
|
19
|
-
value: any;
|
|
20
|
-
} | null;
|
|
17
|
+
pendingInterrupt: PendingInterrupt;
|
|
21
18
|
messagesStreamMeta?: Record<string, {
|
|
22
19
|
lastSeq?: number | null;
|
|
23
20
|
lastText?: string;
|
|
@@ -34,10 +31,7 @@ export type MessagesAction = {
|
|
|
34
31
|
messages: ChatMessage[];
|
|
35
32
|
checkpointId?: string | null;
|
|
36
33
|
checkpointNs?: string | null;
|
|
37
|
-
pendingInterrupt?:
|
|
38
|
-
id: string;
|
|
39
|
-
value: any;
|
|
40
|
-
} | null;
|
|
34
|
+
pendingInterrupt?: PendingInterrupt;
|
|
41
35
|
};
|
|
42
36
|
} | {
|
|
43
37
|
type: "prepend";
|
package/dist/index.esm.js
CHANGED
|
@@ -4332,7 +4332,7 @@ function wv({
|
|
|
4332
4332
|
hasMore: S.hasMore,
|
|
4333
4333
|
nextCursor: S.nextCursor ?? null,
|
|
4334
4334
|
nextCursorNs: S.nextCursorNs ?? null,
|
|
4335
|
-
pendingInterrupt: S.
|
|
4335
|
+
pendingInterrupt: S.interrupt ?? null
|
|
4336
4336
|
};
|
|
4337
4337
|
if (S.checkpointId) {
|
|
4338
4338
|
const $ = Jo(S.checkpointId, S.checkpointNs ?? null);
|
|
@@ -4343,7 +4343,7 @@ function wv({
|
|
|
4343
4343
|
checkpointNs: S.checkpointNs ?? null,
|
|
4344
4344
|
nextCursor: S.nextCursor ?? null,
|
|
4345
4345
|
nextCursorNs: S.nextCursorNs ?? null,
|
|
4346
|
-
interrupt: S.
|
|
4346
|
+
interrupt: S.interrupt ?? null
|
|
4347
4347
|
}
|
|
4348
4348
|
}, "prepend");
|
|
4349
4349
|
}
|
|
@@ -15111,7 +15111,7 @@ function Ui({
|
|
|
15111
15111
|
] }),
|
|
15112
15112
|
x && Q.length > 0 && /* @__PURE__ */ c.jsxs("div", { className: "flex-shrink-0 flex items-center gap-2 px-4 py-2 border-b border-border bg-muted/60 text-xs dark:bg-muted/50", children: [
|
|
15113
15113
|
/* @__PURE__ */ c.jsx("span", { className: "opacity-70", children: "Checkpoint:" }),
|
|
15114
|
-
/* @__PURE__ */ c.
|
|
15114
|
+
/* @__PURE__ */ c.jsx(
|
|
15115
15115
|
"select",
|
|
15116
15116
|
{
|
|
15117
15117
|
className: "border border-border rounded px-2 py-1 text-xs bg-card text-foreground focus:outline-none focus:ring-1 focus:ring-ring dark:bg-secondary",
|
|
@@ -15120,13 +15120,10 @@ function Ui({
|
|
|
15120
15120
|
const Te = oe.target.value || null;
|
|
15121
15121
|
sr(Te);
|
|
15122
15122
|
},
|
|
15123
|
-
children: [
|
|
15124
|
-
|
|
15125
|
-
|
|
15126
|
-
|
|
15127
|
-
oe.preview ? ` — ${oe.preview.slice(0, 40)}` : ""
|
|
15128
|
-
] }, oe.checkpointId))
|
|
15129
|
-
]
|
|
15123
|
+
children: Q.map((oe) => /* @__PURE__ */ c.jsxs("option", { value: oe.checkpointId, children: [
|
|
15124
|
+
Sn(oe.createdAt),
|
|
15125
|
+
oe.preview ? ` — ${oe.preview.slice(0, 40)}` : ""
|
|
15126
|
+
] }, oe.checkpointId))
|
|
15130
15127
|
}
|
|
15131
15128
|
)
|
|
15132
15129
|
] }),
|
package/dist/index.umd.js
CHANGED
|
@@ -35,7 +35,7 @@ React keys must be passed directly to JSX without using spread:
|
|
|
35
35
|
`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=or(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Lo.assertOptions(r,{silentJSONParsing:gn.transitional(gn.boolean),forcedJSONParsing:gn.transitional(gn.boolean),clarifyTimeoutError:gn.transitional(gn.boolean)},!1),o!=null&&(R.isFunction(o)?n.paramsSerializer={serialize:o}:Lo.assertOptions(o,{encode:gn.function,serialize:gn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Lo.assertOptions(n,{baseUrl:gn.spelling("baseURL"),withXsrfToken:gn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&R.merge(s.common,s[n.method]);s&&R.forEach(["delete","get","head","post","put","patch","common"],b=>{delete s[b]}),n.headers=$t.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(n)===!1||(l=l&&x.synchronous,a.unshift(x.fulfilled,x.rejected))});const u=[];this.interceptors.response.forEach(function(x){u.push(x.fulfilled,x.rejected)});let d,f=0,h;if(!l){const b=[nc.bind(this),void 0];for(b.unshift(...a),b.push(...u),h=b.length,d=Promise.resolve(n);f<h;)d=d.then(b[f++],b[f++]);return d}h=a.length;let p=n;for(;f<h;){const b=a[f++],x=a[f++];try{p=b(p)}catch(g){x.call(this,g);break}}try{d=nc.call(this,p)}catch(b){return Promise.reject(b)}for(f=0,h=u.length;f<h;)d=d.then(u[f++],u[f++]);return d}getUri(t){t=or(this.defaults,t);const n=Vl(t.baseURL,t.url,t.allowAbsoluteUrls);return Dl(n,t.params,t.paramsSerializer)}};R.forEach(["delete","get","head","options"],function(t){sr.prototype[t]=function(n,r){return this.request(or(r||{},{method:t,url:n,data:(r||{}).data}))}}),R.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(or(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}sr.prototype[t]=n(),sr.prototype[t+"Form"]=n(!0)});let Bg=class gm{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new Er(s,i,a),n(r.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 n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new gm(function(o){t=o}),cancel:t}}};function zg(e){return function(n){return e.apply(null,n)}}function Hg(e){return R.isObject(e)&&e.isAxiosError===!0}const bi={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};Object.entries(bi).forEach(([e,t])=>{bi[t]=e});function sc(e){const t=new sr(e),n=yl(sr.prototype.request,t);return R.extend(n,sr.prototype,t,{allOwnKeys:!0}),R.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return sc(or(e,o))},n}const gt=sc(Xr);gt.Axios=sr,gt.CanceledError=Er,gt.CancelToken=Bg,gt.isCancel=zl,gt.VERSION=rc,gt.toFormData=Ro,gt.AxiosError=$e,gt.Cancel=gt.CanceledError,gt.all=function(t){return Promise.all(t)},gt.spread=zg,gt.isAxiosError=Hg,gt.mergeConfig=or,gt.AxiosHeaders=$t,gt.formToJSON=e=>Fl(R.isHTMLForm(e)?new FormData(e):e),gt.getAdapter=tc.getAdapter,gt.HttpStatusCode=bi,gt.default=gt;const{Axios:jk,AxiosError:Rk,CanceledError:Pk,isCancel:Ok,CancelToken:Mk,VERSION:Dk,all:Lk,Cancel:$k,isAxiosError:Fk,spread:Bk,toFormData:zk,AxiosHeaders:Hk,HttpStatusCode:Uk,formToJSON:Wk,getAdapter:Vk,mergeConfig:Kk}=gt,ic=typeof window<"u"?window.__API_BASE_URL__:void 0,ac=ic?On(ic):void 0;function On(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let $o=null;const wi=new Set;function lc(){return $o}function yi(e){$o=e,wi.forEach(t=>t(e))}function cc(e){return wi.add(e),()=>wi.delete(e)}const Kt=gt.create({...ac?{baseURL:ac}:{},timeout:3e4,withCredentials:!0});Kt.interceptors.request.use(e=>($o&&(e.headers.Authorization=`Bearer ${$o}`),e)),Kt.interceptors.response.use(e=>e,e=>Promise.reject(e));async function nn(e,t){return Kt.defaults.baseURL?(await Kt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Si(e,t,n){return Kt.defaults.baseURL?(await Kt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function uc(e,t,n){return Kt.defaults.baseURL?(await Kt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function dc(e,t){return Kt.defaults.baseURL?(await Kt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function rn(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class fc{get baseUrl(){const t=Kt.defaults.baseURL;return t?On(String(t)):""}updateConfig(t){t.baseUrl&&(Kt.defaults.baseURL=On(String(t.baseUrl))),t.authToken!==void 0&&yi(t.authToken)}getAuthToken(){return lc()}setAuthToken(t){yi(t)}onTokenChange(t){return cc(t)}async listThreads(){const t=await nn("/threads"),n=rn(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await Si("/threads",t?{title:t}:void 0);return rn(r)}async updateThread(t,n){const r=await uc(`/threads/${t}`,{title:n});return rn(r)}async deleteThread(t){const n=await dc(`/threads/${t}`);return rn(n)}async threadInfo(t){const n=await nn(`/threads/${t}/info`);return rn(n)}async listAgents(){const t=await nn("/agents"),n=rn(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await nn(`/agents/${t}`);return rn(n)}async getAgentSchema(t){const n=await nn(`/agents/${t}/schema`);return rn(n)}async getMessages(t){const n=await nn(`/threads/${t.threadId}/messages`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs,limit:t.limit,before_id:t.beforeId??void 0}});return rn(n)}async getStateHistory(t){const n=await nn(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return rn(n)}resumeStream(t){}async resume(t){const n=await Si("/runs/resume",{thread_id:t.threadId,value:t.value});return rn(n)}}const Bn=new fc,hc=y.createContext(null);function Ug({children:e,apiConfig:t}){const n=Bn;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return c.jsx(hc.Provider,{value:r,children:e})}function Ci(){const e=y.useContext(hc);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Wg(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function Vg(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const u=await Wg(l);a.push({filename:l.name,data:u,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Kg={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function ki(e){if(!e||typeof e!="object")return!1;const t=e;return"values"in t&&"config"in t&&typeof t.values=="object"&&t.values!==null&&typeof t.config=="object"&&t.config!==null}function Fo(e,t){return`${e??""}::${t??""}`}function Ti(e){const t=Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[],n=(e==null?void 0:e.threadId)??"",r=t[0];if(!ki(r))return{payload:{threadId:n,checkpointId:void 0,checkpointNs:void 0,messages:[],hasMore:!1,nextCursor:null,nextCursorNs:null},checkpoints:[],interrupt:null,snapshots:{}};const{summaries:o,snapshots:s}=Gg(t),i=pc(r,0);return{payload:{threadId:n,checkpointId:(i==null?void 0:i.checkpointId)??void 0,checkpointNs:(i==null?void 0:i.checkpointNs)??void 0,messages:(i==null?void 0:i.messages)??[],hasMore:!!(i!=null&&i.nextCursor),nextCursor:(i==null?void 0:i.nextCursor)??null,nextCursorNs:(i==null?void 0:i.nextCursorNs)??null,pendingInterrupt:(i==null?void 0:i.interrupt)??null},checkpoints:o,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function pc(e,t){var h,p;if(!ki(e))return null;const n=e.values??{},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],o=e.tasks,s=r.map((b,x)=>Qg(b,x)).filter(b=>!!b),i=Bt((h=e.config)==null?void 0:h.configurable),a=pt(i,["checkpoint_id","checkpointId"]),l=pt(i,["checkpoint_ns","checkpointNs"]),u=Bt((p=e.parentConfig)==null?void 0:p.configurable),d=pt(u,["checkpoint_id","checkpointId"])??null,f=pt(u,["checkpoint_ns","checkpointNs"])??null;return{messages:s,checkpointId:a??null,checkpointNs:l??null,nextCursor:d,nextCursorNs:f,interrupt:qg(o,s,t)}}function qg(e,t,n){const r=Jg(e,n);return r||Xg(t,n)}function Gg(e){const t=new Map,n={};e.forEach((o,s)=>{if(!ki(o))return;const i=pc(o,s);if(!(i!=null&&i.checkpointId))return;const a=o==null?void 0:o.createdAt,l=typeof a=="string"&&a.trim()?a:new Date(Date.now()-s).toISOString(),u=Yg(i.messages),d=i.messages[i.messages.length-1],f=Bt(o==null?void 0:o.metadata),h=pt(f,["branch_label","branchLabel"]),p=Bt(o==null?void 0:o.parentConfig),b=Bt(p==null?void 0:p.configurable),x=pt(b,["checkpoint_id","checkpointId"]),g={checkpointId:i.checkpointId,checkpointNs:i.checkpointNs??"",createdAt:l,messagesLen:i.messages.length,preview:u??null,role:(d==null?void 0:d.role)??null,parentId:x??null,branchLabel:h??null,lastMessageId:(d==null?void 0:d.id)??null,hasMessages:i.messages.length>0},v=Fo(g.checkpointId,g.checkpointNs);t.has(v)||t.set(v,g),n[v]||(n[v]=i)});const r=Array.from(t.values());return r.sort((o,s)=>gc(s.createdAt)-gc(o.createdAt)),{summaries:r,snapshots:n}}function Yg(e){var t;for(let n=e.length-1;n>=0;n--){const r=((t=e[n])==null?void 0:t.content)??[];for(let o=0;o<r.length;o++){const s=r[o];if(s&&s.type==="text"&&typeof s.text=="string"){const i=s.text.trim();if(i)return i}}}return null}function Xg(e,t){var n;for(let r=e.length-1;r>=0;r--){const o=((n=e[r])==null?void 0:n.content)??[];for(let s=o.length-1;s>=0;s--){const i=o[s];if((i==null?void 0:i.type)==="interrupt"){const a=i;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${t}-${r}-${s}`,value:a.value}}}}return null}function Jg(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=Zg(e[n],`task-${t}-${n}`);if(!r)continue;const o=r.id||`task-${t}-${n}`;if(Array.isArray(r.interrupts)&&r.interrupts.length)for(let s=r.interrupts.length-1;s>=0;s--){const i=Zr(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=Zr(r.state,`${o}-state`);if(s)return s}}return null}function Zg(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,u,,d,,f,...h]=e,p=typeof a=="string"&&a.trim()?a:t,b=typeof l=="string"&&l.trim()?l:Array.isArray(u)&&typeof u[0]=="string"?String(u[0]):"task",x=Array.isArray(d)?d:void 0,g=h.length?h[h.length-1]:void 0;return{id:p,name:b,interrupts:x,state:g!==void 0?g:f}}const n=Bt(e);if(!n)return null;const r=pt(n,["id","task_id","taskId"])??t,o=pt(n,["name"])??"task",s=Array.isArray(n.interrupts)?n.interrupts:void 0,i=Object.prototype.hasOwnProperty.call(n,"state")?n.state:void 0;return{id:r,name:o,interrupts:s,state:i}}function Zr(e,t,n=0,r=new Set){if(n>6||e==null)return null;if(typeof e=="object"){if(r.has(e))return null;r.add(e)}const o=mc(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=Zr(e[s],t,n+1,r);if(i)return i}return null}if(typeof e=="object"){const s=e,i=["interrupt","pending_interrupt","pendingInterrupt","value","data","payload","result","response"];for(const a of i)if(a in s){const l=Zr(s[a],t,n+1,r);if(l)return l}for(const[a,l]of Object.entries(s)){if(i.includes(a)||a==="messages"||a==="results")continue;const u=Zr(l,t,n+1,r);if(u)return u}}return null}function mc(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=pt(n,["type","event","kind"]),o=pt(n,["id","interrupt_id","interruptId","value_id"])??(r&&r.toLowerCase().includes("interrupt")?t:void 0);if(!(Object.prototype.hasOwnProperty.call(n,"value")||Object.prototype.hasOwnProperty.call(n,"data")||Object.prototype.hasOwnProperty.call(n,"payload"))&&!(r&&r.toLowerCase().includes("interrupt")))return null;const i=Object.prototype.hasOwnProperty.call(n,"value")?n.value:Object.prototype.hasOwnProperty.call(n,"data")?n.data:Object.prototype.hasOwnProperty.call(n,"payload")?n.payload:n,a=o&&o.trim()?o:t;return a?{id:a,value:i}:null}if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){const r=mc(e[n],t);if(r)return r}return e.length>=2&&typeof e[0]=="string"&&e[0].trim()?{id:e[0],value:e[1]}:null}if(typeof e=="string"){const n=e.trim();return n?{id:t||n,value:n}:null}return null}function gc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Qg(e,t){if(!e||typeof e!="object")return null;const n=e,r=Bt(e)??{},o=Bt(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=Kg[s];if(!i)return null;const a=o.id??o.message_id??o.run_id??null,l=typeof a=="string"&&a.trim()?a:`history-${i}-${t}`,u=Bt(o.additional_kwargs)??Bt(o.additionalKwargs),d=Bt(o.response_metadata)??Bt(o.responseMetadata),f=pt(u,["createdAt","created_at"])??pt(o,["created_at","createdAt"]),h=pt(u,["checkpointId","checkpoint_id"]),p=pt(u,["checkpointNs","checkpoint_ns"]),b=ex(o.content),x={id:l,role:i,content:b};f&&(x.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(x.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(x.model=String(d.model_name)),!x.model&&typeof o.model=="string"&&(x.model=o.model),h&&(x.checkpointId=h),p&&(x.checkpointNs=p);const g=sx(u,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),v=d?{...d}:void 0;g&&Object.keys(g).length&&(x.additionalKwargs=g),v&&Object.keys(v).length&&(x.responseMetadata=v);const w=tx((u==null?void 0:u.tool_calls)??o.tool_calls);if(w.length&&(x.content=[...x.content,...w]),i==="tool"){const S=rx(o,x.content);S&&(x.content=S)}return x}function ex(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>xc(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=xc(e);return t?[t]:[]}return[]}function xc(e){if(!e||typeof e!="object")return typeof e=="string"&&e.trim()?{type:"text",text:e}:null;const t=e,n=String(t.type??"").toLowerCase();if(!n||n==="text"){const o=typeof t.text=="string"?t.text:typeof t.value=="string"?t.value:"";return o.trim()?{type:"text",text:o}:null}if(n==="image"||n==="image_url"){const o=pt(t,["url","src"]);if(!o)return null;const s={type:"image_url",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.alt=="string"&&(s.alt=t.alt),s}if(n==="file"){const o=pt(t,["url"]);if(!o)return null;const s={type:"file",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.name=="string"&&(s.name=t.name),typeof t.size=="number"&&(s.size=t.size),typeof t.sourceType=="string"&&(s.sourceType=t.sourceType),s}if(n==="tool_call")return nx(t)??null;if(n==="tool_end"){const o=pt(t,["tool_call_id","toolCallId","id"]);if(!o)return null;const s={type:"tool_end",toolCallId:o,output:"output"in t?t.output:t.content};return typeof t.error=="string"&&(s.error=t.error),s}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=pt(t,["text","content"]);if(o)return{type:"text",text:o}}const r=typeof t.content=="string"?t.content:typeof t.value=="string"?t.value:JSON.stringify(t);return r?{type:"text",text:r}:null}function tx(e){return Array.isArray(e)?e.map((t,n)=>{if(!t||typeof t!="object")return null;const r=t,o=pt(r,["id","call_id"]),s=Bt(r.function),i=pt(s,["name"])??"tool",a=s==null?void 0:s.arguments,l=vc(a);return{type:"tool_call",id:o??`tool_call_${n}`,name:i,args:l}}).filter(t=>!!t):[]}function nx(e){const t=pt(e,["id","call_id"]),n=pt(e,["name"]);if(!t||!n)return null;const r=vc(e.args??e.arguments);return{type:"tool_call",id:t,name:n,args:r}}function rx(e,t){const n=pt(e,["tool_call_id","toolCallId","id"]);if(!n)return t;const r=e.content??e.output,o=typeof r=="string"?ox(r):r,s={type:"tool_end",toolCallId:n,output:o};return typeof e.error=="string"&&(s.error=e.error),[s]}function vc(e){if(!e)return{};if(typeof e=="string")try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{raw:e}}catch{return{raw:e}}return typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function ox(e){try{return JSON.parse(e)}catch{return e}}function Bt(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function pt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function sx(e,t){if(!e)return;const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(t.includes(o)){r=!0;continue}s!==void 0&&(n[o]=s)}return r?Object.keys(n).length?n:void 0:e}function ix(e){return e.type!=="thread_info"&&e.type!=="token"}const ax={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function lx(e,t){var n;switch(t.type){case"reset":{console.log("[MessageReducer] 🔄 RESET action received"),console.log("[MessageReducer] 📊 Before reset - messages count:",e.messages.length);const r={messages:Ii(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};return console.log("[MessageReducer] 📊 After reset - messages count:",r.messages.length),r}case"seed":{const r=Ii(t.payload.messages),o={...e,messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(o.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(o.lastCheckpointNs=t.payload.checkpointNs??null),console.log("[MessageReducer] seed action (REPLACE mode):",{incomingCount:t.payload.messages.length,sanitizedCount:r.length,previousCount:e.messages.length,checkpointId:o.lastCheckpointId}),o}case"prepend":{const r=Ii(t.payload.messages);if(!r.length)return console.log("[MessageReducer] No incoming messages after sanitize - skipping"),e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return console.log("[MessageReducer] After dedup:",{uniqueCount:s.length,duplicates:r.length-s.length,finalTotal:s.length+e.messages.length}),s.length?{...e,messages:[...s,...e.messages]}:(console.log("[MessageReducer] All messages were duplicates - skipping"),e)}case"user_message":{const r=t.payload.message;return e.messages.some(o=>o.id===r.id)?e:{...e,messages:[...e.messages,r]}}case"event":return wc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>wc(o,s),e):e}case"interrupt_response":{const{interruptId:r}=t.payload,o=e.messages.map(s=>({...s,content:s.content.filter(i=>i.type!=="interrupt")}));return{...e,messages:o,pendingInterrupt:null}}default:return e}}function bc(e=[]){const[t,n]=y.useReducer(lx,{...ax,messages:e}),r=y.useRef([]),o=y.useRef(null),s=y.useRef(null),i=y.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=y.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=y.useCallback(d=>{r.current.push(d),a()},[a]);y.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const u=y.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...u}}function wc(e,t){var n,r,o,s;if(t.type==="message_start"&&t.role==="assistant"){const i=t.id,a=dx(t.model);if(e.messages.some(d=>d.id===i)){const d=e.messagesStreamMeta??{},f={...d,[i]:d[i]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:i,messagesStreamMeta:f}}const u={id:i,role:"assistant",name:a||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:i,messages:[...e.messages,u]}}if(t.type==="message_delta"){const i=e.assemblingId??Ei(e.messages);if(!i)return e;const a=e.messages,l=a.findIndex(S=>S.id===i&&S.role==="assistant");if(l===-1)return e;const u=a[l],d=e.messagesStreamMeta??{},f=d[i]??{lastSeq:null,lastText:Tc(u.content)},h=t.seq??null;if(h!==null&&typeof h=="number"&&typeof f.lastSeq=="number"&&h<=f.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:h,lastSeq:f.lastSeq}),e;const{newParts:p,newMeta:b,changed:x}=cx(u.content,t.delta,f,h);if(!x)return e;const g={...u,content:p},v=yc(a,l,g),w={...d,[i]:b};return{...e,messages:v,messagesStreamMeta:w}}if(t.type==="message_end"){const i=e.assemblingId??Ei(e.messages);if(!i)return{...e,assemblingId:null};const a=e.messages,l=a.findIndex(u=>u.id===i&&u.role==="assistant");if(l>=0){const u=a[l];if(!((n=u.content)==null?void 0:n.some(f=>{var h;return(f==null?void 0:f.type)==="text"&&((h=f.text)==null?void 0:h.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:u.id,contentTypes:(r=u.content)==null?void 0:r.map(h=>h==null?void 0:h.type),contentPreview:(o=u.content)==null?void 0:o.map(h=>(h==null?void 0:h.type)==="text"?String(h.text).slice(0,100):h==null?void 0:h.type)});const f=[...a.slice(0,l),...a.slice(l+1)];return{...e,assemblingId:null,messages:f}}}return e}if(t.type==="tool_start"){const i=t.id??t.call_id,a=t.name??t.tool??"tool";if(!i)return e;const l=`tool-${i}`,u={type:"tool_call",id:i,name:a,args:t.args};if(e.messages.find(h=>h.id===l))return{...e,toolIndex:{...e.toolIndex,[i]:l}};const f={id:l,role:"tool",name:a,createdAt:new Date().toISOString(),content:[u]};return{...e,messages:[...e.messages,f],toolIndex:{...e.toolIndex,[i]:l}}}if(t.type==="tool_end"){const i=t.id??t.call_id;if(!i)return e;const a=e.toolIndex[i]??`tool-${i}`,l={type:"tool_end",toolCallId:i,output:t.output,error:t.error},u=e.messages.find(h=>h.id===a),d={id:a,role:"tool",name:t.name??((s=e.messages.find(h=>h.id===a))==null?void 0:s.name),content:[l],createdAt:new Date().toISOString()},f=u?Cc(e.messages,a,[l]):[...e.messages,d];return{...e,messages:f,toolIndex:{...e.toolIndex,[i]:a}}}if(t.type==="checkpoint"){const i=t.checkpointNs??e.lastCheckpointNs??null,a=ux(e.messages,t.checkpointId,i);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:i,messages:a}}if(t.type==="branch"){const i=t.checkpointId??e.lastCheckpointId,a=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:i??null,lastCheckpointNs:a??null}}if(t.type==="error"){const i={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,i]}}if(t.type==="interrupt"){const i=e.assemblingId??Ei(e.messages),a={type:"interrupt",value:t.value,id:t.id};if(i)return{...e,assemblingId:null,messages:Cc(e.messages,i,[a]),pendingInterrupt:{id:t.id,value:t.value}};const l=`interrupt-${t.id}`;if(e.messages.findIndex(f=>f.id===l)!==-1)return{...e,assemblingId:null,messages:Sc(e.messages,l,f=>({...f,content:kc(f.content??[],[a])})),pendingInterrupt:{id:t.id,value:t.value}};const d={id:l,role:"system",createdAt:new Date().toISOString(),content:[a]};return{...e,messages:[...e.messages,d],pendingInterrupt:{id:t.id,value:t.value}}}return e}function Ii(e){return e.filter(t=>{if(t.role!=="assistant")return!0;const n=(t.content||[]).some(o=>{var s;return o&&o.type==="text"&&((s=o.text)==null?void 0:s.trim())}),r=(t.content||[]).some(o=>o&&o.type==="image_url");return!!(n||r)})}function yc(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Ei(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function Sc(e,t,n){const r=e.findIndex(i=>i.id===t);if(r===-1)return e;const o=e[r],s=n(o);return s===o?e:[...e.slice(0,r),s,...e.slice(r+1)]}function Cc(e,t,n){return Sc(e,t,r=>({...r,content:kc(r.content,n)}))}function kc(e,t){const n=e.slice();for(const r of t)if(r.type==="text"){const o=n[n.length-1],s=r.text??"";if(!s)continue;if((o==null?void 0:o.type)==="text"){let i=function(p){return p.replace(/\s+/g," ").trim()};const a=o,l=a.text??"";if(console.debug("[MessageReducer] mergeParts",{incomingLength:s.length,previousLength:l.length,incomingSnippet:s.slice(0,100),previousSnippet:l.slice(-100)}),!l){a.text=s;continue}const u=i(s),d=i(l);if(u.startsWith(d)||s.startsWith(l)){console.debug("[MessageReducer] incoming startsWith previous (norm/raw) - replacing",{incomingLength:s.length,previousLength:l.length}),a.text=s;continue}if(u.includes(d)){console.debug("[MessageReducer] incoming includes previous (normalized) - replacing",{incomingLength:s.length,previousLength:l.length}),a.text=s;continue}if(d.includes(u)&&u.length<=3){console.debug("[MessageReducer] previous includes incoming (normalized) - skipping trivial incoming",{incomingLength:s.length,previousLength:l.length});continue}const h=Ec(l,s);h?(console.debug("[MessageReducer] suffix computed",{suffixLength:h.length}),a.text=l+h):(console.debug("[MessageReducer] no overlap detected - appending incoming",{incomingLength:s.length}),a.text=l+s)}else n.push({type:"text",text:s})}else n.push(r);return n}function Tc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function cx(e,t,n,r){const o={...n};if(r!==null&&typeof r=="number"){if(typeof o.lastSeq=="number"&&r<=o.lastSeq)return{newParts:e,newMeta:o,changed:!1};o.lastSeq=r}const s=t.filter(f=>f.type==="text").map(f=>f.text??"").join(""),i=t.filter(f=>f.type!=="text"),a=o.lastText??Tc(e);let l="",u=e.slice();if(s){const f=Ec(a,s);if(f===""?l="":f===s?l=s:l=f,l){const h=u[u.length-1];if((h==null?void 0:h.type)==="text"){const p=h.text??"",b={...h,text:p+l};u=[...u.slice(0,u.length-1),b]}else u=[...u,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(u=[...u,...i]);const d=!!(l||i.length);return{newParts:u,newMeta:o,changed:d}}function Ic(e){return e.replace(/\s+/g," ").trim()}function Ec(e,t){if(!t)return"";if(!e)return t;if(e===t)return"";const n=Math.min(e.length,t.length);for(let i=n;i>0;i--)if(e.slice(-i)===t.slice(0,i))return t.slice(i);const r=Ic(e),o=Ic(t);if(r===o)return"";const s=Math.min(r.length,o.length);for(let i=s;i>0;i--)if(r.slice(-i)===o.slice(0,i))return t;return t}function ux(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return yc(e,r,s)}return e}function dx(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function Nc(e={}){const t=y.useMemo(()=>On(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=y.useState(e.token??null),s=y.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=y.useState(!1),[u,d]=y.useState(null),[f,h]=y.useState(""),[p,b]=y.useState(null),[x,g]=y.useState(0),[v,w]=y.useState(!1),S=y.useRef(null),N=y.useRef(!0),k=y.useRef(0),T=y.useCallback(P=>{o(P)},[]),E=y.useCallback(()=>{var P;(P=S.current)==null||P.abort(),S.current=null,l(!1),w(!1),k.current=0,g(0)},[]),A=y.useCallback(()=>{h(""),b(null),d(null)},[]),j=y.useCallback((P,L,$)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h("");const V=new AbortController;return S.current=V,(async()=>{var G,K,W,z,B,ue,D,te;const M=he=>{var we;try{const ye=JSON.parse(JSON.stringify(he));return(we=ye==null?void 0:ye.payload)!=null&&we.files_info&&Array.isArray(ye.payload.files_info)&&(ye.payload.files_info=ye.payload.files_info.map(Se=>({...Se,data:Se!=null&&Se.data?`<base64 ${String(Se.data).length} chars>`:Se==null?void 0:Se.data}))),ye}catch{return he}};try{let he={};try{if(r)he={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Ve=window.__AUTH_TOKEN__,ut=((G=window.localStorage)==null?void 0:G.getItem("authToken"))||null;let nt=null;try{const vt=(K=window.localStorage)==null?void 0:K.getItem("chat-settings");vt&&(nt=((W=JSON.parse(vt))==null?void 0:W.apiKey)||null)}catch{}const Ke=Ve||ut||nt||null;Ke&&(he={Authorization:`Bearer ${Ke}`})}}catch{}console.debug("[use-chat] POST",t+n,M(P));const we=await fetch(t+n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...he,...s.current},body:JSON.stringify(P),signal:V.signal,credentials:i});if(!we.ok||!we.body){const Pe=await we.text().catch(()=>"");throw console.debug("[use-chat] non-OK response",we.status,Pe==null?void 0:Pe.slice(0,500)),new Error(`stream ${we.status}${Pe?": "+Pe:""}`)}w(!0);const ye=we.body.getReader(),Se=new TextDecoder;let q="",O=[];k.current=0,g(0);let X=0,ne=null;const pe=()=>{if(O.length){const Pe=O.join("");O=[],N.current&&h(Ve=>Ve+Pe)}ne=null},se=()=>{typeof window<"u"&&ne==null&&(ne=requestAnimationFrame(pe))};let me=Date.now();const et=setInterval(()=>{var Pe;if(Date.now()-me>6e4){const Ve="Stream idle timeout";d(Ve),V.abort(),(Pe=$==null?void 0:$.onError)==null||Pe.call($,Ve)}},5e3),tt=1024*1024;try{const Pe=we.headers.get("X-Thread-Id")||we.headers.get("x-thread-id"),Ve=we.headers.get("X-Thread-Created")||we.headers.get("x-thread-created"),ut=Pe??null,nt=String(Ve??"").toLowerCase()==="true";for((z=$==null?void 0:$.onOpen)==null||z.call($,{threadId:ut,created:nt});;){const{value:Ke,done:vt}=await ye.read();if(vt)break;q+=Se.decode(Ke,{stream:!0}),q.length>tt&&(q="",console.warn("Stream buffer reset: exceeded 1MB"));let Q;for(;(Q=q.indexOf(`
|
|
36
36
|
|
|
37
37
|
`))>=0;){const ie=q.slice(0,Q);q=q.slice(Q+2);const xe=hx(ie);if(!xe)continue;let Ce;try{Ce=JSON.parse(xe)}catch{console.debug("[use-chat] malformed SSE:",xe.slice(0,200));continue}const ve=fx(Ce)?Ce.data:Ce;me=Date.now();const Oe=ve.seq;if(Oe!==void 0){if(Oe<=X){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:Oe,lastProcessedSeq:X,type:ve.type});continue}X>0&&Oe>X+1&&((B=$==null?void 0:$.onGap)==null||B.call($,{from:X,to:Oe})),X=Oe,k.current=Oe,g(Oe)}if(console.debug("[use-chat] received event",{seq:ve.seq,type:ve.type,preview:(()=>{var at;try{return ve.type==="message_delta"?{deltaTypes:(at=ve.delta)==null?void 0:at.map(Me=>Me.type),textLen:(ve.delta||[]).filter(Me=>Me.type==="text").map(Me=>String(Me.text||"").length)}:ve.content||ve.delta?{hasContent:!0}:{}}catch(Me){return{err:String(Me)}}})()}),L==null||L(ve),ve.type==="token"&&e.autoAppendAssistant!==!1)O.push(ve.content),se();else if(ve.type==="message_delta"){const at=ve.delta.filter(Me=>Me.type==="text").map(Me=>Me.text).join("");at&&e.autoAppendAssistant!==!1&&(O.push(at),se())}else ve.type==="heartbeat"?console.debug("[use-chat] heartbeat received"):(ne!==null&&cancelAnimationFrame(ne),pe(),ve.type==="checkpoint"?b(ve.checkpointId):ve.type==="error"&&d(ve.message))}}pe()}catch(Pe){if(Pe.name!=="AbortError"){const Ve=Pe.message||String(Pe);d(Ve),(ue=$==null?void 0:$.onError)==null||ue.call($,Ve)}}finally{try{await ye.cancel()}catch{}finally{(D=ye.releaseLock)==null||D.call(ye)}ne!==null&&typeof window<"u"&&window.cancelAnimationFrame(ne),clearInterval(et),l(!1),w(!1),S.current=null,k.current=0,g(0)}}catch(he){if(he.name!=="AbortError"){const we=he.message||String(he);d(we),(te=$==null?void 0:$.onError)==null||te.call($,we)}}finally{l(!1),w(!1),S.current=null,k.current=0,g(0)}})(),{close:()=>V.abort()}},[t,n,r,e.autoAppendAssistant]);return y.useEffect(()=>()=>{var P;N.current=!1,(P=S.current)==null||P.abort()},[]),{isStreaming:a,error:u,assistantText:f,lastCheckpointId:p,lastSeq:x,connected:v,stream:j,stop:E,clear:A,setToken:T}}function fx(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function hx(e){const t=e.split(/\r?\n/),n=[];for(const r of t)if(r&&!r.startsWith(":")&&r.startsWith("data:")){const o=r.slice(5);n.push(o.startsWith(" ")?o.slice(1):o)}return n.length===0?null:n.join(`
|
|
38
|
-
`)}function px({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o}){const s=y.useRef(null),i=y.useCallback(p=>{const b=p.seq??null;if(b!==null){const x=s.current;if(x!==null){if(b<=x)return;b>x+1&&(o==null||o({from:x,to:b}))}s.current=b}if(p.type==="thread_info"){console.log("[useChatStreamingService] 🎯 Received thread_info event:",p),t(p);return}if(ix(p)){n(p);return}r==null||r(p)},[n,o,t,r]),{stream:a,stop:l,isStreaming:u,error:d,setToken:f}=Nc({baseUrl:e,token:null}),h=y.useCallback((p,b)=>{s.current=null,a(p,i,{onOpen:b==null?void 0:b.onOpen,onError:x=>{var g;(g=b==null?void 0:b.onError)==null||g.call(b,x)},onGap:(b==null?void 0:b.onGap)??o})},[i,o,a]);return y.useMemo(()=>({startStream:h,stop:l,isStreaming:u,error:d,setAuthToken:f}),[h,l,u,d,f])}const Ac=y.createContext(null),_c=y.createContext(null),jc=y.createContext(null),mx=y.createContext(!1),gx="cachedThreads",xx="v1",Bo=300,Ni=200,Rc=50;function vx(e,t,n){return`${e}__${t??""}__${n??""}`}function bx(e,t){if(!e&&!t)return!0;if(!e||!t||e.id!==t.id)return!1;try{return JSON.stringify(e.value)===JSON.stringify(t.value)}catch{return e.value===t.value}}function wx(e){var t;for(let n=e.length-1;n>=0;n--){const r=((t=e[n])==null?void 0:t.content)??[];for(let o=r.length-1;o>=0;o--){const s=r[o];if((s==null?void 0:s.type)==="interrupt"){const i=s.id;return{id:(typeof i=="string"?i:null)??`interrupt-${e[n].id??o}`,value:s.value}}}}return null}function Pc(e){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:1e3});return}catch{}window.setTimeout(e,Bo)}function Nr(){return typeof window<"u"&&typeof window.localStorage<"u"}function Ai(e){if(!Nr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function Oc(e,t){if(Nr())try{window.localStorage.setItem(e,t)}catch{}}function _i(e){if(Nr())try{window.localStorage.removeItem(e)}catch{}}function yx(){const e=Ai(gx);if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>{if(!n||typeof n!="object")return!1;const r=n;return typeof r.threadId=="string"&&typeof r.title=="string"}):[]}catch{return[]}}function Sx(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(36)}function ji(e,t){return`cachedThreads:v1:${e}:${Sx(t||"anon")}`}function Cx(e){const t=Ai(e);if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>{if(!r||typeof r!="object")return!1;const o=r;return typeof o.threadId=="string"&&typeof o.title=="string"}):[]}catch{return[]}}function Ri(e,t){try{Oc(e,JSON.stringify(t))}catch{}}function Pi(e){const t=Cx(e);if(t.length>0)return t;const n=yx();if(n.length>0)try{Ri(e,n.slice(0,Ni))}catch{}return n}function zo(e){const t={},n=[];for(const r of e)!r||typeof r.threadId!="string"||t[r.threadId]||(t[r.threadId]=r,n.push(r.threadId));return{byId:t,order:n}}function Oi(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function kx({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader",onError:i,onThreadChange:a}){const{api:l,baseUrl:u}=Ci(),d=y.useMemo(()=>On(u),[u]),f=y.useMemo(()=>{try{return new URL(u).host}catch{return"unknown"}},[u]),h=y.useMemo(()=>`threadPayload:${xx}:${f}:`,[f]),p=y.useCallback(C=>`${h}${C}`,[h]),b=y.useCallback(C=>{if(!C||typeof C!="object")return null;const _=C;return typeof _.threadId!="string"||!Array.isArray(_.messages)?null:{threadId:_.threadId,messages:_.messages,hasMore:!!_.hasMore,nextCursor:_.nextCursor??null,checkpointId:_.checkpointId??null,checkpointNs:_.checkpointNs??null,nextCursorNs:_.nextCursorNs??null,pendingInterrupt:_.pendingInterrupt??null}},[]),x=y.useCallback(C=>{const _=Ai(p(C));if(!_)return null;try{const F=JSON.parse(_);return b(F)}catch{return null}},[p,b]),g=y.useCallback((C,_=100)=>{const F={...C,messages:Array.isArray(C.messages)?C.messages.slice(-_):[]};try{Oc(p(C.threadId),JSON.stringify(F))}catch{}},[p]),v=y.useCallback(C=>{_i(p(C))},[p]),w=y.useCallback(()=>{if(Nr())try{const C=h;for(let _=0;_<window.localStorage.length;_++){const F=window.localStorage.key(_);F&&F.startsWith(C)&&window.localStorage.removeItem(F)}}catch{}},[h]),[S,N]=y.useState(()=>{var C;return ji(f,(C=l.getAuthToken)==null?void 0:C.call(l))}),[k,T]=y.useState(()=>{var _;const C=Pi(ji(f,(_=l.getAuthToken)==null?void 0:_.call(l)));return zo(C)}),E=y.useMemo(()=>Oi(k),[k]),[A,j]=y.useState(t),[P,L]=y.useState(!1),[$,V]=y.useState(!1),[M,G]=y.useState(null),[K,W]=y.useState(null),[z,B]=y.useState(null),ue=y.useCallback(()=>{const C=Pi(S);y.startTransition(()=>{T(zo(C))})},[S]),[D,te]=y.useState(!1),[he,we]=y.useState(!1),[ye,Se]=y.useState(null),[q,O]=y.useState(void 0),[X,ne]=y.useState(void 0),[pe,se]=y.useState(void 0),{state:me,dispatch:et,seed:tt,prepend:Pe,pushUser:Ve,onEvent:ut,reset:nt}=bc(),Ke=y.useRef(A);y.useEffect(()=>{Ke.current=A},[A]);const vt=y.useRef(!1),Q=y.useRef([]),ie=y.useRef(null),xe=y.useRef(null),Ce=y.useRef(new Map),ve=y.useRef(A),Oe=y.useRef(!1),at=y.useRef(null),Me=y.useRef(new Map),st=y.useRef(new Map),ft=y.useRef(new Map),It=y.useRef(new Map),Nn=y.useCallback(()=>{var de;const C=It.current;if(C.size<=Rc)return;const _=Array.from(C.entries()).sort((J,Z)=>J[1].timestamp-Z[1].timestamp),F=C.size-Rc;for(let J=0;J<F;J++){const Z=(de=_[J])==null?void 0:de[0];Z&&C.delete(Z)}},[]),dn=y.useCallback((C,_,F)=>{if(!C)return;const de=F==="replace"?[]:Me.current.get(C)??[],J=F==="replace"?_:[..._,...de];if(!J.length){F==="replace"&&Me.current.set(C,[]);return}const Z=new Map;for(const We of J){if(!(We!=null&&We.checkpointId))continue;const Le=`${We.checkpointId}::${We.checkpointNs??""}`;Z.has(Le)||Z.set(Le,We)}const ze=Array.from(Z.values()).sort((We,Le)=>{const ge=Number.isFinite(Date.parse(We.createdAt))?Date.parse(We.createdAt):0;return(Number.isFinite(Date.parse(Le.createdAt))?Date.parse(Le.createdAt):0)-ge});Me.current.set(C,ze)},[]),Zt=y.useCallback((C,_,F)=>{if(!C)return;const de=st.current.get(C),J=F==="replace"||!de?new Map:new Map(de);if(_&&typeof _=="object")for(const[Z,ze]of Object.entries(_)){if(!(ze!=null&&ze.checkpointId))continue;const We=Z||Fo(ze.checkpointId,ze.checkpointNs??null);J.set(We,ze)}st.current.set(C,J)},[]),An=y.useCallback((C,_)=>{const{threadId:F,checkpointId:de=null,checkpointNs:J=null}=C,Z=vx(F,de,J);if(_!=null&&_.force)ft.current.delete(Z),It.current.delete(Z);else{if(_!=null&&_.preferCache){const ge=It.current.get(Z);if(ge)return Promise.resolve(ge.payload)}const Le=ft.current.get(Z);if(Le)return Le}const We=l.getStateHistory({threadId:F,checkpointId:de??void 0,checkpointNs:J??void 0}).then(Le=>(It.current.set(Z,{payload:Le,timestamp:Date.now()}),Nn(),Le)).finally(()=>{ft.current.get(Z)===We&&ft.current.delete(Z)});return ft.current.set(Z,We),We},[l,Nn]),_n=y.useCallback((C,_)=>new Promise((F,de)=>{const J=async()=>{vt.current=!0;try{await C(),F()}catch(Z){de(Z)}finally{vt.current=!1;const Z=Q.current.shift();Z&&Z().catch(()=>{})}};vt.current?Q.current.push(J):J().catch(Z=>{de(Z)})}),[]),Qn=y.useRef(E.length),[To,fn]=y.useState(!1),hn=y.useRef(!1);y.useEffect(()=>{Qn.current=E.length},[E.length]),y.useEffect(()=>{const C=me.pendingInterrupt??wx(me.messages);bx(z,C)||B(C??null)},[z,me.messages,me.pendingInterrupt]);const Et=y.useCallback(async()=>{const C=Qn.current>0;C||L(!0);try{const _=await l.listThreads();y.startTransition(()=>{T(F=>{const de=ze=>ze.map(We=>`${We.threadId}:${We.updatedAt??""}:${We.messageCount??""}`).join("|"),J=Oi(F);return de(J)===de(_)||_.length===0&&J.length>0&&!hn.current?F:zo(_)})}),G(null),hn.current||(hn.current=!0,fn(!0))}catch(_){i==null||i(String(_)),console.error("[ChatSessionProvider] Failed to refresh threads:",_),G(String(_))}finally{C||L(!1)}},[l,i]),Ur=y.useRef(!1),yr=y.useRef(null),yt=y.useRef(null),jn=y.useRef(""),Rn=y.useCallback((C,_)=>{if(!Nr())return;yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null);const F=C.map(J=>`${J.threadId}:${J.updatedAt??""}:${J.messageCount??""}`).join("|");if(C.length===0){try{_i(S)}catch{}jn.current="";return}if(F===jn.current)return;const de=()=>{try{const J=C.slice(0,Ni);Ri(S,J),jn.current=F}catch{}finally{yt.current=null}};if(_!=null&&_.immediate){de();return}yt.current=window.setTimeout(()=>{Pc(de)},Bo)},[S]),Sr=y.useCallback(()=>{Rn(E,{immediate:!0})},[Rn,E]),Qt=y.useCallback((C,_,F,de)=>{const J=Array.isArray(C==null?void 0:C.messages)?C.messages:[],Z=F??(C==null?void 0:C.threadId)??Ke.current,ze=Z!=null&&Z===Ke.current,We=(C==null?void 0:C.pendingInterrupt)??null,Le=(de==null?void 0:de.persist)!==!1;if(_==="replace"){if(Le&&Z){const ge={threadId:Z,messages:J.slice(),hasMore:!!(C!=null&&C.hasMore),nextCursor:(C==null?void 0:C.nextCursor)??null,checkpointId:(C==null?void 0:C.checkpointId)??null,checkpointNs:(C==null?void 0:C.checkpointNs)??null,nextCursorNs:(C==null?void 0:C.nextCursorNs)??null,pendingInterrupt:We};Ce.current.set(Z,ge),ve.current=Z}if(!ze)return;tt(J,{checkpointId:(C==null?void 0:C.checkpointId)??null,checkpointNs:(C==null?void 0:C.checkpointNs)??null,pendingInterrupt:We}),B(We??null)}else if(_==="prepend"&&J.length&&Z){const ge=Ce.current.get(Z),Rt=(ge==null?void 0:ge.messages)??[],mn=new Set,en=[...J,...Rt].filter(kr=>{const tr=kr==null?void 0:kr.id;return tr?mn.has(tr)?!1:(mn.add(tr),!0):!0}),er={threadId:Z,messages:en,hasMore:(C==null?void 0:C.hasMore)??(ge==null?void 0:ge.hasMore)??!1,nextCursor:(C==null?void 0:C.nextCursor)??(ge==null?void 0:ge.nextCursor)??null,checkpointId:(ge==null?void 0:ge.checkpointId)??(C==null?void 0:C.checkpointId)??null,checkpointNs:(ge==null?void 0:ge.checkpointNs)??(C==null?void 0:C.checkpointNs)??null,nextCursorNs:(C==null?void 0:C.nextCursorNs)??(ge==null?void 0:ge.nextCursorNs)??null,pendingInterrupt:(ge==null?void 0:ge.pendingInterrupt)??We??null};if(Ce.current.set(Z,er),!ze)return;Pe(J)}else _==="prepend"&&J.length&&Pe(J);ze&&(_==="replace"?(Se((C==null?void 0:C.nextCursor)??null),te(!!(C!=null&&C.hasMore)),O((C==null?void 0:C.checkpointId)??void 0),ne((C==null?void 0:C.checkpointNs)??void 0),se((C==null?void 0:C.nextCursorNs)??void 0)):(Se(ge=>(C==null?void 0:C.nextCursor)??ge??null),te(ge=>(C==null?void 0:C.hasMore)!==void 0?!!(C!=null&&C.hasMore):ge),O(ge=>(C==null?void 0:C.checkpointId)??ge??void 0),ne(ge=>(C==null?void 0:C.checkpointNs)??ge??void 0),se(ge=>(C==null?void 0:C.nextCursorNs)!==void 0?C.nextCursorNs??void 0:ge)))},[Pe,tt,B]),Cr=y.useCallback(C=>{C.threadId!=null&&C.threadId!==Ke.current||(tt(C.messages,{checkpointId:C.checkpointId,checkpointNs:C.checkpointNs,pendingInterrupt:C.pendingInterrupt??null}),B(C.pendingInterrupt??null),Se(C.nextCursor),te(C.hasMore),O(C.checkpointId??void 0),ne(C.checkpointNs??void 0),se(C.nextCursorNs??void 0),ve.current=C.threadId)},[tt,B]),pn=y.useCallback(C=>{if(!C)return;Ce.current.delete(C),v(C),Me.current.delete(C),st.current.delete(C);const _=`${C}__`;for(const F of ft.current.keys())F.startsWith(_)&&ft.current.delete(F);for(const F of It.current.keys())F.startsWith(_)&&It.current.delete(F);ve.current===C&&(ve.current=null)},[v]),oe=y.useCallback(()=>{const C=Ke.current;C&&pn(C),nt([]),te(!1),we(!1),Se(null),O(void 0),ne(void 0),se(void 0)},[pn,nt]),ke=y.useCallback(({from:C,to:_})=>{const F=Ke.current;F&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${C} -> ${_}) for thread ${F}`)},[]),qe=y.useCallback(C=>{const _=C.threadId;console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:_,title:C.title,created:C.created,currentThreads:E.length});const F={threadId:_,title:C.title||`Thread ${_.slice(0,8)}`,createdAt:C.createdAt||new Date().toISOString(),updatedAt:C.updatedAt||new Date().toISOString(),messageCount:C.messageCount||0};Ke.current!==_&&(!Ke.current&&me.messages.length<=1&&(xe.current=_),j(_)),y.startTransition(()=>{T(de=>{const J=de.byId[_];return J?J.title===F.title&&J.updatedAt===F.updatedAt&&J.messageCount===F.messageCount?de:{byId:{...de.byId,[_]:F},order:de.order}:{byId:{...de.byId,[_]:F},order:[_,...de.order]}})})},[me.messages.length]),{startStream:it,stop:Mt,isStreaming:I,error:H,setAuthToken:re}=px({baseUrl:d,onThreadInfo:qe,onMessageEvent:ut,onUnhandledEvent:C=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${C.type}`,C)},onSequenceGap:ke});y.useEffect(()=>{Ur.current=I},[I]),y.useEffect(()=>{if(!Nr())return;yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null);const C=E.map(F=>`${F.threadId}:${F.updatedAt??""}:${F.messageCount??""}`).join("|");if(E.length===0){try{_i(S)}catch{}jn.current="";return}if(C===jn.current)return;const _=()=>{try{const F=E.slice(0,Ni);Ri(S,F),jn.current=C}catch{}finally{yt.current=null}};return yt.current=window.setTimeout(()=>{Pc(_),yt.current=null},Bo),()=>{yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null)}},[E,Rn]),y.useEffect(()=>{var de;const C=l.getAuthToken();re(C);const _=J=>{const Z=ji(f,J);at.current!==Z&&(at.current=Z,Oe.current=!1),N(Z);const ze=Pi(Z);y.startTransition(()=>{T(zo(ze))}),Oe.current||(Oe.current=!0,Et().catch(()=>{}))};_(C);const F=(de=l.onTokenChange)==null?void 0:de.call(l,J=>{re(J),w(),ft.current.clear(),It.current.clear(),_(J)});return()=>{F==null||F()}},[l,f,re,w,Et]);const Ee=y.useCallback(async C=>{var de;const _=`Thread ${(de=crypto.randomUUID)==null?void 0:de.call(crypto)}`,F={threadId:_,title:C||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};T(J=>({byId:{...J.byId,[_]:F},order:[_,...J.order]})),j(_);try{const J=await l.createThread(C),Z=typeof J=="string"?J:J.threadId;return T(ze=>{const We=ze.byId[_];if(!We)return ze;const Le={...ze.byId};delete Le[_],Le[Z]={...We,threadId:Z};const ge=ze.order.map(Rt=>Rt===_?Z:Rt);return{byId:Le,order:ge}}),j(Z),setTimeout(()=>Et(),10),G(null),Z}catch(J){throw T(Z=>{if(!Z.byId[_])return Z;const ze={...Z.byId};delete ze[_];const We=Z.order.filter(Le=>Le!==_);return{byId:ze,order:We}}),j(null),G(String(J)),J}},[l,Et]),Be=y.useCallback(async C=>{try{await l.deleteThread(C);let _=null;T(F=>{if(!F.byId[C])return F;const de={...F.byId};delete de[C];const J=F.order.filter(ze=>ze!==C),Z={byId:de,order:J};return _=Oi(Z),Z}),_&&Rn(_,{immediate:!0}),pn(C),Ke.current===C&&(xe.current=C,j(null),Ke.current=null,ve.current=null,oe()),await Et(),G(null)}catch(_){throw G(String(_)),_}},[l,oe,pn,Et,Rn]),Xe=y.useCallback(async(C,_)=>{try{await l.updateThread(C,_),T(F=>{const de=F.byId[C];return de?{byId:{...F.byId,[C]:{...de,title:_}},order:F.order}:F}),G(null)}catch(F){throw await Et(),G(String(F)),F}},[l,Et]),De=y.useCallback(async(C,_,F,de=!1)=>{await _n(async()=>{if(xe.current===C&&!de){xe.current=null;return}if(ie.current===C&&!de)return;j(Le=>Le===C?Le:C),Ke.current=C;const J=!de&&!_&&!F;let Z=!1;if(J){const Le=Ce.current.get(C);if(Le)Cr(Le),Z=!0;else{const ge=x(C);ge&&(Ce.current.set(C,ge),Cr(ge),Z=!0)}}const ze=de||!Z||!!_||!!F,We=async Le=>{Le&&V(!0),ie.current=C;try{const ge=await An({threadId:C,checkpointId:_,checkpointNs:F},{force:de}),{payload:Rt,checkpoints:mn,snapshots:en}=Ti(ge);Qt(Rt,"replace",C),dn(C,mn,"replace"),Zt(C,en,"replace"),W(null)}catch(ge){throw(!Z||de||Le)&&(i==null||i(String(ge))),W(String(ge)),ge}finally{ie.current=null,Le&&V(!1)}};ze?await We(!0):J&&Z&&We(!1).catch(Le=>{console.warn("[ChatSessionProvider] Background refresh failed:",Le)})},`loadThread-${C}`)},[Cr,Qt,_n,An,i,dn,Zt]),Ue=y.useCallback(async()=>{await _n(async()=>{const C=Ke.current;C&&pn(C),xe.current=null,j(null),Ke.current=null,ve.current=null,oe(),O(void 0),ne(void 0),se(void 0);try{localStorage.removeItem("lastThreadId")}catch(_){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",_)}},"clearCurrentThread")},[oe,pn,_n]),kt=y.useCallback(async C=>{const _=Me.current.get(C);if(_)return{threadId:C,checkpoints:_.slice()};const F=await An({threadId:C},{preferCache:!0}),{checkpoints:de,snapshots:J}=Ti(F);dn(C,de,"replace"),Zt(C,J,"replace");const Z=Me.current.get(C)??[];return{threadId:C,checkpoints:Z.slice()}},[An,dn,Zt]),ht=y.useCallback(async(C,_)=>{var Z;const F=Ke.current;if(!F)throw new Error("No active thread");const de=Fo(C,_??null),J=(Z=st.current.get(F))==null?void 0:Z.get(de);if(J){await _n(async()=>{Qt({threadId:F,checkpointId:J.checkpointId??void 0,checkpointNs:J.checkpointNs??void 0,messages:J.messages??[],hasMore:!!J.nextCursor,nextCursor:J.nextCursor??null,nextCursorNs:J.nextCursorNs??null,pendingInterrupt:J.interrupt??null},"replace",F,{persist:!1})},`navigateToCheckpoint-${F}-${de}`);return}await De(F,C,_??void 0,!0)},[Qt,_n,De]),mt=y.useCallback(async()=>{if(!Ke.current)throw new Error("No active thread");await De(Ke.current,void 0,void 0,!0)},[De]),Dt=y.useCallback(async()=>{if(!Ke.current)throw new Error("No active thread");if(he||!D)return;const C=ye;if(C){we(!0);try{const _=Ke.current,F=await An({threadId:_,checkpointId:C??q??null,checkpointNs:pe??X??null}),{payload:de,checkpoints:J,snapshots:Z}=Ti(F);Qt(de,"prepend",_??void 0),_&&(dn(_,J,"prepend"),Zt(_,Z,"prepend")),W(null)}catch(_){throw W(String(_)),_}finally{we(!1)}}},[Qt,An,D,q,X,pe,ye,he,dn,Zt]),$n=y.useCallback(C=>{if(!(C!=null&&C.threadId))return;const _={threadId:C.threadId,checkpointId:C.checkpointId??void 0,checkpointNs:C.checkpointNs??void 0,messages:C.messages??[],hasMore:C.hasMore,nextCursor:C.nextCursor??null,nextCursorNs:C.nextCursorNs??null,pendingInterrupt:C.pendingInterrupt??null};if(C.checkpointId){const F=Fo(C.checkpointId,C.checkpointNs??null);Zt(C.threadId,{[F]:{messages:C.messages??[],checkpointId:C.checkpointId??null,checkpointNs:C.checkpointNs??null,nextCursor:C.nextCursor??null,nextCursorNs:C.nextCursorNs??null,interrupt:C.pendingInterrupt??null}},"prepend")}Qt(_,"replace",C.threadId)},[Qt,Zt]),Pn=y.useCallback(async(C,_)=>{var ii;const F=Ke.current,de=(C==null?void 0:C.text)??"",J=(C==null?void 0:C.attachments)??[],Z=J.length?J:(_==null?void 0:_.attachments)??[],ze={...(_==null?void 0:_.payloadExtras)??{},...(C==null?void 0:C.payload)??{}};if(!F&&!Object.keys(ze).length&&Z.length===0&&!de.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!F&&!ze.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:We,filesInfo:Le}=await Vg(l,Z),ge=[...We];de&&de.trim()&&ge.push({type:"text",text:de.trim()});const Rt=!!F,mn=Rt?(_==null?void 0:_.checkpointId)??me.lastCheckpointId??void 0:void 0,en=Rt?(_==null?void 0:_.checkpointNs)??me.lastCheckpointNs??void 0:void 0,er={id:((ii=crypto.randomUUID)==null?void 0:ii.call(crypto))||`user-${Date.now()}`,role:"user",content:ge,createdAt:new Date().toISOString(),...mn!=null?{checkpointId:mn}:{},...en!=null?{checkpointNs:en}:{}};ge.length>0&&Ve(er);const kr={...er,content:ge},tr=Z.length>0,si={...F?{threadId:F}:{},payload:{messages:ge.length>0?[kr]:[],files_info:Le,...o&&tr&&s?{active_agent:s}:{},...ze},...mn!=null?{checkpointId:mn}:{},...en!=null?{checkpointNs:en}:{},nodeFilter:_==null?void 0:_.nodeFilter,config:_==null?void 0:_.config};it(si,{onError:Fn=>{console.warn("[ChatSessionProvider] Stream error:",Fn)},onOpen:({threadId:Fn})=>{!Ke.current&&Fn&&(me.messages.length<=1&&(xe.current=Fn),j(Fn))},onGap:ke})},[l,o,s,ke,me.lastCheckpointId,me.lastCheckpointNs,me.messages.length,Ve,it]),St=y.useCallback(async(C,_,F)=>{var J,Z;const de=Ke.current;if(!de)throw new Error("No active thread to handle interrupt");try{const ze=_?F??!0:!1;try{et({type:"interrupt_response",payload:{interruptId:C}})}catch(er){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",er)}const We=`${d}/runs/resume`,Le=(J=l.getAuthToken)==null?void 0:J.call(l),ge=await fetch(We,{method:"POST",headers:{"Content-Type":"application/json",...Le?{Authorization:`Bearer ${Le}`}:{}},body:JSON.stringify({thread_id:de,value:ze})});if(!ge.ok)throw new Error(`Resume failed with status ${ge.status}`);const Rt=(Z=ge.body)==null?void 0:Z.getReader();if(!Rt)throw new Error("No response body for resume stream");const mn=new TextDecoder;let en="";for(;;){const{done:er,value:kr}=await Rt.read();if(er)break;en+=mn.decode(kr,{stream:!0});const tr=en.split(`
|
|
38
|
+
`)}function px({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o}){const s=y.useRef(null),i=y.useCallback(p=>{const b=p.seq??null;if(b!==null){const x=s.current;if(x!==null){if(b<=x)return;b>x+1&&(o==null||o({from:x,to:b}))}s.current=b}if(p.type==="thread_info"){console.log("[useChatStreamingService] 🎯 Received thread_info event:",p),t(p);return}if(ix(p)){n(p);return}r==null||r(p)},[n,o,t,r]),{stream:a,stop:l,isStreaming:u,error:d,setToken:f}=Nc({baseUrl:e,token:null}),h=y.useCallback((p,b)=>{s.current=null,a(p,i,{onOpen:b==null?void 0:b.onOpen,onError:x=>{var g;(g=b==null?void 0:b.onError)==null||g.call(b,x)},onGap:(b==null?void 0:b.onGap)??o})},[i,o,a]);return y.useMemo(()=>({startStream:h,stop:l,isStreaming:u,error:d,setAuthToken:f}),[h,l,u,d,f])}const Ac=y.createContext(null),_c=y.createContext(null),jc=y.createContext(null),mx=y.createContext(!1),gx="cachedThreads",xx="v1",Bo=300,Ni=200,Rc=50;function vx(e,t,n){return`${e}__${t??""}__${n??""}`}function bx(e,t){if(!e&&!t)return!0;if(!e||!t||e.id!==t.id)return!1;try{return JSON.stringify(e.value)===JSON.stringify(t.value)}catch{return e.value===t.value}}function wx(e){var t;for(let n=e.length-1;n>=0;n--){const r=((t=e[n])==null?void 0:t.content)??[];for(let o=r.length-1;o>=0;o--){const s=r[o];if((s==null?void 0:s.type)==="interrupt"){const i=s.id;return{id:(typeof i=="string"?i:null)??`interrupt-${e[n].id??o}`,value:s.value}}}}return null}function Pc(e){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:1e3});return}catch{}window.setTimeout(e,Bo)}function Nr(){return typeof window<"u"&&typeof window.localStorage<"u"}function Ai(e){if(!Nr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function Oc(e,t){if(Nr())try{window.localStorage.setItem(e,t)}catch{}}function _i(e){if(Nr())try{window.localStorage.removeItem(e)}catch{}}function yx(){const e=Ai(gx);if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>{if(!n||typeof n!="object")return!1;const r=n;return typeof r.threadId=="string"&&typeof r.title=="string"}):[]}catch{return[]}}function Sx(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(36)}function ji(e,t){return`cachedThreads:v1:${e}:${Sx(t||"anon")}`}function Cx(e){const t=Ai(e);if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>{if(!r||typeof r!="object")return!1;const o=r;return typeof o.threadId=="string"&&typeof o.title=="string"}):[]}catch{return[]}}function Ri(e,t){try{Oc(e,JSON.stringify(t))}catch{}}function Pi(e){const t=Cx(e);if(t.length>0)return t;const n=yx();if(n.length>0)try{Ri(e,n.slice(0,Ni))}catch{}return n}function zo(e){const t={},n=[];for(const r of e)!r||typeof r.threadId!="string"||t[r.threadId]||(t[r.threadId]=r,n.push(r.threadId));return{byId:t,order:n}}function Oi(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function kx({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader",onError:i,onThreadChange:a}){const{api:l,baseUrl:u}=Ci(),d=y.useMemo(()=>On(u),[u]),f=y.useMemo(()=>{try{return new URL(u).host}catch{return"unknown"}},[u]),h=y.useMemo(()=>`threadPayload:${xx}:${f}:`,[f]),p=y.useCallback(C=>`${h}${C}`,[h]),b=y.useCallback(C=>{if(!C||typeof C!="object")return null;const _=C;return typeof _.threadId!="string"||!Array.isArray(_.messages)?null:{threadId:_.threadId,messages:_.messages,hasMore:!!_.hasMore,nextCursor:_.nextCursor??null,checkpointId:_.checkpointId??null,checkpointNs:_.checkpointNs??null,nextCursorNs:_.nextCursorNs??null,pendingInterrupt:_.pendingInterrupt??null}},[]),x=y.useCallback(C=>{const _=Ai(p(C));if(!_)return null;try{const F=JSON.parse(_);return b(F)}catch{return null}},[p,b]),g=y.useCallback((C,_=100)=>{const F={...C,messages:Array.isArray(C.messages)?C.messages.slice(-_):[]};try{Oc(p(C.threadId),JSON.stringify(F))}catch{}},[p]),v=y.useCallback(C=>{_i(p(C))},[p]),w=y.useCallback(()=>{if(Nr())try{const C=h;for(let _=0;_<window.localStorage.length;_++){const F=window.localStorage.key(_);F&&F.startsWith(C)&&window.localStorage.removeItem(F)}}catch{}},[h]),[S,N]=y.useState(()=>{var C;return ji(f,(C=l.getAuthToken)==null?void 0:C.call(l))}),[k,T]=y.useState(()=>{var _;const C=Pi(ji(f,(_=l.getAuthToken)==null?void 0:_.call(l)));return zo(C)}),E=y.useMemo(()=>Oi(k),[k]),[A,j]=y.useState(t),[P,L]=y.useState(!1),[$,V]=y.useState(!1),[M,G]=y.useState(null),[K,W]=y.useState(null),[z,B]=y.useState(null),ue=y.useCallback(()=>{const C=Pi(S);y.startTransition(()=>{T(zo(C))})},[S]),[D,te]=y.useState(!1),[he,we]=y.useState(!1),[ye,Se]=y.useState(null),[q,O]=y.useState(void 0),[X,ne]=y.useState(void 0),[pe,se]=y.useState(void 0),{state:me,dispatch:et,seed:tt,prepend:Pe,pushUser:Ve,onEvent:ut,reset:nt}=bc(),Ke=y.useRef(A);y.useEffect(()=>{Ke.current=A},[A]);const vt=y.useRef(!1),Q=y.useRef([]),ie=y.useRef(null),xe=y.useRef(null),Ce=y.useRef(new Map),ve=y.useRef(A),Oe=y.useRef(!1),at=y.useRef(null),Me=y.useRef(new Map),st=y.useRef(new Map),ft=y.useRef(new Map),It=y.useRef(new Map),Nn=y.useCallback(()=>{var de;const C=It.current;if(C.size<=Rc)return;const _=Array.from(C.entries()).sort((J,Z)=>J[1].timestamp-Z[1].timestamp),F=C.size-Rc;for(let J=0;J<F;J++){const Z=(de=_[J])==null?void 0:de[0];Z&&C.delete(Z)}},[]),dn=y.useCallback((C,_,F)=>{if(!C)return;const de=F==="replace"?[]:Me.current.get(C)??[],J=F==="replace"?_:[..._,...de];if(!J.length){F==="replace"&&Me.current.set(C,[]);return}const Z=new Map;for(const We of J){if(!(We!=null&&We.checkpointId))continue;const Le=`${We.checkpointId}::${We.checkpointNs??""}`;Z.has(Le)||Z.set(Le,We)}const ze=Array.from(Z.values()).sort((We,Le)=>{const ge=Number.isFinite(Date.parse(We.createdAt))?Date.parse(We.createdAt):0;return(Number.isFinite(Date.parse(Le.createdAt))?Date.parse(Le.createdAt):0)-ge});Me.current.set(C,ze)},[]),Zt=y.useCallback((C,_,F)=>{if(!C)return;const de=st.current.get(C),J=F==="replace"||!de?new Map:new Map(de);if(_&&typeof _=="object")for(const[Z,ze]of Object.entries(_)){if(!(ze!=null&&ze.checkpointId))continue;const We=Z||Fo(ze.checkpointId,ze.checkpointNs??null);J.set(We,ze)}st.current.set(C,J)},[]),An=y.useCallback((C,_)=>{const{threadId:F,checkpointId:de=null,checkpointNs:J=null}=C,Z=vx(F,de,J);if(_!=null&&_.force)ft.current.delete(Z),It.current.delete(Z);else{if(_!=null&&_.preferCache){const ge=It.current.get(Z);if(ge)return Promise.resolve(ge.payload)}const Le=ft.current.get(Z);if(Le)return Le}const We=l.getStateHistory({threadId:F,checkpointId:de??void 0,checkpointNs:J??void 0}).then(Le=>(It.current.set(Z,{payload:Le,timestamp:Date.now()}),Nn(),Le)).finally(()=>{ft.current.get(Z)===We&&ft.current.delete(Z)});return ft.current.set(Z,We),We},[l,Nn]),_n=y.useCallback((C,_)=>new Promise((F,de)=>{const J=async()=>{vt.current=!0;try{await C(),F()}catch(Z){de(Z)}finally{vt.current=!1;const Z=Q.current.shift();Z&&Z().catch(()=>{})}};vt.current?Q.current.push(J):J().catch(Z=>{de(Z)})}),[]),Qn=y.useRef(E.length),[To,fn]=y.useState(!1),hn=y.useRef(!1);y.useEffect(()=>{Qn.current=E.length},[E.length]),y.useEffect(()=>{const C=me.pendingInterrupt??wx(me.messages);bx(z,C)||B(C??null)},[z,me.messages,me.pendingInterrupt]);const Et=y.useCallback(async()=>{const C=Qn.current>0;C||L(!0);try{const _=await l.listThreads();y.startTransition(()=>{T(F=>{const de=ze=>ze.map(We=>`${We.threadId}:${We.updatedAt??""}:${We.messageCount??""}`).join("|"),J=Oi(F);return de(J)===de(_)||_.length===0&&J.length>0&&!hn.current?F:zo(_)})}),G(null),hn.current||(hn.current=!0,fn(!0))}catch(_){i==null||i(String(_)),console.error("[ChatSessionProvider] Failed to refresh threads:",_),G(String(_))}finally{C||L(!1)}},[l,i]),Ur=y.useRef(!1),yr=y.useRef(null),yt=y.useRef(null),jn=y.useRef(""),Rn=y.useCallback((C,_)=>{if(!Nr())return;yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null);const F=C.map(J=>`${J.threadId}:${J.updatedAt??""}:${J.messageCount??""}`).join("|");if(C.length===0){try{_i(S)}catch{}jn.current="";return}if(F===jn.current)return;const de=()=>{try{const J=C.slice(0,Ni);Ri(S,J),jn.current=F}catch{}finally{yt.current=null}};if(_!=null&&_.immediate){de();return}yt.current=window.setTimeout(()=>{Pc(de)},Bo)},[S]),Sr=y.useCallback(()=>{Rn(E,{immediate:!0})},[Rn,E]),Qt=y.useCallback((C,_,F,de)=>{const J=Array.isArray(C==null?void 0:C.messages)?C.messages:[],Z=F??(C==null?void 0:C.threadId)??Ke.current,ze=Z!=null&&Z===Ke.current,We=(C==null?void 0:C.pendingInterrupt)??null,Le=(de==null?void 0:de.persist)!==!1;if(_==="replace"){if(Le&&Z){const ge={threadId:Z,messages:J.slice(),hasMore:!!(C!=null&&C.hasMore),nextCursor:(C==null?void 0:C.nextCursor)??null,checkpointId:(C==null?void 0:C.checkpointId)??null,checkpointNs:(C==null?void 0:C.checkpointNs)??null,nextCursorNs:(C==null?void 0:C.nextCursorNs)??null,pendingInterrupt:We};Ce.current.set(Z,ge),ve.current=Z}if(!ze)return;tt(J,{checkpointId:(C==null?void 0:C.checkpointId)??null,checkpointNs:(C==null?void 0:C.checkpointNs)??null,pendingInterrupt:We}),B(We??null)}else if(_==="prepend"&&J.length&&Z){const ge=Ce.current.get(Z),Rt=(ge==null?void 0:ge.messages)??[],mn=new Set,en=[...J,...Rt].filter(kr=>{const tr=kr==null?void 0:kr.id;return tr?mn.has(tr)?!1:(mn.add(tr),!0):!0}),er={threadId:Z,messages:en,hasMore:(C==null?void 0:C.hasMore)??(ge==null?void 0:ge.hasMore)??!1,nextCursor:(C==null?void 0:C.nextCursor)??(ge==null?void 0:ge.nextCursor)??null,checkpointId:(ge==null?void 0:ge.checkpointId)??(C==null?void 0:C.checkpointId)??null,checkpointNs:(ge==null?void 0:ge.checkpointNs)??(C==null?void 0:C.checkpointNs)??null,nextCursorNs:(C==null?void 0:C.nextCursorNs)??(ge==null?void 0:ge.nextCursorNs)??null,pendingInterrupt:(ge==null?void 0:ge.pendingInterrupt)??We??null};if(Ce.current.set(Z,er),!ze)return;Pe(J)}else _==="prepend"&&J.length&&Pe(J);ze&&(_==="replace"?(Se((C==null?void 0:C.nextCursor)??null),te(!!(C!=null&&C.hasMore)),O((C==null?void 0:C.checkpointId)??void 0),ne((C==null?void 0:C.checkpointNs)??void 0),se((C==null?void 0:C.nextCursorNs)??void 0)):(Se(ge=>(C==null?void 0:C.nextCursor)??ge??null),te(ge=>(C==null?void 0:C.hasMore)!==void 0?!!(C!=null&&C.hasMore):ge),O(ge=>(C==null?void 0:C.checkpointId)??ge??void 0),ne(ge=>(C==null?void 0:C.checkpointNs)??ge??void 0),se(ge=>(C==null?void 0:C.nextCursorNs)!==void 0?C.nextCursorNs??void 0:ge)))},[Pe,tt,B]),Cr=y.useCallback(C=>{C.threadId!=null&&C.threadId!==Ke.current||(tt(C.messages,{checkpointId:C.checkpointId,checkpointNs:C.checkpointNs,pendingInterrupt:C.pendingInterrupt??null}),B(C.pendingInterrupt??null),Se(C.nextCursor),te(C.hasMore),O(C.checkpointId??void 0),ne(C.checkpointNs??void 0),se(C.nextCursorNs??void 0),ve.current=C.threadId)},[tt,B]),pn=y.useCallback(C=>{if(!C)return;Ce.current.delete(C),v(C),Me.current.delete(C),st.current.delete(C);const _=`${C}__`;for(const F of ft.current.keys())F.startsWith(_)&&ft.current.delete(F);for(const F of It.current.keys())F.startsWith(_)&&It.current.delete(F);ve.current===C&&(ve.current=null)},[v]),oe=y.useCallback(()=>{const C=Ke.current;C&&pn(C),nt([]),te(!1),we(!1),Se(null),O(void 0),ne(void 0),se(void 0)},[pn,nt]),ke=y.useCallback(({from:C,to:_})=>{const F=Ke.current;F&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${C} -> ${_}) for thread ${F}`)},[]),qe=y.useCallback(C=>{const _=C.threadId;console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:_,title:C.title,created:C.created,currentThreads:E.length});const F={threadId:_,title:C.title||`Thread ${_.slice(0,8)}`,createdAt:C.createdAt||new Date().toISOString(),updatedAt:C.updatedAt||new Date().toISOString(),messageCount:C.messageCount||0};Ke.current!==_&&(!Ke.current&&me.messages.length<=1&&(xe.current=_),j(_)),y.startTransition(()=>{T(de=>{const J=de.byId[_];return J?J.title===F.title&&J.updatedAt===F.updatedAt&&J.messageCount===F.messageCount?de:{byId:{...de.byId,[_]:F},order:de.order}:{byId:{...de.byId,[_]:F},order:[_,...de.order]}})})},[me.messages.length]),{startStream:it,stop:Mt,isStreaming:I,error:H,setAuthToken:re}=px({baseUrl:d,onThreadInfo:qe,onMessageEvent:ut,onUnhandledEvent:C=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${C.type}`,C)},onSequenceGap:ke});y.useEffect(()=>{Ur.current=I},[I]),y.useEffect(()=>{if(!Nr())return;yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null);const C=E.map(F=>`${F.threadId}:${F.updatedAt??""}:${F.messageCount??""}`).join("|");if(E.length===0){try{_i(S)}catch{}jn.current="";return}if(C===jn.current)return;const _=()=>{try{const F=E.slice(0,Ni);Ri(S,F),jn.current=C}catch{}finally{yt.current=null}};return yt.current=window.setTimeout(()=>{Pc(_),yt.current=null},Bo),()=>{yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null)}},[E,Rn]),y.useEffect(()=>{var de;const C=l.getAuthToken();re(C);const _=J=>{const Z=ji(f,J);at.current!==Z&&(at.current=Z,Oe.current=!1),N(Z);const ze=Pi(Z);y.startTransition(()=>{T(zo(ze))}),Oe.current||(Oe.current=!0,Et().catch(()=>{}))};_(C);const F=(de=l.onTokenChange)==null?void 0:de.call(l,J=>{re(J),w(),ft.current.clear(),It.current.clear(),_(J)});return()=>{F==null||F()}},[l,f,re,w,Et]);const Ee=y.useCallback(async C=>{var de;const _=`Thread ${(de=crypto.randomUUID)==null?void 0:de.call(crypto)}`,F={threadId:_,title:C||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};T(J=>({byId:{...J.byId,[_]:F},order:[_,...J.order]})),j(_);try{const J=await l.createThread(C),Z=typeof J=="string"?J:J.threadId;return T(ze=>{const We=ze.byId[_];if(!We)return ze;const Le={...ze.byId};delete Le[_],Le[Z]={...We,threadId:Z};const ge=ze.order.map(Rt=>Rt===_?Z:Rt);return{byId:Le,order:ge}}),j(Z),setTimeout(()=>Et(),10),G(null),Z}catch(J){throw T(Z=>{if(!Z.byId[_])return Z;const ze={...Z.byId};delete ze[_];const We=Z.order.filter(Le=>Le!==_);return{byId:ze,order:We}}),j(null),G(String(J)),J}},[l,Et]),Be=y.useCallback(async C=>{try{await l.deleteThread(C);let _=null;T(F=>{if(!F.byId[C])return F;const de={...F.byId};delete de[C];const J=F.order.filter(ze=>ze!==C),Z={byId:de,order:J};return _=Oi(Z),Z}),_&&Rn(_,{immediate:!0}),pn(C),Ke.current===C&&(xe.current=C,j(null),Ke.current=null,ve.current=null,oe()),await Et(),G(null)}catch(_){throw G(String(_)),_}},[l,oe,pn,Et,Rn]),Xe=y.useCallback(async(C,_)=>{try{await l.updateThread(C,_),T(F=>{const de=F.byId[C];return de?{byId:{...F.byId,[C]:{...de,title:_}},order:F.order}:F}),G(null)}catch(F){throw await Et(),G(String(F)),F}},[l,Et]),De=y.useCallback(async(C,_,F,de=!1)=>{await _n(async()=>{if(xe.current===C&&!de){xe.current=null;return}if(ie.current===C&&!de)return;j(Le=>Le===C?Le:C),Ke.current=C;const J=!de&&!_&&!F;let Z=!1;if(J){const Le=Ce.current.get(C);if(Le)Cr(Le),Z=!0;else{const ge=x(C);ge&&(Ce.current.set(C,ge),Cr(ge),Z=!0)}}const ze=de||!Z||!!_||!!F,We=async Le=>{Le&&V(!0),ie.current=C;try{const ge=await An({threadId:C,checkpointId:_,checkpointNs:F},{force:de}),{payload:Rt,checkpoints:mn,snapshots:en}=Ti(ge);Qt(Rt,"replace",C),dn(C,mn,"replace"),Zt(C,en,"replace"),W(null)}catch(ge){throw(!Z||de||Le)&&(i==null||i(String(ge))),W(String(ge)),ge}finally{ie.current=null,Le&&V(!1)}};ze?await We(!0):J&&Z&&We(!1).catch(Le=>{console.warn("[ChatSessionProvider] Background refresh failed:",Le)})},`loadThread-${C}`)},[Cr,Qt,_n,An,i,dn,Zt]),Ue=y.useCallback(async()=>{await _n(async()=>{const C=Ke.current;C&&pn(C),xe.current=null,j(null),Ke.current=null,ve.current=null,oe(),O(void 0),ne(void 0),se(void 0);try{localStorage.removeItem("lastThreadId")}catch(_){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",_)}},"clearCurrentThread")},[oe,pn,_n]),kt=y.useCallback(async C=>{const _=Me.current.get(C);if(_)return{threadId:C,checkpoints:_.slice()};const F=await An({threadId:C},{preferCache:!0}),{checkpoints:de,snapshots:J}=Ti(F);dn(C,de,"replace"),Zt(C,J,"replace");const Z=Me.current.get(C)??[];return{threadId:C,checkpoints:Z.slice()}},[An,dn,Zt]),ht=y.useCallback(async(C,_)=>{var Z;const F=Ke.current;if(!F)throw new Error("No active thread");const de=Fo(C,_??null),J=(Z=st.current.get(F))==null?void 0:Z.get(de);if(J){await _n(async()=>{Qt({threadId:F,checkpointId:J.checkpointId??void 0,checkpointNs:J.checkpointNs??void 0,messages:J.messages??[],hasMore:!!J.nextCursor,nextCursor:J.nextCursor??null,nextCursorNs:J.nextCursorNs??null,pendingInterrupt:J.interrupt??null},"replace",F,{persist:!1})},`navigateToCheckpoint-${F}-${de}`);return}await De(F,C,_??void 0,!0)},[Qt,_n,De]),mt=y.useCallback(async()=>{if(!Ke.current)throw new Error("No active thread");await De(Ke.current,void 0,void 0,!0)},[De]),Dt=y.useCallback(async()=>{if(!Ke.current)throw new Error("No active thread");if(he||!D)return;const C=ye;if(C){we(!0);try{const _=Ke.current,F=await An({threadId:_,checkpointId:C??q??null,checkpointNs:pe??X??null}),{payload:de,checkpoints:J,snapshots:Z}=Ti(F);Qt(de,"prepend",_??void 0),_&&(dn(_,J,"prepend"),Zt(_,Z,"prepend")),W(null)}catch(_){throw W(String(_)),_}finally{we(!1)}}},[Qt,An,D,q,X,pe,ye,he,dn,Zt]),$n=y.useCallback(C=>{if(!(C!=null&&C.threadId))return;const _={threadId:C.threadId,checkpointId:C.checkpointId??void 0,checkpointNs:C.checkpointNs??void 0,messages:C.messages??[],hasMore:C.hasMore,nextCursor:C.nextCursor??null,nextCursorNs:C.nextCursorNs??null,pendingInterrupt:C.interrupt??null};if(C.checkpointId){const F=Fo(C.checkpointId,C.checkpointNs??null);Zt(C.threadId,{[F]:{messages:C.messages??[],checkpointId:C.checkpointId??null,checkpointNs:C.checkpointNs??null,nextCursor:C.nextCursor??null,nextCursorNs:C.nextCursorNs??null,interrupt:C.interrupt??null}},"prepend")}Qt(_,"replace",C.threadId)},[Qt,Zt]),Pn=y.useCallback(async(C,_)=>{var ii;const F=Ke.current,de=(C==null?void 0:C.text)??"",J=(C==null?void 0:C.attachments)??[],Z=J.length?J:(_==null?void 0:_.attachments)??[],ze={...(_==null?void 0:_.payloadExtras)??{},...(C==null?void 0:C.payload)??{}};if(!F&&!Object.keys(ze).length&&Z.length===0&&!de.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!F&&!ze.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:We,filesInfo:Le}=await Vg(l,Z),ge=[...We];de&&de.trim()&&ge.push({type:"text",text:de.trim()});const Rt=!!F,mn=Rt?(_==null?void 0:_.checkpointId)??me.lastCheckpointId??void 0:void 0,en=Rt?(_==null?void 0:_.checkpointNs)??me.lastCheckpointNs??void 0:void 0,er={id:((ii=crypto.randomUUID)==null?void 0:ii.call(crypto))||`user-${Date.now()}`,role:"user",content:ge,createdAt:new Date().toISOString(),...mn!=null?{checkpointId:mn}:{},...en!=null?{checkpointNs:en}:{}};ge.length>0&&Ve(er);const kr={...er,content:ge},tr=Z.length>0,si={...F?{threadId:F}:{},payload:{messages:ge.length>0?[kr]:[],files_info:Le,...o&&tr&&s?{active_agent:s}:{},...ze},...mn!=null?{checkpointId:mn}:{},...en!=null?{checkpointNs:en}:{},nodeFilter:_==null?void 0:_.nodeFilter,config:_==null?void 0:_.config};it(si,{onError:Fn=>{console.warn("[ChatSessionProvider] Stream error:",Fn)},onOpen:({threadId:Fn})=>{!Ke.current&&Fn&&(me.messages.length<=1&&(xe.current=Fn),j(Fn))},onGap:ke})},[l,o,s,ke,me.lastCheckpointId,me.lastCheckpointNs,me.messages.length,Ve,it]),St=y.useCallback(async(C,_,F)=>{var J,Z;const de=Ke.current;if(!de)throw new Error("No active thread to handle interrupt");try{const ze=_?F??!0:!1;try{et({type:"interrupt_response",payload:{interruptId:C}})}catch(er){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",er)}const We=`${d}/runs/resume`,Le=(J=l.getAuthToken)==null?void 0:J.call(l),ge=await fetch(We,{method:"POST",headers:{"Content-Type":"application/json",...Le?{Authorization:`Bearer ${Le}`}:{}},body:JSON.stringify({thread_id:de,value:ze})});if(!ge.ok)throw new Error(`Resume failed with status ${ge.status}`);const Rt=(Z=ge.body)==null?void 0:Z.getReader();if(!Rt)throw new Error("No response body for resume stream");const mn=new TextDecoder;let en="";for(;;){const{done:er,value:kr}=await Rt.read();if(er)break;en+=mn.decode(kr,{stream:!0});const tr=en.split(`
|
|
39
39
|
`);en=tr.pop()||"";for(const si of tr)if(si.startsWith("data: ")){const ii=si.slice(6);try{const Fn=JSON.parse(ii);et({type:"event",payload:{ev:Fn}})}catch(Fn){console.warn("[ChatSessionProvider] Failed to parse resume SSE event:",Fn)}}}B(null)}catch(ze){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${C}:`,ze),ze}},[l,et,d]),Wr=y.useCallback(C=>St(C.interruptId,C.approved,C.value),[St]);y.useEffect(()=>{if(a==null||a(A),A)try{localStorage.setItem("lastThreadId",A)}catch(C){console.warn("[ChatSessionProvider] Failed to persist lastThreadId:",C)}},[A,a]),y.useEffect(()=>((async()=>{try{if(Et().catch(_=>{console.error("[ChatSessionProvider] Failed to refresh threads (background):",_),i==null||i(String(_))}),!r&&!t)try{const _=localStorage.getItem("lastThreadId");_&&(j(_),n&&await De(_))}catch(_){console.warn("[ChatSessionProvider] Failed to restore last thread:",_)}else t&&n&&await De(t)}catch(_){console.error("[ChatSessionProvider] Initialization failed:",_),i==null||i(String(_))}})(),()=>{}),[]),y.useEffect(()=>{var J,Z,ze,We;const C=Ke.current;if(!C||ve.current!==C)return;const _={threadId:C,messages:me.messages.slice(),hasMore:D,nextCursor:ye,checkpointId:me.lastCheckpointId??null,checkpointNs:me.lastCheckpointNs??null,nextCursorNs:pe??null,pendingInterrupt:me.pendingInterrupt??z??null},F=Ce.current.get(C);(!F||F.messages.length!==_.messages.length||F.messages.some((Le,ge)=>{var Rt;return(Le==null?void 0:Le.id)!==((Rt=_.messages[ge])==null?void 0:Rt.id)})||(F==null?void 0:F.hasMore)!==_.hasMore||(F==null?void 0:F.nextCursor)!==_.nextCursor||(F==null?void 0:F.nextCursorNs)!==_.nextCursorNs||(F==null?void 0:F.checkpointId)!==_.checkpointId||(F==null?void 0:F.checkpointNs)!==_.checkpointNs||(((J=F==null?void 0:F.pendingInterrupt)==null?void 0:J.id)??null)!==(((Z=_.pendingInterrupt)==null?void 0:Z.id)??null)||JSON.stringify((ze=F==null?void 0:F.pendingInterrupt)==null?void 0:ze.value)!==JSON.stringify((We=_.pendingInterrupt)==null?void 0:We.value))&&(Ce.current.set(C,_),yr.current&&window.clearTimeout(yr.current),yr.current=window.setTimeout(()=>{try{g(_,100)}catch(Le){console.warn("[ChatSessionProvider] Failed to persist thread payload:",Le)}},Bo))},[D,ye,pe,me.lastCheckpointId,me.lastCheckpointNs,me.messages,me.pendingInterrupt,z]);const gl=y.useMemo(()=>({threads:E,currentThreadId:A,setCurrentThreadId:j,isLoading:P,error:M,actions:{createThread:Ee,deleteThread:Be,renameThread:Xe,refreshThreads:()=>Et()},persistThreadsCache:Sr,hydrateFromCache:ue}),[E,A,P,M,Ee,Be,Xe,Et,Sr,ue,j]),xl=y.useMemo(()=>{const C=me.lastBranch??null,_=me.assemblingId??null,F=C||_?{branchLabel:(C==null?void 0:C.branchLabel)??null,lastBranch:C,assemblingMessageId:_}:null;return{threadId:A,messages:me.messages,interrupt:z,checkpoint:{id:me.lastCheckpointId??null,namespace:me.lastCheckpointNs??null},metadata:F,isLoading:$,isHistoryLoading:he,error:K,hasMore:D,loadOlder:Dt,seedFromSnapshot:$n,clearState:oe,listCheckpoints:kt,navigateToCheckpoint:ht,returnToLatest:mt,loadThread:De,clearThread:Ue,respondToInterrupt:St}},[Ue,oe,A,z,D,he,$,kt,Dt,De,me.assemblingId,me.lastBranch,me.lastCheckpointId,me.lastCheckpointNs,me.messages,ht,St,mt,$n,K]),Sk=y.useMemo(()=>({isStreaming:I,error:H,submit:Pn,stop:Mt,resume:Wr,setAuthToken:re}),[I,H,Pn,Mt,Wr,re]);return c.jsx(mx.Provider,{value:!0,children:c.jsx(jc.Provider,{value:Sk,children:c.jsx(Ac.Provider,{value:gl,children:c.jsx(_c.Provider,{value:xl,children:e})})})})}function Ho(){const e=y.useContext(Ac);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Uo(){const e=y.useContext(_c);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function Mc(){const e=y.useContext(jc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Wo({children:e,apiConfig:t,initialThreadId:n=null,autoLoadInitial:r=!0,disableAutoRestore:o=!1,enableFileAgentRouting:s=!1,fileAgentId:i="invoice_reader",onError:a,onThreadChange:l}){return c.jsx(Ug,{apiConfig:t,children:c.jsx(kx,{initialThreadId:n,autoLoadInitial:r,disableAutoRestore:o,enableFileAgentRouting:s,fileAgentId:i,onError:a,onThreadChange:l,children:e})})}function ee(...e){return vm.twMerge(xm.clsx(e))}const Tx=Io.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Je=m.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?nr.Slot:"button";return c.jsx(i,{className:ee(Tx({variant:t,size:n,className:e})),ref:s,...o})});Je.displayName="Button";const Dc=m.forwardRef(({className:e,...t},n)=>c.jsx("textarea",{className:ee("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));Dc.displayName="Textarea";function Ix({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,onSend:i,onCancelEdit:a,onStop:l,className:u="",textareaClassName:d="",allowEmptySend:f=!1}){const[h,p]=y.useState(e),[b,x]=y.useTransition(),g=y.useRef(null);y.useEffect(()=>{p(e??""),g.current&&(g.current.style.height="auto",g.current.style.height=`${g.current.scrollHeight}px`)},[e,t]);const v=y.useCallback(()=>{const A=g.current;A&&(A.style.height="auto",A.style.height=`${A.scrollHeight}px`)},[]);y.useEffect(()=>{v()},[v]);const w=y.useCallback(async A=>{A&&A.preventDefault();const j=(h??"").trim();!j&&!f||x(()=>{try{const P=i(j);P&&typeof P.then=="function"?P.then(()=>{p(""),g.current&&(g.current.style.height="auto")}).catch(()=>{}):(p(""),g.current&&(g.current.style.height="auto"))}catch{}})},[h,i,f]),S=y.useCallback(A=>{p(A.target.value),g.current&&(g.current.style.height="auto",g.current.style.height=`${g.current.scrollHeight}px`)},[]),N=y.useCallback(A=>{A.key==="Enter"&&!A.shiftKey?(A.preventDefault(),w()):A.key==="Escape"&&t&&(A.preventDefault(),a==null||a())},[w,t,a]),E=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${d}`;return c.jsx("form",{onSubmit:A=>void w(A),className:`w-full ${u}`,children:c.jsxs("div",{className:"flex items-end gap-2",children:[c.jsx("div",{className:"flex-1",children:c.jsx(Dc,{ref:g,value:h,onChange:S,onKeyDown:N,placeholder:t?"Edit your message...":n,className:E,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),c.jsx("div",{children:r?c.jsx(Je,{type:"button",onClick:()=>{l==null||l()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!l,children:c.jsx(ae.Square,{size:16})}):c.jsx(Je,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!h.trim()&&!f||b,children:c.jsx(ae.Send,{size:16})})})]})})}const Ex=y.memo(Ix),Vo=0,zn=1,Ar=2,Lc=4;function $c(e){return()=>e}function Nx(e){e()}function Fc(e,t){return n=>e(t(n))}function Bc(e,t){return()=>e(t)}function Ax(e,t){return n=>e(t,n)}function Mi(e){return e!==void 0}function _x(...e){return()=>{e.map(Nx)}}function _r(){}function Ko(e,t){return t(e),e}function jx(e,t){return t(e)}function lt(...e){return e}function Qe(e,t){return e(zn,t)}function Fe(e,t){e(Vo,t)}function Di(e){e(Ar)}function xt(e){return e(Lc)}function be(e,t){return Qe(e,Ax(t,Vo))}function on(e,t){const n=e(zn,r=>{n(),t(r)});return n}function zc(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function Hc(e,t){return e===t}function ct(e=Hc){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function Ae(e){return t=>n=>{e(n)&&t(n)}}function le(e){return t=>Fc(t,e)}function xn(e){return t=>()=>{t(e)}}function U(e,...t){const n=Rx(...t);return(r,o)=>{switch(r){case Ar:Di(e);return;case zn:return Qe(e,n(o))}}}function vn(e,t){return n=>r=>{n(t=e(t,r))}}function ir(e){return t=>n=>{e>0?e--:t(n)}}function Mn(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function He(...e){const t=new Array(e.length);let n=0,r=null;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);Qe(s,l=>{const u=n;n=n|a,t[i]=l,u!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function Rx(...e){return t=>e.reduceRight(jx,t)}function Px(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case zn:return s?n===s?void 0:(r(),n=s,t=Qe(e,s),t):(r(),_r);case Ar:r(),n=null;return}}}function Y(e){let t=e;const n=Ye();return(r,o)=>{switch(r){case Vo:t=o;break;case zn:{o(t);break}case Lc:return t}return n(r,o)}}function At(e,t){return Ko(Y(t),n=>be(e,n))}function Ye(){const e=[];return(t,n)=>{switch(t){case Vo:e.slice().forEach(r=>{r(n)});return;case Ar:e.splice(0,e.length);return;case zn:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function zt(e){return Ko(Ye(),t=>be(e,t))}function Ze(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:Ox(),singleton:n}}const Ox=()=>Symbol();function Mx(e){const t=new Map,n=({constructor:r,dependencies:o,id:s,singleton:i})=>{if(i&&t.has(s))return t.get(s);const a=r(o.map(l=>n(l)));return i&&t.set(s,a),a};return n(e)}function bt(...e){const t=Ye(),n=new Array(e.length);let r=0;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);Qe(s,l=>{n[i]=l,r=r|a,r===o&&Fe(t,n)})}),function(s,i){switch(s){case Ar:{Di(t);return}case zn:return r===o&&i(n),Qe(t,i)}}}function Ne(e,t=Hc){return U(e,ct(t))}function Li(...e){return function(t,n){switch(t){case Ar:return;case zn:return _x(...e.map(r=>Qe(r,n)))}}}var Ft=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(Ft||{});const Dx={0:"debug",3:"error",1:"log",2:"warn"},Lx=()=>typeof globalThis>"u"?window:globalThis,Hn=Ze(()=>{const e=Y(3);return{log:Y((t,n,r=1)=>{var o;const s=(o=Lx().VIRTUOSO_LOG_LEVEL)!=null?o:xt(e);r>=s&&console[Dx[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function ar(e,t,n){return $i(e,t,n).callbackRef}function $i(e,t,n){const r=y.useRef(null);let o=i=>{};const s=y.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(i=>{const a=()=>{const l=i[0].target;l.offsetParent!==null&&e(l)};n?a():requestAnimationFrame(a)}):null,[e,n]);return o=i=>{i&&t?(s==null||s.observe(i),r.current=i):(r.current&&(s==null||s.unobserve(r.current)),r.current=null)},{callbackRef:o,ref:r}}function $x(e,t,n,r,o,s,i,a,l){const u=y.useCallback(d=>{const f=Fx(d.children,t,a?"offsetWidth":"offsetHeight",o);let h=d.parentElement;for(;!h.dataset.virtuosoScroller;)h=h.parentElement;const p=h.lastElementChild.dataset.viewportType==="window";let b;p&&(b=h.ownerDocument.defaultView);const x=i?a?i.scrollLeft:i.scrollTop:p?a?b.scrollX||b.document.documentElement.scrollLeft:b.scrollY||b.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,g=i?a?i.scrollWidth:i.scrollHeight:p?a?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,v=i?a?i.offsetWidth:i.offsetHeight:p?a?b.innerWidth:b.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:g,scrollTop:Math.max(x,0),viewportHeight:v}),s==null||s(a?Uc("column-gap",getComputedStyle(d).columnGap,o):Uc("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return $i(u,n,l)}function Fx(e,t,n,r){const o=e.length;if(o===0)return null;const s=[];for(let i=0;i<o;i++){const a=e.item(i);if(a.dataset.index===void 0)continue;const l=parseInt(a.dataset.index),u=parseFloat(a.dataset.knownSize),d=t(a,n);if(d===0&&r("Zero-sized element, this should not happen",{child:a},Ft.ERROR),d===u)continue;const f=s[s.length-1];s.length===0||f.size!==d||f.endIndex!==l-1?s.push({endIndex:l,size:d,startIndex:l}):s[s.length-1].endIndex++}return s}function Uc(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Ft.WARN),t==="normal"?0:parseInt(t??"0",10)}function Wc(e,t,n){const r=y.useRef(null),o=y.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const u=l.getBoundingClientRect(),d=u.width;let f,h;if(t){const p=t.getBoundingClientRect(),b=u.top-p.top;h=p.height-Math.max(0,b),f=b+t.scrollTop}else{const p=i.current.ownerDocument.defaultView;h=p.innerHeight-Math.max(0,u.top),f=u.top+p.scrollY}r.current={offsetTop:f,visibleHeight:h,visibleWidth:d},e(r.current)},[e,t]),{callbackRef:s,ref:i}=$i(o,!0,n),a=y.useCallback(()=>{o(i.current)},[o,i]);return y.useEffect(()=>{var l;if(t){t.addEventListener("scroll",a);const u=new ResizeObserver(()=>{requestAnimationFrame(a)});return u.observe(t),()=>{t.removeEventListener("scroll",a),u.unobserve(t)}}else{const u=(l=i.current)==null?void 0:l.ownerDocument.defaultView;return u==null||u.addEventListener("scroll",a),u==null||u.addEventListener("resize",a),()=>{u==null||u.removeEventListener("scroll",a),u==null||u.removeEventListener("resize",a)}}},[a,t,i]),s}const Pt=Ze(()=>{const e=Ye(),t=Ye(),n=Y(0),r=Ye(),o=Y(0),s=Ye(),i=Ye(),a=Y(0),l=Y(0),u=Y(0),d=Y(0),f=Ye(),h=Ye(),p=Y(!1),b=Y(!1),x=Y(!1);return be(U(e,le(({scrollTop:g})=>g)),t),be(U(e,le(({scrollHeight:g})=>g)),i),be(t,o),{deviation:n,fixedFooterHeight:u,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:b,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:p,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:x,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),Qr={lvl:0};function Vc(e,t){const n=e.length;if(n===0)return[];let{index:r,value:o}=t(e[0]);const s=[];for(let i=1;i<n;i++){const{index:a,value:l}=t(e[i]);s.push({end:a-1,start:r,value:o}),r=a,o=l}return s.push({end:1/0,start:r,value:o}),s}function rt(e){return e===Qr}function eo(e,t){if(!rt(e))return t===e.k?e.v:t<e.k?eo(e.l,t):eo(e.r,t)}function sn(e,t,n="k"){if(rt(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=sn(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return sn(e.l,t,n)}function Ht(e,t,n){return rt(e)?Gc(t,n,1):t===e.k?wt(e,{k:t,v:n}):t<e.k?Yc(wt(e,{l:Ht(e.l,t,n)})):Yc(wt(e,{r:Ht(e.r,t,n)}))}function jr(){return Qr}function qo(e,t,n){if(rt(e))return[];const r=sn(e,t)[0];return Bx(Bi(e,r,n))}function Fi(e,t){if(rt(e))return Qr;const{k:n,l:r,r:o}=e;if(t===n){if(rt(r))return o;if(rt(o))return r;{const[s,i]=qc(r);return Go(wt(e,{k:s,l:Kc(r),v:i}))}}else return t<n?Go(wt(e,{l:Fi(r,t)})):Go(wt(e,{r:Fi(o,t)}))}function lr(e){return rt(e)?[]:[...lr(e.l),{k:e.k,v:e.v},...lr(e.r)]}function Bi(e,t,n){if(rt(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(Bi(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(Bi(s,t,n))),a}function Go(e){const{l:t,lvl:n,r}=e;if(r.lvl>=n-1&&t.lvl>=n-1)return e;if(n>r.lvl+1){if(zi(t))return Xc(wt(e,{lvl:n-1}));if(!rt(t)&&!rt(t.r))return wt(t.r,{l:wt(t,{r:t.r.l}),lvl:n,r:wt(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(zi(e))return Hi(wt(e,{lvl:n-1}));if(!rt(r)&&!rt(r.l)){const o=r.l,s=zi(o)?r.lvl-1:r.lvl;return wt(o,{l:wt(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:Hi(wt(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function wt(e,t){return Gc(t.k!==void 0?t.k:e.k,t.v!==void 0?t.v:e.v,t.lvl!==void 0?t.lvl:e.lvl,t.l!==void 0?t.l:e.l,t.r!==void 0?t.r:e.r)}function Kc(e){return rt(e.r)?e.l:Go(wt(e,{r:Kc(e.r)}))}function zi(e){return rt(e)||e.lvl>e.r.lvl}function qc(e){return rt(e.r)?[e.k,e.v]:qc(e.r)}function Gc(e,t,n,r=Qr,o=Qr){return{k:e,l:r,lvl:n,r:o,v:t}}function Yc(e){return Hi(Xc(e))}function Xc(e){const{l:t}=e;return!rt(t)&&t.lvl===e.lvl?wt(t,{r:wt(e,{l:t.r})}):e}function Hi(e){const{lvl:t,r:n}=e;return!rt(n)&&!rt(n.r)&&n.lvl===t&&n.r.lvl===t?wt(n,{l:wt(e,{r:n.l}),lvl:t+1}):e}function Bx(e){return Vc(e,({k:t,v:n})=>({index:t,value:n}))}function Jc(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function to(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const Ui=Ze(()=>({recalcInProgress:Y(!1)}),[],{singleton:!0});function Zc(e,t,n){return e[Yo(e,t,n)]}function Yo(e,t,n,r=0){let o=e.length-1;for(;r<=o;){const s=Math.floor((r+o)/2),i=e[s],a=n(i,t);if(a===0)return s;if(a===-1){if(o-r<2)return s-1;o=s-1}else{if(o===r)return s;r=s+1}}throw new Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function zx(e,t,n,r){const o=Yo(e,t,r),s=Yo(e,n,r,o);return e.slice(o,s+1)}function Un(e,t){return Math.round(e.getBoundingClientRect()[t])}function Xo(e){return!rt(e.groupOffsetTree)}function Wi({index:e},t){return t===e?0:t<e?-1:1}function Hx(){return{groupIndices:[],groupOffsetTree:jr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:jr()}}function Ux(e,t){let n=rt(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),rt(e)){e=Ht(e,0,s);continue}const a=qo(e,i-1,o+1);if(a.some(Xx(r)))continue;let l=!1,u=!1;for(const{end:d,start:f,value:h}of a)l?(o>=f||s===h)&&(e=Fi(e,f)):(u=h!==s,l=!0),d>o&&o>=f&&h!==s&&(e=Ht(e,o+1,h));u&&(e=Ht(e,i,s))}return[e,n]}function Wx(e){return typeof e.groupIndex<"u"}function Vx({offset:e},t){return t===e?0:t<e?-1:1}function no(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=Zc(t,e,Wi),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function Qc(e,t){if(!Xo(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function eu(e,t,n){if(Wx(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=Qc(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function Kx(e,t,n,r=0){return r>0&&(t=Math.max(t,Zc(e,r,Wi).offset)),Vc(zx(e,t,n,Vx),Yx)}function qx(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,Ft.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&rt(s)&&t.length===2){const h=t[0].size,p=t[1].size;i=n.reduce((b,x)=>Ht(Ht(b,x,h),x+1,p),i)}else[i,a]=Ux(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:u,lastSize:d,offsetTree:f}=Vi(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,p)=>Ht(h,p,no(p,f,o)),jr()),lastIndex:l,lastOffset:u,lastSize:d,offsetTree:f,sizeTree:i}}function Gx(e){return lr(e).map(({k:t,v:n},r,o)=>{const s=o[r+1];return{endIndex:s?s.k-1:1/0,size:n,startIndex:t}})}function tu(e,t){let n=0,r=0;for(;n<e;)n+=t[r+1]-t[r]-1,r++;return r-(n===e?0:1)}function Vi(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=Yo(o,t-1,Wi),a=o[l].offset;const u=sn(n,t-1);s=u[0],i=u[1],o.length&&o[l].size===sn(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:u,value:d}of qo(n,t,1/0)){const f=u-s,h=f*i+a+f*r;o.push({index:u,offset:h,size:d}),s=u,a=h,i=d}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function Yx(e){return{index:e.index,value:e}}function Xx(e){const{endIndex:t,size:n,startIndex:r}=e;return o=>o.start===r&&(o.end===t||o.end===1/0)&&o.value===n}const Jx={offsetHeight:"height",offsetWidth:"width"},bn=Ze(([{log:e},{recalcInProgress:t}])=>{const n=Ye(),r=Ye(),o=At(r,0),s=Ye(),i=Ye(),a=Y(0),l=Y([]),u=Y(void 0),d=Y(void 0),f=Y((k,T)=>Un(k,Jx[T])),h=Y(void 0),p=Y(0),b=Hx(),x=At(U(n,He(l,e,p),vn(qx,b),ct()),b),g=At(U(l,ct(),vn((k,T)=>({current:T,prev:k.current}),{current:[],prev:[]}),le(({prev:k})=>k)),[]);be(U(l,Ae(k=>k.length>0),He(x,p),le(([k,T,E])=>{const A=k.reduce((j,P,L)=>Ht(j,P,no(P,T.offsetTree,E)||L),jr());return{...T,groupIndices:k,groupOffsetTree:A}})),x),be(U(r,He(x),Ae(([k,{lastIndex:T}])=>k<T),le(([k,{lastIndex:T,lastSize:E}])=>[{endIndex:T,size:E,startIndex:k}])),n),be(u,d);const v=At(U(u,le(k=>k===void 0)),!0);be(U(d,Ae(k=>k!==void 0&&rt(xt(x).sizeTree)),le(k=>[{endIndex:0,size:k,startIndex:0}])),n);const w=zt(U(n,He(x),vn(({sizes:k},[T,E])=>({changed:E!==k,sizes:E}),{changed:!1,sizes:b}),le(k=>k.changed)));Qe(U(a,vn((k,T)=>({diff:k.prev-T,prev:T}),{diff:0,prev:0}),le(k=>k.diff)),k=>{const{groupIndices:T}=xt(x);if(k>0)Fe(t,!0),Fe(s,k+tu(k,T));else if(k<0){const E=xt(g);E.length>0&&(k-=tu(-k,E)),Fe(i,k)}}),Qe(U(a,He(e)),([k,T])=>{k<0&&T("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:a},Ft.ERROR)});const S=zt(s);be(U(s,He(x),le(([k,T])=>{const E=T.groupIndices.length>0,A=[],j=T.lastSize;if(E){const P=eo(T.sizeTree,0);let L=0,$=0;for(;L<k;){const M=T.groupIndices[$],G=T.groupIndices.length===$+1?1/0:T.groupIndices[$+1]-M-1;A.push({endIndex:M,size:P,startIndex:M}),A.push({endIndex:M+1+G-1,size:j,startIndex:M+1}),$++,L+=G+1}const V=lr(T.sizeTree);return L!==k&&V.shift(),V.reduce((M,{k:G,v:K})=>{let W=M.ranges;return M.prevSize!==0&&(W=[...M.ranges,{endIndex:G+k-1,size:M.prevSize,startIndex:M.prevIndex}]),{prevIndex:G+k,prevSize:K,ranges:W}},{prevIndex:k,prevSize:0,ranges:A}).ranges}return lr(T.sizeTree).reduce((P,{k:L,v:$})=>({prevIndex:L+k,prevSize:$,ranges:[...P.ranges,{endIndex:L+k-1,size:P.prevSize,startIndex:P.prevIndex}]}),{prevIndex:0,prevSize:j,ranges:[]}).ranges})),n);const N=zt(U(i,He(x,p),le(([k,{offsetTree:T},E])=>{const A=-k;return no(A,T,E)})));return be(U(i,He(x,p),le(([k,T,E])=>{if(T.groupIndices.length>0){if(rt(T.sizeTree))return T;let A=jr();const j=xt(g);let P=0,L=0,$=0;for(;P<-k;){$=j[L];const V=j[L+1]-$-1;L++,P+=V+1}if(A=lr(T.sizeTree).reduce((V,{k:M,v:G})=>Ht(V,Math.max(0,M+k),G),A),P!==-k){const V=eo(T.sizeTree,$);A=Ht(A,0,V);const M=sn(T.sizeTree,-k+1)[1];A=Ht(A,1,M)}return{...T,sizeTree:A,...Vi(T.offsetTree,0,A,E)}}else{const A=lr(T.sizeTree).reduce((j,{k:P,v:L})=>Ht(j,Math.max(0,P+k),L),jr());return{...T,sizeTree:A,...Vi(T.offsetTree,0,A,E)}}})),x),{beforeUnshiftWith:S,data:h,defaultItemSize:d,firstItemIndex:a,fixedItemSize:u,gap:p,groupIndices:l,itemSize:f,listRefresh:w,shiftWith:i,shiftWithOffset:N,sizeRanges:n,sizes:x,statefulTotalCount:o,totalCount:r,trackItemSizes:v,unshiftWith:s}},lt(Hn,Ui),{singleton:!0});function Zx(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const nu=Ze(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=Ye(),i=Ye(),a=zt(U(s,le(Zx)));return be(U(a,le(l=>l.totalCount)),n),be(U(a,le(l=>l.groupIndices)),e),be(U(bt(o,t,r),Ae(([l,u])=>Xo(u)),le(([l,u,d])=>sn(u.groupOffsetTree,Math.max(l-d,0),"v")[0]),ct(),le(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},lt(bn,Pt)),Wn=Ze(([{log:e}])=>{const t=Y(!1),n=zt(U(t,Ae(r=>r),ct()));return Qe(t,r=>{r&&xt(e)("props updated",{},Ft.DEBUG)}),{didMount:n,propsReady:t}},lt(Hn),{singleton:!0}),Qx=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function ru(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!Qx)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const ro=Ze(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:l,scrollTo:u,smoothScrollTargetReached:d,viewportHeight:f},{log:h}])=>{const p=Ye(),b=Ye(),x=Y(0);let g=null,v=null,w=null;function S(){g&&(g(),g=null),w&&(w(),w=null),v&&(clearTimeout(v),v=null),Fe(l,!1)}return be(U(p,He(n,f,r,x,a,i,h),He(e,s,o),le(([[N,k,T,E,A,j,P,L],$,V,M])=>{const G=ru(N),{align:K,behavior:W,offset:z}=G,B=E-1,ue=eu(G,k,B);let D=no(ue,k.offsetTree,$)+j;K==="end"?(D+=V+sn(k.sizeTree,ue)[1]-T+M,ue===B&&(D+=P)):K==="center"?D+=(V+sn(k.sizeTree,ue)[1]-T+M)/2:D-=A,z&&(D+=z);const te=he=>{S(),he?(L("retrying to scroll to",{location:N},Ft.DEBUG),Fe(p,N)):(Fe(b,!0),L("list did not change, scroll successful",{},Ft.DEBUG))};if(S(),W==="smooth"){let he=!1;w=Qe(t,we=>{he=he||we}),g=on(d,()=>{te(he)})}else g=on(U(t,ev(150)),te);return v=setTimeout(()=>{S()},1200),Fe(l,!0),L("scrolling from index to",{behavior:W,index:ue,top:D},Ft.DEBUG),{behavior:W,top:D}})),u),{scrollTargetReached:b,scrollToIndex:p,topListHeight:x}},lt(bn,Pt,Hn),{singleton:!0});function ev(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function Ki(e,t){e==0?t():requestAnimationFrame(()=>{Ki(e-1,t)})}function qi(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const oo=Ze(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=Y(!0),l=Y(0),u=Y(!0);return be(U(i,He(l),Ae(([d,f])=>!!f),xn(!1)),a),be(U(i,He(l),Ae(([d,f])=>!!f),xn(!1)),u),Qe(U(bt(t,i),He(a,n,e,u),Ae(([[,d],f,{sizeTree:h},p,b])=>d&&(!rt(h)||Mi(p))&&!f&&!b),He(l)),([,d])=>{on(o,()=>{Fe(u,!0)}),Ki(4,()=>{on(r,()=>{Fe(a,!0)}),Fe(s,d)})}),{initialItemFinalLocationReached:u,initialTopMostItemIndex:l,scrolledToInitialItem:a}},lt(bn,Pt,ro,Wn),{singleton:!0});function ou(e,t){return Math.abs(e-t)<1.01}const so="up",io="down",tv="none",nv={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},rv=0,ao=Ze(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=Y(!1),a=Y(!0),l=Ye(),u=Ye(),d=Y(4),f=Y(rv),h=At(U(Li(U(Ne(o),ir(1),xn(!0)),U(Ne(o),ir(1),xn(!1),zc(100))),ct()),!1),p=At(U(Li(U(n,xn(!0)),U(n,xn(!1),zc(200))),ct()),!1);be(U(bt(Ne(o),Ne(f)),le(([w,S])=>w<=S),ct()),a),be(U(a,Mn(50)),u);const b=zt(U(bt(r,Ne(s),Ne(t),Ne(e),Ne(d)),vn((w,[{scrollHeight:S,scrollTop:N},k,T,E,A])=>{const j=N+k-S>-A,P={scrollHeight:S,scrollTop:N,viewportHeight:k};if(j){let $,V;return N>w.state.scrollTop?($="SCROLLED_DOWN",V=w.state.scrollTop-N):($="SIZE_DECREASED",V=w.state.scrollTop-N||w.scrollTopDelta),{atBottom:!0,atBottomBecause:$,scrollTopDelta:V,state:P}}let L;return P.scrollHeight>w.state.scrollHeight?L="SIZE_INCREASED":k<w.state.viewportHeight?L="VIEWPORT_HEIGHT_DECREASING":N<w.state.scrollTop?L="SCROLLING_UPWARDS":L="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:L,state:P}},nv),ct((w,S)=>w&&w.atBottom===S.atBottom))),x=At(U(r,vn((w,{scrollHeight:S,scrollTop:N,viewportHeight:k})=>{if(ou(w.scrollHeight,S))return{changed:!1,jump:0,scrollHeight:S,scrollTop:N};{const T=S-(N+k)<1;return w.scrollTop!==N&&T?{changed:!0,jump:w.scrollTop-N,scrollHeight:S,scrollTop:N}:{changed:!0,jump:0,scrollHeight:S,scrollTop:N}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Ae(w=>w.changed),le(w=>w.jump)),0);be(U(b,le(w=>w.atBottom)),i),be(U(i,Mn(50)),l);const g=Y(io);be(U(r,le(({scrollTop:w})=>w),ct(),vn((w,S)=>xt(p)?{direction:w.direction,prevScrollTop:S}:{direction:S<w.prevScrollTop?so:io,prevScrollTop:S},{direction:io,prevScrollTop:0}),le(w=>w.direction)),g),be(U(r,Mn(50),xn(tv)),g);const v=Y(0);return be(U(h,Ae(w=>!w),xn(0)),v),be(U(o,Mn(100),He(h),Ae(([w,S])=>!!S),vn(([w,S],[N])=>[S,N],[0,0]),le(([w,S])=>S-w)),v),{atBottomState:b,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:u,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:x,scrollDirection:g,scrollVelocity:v}},lt(Pt)),Jo="top",Zo="bottom",su="none";function iu(e,t,n){return typeof e=="number"?n===so&&t===Jo||n===io&&t===Zo?e:0:n===so?t===Jo?e.main:e.reverse:t===Zo?e.main:e.reverse}function au(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const Gi=Ze(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=Ye(),i=Y(0),a=Y(0),l=Y(0),u=At(U(bt(Ne(r),Ne(o),Ne(n),Ne(s,to),Ne(l),Ne(i),Ne(t),Ne(e),Ne(a)),le(([d,f,h,[p,b],x,g,v,w,S])=>{const N=d-w,k=g+v,T=Math.max(h-N,0);let E=su;const A=au(S,Jo),j=au(S,Zo);return p-=w,p+=h+v,b+=h+v,b-=w,p>d+k-A&&(E=so),b<d-T+f+j&&(E=io),E!==su?[Math.max(N-h-iu(x,Jo,E)-A,0),N-T-v+f+iu(x,Zo,E)+j]:null}),Ae(d=>d!=null),ct(to)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:u}},lt(Pt),{singleton:!0});function ov(e,t,n){if(Xo(t)){const r=Qc(e,t);return[{index:sn(t.groupOffsetTree,r)[0],offset:0,size:0},{data:n==null?void 0:n[0],index:r,offset:0,size:0}]}return[{data:n==null?void 0:n[0],index:e,offset:0,size:0}]}const Yi={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Qo(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:l}=o;let u=0,d=0;if(e.length>0){u=e[0].offset;const x=e[e.length-1];d=x.offset+x.size}const f=n-i,h=a+f*l+(f-1)*r,p=u,b=h-d;return{bottom:d,firstItemIndex:s,items:cu(e,o,s),offsetBottom:b,offsetTop:u,top:p,topItems:cu(t,o,s),topListHeight:t.reduce((x,g)=>g.size+x,0),totalCount:n}}function lu(e,t,n,r,o,s){let i=0;if(n.groupIndices.length>0)for(const d of n.groupIndices){if(d-i>=e)break;i++}const a=e+i,l=qi(t,a),u=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return Qo(u,[],a,o,n,r)}function cu(e,t,n){if(e.length===0)return[];if(!Xo(t))return e.map(u=>({...u,index:u.index+n,originalIndex:u.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=qo(t.groupOffsetTree,r,o);let a,l=0;for(const u of e){(!a||a.end<u.index)&&(a=i.shift(),l=t.groupIndices.indexOf(a.start));let d;u.index===a.start?d={index:l,type:"group"}:d={groupIndex:l,index:u.index-(l+1)+n},s.push({...d,data:u.data,offset:u.offset,originalIndex:u.index,size:u.size})}return s}const cr=Ze(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:l},{initialTopMostItemIndex:u,scrolledToInitialItem:d},{topListHeight:f},h,{didMount:p},{recalcInProgress:b}])=>{const x=Y([]),g=Y(0),v=Ye();be(s.topItemsIndexes,x);const w=At(U(bt(p,b,Ne(l,to),Ne(o),Ne(r),Ne(u),d,Ne(x),Ne(t),Ne(n),e),Ae(([T,E,,A,,,,,,,j])=>{const P=j&&j.length!==A;return T&&!E&&!P}),le(([,,[T,E],A,j,P,L,$,V,M,G])=>{const K=j,{offsetTree:W,sizeTree:z}=K,B=xt(g);if(A===0)return{...Yi,totalCount:A};if(T===0&&E===0)return B===0?{...Yi,totalCount:A}:lu(B,P,j,V,M,G||[]);if(rt(z))return B>0?null:Qo(ov(qi(P,A),K,G),[],A,M,K,V);const ue=[];if($.length>0){const ye=$[0],Se=$[$.length-1];let q=0;for(const O of qo(z,ye,Se)){const X=O.value,ne=Math.max(O.start,ye),pe=Math.min(O.end,Se);for(let se=ne;se<=pe;se++)ue.push({data:G==null?void 0:G[se],index:se,offset:q,size:X}),q+=X}}if(!L)return Qo([],ue,A,M,K,V);const D=$.length>0?$[$.length-1]+1:0,te=Kx(W,T,E,D);if(te.length===0)return null;const he=A-1,we=Ko([],ye=>{for(const Se of te){const q=Se.value;let O=q.offset,X=Se.start;const ne=q.size;if(q.offset<T){X+=Math.floor((T-q.offset+M)/(ne+M));const se=X-Se.start;O+=se*ne+se*M}X<D&&(O+=(D-X)*ne,X=D);const pe=Math.min(Se.end,he);for(let se=X;se<=pe&&!(O>=E);se++)ye.push({data:G==null?void 0:G[se],index:se,offset:O,size:ne}),O+=ne+M}});return Qo(we,ue,A,M,K,V)}),Ae(T=>T!==null),ct()),Yi);be(U(e,Ae(Mi),le(T=>T==null?void 0:T.length)),o),be(U(w,le(T=>T.topListHeight)),f),be(f,a),be(U(w,le(T=>[T.top,T.bottom])),i),be(U(w,le(T=>T.items)),v);const S=zt(U(w,Ae(({items:T})=>T.length>0),He(o,e),Ae(([{items:T},E])=>T[T.length-1].originalIndex===E-1),le(([,T,E])=>[T-1,E]),ct(to),le(([T])=>T))),N=zt(U(w,Mn(200),Ae(({items:T,topItems:E})=>T.length>0&&T[0].originalIndex===E.length),le(({items:T})=>T[0].index),ct())),k=zt(U(w,Ae(({items:T})=>T.length>0),le(({items:T})=>{let E=0,A=T.length-1;for(;T[E].type==="group"&&E<A;)E++;for(;T[A].type==="group"&&A>E;)A--;return{endIndex:T[A].index,startIndex:T[E].index}}),ct(Jc)));return{endReached:S,initialItemCount:g,itemsRendered:v,listState:w,rangeChanged:k,startReached:N,topItemsIndexes:x,...h}},lt(bn,nu,Gi,oo,ro,ao,Wn,Ui),{singleton:!0}),uu=Ze(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=Ye(),i=At(U(bt(n,e,r,t,o),le(([a,l,u,d,f])=>a+l+u+d+f.offsetBottom+f.bottom)),0);return be(Ne(i),s),{totalListHeight:i,totalListHeightChanged:s}},lt(Pt,cr),{singleton:!0}),sv=Ze(([{viewportHeight:e},{totalListHeight:t}])=>{const n=Y(!1),r=At(U(bt(n,e,t),Ae(([o])=>o),le(([,o,s])=>Math.max(0,o-s)),Mn(0),ct()),0);return{alignToBottom:n,paddingTopAddition:r}},lt(Pt,uu),{singleton:!0}),du=Ze(()=>({context:Y(null)})),iv=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:r,...o},viewportBottom:s,viewportTop:i})=>t<i?{...o,align:n??"start",behavior:r}:e>s?{...o,align:n??"end",behavior:r}:null,fu=Ze(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:u}])=>{const d=Ye();return be(U(d,He(t,l,n,s,o,r,a),He(e),le(([[f,h,p,b,x,g,v,w],S])=>{const{align:N,behavior:k,calculateViewLocation:T=iv,done:E,...A}=f,j=eu(f,h,b-1),P=no(j,h.offsetTree,S)+x+g,L=P+sn(h.sizeTree,j)[1],$=w+g,V=w+p-v,M=T({itemBottom:L,itemTop:P,locationParams:{align:N,behavior:k,...A},viewportBottom:V,viewportTop:$});return M?E&&on(U(i,Ae(G=>!G),ir(xt(i)?1:2)),E):E&&E(),M}),Ae(f=>f!==null)),u),{scrollIntoView:d}},lt(bn,Pt,ro,cr,Hn),{singleton:!0});function hu(e){return e?e==="smooth"?"smooth":"auto":!1}const av=(e,t)=>typeof e=="function"?hu(e(t)):t&&hu(e),lv=Ze(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:l,propsReady:u},{log:d},{scrollingInProgress:f},{context:h},{scrollIntoView:p}])=>{const b=Y(!1),x=Ye();let g=null;function v(k){Fe(i,{align:"end",behavior:k,index:"LAST"})}Qe(U(bt(U(Ne(t),ir(1)),l),He(Ne(b),s,a,f),le(([[k,T],E,A,j,P])=>{let L=T&&j,$="auto";return L&&($=av(E,A||P),L=L&&!!$),{followOutputBehavior:$,shouldFollow:L,totalCount:k}}),Ae(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:T})=>{g&&(g(),g=null),xt(n)?requestAnimationFrame(()=>{xt(d)("following output to ",{totalCount:T},Ft.DEBUG),v(k)}):g=on(e,()=>{xt(d)("following output to ",{totalCount:T},Ft.DEBUG),v(k),g=null})});function w(k){const T=on(o,E=>{k&&!E.atBottom&&E.notAtBottomBecause==="SIZE_INCREASED"&&!g&&(xt(d)("scrolling to bottom due to increased size",{},Ft.DEBUG),v("auto"))});setTimeout(T,100)}Qe(U(bt(Ne(b),t,u),Ae(([k,,T])=>k&&T),vn(({value:k},[,T])=>({refreshed:k===T,value:T}),{refreshed:!1,value:0}),Ae(({refreshed:k})=>k),He(b,t)),([,k])=>{xt(a)&&w(k!==!1)}),Qe(x,()=>{w(xt(b)!==!1)}),Qe(bt(Ne(b),o),([k,T])=>{k&&!T.atBottom&&T.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&v("auto")});const S=Y(null),N=Ye();return be(Li(U(Ne(r),le(k=>{var T;return(T=k==null?void 0:k.length)!=null?T:0})),U(Ne(t))),N),Qe(U(bt(U(N,ir(1)),l),He(Ne(S),a,f,h),le(([[k,T],E,A,j,P])=>T&&A&&(E==null?void 0:E({context:P,totalCount:k,scrollingInProgress:j}))),Ae(k=>!!k),Mn(0)),k=>{g&&(g(),g=null),xt(n)?requestAnimationFrame(()=>{xt(d)("scrolling into view",{}),Fe(p,k)}):g=on(e,()=>{xt(d)("scrolling into view",{}),Fe(p,k),g=null})}),{autoscrollToBottom:x,followOutput:b,scrollIntoViewOnChange:S}},lt(bn,ao,ro,oo,Wn,Hn,Pt,du,fu)),cv=Ze(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(be(U(a,He(s),Ae(([,l])=>l!==0),He(o,r,t,n,e),le(([[,l],u,d,f,h,p=[]])=>lu(l,u,d,f,h,p))),i),{}),lt(bn,oo,cr,Wn),{singleton:!0}),uv=Ze(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=Y(0);return Qe(U(e,He(r),Ae(([,o])=>o!==0),le(([,o])=>({top:o}))),o=>{on(U(n,ir(1),Ae(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{Fe(t,o)})})}),{initialScrollTop:r}},lt(Wn,Pt,cr),{singleton:!0}),pu=Ze(([{scrollVelocity:e}])=>{const t=Y(!1),n=Ye(),r=Y(!1);return be(U(e,He(r,t,n),Ae(([o,s])=>!!s),le(([o,s,i,a])=>{const{enter:l,exit:u}=s;if(i){if(u(o,a))return!1}else if(l(o,a))return!0;return i}),ct()),t),Qe(U(bt(t,e,n),He(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},lt(ao),{singleton:!0}),Xi=Ze(([{scrollContainerState:e,scrollTo:t}])=>{const n=Ye(),r=Ye(),o=Ye(),s=Y(!1),i=Y(void 0);return be(U(bt(n,r),le(([{scrollHeight:a,scrollTop:l,viewportHeight:u},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:u}))),e),be(U(t,He(r),le(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},lt(Pt)),dv=Ze(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const u=Ye(),d=Y(void 0),f=Y(null),h=Y(null);return be(a,f),be(l,h),Qe(U(u,He(t,r,i,f,h,n)),([p,b,x,g,v,w,S])=>{const N=Gx(b.sizeTree);g&&v!==null&&w!==null&&(x=v.scrollTop-w.offsetTop),x-=S,p({ranges:N,scrollTop:x})}),be(U(d,Ae(Mi),le(fv)),o),be(U(s,He(d),Ae(([,p])=>p!==void 0),ct(),le(([,p])=>p.ranges)),e),{getState:u,restoreStateFrom:d}},lt(bn,Pt,oo,Wn,Xi));function fv(e){return{align:"start",index:0,offset:e.scrollTop}}const hv=Ze(([{topItemsIndexes:e}])=>{const t=Y(0);return be(U(t,Ae(n=>n>=0),le(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},lt(cr));function mu(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const pv=mu(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),mv=Ze(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:l},{beforeUnshiftWith:u,gap:d,shiftWithOffset:f,sizes:h},{log:p},{recalcInProgress:b}])=>{const x=zt(U(l,He(i),vn(([,v,w,S],[{bottom:N,items:k,offsetBottom:T,totalCount:E},A])=>{const j=N+T;let P=0;return w===E&&v.length>0&&k.length>0&&(k[0].originalIndex===0&&v[0].originalIndex===0||(P=j-S,P!==0&&(P+=A))),[P,k,E,j]},[0,[],0,0]),Ae(([v])=>v!==0),He(r,a,n,o,p,b),Ae(([,v,w,S,,,N])=>!N&&!S&&v!==0&&w===so),le(([[v],,,,,w])=>(w("Upward scrolling compensation",{amount:v},Ft.DEBUG),v))));function g(v){v>0?(Fe(t,{behavior:"auto",top:-v}),Fe(e,0)):(Fe(e,0),Fe(t,{behavior:"auto",top:-v}))}return Qe(U(x,He(e,s)),([v,w,S])=>{S&&pv()?Fe(e,w-v):g(-v)}),Qe(U(bt(At(s,!1),e,b),Ae(([v,w,S])=>!v&&!S&&w!==0),le(([v,w])=>w),Mn(1)),g),be(U(f,le(v=>({top:-v}))),t),Qe(U(u,He(h,d),le(([v,{groupIndices:w,lastSize:S,sizeTree:N},k])=>{function T(E){return E*(S+k)}if(w.length===0)return T(v);{let E=0;const A=eo(N,0);let j=0,P=0;for(;j<v;){j++,E+=A;let L=w.length===P+1?1/0:w[P+1]-w[P]-1;j+L>v&&(E-=A,L=v-j+1),j+=L,E+=T(L),P++}return E}})),v=>{Fe(e,v),requestAnimationFrame(()=>{Fe(t,{top:v}),requestAnimationFrame(()=>{Fe(e,0),Fe(b,!1)})})}),{deviation:e}},lt(Pt,ao,cr,bn,Hn,Ui)),gv=Ze(([e,t,n,r,o,s,i,a,l,u,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...u,...d}),lt(Gi,cv,Wn,pu,uu,uv,sv,Xi,fu,Hn,du)),gu=Ze(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:l,statefulTotalCount:u,totalCount:d,trackItemSizes:f},{initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:b},x,g,v,{listState:w,topItemsIndexes:S,...N},{scrollToIndex:k},T,{topItemCount:E},{groupCounts:A},j])=>(be(N.rangeChanged,j.scrollSeekRangeChanged),be(U(j.windowViewportRect,le(P=>P.visibleHeight)),x.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:A,initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:b,sizeRanges:a,topItemCount:E,topItemsIndexes:S,totalCount:d,...v,groupIndices:s,itemSize:i,listState:w,scrollToIndex:k,statefulTotalCount:u,trackItemSizes:f,...N,...j,...x,sizes:l,...g}),lt(bn,oo,Pt,dv,lv,cr,ro,mv,hv,nu,gv));function xv(e,t){const n={},r={};let o=0;const s=e.length;for(;o<s;)r[e[o]]=1,o+=1;for(const i in t)Object.hasOwn(r,i)||(n[i]=t[i]);return n}const es=typeof document<"u"?y.useLayoutEffect:y.useEffect;function xu(e,t,n){const r=Object.keys(t.required||{}),o=Object.keys(t.optional||{}),s=Object.keys(t.methods||{}),i=Object.keys(t.events||{}),a=y.createContext({});function l(g,v){g.propsReady&&Fe(g.propsReady,!1);for(const w of r){const S=g[t.required[w]];Fe(S,v[w])}for(const w of o)if(w in v){const S=g[t.optional[w]];Fe(S,v[w])}g.propsReady&&Fe(g.propsReady,!0)}function u(g){return s.reduce((v,w)=>(v[w]=S=>{const N=g[t.methods[w]];Fe(N,S)},v),{})}function d(g){return i.reduce((v,w)=>(v[w]=Px(g[t.events[w]]),v),{})}const f=y.forwardRef((g,v)=>{const{children:w,...S}=g,[N]=y.useState(()=>Ko(Mx(e),E=>{l(E,S)})),[k]=y.useState(Bc(d,N));es(()=>{for(const E of i)E in S&&Qe(k[E],S[E]);return()=>{Object.values(k).map(Di)}},[S,k,N]),es(()=>{l(N,S)}),y.useImperativeHandle(v,$c(u(N)));const T=n;return c.jsx(a.Provider,{value:N,children:n?c.jsx(T,{...xv([...r,...o,...i],S),children:w}):w})}),h=g=>{const v=y.useContext(a);return y.useCallback(w=>{Fe(v[g],w)},[v,g])},p=g=>{const v=y.useContext(a)[g],w=y.useCallback(S=>Qe(v,S),[v]);return y.useSyncExternalStore(w,()=>xt(v),()=>xt(v))},b=g=>{const v=y.useContext(a)[g],[w,S]=y.useState(Bc(xt,v));return es(()=>Qe(v,N=>{N!==w&&S($c(N))}),[v,w]),w},x=y.version.startsWith("18")?p:b;return{Component:f,useEmitter:(g,v)=>{const w=y.useContext(a)[g];es(()=>Qe(w,v),[v,w])},useEmitterValue:x,usePublisher:h}}const vu=y.createContext(void 0),bu=y.createContext(void 0),wu=typeof document<"u"?y.useLayoutEffect:y.useEffect;function Ji(e){return"self"in e}function vv(e){return"body"in e}function yu(e,t,n,r=_r,o,s){const i=y.useRef(null),a=y.useRef(null),l=y.useRef(null),u=y.useCallback(h=>{let p,b,x;const g=h.target;if(vv(g)||Ji(g)){const w=Ji(g)?g:g.defaultView;x=s?w.scrollX:w.scrollY,p=s?w.document.documentElement.scrollWidth:w.document.documentElement.scrollHeight,b=s?w.innerWidth:w.innerHeight}else x=s?g.scrollLeft:g.scrollTop,p=s?g.scrollWidth:g.scrollHeight,b=s?g.offsetWidth:g.offsetHeight;const v=()=>{e({scrollHeight:p,scrollTop:Math.max(x,0),viewportHeight:b})};h.suppressFlushSync?v():ai.flushSync(v),a.current!==null&&(x===a.current||x<=0||x===p-b)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);y.useEffect(()=>{const h=o||i.current;return r(o||i.current),u({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",u,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",u)}},[i,u,n,r,o]);function d(h){const p=i.current;if(!p||(s?"offsetWidth"in p&&p.offsetWidth===0:"offsetHeight"in p&&p.offsetHeight===0))return;const b=h.behavior==="smooth";let x,g,v;Ji(p)?(g=Math.max(Un(p.document.documentElement,s?"width":"height"),s?p.document.documentElement.scrollWidth:p.document.documentElement.scrollHeight),x=s?p.innerWidth:p.innerHeight,v=s?window.scrollX:window.scrollY):(g=p[s?"scrollWidth":"scrollHeight"],x=Un(p,s?"width":"height"),v=p[s?"scrollLeft":"scrollTop"]);const w=g-x;if(h.top=Math.ceil(Math.max(Math.min(w,h.top),0)),ou(x,g)||h.top===v){e({scrollHeight:g,scrollTop:v,viewportHeight:x}),b&&t(!0);return}b?(a.current=h.top,l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{l.current=null,a.current=null,t(!0)},1e3)):a.current=null,s&&(h={behavior:h.behavior,left:h.top}),p.scrollTo(h)}function f(h){s&&(h={behavior:h.behavior,left:h.top}),i.current.scrollBy(h)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:d}}const Zi="-webkit-sticky",Su="sticky",Qi=mu(()=>{if(typeof document>"u")return Su;const e=document.createElement("div");return e.style.position=Zi,e.style.position===Zi?Zi:Su});function ea(e){return e}const bv=Ze(()=>{const e=Y(a=>`Item ${a}`),t=Y(a=>`Group ${a}`),n=Y({}),r=Y(ea),o=Y("div"),s=Y(_r),i=(a,l=null)=>At(U(n,le(u=>u[a]),ct()),l);return{components:n,computeItemKey:r,EmptyPlaceholder:i("EmptyPlaceholder"),FooterComponent:i("Footer"),GroupComponent:i("Group","div"),groupContent:t,HeaderComponent:i("Header"),HeaderFooterTag:o,ItemComponent:i("Item","div"),itemContent:e,ListComponent:i("List","div"),ScrollerComponent:i("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:i("ScrollSeekPlaceholder"),TopItemListComponent:i("TopItemList")}}),wv=Ze(([e,t])=>({...e,...t}),lt(gu,bv)),yv=({height:e})=>c.jsx("div",{style:{height:e}}),Sv={overflowAnchor:"none",position:Qi(),zIndex:1},Cu={overflowAnchor:"none"},Cv={...Cu,display:"inline-block",height:"100%"},ku=y.memo(function({showTopList:e=!1}){const t=Re("listState"),n=qt("sizeRanges"),r=Re("useWindowScroll"),o=Re("customScrollParent"),s=qt("windowScrollContainerState"),i=qt("scrollContainerState"),a=o||r?s:i,l=Re("itemContent"),u=Re("context"),d=Re("groupContent"),f=Re("trackItemSizes"),h=Re("itemSize"),p=Re("log"),b=qt("gap"),x=Re("horizontalDirection"),{callbackRef:g}=$x(n,h,f,e?_r:a,p,b,o,x,Re("skipAnimationFrameInResizeObserver")),[v,w]=y.useState(0);ta("deviation",M=>{v!==M&&w(M)});const S=Re("EmptyPlaceholder"),N=Re("ScrollSeekPlaceholder")||yv,k=Re("ListComponent"),T=Re("ItemComponent"),E=Re("GroupComponent"),A=Re("computeItemKey"),j=Re("isSeeking"),P=Re("groupIndices").length>0,L=Re("alignToBottom"),$=Re("initialItemFinalLocationReached"),V=e?{}:{boxSizing:"border-box",...x?{display:"inline-block",height:"100%",marginLeft:v!==0?v:L?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:v!==0?v:L?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...$?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&S?c.jsx(S,{..._t(S,u)}):c.jsx(k,{..._t(k,u),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:g,style:V,children:(e?t.topItems:t.items).map(M=>{const G=M.originalIndex,K=A(G+t.firstItemIndex,M.data,u);return j?y.createElement(N,{..._t(N,u),height:M.size,index:M.index,key:K,type:M.type||"item",...M.type==="group"?{}:{groupIndex:M.groupIndex}}):M.type==="group"?y.createElement(E,{..._t(E,u),"data-index":G,"data-item-index":M.index,"data-known-size":M.size,key:K,style:Sv},d(M.index,u)):y.createElement(T,{..._t(T,u),...Ev(T,M.data),"data-index":G,"data-item-group-index":M.groupIndex,"data-item-index":M.index,"data-known-size":M.size,key:K,style:x?Cv:Cu},P?l(M.index,M.groupIndex,M.data,u):l(M.index,M.data,u))})})}),kv={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},Tv={outline:"none",overflowX:"auto",position:"relative"},ts=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),Iv={position:Qi(),top:0,width:"100%",zIndex:1};function _t(e,t){if(typeof e!="string")return{context:t}}function Ev(e,t){return{item:typeof e=="string"?void 0:t}}const Nv=y.memo(function(){const e=Re("HeaderComponent"),t=qt("headerHeight"),n=Re("HeaderFooterTag"),r=ar(y.useMemo(()=>s=>{t(Un(s,"height"))},[t]),!0,Re("skipAnimationFrameInResizeObserver")),o=Re("context");return e?c.jsx(n,{ref:r,children:c.jsx(e,{..._t(e,o)})}):null}),Av=y.memo(function(){const e=Re("FooterComponent"),t=qt("footerHeight"),n=Re("HeaderFooterTag"),r=ar(y.useMemo(()=>s=>{t(Un(s,"height"))},[t]),!0,Re("skipAnimationFrameInResizeObserver")),o=Re("context");return e?c.jsx(n,{ref:r,children:c.jsx(e,{..._t(e,o)})}):null});function Tu({useEmitter:e,useEmitterValue:t,usePublisher:n}){return y.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),l=t("ScrollerComponent"),u=n("smoothScrollTargetReached"),d=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:p,scrollToCallback:b}=yu(a,u,l,d,void 0,f);return e("scrollTo",b),e("scrollBy",h),c.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:p,style:{...f?Tv:kv,...o},tabIndex:0,...i,..._t(l,s),children:r})})}function Iu({useEmitter:e,useEmitterValue:t,usePublisher:n}){return y.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),l=t("ScrollerComponent"),u=n("smoothScrollTargetReached"),d=t("totalListHeight"),f=t("deviation"),h=t("customScrollParent"),p=y.useRef(null),b=t("scrollerRef"),{scrollByCallback:x,scrollerRef:g,scrollToCallback:v}=yu(a,u,l,b,h);return wu(()=>{var w;return g.current=h||((w=p.current)==null?void 0:w.ownerDocument.defaultView),()=>{g.current=null}},[g,h]),e("windowScrollTo",v),e("scrollBy",x),c.jsx(l,{ref:p,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...d!==0?{height:d+f}:{}},...i,..._t(l,s),children:r})})}const _v=({children:e})=>{const t=y.useContext(vu),n=qt("viewportHeight"),r=qt("fixedItemHeight"),o=Re("alignToBottom"),s=Re("horizontalDirection"),i=y.useMemo(()=>Fc(n,l=>Un(l,s?"width":"height")),[n,s]),a=ar(i,!0,Re("skipAnimationFrameInResizeObserver"));return y.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),c.jsx("div",{"data-viewport-type":"element",ref:a,style:ts(o),children:e})},jv=({children:e})=>{const t=y.useContext(vu),n=qt("windowViewportRect"),r=qt("fixedItemHeight"),o=Re("customScrollParent"),s=Wc(n,o,Re("skipAnimationFrameInResizeObserver")),i=Re("alignToBottom");return y.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),c.jsx("div",{"data-viewport-type":"window",ref:s,style:ts(i),children:e})},Rv=({children:e})=>{const t=Re("TopItemListComponent")||"div",n=Re("headerHeight"),r={...Iv,marginTop:`${n}px`},o=Re("context");return c.jsx(t,{style:r,..._t(t,o),children:e})},Pv=y.memo(function(e){const t=Re("useWindowScroll"),n=Re("topItemsIndexes").length>0,r=Re("customScrollParent"),o=Re("context");return c.jsxs(r||t?Dv:Mv,{...e,context:o,children:[n&&c.jsx(Rv,{children:c.jsx(ku,{showTopList:!0})}),c.jsxs(r||t?jv:_v,{children:[c.jsx(Nv,{}),c.jsx(ku,{}),c.jsx(Av,{})]})]})}),{Component:Ov,useEmitter:ta,useEmitterValue:Re,usePublisher:qt}=xu(wv,{required:{},optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedItemHeight:"fixedItemHeight",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},Pv),Mv=Tu({useEmitter:ta,useEmitterValue:Re,usePublisher:qt}),Dv=Iu({useEmitter:ta,useEmitterValue:Re,usePublisher:qt}),Lv=Ov;lt(gu,Ze(()=>{const e=Y(u=>c.jsxs("td",{children:["Item $",u]})),t=Y(null),n=Y(u=>c.jsxs("td",{colSpan:1e3,children:["Group ",u]})),r=Y(null),o=Y(null),s=Y({}),i=Y(ea),a=Y(_r),l=(u,d=null)=>At(U(s,le(f=>f[u]),ct()),d);return{components:s,computeItemKey:i,context:t,EmptyPlaceholder:l("EmptyPlaceholder"),FillerRow:l("FillerRow"),fixedFooterContent:o,fixedHeaderContent:r,itemContent:e,groupContent:n,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder"),TableBodyComponent:l("TableBody","tbody"),TableComponent:l("Table","table"),TableFooterComponent:l("TableFoot","tfoot"),TableHeadComponent:l("TableHead","thead"),TableRowComponent:l("TableRow","tr"),GroupComponent:l("Group","tr")}})),Qi();const Eu={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},$v={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:Nu,floor:ns,max:lo,min:na,round:Au}=Math;function _u(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function Fv(e){return{...$v,items:e}}function rs(e,t){return e&&e.width===t.width&&e.height===t.height}function Bv(e,t){return e&&e.column===t.column&&e.row===t.row}const zv=Ze(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:l,scrollTop:u,smoothScrollTargetReached:d,viewportHeight:f},h,p,{didMount:b,propsReady:x},{customScrollParent:g,useWindowScroll:v,windowScrollContainerState:w,windowScrollTo:S,windowViewportRect:N},k])=>{const T=Y(0),E=Y(0),A=Y(Eu),j=Y({height:0,width:0}),P=Y({height:0,width:0}),L=Ye(),$=Ye(),V=Y(0),M=Y(null),G=Y({column:0,row:0}),K=Ye(),W=Ye(),z=Y(!1),B=Y(0),ue=Y(!0),D=Y(!1),te=Y(!1);Qe(U(b,He(B),Ae(([O,X])=>!!X)),()=>{Fe(ue,!1)}),Qe(U(bt(b,ue,P,j,B,D),Ae(([O,X,ne,pe,,se])=>O&&!X&&ne.height!==0&&pe.height!==0&&!se)),([,,,,O])=>{Fe(D,!0),Ki(1,()=>{Fe(L,O)}),on(U(u),()=>{Fe(t,[0,0]),Fe(ue,!0)})}),be(U(W,Ae(O=>O!=null&&O.scrollTop>0),xn(0)),E),Qe(U(b,He(W),Ae(([,O])=>O!=null)),([,O])=>{O&&(Fe(j,O.viewport),Fe(P,O.item),Fe(G,O.gap),O.scrollTop>0&&(Fe(z,!0),on(U(u,ir(1)),X=>{Fe(z,!1)}),Fe(l,{top:O.scrollTop})))}),be(U(j,le(({height:O})=>O)),f),be(U(bt(Ne(j,rs),Ne(P,rs),Ne(G,(O,X)=>O&&O.column===X.column&&O.row===X.row),Ne(u)),le(([O,X,ne,pe])=>({gap:ne,item:X,scrollTop:pe,viewport:O}))),K),be(U(bt(Ne(T),r,Ne(G,Bv),Ne(P,rs),Ne(j,rs),Ne(M),Ne(E),Ne(z),Ne(ue),Ne(B)),Ae(([,,,,,,,O])=>!O),le(([O,[X,ne],pe,se,me,et,tt,,Pe,Ve])=>{const{column:ut,row:nt}=pe,{height:Ke,width:vt}=se,{width:Q}=me;if(tt===0&&(O===0||Q===0))return Eu;if(vt===0){const ft=qi(Ve,O),It=ft+Math.max(tt-1,0);return Fv(_u(ft,It,et))}const ie=ju(Q,vt,ut);let xe,Ce;Pe?X===0&&ne===0&&tt>0?(xe=0,Ce=tt-1):(xe=ie*ns((X+nt)/(Ke+nt)),Ce=ie*Nu((ne+nt)/(Ke+nt))-1,Ce=na(O-1,lo(Ce,ie-1)),xe=na(Ce,lo(0,xe))):(xe=0,Ce=-1);const ve=_u(xe,Ce,et),{bottom:Oe,top:at}=Ru(me,pe,se,ve),Me=Nu(O/ie),st=Me*Ke+(Me-1)*nt-Oe;return{bottom:Oe,itemHeight:Ke,items:ve,itemWidth:vt,offsetBottom:st,offsetTop:at,top:at}})),A),be(U(M,Ae(O=>O!==null),le(O=>O.length)),T),be(U(bt(j,P,A,G),Ae(([O,X,{items:ne}])=>ne.length>0&&X.height!==0&&O.height!==0),le(([O,X,{items:ne},pe])=>{const{bottom:se,top:me}=Ru(O,pe,X,ne);return[me,se]}),ct(to)),t);const he=Y(!1);be(U(u,He(he),le(([O,X])=>X||O!==0)),he);const we=zt(U(bt(A,T),Ae(([{items:O}])=>O.length>0),He(he),Ae(([[O,X],ne])=>{const pe=O.items[O.items.length-1].index===X-1;return(ne||O.bottom>0&&O.itemHeight>0&&O.offsetBottom===0&&O.items.length===X)&&pe}),le(([[,O]])=>O-1),ct())),ye=zt(U(Ne(A),Ae(({items:O})=>O.length>0&&O[0].index===0),xn(0),ct())),Se=zt(U(Ne(A),He(z),Ae(([{items:O},X])=>O.length>0&&!X),le(([{items:O}])=>({endIndex:O[O.length-1].index,startIndex:O[0].index})),ct(Jc),Mn(0)));be(Se,p.scrollSeekRangeChanged),be(U(L,He(j,P,T,G),le(([O,X,ne,pe,se])=>{const me=ru(O),{align:et,behavior:tt,offset:Pe}=me;let Ve=me.index;Ve==="LAST"&&(Ve=pe-1),Ve=lo(0,Ve,na(pe-1,Ve));let ut=ra(X,se,ne,Ve);return et==="end"?ut=Au(ut-X.height+ne.height):et==="center"&&(ut=Au(ut-X.height/2+ne.height/2)),Pe&&(ut+=Pe),{behavior:tt,top:ut}})),l);const q=At(U(A,le(O=>O.offsetBottom+O.bottom)),0);return be(U(N,le(O=>({height:O.visibleHeight,width:O.visibleWidth}))),j),{customScrollParent:g,data:M,deviation:V,footerHeight:o,gap:G,headerHeight:s,increaseViewportBy:e,initialItemCount:E,itemDimensions:P,overscan:n,restoreStateFrom:W,scrollBy:i,scrollContainerState:a,scrollHeight:$,scrollTo:l,scrollToIndex:L,scrollTop:u,smoothScrollTargetReached:d,totalCount:T,useWindowScroll:v,viewportDimensions:j,windowScrollContainerState:w,windowScrollTo:S,windowViewportRect:N,...p,gridState:A,horizontalDirection:te,initialTopMostItemIndex:B,totalListHeight:q,...h,endReached:we,propsReady:x,rangeChanged:Se,startReached:ye,stateChanged:K,stateRestoreInProgress:z,...k}},lt(Gi,Pt,ao,pu,Wn,Xi,Hn));function ju(e,t,n){return lo(1,ns((e+n)/(ns(t)+n)))}function Ru(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=ra(e,t,n,r[0].index);return{bottom:ra(e,t,n,r[r.length-1].index)+o,top:s}}function ra(e,t,n,r){const o=ju(e.width,n.width,t.column),s=ns(r/o),i=s*n.height+lo(0,s-1)*t.row;return i>0?i+t.row:i}const Hv=Ze(()=>{const e=Y(f=>`Item ${f}`),t=Y({}),n=Y(null),r=Y("virtuoso-grid-item"),o=Y("virtuoso-grid-list"),s=Y(ea),i=Y("div"),a=Y(_r),l=(f,h=null)=>At(U(t,le(p=>p[f]),ct()),h),u=Y(!1),d=Y(!1);return be(Ne(d),u),{components:t,computeItemKey:s,context:n,FooterComponent:l("Footer"),HeaderComponent:l("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:l("Item","div"),itemContent:e,listClassName:o,ListComponent:l("List","div"),readyStateChanged:u,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),Uv=Ze(([e,t])=>({...e,...t}),lt(zv,Hv)),Wv=y.memo(function(){const e=dt("gridState"),t=dt("listClassName"),n=dt("itemClassName"),r=dt("itemContent"),o=dt("computeItemKey"),s=dt("isSeeking"),i=Gt("scrollHeight"),a=dt("ItemComponent"),l=dt("ListComponent"),u=dt("ScrollSeekPlaceholder"),d=dt("context"),f=Gt("itemDimensions"),h=Gt("gap"),p=dt("log"),b=dt("stateRestoreInProgress"),x=Gt("reportReadyState"),g=ar(y.useMemo(()=>v=>{const w=v.parentElement.parentElement.scrollHeight;i(w);const S=v.firstChild;if(S){const{height:N,width:k}=S.getBoundingClientRect();f({height:N,width:k})}h({column:Ou("column-gap",getComputedStyle(v).columnGap,p),row:Ou("row-gap",getComputedStyle(v).rowGap,p)})},[i,f,h,p]),!0,!1);return wu(()=>{e.itemHeight>0&&e.itemWidth>0&&x(!0)},[e]),b?null:c.jsx(l,{className:t,ref:g,..._t(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(v=>{const w=o(v.index,v.data,d);return s?c.jsx(u,{..._t(u,d),height:e.itemHeight,index:v.index,width:e.itemWidth},w):y.createElement(a,{..._t(a,d),className:n,"data-index":v.index,key:w},r(v.index,v.data,d))})})}),Vv=y.memo(function(){const e=dt("HeaderComponent"),t=Gt("headerHeight"),n=dt("headerFooterTag"),r=ar(y.useMemo(()=>s=>{t(Un(s,"height"))},[t]),!0,!1),o=dt("context");return e?c.jsx(n,{ref:r,children:c.jsx(e,{..._t(e,o)})}):null}),Kv=y.memo(function(){const e=dt("FooterComponent"),t=Gt("footerHeight"),n=dt("headerFooterTag"),r=ar(y.useMemo(()=>s=>{t(Un(s,"height"))},[t]),!0,!1),o=dt("context");return e?c.jsx(n,{ref:r,children:c.jsx(e,{..._t(e,o)})}):null}),qv=({children:e})=>{const t=y.useContext(bu),n=Gt("itemDimensions"),r=Gt("viewportDimensions"),o=ar(y.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return y.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),c.jsx("div",{ref:o,style:ts(!1),children:e})},Gv=({children:e})=>{const t=y.useContext(bu),n=Gt("windowViewportRect"),r=Gt("itemDimensions"),o=dt("customScrollParent"),s=Wc(n,o,!1);return y.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),c.jsx("div",{ref:s,style:ts(!1),children:e})},Yv=y.memo(function({...e}){const t=dt("useWindowScroll"),n=dt("customScrollParent"),r=n||t?Jv:Xv,o=n||t?Gv:qv,s=dt("context");return c.jsx(r,{...e,..._t(r,s),children:c.jsxs(o,{children:[c.jsx(Vv,{}),c.jsx(Wv,{}),c.jsx(Kv,{})]})})}),{useEmitter:Pu,useEmitterValue:dt,usePublisher:Gt}=xu(Uv,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},Yv),Xv=Tu({useEmitter:Pu,useEmitterValue:dt,usePublisher:Gt}),Jv=Iu({useEmitter:Pu,useEmitterValue:dt,usePublisher:Gt});function Ou(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Ft.WARN),t==="normal"?0:parseInt(t??"0",10)}const Zv=Io.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function oa({className:e,variant:t,...n}){return c.jsx("div",{className:ee(Zv({variant:t}),e),...n})}function fe(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function Qv(e,t){const n=m.createContext(t),r=s=>{const{children:i,...a}=s,l=m.useMemo(()=>a,Object.values(a));return c.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=m.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function wn(e,t=[]){let n=[];function r(s,i){const a=m.createContext(i),l=n.length;n=[...n,i];const u=f=>{var v;const{scope:h,children:p,...b}=f,x=((v=h==null?void 0:h[e])==null?void 0:v[l])||a,g=m.useMemo(()=>b,Object.values(b));return c.jsx(x.Provider,{value:g,children:p})};u.displayName=s+"Provider";function d(f,h){var x;const p=((x=h==null?void 0:h[e])==null?void 0:x[l])||a,b=m.useContext(p);if(b)return b;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[u,d]}const o=()=>{const s=n.map(i=>m.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return m.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,eb(o,...t)]}function eb(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:u})=>{const f=l(s)[`__scope${u}`];return{...a,...f}},{});return m.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Ct=globalThis!=null&&globalThis.document?m.useLayoutEffect:()=>{},tb=m[" useInsertionEffect ".trim().toString()]||Ct;function ur({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=nb({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=m.useRef(e!==void 0);m.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const u=m.useCallback(d=>{var f;if(a){const h=rb(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[l,u]}function nb({defaultProp:e,onChange:t}){const[n,r]=m.useState(e),o=m.useRef(n),s=m.useRef(t);return tb(()=>{s.current=t},[t]),m.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function rb(e){return typeof e=="function"}function Mu(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function sa(...e){return t=>{let n=!1;const r=e.map(o=>{const s=Mu(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():Mu(e[o],null)}}}}function Ge(...e){return m.useCallback(sa(...e),e)}var ob=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],_e=ob.reduce((e,t)=>{const n=nr.createSlot(`Primitive.${t}`),r=m.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Du(e,t){e&&Eo.flushSync(()=>e.dispatchEvent(t))}function sb(e,t){return m.useReducer((n,r)=>t[n][r]??n,e)}var Ut=e=>{const{present:t,children:n}=e,r=ib(t),o=typeof n=="function"?n({present:r.isPresent}):m.Children.only(n),s=Ge(r.ref,ab(o));return typeof n=="function"||r.isPresent?m.cloneElement(o,{ref:s}):null};Ut.displayName="Presence";function ib(e){const[t,n]=m.useState(),r=m.useRef(null),o=m.useRef(e),s=m.useRef("none"),i=e?"mounted":"unmounted",[a,l]=sb(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return m.useEffect(()=>{const u=os(r.current);s.current=a==="mounted"?u:"none"},[a]),Ct(()=>{const u=r.current,d=o.current;if(d!==e){const h=s.current,p=os(u);e?l("MOUNT"):p==="none"||(u==null?void 0:u.display)==="none"?l("UNMOUNT"):l(d&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Ct(()=>{if(t){let u;const d=t.ownerDocument.defaultView??window,f=p=>{const x=os(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&x&&(l("ANIMATION_END"),!o.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",u=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},h=p=>{p.target===t&&(s.current=os(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(u),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:m.useCallback(u=>{r.current=u?getComputedStyle(u):null,n(u)},[])}}function os(e){return(e==null?void 0:e.animationName)||"none"}function ab(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var lb=m[" useId ".trim().toString()]||(()=>{}),cb=0;function yn(e){const[t,n]=m.useState(lb());return Ct(()=>{n(r=>r??String(cb++))},[e]),e||(t?`radix-${t}`:"")}var ss="Collapsible",[ub,Gk]=wn(ss),[db,ia]=ub(ss),Lu=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:o,disabled:s,onOpenChange:i,...a}=e,[l,u]=ur({prop:r,defaultProp:o??!1,onChange:i,caller:ss});return c.jsx(db,{scope:n,disabled:s,contentId:yn(),open:l,onOpenToggle:m.useCallback(()=>u(d=>!d),[u]),children:c.jsx(_e.div,{"data-state":la(l),"data-disabled":s?"":void 0,...a,ref:t})})});Lu.displayName=ss;var $u="CollapsibleTrigger",Fu=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,o=ia($u,n);return c.jsx(_e.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":la(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...r,ref:t,onClick:fe(e.onClick,o.onOpenToggle)})});Fu.displayName=$u;var aa="CollapsibleContent",fb=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=ia(aa,e.__scopeCollapsible);return c.jsx(Ut,{present:n||o.open,children:({present:s})=>c.jsx(hb,{...r,ref:t,present:s})})});fb.displayName=aa;var hb=m.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:o,...s}=e,i=ia(aa,n),[a,l]=m.useState(r),u=m.useRef(null),d=Ge(t,u),f=m.useRef(0),h=f.current,p=m.useRef(0),b=p.current,x=i.open||a,g=m.useRef(x),v=m.useRef(void 0);return m.useEffect(()=>{const w=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(w)},[]),Ct(()=>{const w=u.current;if(w){v.current=v.current||{transitionDuration:w.style.transitionDuration,animationName:w.style.animationName},w.style.transitionDuration="0s",w.style.animationName="none";const S=w.getBoundingClientRect();f.current=S.height,p.current=S.width,g.current||(w.style.transitionDuration=v.current.transitionDuration,w.style.animationName=v.current.animationName),l(r)}},[i.open,r]),c.jsx(_e.div,{"data-state":la(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!x,...s,ref:d,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":b?`${b}px`:void 0,...e.style},children:x&&o})});function la(e){return e?"open":"closed"}var pb=Lu;const Bu=pb,zu=Fu,co=m.forwardRef(({className:e,...t},n)=>c.jsx("div",{ref:n,className:ee("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));co.displayName="Card";const uo=m.forwardRef(({className:e,...t},n)=>c.jsx("div",{ref:n,className:ee("flex flex-col space-y-1.5 p-6",e),...t}));uo.displayName="CardHeader";const fo=m.forwardRef(({className:e,...t},n)=>c.jsx("h3",{ref:n,className:ee("text-2xl font-semibold leading-none tracking-tight",e),...t}));fo.displayName="CardTitle";const Hu=m.forwardRef(({className:e,...t},n)=>c.jsx("p",{ref:n,className:ee("text-sm text-muted-foreground",e),...t}));Hu.displayName="CardDescription";const is=m.forwardRef(({className:e,...t},n)=>c.jsx("div",{ref:n,className:ee("p-6 pt-0",e),...t}));is.displayName="CardContent";const Uu=m.forwardRef(({className:e,...t},n)=>c.jsx("div",{ref:n,className:ee("flex items-center p-6 pt-0",e),...t}));Uu.displayName="CardFooter";function Wu(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}let dr=Wu();function mb(e){dr=e}const Vu=/[&<>"']/,gb=new RegExp(Vu.source,"g"),Ku=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,xb=new RegExp(Ku.source,"g"),vb={"&":"&","<":"<",">":">",'"':""","'":"'"},qu=e=>vb[e];function jt(e,t){if(t){if(Vu.test(e))return e.replace(gb,qu)}else if(Ku.test(e))return e.replace(xb,qu);return e}const bb=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Gu(e){return e.replace(bb,(t,n)=>(n=n.toLowerCase(),n==="colon"?":":n.charAt(0)==="#"?n.charAt(1)==="x"?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1)):""))}const wb=/(^|[^\[])\^/g;function ot(e,t){e=typeof e=="string"?e:e.source,t=t||"";const n={replace:(r,o)=>(o=o.source||o,o=o.replace(wb,"$1"),e=e.replace(r,o),n),getRegex:()=>new RegExp(e,t)};return n}const yb=/[^\w:]/g,Sb=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function Yu(e,t,n){if(e){let r;try{r=decodeURIComponent(Gu(n)).replace(yb,"").toLowerCase()}catch{return null}if(r.indexOf("javascript:")===0||r.indexOf("vbscript:")===0||r.indexOf("data:")===0)return null}t&&!Sb.test(n)&&(n=Ib(t,n));try{n=encodeURI(n).replace(/%25/g,"%")}catch{return null}return n}const as={},Cb=/^[^:]+:\/*[^/]*$/,kb=/^([^:]+:)[\s\S]*$/,Tb=/^([^:]+:\/*[^/]*)[\s\S]*$/;function Ib(e,t){as[" "+e]||(Cb.test(e)?as[" "+e]=e+"/":as[" "+e]=cs(e,"/",!0)),e=as[" "+e];const n=e.indexOf(":")===-1;return t.substring(0,2)==="//"?n?t:e.replace(kb,"$1")+t:t.charAt(0)==="/"?n?t:e.replace(Tb,"$1")+t:e+t}const ls={exec:function(){}};function Xu(e,t){const n=e.replace(/\|/g,(s,i,a)=>{let l=!1,u=i;for(;--u>=0&&a[u]==="\\";)l=!l;return l?"|":" |"}),r=n.split(/ \|/);let o=0;if(r[0].trim()||r.shift(),r.length>0&&!r[r.length-1].trim()&&r.pop(),r.length>t)r.splice(t);else for(;r.length<t;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(/\\\|/g,"|");return r}function cs(e,t,n){const r=e.length;if(r===0)return"";let o=0;for(;o<r;){const s=e.charAt(r-o-1);if(s===t&&!n)o++;else if(s!==t&&n)o++;else break}return e.slice(0,r-o)}function Eb(e,t){if(e.indexOf(t[1])===-1)return-1;const n=e.length;let r=0,o=0;for(;o<n;o++)if(e[o]==="\\")o++;else if(e[o]===t[0])r++;else if(e[o]===t[1]&&(r--,r<0))return o;return-1}function Nb(e){e&&e.sanitize&&!e.silent&&console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options")}function Ju(e,t){if(t<1)return"";let n="";for(;t>1;)t&1&&(n+=e),t>>=1,e+=e;return n+e}function Zu(e,t,n,r){const o=t.href,s=t.title?jt(t.title):null,i=e[1].replace(/\\([\[\]])/g,"$1");if(e[0].charAt(0)!=="!"){r.state.inLink=!0;const a={type:"link",raw:n,href:o,title:s,text:i,tokens:r.inlineTokens(i)};return r.state.inLink=!1,a}return{type:"image",raw:n,href:o,title:s,text:jt(i)}}function Ab(e,t){const n=e.match(/^(\s+)(?:```)/);if(n===null)return t;const r=n[1];return t.split(`
|
|
40
40
|
`).map(o=>{const s=o.match(/^\s+/);if(s===null)return o;const[i]=s;return i.length>=r.length?o.slice(r.length):o}).join(`
|
|
41
41
|
`)}class ca{constructor(t){this.options=t||dr}space(t){const n=this.rules.block.newline.exec(t);if(n&&n[0].length>0)return{type:"space",raw:n[0]}}code(t){const n=this.rules.block.code.exec(t);if(n){const r=n[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:n[0],codeBlockStyle:"indented",text:this.options.pedantic?r:cs(r,`
|
|
@@ -137,4 +137,4 @@ For more information, see https://radix-ui.com/primitives/docs/components/${t.do
|
|
|
137
137
|
`).replace(/<ul>/gi,"").replace(/<\/ul>/gi,`
|
|
138
138
|
`).replace(/<ol>/gi,"").replace(/<\/ol>/gi,`
|
|
139
139
|
`).replace(/<li>(.*?)<\/li>/gi,`- $1
|
|
140
|
-
`).trim():n.replace(/</g,"<").replace(/>/g,">").trim()}function hy(e,t=_s){if(!e||typeof e!="string")throw new Error("Invalid content: must be a non-empty string");if(e.length>t)throw new Error(`Message exceeds maximum length of ${t} characters`);return e}function py(e){let t;return typeof e=="string"?t=e:typeof e=="object"&&e!==null?t=JSON.stringify(e):t=String(e),hy(t),fy(t)}function ja(e){const t=e+"CollectionProvider",[n,r]=wn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=x=>{const{scope:g,children:v}=x,w=y.useRef(null),S=y.useRef(new Map).current;return c.jsx(o,{scope:g,itemMap:S,collectionRef:w,children:v})};i.displayName=t;const a=e+"CollectionSlot",l=nr.createSlot(a),u=y.forwardRef((x,g)=>{const{scope:v,children:w}=x,S=s(a,v),N=Ge(g,S.collectionRef);return c.jsx(l,{ref:N,children:w})});u.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=nr.createSlot(d),p=y.forwardRef((x,g)=>{const{scope:v,children:w,...S}=x,N=y.useRef(null),k=Ge(g,N),T=s(d,v);return y.useEffect(()=>(T.itemMap.set(N,{ref:N,...S}),()=>void T.itemMap.delete(N))),c.jsx(h,{[f]:"",ref:k,children:w})});p.displayName=d;function b(x){const g=s(e+"CollectionConsumer",x);return y.useCallback(()=>{const w=g.collectionRef.current;if(!w)return[];const S=Array.from(w.querySelectorAll(`[${f}]`));return Array.from(g.itemMap.values()).sort((T,E)=>S.indexOf(T.ref.current)-S.indexOf(E.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:i,Slot:u,ItemSlot:p},b,r]}var my=m.createContext(void 0);function js(e){const t=m.useContext(my);return e||t||"ltr"}const gy=["top","right","bottom","left"],Gn=Math.min,Wt=Math.max,Rs=Math.round,Ps=Math.floor,Cn=e=>({x:e,y:e}),xy={left:"right",right:"left",bottom:"top",top:"bottom"},vy={start:"end",end:"start"};function Ra(e,t,n){return Wt(e,Gn(t,n))}function Dn(e,t){return typeof e=="function"?e(t):e}function Ln(e){return e.split("-")[0]}function Dr(e){return e.split("-")[1]}function Pa(e){return e==="x"?"y":"x"}function Oa(e){return e==="y"?"height":"width"}const by=new Set(["top","bottom"]);function kn(e){return by.has(Ln(e))?"y":"x"}function Ma(e){return Pa(kn(e))}function wy(e,t,n){n===void 0&&(n=!1);const r=Dr(e),o=Ma(e),s=Oa(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=Os(i)),[i,Os(i)]}function yy(e){const t=Os(e);return[Da(e),t,Da(t)]}function Da(e){return e.replace(/start|end/g,t=>vy[t])}const of=["left","right"],sf=["right","left"],Sy=["top","bottom"],Cy=["bottom","top"];function ky(e,t,n){switch(e){case"top":case"bottom":return n?t?sf:of:t?of:sf;case"left":case"right":return t?Sy:Cy;default:return[]}}function Ty(e,t,n,r){const o=Dr(e);let s=ky(Ln(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Da)))),s}function Os(e){return e.replace(/left|right|bottom|top/g,t=>xy[t])}function Iy(e){return{top:0,right:0,bottom:0,left:0,...e}}function af(e){return typeof e!="number"?Iy(e):{top:e,right:e,bottom:e,left:e}}function Ms(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function lf(e,t,n){let{reference:r,floating:o}=e;const s=kn(t),i=Ma(t),a=Oa(i),l=Ln(t),u=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let p;switch(l){case"top":p={x:d,y:r.y-o.height};break;case"bottom":p={x:d,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:f};break;case"left":p={x:r.x-o.width,y:f};break;default:p={x:r.x,y:r.y}}switch(Dr(t)){case"start":p[i]-=h*(n&&u?-1:1);break;case"end":p[i]+=h*(n&&u?-1:1);break}return p}const Ey=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let u=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=lf(u,r,l),h=r,p={},b=0;for(let x=0;x<a.length;x++){const{name:g,fn:v}=a[x],{x:w,y:S,data:N,reset:k}=await v({x:d,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:u,platform:i,elements:{reference:e,floating:t}});d=w??d,f=S??f,p={...p,[g]:{...p[g],...N}},k&&b<=50&&(b++,typeof k=="object"&&(k.placement&&(h=k.placement),k.rects&&(u=k.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):k.rects),{x:d,y:f}=lf(u,h,l)),x=-1)}return{x:d,y:f,placement:h,strategy:o,middlewareData:p}};async function mo(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:u="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:h=!1,padding:p=0}=Dn(t,e),b=af(p),g=a[h?f==="floating"?"reference":"floating":f],v=Ms(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(g)))==null||n?g:g.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:u,rootBoundary:d,strategy:l})),w=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,S=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),N=await(s.isElement==null?void 0:s.isElement(S))?await(s.getScale==null?void 0:s.getScale(S))||{x:1,y:1}:{x:1,y:1},k=Ms(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:S,strategy:l}):w);return{top:(v.top-k.top+b.top)/N.y,bottom:(k.bottom-v.bottom+b.bottom)/N.y,left:(v.left-k.left+b.left)/N.x,right:(k.right-v.right+b.right)/N.x}}const Ny=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=t,{element:u,padding:d=0}=Dn(e,t)||{};if(u==null)return{};const f=af(d),h={x:n,y:r},p=Ma(o),b=Oa(p),x=await i.getDimensions(u),g=p==="y",v=g?"top":"left",w=g?"bottom":"right",S=g?"clientHeight":"clientWidth",N=s.reference[b]+s.reference[p]-h[p]-s.floating[b],k=h[p]-s.reference[p],T=await(i.getOffsetParent==null?void 0:i.getOffsetParent(u));let E=T?T[S]:0;(!E||!await(i.isElement==null?void 0:i.isElement(T)))&&(E=a.floating[S]||s.floating[b]);const A=N/2-k/2,j=E/2-x[b]/2-1,P=Gn(f[v],j),L=Gn(f[w],j),$=P,V=E-x[b]-L,M=E/2-x[b]/2+A,G=Ra($,M,V),K=!l.arrow&&Dr(o)!=null&&M!==G&&s.reference[b]/2-(M<$?P:L)-x[b]/2<0,W=K?M<$?M-$:M-V:0;return{[p]:h[p]+W,data:{[p]:G,centerOffset:M-G-W,...K&&{alignmentOffset:W}},reset:K}}}),Ay=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:u}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:b="none",flipAlignment:x=!0,...g}=Dn(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const v=Ln(o),w=kn(a),S=Ln(a)===a,N=await(l.isRTL==null?void 0:l.isRTL(u.floating)),k=h||(S||!x?[Os(a)]:yy(a)),T=b!=="none";!h&&T&&k.push(...Ty(a,x,b,N));const E=[a,...k],A=await mo(t,g),j=[];let P=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&j.push(A[v]),f){const M=wy(o,i,N);j.push(A[M[0]],A[M[1]])}if(P=[...P,{placement:o,overflows:j}],!j.every(M=>M<=0)){var L,$;const M=(((L=s.flip)==null?void 0:L.index)||0)+1,G=E[M];if(G&&(!(f==="alignment"?w!==kn(G):!1)||P.every(z=>kn(z.placement)===w?z.overflows[0]>0:!0)))return{data:{index:M,overflows:P},reset:{placement:G}};let K=($=P.filter(W=>W.overflows[0]<=0).sort((W,z)=>W.overflows[1]-z.overflows[1])[0])==null?void 0:$.placement;if(!K)switch(p){case"bestFit":{var V;const W=(V=P.filter(z=>{if(T){const B=kn(z.placement);return B===w||B==="y"}return!0}).map(z=>[z.placement,z.overflows.filter(B=>B>0).reduce((B,ue)=>B+ue,0)]).sort((z,B)=>z[1]-B[1])[0])==null?void 0:V[0];W&&(K=W);break}case"initialPlacement":K=a;break}if(o!==K)return{reset:{placement:K}}}return{}}}};function cf(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function uf(e){return gy.some(t=>e[t]>=0)}const _y=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Dn(e,t);switch(r){case"referenceHidden":{const s=await mo(t,{...o,elementContext:"reference"}),i=cf(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:uf(i)}}}case"escaped":{const s=await mo(t,{...o,altBoundary:!0}),i=cf(s,n.floating);return{data:{escapedOffsets:i,escaped:uf(i)}}}default:return{}}}}},df=new Set(["left","top"]);async function jy(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Ln(n),a=Dr(n),l=kn(n)==="y",u=df.has(i)?-1:1,d=s&&l?-1:1,f=Dn(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:b}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof b=="number"&&(p=a==="end"?b*-1:b),l?{x:p*d,y:h*u}:{x:h*u,y:p*d}}const Ry=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,l=await jy(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},Py=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:g=>{let{x:v,y:w}=g;return{x:v,y:w}}},...l}=Dn(e,t),u={x:n,y:r},d=await mo(t,l),f=kn(Ln(o)),h=Pa(f);let p=u[h],b=u[f];if(s){const g=h==="y"?"top":"left",v=h==="y"?"bottom":"right",w=p+d[g],S=p-d[v];p=Ra(w,p,S)}if(i){const g=f==="y"?"top":"left",v=f==="y"?"bottom":"right",w=b+d[g],S=b-d[v];b=Ra(w,b,S)}const x=a.fn({...t,[h]:p,[f]:b});return{...x,data:{x:x.x-n,y:x.y-r,enabled:{[h]:s,[f]:i}}}}}},Oy=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:l=!0,crossAxis:u=!0}=Dn(e,t),d={x:n,y:r},f=kn(o),h=Pa(f);let p=d[h],b=d[f];const x=Dn(a,t),g=typeof x=="number"?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(l){const S=h==="y"?"height":"width",N=s.reference[h]-s.floating[S]+g.mainAxis,k=s.reference[h]+s.reference[S]-g.mainAxis;p<N?p=N:p>k&&(p=k)}if(u){var v,w;const S=h==="y"?"width":"height",N=df.has(Ln(o)),k=s.reference[f]-s.floating[S]+(N&&((v=i.offset)==null?void 0:v[f])||0)+(N?0:g.crossAxis),T=s.reference[f]+s.reference[S]+(N?0:((w=i.offset)==null?void 0:w[f])||0)-(N?g.crossAxis:0);b<k?b=k:b>T&&(b=T)}return{[h]:p,[f]:b}}}},My=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:l=()=>{},...u}=Dn(e,t),d=await mo(t,u),f=Ln(o),h=Dr(o),p=kn(o)==="y",{width:b,height:x}=s.floating;let g,v;f==="top"||f==="bottom"?(g=f,v=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(v=f,g=h==="end"?"top":"bottom");const w=x-d.top-d.bottom,S=b-d.left-d.right,N=Gn(x-d[g],w),k=Gn(b-d[v],S),T=!t.middlewareData.shift;let E=N,A=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(A=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=w),T&&!h){const P=Wt(d.left,0),L=Wt(d.right,0),$=Wt(d.top,0),V=Wt(d.bottom,0);p?A=b-2*(P!==0||L!==0?P+L:Wt(d.left,d.right)):E=x-2*($!==0||V!==0?$+V:Wt(d.top,d.bottom))}await l({...t,availableWidth:A,availableHeight:E});const j=await i.getDimensions(a.floating);return b!==j.width||x!==j.height?{reset:{rects:!0}}:{}}}};function Ds(){return typeof window<"u"}function Lr(e){return ff(e)?(e.nodeName||"").toLowerCase():"#document"}function Vt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Tn(e){var t;return(t=(ff(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function ff(e){return Ds()?e instanceof Node||e instanceof Vt(e).Node:!1}function ln(e){return Ds()?e instanceof Element||e instanceof Vt(e).Element:!1}function In(e){return Ds()?e instanceof HTMLElement||e instanceof Vt(e).HTMLElement:!1}function hf(e){return!Ds()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Vt(e).ShadowRoot}const Dy=new Set(["inline","contents"]);function go(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=cn(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!Dy.has(o)}const Ly=new Set(["table","td","th"]);function $y(e){return Ly.has(Lr(e))}const Fy=[":popover-open",":modal"];function Ls(e){return Fy.some(t=>{try{return e.matches(t)}catch{return!1}})}const By=["transform","translate","scale","rotate","perspective"],zy=["transform","translate","scale","rotate","perspective","filter"],Hy=["paint","layout","strict","content"];function La(e){const t=$a(),n=ln(e)?cn(e):e;return By.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||zy.some(r=>(n.willChange||"").includes(r))||Hy.some(r=>(n.contain||"").includes(r))}function Uy(e){let t=Yn(e);for(;In(t)&&!$r(t);){if(La(t))return t;if(Ls(t))return null;t=Yn(t)}return null}function $a(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Wy=new Set(["html","body","#document"]);function $r(e){return Wy.has(Lr(e))}function cn(e){return Vt(e).getComputedStyle(e)}function $s(e){return ln(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Yn(e){if(Lr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||hf(e)&&e.host||Tn(e);return hf(t)?t.host:t}function pf(e){const t=Yn(e);return $r(t)?e.ownerDocument?e.ownerDocument.body:e.body:In(t)&&go(t)?t:pf(t)}function xo(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=pf(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=Vt(o);if(s){const a=Fa(i);return t.concat(i,i.visualViewport||[],go(o)?o:[],a&&n?xo(a):[])}return t.concat(o,xo(o,[],n))}function Fa(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function mf(e){const t=cn(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=In(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Rs(n)!==s||Rs(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function Ba(e){return ln(e)?e:e.contextElement}function Fr(e){const t=Ba(e);if(!In(t))return Cn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=mf(t);let i=(s?Rs(n.width):n.width)/r,a=(s?Rs(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const Vy=Cn(0);function gf(e){const t=Vt(e);return!$a()||!t.visualViewport?Vy:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Ky(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Vt(e)?!1:t}function mr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=Ba(e);let i=Cn(1);t&&(r?ln(r)&&(i=Fr(r)):i=Fr(e));const a=Ky(s,n,r)?gf(s):Cn(0);let l=(o.left+a.x)/i.x,u=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const h=Vt(s),p=r&&ln(r)?Vt(r):r;let b=h,x=Fa(b);for(;x&&r&&p!==b;){const g=Fr(x),v=x.getBoundingClientRect(),w=cn(x),S=v.left+(x.clientLeft+parseFloat(w.paddingLeft))*g.x,N=v.top+(x.clientTop+parseFloat(w.paddingTop))*g.y;l*=g.x,u*=g.y,d*=g.x,f*=g.y,l+=S,u+=N,b=Vt(x),x=Fa(b)}}return Ms({width:d,height:f,x:l,y:u})}function Fs(e,t){const n=$s(e).scrollLeft;return t?t.left+n:mr(Tn(e)).left+n}function xf(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Fs(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function qy(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=Tn(r),a=t?Ls(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},u=Cn(1);const d=Cn(0),f=In(r);if((f||!f&&!s)&&((Lr(r)!=="body"||go(i))&&(l=$s(r)),In(r))){const p=mr(r);u=Fr(r),d.x=p.x+r.clientLeft,d.y=p.y+r.clientTop}const h=i&&!f&&!s?xf(i,l):Cn(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+d.x+h.x,y:n.y*u.y-l.scrollTop*u.y+d.y+h.y}}function Gy(e){return Array.from(e.getClientRects())}function Yy(e){const t=Tn(e),n=$s(e),r=e.ownerDocument.body,o=Wt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Wt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Fs(e);const a=-n.scrollTop;return cn(r).direction==="rtl"&&(i+=Wt(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const vf=25;function Xy(e,t){const n=Vt(e),r=Tn(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const d=$a();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const u=Fs(r);if(u<=0){const d=r.ownerDocument,f=d.body,h=getComputedStyle(f),p=d.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,b=Math.abs(r.clientWidth-f.clientWidth-p);b<=vf&&(s-=b)}else u<=vf&&(s+=u);return{width:s,height:i,x:a,y:l}}const Jy=new Set(["absolute","fixed"]);function Zy(e,t){const n=mr(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=In(e)?Fr(e):Cn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,u=r*s.y;return{width:i,height:a,x:l,y:u}}function bf(e,t,n){let r;if(t==="viewport")r=Xy(e,n);else if(t==="document")r=Yy(Tn(e));else if(ln(t))r=Zy(t,n);else{const o=gf(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Ms(r)}function wf(e,t){const n=Yn(e);return n===t||!ln(n)||$r(n)?!1:cn(n).position==="fixed"||wf(n,t)}function Qy(e,t){const n=t.get(e);if(n)return n;let r=xo(e,[],!1).filter(a=>ln(a)&&Lr(a)!=="body"),o=null;const s=cn(e).position==="fixed";let i=s?Yn(e):e;for(;ln(i)&&!$r(i);){const a=cn(i),l=La(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&Jy.has(o.position)||go(i)&&!l&&wf(e,i))?r=r.filter(d=>d!==i):o=a,i=Yn(i)}return t.set(e,r),r}function e0(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Ls(t)?[]:Qy(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((u,d)=>{const f=bf(t,d,o);return u.top=Wt(f.top,u.top),u.right=Gn(f.right,u.right),u.bottom=Gn(f.bottom,u.bottom),u.left=Wt(f.left,u.left),u},bf(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function t0(e){const{width:t,height:n}=mf(e);return{width:t,height:n}}function n0(e,t,n){const r=In(t),o=Tn(t),s=n==="fixed",i=mr(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=Cn(0);function u(){l.x=Fs(o)}if(r||!r&&!s)if((Lr(t)!=="body"||go(o))&&(a=$s(t)),r){const p=mr(t,!0,s,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else o&&u();s&&!r&&o&&u();const d=o&&!r&&!s?xf(o,a):Cn(0),f=i.left+a.scrollLeft-l.x-d.x,h=i.top+a.scrollTop-l.y-d.y;return{x:f,y:h,width:i.width,height:i.height}}function za(e){return cn(e).position==="static"}function yf(e,t){if(!In(e)||cn(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Tn(e)===n&&(n=n.ownerDocument.body),n}function Sf(e,t){const n=Vt(e);if(Ls(e))return n;if(!In(e)){let o=Yn(e);for(;o&&!$r(o);){if(ln(o)&&!za(o))return o;o=Yn(o)}return n}let r=yf(e,t);for(;r&&$y(r)&&za(r);)r=yf(r,t);return r&&$r(r)&&za(r)&&!La(r)?n:r||Uy(e)||n}const r0=async function(e){const t=this.getOffsetParent||Sf,n=this.getDimensions,r=await n(e.floating);return{reference:n0(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function o0(e){return cn(e).direction==="rtl"}const s0={convertOffsetParentRelativeRectToViewportRelativeRect:qy,getDocumentElement:Tn,getClippingRect:e0,getOffsetParent:Sf,getElementRects:r0,getClientRects:Gy,getDimensions:t0,getScale:Fr,isElement:ln,isRTL:o0};function Cf(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function i0(e,t){let n=null,r;const o=Tn(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const u=e.getBoundingClientRect(),{left:d,top:f,width:h,height:p}=u;if(a||t(),!h||!p)return;const b=Ps(f),x=Ps(o.clientWidth-(d+h)),g=Ps(o.clientHeight-(f+p)),v=Ps(d),S={rootMargin:-b+"px "+-x+"px "+-g+"px "+-v+"px",threshold:Wt(0,Gn(1,l))||1};let N=!0;function k(T){const E=T[0].intersectionRatio;if(E!==l){if(!N)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!Cf(u,e.getBoundingClientRect())&&i(),N=!1}try{n=new IntersectionObserver(k,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,S)}n.observe(e)}return i(!0),s}function a0(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,u=Ba(e),d=o||s?[...u?xo(u):[],...xo(t)]:[];d.forEach(v=>{o&&v.addEventListener("scroll",n,{passive:!0}),s&&v.addEventListener("resize",n)});const f=u&&a?i0(u,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(v=>{let[w]=v;w&&w.target===u&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var S;(S=p)==null||S.observe(t)})),n()}),u&&!l&&p.observe(u),p.observe(t));let b,x=l?mr(e):null;l&&g();function g(){const v=mr(e);x&&!Cf(x,v)&&n(),x=v,b=requestAnimationFrame(g)}return n(),()=>{var v;d.forEach(w=>{o&&w.removeEventListener("scroll",n),s&&w.removeEventListener("resize",n)}),f==null||f(),(v=p)==null||v.disconnect(),p=null,l&&cancelAnimationFrame(b)}}const l0=Ry,c0=Py,u0=Ay,d0=My,f0=_y,kf=Ny,h0=Oy,p0=(e,t,n)=>{const r=new Map,o={platform:s0,...n},s={...o.platform,_c:r};return Ey(e,t,{...o,platform:s})};var m0=typeof document<"u",g0=function(){},Bs=m0?y.useLayoutEffect:g0;function zs(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!zs(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!zs(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function Tf(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function If(e,t){const n=Tf(e);return Math.round(t*n)/n}function Ha(e){const t=m.useRef(e);return Bs(()=>{t.current=e}),t}function x0(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:u}=e,[d,f]=m.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[h,p]=m.useState(r);zs(h,r)||p(r);const[b,x]=m.useState(null),[g,v]=m.useState(null),w=m.useCallback(z=>{z!==T.current&&(T.current=z,x(z))},[]),S=m.useCallback(z=>{z!==E.current&&(E.current=z,v(z))},[]),N=s||b,k=i||g,T=m.useRef(null),E=m.useRef(null),A=m.useRef(d),j=l!=null,P=Ha(l),L=Ha(o),$=Ha(u),V=m.useCallback(()=>{if(!T.current||!E.current)return;const z={placement:t,strategy:n,middleware:h};L.current&&(z.platform=L.current),p0(T.current,E.current,z).then(B=>{const ue={...B,isPositioned:$.current!==!1};M.current&&!zs(A.current,ue)&&(A.current=ue,Eo.flushSync(()=>{f(ue)}))})},[h,t,n,L,$]);Bs(()=>{u===!1&&A.current.isPositioned&&(A.current.isPositioned=!1,f(z=>({...z,isPositioned:!1})))},[u]);const M=m.useRef(!1);Bs(()=>(M.current=!0,()=>{M.current=!1}),[]),Bs(()=>{if(N&&(T.current=N),k&&(E.current=k),N&&k){if(P.current)return P.current(N,k,V);V()}},[N,k,V,P,j]);const G=m.useMemo(()=>({reference:T,floating:E,setReference:w,setFloating:S}),[w,S]),K=m.useMemo(()=>({reference:N,floating:k}),[N,k]),W=m.useMemo(()=>{const z={position:n,left:0,top:0};if(!K.floating)return z;const B=If(K.floating,d.x),ue=If(K.floating,d.y);return a?{...z,transform:"translate("+B+"px, "+ue+"px)",...Tf(K.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:B,top:ue}},[n,a,K.floating,d.x,d.y]);return m.useMemo(()=>({...d,update:V,refs:G,elements:K,floatingStyles:W}),[d,V,G,K,W])}const v0=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?kf({element:r.current,padding:o}).fn(n):{}:r?kf({element:r,padding:o}).fn(n):{}}}},b0=(e,t)=>({...l0(e),options:[e,t]}),w0=(e,t)=>({...c0(e),options:[e,t]}),y0=(e,t)=>({...h0(e),options:[e,t]}),S0=(e,t)=>({...u0(e),options:[e,t]}),C0=(e,t)=>({...d0(e),options:[e,t]}),k0=(e,t)=>({...f0(e),options:[e,t]}),T0=(e,t)=>({...v0(e),options:[e,t]});var I0="Arrow",Ef=m.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return c.jsx(_e.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:c.jsx("polygon",{points:"0,0 30,0 15,10"})})});Ef.displayName=I0;var E0=Ef;function Nf(e){const[t,n]=m.useState(void 0);return Ct(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,u=Array.isArray(l)?l[0]:l;i=u.inlineSize,a=u.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Ua="Popper",[Af,Hs]=wn(Ua),[N0,_f]=Af(Ua),jf=e=>{const{__scopePopper:t,children:n}=e,[r,o]=m.useState(null);return c.jsx(N0,{scope:t,anchor:r,onAnchorChange:o,children:n})};jf.displayName=Ua;var Rf="PopperAnchor",Pf=m.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=_f(Rf,n),i=m.useRef(null),a=Ge(t,i),l=m.useRef(null);return m.useEffect(()=>{const u=l.current;l.current=(r==null?void 0:r.current)||i.current,u!==l.current&&s.onAnchorChange(l.current)}),r?null:c.jsx(_e.div,{...o,ref:a})});Pf.displayName=Rf;var Wa="PopperContent",[A0,_0]=Af(Wa),Of=m.forwardRef((e,t)=>{var q,O,X,ne,pe,se;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:h=!1,updatePositionStrategy:p="optimized",onPlaced:b,...x}=e,g=_f(Wa,n),[v,w]=m.useState(null),S=Ge(t,me=>w(me)),[N,k]=m.useState(null),T=Nf(N),E=(T==null?void 0:T.width)??0,A=(T==null?void 0:T.height)??0,j=r+(s!=="center"?"-"+s:""),P=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},L=Array.isArray(u)?u:[u],$=L.length>0,V={padding:P,boundary:L.filter(R0),altBoundary:$},{refs:M,floatingStyles:G,placement:K,isPositioned:W,middlewareData:z}=x0({strategy:"fixed",placement:j,whileElementsMounted:(...me)=>a0(...me,{animationFrame:p==="always"}),elements:{reference:g.anchor},middleware:[b0({mainAxis:o+A,alignmentAxis:i}),l&&w0({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?y0():void 0,...V}),l&&S0({...V}),C0({...V,apply:({elements:me,rects:et,availableWidth:tt,availableHeight:Pe})=>{const{width:Ve,height:ut}=et.reference,nt=me.floating.style;nt.setProperty("--radix-popper-available-width",`${tt}px`),nt.setProperty("--radix-popper-available-height",`${Pe}px`),nt.setProperty("--radix-popper-anchor-width",`${Ve}px`),nt.setProperty("--radix-popper-anchor-height",`${ut}px`)}}),N&&T0({element:N,padding:a}),P0({arrowWidth:E,arrowHeight:A}),h&&k0({strategy:"referenceHidden",...V})]}),[B,ue]=Lf(K),D=Tt(b);Ct(()=>{W&&(D==null||D())},[W,D]);const te=(q=z.arrow)==null?void 0:q.x,he=(O=z.arrow)==null?void 0:O.y,we=((X=z.arrow)==null?void 0:X.centerOffset)!==0,[ye,Se]=m.useState();return Ct(()=>{v&&Se(window.getComputedStyle(v).zIndex)},[v]),c.jsx("div",{ref:M.setFloating,"data-radix-popper-content-wrapper":"",style:{...G,transform:W?G.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ye,"--radix-popper-transform-origin":[(ne=z.transformOrigin)==null?void 0:ne.x,(pe=z.transformOrigin)==null?void 0:pe.y].join(" "),...((se=z.hide)==null?void 0:se.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:c.jsx(A0,{scope:n,placedSide:B,onArrowChange:k,arrowX:te,arrowY:he,shouldHideArrow:we,children:c.jsx(_e.div,{"data-side":B,"data-align":ue,...x,ref:S,style:{...x.style,animation:W?void 0:"none"}})})})});Of.displayName=Wa;var Mf="PopperArrow",j0={top:"bottom",right:"left",bottom:"top",left:"right"},Df=m.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=_0(Mf,r),i=j0[s.placedSide];return c.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:c.jsx(E0,{...o,ref:n,style:{...o.style,display:"block"}})})});Df.displayName=Mf;function R0(e){return e!==null}var P0=e=>({name:"transformOrigin",options:e,fn(t){var g,v,w;const{placement:n,rects:r,middlewareData:o}=t,i=((g=o.arrow)==null?void 0:g.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[u,d]=Lf(n),f={start:"0%",center:"50%",end:"100%"}[d],h=(((v=o.arrow)==null?void 0:v.x)??0)+a/2,p=(((w=o.arrow)==null?void 0:w.y)??0)+l/2;let b="",x="";return u==="bottom"?(b=i?f:`${h}px`,x=`${-l}px`):u==="top"?(b=i?f:`${h}px`,x=`${r.floating.height+l}px`):u==="right"?(b=`${-l}px`,x=i?f:`${p}px`):u==="left"&&(b=`${r.floating.width+l}px`,x=i?f:`${p}px`),{data:{x:b,y:x}}}});function Lf(e){const[t,n="center"]=e.split("-");return[t,n]}var $f=jf,Ff=Pf,Bf=Of,zf=Df,Va="rovingFocusGroup.onEntryFocus",O0={bubbles:!1,cancelable:!0},vo="RovingFocusGroup",[Ka,Hf,M0]=ja(vo),[D0,Uf]=wn(vo,[M0]),[L0,$0]=D0(vo),Wf=m.forwardRef((e,t)=>c.jsx(Ka.Provider,{scope:e.__scopeRovingFocusGroup,children:c.jsx(Ka.Slot,{scope:e.__scopeRovingFocusGroup,children:c.jsx(F0,{...e,ref:t})})}));Wf.displayName=vo;var F0=m.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:u,preventScrollOnEntryFocus:d=!1,...f}=e,h=m.useRef(null),p=Ge(t,h),b=js(s),[x,g]=ur({prop:i,defaultProp:a??null,onChange:l,caller:vo}),[v,w]=m.useState(!1),S=Tt(u),N=Hf(n),k=m.useRef(!1),[T,E]=m.useState(0);return m.useEffect(()=>{const A=h.current;if(A)return A.addEventListener(Va,S),()=>A.removeEventListener(Va,S)},[S]),c.jsx(L0,{scope:n,orientation:r,dir:b,loop:o,currentTabStopId:x,onItemFocus:m.useCallback(A=>g(A),[g]),onItemShiftTab:m.useCallback(()=>w(!0),[]),onFocusableItemAdd:m.useCallback(()=>E(A=>A+1),[]),onFocusableItemRemove:m.useCallback(()=>E(A=>A-1),[]),children:c.jsx(_e.div,{tabIndex:v||T===0?-1:0,"data-orientation":r,...f,ref:p,style:{outline:"none",...e.style},onMouseDown:fe(e.onMouseDown,()=>{k.current=!0}),onFocus:fe(e.onFocus,A=>{const j=!k.current;if(A.target===A.currentTarget&&j&&!v){const P=new CustomEvent(Va,O0);if(A.currentTarget.dispatchEvent(P),!P.defaultPrevented){const L=N().filter(K=>K.focusable),$=L.find(K=>K.active),V=L.find(K=>K.id===x),G=[$,V,...L].filter(Boolean).map(K=>K.ref.current);qf(G,d)}}k.current=!1}),onBlur:fe(e.onBlur,()=>w(!1))})})}),Vf="RovingFocusGroupItem",Kf=m.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=yn(),u=s||l,d=$0(Vf,n),f=d.currentTabStopId===u,h=Hf(n),{onFocusableItemAdd:p,onFocusableItemRemove:b,currentTabStopId:x}=d;return m.useEffect(()=>{if(r)return p(),()=>b()},[r,p,b]),c.jsx(Ka.ItemSlot,{scope:n,id:u,focusable:r,active:o,children:c.jsx(_e.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:fe(e.onMouseDown,g=>{r?d.onItemFocus(u):g.preventDefault()}),onFocus:fe(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:fe(e.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){d.onItemShiftTab();return}if(g.target!==g.currentTarget)return;const v=H0(g,d.orientation,d.dir);if(v!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let S=h().filter(N=>N.focusable).map(N=>N.ref.current);if(v==="last")S.reverse();else if(v==="prev"||v==="next"){v==="prev"&&S.reverse();const N=S.indexOf(g.currentTarget);S=d.loop?U0(S,N+1):S.slice(N+1)}setTimeout(()=>qf(S))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:x!=null}):i})})});Kf.displayName=Vf;var B0={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function z0(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function H0(e,t,n){const r=z0(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return B0[r]}function qf(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function U0(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var W0=Wf,V0=Kf,qa=["Enter"," "],K0=["ArrowDown","PageUp","Home"],Gf=["ArrowUp","PageDown","End"],q0=[...K0,...Gf],G0={ltr:[...qa,"ArrowRight"],rtl:[...qa,"ArrowLeft"]},Y0={ltr:["ArrowLeft"],rtl:["ArrowRight"]},bo="Menu",[wo,X0,J0]=ja(bo),[gr,Yf]=wn(bo,[J0,Hs,Uf]),Us=Hs(),Xf=Uf(),[Z0,xr]=gr(bo),[Q0,yo]=gr(bo),Jf=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:s,modal:i=!0}=e,a=Us(t),[l,u]=m.useState(null),d=m.useRef(!1),f=Tt(s),h=js(o);return m.useEffect(()=>{const p=()=>{d.current=!0,document.addEventListener("pointerdown",b,{capture:!0,once:!0}),document.addEventListener("pointermove",b,{capture:!0,once:!0})},b=()=>d.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",b,{capture:!0}),document.removeEventListener("pointermove",b,{capture:!0})}},[]),c.jsx($f,{...a,children:c.jsx(Z0,{scope:t,open:n,onOpenChange:f,content:l,onContentChange:u,children:c.jsx(Q0,{scope:t,onClose:m.useCallback(()=>f(!1),[f]),isUsingKeyboardRef:d,dir:h,modal:i,children:r})})})};Jf.displayName=bo;var eS="MenuAnchor",Ga=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=Us(n);return c.jsx(Ff,{...o,...r,ref:t})});Ga.displayName=eS;var Ya="MenuPortal",[tS,Zf]=gr(Ya,{forceMount:void 0}),Qf=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,s=xr(Ya,t);return c.jsx(tS,{scope:t,forceMount:n,children:c.jsx(Ut,{present:n||s.open,children:c.jsx(ms,{asChild:!0,container:o,children:r})})})};Qf.displayName=Ya;var Yt="MenuContent",[nS,Xa]=gr(Yt),eh=m.forwardRef((e,t)=>{const n=Zf(Yt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=xr(Yt,e.__scopeMenu),i=yo(Yt,e.__scopeMenu);return c.jsx(wo.Provider,{scope:e.__scopeMenu,children:c.jsx(Ut,{present:r||s.open,children:c.jsx(wo.Slot,{scope:e.__scopeMenu,children:i.modal?c.jsx(rS,{...o,ref:t}):c.jsx(oS,{...o,ref:t})})})})}),rS=m.forwardRef((e,t)=>{const n=xr(Yt,e.__scopeMenu),r=m.useRef(null),o=Ge(t,r);return m.useEffect(()=>{const s=r.current;if(s)return Ta(s)},[]),c.jsx(Ja,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:fe(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),oS=m.forwardRef((e,t)=>{const n=xr(Yt,e.__scopeMenu);return c.jsx(Ja,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),sS=nr.createSlot("MenuContent.ScrollLock"),Ja=m.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:u,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:h,onDismiss:p,disableOutsideScroll:b,...x}=e,g=xr(Yt,n),v=yo(Yt,n),w=Us(n),S=Xf(n),N=X0(n),[k,T]=m.useState(null),E=m.useRef(null),A=Ge(t,E,g.onContentChange),j=m.useRef(0),P=m.useRef(""),L=m.useRef(0),$=m.useRef(null),V=m.useRef("right"),M=m.useRef(0),G=b?ys:m.Fragment,K=b?{as:sS,allowPinchZoom:!0}:void 0,W=B=>{var q,O;const ue=P.current+B,D=N().filter(X=>!X.disabled),te=document.activeElement,he=(q=D.find(X=>X.ref.current===te))==null?void 0:q.textValue,we=D.map(X=>X.textValue),ye=xS(we,ue,he),Se=(O=D.find(X=>X.textValue===ye))==null?void 0:O.ref.current;(function X(ne){P.current=ne,window.clearTimeout(j.current),ne!==""&&(j.current=window.setTimeout(()=>X(""),1e3))})(ue),Se&&setTimeout(()=>Se.focus())};m.useEffect(()=>()=>window.clearTimeout(j.current),[]),ba();const z=m.useCallback(B=>{var D,te;return V.current===((D=$.current)==null?void 0:D.side)&&bS(B,(te=$.current)==null?void 0:te.area)},[]);return c.jsx(nS,{scope:n,searchRef:P,onItemEnter:m.useCallback(B=>{z(B)&&B.preventDefault()},[z]),onItemLeave:m.useCallback(B=>{var ue;z(B)||((ue=E.current)==null||ue.focus(),T(null))},[z]),onTriggerLeave:m.useCallback(B=>{z(B)&&B.preventDefault()},[z]),pointerGraceTimerRef:L,onPointerGraceIntentChange:m.useCallback(B=>{$.current=B},[]),children:c.jsx(G,{...K,children:c.jsx(ps,{asChild:!0,trapped:o,onMountAutoFocus:fe(s,B=>{var ue;B.preventDefault(),(ue=E.current)==null||ue.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:c.jsx(hs,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:u,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:h,onDismiss:p,children:c.jsx(W0,{asChild:!0,...S,dir:v.dir,orientation:"vertical",loop:r,currentTabStopId:k,onCurrentTabStopIdChange:T,onEntryFocus:fe(l,B=>{v.isUsingKeyboardRef.current||B.preventDefault()}),preventScrollOnEntryFocus:!0,children:c.jsx(Bf,{role:"menu","aria-orientation":"vertical","data-state":xh(g.open),"data-radix-menu-content":"",dir:v.dir,...w,...x,ref:A,style:{outline:"none",...x.style},onKeyDown:fe(x.onKeyDown,B=>{const D=B.target.closest("[data-radix-menu-content]")===B.currentTarget,te=B.ctrlKey||B.altKey||B.metaKey,he=B.key.length===1;D&&(B.key==="Tab"&&B.preventDefault(),!te&&he&&W(B.key));const we=E.current;if(B.target!==we||!q0.includes(B.key))return;B.preventDefault();const Se=N().filter(q=>!q.disabled).map(q=>q.ref.current);Gf.includes(B.key)&&Se.reverse(),mS(Se)}),onBlur:fe(e.onBlur,B=>{B.currentTarget.contains(B.target)||(window.clearTimeout(j.current),P.current="")}),onPointerMove:fe(e.onPointerMove,Co(B=>{const ue=B.target,D=M.current!==B.clientX;if(B.currentTarget.contains(ue)&&D){const te=B.clientX>M.current?"right":"left";V.current=te,M.current=B.clientX}}))})})})})})})});eh.displayName=Yt;var iS="MenuGroup",Za=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return c.jsx(_e.div,{role:"group",...r,ref:t})});Za.displayName=iS;var aS="MenuLabel",th=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return c.jsx(_e.div,{...r,ref:t})});th.displayName=aS;var Ws="MenuItem",nh="menu.itemSelect",Vs=m.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,s=m.useRef(null),i=yo(Ws,e.__scopeMenu),a=Xa(Ws,e.__scopeMenu),l=Ge(t,s),u=m.useRef(!1),d=()=>{const f=s.current;if(!n&&f){const h=new CustomEvent(nh,{bubbles:!0,cancelable:!0});f.addEventListener(nh,p=>r==null?void 0:r(p),{once:!0}),Du(f,h),h.defaultPrevented?u.current=!1:i.onClose()}};return c.jsx(rh,{...o,ref:l,disabled:n,onClick:fe(e.onClick,d),onPointerDown:f=>{var h;(h=e.onPointerDown)==null||h.call(e,f),u.current=!0},onPointerUp:fe(e.onPointerUp,f=>{var h;u.current||(h=f.currentTarget)==null||h.click()}),onKeyDown:fe(e.onKeyDown,f=>{const h=a.searchRef.current!=="";n||h&&f.key===" "||qa.includes(f.key)&&(f.currentTarget.click(),f.preventDefault())})})});Vs.displayName=Ws;var rh=m.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...s}=e,i=Xa(Ws,n),a=Xf(n),l=m.useRef(null),u=Ge(t,l),[d,f]=m.useState(!1),[h,p]=m.useState("");return m.useEffect(()=>{const b=l.current;b&&p((b.textContent??"").trim())},[s.children]),c.jsx(wo.ItemSlot,{scope:n,disabled:r,textValue:o??h,children:c.jsx(V0,{asChild:!0,...a,focusable:!r,children:c.jsx(_e.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:u,onPointerMove:fe(e.onPointerMove,Co(b=>{r?i.onItemLeave(b):(i.onItemEnter(b),b.defaultPrevented||b.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:fe(e.onPointerLeave,Co(b=>i.onItemLeave(b))),onFocus:fe(e.onFocus,()=>f(!0)),onBlur:fe(e.onBlur,()=>f(!1))})})})}),lS="MenuCheckboxItem",oh=m.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return c.jsx(ch,{scope:e.__scopeMenu,checked:n,children:c.jsx(Vs,{role:"menuitemcheckbox","aria-checked":Ks(n)?"mixed":n,...o,ref:t,"data-state":el(n),onSelect:fe(o.onSelect,()=>r==null?void 0:r(Ks(n)?!0:!n),{checkForDefaultPrevented:!1})})})});oh.displayName=lS;var sh="MenuRadioGroup",[cS,uS]=gr(sh,{value:void 0,onValueChange:()=>{}}),ih=m.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,s=Tt(r);return c.jsx(cS,{scope:e.__scopeMenu,value:n,onValueChange:s,children:c.jsx(Za,{...o,ref:t})})});ih.displayName=sh;var ah="MenuRadioItem",lh=m.forwardRef((e,t)=>{const{value:n,...r}=e,o=uS(ah,e.__scopeMenu),s=n===o.value;return c.jsx(ch,{scope:e.__scopeMenu,checked:s,children:c.jsx(Vs,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":el(s),onSelect:fe(r.onSelect,()=>{var i;return(i=o.onValueChange)==null?void 0:i.call(o,n)},{checkForDefaultPrevented:!1})})})});lh.displayName=ah;var Qa="MenuItemIndicator",[ch,dS]=gr(Qa,{checked:!1}),uh=m.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,s=dS(Qa,n);return c.jsx(Ut,{present:r||Ks(s.checked)||s.checked===!0,children:c.jsx(_e.span,{...o,ref:t,"data-state":el(s.checked)})})});uh.displayName=Qa;var fS="MenuSeparator",dh=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return c.jsx(_e.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});dh.displayName=fS;var hS="MenuArrow",fh=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=Us(n);return c.jsx(zf,{...o,...r,ref:t})});fh.displayName=hS;var pS="MenuSub",[Jk,hh]=gr(pS),So="MenuSubTrigger",ph=m.forwardRef((e,t)=>{const n=xr(So,e.__scopeMenu),r=yo(So,e.__scopeMenu),o=hh(So,e.__scopeMenu),s=Xa(So,e.__scopeMenu),i=m.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=s,u={__scopeMenu:e.__scopeMenu},d=m.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return m.useEffect(()=>d,[d]),m.useEffect(()=>{const f=a.current;return()=>{window.clearTimeout(f),l(null)}},[a,l]),c.jsx(Ga,{asChild:!0,...u,children:c.jsx(rh,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":xh(n.open),...e,ref:sa(t,o.onTriggerChange),onClick:f=>{var h;(h=e.onClick)==null||h.call(e,f),!(e.disabled||f.defaultPrevented)&&(f.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:fe(e.onPointerMove,Co(f=>{s.onItemEnter(f),!f.defaultPrevented&&!e.disabled&&!n.open&&!i.current&&(s.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{n.onOpenChange(!0),d()},100))})),onPointerLeave:fe(e.onPointerLeave,Co(f=>{var p,b;d();const h=(p=n.content)==null?void 0:p.getBoundingClientRect();if(h){const x=(b=n.content)==null?void 0:b.dataset.side,g=x==="right",v=g?-5:5,w=h[g?"left":"right"],S=h[g?"right":"left"];s.onPointerGraceIntentChange({area:[{x:f.clientX+v,y:f.clientY},{x:w,y:h.top},{x:S,y:h.top},{x:S,y:h.bottom},{x:w,y:h.bottom}],side:x}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(f),f.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:fe(e.onKeyDown,f=>{var p;const h=s.searchRef.current!=="";e.disabled||h&&f.key===" "||G0[r.dir].includes(f.key)&&(n.onOpenChange(!0),(p=n.content)==null||p.focus(),f.preventDefault())})})})});ph.displayName=So;var mh="MenuSubContent",gh=m.forwardRef((e,t)=>{const n=Zf(Yt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=xr(Yt,e.__scopeMenu),i=yo(Yt,e.__scopeMenu),a=hh(mh,e.__scopeMenu),l=m.useRef(null),u=Ge(t,l);return c.jsx(wo.Provider,{scope:e.__scopeMenu,children:c.jsx(Ut,{present:r||s.open,children:c.jsx(wo.Slot,{scope:e.__scopeMenu,children:c.jsx(Ja,{id:a.contentId,"aria-labelledby":a.triggerId,...o,ref:u,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:d=>{var f;i.isUsingKeyboardRef.current&&((f=l.current)==null||f.focus()),d.preventDefault()},onCloseAutoFocus:d=>d.preventDefault(),onFocusOutside:fe(e.onFocusOutside,d=>{d.target!==a.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:fe(e.onEscapeKeyDown,d=>{i.onClose(),d.preventDefault()}),onKeyDown:fe(e.onKeyDown,d=>{var p;const f=d.currentTarget.contains(d.target),h=Y0[i.dir].includes(d.key);f&&h&&(s.onOpenChange(!1),(p=a.trigger)==null||p.focus(),d.preventDefault())})})})})})});gh.displayName=mh;function xh(e){return e?"open":"closed"}function Ks(e){return e==="indeterminate"}function el(e){return Ks(e)?"indeterminate":e?"checked":"unchecked"}function mS(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function gS(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function xS(e,t,n){const o=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=gS(e,Math.max(s,0));o.length===1&&(i=i.filter(u=>u!==n));const l=i.find(u=>u.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function vS(e,t){const{x:n,y:r}=e;let o=!1;for(let s=0,i=t.length-1;s<t.length;i=s++){const a=t[s],l=t[i],u=a.x,d=a.y,f=l.x,h=l.y;d>r!=h>r&&n<(f-u)*(r-d)/(h-d)+u&&(o=!o)}return o}function bS(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return vS(n,t)}function Co(e){return t=>t.pointerType==="mouse"?e(t):void 0}var wS=Jf,yS=Ga,SS=Qf,CS=eh,kS=Za,TS=th,IS=Vs,ES=oh,NS=ih,AS=lh,_S=uh,jS=dh,RS=fh,PS=ph,OS=gh,qs="DropdownMenu",[MS,Zk]=wn(qs,[Yf]),Ot=Yf(),[DS,vh]=MS(qs),bh=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:s,onOpenChange:i,modal:a=!0}=e,l=Ot(t),u=m.useRef(null),[d,f]=ur({prop:o,defaultProp:s??!1,onChange:i,caller:qs});return c.jsx(DS,{scope:t,triggerId:yn(),triggerRef:u,contentId:yn(),open:d,onOpenChange:f,onOpenToggle:m.useCallback(()=>f(h=>!h),[f]),modal:a,children:c.jsx(wS,{...l,open:d,onOpenChange:f,dir:r,modal:a,children:n})})};bh.displayName=qs;var wh="DropdownMenuTrigger",yh=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,s=vh(wh,n),i=Ot(n);return c.jsx(yS,{asChild:!0,...i,children:c.jsx(_e.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...o,ref:sa(t,s.triggerRef),onPointerDown:fe(e.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(s.onOpenToggle(),s.open||a.preventDefault())}),onKeyDown:fe(e.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&s.onOpenToggle(),a.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});yh.displayName=wh;var LS="DropdownMenuPortal",Sh=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Ot(t);return c.jsx(SS,{...r,...n})};Sh.displayName=LS;var Ch="DropdownMenuContent",kh=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=vh(Ch,n),s=Ot(n),i=m.useRef(!1);return c.jsx(CS,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...r,ref:t,onCloseAutoFocus:fe(e.onCloseAutoFocus,a=>{var l;i.current||(l=o.triggerRef.current)==null||l.focus(),i.current=!1,a.preventDefault()}),onInteractOutside:fe(e.onInteractOutside,a=>{const l=a.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;(!o.modal||d)&&(i.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});kh.displayName=Ch;var $S="DropdownMenuGroup",FS=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(kS,{...o,...r,ref:t})});FS.displayName=$S;var BS="DropdownMenuLabel",Th=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(TS,{...o,...r,ref:t})});Th.displayName=BS;var zS="DropdownMenuItem",Ih=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(IS,{...o,...r,ref:t})});Ih.displayName=zS;var HS="DropdownMenuCheckboxItem",Eh=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(ES,{...o,...r,ref:t})});Eh.displayName=HS;var US="DropdownMenuRadioGroup",WS=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(NS,{...o,...r,ref:t})});WS.displayName=US;var VS="DropdownMenuRadioItem",Nh=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(AS,{...o,...r,ref:t})});Nh.displayName=VS;var KS="DropdownMenuItemIndicator",Ah=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(_S,{...o,...r,ref:t})});Ah.displayName=KS;var qS="DropdownMenuSeparator",_h=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(jS,{...o,...r,ref:t})});_h.displayName=qS;var GS="DropdownMenuArrow",YS=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(RS,{...o,...r,ref:t})});YS.displayName=GS;var XS="DropdownMenuSubTrigger",jh=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(PS,{...o,...r,ref:t})});jh.displayName=XS;var JS="DropdownMenuSubContent",Rh=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(OS,{...o,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Rh.displayName=JS;var ZS=bh,QS=yh,eC=Sh,Ph=kh,Oh=Th,Mh=Ih,Dh=Eh,Lh=Nh,$h=Ah,Fh=_h,Bh=jh,zh=Rh;const tC=ZS,nC=QS,rC=m.forwardRef(({className:e,inset:t,children:n,...r},o)=>c.jsxs(Bh,{ref:o,className:ee("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...r,children:[n,c.jsx(ae.ChevronRight,{className:"ml-auto h-4 w-4"})]}));rC.displayName=Bh.displayName;const oC=m.forwardRef(({className:e,...t},n)=>c.jsx(zh,{ref:n,className:ee("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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",e),...t}));oC.displayName=zh.displayName;const Hh=m.forwardRef(({className:e,sideOffset:t=4,...n},r)=>c.jsx(eC,{children:c.jsx(Ph,{ref:r,sideOffset:t,className:ee("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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",e),...n})}));Hh.displayName=Ph.displayName;const tl=m.forwardRef(({className:e,inset:t,...n},r)=>c.jsx(Mh,{ref:r,className:ee("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));tl.displayName=Mh.displayName;const sC=m.forwardRef(({className:e,children:t,checked:n,...r},o)=>c.jsxs(Dh,{ref:o,className:ee("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[c.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:c.jsx($h,{children:c.jsx(ae.Check,{className:"h-4 w-4"})})}),t]}));sC.displayName=Dh.displayName;const iC=m.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(Lh,{ref:r,className:ee("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[c.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:c.jsx($h,{children:c.jsx(ae.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));iC.displayName=Lh.displayName;const aC=m.forwardRef(({className:e,inset:t,...n},r)=>c.jsx(Oh,{ref:r,className:ee("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));aC.displayName=Oh.displayName;const lC=m.forwardRef(({className:e,...t},n)=>c.jsx(Fh,{ref:n,className:ee("-mx-1 my-1 h-px bg-muted",e),...t}));lC.displayName=Fh.displayName;function Gs({className:e="",placeholder:t="Type your message...",autoFocus:n=!0,maxHeight:r=void 0,streamingDebounceMs:o=500,streamingThrottleMs:s,followNewMessages:i=!0,enableFileUpload:a=!0,enableExcelUpload:l=!1,enableMessageEditing:u=!0,customStyles:d={},onMessageSent:f,onExcelUploadSuccess:h,onError:p}){const{api:b}=Ci(),{currentThreadId:x}=Ho(),{threadId:g,messages:v,hasMore:w,isHistoryLoading:S,isLoading:N,loadOlder:k,listCheckpoints:T,navigateToCheckpoint:E,returnToLatest:A,checkpoint:j,respondToInterrupt:P,metadata:L}=Uo(),{isStreaming:$,error:V,submit:M,stop:G}=Mc(),K=g??x??null,W=(j==null?void 0:j.id)??null,z=(j==null?void 0:j.namespace)??null,B=(L==null?void 0:L.assemblingMessageId)??null,[ue,D]=y.useState(null),[te,he]=y.useState(""),[we,ye]=y.useState(null),[Se,q]=y.useState([]),[O,X]=y.useState(0),[ne,pe]=y.useState(0),[se,me]=y.useState(!1),[et,tt]=y.useState(null),[Pe,Ve]=y.useState(null),[ut,nt]=y.useState(!1),[Ke,vt]=y.useState(null),[Q,ie]=y.useState([]),[xe,Ce]=y.useState(null),[ve,Oe]=y.useState(null),[at,Me]=y.useState(!1),st=y.useRef(null),ft=y.useRef(null),It=y.useRef(null),Nn=y.useCallback(()=>{st.current&&(st.current.value=""),ft.current&&(ft.current.value=""),X(oe=>oe+1),pe(oe=>oe+1)},[]),dn=y.useRef(!1);y.useEffect(()=>{dn.current&&!$&&(q([]),Nn()),dn.current=$},[$,Nn]);const[Zt,An]=y.useState("desktop");y.useEffect(()=>{const oe=()=>{const ke=window.innerWidth;An(ke<640?"phone":ke<1024?"tablet":"desktop")};return oe(),window.addEventListener("resize",oe),()=>window.removeEventListener("resize",oe)},[]),y.useEffect(()=>{let oe=!1;if(!K){ie([]),Ce(null),Oe(null),It.current=null;return}const ke={threadId:K,checkpointId:W??null,checkpointNs:z??null},qe=It.current;if(!(qe&&qe.threadId===ke.threadId&&qe.checkpointId===ke.checkpointId&&qe.checkpointNs===ke.checkpointNs))return T(K).then(it=>{var Ee;if(oe)return;const Mt=((it==null?void 0:it.checkpoints)??[]).slice().sort((Be,Xe)=>new Date(Xe.createdAt).getTime()-new Date(Be.createdAt).getTime());ie(Mt);const I=xe,H=I&&Mt.some(Be=>Be.checkpointId===I)?I:((Ee=Mt[0])==null?void 0:Ee.checkpointId)??null;let re=null;if(H){const Be=Mt.find(Xe=>Xe.checkpointId===H);re=(Be==null?void 0:Be.checkpointNs)??null}Ce(H),Oe(re),It.current=ke}).catch(it=>{console.error("ChatInterface - listCheckpoints error:",it),oe||(ie([]),It.current=null)}),()=>{oe=!0}},[K,W,z,xe,T]),y.useEffect(()=>{W&&(Ce(W),Oe(z??null))},[W,z]);const _n=y.useCallback(async()=>{if(!(!w||S))try{await k()}catch(oe){console.warn("loadOlder failed",oe)}},[w,S,k]);y.useEffect(()=>{(async()=>{if(!b.baseUrl){vt(null);return}try{const ke=await b.getAgent("default");vt(ke.uiDefaultMessage||null)}catch(ke){console.warn("Failed to fetch default message:",ke),vt(null)}})()},[b]),y.useEffect(()=>{V&&!ut&&(p==null||p(V))},[V,ut,p]);const Qn=oe=>{if(oe.length>_s)return`Message too long (${oe.length}/${_s} characters)`;try{return py(oe),null}catch(ke){return(ke==null?void 0:ke.message)||"Invalid message"}},To=async oe=>{const ke=oe.trim();if(!(!ke&&Se.length===0)){if(ke){const qe=Qn(ke);if(qe){ye(qe);return}}try{await M({text:ke||"",attachments:Se,payload:ue?{edit:!0,originalMessageId:ue}:void 0},{checkpointId:xe??W??void 0,checkpointNs:ve??z??void 0}),f==null||f(ke),ye(null),q([]),Nn(),D(null),he("")}catch(qe){const it=(qe==null?void 0:qe.message)||"Failed to send message";ye(it),p==null||p(it)}}},fn=y.useCallback((oe,ke)=>{u&&(D(oe),he(ke),ye(null))},[u]),hn=y.useCallback(()=>{D(null),he(""),ye(null)},[]),Et=y.useCallback((oe,ke)=>{fn(oe,ke)},[fn]),Ur=y.useCallback(oe=>{const ke=qe=>{const it=qe.content||[],Mt=it.filter(I=>I.type==="text").map(I=>I.text).join("");if(Mt)return Mt;try{return JSON.stringify(it,null,2)}catch{return String(it)}};for(let qe=oe-1;qe>=0;qe--)if(v[qe].role==="user"){const it=ke(v[qe]);it&&M({text:it},{checkpointId:xe??W??void 0,checkpointNs:ve??z??void 0});break}},[v,M,xe,ve,W,z]),yr=oe=>{const ke=Array.from(oe.target.files||[]);q(qe=>[...qe,...ke]),oe.target.value=""},yt=oe=>{q(ke=>{const qe=ke.filter((it,Mt)=>oe!==Mt);return qe.length===0&&Nn(),qe})},jn=async oe=>{const ke=(oe.target.files||[])[0];if(ke){tt(null),Ve(null),me(!0);try{await M({attachments:[ke]},{checkpointId:xe??W??void 0,checkpointNs:ve??z??void 0});const qe=`Uploaded ${ke.name} - processing through chat stream`;Ve(qe)}catch(qe){const it=qe instanceof Error?qe.message:"Failed to upload Excel file";console.error("Excel upload failed",qe),tt(it),p==null||p(it)}finally{me(!1),oe.target.value="",Nn()}}},Rn=oe=>{if(!oe)return"Unknown";const ke=Date.parse(oe);return Number.isNaN(ke)?oe:new Date(ke).toLocaleString()},Sr=async oe=>{if(x){Me(!0);try{if(!oe){await A(),Ce(null),Oe(null);return}const ke=Q.find(it=>it.checkpointId===oe),qe=(ke==null?void 0:ke.checkpointNs)??null;await E(oe,qe),Ce(oe),Oe(qe)}finally{Me(!1)}}},Qt=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${d.container||""}`,Cr=`flex-1 min-h-0 min-w-0 max-h-full w-full overflow-hidden overscroll-contain break-words break-anywhere p-4 bg-transparent ${d.messagesArea||""}`,pn=`flex-shrink-0 w-full border-t p-4 bg-transparent ${d.inputArea||""}`;return c.jsxs("div",{className:Qt,children:[!!V&&!ut&&c.jsxs("div",{className:"flex-shrink-0 bg-red-50 border border-red-200 text-red-800 px-4 py-2 text-sm flex items-center justify-between",children:[c.jsx("span",{children:V}),c.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>nt(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:c.jsx(ae.X,{size:16})})]}),x&&Q.length>0&&c.jsxs("div",{className:"flex-shrink-0 flex items-center gap-2 px-4 py-2 border-b border-border bg-muted/60 text-xs dark:bg-muted/50",children:[c.jsx("span",{className:"opacity-70",children:"Checkpoint:"}),c.jsxs("select",{className:"border border-border rounded px-2 py-1 text-xs bg-card text-foreground focus:outline-none focus:ring-1 focus:ring-ring dark:bg-secondary",value:xe??"",onChange:oe=>{const ke=oe.target.value||null;Sr(ke)},children:[c.jsx("option",{value:"",children:"Latest"}),Q.map(oe=>c.jsxs("option",{value:oe.checkpointId,children:[Rn(oe.createdAt),oe.preview?` — ${oe.preview.slice(0,40)}`:""]},oe.checkpointId))]})]}),c.jsxs("div",{className:`relative ${Cr}`,style:r?{maxHeight:r}:void 0,children:[c.jsx(_a,{className:"h-full",style:{height:"100%"},messages:v,isStreaming:$,streamingAssistantId:B,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:Zt,enableMessageEditing:u,editingMessageId:ue,onStartReached:()=>{_n()},onEdit:Et,onRegenerate:Ur,onCancelEdit:hn,emptyMessage:Ke??void 0,isNavigatingCheckpoint:at}),N&&c.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[c.jsx(ae.Loader2,{className:"h-6 w-6 animate-spin"}),c.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]})]}),c.jsxs("div",{className:pn,children:[ue&&c.jsx("div",{className:"mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(ae.Edit3,{size:16,className:"text-blue-600"}),c.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),c.jsx(Je,{variant:"ghost",size:"sm",onClick:hn,className:"text-blue-600 hover:bg-blue-100",children:c.jsx(ae.X,{size:16})})]})}),(a||l)&&c.jsxs("div",{className:"mb-3 space-y-3",children:[a&&c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:st,type:"file",multiple:!0,onChange:oe=>yr(oe),className:"hidden"},O),Se.length>0&&c.jsx("div",{className:"flex flex-wrap gap-2",children:Se.map((oe,ke)=>c.jsxs("div",{className:"flex items-center gap-2 bg-gray-100 dark:bg-gray-800 rounded-lg px-3 py-2 text-sm text-gray-900 dark:text-gray-100",children:[c.jsx(ae.Paperclip,{size:14}),c.jsx("span",{className:"truncate max-w-[150px]",children:oe.name}),c.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>yt(ke),className:"h-4 w-4 p-0 text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400","aria-label":`Remove ${oe.name}`,children:c.jsx(ae.X,{size:12})})]},ke))})]}),l&&c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:ft,type:"file",accept:".xls,.xlsx,.xlsm",onChange:jn,className:"hidden"},ne),se&&c.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[c.jsx(ae.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),Pe&&!se&&c.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:Pe}),et&&!se&&c.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:et})]})]}),we&&c.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:we}),c.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&c.jsxs(tC,{children:[c.jsx(nC,{asChild:!0,children:c.jsx(Je,{type:"button",size:"icon",variant:"outline",disabled:$,title:"More input actions",className:d.moreButton||"",children:c.jsx(ae.Plus,{size:16})})}),c.jsxs(Hh,{align:"start",sideOffset:6,className:"w-52",children:[a&&c.jsxs(tl,{onClick:()=>{var oe;return(oe=st.current)==null?void 0:oe.click()},className:"cursor-pointer",children:[c.jsx(ae.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&c.jsxs(tl,{onClick:()=>{var oe;se||(oe=ft.current)==null||oe.click()},className:`cursor-pointer ${se?"opacity-60 pointer-events-none":""}`,children:[c.jsx(ae.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),c.jsx("div",{className:"flex-1",children:c.jsx(Ex,{initialValue:te,editingMessageId:ue,placeholder:ue?"Edit your message...":t,isStreaming:$,disabled:!1,maxLength:_s,onSend:To,onCancelEdit:hn,onStop:G,allowEmptySend:Se.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${ue?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${we?"border-red-400":""} ${d.textarea||""}`})})]})]})]})}const Ys=m.forwardRef(({className:e,type:t,...n},r)=>c.jsx("input",{type:t,className:ee("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:r,...n}));Ys.displayName="Input";function nl(e,[t,n]){return Math.min(n,Math.max(t,e))}function cC(e,t){return m.useReducer((n,r)=>t[n][r]??n,e)}var rl="ScrollArea",[Uh,Qk]=wn(rl),[uC,Xt]=Uh(rl),Wh=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,l]=m.useState(null),[u,d]=m.useState(null),[f,h]=m.useState(null),[p,b]=m.useState(null),[x,g]=m.useState(null),[v,w]=m.useState(0),[S,N]=m.useState(0),[k,T]=m.useState(!1),[E,A]=m.useState(!1),j=Ge(t,L=>l(L)),P=js(o);return c.jsx(uC,{scope:n,type:r,dir:P,scrollHideDelay:s,scrollArea:a,viewport:u,onViewportChange:d,content:f,onContentChange:h,scrollbarX:p,onScrollbarXChange:b,scrollbarXEnabled:k,onScrollbarXEnabledChange:T,scrollbarY:x,onScrollbarYChange:g,scrollbarYEnabled:E,onScrollbarYEnabledChange:A,onCornerWidthChange:w,onCornerHeightChange:N,children:c.jsx(_e.div,{dir:P,...i,ref:j,style:{position:"relative","--radix-scroll-area-corner-width":v+"px","--radix-scroll-area-corner-height":S+"px",...e.style}})})});Wh.displayName=rl;var Vh="ScrollAreaViewport",Kh=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=Xt(Vh,n),a=m.useRef(null),l=Ge(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(_e.div,{"data-radix-scroll-area-viewport":"",...s,ref:l,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:r})})]})});Kh.displayName=Vh;var En="ScrollAreaScrollbar",ol=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Xt(En,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return m.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?c.jsx(dC,{...r,ref:t,forceMount:n}):o.type==="scroll"?c.jsx(fC,{...r,ref:t,forceMount:n}):o.type==="auto"?c.jsx(qh,{...r,ref:t,forceMount:n}):o.type==="always"?c.jsx(sl,{...r,ref:t}):null});ol.displayName=En;var dC=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Xt(En,e.__scopeScrollArea),[s,i]=m.useState(!1);return m.useEffect(()=>{const a=o.scrollArea;let l=0;if(a){const u=()=>{window.clearTimeout(l),i(!0)},d=()=>{l=window.setTimeout(()=>i(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",u),a.addEventListener("pointerleave",d),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",u),a.removeEventListener("pointerleave",d)}}},[o.scrollArea,o.scrollHideDelay]),c.jsx(Ut,{present:n||s,children:c.jsx(qh,{"data-state":s?"visible":"hidden",...r,ref:t})})}),fC=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Xt(En,e.__scopeScrollArea),s=e.orientation==="horizontal",i=Qs(()=>l("SCROLL_END"),100),[a,l]=cC("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 m.useEffect(()=>{if(a==="idle"){const u=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(u)}},[a,o.scrollHideDelay,l]),m.useEffect(()=>{const u=o.viewport,d=s?"scrollLeft":"scrollTop";if(u){let f=u[d];const h=()=>{const p=u[d];f!==p&&(l("SCROLL"),i()),f=p};return u.addEventListener("scroll",h),()=>u.removeEventListener("scroll",h)}},[o.viewport,s,l,i]),c.jsx(Ut,{present:n||a!=="hidden",children:c.jsx(sl,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:fe(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:fe(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),qh=m.forwardRef((e,t)=>{const n=Xt(En,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=m.useState(!1),a=e.orientation==="horizontal",l=Qs(()=>{if(n.viewport){const u=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?u:d)}},10);return Br(n.viewport,l),Br(n.content,l),c.jsx(Ut,{present:r||s,children:c.jsx(sl,{"data-state":s?"visible":"hidden",...o,ref:t})})}),sl=m.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=Xt(En,e.__scopeScrollArea),s=m.useRef(null),i=m.useRef(0),[a,l]=m.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),u=Zh(a.viewport,a.content),d={...r,sizes:a,onSizesChange:l,hasThumb:u>0&&u<1,onThumbChange:h=>s.current=h,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:h=>i.current=h};function f(h,p){return vC(h,i.current,a,p)}return n==="horizontal"?c.jsx(hC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollLeft,p=Qh(h,a,o.dir);s.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollLeft=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollLeft=f(h,o.dir))}}):n==="vertical"?c.jsx(pC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollTop,p=Qh(h,a);s.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollTop=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollTop=f(h))}}):null}),hC=m.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=Xt(En,e.__scopeScrollArea),[i,a]=m.useState(),l=m.useRef(null),u=Ge(t,l,s.onScrollbarXChange);return m.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c.jsx(Yh,{"data-orientation":"horizontal",...o,ref:u,sizes:n,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":Zs(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,f)=>{if(s.viewport){const h=s.viewport.scrollLeft+d.deltaX;e.onWheelScroll(h),tp(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:Js(i.paddingLeft),paddingEnd:Js(i.paddingRight)}})}})}),pC=m.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=Xt(En,e.__scopeScrollArea),[i,a]=m.useState(),l=m.useRef(null),u=Ge(t,l,s.onScrollbarYChange);return m.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c.jsx(Yh,{"data-orientation":"vertical",...o,ref:u,sizes:n,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":Zs(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,f)=>{if(s.viewport){const h=s.viewport.scrollTop+d.deltaY;e.onWheelScroll(h),tp(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:Js(i.paddingTop),paddingEnd:Js(i.paddingBottom)}})}})}),[mC,Gh]=Uh(En),Yh=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:u,onWheelScroll:d,onResize:f,...h}=e,p=Xt(En,n),[b,x]=m.useState(null),g=Ge(t,j=>x(j)),v=m.useRef(null),w=m.useRef(""),S=p.viewport,N=r.content-r.viewport,k=Tt(d),T=Tt(l),E=Qs(f,10);function A(j){if(v.current){const P=j.clientX-v.current.left,L=j.clientY-v.current.top;u({x:P,y:L})}}return m.useEffect(()=>{const j=P=>{const L=P.target;(b==null?void 0:b.contains(L))&&k(P,N)};return document.addEventListener("wheel",j,{passive:!1}),()=>document.removeEventListener("wheel",j,{passive:!1})},[S,b,N,k]),m.useEffect(T,[r,T]),Br(b,E),Br(p.content,E),c.jsx(mC,{scope:n,scrollbar:b,hasThumb:o,onThumbChange:Tt(s),onThumbPointerUp:Tt(i),onThumbPositionChange:T,onThumbPointerDown:Tt(a),children:c.jsx(_e.div,{...h,ref:g,style:{position:"absolute",...h.style},onPointerDown:fe(e.onPointerDown,j=>{j.button===0&&(j.target.setPointerCapture(j.pointerId),v.current=b.getBoundingClientRect(),w.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),A(j))}),onPointerMove:fe(e.onPointerMove,A),onPointerUp:fe(e.onPointerUp,j=>{const P=j.target;P.hasPointerCapture(j.pointerId)&&P.releasePointerCapture(j.pointerId),document.body.style.webkitUserSelect=w.current,p.viewport&&(p.viewport.style.scrollBehavior=""),v.current=null})})})}),Xs="ScrollAreaThumb",Xh=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Gh(Xs,e.__scopeScrollArea);return c.jsx(Ut,{present:n||o.hasThumb,children:c.jsx(gC,{ref:t,...r})})}),gC=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=Xt(Xs,n),i=Gh(Xs,n),{onThumbPositionChange:a}=i,l=Ge(t,f=>i.onThumbChange(f)),u=m.useRef(void 0),d=Qs(()=>{u.current&&(u.current(),u.current=void 0)},100);return m.useEffect(()=>{const f=s.viewport;if(f){const h=()=>{if(d(),!u.current){const p=bC(f,a);u.current=p,a()}};return a(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[s.viewport,d,a]),c.jsx(_e.div,{"data-state":i.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:fe(e.onPointerDownCapture,f=>{const p=f.target.getBoundingClientRect(),b=f.clientX-p.left,x=f.clientY-p.top;i.onThumbPointerDown({x:b,y:x})}),onPointerUp:fe(e.onPointerUp,i.onThumbPointerUp)})});Xh.displayName=Xs;var il="ScrollAreaCorner",Jh=m.forwardRef((e,t)=>{const n=Xt(il,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?c.jsx(xC,{...e,ref:t}):null});Jh.displayName=il;var xC=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=Xt(il,n),[s,i]=m.useState(0),[a,l]=m.useState(0),u=!!(s&&a);return Br(o.scrollbarX,()=>{var f;const d=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(d),l(d)}),Br(o.scrollbarY,()=>{var f;const d=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(d),i(d)}),u?c.jsx(_e.div,{...r,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 Js(e){return e?parseInt(e,10):0}function Zh(e,t){const n=e/t;return isNaN(n)?0:n}function Zs(e){const t=Zh(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function vC(e,t,n,r="ltr"){const o=Zs(n),s=o/2,i=t||s,a=o-i,l=n.scrollbar.paddingStart+i,u=n.scrollbar.size-n.scrollbar.paddingEnd-a,d=n.content-n.viewport,f=r==="ltr"?[0,d]:[d*-1,0];return ep([l,u],f)(e)}function Qh(e,t,n="ltr"){const r=Zs(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,s=t.scrollbar.size-o,i=t.content-t.viewport,a=s-r,l=n==="ltr"?[0,i]:[i*-1,0],u=nl(e,l);return ep([0,i],[0,a])(u)}function ep(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function tp(e,t){return e>0&&e<t}var bC=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const s={left:e.scrollLeft,top:e.scrollTop},i=n.left!==s.left,a=n.top!==s.top;(i||a)&&t(),n=s,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function Qs(e,t){const n=Tt(e),r=m.useRef(0);return m.useEffect(()=>()=>window.clearTimeout(r.current),[]),m.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function Br(e,t){const n=Tt(t);Ct(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var np=Wh,wC=Kh,yC=Jh;const rp=m.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(np,{ref:r,className:ee("relative overflow-hidden",e),...n,children:[c.jsx(wC,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),c.jsx(op,{}),c.jsx(yC,{})]}));rp.displayName=np.displayName;const op=m.forwardRef(({className:e,orientation:t="vertical",...n},r)=>c.jsx(ol,{ref:r,orientation:t,className:ee("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:c.jsx(Xh,{className:"relative flex-1 rounded-full bg-border"})}));op.displayName=ol.displayName;function al({className:e="",showCreateButton:t=!0,showDeleteButton:n=!0,showEditTitle:r=!0,maxHeight:o="400px",customStyles:s={},currentThreadId:i=null,navigateToThread:a,onThreadSelect:l,onThreadCreate:u,onThreadDelete:d}){const{threads:f,currentThreadId:h,isLoading:p,actions:b}=Ho(),{loadThread:x}=Uo(),{createThread:g,deleteThread:v,renameThread:w}=b,[S,N]=y.useState(Array.isArray(f)?f:[]),k=y.useRef(S.length>0),[T,E]=y.useState(null),[A,j]=y.useState(""),[P,L]=y.useState(!1);y.useEffect(()=>{const D=Array.isArray(f)?f:[];if(D.length>0){k.current=!0,N(D);return}p||(k.current=!1,N(D))},[f,p]);const $=async D=>{try{await x(D),a==null||a(D),l==null||l(D)}catch(te){console.error("Failed to select thread:",te)}},V=async()=>{try{L(!0);const D=await g();u==null||u(D),a==null||a(D)}catch(D){console.error("Failed to create thread:",D)}finally{L(!1)}},M=async(D,te)=>{if(te.stopPropagation(),!!confirm("Delete this thread?"))try{await v(D),d==null||d(D)}catch(he){console.error("Failed to delete thread:",he)}},G=(D,te)=>{te.stopPropagation(),E(D.threadId),j(D.title||`Thread ${D.threadId.slice(0,8)}`)},K=async D=>{if(A.trim())try{await w(D,A.trim()),E(null),j("")}catch(te){console.error("Failed to update title:",te)}},W=()=>{E(null),j("")},z=(D,te)=>{D.key==="Enter"?K(te):D.key==="Escape"&&W()},B=D=>{if(!D)return"";try{const te=new Date(D),we=new Date().getTime()-te.getTime(),ye=Math.floor(we/(1e3*60*60*24));return ye===0?te.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):ye===1?"Yesterday":ye<7?`${ye} days ago`:te.toLocaleDateString()}catch{return""}},ue=D=>D.title||`Thread ${D.threadId.slice(0,8)}`;return c.jsxs("div",{className:`flex flex-col h-full ${e} ${s.container||""}`,children:[t&&c.jsx("div",{className:s.header||"flex-shrink-0 p-2 border-b bg-slate-800 border-slate-700 text-slate-100 flex justify-end",children:c.jsx(Je,{onClick:V,disabled:P||p,className:s.createButton||"p-2",size:"sm",variant:"ghost",title:P?"Creating...":"New Chat",children:c.jsx(ae.MessageSquarePlus,{size:20})})}),c.jsx(rp,{className:`flex-1 min-h-0 ${s.threadList||""}`,style:o?{maxHeight:o}:void 0,children:c.jsx("div",{className:"p-2 space-y-1 pb-4",children:p?c.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[c.jsx(ae.Loader2,{className:"h-5 w-5 animate-spin"}),c.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):S.length===0?c.jsxs("div",{className:"text-center py-8 text-slate-400",children:[c.jsx(ae.MessageSquare,{className:"w-8 h-8 mx-auto mb-2 opacity-40 text-slate-500"}),c.jsx("p",{className:"text-sm text-slate-500",children:"No conversations yet"})]}):S.slice().sort((D,te)=>new Date(te.updatedAt||te.createdAt||"").getTime()-new Date(D.updatedAt||D.createdAt||"").getTime()).map(D=>c.jsxs("div",{onClick:()=>$(D.threadId),className:`group relative p-3 rounded-lg cursor-pointer transition-colors border ${(i??h)===D.threadId?`${s.activeThread||"bg-slate-600 border-slate-500"} `:`${s.threadItem||"bg-slate-700 border-slate-600 hover:bg-slate-600 text-gray-900 dark:text-slate-100"}`} ${s.threadItem||""} text-gray-900 dark:text-slate-100`,children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("div",{className:"flex-1 min-w-0",children:T===D.threadId?c.jsxs("div",{className:"flex items-center gap-2",onClick:te=>te.stopPropagation(),children:[c.jsx(Ys,{value:A,onChange:te=>j(te.target.value),onKeyDown:te=>z(te,D.threadId),className:"h-6 text-sm",autoFocus:!0}),c.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>K(D.threadId),className:"h-6 w-6 p-0",children:c.jsx(ae.Check,{size:12})}),c.jsx(Je,{variant:"ghost",size:"sm",onClick:W,className:"h-6 w-6 p-0",children:c.jsx(ae.X,{size:12})})]}):c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"font-medium text-sm truncate text-gray-900 dark:text-slate-100",children:ue(D)}),c.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mt-1",children:[c.jsx(ae.Calendar,{size:10}),c.jsx("span",{children:B(D.updatedAt||D.createdAt)})]})]})}),c.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2",children:[r&&T!==D.threadId&&c.jsx(Je,{variant:"ghost",size:"sm",onClick:te=>G(D,te),className:"h-6 w-6 p-0",title:"Edit title",children:c.jsx(ae.Edit3,{size:12})}),n&&c.jsx(Je,{variant:"ghost",size:"sm",onClick:te=>M(D.threadId,te),className:"h-6 w-6 p-0 text-red-400 hover:text-red-300 hover:bg-red-900/20",title:"Delete thread",children:c.jsx(ae.Trash2,{size:12})})]})]}),i===D.threadId&&c.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-blue-400 rounded-r"})]},D.threadId))})})]})}function zr(e){if(!(typeof globalThis>"u"))return globalThis[e]}function SC(e){if(typeof e!="string")return;const t=e.trim();if(t)return On(t)}function sp(){const e=[zr("__API_BASE_URL__"),zr("__CHAT_API_BASE_URL__"),zr("__CHAT_API_URL__")];for(const t of e){const n=SC(t);if(n)return n}}function ip(){const e=[zr("__API_AUTH_TOKEN__"),zr("__CHAT_API_KEY__"),zr("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function ap(...e){for(const t of e)if(typeof t=="string"&&t.trim())return On(t);return On()}function lp(){const e={},t=sp(),n=ip();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function cp(){const e=lp(),t=Bn.getAuthToken(),n=sp();return{apiBaseUrl:ap(e.baseUrl,Bn.baseUrl,n),apiKey:t||e.apiKey||ip()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,truncateToolMessages:!0,toolMessagePreviewLength:200,darkMode:!1,enableSound:!1,messageHistory:100}}const up="chat-settings";function CC(){try{const e=localStorage.getItem(up);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function kC(e){try{const t={...e,apiBaseUrl:On(e.apiBaseUrl)};localStorage.setItem(up,JSON.stringify(t)),t.apiKey&&Bn.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function TC(){const e=cp(),t=CC(),n=Bn.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:ap(Bn.baseUrl,r,e.apiBaseUrl)}}function IC(e){Bn.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),kC(e)}var EC="Label",dp=m.forwardRef((e,t)=>c.jsx(_e.label,{...e,ref:t,onMouseDown:n=>{var o;n.target.closest("button, input, select, textarea")||((o=e.onMouseDown)==null||o.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));dp.displayName=EC;var fp=dp;const NC=Io.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Jt=m.forwardRef(({className:e,...t},n)=>c.jsx(fp,{ref:n,className:ee(NC(),e),...t}));Jt.displayName=fp.displayName;function hp(e){const t=m.useRef({value:e,previous:e});return m.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var ei="Switch",[AC,eT]=wn(ei),[_C,jC]=AC(ei),pp=m.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:s,required:i,disabled:a,value:l="on",onCheckedChange:u,form:d,...f}=e,[h,p]=m.useState(null),b=Ge(t,S=>p(S)),x=m.useRef(!1),g=h?d||!!h.closest("form"):!0,[v,w]=ur({prop:o,defaultProp:s??!1,onChange:u,caller:ei});return c.jsxs(_C,{scope:n,checked:v,disabled:a,children:[c.jsx(_e.button,{type:"button",role:"switch","aria-checked":v,"aria-required":i,"data-state":vp(v),"data-disabled":a?"":void 0,disabled:a,value:l,...f,ref:b,onClick:fe(e.onClick,S=>{w(N=>!N),g&&(x.current=S.isPropagationStopped(),x.current||S.stopPropagation())})}),g&&c.jsx(xp,{control:h,bubbles:!x.current,name:r,value:l,checked:v,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});pp.displayName=ei;var mp="SwitchThumb",gp=m.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=jC(mp,n);return c.jsx(_e.span,{"data-state":vp(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});gp.displayName=mp;var RC="SwitchBubbleInput",xp=m.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=m.useRef(null),a=Ge(i,s),l=hp(n),u=Nf(t);return m.useEffect(()=>{const d=i.current;if(!d)return;const f=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(f,"checked").set;if(l!==n&&p){const b=new Event("click",{bubbles:r});p.call(d,n),d.dispatchEvent(b)}},[l,n,r]),c.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...o,tabIndex:-1,ref:a,style:{...o.style,...u,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});xp.displayName=RC;function vp(e){return e?"checked":"unchecked"}var bp=pp,PC=gp;const Xn=m.forwardRef(({className:e,...t},n)=>c.jsx(bp,{className:ee("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:c.jsx(PC,{className:ee("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Xn.displayName=bp.displayName;var wp=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),OC="VisuallyHidden",MC=m.forwardRef((e,t)=>c.jsx(_e.span,{...e,ref:t,style:{...wp,...e.style}}));MC.displayName=OC;var DC=[" ","Enter","ArrowUp","ArrowDown"],LC=[" ","Enter"],vr="Select",[ti,ni,$C]=ja(vr),[Hr,tT]=wn(vr,[$C,Hs]),ri=Hs(),[FC,Jn]=Hr(vr),[BC,zC]=Hr(vr),yp=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:s,value:i,defaultValue:a,onValueChange:l,dir:u,name:d,autoComplete:f,disabled:h,required:p,form:b}=e,x=ri(t),[g,v]=m.useState(null),[w,S]=m.useState(null),[N,k]=m.useState(!1),T=js(u),[E,A]=ur({prop:r,defaultProp:o??!1,onChange:s,caller:vr}),[j,P]=ur({prop:i,defaultProp:a,onChange:l,caller:vr}),L=m.useRef(null),$=g?b||!!g.closest("form"):!0,[V,M]=m.useState(new Set),G=Array.from(V).map(K=>K.props.value).join(";");return c.jsx($f,{...x,children:c.jsxs(FC,{required:p,scope:t,trigger:g,onTriggerChange:v,valueNode:w,onValueNodeChange:S,valueNodeHasChildren:N,onValueNodeHasChildrenChange:k,contentId:yn(),value:j,onValueChange:P,open:E,onOpenChange:A,dir:T,triggerPointerDownPosRef:L,disabled:h,children:[c.jsx(ti.Provider,{scope:t,children:c.jsx(BC,{scope:e.__scopeSelect,onNativeOptionAdd:m.useCallback(K=>{M(W=>new Set(W).add(K))},[]),onNativeOptionRemove:m.useCallback(K=>{M(W=>{const z=new Set(W);return z.delete(K),z})},[]),children:n})}),$?c.jsxs(Vp,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:f,value:j,onChange:K=>P(K.target.value),disabled:h,form:b,children:[j===void 0?c.jsx("option",{value:""}):null,Array.from(V)]},G):null]})})};yp.displayName=vr;var Sp="SelectTrigger",Cp=m.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=ri(n),i=Jn(Sp,n),a=i.disabled||r,l=Ge(t,i.onTriggerChange),u=ni(n),d=m.useRef("touch"),[f,h,p]=qp(x=>{const g=u().filter(S=>!S.disabled),v=g.find(S=>S.value===i.value),w=Gp(g,x,v);w!==void 0&&i.onValueChange(w.value)}),b=x=>{a||(i.onOpenChange(!0),p()),x&&(i.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)})};return c.jsx(Ff,{asChild:!0,...s,children:c.jsx(_e.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":Kp(i.value)?"":void 0,...o,ref:l,onClick:fe(o.onClick,x=>{x.currentTarget.focus(),d.current!=="mouse"&&b(x)}),onPointerDown:fe(o.onPointerDown,x=>{d.current=x.pointerType;const g=x.target;g.hasPointerCapture(x.pointerId)&&g.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&x.pointerType==="mouse"&&(b(x),x.preventDefault())}),onKeyDown:fe(o.onKeyDown,x=>{const g=f.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&h(x.key),!(g&&x.key===" ")&&DC.includes(x.key)&&(b(),x.preventDefault())})})})});Cp.displayName=Sp;var kp="SelectValue",Tp=m.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=Jn(kp,n),{onValueNodeHasChildrenChange:u}=l,d=s!==void 0,f=Ge(t,l.onValueNodeChange);return Ct(()=>{u(d)},[u,d]),c.jsx(_e.span,{...a,ref:f,style:{pointerEvents:"none"},children:Kp(l.value)?c.jsx(c.Fragment,{children:i}):s})});Tp.displayName=kp;var HC="SelectIcon",Ip=m.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return c.jsx(_e.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});Ip.displayName=HC;var UC="SelectPortal",Ep=e=>c.jsx(ms,{asChild:!0,...e});Ep.displayName=UC;var br="SelectContent",Np=m.forwardRef((e,t)=>{const n=Jn(br,e.__scopeSelect),[r,o]=m.useState();if(Ct(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?Eo.createPortal(c.jsx(Ap,{scope:e.__scopeSelect,children:c.jsx(ti.Slot,{scope:e.__scopeSelect,children:c.jsx("div",{children:e.children})})}),s):null}return c.jsx(_p,{...e,ref:t})});Np.displayName=br;var un=10,[Ap,Zn]=Hr(br),WC="SelectContentImpl",VC=nr.createSlot("SelectContent.RemoveScroll"),_p=m.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:s,onPointerDownOutside:i,side:a,sideOffset:l,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:b,hideWhenDetached:x,avoidCollisions:g,...v}=e,w=Jn(br,n),[S,N]=m.useState(null),[k,T]=m.useState(null),E=Ge(t,q=>N(q)),[A,j]=m.useState(null),[P,L]=m.useState(null),$=ni(n),[V,M]=m.useState(!1),G=m.useRef(!1);m.useEffect(()=>{if(S)return Ta(S)},[S]),ba();const K=m.useCallback(q=>{const[O,...X]=$().map(se=>se.ref.current),[ne]=X.slice(-1),pe=document.activeElement;for(const se of q)if(se===pe||(se==null||se.scrollIntoView({block:"nearest"}),se===O&&k&&(k.scrollTop=0),se===ne&&k&&(k.scrollTop=k.scrollHeight),se==null||se.focus(),document.activeElement!==pe))return},[$,k]),W=m.useCallback(()=>K([A,S]),[K,A,S]);m.useEffect(()=>{V&&W()},[V,W]);const{onOpenChange:z,triggerPointerDownPosRef:B}=w;m.useEffect(()=>{if(S){let q={x:0,y:0};const O=ne=>{var pe,se;q={x:Math.abs(Math.round(ne.pageX)-(((pe=B.current)==null?void 0:pe.x)??0)),y:Math.abs(Math.round(ne.pageY)-(((se=B.current)==null?void 0:se.y)??0))}},X=ne=>{q.x<=10&&q.y<=10?ne.preventDefault():S.contains(ne.target)||z(!1),document.removeEventListener("pointermove",O),B.current=null};return B.current!==null&&(document.addEventListener("pointermove",O),document.addEventListener("pointerup",X,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",O),document.removeEventListener("pointerup",X,{capture:!0})}}},[S,z,B]),m.useEffect(()=>{const q=()=>z(!1);return window.addEventListener("blur",q),window.addEventListener("resize",q),()=>{window.removeEventListener("blur",q),window.removeEventListener("resize",q)}},[z]);const[ue,D]=qp(q=>{const O=$().filter(pe=>!pe.disabled),X=O.find(pe=>pe.ref.current===document.activeElement),ne=Gp(O,q,X);ne&&setTimeout(()=>ne.ref.current.focus())}),te=m.useCallback((q,O,X)=>{const ne=!G.current&&!X;(w.value!==void 0&&w.value===O||ne)&&(j(q),ne&&(G.current=!0))},[w.value]),he=m.useCallback(()=>S==null?void 0:S.focus(),[S]),we=m.useCallback((q,O,X)=>{const ne=!G.current&&!X;(w.value!==void 0&&w.value===O||ne)&&L(q)},[w.value]),ye=r==="popper"?ll:jp,Se=ye===ll?{side:a,sideOffset:l,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:b,hideWhenDetached:x,avoidCollisions:g}:{};return c.jsx(Ap,{scope:n,content:S,viewport:k,onViewportChange:T,itemRefCallback:te,selectedItem:A,onItemLeave:he,itemTextRefCallback:we,focusSelectedItem:W,selectedItemText:P,position:r,isPositioned:V,searchRef:ue,children:c.jsx(ys,{as:VC,allowPinchZoom:!0,children:c.jsx(ps,{asChild:!0,trapped:w.open,onMountAutoFocus:q=>{q.preventDefault()},onUnmountAutoFocus:fe(o,q=>{var O;(O=w.trigger)==null||O.focus({preventScroll:!0}),q.preventDefault()}),children:c.jsx(hs,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:q=>q.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:c.jsx(ye,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:q=>q.preventDefault(),...v,...Se,onPlaced:()=>M(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...v.style},onKeyDown:fe(v.onKeyDown,q=>{const O=q.ctrlKey||q.altKey||q.metaKey;if(q.key==="Tab"&&q.preventDefault(),!O&&q.key.length===1&&D(q.key),["ArrowUp","ArrowDown","Home","End"].includes(q.key)){let ne=$().filter(pe=>!pe.disabled).map(pe=>pe.ref.current);if(["ArrowUp","End"].includes(q.key)&&(ne=ne.slice().reverse()),["ArrowUp","ArrowDown"].includes(q.key)){const pe=q.target,se=ne.indexOf(pe);ne=ne.slice(se+1)}setTimeout(()=>K(ne)),q.preventDefault()}})})})})})})});_p.displayName=WC;var KC="SelectItemAlignedPosition",jp=m.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=Jn(br,n),i=Zn(br,n),[a,l]=m.useState(null),[u,d]=m.useState(null),f=Ge(t,E=>d(E)),h=ni(n),p=m.useRef(!1),b=m.useRef(!0),{viewport:x,selectedItem:g,selectedItemText:v,focusSelectedItem:w}=i,S=m.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&u&&x&&g&&v){const E=s.trigger.getBoundingClientRect(),A=u.getBoundingClientRect(),j=s.valueNode.getBoundingClientRect(),P=v.getBoundingClientRect();if(s.dir!=="rtl"){const pe=P.left-A.left,se=j.left-pe,me=E.left-se,et=E.width+me,tt=Math.max(et,A.width),Pe=window.innerWidth-un,Ve=nl(se,[un,Math.max(un,Pe-tt)]);a.style.minWidth=et+"px",a.style.left=Ve+"px"}else{const pe=A.right-P.right,se=window.innerWidth-j.right-pe,me=window.innerWidth-E.right-se,et=E.width+me,tt=Math.max(et,A.width),Pe=window.innerWidth-un,Ve=nl(se,[un,Math.max(un,Pe-tt)]);a.style.minWidth=et+"px",a.style.right=Ve+"px"}const L=h(),$=window.innerHeight-un*2,V=x.scrollHeight,M=window.getComputedStyle(u),G=parseInt(M.borderTopWidth,10),K=parseInt(M.paddingTop,10),W=parseInt(M.borderBottomWidth,10),z=parseInt(M.paddingBottom,10),B=G+K+V+z+W,ue=Math.min(g.offsetHeight*5,B),D=window.getComputedStyle(x),te=parseInt(D.paddingTop,10),he=parseInt(D.paddingBottom,10),we=E.top+E.height/2-un,ye=$-we,Se=g.offsetHeight/2,q=g.offsetTop+Se,O=G+K+q,X=B-O;if(O<=we){const pe=L.length>0&&g===L[L.length-1].ref.current;a.style.bottom="0px";const se=u.clientHeight-x.offsetTop-x.offsetHeight,me=Math.max(ye,Se+(pe?he:0)+se+W),et=O+me;a.style.height=et+"px"}else{const pe=L.length>0&&g===L[0].ref.current;a.style.top="0px";const me=Math.max(we,G+x.offsetTop+(pe?te:0)+Se)+X;a.style.height=me+"px",x.scrollTop=O-we+x.offsetTop}a.style.margin=`${un}px 0`,a.style.minHeight=ue+"px",a.style.maxHeight=$+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[h,s.trigger,s.valueNode,a,u,x,g,v,s.dir,r]);Ct(()=>S(),[S]);const[N,k]=m.useState();Ct(()=>{u&&k(window.getComputedStyle(u).zIndex)},[u]);const T=m.useCallback(E=>{E&&b.current===!0&&(S(),w==null||w(),b.current=!1)},[S,w]);return c.jsx(GC,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:T,children:c.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:N},children:c.jsx(_e.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});jp.displayName=KC;var qC="SelectPopperPosition",ll=m.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=un,...s}=e,i=ri(n);return c.jsx(Bf,{...i,...s,ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});ll.displayName=qC;var[GC,cl]=Hr(br,{}),ul="SelectViewport",Rp=m.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=Zn(ul,n),i=cl(ul,n),a=Ge(t,s.onViewportChange),l=m.useRef(0);return c.jsxs(c.Fragment,{children:[c.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),c.jsx(ti.Slot,{scope:n,children:c.jsx(_e.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:fe(o.onScroll,u=>{const d=u.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:h}=i;if(h!=null&&h.current&&f){const p=Math.abs(l.current-d.scrollTop);if(p>0){const b=window.innerHeight-un*2,x=parseFloat(f.style.minHeight),g=parseFloat(f.style.height),v=Math.max(x,g);if(v<b){const w=v+p,S=Math.min(b,w),N=w-S;f.style.height=S+"px",f.style.bottom==="0px"&&(d.scrollTop=N>0?N:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});Rp.displayName=ul;var Pp="SelectGroup",[YC,XC]=Hr(Pp),JC=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=yn();return c.jsx(YC,{scope:n,id:o,children:c.jsx(_e.div,{role:"group","aria-labelledby":o,...r,ref:t})})});JC.displayName=Pp;var Op="SelectLabel",Mp=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=XC(Op,n);return c.jsx(_e.div,{id:o.id,...r,ref:t})});Mp.displayName=Op;var oi="SelectItem",[ZC,Dp]=Hr(oi),Lp=m.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=Jn(oi,n),l=Zn(oi,n),u=a.value===r,[d,f]=m.useState(s??""),[h,p]=m.useState(!1),b=Ge(t,w=>{var S;return(S=l.itemRefCallback)==null?void 0:S.call(l,w,r,o)}),x=yn(),g=m.useRef("touch"),v=()=>{o||(a.onValueChange(r),a.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return c.jsx(ZC,{scope:n,value:r,disabled:o,textId:x,isSelected:u,onItemTextChange:m.useCallback(w=>{f(S=>S||((w==null?void 0:w.textContent)??"").trim())},[]),children:c.jsx(ti.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:c.jsx(_e.div,{role:"option","aria-labelledby":x,"data-highlighted":h?"":void 0,"aria-selected":u&&h,"data-state":u?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:b,onFocus:fe(i.onFocus,()=>p(!0)),onBlur:fe(i.onBlur,()=>p(!1)),onClick:fe(i.onClick,()=>{g.current!=="mouse"&&v()}),onPointerUp:fe(i.onPointerUp,()=>{g.current==="mouse"&&v()}),onPointerDown:fe(i.onPointerDown,w=>{g.current=w.pointerType}),onPointerMove:fe(i.onPointerMove,w=>{var S;g.current=w.pointerType,o?(S=l.onItemLeave)==null||S.call(l):g.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:fe(i.onPointerLeave,w=>{var S;w.currentTarget===document.activeElement&&((S=l.onItemLeave)==null||S.call(l))}),onKeyDown:fe(i.onKeyDown,w=>{var N;((N=l.searchRef)==null?void 0:N.current)!==""&&w.key===" "||(LC.includes(w.key)&&v(),w.key===" "&&w.preventDefault())})})})})});Lp.displayName=oi;var ko="SelectItemText",$p=m.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=Jn(ko,n),a=Zn(ko,n),l=Dp(ko,n),u=zC(ko,n),[d,f]=m.useState(null),h=Ge(t,v=>f(v),l.onItemTextChange,v=>{var w;return(w=a.itemTextRefCallback)==null?void 0:w.call(a,v,l.value,l.disabled)}),p=d==null?void 0:d.textContent,b=m.useMemo(()=>c.jsx("option",{value:l.value,disabled:l.disabled,children:p},l.value),[l.disabled,l.value,p]),{onNativeOptionAdd:x,onNativeOptionRemove:g}=u;return Ct(()=>(x(b),()=>g(b)),[x,g,b]),c.jsxs(c.Fragment,{children:[c.jsx(_e.span,{id:l.textId,...s,ref:h}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Eo.createPortal(s.children,i.valueNode):null]})});$p.displayName=ko;var Fp="SelectItemIndicator",Bp=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return Dp(Fp,n).isSelected?c.jsx(_e.span,{"aria-hidden":!0,...r,ref:t}):null});Bp.displayName=Fp;var dl="SelectScrollUpButton",zp=m.forwardRef((e,t)=>{const n=Zn(dl,e.__scopeSelect),r=cl(dl,e.__scopeSelect),[o,s]=m.useState(!1),i=Ge(t,r.onScrollButtonChange);return Ct(()=>{if(n.viewport&&n.isPositioned){let a=function(){const u=l.scrollTop>0;s(u)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?c.jsx(Up,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});zp.displayName=dl;var fl="SelectScrollDownButton",Hp=m.forwardRef((e,t)=>{const n=Zn(fl,e.__scopeSelect),r=cl(fl,e.__scopeSelect),[o,s]=m.useState(!1),i=Ge(t,r.onScrollButtonChange);return Ct(()=>{if(n.viewport&&n.isPositioned){let a=function(){const u=l.scrollHeight-l.clientHeight,d=Math.ceil(l.scrollTop)<u;s(d)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?c.jsx(Up,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});Hp.displayName=fl;var Up=m.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=Zn("SelectScrollButton",n),i=m.useRef(null),a=ni(n),l=m.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return m.useEffect(()=>()=>l(),[l]),Ct(()=>{var d;const u=a().find(f=>f.ref.current===document.activeElement);(d=u==null?void 0:u.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),c.jsx(_e.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:fe(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:fe(o.onPointerMove,()=>{var u;(u=s.onItemLeave)==null||u.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:fe(o.onPointerLeave,()=>{l()})})}),QC="SelectSeparator",Wp=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return c.jsx(_e.div,{"aria-hidden":!0,...r,ref:t})});Wp.displayName=QC;var hl="SelectArrow",ek=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ri(n),s=Jn(hl,n),i=Zn(hl,n);return s.open&&i.position==="popper"?c.jsx(zf,{...o,...r,ref:t}):null});ek.displayName=hl;var tk="SelectBubbleInput",Vp=m.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=m.useRef(null),s=Ge(r,o),i=hp(t);return m.useEffect(()=>{const a=o.current;if(!a)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("change",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),c.jsx(_e.select,{...n,style:{...wp,...n.style},ref:s,defaultValue:t})});Vp.displayName=tk;function Kp(e){return e===""||e===void 0}function qp(e){const t=Tt(e),n=m.useRef(""),r=m.useRef(0),o=m.useCallback(i=>{const a=n.current+i;t(a),function l(u){n.current=u,window.clearTimeout(r.current),u!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}(a)},[t]),s=m.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return m.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,s]}function Gp(e,t,n){const o=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=nk(e,Math.max(s,0));o.length===1&&(i=i.filter(u=>u!==n));const l=i.find(u=>u.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function nk(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var rk=yp,Yp=Cp,ok=Tp,sk=Ip,ik=Ep,Xp=Np,ak=Rp,Jp=Mp,Zp=Lp,lk=$p,ck=Bp,Qp=zp,em=Hp,tm=Wp;const nm=rk,rm=ok,pl=m.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(Yp,{ref:r,className:ee("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,c.jsx(sk,{asChild:!0,children:c.jsx(ae.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));pl.displayName=Yp.displayName;const om=m.forwardRef(({className:e,...t},n)=>c.jsx(Qp,{ref:n,className:ee("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(ae.ChevronUp,{className:"h-4 w-4"})}));om.displayName=Qp.displayName;const sm=m.forwardRef(({className:e,...t},n)=>c.jsx(em,{ref:n,className:ee("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(ae.ChevronDown,{className:"h-4 w-4"})}));sm.displayName=em.displayName;const ml=m.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>c.jsx(ik,{children:c.jsxs(Xp,{ref:o,className:ee("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md 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",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[c.jsx(om,{}),c.jsx(ak,{className:ee("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),c.jsx(sm,{})]})}));ml.displayName=Xp.displayName;const uk=m.forwardRef(({className:e,...t},n)=>c.jsx(Jp,{ref:n,className:ee("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));uk.displayName=Jp.displayName;const wr=m.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(Zp,{ref:r,className:ee("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[c.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:c.jsx(ck,{children:c.jsx(ae.Check,{className:"h-4 w-4"})})}),c.jsx(lk,{children:t})]}));wr.displayName=Zp.displayName;const dk=m.forwardRef(({className:e,...t},n)=>c.jsx(tm,{ref:n,className:ee("-mx-1 my-1 h-px bg-muted",e),...t}));dk.displayName=tm.displayName;var fk="Separator",im="horizontal",hk=["horizontal","vertical"],am=m.forwardRef((e,t)=>{const{decorative:n,orientation:r=im,...o}=e,s=pk(r)?r:im,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return c.jsx(_e.div,{"data-orientation":s,...a,...o,ref:t})});am.displayName=fk;function pk(e){return hk.includes(e)}var lm=am;const cm=m.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>c.jsx(lm,{ref:o,decorative:n,orientation:t,className:ee("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));cm.displayName=lm.displayName;const mk=Vd,gk=Yw,xk=Kd,um=m.forwardRef(({className:e,...t},n)=>c.jsx(Is,{className:ee("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));um.displayName=Is.displayName;const vk=Io.cva("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),dm=m.forwardRef(({side:e="right",className:t,children:n,...r},o)=>c.jsxs(xk,{children:[c.jsx(um,{}),c.jsxs(Es,{ref:o,className:ee(vk({side:e}),t),...r,children:[n,c.jsxs(qd,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[c.jsx(ae.X,{className:"h-4 w-4"}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));dm.displayName=Es.displayName;const fm=({className:e,...t})=>c.jsx("div",{className:ee("flex flex-col space-y-2 text-center sm:text-left",e),...t});fm.displayName="SheetHeader";const hm=m.forwardRef(({className:e,...t},n)=>c.jsx(hr,{ref:n,className:ee("text-lg font-semibold text-foreground",e),...t}));hm.displayName=hr.displayName;const pm=m.forwardRef(({className:e,...t},n)=>c.jsx(Ns,{ref:n,className:ee("text-sm text-muted-foreground",e),...t}));pm.displayName=Ns.displayName;const bk={api:{baseUrl:"http://localhost:8000/api",authToken:"",enableAuth:!1},ui:{layout:"sidebar",theme:"light",showTimestamps:!0,showAgentNames:!0,compactMessages:!1},behavior:{autoSave:!0,enableStreaming:!0,showTypingIndicator:!0}};function wk({settings:e,onSettingsChange:t,className:n=""}){const[r,o]=y.useState(!1),[s,i]=y.useState(!1),[a,l]=y.useState(e),[u,d]=y.useState(!1),{toast:f}=pa();y.useEffect(()=>{const g=JSON.stringify(a)!==JSON.stringify(e);d(g)},[a,e]),y.useEffect(()=>{l(e)},[e]);const h=()=>{t(a),d(!1),f({title:"Settings saved",description:"Your chat configuration has been updated successfully."})},p=()=>{l(bk),d(!0),f({title:"Settings reset",description:"Configuration has been reset to defaults."})},b=()=>{l(e),d(!1),o(!1)},x=async()=>{try{const v=await(await fetch(`${a.api.baseUrl}/health`)).json();f({title:"Connection successful",description:`API is ${v.status||"healthy"}`})}catch{f({title:"Connection failed",description:"Unable to connect to the API endpoint.",variant:"destructive"})}};return c.jsxs(mk,{open:r,onOpenChange:o,children:[c.jsx(gk,{asChild:!0,children:c.jsxs(Je,{variant:"outline",size:"sm",className:n,children:[c.jsx(ae.Settings,{className:"h-4 w-4 mr-2"}),"Settings",u&&c.jsx(oa,{variant:"destructive",className:"ml-2 h-4 w-4 p-0"})]})}),c.jsxs(dm,{className:"w-[500px] sm:w-[600px] overflow-y-auto",children:[c.jsxs(fm,{children:[c.jsx(hm,{children:"Chat Settings"}),c.jsx(pm,{children:"Configure your chat interface, API connection, and behavior preferences."})]}),c.jsxs("div",{className:"space-y-6 py-6",children:[c.jsxs(co,{children:[c.jsx(uo,{className:"pb-3",children:c.jsxs(fo,{className:"text-lg flex items-center gap-2",children:[c.jsx(ae.Server,{className:"h-5 w-5"}),"API Configuration"]})}),c.jsxs(is,{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Jt,{htmlFor:"api-url",children:"API Base URL"}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx(Ys,{id:"api-url",value:a.api.baseUrl,onChange:g=>l(v=>({...v,api:{...v.api,baseUrl:g.target.value}})),placeholder:"http://localhost:8000/api"}),c.jsx(Je,{variant:"outline",onClick:x,children:"Test"})]})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(Jt,{htmlFor:"enable-auth",children:"Enable Authentication"}),c.jsx(Xn,{id:"enable-auth",checked:a.api.enableAuth,onCheckedChange:g=>l(v=>({...v,api:{...v.api,enableAuth:g}}))})]}),a.api.enableAuth&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(Jt,{htmlFor:"auth-token",children:"Authentication Token"}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx(Ys,{id:"auth-token",type:s?"text":"password",value:a.api.authToken,onChange:g=>l(v=>({...v,api:{...v.api,authToken:g.target.value}})),placeholder:"Enter your Bearer token"}),c.jsx(Je,{variant:"outline",size:"icon",onClick:()=>i(!s),children:s?c.jsx(ae.EyeOff,{className:"h-4 w-4"}):c.jsx(ae.Eye,{className:"h-4 w-4"})})]})]})]})]}),c.jsxs(co,{children:[c.jsx(uo,{className:"pb-3",children:c.jsxs(fo,{className:"text-lg flex items-center gap-2",children:[c.jsx(ae.Layout,{className:"h-5 w-5"}),"Interface Settings"]})}),c.jsxs(is,{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Jt,{htmlFor:"layout",children:"Layout Style"}),c.jsxs(nm,{value:a.ui.layout,onValueChange:g=>l(v=>({...v,ui:{...v.ui,layout:g}})),children:[c.jsx(pl,{children:c.jsx(rm,{})}),c.jsxs(ml,{children:[c.jsx(wr,{value:"sidebar",children:"Sidebar Layout"}),c.jsx(wr,{value:"fullscreen",children:"Fullscreen"}),c.jsx(wr,{value:"tabs",children:"Tabbed Interface"})]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Jt,{htmlFor:"theme",children:"Theme"}),c.jsxs(nm,{value:a.ui.theme,onValueChange:g=>l(v=>({...v,ui:{...v.ui,theme:g}})),children:[c.jsx(pl,{children:c.jsx(rm,{})}),c.jsxs(ml,{children:[c.jsx(wr,{value:"light",children:"Light"}),c.jsx(wr,{value:"dark",children:"Dark"}),c.jsx(wr,{value:"system",children:"System"})]})]})]}),c.jsx(cm,{}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(Jt,{htmlFor:"show-timestamps",children:"Show Timestamps"}),c.jsx(Xn,{id:"show-timestamps",checked:a.ui.showTimestamps,onCheckedChange:g=>l(v=>({...v,ui:{...v.ui,showTimestamps:g}}))})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(Jt,{htmlFor:"show-agent-names",children:"Show Agent Names"}),c.jsx(Xn,{id:"show-agent-names",checked:a.ui.showAgentNames,onCheckedChange:g=>l(v=>({...v,ui:{...v.ui,showAgentNames:g}}))})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(Jt,{htmlFor:"compact-messages",children:"Compact Messages"}),c.jsx(Xn,{id:"compact-messages",checked:a.ui.compactMessages,onCheckedChange:g=>l(v=>({...v,ui:{...v.ui,compactMessages:g}}))})]})]})]})]}),c.jsxs(co,{children:[c.jsx(uo,{className:"pb-3",children:c.jsxs(fo,{className:"text-lg flex items-center gap-2",children:[c.jsx(ae.MessageCircle,{className:"h-5 w-5"}),"Behavior Settings"]})}),c.jsxs(is,{className:"space-y-4",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx(Jt,{htmlFor:"auto-save",children:"Auto-save Conversations"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically save messages to threads"})]}),c.jsx(Xn,{id:"auto-save",checked:a.behavior.autoSave,onCheckedChange:g=>l(v=>({...v,behavior:{...v.behavior,autoSave:g}}))})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx(Jt,{htmlFor:"enable-streaming",children:"Enable Streaming"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Stream responses in real-time"})]}),c.jsx(Xn,{id:"enable-streaming",checked:a.behavior.enableStreaming,onCheckedChange:g=>l(v=>({...v,behavior:{...v.behavior,enableStreaming:g}}))})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx(Jt,{htmlFor:"typing-indicator",children:"Typing Indicator"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Show typing indicator during responses"})]}),c.jsx(Xn,{id:"typing-indicator",checked:a.behavior.showTypingIndicator,onCheckedChange:g=>l(v=>({...v,behavior:{...v.behavior,showTypingIndicator:g}}))})]})]})]})]}),c.jsxs("div",{className:"flex items-center justify-between pt-6 border-t",children:[c.jsxs(Je,{variant:"outline",onClick:p,children:[c.jsx(ae.RotateCcw,{className:"h-4 w-4 mr-2"}),"Reset"]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx(Je,{variant:"outline",onClick:b,children:"Cancel"}),c.jsxs(Je,{onClick:h,disabled:!u,children:[c.jsx(ae.Save,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})]})}function yk({layout:e="sidebar",layoutSize:t="desktop",showThreads:n=!0,className:r="",customStyles:o={},...s}){const i=u=>{const d="h-full";switch(u){case"phone":return`${d} max-w-none`;case"tablet":return`${d} max-w-4xl mx-auto`;case"half-screen":return`${d} max-w-2xl`;case"desktop":default:return`${d} max-w-7xl mx-auto`}},a=u=>({"--chat-sidebar-width":u==="phone"?"100%":u==="tablet"?"280px":u==="half-screen"?"240px":"320px","--chat-message-max-width":u==="phone"?"95%":u==="tablet"?"90%":u==="half-screen"?"85%":"80%","--chat-input-height":u==="phone"?"120px":"100px"}),l=y.useCallback(u=>{var d;(d=s.onThreadChange)==null||d.call(s,u)},[s]);return e==="fullscreen"?c.jsx(Wo,{...s,onThreadChange:l,children:c.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:c.jsx(Gs,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?c.jsx(Wo,{...s,onThreadChange:l,children:c.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:c.jsxs("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:[n&&c.jsx("div",{className:`w-80 border-r flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:c.jsx(al,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),c.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:c.jsx(Gs,{onError:s.onError,enableFileUpload:!0})})]})})}):c.jsx(Wo,{...s,onThreadChange:l,children:c.jsxs("div",{className:`${i(t)} flex overflow-hidden ${r} ${o.container||""}`,style:a(t),children:[n&&c.jsx("div",{className:`w-80 border-r bg-gray-50 flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:c.jsx(al,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),c.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:c.jsx(Gs,{onError:s.onError,enableFileUpload:!0})})]})})}je.ChatApi=fc,je.ChatInterface=Gs,je.ChatProviders=Wo,je.ChatSettings=wk,je.MarkdownContent=da,je.MessageComponent=nf,je.MessageList=_a,je.ThreadManager=al,je.applySettings=IC,je.chatApiClient=Bn,je.default=yk,je.del=dc,je.get=nn,je.getChatToken=lc,je.getCurrentSettings=TC,je.getDefaultApiConfig=lp,je.getDefaultChatSettings=cp,je.onChatTokenChanged=cc,je.post=Si,je.put=uc,je.setChatToken=yi,je.useApi=Ci,je.useChatStream=Nc,je.useMessagesReducer=bc,je.useStream=Mc,je.useThreadState=Uo,je.useThreads=Ho,Object.defineProperties(je,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
140
|
+
`).trim():n.replace(/</g,"<").replace(/>/g,">").trim()}function hy(e,t=_s){if(!e||typeof e!="string")throw new Error("Invalid content: must be a non-empty string");if(e.length>t)throw new Error(`Message exceeds maximum length of ${t} characters`);return e}function py(e){let t;return typeof e=="string"?t=e:typeof e=="object"&&e!==null?t=JSON.stringify(e):t=String(e),hy(t),fy(t)}function ja(e){const t=e+"CollectionProvider",[n,r]=wn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=x=>{const{scope:g,children:v}=x,w=y.useRef(null),S=y.useRef(new Map).current;return c.jsx(o,{scope:g,itemMap:S,collectionRef:w,children:v})};i.displayName=t;const a=e+"CollectionSlot",l=nr.createSlot(a),u=y.forwardRef((x,g)=>{const{scope:v,children:w}=x,S=s(a,v),N=Ge(g,S.collectionRef);return c.jsx(l,{ref:N,children:w})});u.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=nr.createSlot(d),p=y.forwardRef((x,g)=>{const{scope:v,children:w,...S}=x,N=y.useRef(null),k=Ge(g,N),T=s(d,v);return y.useEffect(()=>(T.itemMap.set(N,{ref:N,...S}),()=>void T.itemMap.delete(N))),c.jsx(h,{[f]:"",ref:k,children:w})});p.displayName=d;function b(x){const g=s(e+"CollectionConsumer",x);return y.useCallback(()=>{const w=g.collectionRef.current;if(!w)return[];const S=Array.from(w.querySelectorAll(`[${f}]`));return Array.from(g.itemMap.values()).sort((T,E)=>S.indexOf(T.ref.current)-S.indexOf(E.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:i,Slot:u,ItemSlot:p},b,r]}var my=m.createContext(void 0);function js(e){const t=m.useContext(my);return e||t||"ltr"}const gy=["top","right","bottom","left"],Gn=Math.min,Wt=Math.max,Rs=Math.round,Ps=Math.floor,Cn=e=>({x:e,y:e}),xy={left:"right",right:"left",bottom:"top",top:"bottom"},vy={start:"end",end:"start"};function Ra(e,t,n){return Wt(e,Gn(t,n))}function Dn(e,t){return typeof e=="function"?e(t):e}function Ln(e){return e.split("-")[0]}function Dr(e){return e.split("-")[1]}function Pa(e){return e==="x"?"y":"x"}function Oa(e){return e==="y"?"height":"width"}const by=new Set(["top","bottom"]);function kn(e){return by.has(Ln(e))?"y":"x"}function Ma(e){return Pa(kn(e))}function wy(e,t,n){n===void 0&&(n=!1);const r=Dr(e),o=Ma(e),s=Oa(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=Os(i)),[i,Os(i)]}function yy(e){const t=Os(e);return[Da(e),t,Da(t)]}function Da(e){return e.replace(/start|end/g,t=>vy[t])}const of=["left","right"],sf=["right","left"],Sy=["top","bottom"],Cy=["bottom","top"];function ky(e,t,n){switch(e){case"top":case"bottom":return n?t?sf:of:t?of:sf;case"left":case"right":return t?Sy:Cy;default:return[]}}function Ty(e,t,n,r){const o=Dr(e);let s=ky(Ln(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Da)))),s}function Os(e){return e.replace(/left|right|bottom|top/g,t=>xy[t])}function Iy(e){return{top:0,right:0,bottom:0,left:0,...e}}function af(e){return typeof e!="number"?Iy(e):{top:e,right:e,bottom:e,left:e}}function Ms(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function lf(e,t,n){let{reference:r,floating:o}=e;const s=kn(t),i=Ma(t),a=Oa(i),l=Ln(t),u=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let p;switch(l){case"top":p={x:d,y:r.y-o.height};break;case"bottom":p={x:d,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:f};break;case"left":p={x:r.x-o.width,y:f};break;default:p={x:r.x,y:r.y}}switch(Dr(t)){case"start":p[i]-=h*(n&&u?-1:1);break;case"end":p[i]+=h*(n&&u?-1:1);break}return p}const Ey=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let u=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=lf(u,r,l),h=r,p={},b=0;for(let x=0;x<a.length;x++){const{name:g,fn:v}=a[x],{x:w,y:S,data:N,reset:k}=await v({x:d,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:u,platform:i,elements:{reference:e,floating:t}});d=w??d,f=S??f,p={...p,[g]:{...p[g],...N}},k&&b<=50&&(b++,typeof k=="object"&&(k.placement&&(h=k.placement),k.rects&&(u=k.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):k.rects),{x:d,y:f}=lf(u,h,l)),x=-1)}return{x:d,y:f,placement:h,strategy:o,middlewareData:p}};async function mo(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:u="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:h=!1,padding:p=0}=Dn(t,e),b=af(p),g=a[h?f==="floating"?"reference":"floating":f],v=Ms(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(g)))==null||n?g:g.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:u,rootBoundary:d,strategy:l})),w=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,S=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),N=await(s.isElement==null?void 0:s.isElement(S))?await(s.getScale==null?void 0:s.getScale(S))||{x:1,y:1}:{x:1,y:1},k=Ms(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:S,strategy:l}):w);return{top:(v.top-k.top+b.top)/N.y,bottom:(k.bottom-v.bottom+b.bottom)/N.y,left:(v.left-k.left+b.left)/N.x,right:(k.right-v.right+b.right)/N.x}}const Ny=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=t,{element:u,padding:d=0}=Dn(e,t)||{};if(u==null)return{};const f=af(d),h={x:n,y:r},p=Ma(o),b=Oa(p),x=await i.getDimensions(u),g=p==="y",v=g?"top":"left",w=g?"bottom":"right",S=g?"clientHeight":"clientWidth",N=s.reference[b]+s.reference[p]-h[p]-s.floating[b],k=h[p]-s.reference[p],T=await(i.getOffsetParent==null?void 0:i.getOffsetParent(u));let E=T?T[S]:0;(!E||!await(i.isElement==null?void 0:i.isElement(T)))&&(E=a.floating[S]||s.floating[b]);const A=N/2-k/2,j=E/2-x[b]/2-1,P=Gn(f[v],j),L=Gn(f[w],j),$=P,V=E-x[b]-L,M=E/2-x[b]/2+A,G=Ra($,M,V),K=!l.arrow&&Dr(o)!=null&&M!==G&&s.reference[b]/2-(M<$?P:L)-x[b]/2<0,W=K?M<$?M-$:M-V:0;return{[p]:h[p]+W,data:{[p]:G,centerOffset:M-G-W,...K&&{alignmentOffset:W}},reset:K}}}),Ay=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:u}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:b="none",flipAlignment:x=!0,...g}=Dn(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const v=Ln(o),w=kn(a),S=Ln(a)===a,N=await(l.isRTL==null?void 0:l.isRTL(u.floating)),k=h||(S||!x?[Os(a)]:yy(a)),T=b!=="none";!h&&T&&k.push(...Ty(a,x,b,N));const E=[a,...k],A=await mo(t,g),j=[];let P=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&j.push(A[v]),f){const M=wy(o,i,N);j.push(A[M[0]],A[M[1]])}if(P=[...P,{placement:o,overflows:j}],!j.every(M=>M<=0)){var L,$;const M=(((L=s.flip)==null?void 0:L.index)||0)+1,G=E[M];if(G&&(!(f==="alignment"?w!==kn(G):!1)||P.every(z=>kn(z.placement)===w?z.overflows[0]>0:!0)))return{data:{index:M,overflows:P},reset:{placement:G}};let K=($=P.filter(W=>W.overflows[0]<=0).sort((W,z)=>W.overflows[1]-z.overflows[1])[0])==null?void 0:$.placement;if(!K)switch(p){case"bestFit":{var V;const W=(V=P.filter(z=>{if(T){const B=kn(z.placement);return B===w||B==="y"}return!0}).map(z=>[z.placement,z.overflows.filter(B=>B>0).reduce((B,ue)=>B+ue,0)]).sort((z,B)=>z[1]-B[1])[0])==null?void 0:V[0];W&&(K=W);break}case"initialPlacement":K=a;break}if(o!==K)return{reset:{placement:K}}}return{}}}};function cf(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function uf(e){return gy.some(t=>e[t]>=0)}const _y=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Dn(e,t);switch(r){case"referenceHidden":{const s=await mo(t,{...o,elementContext:"reference"}),i=cf(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:uf(i)}}}case"escaped":{const s=await mo(t,{...o,altBoundary:!0}),i=cf(s,n.floating);return{data:{escapedOffsets:i,escaped:uf(i)}}}default:return{}}}}},df=new Set(["left","top"]);async function jy(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Ln(n),a=Dr(n),l=kn(n)==="y",u=df.has(i)?-1:1,d=s&&l?-1:1,f=Dn(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:b}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof b=="number"&&(p=a==="end"?b*-1:b),l?{x:p*d,y:h*u}:{x:h*u,y:p*d}}const Ry=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,l=await jy(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},Py=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:g=>{let{x:v,y:w}=g;return{x:v,y:w}}},...l}=Dn(e,t),u={x:n,y:r},d=await mo(t,l),f=kn(Ln(o)),h=Pa(f);let p=u[h],b=u[f];if(s){const g=h==="y"?"top":"left",v=h==="y"?"bottom":"right",w=p+d[g],S=p-d[v];p=Ra(w,p,S)}if(i){const g=f==="y"?"top":"left",v=f==="y"?"bottom":"right",w=b+d[g],S=b-d[v];b=Ra(w,b,S)}const x=a.fn({...t,[h]:p,[f]:b});return{...x,data:{x:x.x-n,y:x.y-r,enabled:{[h]:s,[f]:i}}}}}},Oy=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:l=!0,crossAxis:u=!0}=Dn(e,t),d={x:n,y:r},f=kn(o),h=Pa(f);let p=d[h],b=d[f];const x=Dn(a,t),g=typeof x=="number"?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(l){const S=h==="y"?"height":"width",N=s.reference[h]-s.floating[S]+g.mainAxis,k=s.reference[h]+s.reference[S]-g.mainAxis;p<N?p=N:p>k&&(p=k)}if(u){var v,w;const S=h==="y"?"width":"height",N=df.has(Ln(o)),k=s.reference[f]-s.floating[S]+(N&&((v=i.offset)==null?void 0:v[f])||0)+(N?0:g.crossAxis),T=s.reference[f]+s.reference[S]+(N?0:((w=i.offset)==null?void 0:w[f])||0)-(N?g.crossAxis:0);b<k?b=k:b>T&&(b=T)}return{[h]:p,[f]:b}}}},My=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:l=()=>{},...u}=Dn(e,t),d=await mo(t,u),f=Ln(o),h=Dr(o),p=kn(o)==="y",{width:b,height:x}=s.floating;let g,v;f==="top"||f==="bottom"?(g=f,v=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(v=f,g=h==="end"?"top":"bottom");const w=x-d.top-d.bottom,S=b-d.left-d.right,N=Gn(x-d[g],w),k=Gn(b-d[v],S),T=!t.middlewareData.shift;let E=N,A=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(A=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=w),T&&!h){const P=Wt(d.left,0),L=Wt(d.right,0),$=Wt(d.top,0),V=Wt(d.bottom,0);p?A=b-2*(P!==0||L!==0?P+L:Wt(d.left,d.right)):E=x-2*($!==0||V!==0?$+V:Wt(d.top,d.bottom))}await l({...t,availableWidth:A,availableHeight:E});const j=await i.getDimensions(a.floating);return b!==j.width||x!==j.height?{reset:{rects:!0}}:{}}}};function Ds(){return typeof window<"u"}function Lr(e){return ff(e)?(e.nodeName||"").toLowerCase():"#document"}function Vt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Tn(e){var t;return(t=(ff(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function ff(e){return Ds()?e instanceof Node||e instanceof Vt(e).Node:!1}function ln(e){return Ds()?e instanceof Element||e instanceof Vt(e).Element:!1}function In(e){return Ds()?e instanceof HTMLElement||e instanceof Vt(e).HTMLElement:!1}function hf(e){return!Ds()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Vt(e).ShadowRoot}const Dy=new Set(["inline","contents"]);function go(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=cn(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!Dy.has(o)}const Ly=new Set(["table","td","th"]);function $y(e){return Ly.has(Lr(e))}const Fy=[":popover-open",":modal"];function Ls(e){return Fy.some(t=>{try{return e.matches(t)}catch{return!1}})}const By=["transform","translate","scale","rotate","perspective"],zy=["transform","translate","scale","rotate","perspective","filter"],Hy=["paint","layout","strict","content"];function La(e){const t=$a(),n=ln(e)?cn(e):e;return By.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||zy.some(r=>(n.willChange||"").includes(r))||Hy.some(r=>(n.contain||"").includes(r))}function Uy(e){let t=Yn(e);for(;In(t)&&!$r(t);){if(La(t))return t;if(Ls(t))return null;t=Yn(t)}return null}function $a(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Wy=new Set(["html","body","#document"]);function $r(e){return Wy.has(Lr(e))}function cn(e){return Vt(e).getComputedStyle(e)}function $s(e){return ln(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Yn(e){if(Lr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||hf(e)&&e.host||Tn(e);return hf(t)?t.host:t}function pf(e){const t=Yn(e);return $r(t)?e.ownerDocument?e.ownerDocument.body:e.body:In(t)&&go(t)?t:pf(t)}function xo(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=pf(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=Vt(o);if(s){const a=Fa(i);return t.concat(i,i.visualViewport||[],go(o)?o:[],a&&n?xo(a):[])}return t.concat(o,xo(o,[],n))}function Fa(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function mf(e){const t=cn(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=In(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Rs(n)!==s||Rs(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function Ba(e){return ln(e)?e:e.contextElement}function Fr(e){const t=Ba(e);if(!In(t))return Cn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=mf(t);let i=(s?Rs(n.width):n.width)/r,a=(s?Rs(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const Vy=Cn(0);function gf(e){const t=Vt(e);return!$a()||!t.visualViewport?Vy:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Ky(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Vt(e)?!1:t}function mr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=Ba(e);let i=Cn(1);t&&(r?ln(r)&&(i=Fr(r)):i=Fr(e));const a=Ky(s,n,r)?gf(s):Cn(0);let l=(o.left+a.x)/i.x,u=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const h=Vt(s),p=r&&ln(r)?Vt(r):r;let b=h,x=Fa(b);for(;x&&r&&p!==b;){const g=Fr(x),v=x.getBoundingClientRect(),w=cn(x),S=v.left+(x.clientLeft+parseFloat(w.paddingLeft))*g.x,N=v.top+(x.clientTop+parseFloat(w.paddingTop))*g.y;l*=g.x,u*=g.y,d*=g.x,f*=g.y,l+=S,u+=N,b=Vt(x),x=Fa(b)}}return Ms({width:d,height:f,x:l,y:u})}function Fs(e,t){const n=$s(e).scrollLeft;return t?t.left+n:mr(Tn(e)).left+n}function xf(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Fs(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function qy(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=Tn(r),a=t?Ls(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},u=Cn(1);const d=Cn(0),f=In(r);if((f||!f&&!s)&&((Lr(r)!=="body"||go(i))&&(l=$s(r)),In(r))){const p=mr(r);u=Fr(r),d.x=p.x+r.clientLeft,d.y=p.y+r.clientTop}const h=i&&!f&&!s?xf(i,l):Cn(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+d.x+h.x,y:n.y*u.y-l.scrollTop*u.y+d.y+h.y}}function Gy(e){return Array.from(e.getClientRects())}function Yy(e){const t=Tn(e),n=$s(e),r=e.ownerDocument.body,o=Wt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Wt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Fs(e);const a=-n.scrollTop;return cn(r).direction==="rtl"&&(i+=Wt(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const vf=25;function Xy(e,t){const n=Vt(e),r=Tn(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const d=$a();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const u=Fs(r);if(u<=0){const d=r.ownerDocument,f=d.body,h=getComputedStyle(f),p=d.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,b=Math.abs(r.clientWidth-f.clientWidth-p);b<=vf&&(s-=b)}else u<=vf&&(s+=u);return{width:s,height:i,x:a,y:l}}const Jy=new Set(["absolute","fixed"]);function Zy(e,t){const n=mr(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=In(e)?Fr(e):Cn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,u=r*s.y;return{width:i,height:a,x:l,y:u}}function bf(e,t,n){let r;if(t==="viewport")r=Xy(e,n);else if(t==="document")r=Yy(Tn(e));else if(ln(t))r=Zy(t,n);else{const o=gf(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Ms(r)}function wf(e,t){const n=Yn(e);return n===t||!ln(n)||$r(n)?!1:cn(n).position==="fixed"||wf(n,t)}function Qy(e,t){const n=t.get(e);if(n)return n;let r=xo(e,[],!1).filter(a=>ln(a)&&Lr(a)!=="body"),o=null;const s=cn(e).position==="fixed";let i=s?Yn(e):e;for(;ln(i)&&!$r(i);){const a=cn(i),l=La(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&Jy.has(o.position)||go(i)&&!l&&wf(e,i))?r=r.filter(d=>d!==i):o=a,i=Yn(i)}return t.set(e,r),r}function e0(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Ls(t)?[]:Qy(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((u,d)=>{const f=bf(t,d,o);return u.top=Wt(f.top,u.top),u.right=Gn(f.right,u.right),u.bottom=Gn(f.bottom,u.bottom),u.left=Wt(f.left,u.left),u},bf(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function t0(e){const{width:t,height:n}=mf(e);return{width:t,height:n}}function n0(e,t,n){const r=In(t),o=Tn(t),s=n==="fixed",i=mr(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=Cn(0);function u(){l.x=Fs(o)}if(r||!r&&!s)if((Lr(t)!=="body"||go(o))&&(a=$s(t)),r){const p=mr(t,!0,s,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else o&&u();s&&!r&&o&&u();const d=o&&!r&&!s?xf(o,a):Cn(0),f=i.left+a.scrollLeft-l.x-d.x,h=i.top+a.scrollTop-l.y-d.y;return{x:f,y:h,width:i.width,height:i.height}}function za(e){return cn(e).position==="static"}function yf(e,t){if(!In(e)||cn(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Tn(e)===n&&(n=n.ownerDocument.body),n}function Sf(e,t){const n=Vt(e);if(Ls(e))return n;if(!In(e)){let o=Yn(e);for(;o&&!$r(o);){if(ln(o)&&!za(o))return o;o=Yn(o)}return n}let r=yf(e,t);for(;r&&$y(r)&&za(r);)r=yf(r,t);return r&&$r(r)&&za(r)&&!La(r)?n:r||Uy(e)||n}const r0=async function(e){const t=this.getOffsetParent||Sf,n=this.getDimensions,r=await n(e.floating);return{reference:n0(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function o0(e){return cn(e).direction==="rtl"}const s0={convertOffsetParentRelativeRectToViewportRelativeRect:qy,getDocumentElement:Tn,getClippingRect:e0,getOffsetParent:Sf,getElementRects:r0,getClientRects:Gy,getDimensions:t0,getScale:Fr,isElement:ln,isRTL:o0};function Cf(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function i0(e,t){let n=null,r;const o=Tn(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const u=e.getBoundingClientRect(),{left:d,top:f,width:h,height:p}=u;if(a||t(),!h||!p)return;const b=Ps(f),x=Ps(o.clientWidth-(d+h)),g=Ps(o.clientHeight-(f+p)),v=Ps(d),S={rootMargin:-b+"px "+-x+"px "+-g+"px "+-v+"px",threshold:Wt(0,Gn(1,l))||1};let N=!0;function k(T){const E=T[0].intersectionRatio;if(E!==l){if(!N)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!Cf(u,e.getBoundingClientRect())&&i(),N=!1}try{n=new IntersectionObserver(k,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,S)}n.observe(e)}return i(!0),s}function a0(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,u=Ba(e),d=o||s?[...u?xo(u):[],...xo(t)]:[];d.forEach(v=>{o&&v.addEventListener("scroll",n,{passive:!0}),s&&v.addEventListener("resize",n)});const f=u&&a?i0(u,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(v=>{let[w]=v;w&&w.target===u&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var S;(S=p)==null||S.observe(t)})),n()}),u&&!l&&p.observe(u),p.observe(t));let b,x=l?mr(e):null;l&&g();function g(){const v=mr(e);x&&!Cf(x,v)&&n(),x=v,b=requestAnimationFrame(g)}return n(),()=>{var v;d.forEach(w=>{o&&w.removeEventListener("scroll",n),s&&w.removeEventListener("resize",n)}),f==null||f(),(v=p)==null||v.disconnect(),p=null,l&&cancelAnimationFrame(b)}}const l0=Ry,c0=Py,u0=Ay,d0=My,f0=_y,kf=Ny,h0=Oy,p0=(e,t,n)=>{const r=new Map,o={platform:s0,...n},s={...o.platform,_c:r};return Ey(e,t,{...o,platform:s})};var m0=typeof document<"u",g0=function(){},Bs=m0?y.useLayoutEffect:g0;function zs(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!zs(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!zs(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function Tf(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function If(e,t){const n=Tf(e);return Math.round(t*n)/n}function Ha(e){const t=m.useRef(e);return Bs(()=>{t.current=e}),t}function x0(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:u}=e,[d,f]=m.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[h,p]=m.useState(r);zs(h,r)||p(r);const[b,x]=m.useState(null),[g,v]=m.useState(null),w=m.useCallback(z=>{z!==T.current&&(T.current=z,x(z))},[]),S=m.useCallback(z=>{z!==E.current&&(E.current=z,v(z))},[]),N=s||b,k=i||g,T=m.useRef(null),E=m.useRef(null),A=m.useRef(d),j=l!=null,P=Ha(l),L=Ha(o),$=Ha(u),V=m.useCallback(()=>{if(!T.current||!E.current)return;const z={placement:t,strategy:n,middleware:h};L.current&&(z.platform=L.current),p0(T.current,E.current,z).then(B=>{const ue={...B,isPositioned:$.current!==!1};M.current&&!zs(A.current,ue)&&(A.current=ue,Eo.flushSync(()=>{f(ue)}))})},[h,t,n,L,$]);Bs(()=>{u===!1&&A.current.isPositioned&&(A.current.isPositioned=!1,f(z=>({...z,isPositioned:!1})))},[u]);const M=m.useRef(!1);Bs(()=>(M.current=!0,()=>{M.current=!1}),[]),Bs(()=>{if(N&&(T.current=N),k&&(E.current=k),N&&k){if(P.current)return P.current(N,k,V);V()}},[N,k,V,P,j]);const G=m.useMemo(()=>({reference:T,floating:E,setReference:w,setFloating:S}),[w,S]),K=m.useMemo(()=>({reference:N,floating:k}),[N,k]),W=m.useMemo(()=>{const z={position:n,left:0,top:0};if(!K.floating)return z;const B=If(K.floating,d.x),ue=If(K.floating,d.y);return a?{...z,transform:"translate("+B+"px, "+ue+"px)",...Tf(K.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:B,top:ue}},[n,a,K.floating,d.x,d.y]);return m.useMemo(()=>({...d,update:V,refs:G,elements:K,floatingStyles:W}),[d,V,G,K,W])}const v0=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?kf({element:r.current,padding:o}).fn(n):{}:r?kf({element:r,padding:o}).fn(n):{}}}},b0=(e,t)=>({...l0(e),options:[e,t]}),w0=(e,t)=>({...c0(e),options:[e,t]}),y0=(e,t)=>({...h0(e),options:[e,t]}),S0=(e,t)=>({...u0(e),options:[e,t]}),C0=(e,t)=>({...d0(e),options:[e,t]}),k0=(e,t)=>({...f0(e),options:[e,t]}),T0=(e,t)=>({...v0(e),options:[e,t]});var I0="Arrow",Ef=m.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return c.jsx(_e.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:c.jsx("polygon",{points:"0,0 30,0 15,10"})})});Ef.displayName=I0;var E0=Ef;function Nf(e){const[t,n]=m.useState(void 0);return Ct(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,u=Array.isArray(l)?l[0]:l;i=u.inlineSize,a=u.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Ua="Popper",[Af,Hs]=wn(Ua),[N0,_f]=Af(Ua),jf=e=>{const{__scopePopper:t,children:n}=e,[r,o]=m.useState(null);return c.jsx(N0,{scope:t,anchor:r,onAnchorChange:o,children:n})};jf.displayName=Ua;var Rf="PopperAnchor",Pf=m.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=_f(Rf,n),i=m.useRef(null),a=Ge(t,i),l=m.useRef(null);return m.useEffect(()=>{const u=l.current;l.current=(r==null?void 0:r.current)||i.current,u!==l.current&&s.onAnchorChange(l.current)}),r?null:c.jsx(_e.div,{...o,ref:a})});Pf.displayName=Rf;var Wa="PopperContent",[A0,_0]=Af(Wa),Of=m.forwardRef((e,t)=>{var q,O,X,ne,pe,se;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:h=!1,updatePositionStrategy:p="optimized",onPlaced:b,...x}=e,g=_f(Wa,n),[v,w]=m.useState(null),S=Ge(t,me=>w(me)),[N,k]=m.useState(null),T=Nf(N),E=(T==null?void 0:T.width)??0,A=(T==null?void 0:T.height)??0,j=r+(s!=="center"?"-"+s:""),P=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},L=Array.isArray(u)?u:[u],$=L.length>0,V={padding:P,boundary:L.filter(R0),altBoundary:$},{refs:M,floatingStyles:G,placement:K,isPositioned:W,middlewareData:z}=x0({strategy:"fixed",placement:j,whileElementsMounted:(...me)=>a0(...me,{animationFrame:p==="always"}),elements:{reference:g.anchor},middleware:[b0({mainAxis:o+A,alignmentAxis:i}),l&&w0({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?y0():void 0,...V}),l&&S0({...V}),C0({...V,apply:({elements:me,rects:et,availableWidth:tt,availableHeight:Pe})=>{const{width:Ve,height:ut}=et.reference,nt=me.floating.style;nt.setProperty("--radix-popper-available-width",`${tt}px`),nt.setProperty("--radix-popper-available-height",`${Pe}px`),nt.setProperty("--radix-popper-anchor-width",`${Ve}px`),nt.setProperty("--radix-popper-anchor-height",`${ut}px`)}}),N&&T0({element:N,padding:a}),P0({arrowWidth:E,arrowHeight:A}),h&&k0({strategy:"referenceHidden",...V})]}),[B,ue]=Lf(K),D=Tt(b);Ct(()=>{W&&(D==null||D())},[W,D]);const te=(q=z.arrow)==null?void 0:q.x,he=(O=z.arrow)==null?void 0:O.y,we=((X=z.arrow)==null?void 0:X.centerOffset)!==0,[ye,Se]=m.useState();return Ct(()=>{v&&Se(window.getComputedStyle(v).zIndex)},[v]),c.jsx("div",{ref:M.setFloating,"data-radix-popper-content-wrapper":"",style:{...G,transform:W?G.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ye,"--radix-popper-transform-origin":[(ne=z.transformOrigin)==null?void 0:ne.x,(pe=z.transformOrigin)==null?void 0:pe.y].join(" "),...((se=z.hide)==null?void 0:se.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:c.jsx(A0,{scope:n,placedSide:B,onArrowChange:k,arrowX:te,arrowY:he,shouldHideArrow:we,children:c.jsx(_e.div,{"data-side":B,"data-align":ue,...x,ref:S,style:{...x.style,animation:W?void 0:"none"}})})})});Of.displayName=Wa;var Mf="PopperArrow",j0={top:"bottom",right:"left",bottom:"top",left:"right"},Df=m.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=_0(Mf,r),i=j0[s.placedSide];return c.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:c.jsx(E0,{...o,ref:n,style:{...o.style,display:"block"}})})});Df.displayName=Mf;function R0(e){return e!==null}var P0=e=>({name:"transformOrigin",options:e,fn(t){var g,v,w;const{placement:n,rects:r,middlewareData:o}=t,i=((g=o.arrow)==null?void 0:g.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[u,d]=Lf(n),f={start:"0%",center:"50%",end:"100%"}[d],h=(((v=o.arrow)==null?void 0:v.x)??0)+a/2,p=(((w=o.arrow)==null?void 0:w.y)??0)+l/2;let b="",x="";return u==="bottom"?(b=i?f:`${h}px`,x=`${-l}px`):u==="top"?(b=i?f:`${h}px`,x=`${r.floating.height+l}px`):u==="right"?(b=`${-l}px`,x=i?f:`${p}px`):u==="left"&&(b=`${r.floating.width+l}px`,x=i?f:`${p}px`),{data:{x:b,y:x}}}});function Lf(e){const[t,n="center"]=e.split("-");return[t,n]}var $f=jf,Ff=Pf,Bf=Of,zf=Df,Va="rovingFocusGroup.onEntryFocus",O0={bubbles:!1,cancelable:!0},vo="RovingFocusGroup",[Ka,Hf,M0]=ja(vo),[D0,Uf]=wn(vo,[M0]),[L0,$0]=D0(vo),Wf=m.forwardRef((e,t)=>c.jsx(Ka.Provider,{scope:e.__scopeRovingFocusGroup,children:c.jsx(Ka.Slot,{scope:e.__scopeRovingFocusGroup,children:c.jsx(F0,{...e,ref:t})})}));Wf.displayName=vo;var F0=m.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:u,preventScrollOnEntryFocus:d=!1,...f}=e,h=m.useRef(null),p=Ge(t,h),b=js(s),[x,g]=ur({prop:i,defaultProp:a??null,onChange:l,caller:vo}),[v,w]=m.useState(!1),S=Tt(u),N=Hf(n),k=m.useRef(!1),[T,E]=m.useState(0);return m.useEffect(()=>{const A=h.current;if(A)return A.addEventListener(Va,S),()=>A.removeEventListener(Va,S)},[S]),c.jsx(L0,{scope:n,orientation:r,dir:b,loop:o,currentTabStopId:x,onItemFocus:m.useCallback(A=>g(A),[g]),onItemShiftTab:m.useCallback(()=>w(!0),[]),onFocusableItemAdd:m.useCallback(()=>E(A=>A+1),[]),onFocusableItemRemove:m.useCallback(()=>E(A=>A-1),[]),children:c.jsx(_e.div,{tabIndex:v||T===0?-1:0,"data-orientation":r,...f,ref:p,style:{outline:"none",...e.style},onMouseDown:fe(e.onMouseDown,()=>{k.current=!0}),onFocus:fe(e.onFocus,A=>{const j=!k.current;if(A.target===A.currentTarget&&j&&!v){const P=new CustomEvent(Va,O0);if(A.currentTarget.dispatchEvent(P),!P.defaultPrevented){const L=N().filter(K=>K.focusable),$=L.find(K=>K.active),V=L.find(K=>K.id===x),G=[$,V,...L].filter(Boolean).map(K=>K.ref.current);qf(G,d)}}k.current=!1}),onBlur:fe(e.onBlur,()=>w(!1))})})}),Vf="RovingFocusGroupItem",Kf=m.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=yn(),u=s||l,d=$0(Vf,n),f=d.currentTabStopId===u,h=Hf(n),{onFocusableItemAdd:p,onFocusableItemRemove:b,currentTabStopId:x}=d;return m.useEffect(()=>{if(r)return p(),()=>b()},[r,p,b]),c.jsx(Ka.ItemSlot,{scope:n,id:u,focusable:r,active:o,children:c.jsx(_e.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:fe(e.onMouseDown,g=>{r?d.onItemFocus(u):g.preventDefault()}),onFocus:fe(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:fe(e.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){d.onItemShiftTab();return}if(g.target!==g.currentTarget)return;const v=H0(g,d.orientation,d.dir);if(v!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let S=h().filter(N=>N.focusable).map(N=>N.ref.current);if(v==="last")S.reverse();else if(v==="prev"||v==="next"){v==="prev"&&S.reverse();const N=S.indexOf(g.currentTarget);S=d.loop?U0(S,N+1):S.slice(N+1)}setTimeout(()=>qf(S))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:x!=null}):i})})});Kf.displayName=Vf;var B0={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function z0(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function H0(e,t,n){const r=z0(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return B0[r]}function qf(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function U0(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var W0=Wf,V0=Kf,qa=["Enter"," "],K0=["ArrowDown","PageUp","Home"],Gf=["ArrowUp","PageDown","End"],q0=[...K0,...Gf],G0={ltr:[...qa,"ArrowRight"],rtl:[...qa,"ArrowLeft"]},Y0={ltr:["ArrowLeft"],rtl:["ArrowRight"]},bo="Menu",[wo,X0,J0]=ja(bo),[gr,Yf]=wn(bo,[J0,Hs,Uf]),Us=Hs(),Xf=Uf(),[Z0,xr]=gr(bo),[Q0,yo]=gr(bo),Jf=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:s,modal:i=!0}=e,a=Us(t),[l,u]=m.useState(null),d=m.useRef(!1),f=Tt(s),h=js(o);return m.useEffect(()=>{const p=()=>{d.current=!0,document.addEventListener("pointerdown",b,{capture:!0,once:!0}),document.addEventListener("pointermove",b,{capture:!0,once:!0})},b=()=>d.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",b,{capture:!0}),document.removeEventListener("pointermove",b,{capture:!0})}},[]),c.jsx($f,{...a,children:c.jsx(Z0,{scope:t,open:n,onOpenChange:f,content:l,onContentChange:u,children:c.jsx(Q0,{scope:t,onClose:m.useCallback(()=>f(!1),[f]),isUsingKeyboardRef:d,dir:h,modal:i,children:r})})})};Jf.displayName=bo;var eS="MenuAnchor",Ga=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=Us(n);return c.jsx(Ff,{...o,...r,ref:t})});Ga.displayName=eS;var Ya="MenuPortal",[tS,Zf]=gr(Ya,{forceMount:void 0}),Qf=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,s=xr(Ya,t);return c.jsx(tS,{scope:t,forceMount:n,children:c.jsx(Ut,{present:n||s.open,children:c.jsx(ms,{asChild:!0,container:o,children:r})})})};Qf.displayName=Ya;var Yt="MenuContent",[nS,Xa]=gr(Yt),eh=m.forwardRef((e,t)=>{const n=Zf(Yt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=xr(Yt,e.__scopeMenu),i=yo(Yt,e.__scopeMenu);return c.jsx(wo.Provider,{scope:e.__scopeMenu,children:c.jsx(Ut,{present:r||s.open,children:c.jsx(wo.Slot,{scope:e.__scopeMenu,children:i.modal?c.jsx(rS,{...o,ref:t}):c.jsx(oS,{...o,ref:t})})})})}),rS=m.forwardRef((e,t)=>{const n=xr(Yt,e.__scopeMenu),r=m.useRef(null),o=Ge(t,r);return m.useEffect(()=>{const s=r.current;if(s)return Ta(s)},[]),c.jsx(Ja,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:fe(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),oS=m.forwardRef((e,t)=>{const n=xr(Yt,e.__scopeMenu);return c.jsx(Ja,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),sS=nr.createSlot("MenuContent.ScrollLock"),Ja=m.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:u,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:h,onDismiss:p,disableOutsideScroll:b,...x}=e,g=xr(Yt,n),v=yo(Yt,n),w=Us(n),S=Xf(n),N=X0(n),[k,T]=m.useState(null),E=m.useRef(null),A=Ge(t,E,g.onContentChange),j=m.useRef(0),P=m.useRef(""),L=m.useRef(0),$=m.useRef(null),V=m.useRef("right"),M=m.useRef(0),G=b?ys:m.Fragment,K=b?{as:sS,allowPinchZoom:!0}:void 0,W=B=>{var q,O;const ue=P.current+B,D=N().filter(X=>!X.disabled),te=document.activeElement,he=(q=D.find(X=>X.ref.current===te))==null?void 0:q.textValue,we=D.map(X=>X.textValue),ye=xS(we,ue,he),Se=(O=D.find(X=>X.textValue===ye))==null?void 0:O.ref.current;(function X(ne){P.current=ne,window.clearTimeout(j.current),ne!==""&&(j.current=window.setTimeout(()=>X(""),1e3))})(ue),Se&&setTimeout(()=>Se.focus())};m.useEffect(()=>()=>window.clearTimeout(j.current),[]),ba();const z=m.useCallback(B=>{var D,te;return V.current===((D=$.current)==null?void 0:D.side)&&bS(B,(te=$.current)==null?void 0:te.area)},[]);return c.jsx(nS,{scope:n,searchRef:P,onItemEnter:m.useCallback(B=>{z(B)&&B.preventDefault()},[z]),onItemLeave:m.useCallback(B=>{var ue;z(B)||((ue=E.current)==null||ue.focus(),T(null))},[z]),onTriggerLeave:m.useCallback(B=>{z(B)&&B.preventDefault()},[z]),pointerGraceTimerRef:L,onPointerGraceIntentChange:m.useCallback(B=>{$.current=B},[]),children:c.jsx(G,{...K,children:c.jsx(ps,{asChild:!0,trapped:o,onMountAutoFocus:fe(s,B=>{var ue;B.preventDefault(),(ue=E.current)==null||ue.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:c.jsx(hs,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:u,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:h,onDismiss:p,children:c.jsx(W0,{asChild:!0,...S,dir:v.dir,orientation:"vertical",loop:r,currentTabStopId:k,onCurrentTabStopIdChange:T,onEntryFocus:fe(l,B=>{v.isUsingKeyboardRef.current||B.preventDefault()}),preventScrollOnEntryFocus:!0,children:c.jsx(Bf,{role:"menu","aria-orientation":"vertical","data-state":xh(g.open),"data-radix-menu-content":"",dir:v.dir,...w,...x,ref:A,style:{outline:"none",...x.style},onKeyDown:fe(x.onKeyDown,B=>{const D=B.target.closest("[data-radix-menu-content]")===B.currentTarget,te=B.ctrlKey||B.altKey||B.metaKey,he=B.key.length===1;D&&(B.key==="Tab"&&B.preventDefault(),!te&&he&&W(B.key));const we=E.current;if(B.target!==we||!q0.includes(B.key))return;B.preventDefault();const Se=N().filter(q=>!q.disabled).map(q=>q.ref.current);Gf.includes(B.key)&&Se.reverse(),mS(Se)}),onBlur:fe(e.onBlur,B=>{B.currentTarget.contains(B.target)||(window.clearTimeout(j.current),P.current="")}),onPointerMove:fe(e.onPointerMove,Co(B=>{const ue=B.target,D=M.current!==B.clientX;if(B.currentTarget.contains(ue)&&D){const te=B.clientX>M.current?"right":"left";V.current=te,M.current=B.clientX}}))})})})})})})});eh.displayName=Yt;var iS="MenuGroup",Za=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return c.jsx(_e.div,{role:"group",...r,ref:t})});Za.displayName=iS;var aS="MenuLabel",th=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return c.jsx(_e.div,{...r,ref:t})});th.displayName=aS;var Ws="MenuItem",nh="menu.itemSelect",Vs=m.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,s=m.useRef(null),i=yo(Ws,e.__scopeMenu),a=Xa(Ws,e.__scopeMenu),l=Ge(t,s),u=m.useRef(!1),d=()=>{const f=s.current;if(!n&&f){const h=new CustomEvent(nh,{bubbles:!0,cancelable:!0});f.addEventListener(nh,p=>r==null?void 0:r(p),{once:!0}),Du(f,h),h.defaultPrevented?u.current=!1:i.onClose()}};return c.jsx(rh,{...o,ref:l,disabled:n,onClick:fe(e.onClick,d),onPointerDown:f=>{var h;(h=e.onPointerDown)==null||h.call(e,f),u.current=!0},onPointerUp:fe(e.onPointerUp,f=>{var h;u.current||(h=f.currentTarget)==null||h.click()}),onKeyDown:fe(e.onKeyDown,f=>{const h=a.searchRef.current!=="";n||h&&f.key===" "||qa.includes(f.key)&&(f.currentTarget.click(),f.preventDefault())})})});Vs.displayName=Ws;var rh=m.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...s}=e,i=Xa(Ws,n),a=Xf(n),l=m.useRef(null),u=Ge(t,l),[d,f]=m.useState(!1),[h,p]=m.useState("");return m.useEffect(()=>{const b=l.current;b&&p((b.textContent??"").trim())},[s.children]),c.jsx(wo.ItemSlot,{scope:n,disabled:r,textValue:o??h,children:c.jsx(V0,{asChild:!0,...a,focusable:!r,children:c.jsx(_e.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:u,onPointerMove:fe(e.onPointerMove,Co(b=>{r?i.onItemLeave(b):(i.onItemEnter(b),b.defaultPrevented||b.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:fe(e.onPointerLeave,Co(b=>i.onItemLeave(b))),onFocus:fe(e.onFocus,()=>f(!0)),onBlur:fe(e.onBlur,()=>f(!1))})})})}),lS="MenuCheckboxItem",oh=m.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return c.jsx(ch,{scope:e.__scopeMenu,checked:n,children:c.jsx(Vs,{role:"menuitemcheckbox","aria-checked":Ks(n)?"mixed":n,...o,ref:t,"data-state":el(n),onSelect:fe(o.onSelect,()=>r==null?void 0:r(Ks(n)?!0:!n),{checkForDefaultPrevented:!1})})})});oh.displayName=lS;var sh="MenuRadioGroup",[cS,uS]=gr(sh,{value:void 0,onValueChange:()=>{}}),ih=m.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,s=Tt(r);return c.jsx(cS,{scope:e.__scopeMenu,value:n,onValueChange:s,children:c.jsx(Za,{...o,ref:t})})});ih.displayName=sh;var ah="MenuRadioItem",lh=m.forwardRef((e,t)=>{const{value:n,...r}=e,o=uS(ah,e.__scopeMenu),s=n===o.value;return c.jsx(ch,{scope:e.__scopeMenu,checked:s,children:c.jsx(Vs,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":el(s),onSelect:fe(r.onSelect,()=>{var i;return(i=o.onValueChange)==null?void 0:i.call(o,n)},{checkForDefaultPrevented:!1})})})});lh.displayName=ah;var Qa="MenuItemIndicator",[ch,dS]=gr(Qa,{checked:!1}),uh=m.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,s=dS(Qa,n);return c.jsx(Ut,{present:r||Ks(s.checked)||s.checked===!0,children:c.jsx(_e.span,{...o,ref:t,"data-state":el(s.checked)})})});uh.displayName=Qa;var fS="MenuSeparator",dh=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return c.jsx(_e.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});dh.displayName=fS;var hS="MenuArrow",fh=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=Us(n);return c.jsx(zf,{...o,...r,ref:t})});fh.displayName=hS;var pS="MenuSub",[Jk,hh]=gr(pS),So="MenuSubTrigger",ph=m.forwardRef((e,t)=>{const n=xr(So,e.__scopeMenu),r=yo(So,e.__scopeMenu),o=hh(So,e.__scopeMenu),s=Xa(So,e.__scopeMenu),i=m.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=s,u={__scopeMenu:e.__scopeMenu},d=m.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return m.useEffect(()=>d,[d]),m.useEffect(()=>{const f=a.current;return()=>{window.clearTimeout(f),l(null)}},[a,l]),c.jsx(Ga,{asChild:!0,...u,children:c.jsx(rh,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":xh(n.open),...e,ref:sa(t,o.onTriggerChange),onClick:f=>{var h;(h=e.onClick)==null||h.call(e,f),!(e.disabled||f.defaultPrevented)&&(f.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:fe(e.onPointerMove,Co(f=>{s.onItemEnter(f),!f.defaultPrevented&&!e.disabled&&!n.open&&!i.current&&(s.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{n.onOpenChange(!0),d()},100))})),onPointerLeave:fe(e.onPointerLeave,Co(f=>{var p,b;d();const h=(p=n.content)==null?void 0:p.getBoundingClientRect();if(h){const x=(b=n.content)==null?void 0:b.dataset.side,g=x==="right",v=g?-5:5,w=h[g?"left":"right"],S=h[g?"right":"left"];s.onPointerGraceIntentChange({area:[{x:f.clientX+v,y:f.clientY},{x:w,y:h.top},{x:S,y:h.top},{x:S,y:h.bottom},{x:w,y:h.bottom}],side:x}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(f),f.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:fe(e.onKeyDown,f=>{var p;const h=s.searchRef.current!=="";e.disabled||h&&f.key===" "||G0[r.dir].includes(f.key)&&(n.onOpenChange(!0),(p=n.content)==null||p.focus(),f.preventDefault())})})})});ph.displayName=So;var mh="MenuSubContent",gh=m.forwardRef((e,t)=>{const n=Zf(Yt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=xr(Yt,e.__scopeMenu),i=yo(Yt,e.__scopeMenu),a=hh(mh,e.__scopeMenu),l=m.useRef(null),u=Ge(t,l);return c.jsx(wo.Provider,{scope:e.__scopeMenu,children:c.jsx(Ut,{present:r||s.open,children:c.jsx(wo.Slot,{scope:e.__scopeMenu,children:c.jsx(Ja,{id:a.contentId,"aria-labelledby":a.triggerId,...o,ref:u,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:d=>{var f;i.isUsingKeyboardRef.current&&((f=l.current)==null||f.focus()),d.preventDefault()},onCloseAutoFocus:d=>d.preventDefault(),onFocusOutside:fe(e.onFocusOutside,d=>{d.target!==a.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:fe(e.onEscapeKeyDown,d=>{i.onClose(),d.preventDefault()}),onKeyDown:fe(e.onKeyDown,d=>{var p;const f=d.currentTarget.contains(d.target),h=Y0[i.dir].includes(d.key);f&&h&&(s.onOpenChange(!1),(p=a.trigger)==null||p.focus(),d.preventDefault())})})})})})});gh.displayName=mh;function xh(e){return e?"open":"closed"}function Ks(e){return e==="indeterminate"}function el(e){return Ks(e)?"indeterminate":e?"checked":"unchecked"}function mS(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function gS(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function xS(e,t,n){const o=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=gS(e,Math.max(s,0));o.length===1&&(i=i.filter(u=>u!==n));const l=i.find(u=>u.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function vS(e,t){const{x:n,y:r}=e;let o=!1;for(let s=0,i=t.length-1;s<t.length;i=s++){const a=t[s],l=t[i],u=a.x,d=a.y,f=l.x,h=l.y;d>r!=h>r&&n<(f-u)*(r-d)/(h-d)+u&&(o=!o)}return o}function bS(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return vS(n,t)}function Co(e){return t=>t.pointerType==="mouse"?e(t):void 0}var wS=Jf,yS=Ga,SS=Qf,CS=eh,kS=Za,TS=th,IS=Vs,ES=oh,NS=ih,AS=lh,_S=uh,jS=dh,RS=fh,PS=ph,OS=gh,qs="DropdownMenu",[MS,Zk]=wn(qs,[Yf]),Ot=Yf(),[DS,vh]=MS(qs),bh=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:s,onOpenChange:i,modal:a=!0}=e,l=Ot(t),u=m.useRef(null),[d,f]=ur({prop:o,defaultProp:s??!1,onChange:i,caller:qs});return c.jsx(DS,{scope:t,triggerId:yn(),triggerRef:u,contentId:yn(),open:d,onOpenChange:f,onOpenToggle:m.useCallback(()=>f(h=>!h),[f]),modal:a,children:c.jsx(wS,{...l,open:d,onOpenChange:f,dir:r,modal:a,children:n})})};bh.displayName=qs;var wh="DropdownMenuTrigger",yh=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,s=vh(wh,n),i=Ot(n);return c.jsx(yS,{asChild:!0,...i,children:c.jsx(_e.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...o,ref:sa(t,s.triggerRef),onPointerDown:fe(e.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(s.onOpenToggle(),s.open||a.preventDefault())}),onKeyDown:fe(e.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&s.onOpenToggle(),a.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});yh.displayName=wh;var LS="DropdownMenuPortal",Sh=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Ot(t);return c.jsx(SS,{...r,...n})};Sh.displayName=LS;var Ch="DropdownMenuContent",kh=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=vh(Ch,n),s=Ot(n),i=m.useRef(!1);return c.jsx(CS,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...r,ref:t,onCloseAutoFocus:fe(e.onCloseAutoFocus,a=>{var l;i.current||(l=o.triggerRef.current)==null||l.focus(),i.current=!1,a.preventDefault()}),onInteractOutside:fe(e.onInteractOutside,a=>{const l=a.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;(!o.modal||d)&&(i.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});kh.displayName=Ch;var $S="DropdownMenuGroup",FS=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(kS,{...o,...r,ref:t})});FS.displayName=$S;var BS="DropdownMenuLabel",Th=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(TS,{...o,...r,ref:t})});Th.displayName=BS;var zS="DropdownMenuItem",Ih=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(IS,{...o,...r,ref:t})});Ih.displayName=zS;var HS="DropdownMenuCheckboxItem",Eh=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(ES,{...o,...r,ref:t})});Eh.displayName=HS;var US="DropdownMenuRadioGroup",WS=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(NS,{...o,...r,ref:t})});WS.displayName=US;var VS="DropdownMenuRadioItem",Nh=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(AS,{...o,...r,ref:t})});Nh.displayName=VS;var KS="DropdownMenuItemIndicator",Ah=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(_S,{...o,...r,ref:t})});Ah.displayName=KS;var qS="DropdownMenuSeparator",_h=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(jS,{...o,...r,ref:t})});_h.displayName=qS;var GS="DropdownMenuArrow",YS=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(RS,{...o,...r,ref:t})});YS.displayName=GS;var XS="DropdownMenuSubTrigger",jh=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(PS,{...o,...r,ref:t})});jh.displayName=XS;var JS="DropdownMenuSubContent",Rh=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ot(n);return c.jsx(OS,{...o,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Rh.displayName=JS;var ZS=bh,QS=yh,eC=Sh,Ph=kh,Oh=Th,Mh=Ih,Dh=Eh,Lh=Nh,$h=Ah,Fh=_h,Bh=jh,zh=Rh;const tC=ZS,nC=QS,rC=m.forwardRef(({className:e,inset:t,children:n,...r},o)=>c.jsxs(Bh,{ref:o,className:ee("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...r,children:[n,c.jsx(ae.ChevronRight,{className:"ml-auto h-4 w-4"})]}));rC.displayName=Bh.displayName;const oC=m.forwardRef(({className:e,...t},n)=>c.jsx(zh,{ref:n,className:ee("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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",e),...t}));oC.displayName=zh.displayName;const Hh=m.forwardRef(({className:e,sideOffset:t=4,...n},r)=>c.jsx(eC,{children:c.jsx(Ph,{ref:r,sideOffset:t,className:ee("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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",e),...n})}));Hh.displayName=Ph.displayName;const tl=m.forwardRef(({className:e,inset:t,...n},r)=>c.jsx(Mh,{ref:r,className:ee("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));tl.displayName=Mh.displayName;const sC=m.forwardRef(({className:e,children:t,checked:n,...r},o)=>c.jsxs(Dh,{ref:o,className:ee("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[c.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:c.jsx($h,{children:c.jsx(ae.Check,{className:"h-4 w-4"})})}),t]}));sC.displayName=Dh.displayName;const iC=m.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(Lh,{ref:r,className:ee("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[c.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:c.jsx($h,{children:c.jsx(ae.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));iC.displayName=Lh.displayName;const aC=m.forwardRef(({className:e,inset:t,...n},r)=>c.jsx(Oh,{ref:r,className:ee("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));aC.displayName=Oh.displayName;const lC=m.forwardRef(({className:e,...t},n)=>c.jsx(Fh,{ref:n,className:ee("-mx-1 my-1 h-px bg-muted",e),...t}));lC.displayName=Fh.displayName;function Gs({className:e="",placeholder:t="Type your message...",autoFocus:n=!0,maxHeight:r=void 0,streamingDebounceMs:o=500,streamingThrottleMs:s,followNewMessages:i=!0,enableFileUpload:a=!0,enableExcelUpload:l=!1,enableMessageEditing:u=!0,customStyles:d={},onMessageSent:f,onExcelUploadSuccess:h,onError:p}){const{api:b}=Ci(),{currentThreadId:x}=Ho(),{threadId:g,messages:v,hasMore:w,isHistoryLoading:S,isLoading:N,loadOlder:k,listCheckpoints:T,navigateToCheckpoint:E,returnToLatest:A,checkpoint:j,respondToInterrupt:P,metadata:L}=Uo(),{isStreaming:$,error:V,submit:M,stop:G}=Mc(),K=g??x??null,W=(j==null?void 0:j.id)??null,z=(j==null?void 0:j.namespace)??null,B=(L==null?void 0:L.assemblingMessageId)??null,[ue,D]=y.useState(null),[te,he]=y.useState(""),[we,ye]=y.useState(null),[Se,q]=y.useState([]),[O,X]=y.useState(0),[ne,pe]=y.useState(0),[se,me]=y.useState(!1),[et,tt]=y.useState(null),[Pe,Ve]=y.useState(null),[ut,nt]=y.useState(!1),[Ke,vt]=y.useState(null),[Q,ie]=y.useState([]),[xe,Ce]=y.useState(null),[ve,Oe]=y.useState(null),[at,Me]=y.useState(!1),st=y.useRef(null),ft=y.useRef(null),It=y.useRef(null),Nn=y.useCallback(()=>{st.current&&(st.current.value=""),ft.current&&(ft.current.value=""),X(oe=>oe+1),pe(oe=>oe+1)},[]),dn=y.useRef(!1);y.useEffect(()=>{dn.current&&!$&&(q([]),Nn()),dn.current=$},[$,Nn]);const[Zt,An]=y.useState("desktop");y.useEffect(()=>{const oe=()=>{const ke=window.innerWidth;An(ke<640?"phone":ke<1024?"tablet":"desktop")};return oe(),window.addEventListener("resize",oe),()=>window.removeEventListener("resize",oe)},[]),y.useEffect(()=>{let oe=!1;if(!K){ie([]),Ce(null),Oe(null),It.current=null;return}const ke={threadId:K,checkpointId:W??null,checkpointNs:z??null},qe=It.current;if(!(qe&&qe.threadId===ke.threadId&&qe.checkpointId===ke.checkpointId&&qe.checkpointNs===ke.checkpointNs))return T(K).then(it=>{var Ee;if(oe)return;const Mt=((it==null?void 0:it.checkpoints)??[]).slice().sort((Be,Xe)=>new Date(Xe.createdAt).getTime()-new Date(Be.createdAt).getTime());ie(Mt);const I=xe,H=I&&Mt.some(Be=>Be.checkpointId===I)?I:((Ee=Mt[0])==null?void 0:Ee.checkpointId)??null;let re=null;if(H){const Be=Mt.find(Xe=>Xe.checkpointId===H);re=(Be==null?void 0:Be.checkpointNs)??null}Ce(H),Oe(re),It.current=ke}).catch(it=>{console.error("ChatInterface - listCheckpoints error:",it),oe||(ie([]),It.current=null)}),()=>{oe=!0}},[K,W,z,xe,T]),y.useEffect(()=>{W&&(Ce(W),Oe(z??null))},[W,z]);const _n=y.useCallback(async()=>{if(!(!w||S))try{await k()}catch(oe){console.warn("loadOlder failed",oe)}},[w,S,k]);y.useEffect(()=>{(async()=>{if(!b.baseUrl){vt(null);return}try{const ke=await b.getAgent("default");vt(ke.uiDefaultMessage||null)}catch(ke){console.warn("Failed to fetch default message:",ke),vt(null)}})()},[b]),y.useEffect(()=>{V&&!ut&&(p==null||p(V))},[V,ut,p]);const Qn=oe=>{if(oe.length>_s)return`Message too long (${oe.length}/${_s} characters)`;try{return py(oe),null}catch(ke){return(ke==null?void 0:ke.message)||"Invalid message"}},To=async oe=>{const ke=oe.trim();if(!(!ke&&Se.length===0)){if(ke){const qe=Qn(ke);if(qe){ye(qe);return}}try{await M({text:ke||"",attachments:Se,payload:ue?{edit:!0,originalMessageId:ue}:void 0},{checkpointId:xe??W??void 0,checkpointNs:ve??z??void 0}),f==null||f(ke),ye(null),q([]),Nn(),D(null),he("")}catch(qe){const it=(qe==null?void 0:qe.message)||"Failed to send message";ye(it),p==null||p(it)}}},fn=y.useCallback((oe,ke)=>{u&&(D(oe),he(ke),ye(null))},[u]),hn=y.useCallback(()=>{D(null),he(""),ye(null)},[]),Et=y.useCallback((oe,ke)=>{fn(oe,ke)},[fn]),Ur=y.useCallback(oe=>{const ke=qe=>{const it=qe.content||[],Mt=it.filter(I=>I.type==="text").map(I=>I.text).join("");if(Mt)return Mt;try{return JSON.stringify(it,null,2)}catch{return String(it)}};for(let qe=oe-1;qe>=0;qe--)if(v[qe].role==="user"){const it=ke(v[qe]);it&&M({text:it},{checkpointId:xe??W??void 0,checkpointNs:ve??z??void 0});break}},[v,M,xe,ve,W,z]),yr=oe=>{const ke=Array.from(oe.target.files||[]);q(qe=>[...qe,...ke]),oe.target.value=""},yt=oe=>{q(ke=>{const qe=ke.filter((it,Mt)=>oe!==Mt);return qe.length===0&&Nn(),qe})},jn=async oe=>{const ke=(oe.target.files||[])[0];if(ke){tt(null),Ve(null),me(!0);try{await M({attachments:[ke]},{checkpointId:xe??W??void 0,checkpointNs:ve??z??void 0});const qe=`Uploaded ${ke.name} - processing through chat stream`;Ve(qe)}catch(qe){const it=qe instanceof Error?qe.message:"Failed to upload Excel file";console.error("Excel upload failed",qe),tt(it),p==null||p(it)}finally{me(!1),oe.target.value="",Nn()}}},Rn=oe=>{if(!oe)return"Unknown";const ke=Date.parse(oe);return Number.isNaN(ke)?oe:new Date(ke).toLocaleString()},Sr=async oe=>{if(x){Me(!0);try{if(!oe){await A(),Ce(null),Oe(null);return}const ke=Q.find(it=>it.checkpointId===oe),qe=(ke==null?void 0:ke.checkpointNs)??null;await E(oe,qe),Ce(oe),Oe(qe)}finally{Me(!1)}}},Qt=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${d.container||""}`,Cr=`flex-1 min-h-0 min-w-0 max-h-full w-full overflow-hidden overscroll-contain break-words break-anywhere p-4 bg-transparent ${d.messagesArea||""}`,pn=`flex-shrink-0 w-full border-t p-4 bg-transparent ${d.inputArea||""}`;return c.jsxs("div",{className:Qt,children:[!!V&&!ut&&c.jsxs("div",{className:"flex-shrink-0 bg-red-50 border border-red-200 text-red-800 px-4 py-2 text-sm flex items-center justify-between",children:[c.jsx("span",{children:V}),c.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>nt(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:c.jsx(ae.X,{size:16})})]}),x&&Q.length>0&&c.jsxs("div",{className:"flex-shrink-0 flex items-center gap-2 px-4 py-2 border-b border-border bg-muted/60 text-xs dark:bg-muted/50",children:[c.jsx("span",{className:"opacity-70",children:"Checkpoint:"}),c.jsx("select",{className:"border border-border rounded px-2 py-1 text-xs bg-card text-foreground focus:outline-none focus:ring-1 focus:ring-ring dark:bg-secondary",value:xe??"",onChange:oe=>{const ke=oe.target.value||null;Sr(ke)},children:Q.map(oe=>c.jsxs("option",{value:oe.checkpointId,children:[Rn(oe.createdAt),oe.preview?` — ${oe.preview.slice(0,40)}`:""]},oe.checkpointId))})]}),c.jsxs("div",{className:`relative ${Cr}`,style:r?{maxHeight:r}:void 0,children:[c.jsx(_a,{className:"h-full",style:{height:"100%"},messages:v,isStreaming:$,streamingAssistantId:B,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:Zt,enableMessageEditing:u,editingMessageId:ue,onStartReached:()=>{_n()},onEdit:Et,onRegenerate:Ur,onCancelEdit:hn,emptyMessage:Ke??void 0,isNavigatingCheckpoint:at}),N&&c.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[c.jsx(ae.Loader2,{className:"h-6 w-6 animate-spin"}),c.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]})]}),c.jsxs("div",{className:pn,children:[ue&&c.jsx("div",{className:"mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(ae.Edit3,{size:16,className:"text-blue-600"}),c.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),c.jsx(Je,{variant:"ghost",size:"sm",onClick:hn,className:"text-blue-600 hover:bg-blue-100",children:c.jsx(ae.X,{size:16})})]})}),(a||l)&&c.jsxs("div",{className:"mb-3 space-y-3",children:[a&&c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:st,type:"file",multiple:!0,onChange:oe=>yr(oe),className:"hidden"},O),Se.length>0&&c.jsx("div",{className:"flex flex-wrap gap-2",children:Se.map((oe,ke)=>c.jsxs("div",{className:"flex items-center gap-2 bg-gray-100 dark:bg-gray-800 rounded-lg px-3 py-2 text-sm text-gray-900 dark:text-gray-100",children:[c.jsx(ae.Paperclip,{size:14}),c.jsx("span",{className:"truncate max-w-[150px]",children:oe.name}),c.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>yt(ke),className:"h-4 w-4 p-0 text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400","aria-label":`Remove ${oe.name}`,children:c.jsx(ae.X,{size:12})})]},ke))})]}),l&&c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:ft,type:"file",accept:".xls,.xlsx,.xlsm",onChange:jn,className:"hidden"},ne),se&&c.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[c.jsx(ae.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),Pe&&!se&&c.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:Pe}),et&&!se&&c.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:et})]})]}),we&&c.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:we}),c.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&c.jsxs(tC,{children:[c.jsx(nC,{asChild:!0,children:c.jsx(Je,{type:"button",size:"icon",variant:"outline",disabled:$,title:"More input actions",className:d.moreButton||"",children:c.jsx(ae.Plus,{size:16})})}),c.jsxs(Hh,{align:"start",sideOffset:6,className:"w-52",children:[a&&c.jsxs(tl,{onClick:()=>{var oe;return(oe=st.current)==null?void 0:oe.click()},className:"cursor-pointer",children:[c.jsx(ae.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&c.jsxs(tl,{onClick:()=>{var oe;se||(oe=ft.current)==null||oe.click()},className:`cursor-pointer ${se?"opacity-60 pointer-events-none":""}`,children:[c.jsx(ae.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),c.jsx("div",{className:"flex-1",children:c.jsx(Ex,{initialValue:te,editingMessageId:ue,placeholder:ue?"Edit your message...":t,isStreaming:$,disabled:!1,maxLength:_s,onSend:To,onCancelEdit:hn,onStop:G,allowEmptySend:Se.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${ue?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${we?"border-red-400":""} ${d.textarea||""}`})})]})]})]})}const Ys=m.forwardRef(({className:e,type:t,...n},r)=>c.jsx("input",{type:t,className:ee("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:r,...n}));Ys.displayName="Input";function nl(e,[t,n]){return Math.min(n,Math.max(t,e))}function cC(e,t){return m.useReducer((n,r)=>t[n][r]??n,e)}var rl="ScrollArea",[Uh,Qk]=wn(rl),[uC,Xt]=Uh(rl),Wh=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,l]=m.useState(null),[u,d]=m.useState(null),[f,h]=m.useState(null),[p,b]=m.useState(null),[x,g]=m.useState(null),[v,w]=m.useState(0),[S,N]=m.useState(0),[k,T]=m.useState(!1),[E,A]=m.useState(!1),j=Ge(t,L=>l(L)),P=js(o);return c.jsx(uC,{scope:n,type:r,dir:P,scrollHideDelay:s,scrollArea:a,viewport:u,onViewportChange:d,content:f,onContentChange:h,scrollbarX:p,onScrollbarXChange:b,scrollbarXEnabled:k,onScrollbarXEnabledChange:T,scrollbarY:x,onScrollbarYChange:g,scrollbarYEnabled:E,onScrollbarYEnabledChange:A,onCornerWidthChange:w,onCornerHeightChange:N,children:c.jsx(_e.div,{dir:P,...i,ref:j,style:{position:"relative","--radix-scroll-area-corner-width":v+"px","--radix-scroll-area-corner-height":S+"px",...e.style}})})});Wh.displayName=rl;var Vh="ScrollAreaViewport",Kh=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=Xt(Vh,n),a=m.useRef(null),l=Ge(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(_e.div,{"data-radix-scroll-area-viewport":"",...s,ref:l,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:r})})]})});Kh.displayName=Vh;var En="ScrollAreaScrollbar",ol=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Xt(En,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return m.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?c.jsx(dC,{...r,ref:t,forceMount:n}):o.type==="scroll"?c.jsx(fC,{...r,ref:t,forceMount:n}):o.type==="auto"?c.jsx(qh,{...r,ref:t,forceMount:n}):o.type==="always"?c.jsx(sl,{...r,ref:t}):null});ol.displayName=En;var dC=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Xt(En,e.__scopeScrollArea),[s,i]=m.useState(!1);return m.useEffect(()=>{const a=o.scrollArea;let l=0;if(a){const u=()=>{window.clearTimeout(l),i(!0)},d=()=>{l=window.setTimeout(()=>i(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",u),a.addEventListener("pointerleave",d),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",u),a.removeEventListener("pointerleave",d)}}},[o.scrollArea,o.scrollHideDelay]),c.jsx(Ut,{present:n||s,children:c.jsx(qh,{"data-state":s?"visible":"hidden",...r,ref:t})})}),fC=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Xt(En,e.__scopeScrollArea),s=e.orientation==="horizontal",i=Qs(()=>l("SCROLL_END"),100),[a,l]=cC("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 m.useEffect(()=>{if(a==="idle"){const u=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(u)}},[a,o.scrollHideDelay,l]),m.useEffect(()=>{const u=o.viewport,d=s?"scrollLeft":"scrollTop";if(u){let f=u[d];const h=()=>{const p=u[d];f!==p&&(l("SCROLL"),i()),f=p};return u.addEventListener("scroll",h),()=>u.removeEventListener("scroll",h)}},[o.viewport,s,l,i]),c.jsx(Ut,{present:n||a!=="hidden",children:c.jsx(sl,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:fe(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:fe(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),qh=m.forwardRef((e,t)=>{const n=Xt(En,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=m.useState(!1),a=e.orientation==="horizontal",l=Qs(()=>{if(n.viewport){const u=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?u:d)}},10);return Br(n.viewport,l),Br(n.content,l),c.jsx(Ut,{present:r||s,children:c.jsx(sl,{"data-state":s?"visible":"hidden",...o,ref:t})})}),sl=m.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=Xt(En,e.__scopeScrollArea),s=m.useRef(null),i=m.useRef(0),[a,l]=m.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),u=Zh(a.viewport,a.content),d={...r,sizes:a,onSizesChange:l,hasThumb:u>0&&u<1,onThumbChange:h=>s.current=h,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:h=>i.current=h};function f(h,p){return vC(h,i.current,a,p)}return n==="horizontal"?c.jsx(hC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollLeft,p=Qh(h,a,o.dir);s.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollLeft=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollLeft=f(h,o.dir))}}):n==="vertical"?c.jsx(pC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollTop,p=Qh(h,a);s.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollTop=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollTop=f(h))}}):null}),hC=m.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=Xt(En,e.__scopeScrollArea),[i,a]=m.useState(),l=m.useRef(null),u=Ge(t,l,s.onScrollbarXChange);return m.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c.jsx(Yh,{"data-orientation":"horizontal",...o,ref:u,sizes:n,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":Zs(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,f)=>{if(s.viewport){const h=s.viewport.scrollLeft+d.deltaX;e.onWheelScroll(h),tp(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:Js(i.paddingLeft),paddingEnd:Js(i.paddingRight)}})}})}),pC=m.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=Xt(En,e.__scopeScrollArea),[i,a]=m.useState(),l=m.useRef(null),u=Ge(t,l,s.onScrollbarYChange);return m.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c.jsx(Yh,{"data-orientation":"vertical",...o,ref:u,sizes:n,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":Zs(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,f)=>{if(s.viewport){const h=s.viewport.scrollTop+d.deltaY;e.onWheelScroll(h),tp(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:Js(i.paddingTop),paddingEnd:Js(i.paddingBottom)}})}})}),[mC,Gh]=Uh(En),Yh=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:u,onWheelScroll:d,onResize:f,...h}=e,p=Xt(En,n),[b,x]=m.useState(null),g=Ge(t,j=>x(j)),v=m.useRef(null),w=m.useRef(""),S=p.viewport,N=r.content-r.viewport,k=Tt(d),T=Tt(l),E=Qs(f,10);function A(j){if(v.current){const P=j.clientX-v.current.left,L=j.clientY-v.current.top;u({x:P,y:L})}}return m.useEffect(()=>{const j=P=>{const L=P.target;(b==null?void 0:b.contains(L))&&k(P,N)};return document.addEventListener("wheel",j,{passive:!1}),()=>document.removeEventListener("wheel",j,{passive:!1})},[S,b,N,k]),m.useEffect(T,[r,T]),Br(b,E),Br(p.content,E),c.jsx(mC,{scope:n,scrollbar:b,hasThumb:o,onThumbChange:Tt(s),onThumbPointerUp:Tt(i),onThumbPositionChange:T,onThumbPointerDown:Tt(a),children:c.jsx(_e.div,{...h,ref:g,style:{position:"absolute",...h.style},onPointerDown:fe(e.onPointerDown,j=>{j.button===0&&(j.target.setPointerCapture(j.pointerId),v.current=b.getBoundingClientRect(),w.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),A(j))}),onPointerMove:fe(e.onPointerMove,A),onPointerUp:fe(e.onPointerUp,j=>{const P=j.target;P.hasPointerCapture(j.pointerId)&&P.releasePointerCapture(j.pointerId),document.body.style.webkitUserSelect=w.current,p.viewport&&(p.viewport.style.scrollBehavior=""),v.current=null})})})}),Xs="ScrollAreaThumb",Xh=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Gh(Xs,e.__scopeScrollArea);return c.jsx(Ut,{present:n||o.hasThumb,children:c.jsx(gC,{ref:t,...r})})}),gC=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=Xt(Xs,n),i=Gh(Xs,n),{onThumbPositionChange:a}=i,l=Ge(t,f=>i.onThumbChange(f)),u=m.useRef(void 0),d=Qs(()=>{u.current&&(u.current(),u.current=void 0)},100);return m.useEffect(()=>{const f=s.viewport;if(f){const h=()=>{if(d(),!u.current){const p=bC(f,a);u.current=p,a()}};return a(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[s.viewport,d,a]),c.jsx(_e.div,{"data-state":i.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:fe(e.onPointerDownCapture,f=>{const p=f.target.getBoundingClientRect(),b=f.clientX-p.left,x=f.clientY-p.top;i.onThumbPointerDown({x:b,y:x})}),onPointerUp:fe(e.onPointerUp,i.onThumbPointerUp)})});Xh.displayName=Xs;var il="ScrollAreaCorner",Jh=m.forwardRef((e,t)=>{const n=Xt(il,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?c.jsx(xC,{...e,ref:t}):null});Jh.displayName=il;var xC=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=Xt(il,n),[s,i]=m.useState(0),[a,l]=m.useState(0),u=!!(s&&a);return Br(o.scrollbarX,()=>{var f;const d=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(d),l(d)}),Br(o.scrollbarY,()=>{var f;const d=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(d),i(d)}),u?c.jsx(_e.div,{...r,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 Js(e){return e?parseInt(e,10):0}function Zh(e,t){const n=e/t;return isNaN(n)?0:n}function Zs(e){const t=Zh(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function vC(e,t,n,r="ltr"){const o=Zs(n),s=o/2,i=t||s,a=o-i,l=n.scrollbar.paddingStart+i,u=n.scrollbar.size-n.scrollbar.paddingEnd-a,d=n.content-n.viewport,f=r==="ltr"?[0,d]:[d*-1,0];return ep([l,u],f)(e)}function Qh(e,t,n="ltr"){const r=Zs(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,s=t.scrollbar.size-o,i=t.content-t.viewport,a=s-r,l=n==="ltr"?[0,i]:[i*-1,0],u=nl(e,l);return ep([0,i],[0,a])(u)}function ep(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function tp(e,t){return e>0&&e<t}var bC=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const s={left:e.scrollLeft,top:e.scrollTop},i=n.left!==s.left,a=n.top!==s.top;(i||a)&&t(),n=s,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function Qs(e,t){const n=Tt(e),r=m.useRef(0);return m.useEffect(()=>()=>window.clearTimeout(r.current),[]),m.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function Br(e,t){const n=Tt(t);Ct(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var np=Wh,wC=Kh,yC=Jh;const rp=m.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(np,{ref:r,className:ee("relative overflow-hidden",e),...n,children:[c.jsx(wC,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),c.jsx(op,{}),c.jsx(yC,{})]}));rp.displayName=np.displayName;const op=m.forwardRef(({className:e,orientation:t="vertical",...n},r)=>c.jsx(ol,{ref:r,orientation:t,className:ee("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:c.jsx(Xh,{className:"relative flex-1 rounded-full bg-border"})}));op.displayName=ol.displayName;function al({className:e="",showCreateButton:t=!0,showDeleteButton:n=!0,showEditTitle:r=!0,maxHeight:o="400px",customStyles:s={},currentThreadId:i=null,navigateToThread:a,onThreadSelect:l,onThreadCreate:u,onThreadDelete:d}){const{threads:f,currentThreadId:h,isLoading:p,actions:b}=Ho(),{loadThread:x}=Uo(),{createThread:g,deleteThread:v,renameThread:w}=b,[S,N]=y.useState(Array.isArray(f)?f:[]),k=y.useRef(S.length>0),[T,E]=y.useState(null),[A,j]=y.useState(""),[P,L]=y.useState(!1);y.useEffect(()=>{const D=Array.isArray(f)?f:[];if(D.length>0){k.current=!0,N(D);return}p||(k.current=!1,N(D))},[f,p]);const $=async D=>{try{await x(D),a==null||a(D),l==null||l(D)}catch(te){console.error("Failed to select thread:",te)}},V=async()=>{try{L(!0);const D=await g();u==null||u(D),a==null||a(D)}catch(D){console.error("Failed to create thread:",D)}finally{L(!1)}},M=async(D,te)=>{if(te.stopPropagation(),!!confirm("Delete this thread?"))try{await v(D),d==null||d(D)}catch(he){console.error("Failed to delete thread:",he)}},G=(D,te)=>{te.stopPropagation(),E(D.threadId),j(D.title||`Thread ${D.threadId.slice(0,8)}`)},K=async D=>{if(A.trim())try{await w(D,A.trim()),E(null),j("")}catch(te){console.error("Failed to update title:",te)}},W=()=>{E(null),j("")},z=(D,te)=>{D.key==="Enter"?K(te):D.key==="Escape"&&W()},B=D=>{if(!D)return"";try{const te=new Date(D),we=new Date().getTime()-te.getTime(),ye=Math.floor(we/(1e3*60*60*24));return ye===0?te.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):ye===1?"Yesterday":ye<7?`${ye} days ago`:te.toLocaleDateString()}catch{return""}},ue=D=>D.title||`Thread ${D.threadId.slice(0,8)}`;return c.jsxs("div",{className:`flex flex-col h-full ${e} ${s.container||""}`,children:[t&&c.jsx("div",{className:s.header||"flex-shrink-0 p-2 border-b bg-slate-800 border-slate-700 text-slate-100 flex justify-end",children:c.jsx(Je,{onClick:V,disabled:P||p,className:s.createButton||"p-2",size:"sm",variant:"ghost",title:P?"Creating...":"New Chat",children:c.jsx(ae.MessageSquarePlus,{size:20})})}),c.jsx(rp,{className:`flex-1 min-h-0 ${s.threadList||""}`,style:o?{maxHeight:o}:void 0,children:c.jsx("div",{className:"p-2 space-y-1 pb-4",children:p?c.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[c.jsx(ae.Loader2,{className:"h-5 w-5 animate-spin"}),c.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):S.length===0?c.jsxs("div",{className:"text-center py-8 text-slate-400",children:[c.jsx(ae.MessageSquare,{className:"w-8 h-8 mx-auto mb-2 opacity-40 text-slate-500"}),c.jsx("p",{className:"text-sm text-slate-500",children:"No conversations yet"})]}):S.slice().sort((D,te)=>new Date(te.updatedAt||te.createdAt||"").getTime()-new Date(D.updatedAt||D.createdAt||"").getTime()).map(D=>c.jsxs("div",{onClick:()=>$(D.threadId),className:`group relative p-3 rounded-lg cursor-pointer transition-colors border ${(i??h)===D.threadId?`${s.activeThread||"bg-slate-600 border-slate-500"} `:`${s.threadItem||"bg-slate-700 border-slate-600 hover:bg-slate-600 text-gray-900 dark:text-slate-100"}`} ${s.threadItem||""} text-gray-900 dark:text-slate-100`,children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("div",{className:"flex-1 min-w-0",children:T===D.threadId?c.jsxs("div",{className:"flex items-center gap-2",onClick:te=>te.stopPropagation(),children:[c.jsx(Ys,{value:A,onChange:te=>j(te.target.value),onKeyDown:te=>z(te,D.threadId),className:"h-6 text-sm",autoFocus:!0}),c.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>K(D.threadId),className:"h-6 w-6 p-0",children:c.jsx(ae.Check,{size:12})}),c.jsx(Je,{variant:"ghost",size:"sm",onClick:W,className:"h-6 w-6 p-0",children:c.jsx(ae.X,{size:12})})]}):c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"font-medium text-sm truncate text-gray-900 dark:text-slate-100",children:ue(D)}),c.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mt-1",children:[c.jsx(ae.Calendar,{size:10}),c.jsx("span",{children:B(D.updatedAt||D.createdAt)})]})]})}),c.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2",children:[r&&T!==D.threadId&&c.jsx(Je,{variant:"ghost",size:"sm",onClick:te=>G(D,te),className:"h-6 w-6 p-0",title:"Edit title",children:c.jsx(ae.Edit3,{size:12})}),n&&c.jsx(Je,{variant:"ghost",size:"sm",onClick:te=>M(D.threadId,te),className:"h-6 w-6 p-0 text-red-400 hover:text-red-300 hover:bg-red-900/20",title:"Delete thread",children:c.jsx(ae.Trash2,{size:12})})]})]}),i===D.threadId&&c.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-blue-400 rounded-r"})]},D.threadId))})})]})}function zr(e){if(!(typeof globalThis>"u"))return globalThis[e]}function SC(e){if(typeof e!="string")return;const t=e.trim();if(t)return On(t)}function sp(){const e=[zr("__API_BASE_URL__"),zr("__CHAT_API_BASE_URL__"),zr("__CHAT_API_URL__")];for(const t of e){const n=SC(t);if(n)return n}}function ip(){const e=[zr("__API_AUTH_TOKEN__"),zr("__CHAT_API_KEY__"),zr("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function ap(...e){for(const t of e)if(typeof t=="string"&&t.trim())return On(t);return On()}function lp(){const e={},t=sp(),n=ip();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function cp(){const e=lp(),t=Bn.getAuthToken(),n=sp();return{apiBaseUrl:ap(e.baseUrl,Bn.baseUrl,n),apiKey:t||e.apiKey||ip()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,truncateToolMessages:!0,toolMessagePreviewLength:200,darkMode:!1,enableSound:!1,messageHistory:100}}const up="chat-settings";function CC(){try{const e=localStorage.getItem(up);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function kC(e){try{const t={...e,apiBaseUrl:On(e.apiBaseUrl)};localStorage.setItem(up,JSON.stringify(t)),t.apiKey&&Bn.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function TC(){const e=cp(),t=CC(),n=Bn.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:ap(Bn.baseUrl,r,e.apiBaseUrl)}}function IC(e){Bn.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),kC(e)}var EC="Label",dp=m.forwardRef((e,t)=>c.jsx(_e.label,{...e,ref:t,onMouseDown:n=>{var o;n.target.closest("button, input, select, textarea")||((o=e.onMouseDown)==null||o.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));dp.displayName=EC;var fp=dp;const NC=Io.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Jt=m.forwardRef(({className:e,...t},n)=>c.jsx(fp,{ref:n,className:ee(NC(),e),...t}));Jt.displayName=fp.displayName;function hp(e){const t=m.useRef({value:e,previous:e});return m.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var ei="Switch",[AC,eT]=wn(ei),[_C,jC]=AC(ei),pp=m.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:s,required:i,disabled:a,value:l="on",onCheckedChange:u,form:d,...f}=e,[h,p]=m.useState(null),b=Ge(t,S=>p(S)),x=m.useRef(!1),g=h?d||!!h.closest("form"):!0,[v,w]=ur({prop:o,defaultProp:s??!1,onChange:u,caller:ei});return c.jsxs(_C,{scope:n,checked:v,disabled:a,children:[c.jsx(_e.button,{type:"button",role:"switch","aria-checked":v,"aria-required":i,"data-state":vp(v),"data-disabled":a?"":void 0,disabled:a,value:l,...f,ref:b,onClick:fe(e.onClick,S=>{w(N=>!N),g&&(x.current=S.isPropagationStopped(),x.current||S.stopPropagation())})}),g&&c.jsx(xp,{control:h,bubbles:!x.current,name:r,value:l,checked:v,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});pp.displayName=ei;var mp="SwitchThumb",gp=m.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=jC(mp,n);return c.jsx(_e.span,{"data-state":vp(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});gp.displayName=mp;var RC="SwitchBubbleInput",xp=m.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=m.useRef(null),a=Ge(i,s),l=hp(n),u=Nf(t);return m.useEffect(()=>{const d=i.current;if(!d)return;const f=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(f,"checked").set;if(l!==n&&p){const b=new Event("click",{bubbles:r});p.call(d,n),d.dispatchEvent(b)}},[l,n,r]),c.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...o,tabIndex:-1,ref:a,style:{...o.style,...u,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});xp.displayName=RC;function vp(e){return e?"checked":"unchecked"}var bp=pp,PC=gp;const Xn=m.forwardRef(({className:e,...t},n)=>c.jsx(bp,{className:ee("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:c.jsx(PC,{className:ee("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Xn.displayName=bp.displayName;var wp=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),OC="VisuallyHidden",MC=m.forwardRef((e,t)=>c.jsx(_e.span,{...e,ref:t,style:{...wp,...e.style}}));MC.displayName=OC;var DC=[" ","Enter","ArrowUp","ArrowDown"],LC=[" ","Enter"],vr="Select",[ti,ni,$C]=ja(vr),[Hr,tT]=wn(vr,[$C,Hs]),ri=Hs(),[FC,Jn]=Hr(vr),[BC,zC]=Hr(vr),yp=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:s,value:i,defaultValue:a,onValueChange:l,dir:u,name:d,autoComplete:f,disabled:h,required:p,form:b}=e,x=ri(t),[g,v]=m.useState(null),[w,S]=m.useState(null),[N,k]=m.useState(!1),T=js(u),[E,A]=ur({prop:r,defaultProp:o??!1,onChange:s,caller:vr}),[j,P]=ur({prop:i,defaultProp:a,onChange:l,caller:vr}),L=m.useRef(null),$=g?b||!!g.closest("form"):!0,[V,M]=m.useState(new Set),G=Array.from(V).map(K=>K.props.value).join(";");return c.jsx($f,{...x,children:c.jsxs(FC,{required:p,scope:t,trigger:g,onTriggerChange:v,valueNode:w,onValueNodeChange:S,valueNodeHasChildren:N,onValueNodeHasChildrenChange:k,contentId:yn(),value:j,onValueChange:P,open:E,onOpenChange:A,dir:T,triggerPointerDownPosRef:L,disabled:h,children:[c.jsx(ti.Provider,{scope:t,children:c.jsx(BC,{scope:e.__scopeSelect,onNativeOptionAdd:m.useCallback(K=>{M(W=>new Set(W).add(K))},[]),onNativeOptionRemove:m.useCallback(K=>{M(W=>{const z=new Set(W);return z.delete(K),z})},[]),children:n})}),$?c.jsxs(Vp,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:f,value:j,onChange:K=>P(K.target.value),disabled:h,form:b,children:[j===void 0?c.jsx("option",{value:""}):null,Array.from(V)]},G):null]})})};yp.displayName=vr;var Sp="SelectTrigger",Cp=m.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=ri(n),i=Jn(Sp,n),a=i.disabled||r,l=Ge(t,i.onTriggerChange),u=ni(n),d=m.useRef("touch"),[f,h,p]=qp(x=>{const g=u().filter(S=>!S.disabled),v=g.find(S=>S.value===i.value),w=Gp(g,x,v);w!==void 0&&i.onValueChange(w.value)}),b=x=>{a||(i.onOpenChange(!0),p()),x&&(i.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)})};return c.jsx(Ff,{asChild:!0,...s,children:c.jsx(_e.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":Kp(i.value)?"":void 0,...o,ref:l,onClick:fe(o.onClick,x=>{x.currentTarget.focus(),d.current!=="mouse"&&b(x)}),onPointerDown:fe(o.onPointerDown,x=>{d.current=x.pointerType;const g=x.target;g.hasPointerCapture(x.pointerId)&&g.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&x.pointerType==="mouse"&&(b(x),x.preventDefault())}),onKeyDown:fe(o.onKeyDown,x=>{const g=f.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&h(x.key),!(g&&x.key===" ")&&DC.includes(x.key)&&(b(),x.preventDefault())})})})});Cp.displayName=Sp;var kp="SelectValue",Tp=m.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=Jn(kp,n),{onValueNodeHasChildrenChange:u}=l,d=s!==void 0,f=Ge(t,l.onValueNodeChange);return Ct(()=>{u(d)},[u,d]),c.jsx(_e.span,{...a,ref:f,style:{pointerEvents:"none"},children:Kp(l.value)?c.jsx(c.Fragment,{children:i}):s})});Tp.displayName=kp;var HC="SelectIcon",Ip=m.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return c.jsx(_e.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});Ip.displayName=HC;var UC="SelectPortal",Ep=e=>c.jsx(ms,{asChild:!0,...e});Ep.displayName=UC;var br="SelectContent",Np=m.forwardRef((e,t)=>{const n=Jn(br,e.__scopeSelect),[r,o]=m.useState();if(Ct(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?Eo.createPortal(c.jsx(Ap,{scope:e.__scopeSelect,children:c.jsx(ti.Slot,{scope:e.__scopeSelect,children:c.jsx("div",{children:e.children})})}),s):null}return c.jsx(_p,{...e,ref:t})});Np.displayName=br;var un=10,[Ap,Zn]=Hr(br),WC="SelectContentImpl",VC=nr.createSlot("SelectContent.RemoveScroll"),_p=m.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:s,onPointerDownOutside:i,side:a,sideOffset:l,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:b,hideWhenDetached:x,avoidCollisions:g,...v}=e,w=Jn(br,n),[S,N]=m.useState(null),[k,T]=m.useState(null),E=Ge(t,q=>N(q)),[A,j]=m.useState(null),[P,L]=m.useState(null),$=ni(n),[V,M]=m.useState(!1),G=m.useRef(!1);m.useEffect(()=>{if(S)return Ta(S)},[S]),ba();const K=m.useCallback(q=>{const[O,...X]=$().map(se=>se.ref.current),[ne]=X.slice(-1),pe=document.activeElement;for(const se of q)if(se===pe||(se==null||se.scrollIntoView({block:"nearest"}),se===O&&k&&(k.scrollTop=0),se===ne&&k&&(k.scrollTop=k.scrollHeight),se==null||se.focus(),document.activeElement!==pe))return},[$,k]),W=m.useCallback(()=>K([A,S]),[K,A,S]);m.useEffect(()=>{V&&W()},[V,W]);const{onOpenChange:z,triggerPointerDownPosRef:B}=w;m.useEffect(()=>{if(S){let q={x:0,y:0};const O=ne=>{var pe,se;q={x:Math.abs(Math.round(ne.pageX)-(((pe=B.current)==null?void 0:pe.x)??0)),y:Math.abs(Math.round(ne.pageY)-(((se=B.current)==null?void 0:se.y)??0))}},X=ne=>{q.x<=10&&q.y<=10?ne.preventDefault():S.contains(ne.target)||z(!1),document.removeEventListener("pointermove",O),B.current=null};return B.current!==null&&(document.addEventListener("pointermove",O),document.addEventListener("pointerup",X,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",O),document.removeEventListener("pointerup",X,{capture:!0})}}},[S,z,B]),m.useEffect(()=>{const q=()=>z(!1);return window.addEventListener("blur",q),window.addEventListener("resize",q),()=>{window.removeEventListener("blur",q),window.removeEventListener("resize",q)}},[z]);const[ue,D]=qp(q=>{const O=$().filter(pe=>!pe.disabled),X=O.find(pe=>pe.ref.current===document.activeElement),ne=Gp(O,q,X);ne&&setTimeout(()=>ne.ref.current.focus())}),te=m.useCallback((q,O,X)=>{const ne=!G.current&&!X;(w.value!==void 0&&w.value===O||ne)&&(j(q),ne&&(G.current=!0))},[w.value]),he=m.useCallback(()=>S==null?void 0:S.focus(),[S]),we=m.useCallback((q,O,X)=>{const ne=!G.current&&!X;(w.value!==void 0&&w.value===O||ne)&&L(q)},[w.value]),ye=r==="popper"?ll:jp,Se=ye===ll?{side:a,sideOffset:l,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:b,hideWhenDetached:x,avoidCollisions:g}:{};return c.jsx(Ap,{scope:n,content:S,viewport:k,onViewportChange:T,itemRefCallback:te,selectedItem:A,onItemLeave:he,itemTextRefCallback:we,focusSelectedItem:W,selectedItemText:P,position:r,isPositioned:V,searchRef:ue,children:c.jsx(ys,{as:VC,allowPinchZoom:!0,children:c.jsx(ps,{asChild:!0,trapped:w.open,onMountAutoFocus:q=>{q.preventDefault()},onUnmountAutoFocus:fe(o,q=>{var O;(O=w.trigger)==null||O.focus({preventScroll:!0}),q.preventDefault()}),children:c.jsx(hs,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:q=>q.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:c.jsx(ye,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:q=>q.preventDefault(),...v,...Se,onPlaced:()=>M(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...v.style},onKeyDown:fe(v.onKeyDown,q=>{const O=q.ctrlKey||q.altKey||q.metaKey;if(q.key==="Tab"&&q.preventDefault(),!O&&q.key.length===1&&D(q.key),["ArrowUp","ArrowDown","Home","End"].includes(q.key)){let ne=$().filter(pe=>!pe.disabled).map(pe=>pe.ref.current);if(["ArrowUp","End"].includes(q.key)&&(ne=ne.slice().reverse()),["ArrowUp","ArrowDown"].includes(q.key)){const pe=q.target,se=ne.indexOf(pe);ne=ne.slice(se+1)}setTimeout(()=>K(ne)),q.preventDefault()}})})})})})})});_p.displayName=WC;var KC="SelectItemAlignedPosition",jp=m.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=Jn(br,n),i=Zn(br,n),[a,l]=m.useState(null),[u,d]=m.useState(null),f=Ge(t,E=>d(E)),h=ni(n),p=m.useRef(!1),b=m.useRef(!0),{viewport:x,selectedItem:g,selectedItemText:v,focusSelectedItem:w}=i,S=m.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&u&&x&&g&&v){const E=s.trigger.getBoundingClientRect(),A=u.getBoundingClientRect(),j=s.valueNode.getBoundingClientRect(),P=v.getBoundingClientRect();if(s.dir!=="rtl"){const pe=P.left-A.left,se=j.left-pe,me=E.left-se,et=E.width+me,tt=Math.max(et,A.width),Pe=window.innerWidth-un,Ve=nl(se,[un,Math.max(un,Pe-tt)]);a.style.minWidth=et+"px",a.style.left=Ve+"px"}else{const pe=A.right-P.right,se=window.innerWidth-j.right-pe,me=window.innerWidth-E.right-se,et=E.width+me,tt=Math.max(et,A.width),Pe=window.innerWidth-un,Ve=nl(se,[un,Math.max(un,Pe-tt)]);a.style.minWidth=et+"px",a.style.right=Ve+"px"}const L=h(),$=window.innerHeight-un*2,V=x.scrollHeight,M=window.getComputedStyle(u),G=parseInt(M.borderTopWidth,10),K=parseInt(M.paddingTop,10),W=parseInt(M.borderBottomWidth,10),z=parseInt(M.paddingBottom,10),B=G+K+V+z+W,ue=Math.min(g.offsetHeight*5,B),D=window.getComputedStyle(x),te=parseInt(D.paddingTop,10),he=parseInt(D.paddingBottom,10),we=E.top+E.height/2-un,ye=$-we,Se=g.offsetHeight/2,q=g.offsetTop+Se,O=G+K+q,X=B-O;if(O<=we){const pe=L.length>0&&g===L[L.length-1].ref.current;a.style.bottom="0px";const se=u.clientHeight-x.offsetTop-x.offsetHeight,me=Math.max(ye,Se+(pe?he:0)+se+W),et=O+me;a.style.height=et+"px"}else{const pe=L.length>0&&g===L[0].ref.current;a.style.top="0px";const me=Math.max(we,G+x.offsetTop+(pe?te:0)+Se)+X;a.style.height=me+"px",x.scrollTop=O-we+x.offsetTop}a.style.margin=`${un}px 0`,a.style.minHeight=ue+"px",a.style.maxHeight=$+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[h,s.trigger,s.valueNode,a,u,x,g,v,s.dir,r]);Ct(()=>S(),[S]);const[N,k]=m.useState();Ct(()=>{u&&k(window.getComputedStyle(u).zIndex)},[u]);const T=m.useCallback(E=>{E&&b.current===!0&&(S(),w==null||w(),b.current=!1)},[S,w]);return c.jsx(GC,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:T,children:c.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:N},children:c.jsx(_e.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});jp.displayName=KC;var qC="SelectPopperPosition",ll=m.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=un,...s}=e,i=ri(n);return c.jsx(Bf,{...i,...s,ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});ll.displayName=qC;var[GC,cl]=Hr(br,{}),ul="SelectViewport",Rp=m.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=Zn(ul,n),i=cl(ul,n),a=Ge(t,s.onViewportChange),l=m.useRef(0);return c.jsxs(c.Fragment,{children:[c.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),c.jsx(ti.Slot,{scope:n,children:c.jsx(_e.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:fe(o.onScroll,u=>{const d=u.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:h}=i;if(h!=null&&h.current&&f){const p=Math.abs(l.current-d.scrollTop);if(p>0){const b=window.innerHeight-un*2,x=parseFloat(f.style.minHeight),g=parseFloat(f.style.height),v=Math.max(x,g);if(v<b){const w=v+p,S=Math.min(b,w),N=w-S;f.style.height=S+"px",f.style.bottom==="0px"&&(d.scrollTop=N>0?N:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});Rp.displayName=ul;var Pp="SelectGroup",[YC,XC]=Hr(Pp),JC=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=yn();return c.jsx(YC,{scope:n,id:o,children:c.jsx(_e.div,{role:"group","aria-labelledby":o,...r,ref:t})})});JC.displayName=Pp;var Op="SelectLabel",Mp=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=XC(Op,n);return c.jsx(_e.div,{id:o.id,...r,ref:t})});Mp.displayName=Op;var oi="SelectItem",[ZC,Dp]=Hr(oi),Lp=m.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=Jn(oi,n),l=Zn(oi,n),u=a.value===r,[d,f]=m.useState(s??""),[h,p]=m.useState(!1),b=Ge(t,w=>{var S;return(S=l.itemRefCallback)==null?void 0:S.call(l,w,r,o)}),x=yn(),g=m.useRef("touch"),v=()=>{o||(a.onValueChange(r),a.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return c.jsx(ZC,{scope:n,value:r,disabled:o,textId:x,isSelected:u,onItemTextChange:m.useCallback(w=>{f(S=>S||((w==null?void 0:w.textContent)??"").trim())},[]),children:c.jsx(ti.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:c.jsx(_e.div,{role:"option","aria-labelledby":x,"data-highlighted":h?"":void 0,"aria-selected":u&&h,"data-state":u?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:b,onFocus:fe(i.onFocus,()=>p(!0)),onBlur:fe(i.onBlur,()=>p(!1)),onClick:fe(i.onClick,()=>{g.current!=="mouse"&&v()}),onPointerUp:fe(i.onPointerUp,()=>{g.current==="mouse"&&v()}),onPointerDown:fe(i.onPointerDown,w=>{g.current=w.pointerType}),onPointerMove:fe(i.onPointerMove,w=>{var S;g.current=w.pointerType,o?(S=l.onItemLeave)==null||S.call(l):g.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:fe(i.onPointerLeave,w=>{var S;w.currentTarget===document.activeElement&&((S=l.onItemLeave)==null||S.call(l))}),onKeyDown:fe(i.onKeyDown,w=>{var N;((N=l.searchRef)==null?void 0:N.current)!==""&&w.key===" "||(LC.includes(w.key)&&v(),w.key===" "&&w.preventDefault())})})})})});Lp.displayName=oi;var ko="SelectItemText",$p=m.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=Jn(ko,n),a=Zn(ko,n),l=Dp(ko,n),u=zC(ko,n),[d,f]=m.useState(null),h=Ge(t,v=>f(v),l.onItemTextChange,v=>{var w;return(w=a.itemTextRefCallback)==null?void 0:w.call(a,v,l.value,l.disabled)}),p=d==null?void 0:d.textContent,b=m.useMemo(()=>c.jsx("option",{value:l.value,disabled:l.disabled,children:p},l.value),[l.disabled,l.value,p]),{onNativeOptionAdd:x,onNativeOptionRemove:g}=u;return Ct(()=>(x(b),()=>g(b)),[x,g,b]),c.jsxs(c.Fragment,{children:[c.jsx(_e.span,{id:l.textId,...s,ref:h}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Eo.createPortal(s.children,i.valueNode):null]})});$p.displayName=ko;var Fp="SelectItemIndicator",Bp=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return Dp(Fp,n).isSelected?c.jsx(_e.span,{"aria-hidden":!0,...r,ref:t}):null});Bp.displayName=Fp;var dl="SelectScrollUpButton",zp=m.forwardRef((e,t)=>{const n=Zn(dl,e.__scopeSelect),r=cl(dl,e.__scopeSelect),[o,s]=m.useState(!1),i=Ge(t,r.onScrollButtonChange);return Ct(()=>{if(n.viewport&&n.isPositioned){let a=function(){const u=l.scrollTop>0;s(u)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?c.jsx(Up,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});zp.displayName=dl;var fl="SelectScrollDownButton",Hp=m.forwardRef((e,t)=>{const n=Zn(fl,e.__scopeSelect),r=cl(fl,e.__scopeSelect),[o,s]=m.useState(!1),i=Ge(t,r.onScrollButtonChange);return Ct(()=>{if(n.viewport&&n.isPositioned){let a=function(){const u=l.scrollHeight-l.clientHeight,d=Math.ceil(l.scrollTop)<u;s(d)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?c.jsx(Up,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});Hp.displayName=fl;var Up=m.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=Zn("SelectScrollButton",n),i=m.useRef(null),a=ni(n),l=m.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return m.useEffect(()=>()=>l(),[l]),Ct(()=>{var d;const u=a().find(f=>f.ref.current===document.activeElement);(d=u==null?void 0:u.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),c.jsx(_e.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:fe(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:fe(o.onPointerMove,()=>{var u;(u=s.onItemLeave)==null||u.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:fe(o.onPointerLeave,()=>{l()})})}),QC="SelectSeparator",Wp=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return c.jsx(_e.div,{"aria-hidden":!0,...r,ref:t})});Wp.displayName=QC;var hl="SelectArrow",ek=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ri(n),s=Jn(hl,n),i=Zn(hl,n);return s.open&&i.position==="popper"?c.jsx(zf,{...o,...r,ref:t}):null});ek.displayName=hl;var tk="SelectBubbleInput",Vp=m.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=m.useRef(null),s=Ge(r,o),i=hp(t);return m.useEffect(()=>{const a=o.current;if(!a)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("change",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),c.jsx(_e.select,{...n,style:{...wp,...n.style},ref:s,defaultValue:t})});Vp.displayName=tk;function Kp(e){return e===""||e===void 0}function qp(e){const t=Tt(e),n=m.useRef(""),r=m.useRef(0),o=m.useCallback(i=>{const a=n.current+i;t(a),function l(u){n.current=u,window.clearTimeout(r.current),u!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}(a)},[t]),s=m.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return m.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,s]}function Gp(e,t,n){const o=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=nk(e,Math.max(s,0));o.length===1&&(i=i.filter(u=>u!==n));const l=i.find(u=>u.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function nk(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var rk=yp,Yp=Cp,ok=Tp,sk=Ip,ik=Ep,Xp=Np,ak=Rp,Jp=Mp,Zp=Lp,lk=$p,ck=Bp,Qp=zp,em=Hp,tm=Wp;const nm=rk,rm=ok,pl=m.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(Yp,{ref:r,className:ee("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,c.jsx(sk,{asChild:!0,children:c.jsx(ae.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));pl.displayName=Yp.displayName;const om=m.forwardRef(({className:e,...t},n)=>c.jsx(Qp,{ref:n,className:ee("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(ae.ChevronUp,{className:"h-4 w-4"})}));om.displayName=Qp.displayName;const sm=m.forwardRef(({className:e,...t},n)=>c.jsx(em,{ref:n,className:ee("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(ae.ChevronDown,{className:"h-4 w-4"})}));sm.displayName=em.displayName;const ml=m.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>c.jsx(ik,{children:c.jsxs(Xp,{ref:o,className:ee("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md 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",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[c.jsx(om,{}),c.jsx(ak,{className:ee("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),c.jsx(sm,{})]})}));ml.displayName=Xp.displayName;const uk=m.forwardRef(({className:e,...t},n)=>c.jsx(Jp,{ref:n,className:ee("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));uk.displayName=Jp.displayName;const wr=m.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(Zp,{ref:r,className:ee("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[c.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:c.jsx(ck,{children:c.jsx(ae.Check,{className:"h-4 w-4"})})}),c.jsx(lk,{children:t})]}));wr.displayName=Zp.displayName;const dk=m.forwardRef(({className:e,...t},n)=>c.jsx(tm,{ref:n,className:ee("-mx-1 my-1 h-px bg-muted",e),...t}));dk.displayName=tm.displayName;var fk="Separator",im="horizontal",hk=["horizontal","vertical"],am=m.forwardRef((e,t)=>{const{decorative:n,orientation:r=im,...o}=e,s=pk(r)?r:im,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return c.jsx(_e.div,{"data-orientation":s,...a,...o,ref:t})});am.displayName=fk;function pk(e){return hk.includes(e)}var lm=am;const cm=m.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>c.jsx(lm,{ref:o,decorative:n,orientation:t,className:ee("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));cm.displayName=lm.displayName;const mk=Vd,gk=Yw,xk=Kd,um=m.forwardRef(({className:e,...t},n)=>c.jsx(Is,{className:ee("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));um.displayName=Is.displayName;const vk=Io.cva("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),dm=m.forwardRef(({side:e="right",className:t,children:n,...r},o)=>c.jsxs(xk,{children:[c.jsx(um,{}),c.jsxs(Es,{ref:o,className:ee(vk({side:e}),t),...r,children:[n,c.jsxs(qd,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[c.jsx(ae.X,{className:"h-4 w-4"}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));dm.displayName=Es.displayName;const fm=({className:e,...t})=>c.jsx("div",{className:ee("flex flex-col space-y-2 text-center sm:text-left",e),...t});fm.displayName="SheetHeader";const hm=m.forwardRef(({className:e,...t},n)=>c.jsx(hr,{ref:n,className:ee("text-lg font-semibold text-foreground",e),...t}));hm.displayName=hr.displayName;const pm=m.forwardRef(({className:e,...t},n)=>c.jsx(Ns,{ref:n,className:ee("text-sm text-muted-foreground",e),...t}));pm.displayName=Ns.displayName;const bk={api:{baseUrl:"http://localhost:8000/api",authToken:"",enableAuth:!1},ui:{layout:"sidebar",theme:"light",showTimestamps:!0,showAgentNames:!0,compactMessages:!1},behavior:{autoSave:!0,enableStreaming:!0,showTypingIndicator:!0}};function wk({settings:e,onSettingsChange:t,className:n=""}){const[r,o]=y.useState(!1),[s,i]=y.useState(!1),[a,l]=y.useState(e),[u,d]=y.useState(!1),{toast:f}=pa();y.useEffect(()=>{const g=JSON.stringify(a)!==JSON.stringify(e);d(g)},[a,e]),y.useEffect(()=>{l(e)},[e]);const h=()=>{t(a),d(!1),f({title:"Settings saved",description:"Your chat configuration has been updated successfully."})},p=()=>{l(bk),d(!0),f({title:"Settings reset",description:"Configuration has been reset to defaults."})},b=()=>{l(e),d(!1),o(!1)},x=async()=>{try{const v=await(await fetch(`${a.api.baseUrl}/health`)).json();f({title:"Connection successful",description:`API is ${v.status||"healthy"}`})}catch{f({title:"Connection failed",description:"Unable to connect to the API endpoint.",variant:"destructive"})}};return c.jsxs(mk,{open:r,onOpenChange:o,children:[c.jsx(gk,{asChild:!0,children:c.jsxs(Je,{variant:"outline",size:"sm",className:n,children:[c.jsx(ae.Settings,{className:"h-4 w-4 mr-2"}),"Settings",u&&c.jsx(oa,{variant:"destructive",className:"ml-2 h-4 w-4 p-0"})]})}),c.jsxs(dm,{className:"w-[500px] sm:w-[600px] overflow-y-auto",children:[c.jsxs(fm,{children:[c.jsx(hm,{children:"Chat Settings"}),c.jsx(pm,{children:"Configure your chat interface, API connection, and behavior preferences."})]}),c.jsxs("div",{className:"space-y-6 py-6",children:[c.jsxs(co,{children:[c.jsx(uo,{className:"pb-3",children:c.jsxs(fo,{className:"text-lg flex items-center gap-2",children:[c.jsx(ae.Server,{className:"h-5 w-5"}),"API Configuration"]})}),c.jsxs(is,{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Jt,{htmlFor:"api-url",children:"API Base URL"}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx(Ys,{id:"api-url",value:a.api.baseUrl,onChange:g=>l(v=>({...v,api:{...v.api,baseUrl:g.target.value}})),placeholder:"http://localhost:8000/api"}),c.jsx(Je,{variant:"outline",onClick:x,children:"Test"})]})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(Jt,{htmlFor:"enable-auth",children:"Enable Authentication"}),c.jsx(Xn,{id:"enable-auth",checked:a.api.enableAuth,onCheckedChange:g=>l(v=>({...v,api:{...v.api,enableAuth:g}}))})]}),a.api.enableAuth&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(Jt,{htmlFor:"auth-token",children:"Authentication Token"}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx(Ys,{id:"auth-token",type:s?"text":"password",value:a.api.authToken,onChange:g=>l(v=>({...v,api:{...v.api,authToken:g.target.value}})),placeholder:"Enter your Bearer token"}),c.jsx(Je,{variant:"outline",size:"icon",onClick:()=>i(!s),children:s?c.jsx(ae.EyeOff,{className:"h-4 w-4"}):c.jsx(ae.Eye,{className:"h-4 w-4"})})]})]})]})]}),c.jsxs(co,{children:[c.jsx(uo,{className:"pb-3",children:c.jsxs(fo,{className:"text-lg flex items-center gap-2",children:[c.jsx(ae.Layout,{className:"h-5 w-5"}),"Interface Settings"]})}),c.jsxs(is,{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Jt,{htmlFor:"layout",children:"Layout Style"}),c.jsxs(nm,{value:a.ui.layout,onValueChange:g=>l(v=>({...v,ui:{...v.ui,layout:g}})),children:[c.jsx(pl,{children:c.jsx(rm,{})}),c.jsxs(ml,{children:[c.jsx(wr,{value:"sidebar",children:"Sidebar Layout"}),c.jsx(wr,{value:"fullscreen",children:"Fullscreen"}),c.jsx(wr,{value:"tabs",children:"Tabbed Interface"})]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Jt,{htmlFor:"theme",children:"Theme"}),c.jsxs(nm,{value:a.ui.theme,onValueChange:g=>l(v=>({...v,ui:{...v.ui,theme:g}})),children:[c.jsx(pl,{children:c.jsx(rm,{})}),c.jsxs(ml,{children:[c.jsx(wr,{value:"light",children:"Light"}),c.jsx(wr,{value:"dark",children:"Dark"}),c.jsx(wr,{value:"system",children:"System"})]})]})]}),c.jsx(cm,{}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(Jt,{htmlFor:"show-timestamps",children:"Show Timestamps"}),c.jsx(Xn,{id:"show-timestamps",checked:a.ui.showTimestamps,onCheckedChange:g=>l(v=>({...v,ui:{...v.ui,showTimestamps:g}}))})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(Jt,{htmlFor:"show-agent-names",children:"Show Agent Names"}),c.jsx(Xn,{id:"show-agent-names",checked:a.ui.showAgentNames,onCheckedChange:g=>l(v=>({...v,ui:{...v.ui,showAgentNames:g}}))})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(Jt,{htmlFor:"compact-messages",children:"Compact Messages"}),c.jsx(Xn,{id:"compact-messages",checked:a.ui.compactMessages,onCheckedChange:g=>l(v=>({...v,ui:{...v.ui,compactMessages:g}}))})]})]})]})]}),c.jsxs(co,{children:[c.jsx(uo,{className:"pb-3",children:c.jsxs(fo,{className:"text-lg flex items-center gap-2",children:[c.jsx(ae.MessageCircle,{className:"h-5 w-5"}),"Behavior Settings"]})}),c.jsxs(is,{className:"space-y-4",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx(Jt,{htmlFor:"auto-save",children:"Auto-save Conversations"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically save messages to threads"})]}),c.jsx(Xn,{id:"auto-save",checked:a.behavior.autoSave,onCheckedChange:g=>l(v=>({...v,behavior:{...v.behavior,autoSave:g}}))})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx(Jt,{htmlFor:"enable-streaming",children:"Enable Streaming"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Stream responses in real-time"})]}),c.jsx(Xn,{id:"enable-streaming",checked:a.behavior.enableStreaming,onCheckedChange:g=>l(v=>({...v,behavior:{...v.behavior,enableStreaming:g}}))})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{children:[c.jsx(Jt,{htmlFor:"typing-indicator",children:"Typing Indicator"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Show typing indicator during responses"})]}),c.jsx(Xn,{id:"typing-indicator",checked:a.behavior.showTypingIndicator,onCheckedChange:g=>l(v=>({...v,behavior:{...v.behavior,showTypingIndicator:g}}))})]})]})]})]}),c.jsxs("div",{className:"flex items-center justify-between pt-6 border-t",children:[c.jsxs(Je,{variant:"outline",onClick:p,children:[c.jsx(ae.RotateCcw,{className:"h-4 w-4 mr-2"}),"Reset"]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx(Je,{variant:"outline",onClick:b,children:"Cancel"}),c.jsxs(Je,{onClick:h,disabled:!u,children:[c.jsx(ae.Save,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})]})}function yk({layout:e="sidebar",layoutSize:t="desktop",showThreads:n=!0,className:r="",customStyles:o={},...s}){const i=u=>{const d="h-full";switch(u){case"phone":return`${d} max-w-none`;case"tablet":return`${d} max-w-4xl mx-auto`;case"half-screen":return`${d} max-w-2xl`;case"desktop":default:return`${d} max-w-7xl mx-auto`}},a=u=>({"--chat-sidebar-width":u==="phone"?"100%":u==="tablet"?"280px":u==="half-screen"?"240px":"320px","--chat-message-max-width":u==="phone"?"95%":u==="tablet"?"90%":u==="half-screen"?"85%":"80%","--chat-input-height":u==="phone"?"120px":"100px"}),l=y.useCallback(u=>{var d;(d=s.onThreadChange)==null||d.call(s,u)},[s]);return e==="fullscreen"?c.jsx(Wo,{...s,onThreadChange:l,children:c.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:c.jsx(Gs,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?c.jsx(Wo,{...s,onThreadChange:l,children:c.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:c.jsxs("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:[n&&c.jsx("div",{className:`w-80 border-r flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:c.jsx(al,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),c.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:c.jsx(Gs,{onError:s.onError,enableFileUpload:!0})})]})})}):c.jsx(Wo,{...s,onThreadChange:l,children:c.jsxs("div",{className:`${i(t)} flex overflow-hidden ${r} ${o.container||""}`,style:a(t),children:[n&&c.jsx("div",{className:`w-80 border-r bg-gray-50 flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:c.jsx(al,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),c.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:c.jsx(Gs,{onError:s.onError,enableFileUpload:!0})})]})})}je.ChatApi=fc,je.ChatInterface=Gs,je.ChatProviders=Wo,je.ChatSettings=wk,je.MarkdownContent=da,je.MessageComponent=nf,je.MessageList=_a,je.ThreadManager=al,je.applySettings=IC,je.chatApiClient=Bn,je.default=yk,je.del=dc,je.get=nn,je.getChatToken=lc,je.getCurrentSettings=TC,je.getDefaultApiConfig=lp,je.getDefaultChatSettings=cp,je.onChatTokenChanged=cc,je.post=Si,je.put=uc,je.setChatToken=yi,je.useApi=Ci,je.useChatStream=Nc,je.useMessagesReducer=bc,je.useStream=Mc,je.useThreadState=Uo,je.useThreads=Ho,Object.defineProperties(je,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
@@ -1,23 +1,12 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
export type HistoryPendingInterrupt =
|
|
3
|
-
id: string;
|
|
4
|
-
value: unknown;
|
|
5
|
-
} | null;
|
|
6
|
-
export type HydratedCheckpointSnapshot = {
|
|
7
|
-
messages: ChatMessage[];
|
|
8
|
-
checkpointId: string | null;
|
|
9
|
-
checkpointNs: string | null;
|
|
10
|
-
nextCursor: string | null;
|
|
11
|
-
nextCursorNs: string | null;
|
|
12
|
-
interrupt: HistoryPendingInterrupt;
|
|
13
|
-
};
|
|
1
|
+
import type { CheckpointSummary, HistoryPayload, HydratedCheckpointSnapshot, MessagesPayload, PendingInterrupt } from "@/types/api";
|
|
2
|
+
export type HistoryPendingInterrupt = PendingInterrupt;
|
|
14
3
|
export type HistoryHydrationResult = {
|
|
15
4
|
payload: MessagesPayload & {
|
|
16
5
|
nextCursorNs?: string | null;
|
|
17
|
-
pendingInterrupt?:
|
|
6
|
+
pendingInterrupt?: PendingInterrupt;
|
|
18
7
|
};
|
|
19
8
|
checkpoints: CheckpointSummary[];
|
|
20
|
-
interrupt:
|
|
9
|
+
interrupt: PendingInterrupt;
|
|
21
10
|
snapshots: Record<string, HydratedCheckpointSnapshot>;
|
|
22
11
|
};
|
|
23
12
|
export declare function buildSnapshotKey(checkpointId: string | null | undefined, checkpointNs: string | null | undefined): string;
|
package/dist/types/api.d.ts
CHANGED
|
@@ -71,6 +71,18 @@ export interface CheckpointSnapshot {
|
|
|
71
71
|
parentConfig?: Record<string, unknown> | null;
|
|
72
72
|
tasks?: PregelTask[] | null;
|
|
73
73
|
}
|
|
74
|
+
export type PendingInterrupt = {
|
|
75
|
+
id: string;
|
|
76
|
+
value: unknown;
|
|
77
|
+
} | null;
|
|
78
|
+
export interface HydratedCheckpointSnapshot {
|
|
79
|
+
checkpointId: string | null;
|
|
80
|
+
checkpointNs: string | null;
|
|
81
|
+
messages: ChatMessage[];
|
|
82
|
+
nextCursor: string | null;
|
|
83
|
+
nextCursorNs: string | null;
|
|
84
|
+
interrupt: PendingInterrupt;
|
|
85
|
+
}
|
|
74
86
|
export interface HistoryPayload {
|
|
75
87
|
version: "chat-history@1";
|
|
76
88
|
threadId: string;
|
|
@@ -84,10 +96,7 @@ export interface MessagesPayload {
|
|
|
84
96
|
hasMore?: boolean;
|
|
85
97
|
nextCursor?: string | null;
|
|
86
98
|
nextCursorNs?: string | null;
|
|
87
|
-
pendingInterrupt?:
|
|
88
|
-
id: string;
|
|
89
|
-
value: any;
|
|
90
|
-
} | null;
|
|
99
|
+
pendingInterrupt?: PendingInterrupt;
|
|
91
100
|
}
|
|
92
101
|
export interface StatePayload {
|
|
93
102
|
threadId: string;
|
|
@@ -300,18 +309,9 @@ export interface ThreadsContextValue {
|
|
|
300
309
|
persistThreadsCache: () => void;
|
|
301
310
|
hydrateFromCache: () => void;
|
|
302
311
|
}
|
|
303
|
-
export interface ThreadSnapshot {
|
|
312
|
+
export interface ThreadSnapshot extends HydratedCheckpointSnapshot {
|
|
304
313
|
threadId: string;
|
|
305
|
-
checkpointId?: string | null;
|
|
306
|
-
checkpointNs?: string | null;
|
|
307
|
-
messages: ChatMessage[];
|
|
308
314
|
hasMore?: boolean;
|
|
309
|
-
nextCursor?: string | null;
|
|
310
|
-
nextCursorNs?: string | null;
|
|
311
|
-
pendingInterrupt?: {
|
|
312
|
-
id: string;
|
|
313
|
-
value: any;
|
|
314
|
-
} | null;
|
|
315
315
|
}
|
|
316
316
|
export interface ThreadStateMetadata {
|
|
317
317
|
branchLabel?: string | null;
|
|
@@ -323,10 +323,7 @@ export interface ThreadStateMetadata {
|
|
|
323
323
|
export interface ThreadStateContextValue {
|
|
324
324
|
threadId: string | null;
|
|
325
325
|
messages: ChatMessage[];
|
|
326
|
-
interrupt:
|
|
327
|
-
id: string;
|
|
328
|
-
value: any;
|
|
329
|
-
} | null;
|
|
326
|
+
interrupt: PendingInterrupt;
|
|
330
327
|
checkpoint: {
|
|
331
328
|
id: string | null;
|
|
332
329
|
namespace: string | null;
|
package/package.json
CHANGED