teodor-new-chat-ui 4.3.320 → 4.3.321

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/index.umd.js CHANGED
@@ -14,28 +14,28 @@
14
14
  *
15
15
  * This source code is licensed under the MIT license found in the
16
16
  * LICENSE file in the root directory of this source tree.
17
- */var Qa;function Zh(){return Qa||(Qa=1,process.env.NODE_ENV!=="production"&&function(){var e=w,t=Symbol.for("react.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),i=Symbol.for("react.provider"),a=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),h=Symbol.for("react.offscreen"),x=Symbol.iterator,m="@@iterator";function v(I){if(I===null||typeof I!="object")return null;var K=x&&I[x]||I[m];return typeof K=="function"?K:null}var g=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function b(I){{for(var K=arguments.length,le=new Array(K>1?K-1:0),Ee=1;Ee<K;Ee++)le[Ee-1]=arguments[Ee];S("error",I,le)}}function S(I,K,le){{var Ee=g.ReactDebugCurrentFrame,rt=Ee.getStackAddendum();rt!==""&&(K+="%s",le=le.concat([rt]));var lt=le.map(function(qe){return String(qe)});lt.unshift("Warning: "+K),Function.prototype.apply.call(console[I],console,lt)}}var k=!1,C=!1,T=!1,E=!1,N=!1,_;_=Symbol.for("react.module.reference");function P(I){return!!(typeof I=="string"||typeof I=="function"||I===r||I===s||N||I===o||I===c||I===d||E||I===h||k||C||T||typeof I=="object"&&I!==null&&(I.$$typeof===p||I.$$typeof===f||I.$$typeof===i||I.$$typeof===a||I.$$typeof===l||I.$$typeof===_||I.getModuleId!==void 0))}function R(I,K,le){var Ee=I.displayName;if(Ee)return Ee;var rt=K.displayName||K.name||"";return rt!==""?le+"("+rt+")":le}function D(I){return I.displayName||"Context"}function F(I){if(I==null)return null;if(typeof I.tag=="number"&&b("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof I=="function")return I.displayName||I.name||null;if(typeof I=="string")return I;switch(I){case r:return"Fragment";case n:return"Portal";case s:return"Profiler";case o:return"StrictMode";case c:return"Suspense";case d:return"SuspenseList"}if(typeof I=="object")switch(I.$$typeof){case a:var K=I;return D(K)+".Consumer";case i:var le=I;return D(le._context)+".Provider";case l:return R(I,I.render,"ForwardRef");case f:var Ee=I.displayName||null;return Ee!==null?Ee:F(I.type)||"Memo";case p:{var rt=I,lt=rt._payload,qe=rt._init;try{return F(qe(lt))}catch{return null}}}return null}var A=Object.assign,z=0,j,J,B,O,W,X,he;function ae(){}ae.__reactDisabledLog=!0;function Re(){{if(z===0){j=console.log,J=console.info,B=console.warn,O=console.error,W=console.group,X=console.groupCollapsed,he=console.groupEnd;var I={configurable:!0,enumerable:!0,value:ae,writable:!0};Object.defineProperties(console,{info:I,log:I,warn:I,error:I,group:I,groupCollapsed:I,groupEnd:I})}z++}}function G(){{if(z--,z===0){var I={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:A({},I,{value:j}),info:A({},I,{value:J}),warn:A({},I,{value:B}),error:A({},I,{value:O}),group:A({},I,{value:W}),groupCollapsed:A({},I,{value:X}),groupEnd:A({},I,{value:he})})}z<0&&b("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var U=g.ReactCurrentDispatcher,q;function $(I,K,le){{if(q===void 0)try{throw Error()}catch(rt){var Ee=rt.stack.trim().match(/\n( *(at )?)/);q=Ee&&Ee[1]||""}return`
17
+ */var Qa;function Zh(){return Qa||(Qa=1,process.env.NODE_ENV!=="production"&&function(){var e=w,t=Symbol.for("react.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),i=Symbol.for("react.provider"),a=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),h=Symbol.for("react.offscreen"),x=Symbol.iterator,m="@@iterator";function v(I){if(I===null||typeof I!="object")return null;var K=x&&I[x]||I[m];return typeof K=="function"?K:null}var g=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function b(I){{for(var K=arguments.length,le=new Array(K>1?K-1:0),Ee=1;Ee<K;Ee++)le[Ee-1]=arguments[Ee];S("error",I,le)}}function S(I,K,le){{var Ee=g.ReactDebugCurrentFrame,rt=Ee.getStackAddendum();rt!==""&&(K+="%s",le=le.concat([rt]));var lt=le.map(function(qe){return String(qe)});lt.unshift("Warning: "+K),Function.prototype.apply.call(console[I],console,lt)}}var k=!1,C=!1,T=!1,E=!1,N=!1,_;_=Symbol.for("react.module.reference");function P(I){return!!(typeof I=="string"||typeof I=="function"||I===r||I===s||N||I===o||I===c||I===d||E||I===h||k||C||T||typeof I=="object"&&I!==null&&(I.$$typeof===p||I.$$typeof===f||I.$$typeof===i||I.$$typeof===a||I.$$typeof===l||I.$$typeof===_||I.getModuleId!==void 0))}function R(I,K,le){var Ee=I.displayName;if(Ee)return Ee;var rt=K.displayName||K.name||"";return rt!==""?le+"("+rt+")":le}function D(I){return I.displayName||"Context"}function F(I){if(I==null)return null;if(typeof I.tag=="number"&&b("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof I=="function")return I.displayName||I.name||null;if(typeof I=="string")return I;switch(I){case r:return"Fragment";case n:return"Portal";case s:return"Profiler";case o:return"StrictMode";case c:return"Suspense";case d:return"SuspenseList"}if(typeof I=="object")switch(I.$$typeof){case a:var K=I;return D(K)+".Consumer";case i:var le=I;return D(le._context)+".Provider";case l:return R(I,I.render,"ForwardRef");case f:var Ee=I.displayName||null;return Ee!==null?Ee:F(I.type)||"Memo";case p:{var rt=I,lt=rt._payload,qe=rt._init;try{return F(qe(lt))}catch{return null}}}return null}var A=Object.assign,z=0,j,J,B,O,W,X,fe;function ae(){}ae.__reactDisabledLog=!0;function Re(){{if(z===0){j=console.log,J=console.info,B=console.warn,O=console.error,W=console.group,X=console.groupCollapsed,fe=console.groupEnd;var I={configurable:!0,enumerable:!0,value:ae,writable:!0};Object.defineProperties(console,{info:I,log:I,warn:I,error:I,group:I,groupCollapsed:I,groupEnd:I})}z++}}function G(){{if(z--,z===0){var I={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:A({},I,{value:j}),info:A({},I,{value:J}),warn:A({},I,{value:B}),error:A({},I,{value:O}),group:A({},I,{value:W}),groupCollapsed:A({},I,{value:X}),groupEnd:A({},I,{value:fe})})}z<0&&b("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var U=g.ReactCurrentDispatcher,q;function $(I,K,le){{if(q===void 0)try{throw Error()}catch(rt){var Ee=rt.stack.trim().match(/\n( *(at )?)/);q=Ee&&Ee[1]||""}return`
18
18
  `+q+I}}var V=!1,re;{var oe=typeof WeakMap=="function"?WeakMap:Map;re=new oe}function se(I,K){if(!I||V)return"";{var le=re.get(I);if(le!==void 0)return le}var Ee;V=!0;var rt=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var lt;lt=U.current,U.current=null,Re();try{if(K){var qe=function(){throw Error()};if(Object.defineProperty(qe.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(qe,[])}catch(Z){Ee=Z}Reflect.construct(I,[],qe)}else{try{qe.call()}catch(Z){Ee=Z}I.call(qe.prototype)}}else{try{throw Error()}catch(Z){Ee=Z}I()}}catch(Z){if(Z&&Ee&&typeof Z.stack=="string"){for(var We=Z.stack.split(`
19
19
  `),Rt=Ee.stack.split(`
20
20
  `),yt=We.length-1,St=Rt.length-1;yt>=1&&St>=0&&We[yt]!==Rt[St];)St--;for(;yt>=1&&St>=0;yt--,St--)if(We[yt]!==Rt[St]){if(yt!==1||St!==1)do if(yt--,St--,St<0||We[yt]!==Rt[St]){var Vt=`
21
- `+We[yt].replace(" at new "," at ");return I.displayName&&Vt.includes("<anonymous>")&&(Vt=Vt.replace("<anonymous>",I.displayName)),typeof I=="function"&&re.set(I,Vt),Vt}while(yt>=1&&St>=0);break}}}finally{V=!1,U.current=lt,G(),Error.prepareStackTrace=rt}var Kn=I?I.displayName||I.name:"",_n=Kn?$(Kn):"";return typeof I=="function"&&re.set(I,_n),_n}function Se(I,K,le){return se(I,!1)}function Qe(I){var K=I.prototype;return!!(K&&K.isReactComponent)}function Fe(I,K,le){if(I==null)return"";if(typeof I=="function")return se(I,Qe(I));if(typeof I=="string")return $(I);switch(I){case c:return $("Suspense");case d:return $("SuspenseList")}if(typeof I=="object")switch(I.$$typeof){case l:return Se(I.render);case f:return Fe(I.type,K,le);case p:{var Ee=I,rt=Ee._payload,lt=Ee._init;try{return Fe(lt(rt),K,le)}catch{}}}return""}var Xe=Object.prototype.hasOwnProperty,nt={},fe=g.ReactDebugCurrentFrame;function ge(I){if(I){var K=I._owner,le=Fe(I.type,I._source,K?K.type:null);fe.setExtraStackFrame(le)}else fe.setExtraStackFrame(null)}function Le(I,K,le,Ee,rt){{var lt=Function.call.bind(Xe);for(var qe in I)if(lt(I,qe)){var We=void 0;try{if(typeof I[qe]!="function"){var Rt=Error((Ee||"React class")+": "+le+" type `"+qe+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof I[qe]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw Rt.name="Invariant Violation",Rt}We=I[qe](K,qe,Ee,le,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(yt){We=yt}We&&!(We instanceof Error)&&(ge(rt),b("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",Ee||"React class",le,qe,typeof We),ge(null)),We instanceof Error&&!(We.message in nt)&&(nt[We.message]=!0,ge(rt),b("Failed %s type: %s",le,We.message),ge(null))}}}var Be=Array.isArray;function Ve(I){return Be(I)}function Je(I){{var K=typeof Symbol=="function"&&Symbol.toStringTag,le=K&&I[Symbol.toStringTag]||I.constructor.name||"Object";return le}}function ze(I){try{return Ze(I),!1}catch{return!0}}function Ze(I){return""+I}function Et(I){if(ze(I))return b("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Je(I)),Ze(I)}var ft=g.ReactCurrentOwner,Ue={key:!0,ref:!0,__self:!0,__source:!0},xt,vt;function It(I){if(Xe.call(I,"ref")){var K=Object.getOwnPropertyDescriptor(I,"ref").get;if(K&&K.isReactWarning)return!1}return I.ref!==void 0}function bt(I){if(Xe.call(I,"key")){var K=Object.getOwnPropertyDescriptor(I,"key").get;if(K&&K.isReactWarning)return!1}return I.key!==void 0}function wt(I,K){typeof I.ref=="string"&&ft.current}function He(I,K){{var le=function(){xt||(xt=!0,b("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",K))};le.isReactWarning=!0,Object.defineProperty(I,"key",{get:le,configurable:!0})}}function zt(I,K){{var le=function(){vt||(vt=!0,b("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",K))};le.isReactWarning=!0,Object.defineProperty(I,"ref",{get:le,configurable:!0})}}var Pe=function(I,K,le,Ee,rt,lt,qe){var We={$$typeof:t,type:I,key:K,ref:le,props:qe,_owner:lt};return We._store={},Object.defineProperty(We._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(We,"_self",{configurable:!1,enumerable:!1,writable:!1,value:Ee}),Object.defineProperty(We,"_source",{configurable:!1,enumerable:!1,writable:!1,value:rt}),Object.freeze&&(Object.freeze(We.props),Object.freeze(We)),We};function _e(I,K,le,Ee,rt){{var lt,qe={},We=null,Rt=null;le!==void 0&&(Et(le),We=""+le),bt(K)&&(Et(K.key),We=""+K.key),It(K)&&(Rt=K.ref,wt(K,rt));for(lt in K)Xe.call(K,lt)&&!Ue.hasOwnProperty(lt)&&(qe[lt]=K[lt]);if(I&&I.defaultProps){var yt=I.defaultProps;for(lt in yt)qe[lt]===void 0&&(qe[lt]=yt[lt])}if(We||Rt){var St=typeof I=="function"?I.displayName||I.name||"Unknown":I;We&&He(qe,St),Rt&&zt(qe,St)}return Pe(I,We,Rt,rt,Ee,ft.current,qe)}}var at=g.ReactCurrentOwner,Y=g.ReactDebugCurrentFrame;function ee(I){if(I){var K=I._owner,le=Fe(I.type,I._source,K?K.type:null);Y.setExtraStackFrame(le)}else Y.setExtraStackFrame(null)}var Ce;Ce=!1;function Te(I){return typeof I=="object"&&I!==null&&I.$$typeof===t}function L(){{if(at.current){var I=F(at.current.type);if(I)return`
21
+ `+We[yt].replace(" at new "," at ");return I.displayName&&Vt.includes("<anonymous>")&&(Vt=Vt.replace("<anonymous>",I.displayName)),typeof I=="function"&&re.set(I,Vt),Vt}while(yt>=1&&St>=0);break}}}finally{V=!1,U.current=lt,G(),Error.prepareStackTrace=rt}var Kn=I?I.displayName||I.name:"",_n=Kn?$(Kn):"";return typeof I=="function"&&re.set(I,_n),_n}function Se(I,K,le){return se(I,!1)}function Qe(I){var K=I.prototype;return!!(K&&K.isReactComponent)}function Fe(I,K,le){if(I==null)return"";if(typeof I=="function")return se(I,Qe(I));if(typeof I=="string")return $(I);switch(I){case c:return $("Suspense");case d:return $("SuspenseList")}if(typeof I=="object")switch(I.$$typeof){case l:return Se(I.render);case f:return Fe(I.type,K,le);case p:{var Ee=I,rt=Ee._payload,lt=Ee._init;try{return Fe(lt(rt),K,le)}catch{}}}return""}var Xe=Object.prototype.hasOwnProperty,nt={},de=g.ReactDebugCurrentFrame;function me(I){if(I){var K=I._owner,le=Fe(I.type,I._source,K?K.type:null);de.setExtraStackFrame(le)}else de.setExtraStackFrame(null)}function Le(I,K,le,Ee,rt){{var lt=Function.call.bind(Xe);for(var qe in I)if(lt(I,qe)){var We=void 0;try{if(typeof I[qe]!="function"){var Rt=Error((Ee||"React class")+": "+le+" type `"+qe+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof I[qe]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw Rt.name="Invariant Violation",Rt}We=I[qe](K,qe,Ee,le,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(yt){We=yt}We&&!(We instanceof Error)&&(me(rt),b("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",Ee||"React class",le,qe,typeof We),me(null)),We instanceof Error&&!(We.message in nt)&&(nt[We.message]=!0,me(rt),b("Failed %s type: %s",le,We.message),me(null))}}}var Be=Array.isArray;function Ve(I){return Be(I)}function Je(I){{var K=typeof Symbol=="function"&&Symbol.toStringTag,le=K&&I[Symbol.toStringTag]||I.constructor.name||"Object";return le}}function ze(I){try{return Ze(I),!1}catch{return!0}}function Ze(I){return""+I}function Et(I){if(ze(I))return b("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Je(I)),Ze(I)}var ft=g.ReactCurrentOwner,Ue={key:!0,ref:!0,__self:!0,__source:!0},xt,vt;function It(I){if(Xe.call(I,"ref")){var K=Object.getOwnPropertyDescriptor(I,"ref").get;if(K&&K.isReactWarning)return!1}return I.ref!==void 0}function bt(I){if(Xe.call(I,"key")){var K=Object.getOwnPropertyDescriptor(I,"key").get;if(K&&K.isReactWarning)return!1}return I.key!==void 0}function wt(I,K){typeof I.ref=="string"&&ft.current}function He(I,K){{var le=function(){xt||(xt=!0,b("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",K))};le.isReactWarning=!0,Object.defineProperty(I,"key",{get:le,configurable:!0})}}function zt(I,K){{var le=function(){vt||(vt=!0,b("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",K))};le.isReactWarning=!0,Object.defineProperty(I,"ref",{get:le,configurable:!0})}}var Pe=function(I,K,le,Ee,rt,lt,qe){var We={$$typeof:t,type:I,key:K,ref:le,props:qe,_owner:lt};return We._store={},Object.defineProperty(We._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(We,"_self",{configurable:!1,enumerable:!1,writable:!1,value:Ee}),Object.defineProperty(We,"_source",{configurable:!1,enumerable:!1,writable:!1,value:rt}),Object.freeze&&(Object.freeze(We.props),Object.freeze(We)),We};function _e(I,K,le,Ee,rt){{var lt,qe={},We=null,Rt=null;le!==void 0&&(Et(le),We=""+le),bt(K)&&(Et(K.key),We=""+K.key),It(K)&&(Rt=K.ref,wt(K,rt));for(lt in K)Xe.call(K,lt)&&!Ue.hasOwnProperty(lt)&&(qe[lt]=K[lt]);if(I&&I.defaultProps){var yt=I.defaultProps;for(lt in yt)qe[lt]===void 0&&(qe[lt]=yt[lt])}if(We||Rt){var St=typeof I=="function"?I.displayName||I.name||"Unknown":I;We&&He(qe,St),Rt&&zt(qe,St)}return Pe(I,We,Rt,rt,Ee,ft.current,qe)}}var at=g.ReactCurrentOwner,Y=g.ReactDebugCurrentFrame;function ee(I){if(I){var K=I._owner,le=Fe(I.type,I._source,K?K.type:null);Y.setExtraStackFrame(le)}else Y.setExtraStackFrame(null)}var Ce;Ce=!1;function Te(I){return typeof I=="object"&&I!==null&&I.$$typeof===t}function L(){{if(at.current){var I=F(at.current.type);if(I)return`
22
22
 
23
- Check the render method of \``+I+"`."}return""}}function ne(I){return""}var pe={};function ce(I){{var K=L();if(!K){var le=typeof I=="string"?I:I.displayName||I.name;le&&(K=`
23
+ Check the render method of \``+I+"`."}return""}}function ne(I){return""}var ge={};function pe(I){{var K=L();if(!K){var le=typeof I=="string"?I:I.displayName||I.name;le&&(K=`
24
24
 
25
- Check the top-level render call using <`+le+">.")}return K}}function et(I,K){{if(!I._store||I._store.validated||I.key!=null)return;I._store.validated=!0;var le=ce(K);if(pe[le])return;pe[le]=!0;var Ee="";I&&I._owner&&I._owner!==at.current&&(Ee=" It was passed a child from "+F(I._owner.type)+"."),ee(I),b('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',le,Ee),ee(null)}}function ke(I,K){{if(typeof I!="object")return;if(Ve(I))for(var le=0;le<I.length;le++){var Ee=I[le];Te(Ee)&&et(Ee,K)}else if(Te(I))I._store&&(I._store.validated=!0);else if(I){var rt=v(I);if(typeof rt=="function"&&rt!==I.entries)for(var lt=rt.call(I),qe;!(qe=lt.next()).done;)Te(qe.value)&&et(qe.value,K)}}}function ct(I){{var K=I.type;if(K==null||typeof K=="string")return;var le;if(typeof K=="function")le=K.propTypes;else if(typeof K=="object"&&(K.$$typeof===l||K.$$typeof===f))le=K.propTypes;else return;if(le){var Ee=F(K);Le(le,I.props,"prop",Ee,I)}else if(K.PropTypes!==void 0&&!Ce){Ce=!0;var rt=F(K);b("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",rt||"Unknown")}typeof K.getDefaultProps=="function"&&!K.getDefaultProps.isReactClassApproved&&b("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Wn(I){{for(var K=Object.keys(I.props),le=0;le<K.length;le++){var Ee=K[le];if(Ee!=="children"&&Ee!=="key"){ee(I),b("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",Ee),ee(null);break}}I.ref!==null&&(ee(I),b("Invalid attribute `ref` supplied to `React.Fragment`."),ee(null))}}var ur={};function Vn(I,K,le,Ee,rt,lt){{var qe=P(I);if(!qe){var We="";(I===void 0||typeof I=="object"&&I!==null&&Object.keys(I).length===0)&&(We+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var Rt=ne();Rt?We+=Rt:We+=L();var yt;I===null?yt="null":Ve(I)?yt="array":I!==void 0&&I.$$typeof===t?(yt="<"+(F(I.type)||"Unknown")+" />",We=" Did you accidentally export a JSX literal instead of a component?"):yt=typeof I,b("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",yt,We)}var St=_e(I,K,le,rt,lt);if(St==null)return St;if(qe){var Vt=K.children;if(Vt!==void 0)if(Ee)if(Ve(Vt)){for(var Kn=0;Kn<Vt.length;Kn++)ke(Vt[Kn],I);Object.freeze&&Object.freeze(Vt)}else b("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else ke(Vt,I)}if(Xe.call(K,"key")){var _n=F(I),Z=Object.keys(K).filter(function(Ke){return Ke!=="key"}),xe=Z.length>0?"{key: someKey, "+Z.join(": ..., ")+": ...}":"{key: someKey}";if(!ur[_n+xe]){var ye=Z.length>0?"{"+Z.join(": ..., ")+": ...}":"{}";b(`A props object containing a "key" prop is being spread into JSX:
25
+ Check the top-level render call using <`+le+">.")}return K}}function et(I,K){{if(!I._store||I._store.validated||I.key!=null)return;I._store.validated=!0;var le=pe(K);if(ge[le])return;ge[le]=!0;var Ee="";I&&I._owner&&I._owner!==at.current&&(Ee=" It was passed a child from "+F(I._owner.type)+"."),ee(I),b('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',le,Ee),ee(null)}}function ke(I,K){{if(typeof I!="object")return;if(Ve(I))for(var le=0;le<I.length;le++){var Ee=I[le];Te(Ee)&&et(Ee,K)}else if(Te(I))I._store&&(I._store.validated=!0);else if(I){var rt=v(I);if(typeof rt=="function"&&rt!==I.entries)for(var lt=rt.call(I),qe;!(qe=lt.next()).done;)Te(qe.value)&&et(qe.value,K)}}}function ct(I){{var K=I.type;if(K==null||typeof K=="string")return;var le;if(typeof K=="function")le=K.propTypes;else if(typeof K=="object"&&(K.$$typeof===l||K.$$typeof===f))le=K.propTypes;else return;if(le){var Ee=F(K);Le(le,I.props,"prop",Ee,I)}else if(K.PropTypes!==void 0&&!Ce){Ce=!0;var rt=F(K);b("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",rt||"Unknown")}typeof K.getDefaultProps=="function"&&!K.getDefaultProps.isReactClassApproved&&b("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Wn(I){{for(var K=Object.keys(I.props),le=0;le<K.length;le++){var Ee=K[le];if(Ee!=="children"&&Ee!=="key"){ee(I),b("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",Ee),ee(null);break}}I.ref!==null&&(ee(I),b("Invalid attribute `ref` supplied to `React.Fragment`."),ee(null))}}var ur={};function Vn(I,K,le,Ee,rt,lt){{var qe=P(I);if(!qe){var We="";(I===void 0||typeof I=="object"&&I!==null&&Object.keys(I).length===0)&&(We+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var Rt=ne();Rt?We+=Rt:We+=L();var yt;I===null?yt="null":Ve(I)?yt="array":I!==void 0&&I.$$typeof===t?(yt="<"+(F(I.type)||"Unknown")+" />",We=" Did you accidentally export a JSX literal instead of a component?"):yt=typeof I,b("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",yt,We)}var St=_e(I,K,le,rt,lt);if(St==null)return St;if(qe){var Vt=K.children;if(Vt!==void 0)if(Ee)if(Ve(Vt)){for(var Kn=0;Kn<Vt.length;Kn++)ke(Vt[Kn],I);Object.freeze&&Object.freeze(Vt)}else b("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else ke(Vt,I)}if(Xe.call(K,"key")){var _n=F(I),Z=Object.keys(K).filter(function(Ke){return Ke!=="key"}),xe=Z.length>0?"{key: someKey, "+Z.join(": ..., ")+": ...}":"{key: someKey}";if(!ur[_n+xe]){var ye=Z.length>0?"{"+Z.join(": ..., ")+": ...}":"{}";b(`A props object containing a "key" prop is being spread into JSX:
26
26
  let props = %s;
27
27
  <%s {...props} />
28
28
  React keys must be passed directly to JSX without using spread:
29
29
  let props = %s;
30
30
  <%s key={someKey} {...props} />`,xe,_n,ye,_n),ur[_n+xe]=!0}}return I===r?Wn(St):ct(St),St}}function Ga(I,K,le){return Vn(I,K,le,!0)}function Gs(I,K,le){return Vn(I,K,le,!1)}var Ya=Gs,Xa=Ga;Pr.Fragment=r,Pr.jsx=Ya,Pr.jsxs=Xa}()),Pr}process.env.NODE_ENV==="production"?Js.exports=Jh():Js.exports=Zh();var u=Js.exports;function el(e,t){return function(){return e.apply(t,arguments)}}const{toString:Qh}=Object.prototype,{getPrototypeOf:Zs}=Object,{iterator:xo,toStringTag:tl}=Symbol,yo=(e=>t=>{const n=Qh.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),an=e=>(e=e.toLowerCase(),t=>yo(t)===e),vo=e=>t=>typeof t===e,{isArray:dr}=Array,fr=vo("undefined");function Or(e){return e!==null&&!fr(e)&&e.constructor!==null&&!fr(e.constructor)&&Ut(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const nl=an("ArrayBuffer");function em(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&nl(e.buffer),t}const tm=vo("string"),Ut=vo("function"),rl=vo("number"),Mr=e=>e!==null&&typeof e=="object",nm=e=>e===!0||e===!1,bo=e=>{if(yo(e)!=="object")return!1;const t=Zs(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(tl in e)&&!(xo in e)},rm=e=>{if(!Mr(e)||Or(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},om=an("Date"),sm=an("File"),im=an("Blob"),am=an("FileList"),lm=e=>Mr(e)&&Ut(e.pipe),cm=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Ut(e.append)&&((t=yo(e))==="formdata"||t==="object"&&Ut(e.toString)&&e.toString()==="[object FormData]"))},um=an("URLSearchParams"),[dm,fm,pm,hm]=["ReadableStream","Request","Response","Headers"].map(an),mm=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Dr(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),dr(e))for(r=0,o=e.length;r<o;r++)t.call(null,e[r],r,e);else{if(Or(e))return;const s=n?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let a;for(r=0;r<i;r++)a=s[r],t.call(null,e[a],a,e)}}function ol(e,t){if(Or(e))return null;t=t.toLowerCase();const n=Object.keys(e);let r=n.length,o;for(;r-- >0;)if(o=n[r],t===o.toLowerCase())return o;return null}const Gn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,sl=e=>!fr(e)&&e!==Gn;function Qs(){const{caseless:e,skipUndefined:t}=sl(this)&&this||{},n={},r=(o,s)=>{const i=e&&ol(n,s)||s;bo(n[i])&&bo(o)?n[i]=Qs(n[i],o):bo(o)?n[i]=Qs({},o):dr(o)?n[i]=o.slice():(!t||!fr(o))&&(n[i]=o)};for(let o=0,s=arguments.length;o<s;o++)arguments[o]&&Dr(arguments[o],r);return n}const gm=(e,t,n,{allOwnKeys:r}={})=>(Dr(t,(o,s)=>{n&&Ut(o)?e[s]=el(o,n):e[s]=o},{allOwnKeys:r}),e),xm=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),ym=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},vm=(e,t,n,r)=>{let o,s,i;const a={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),s=o.length;s-- >0;)i=o[s],(!r||r(i,e,t))&&!a[i]&&(t[i]=e[i],a[i]=!0);e=n!==!1&&Zs(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},bm=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},wm=e=>{if(!e)return null;if(dr(e))return e;let t=e.length;if(!rl(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},Sm=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Zs(Uint8Array)),Cm=(e,t)=>{const r=(e&&e[xo]).call(e);let o;for(;(o=r.next())&&!o.done;){const s=o.value;t.call(e,s[0],s[1])}},Tm=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},km=an("HTMLFormElement"),Em=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),il=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),Im=an("RegExp"),al=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Dr(n,(o,s)=>{let i;(i=t(o,s,e))!==!1&&(r[s]=i||o)}),Object.defineProperties(e,r)},Nm=e=>{al(e,(t,n)=>{if(Ut(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Ut(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},Am=(e,t)=>{const n={},r=o=>{o.forEach(s=>{n[s]=!0})};return dr(e)?r(e):r(String(e).split(t)),n},_m=()=>{},jm=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function Rm(e){return!!(e&&Ut(e.append)&&e[tl]==="FormData"&&e[xo])}const Pm=e=>{const t=new Array(10),n=(r,o)=>{if(Mr(r)){if(t.indexOf(r)>=0)return;if(Or(r))return r;if(!("toJSON"in r)){t[o]=r;const s=dr(r)?[]:{};return Dr(r,(i,a)=>{const l=n(i,o+1);!fr(l)&&(s[a]=l)}),t[o]=void 0,s}}return r};return n(e,0)},Om=an("AsyncFunction"),Mm=e=>e&&(Mr(e)||Ut(e))&&Ut(e.then)&&Ut(e.catch),ll=((e,t)=>e?setImmediate:t?((n,r)=>(Gn.addEventListener("message",({source:o,data:s})=>{o===Gn&&s===n&&r.length&&r.shift()()},!1),o=>{r.push(o),Gn.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",Ut(Gn.postMessage)),Dm=typeof queueMicrotask<"u"?queueMicrotask.bind(Gn):typeof process<"u"&&process.nextTick||ll,M={isArray:dr,isArrayBuffer:nl,isBuffer:Or,isFormData:cm,isArrayBufferView:em,isString:tm,isNumber:rl,isBoolean:nm,isObject:Mr,isPlainObject:bo,isEmptyObject:rm,isReadableStream:dm,isRequest:fm,isResponse:pm,isHeaders:hm,isUndefined:fr,isDate:om,isFile:sm,isBlob:im,isRegExp:Im,isFunction:Ut,isStream:lm,isURLSearchParams:um,isTypedArray:Sm,isFileList:am,forEach:Dr,merge:Qs,extend:gm,trim:mm,stripBOM:xm,inherits:ym,toFlatObject:vm,kindOf:yo,kindOfTest:an,endsWith:bm,toArray:wm,forEachEntry:Cm,matchAll:Tm,isHTMLForm:km,hasOwnProperty:il,hasOwnProp:il,reduceDescriptors:al,freezeMethods:Nm,toObjectSet:Am,toCamelCase:Em,noop:_m,toFiniteNumber:jm,findKey:ol,global:Gn,isContextDefined:sl,isSpecCompliantForm:Rm,toJSONObject:Pm,isAsyncFn:Om,isThenable:Mm,setImmediate:ll,asap:Dm,isIterable:e=>e!=null&&Ut(e[xo])};function Me(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o,this.status=o.status?o.status:null)}M.inherits(Me,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:M.toJSONObject(this.config),code:this.code,status:this.status}}});const cl=Me.prototype,ul={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{ul[e]={value:e}}),Object.defineProperties(Me,ul),Object.defineProperty(cl,"isAxiosError",{value:!0}),Me.from=(e,t,n,r,o,s)=>{const i=Object.create(cl);M.toFlatObject(e,i,function(d){return d!==Error.prototype},c=>c!=="isAxiosError");const a=e&&e.message?e.message:"Error",l=t==null&&e?e.code:t;return Me.call(i,a,l,n,r,o),e&&i.cause==null&&Object.defineProperty(i,"cause",{value:e,configurable:!0}),i.name=e&&e.name||"Error",s&&Object.assign(i,s),i};const Lm=null;function ei(e){return M.isPlainObject(e)||M.isArray(e)}function dl(e){return M.endsWith(e,"[]")?e.slice(0,-2):e}function fl(e,t,n){return e?e.concat(t).map(function(o,s){return o=dl(o),!n&&s?"["+o+"]":o}).join(n?".":""):t}function $m(e){return M.isArray(e)&&!e.some(ei)}const Fm=M.toFlatObject(M,{},null,function(t){return/^is[A-Z]/.test(t)});function wo(e,t,n){if(!M.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=M.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,v){return!M.isUndefined(v[m])});const r=n.metaTokens,o=n.visitor||d,s=n.dots,i=n.indexes,l=(n.Blob||typeof Blob<"u"&&Blob)&&M.isSpecCompliantForm(t);if(!M.isFunction(o))throw new TypeError("visitor must be a function");function c(x){if(x===null)return"";if(M.isDate(x))return x.toISOString();if(M.isBoolean(x))return x.toString();if(!l&&M.isBlob(x))throw new Me("Blob is not supported. Use a Buffer instead.");return M.isArrayBuffer(x)||M.isTypedArray(x)?l&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function d(x,m,v){let g=x;if(x&&!v&&typeof x=="object"){if(M.endsWith(m,"{}"))m=r?m:m.slice(0,-2),x=JSON.stringify(x);else if(M.isArray(x)&&$m(x)||(M.isFileList(x)||M.endsWith(m,"[]"))&&(g=M.toArray(x)))return m=dl(m),g.forEach(function(S,k){!(M.isUndefined(S)||S===null)&&t.append(i===!0?fl([m],k,s):i===null?m:m+"[]",c(S))}),!1}return ei(x)?!0:(t.append(fl(v,m,s),c(x)),!1)}const f=[],p=Object.assign(Fm,{defaultVisitor:d,convertValue:c,isVisitable:ei});function h(x,m){if(!M.isUndefined(x)){if(f.indexOf(x)!==-1)throw Error("Circular reference detected in "+m.join("."));f.push(x),M.forEach(x,function(g,b){(!(M.isUndefined(g)||g===null)&&o.call(t,g,M.isString(b)?b.trim():b,m,p))===!0&&h(g,m?m.concat(b):[b])}),f.pop()}}if(!M.isObject(e))throw new TypeError("data must be an object");return h(e),t}function pl(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function ti(e,t){this._pairs=[],e&&wo(e,this,t)}const hl=ti.prototype;hl.append=function(t,n){this._pairs.push([t,n])},hl.toString=function(t){const n=t?function(r){return t.call(this,r,pl)}:pl;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function zm(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function ml(e,t,n){if(!t)return e;const r=n&&n.encode||zm;M.isFunction(n)&&(n={serialize:n});const o=n&&n.serialize;let s;if(o?s=o(t,n):s=M.isURLSearchParams(t)?t.toString():new ti(t,n).toString(r),s){const i=e.indexOf("#");i!==-1&&(e=e.slice(0,i)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}class gl{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){M.forEach(this.handlers,function(r){r!==null&&t(r)})}}const xl={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Bm={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:ti,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},ni=typeof window<"u"&&typeof document<"u",ri=typeof navigator=="object"&&navigator||void 0,Um=ni&&(!ri||["ReactNative","NativeScript","NS"].indexOf(ri.product)<0),Hm=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Wm=ni&&window.location.href||"http://localhost",Pt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:ni,hasStandardBrowserEnv:Um,hasStandardBrowserWebWorkerEnv:Hm,navigator:ri,origin:Wm},Symbol.toStringTag,{value:"Module"})),...Bm};function Vm(e,t){return wo(e,new Pt.classes.URLSearchParams,{visitor:function(n,r,o,s){return Pt.isNode&&M.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...t})}function Km(e){return M.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function qm(e){const t={},n=Object.keys(e);let r;const o=n.length;let s;for(r=0;r<o;r++)s=n[r],t[s]=e[s];return t}function yl(e){function t(n,r,o,s){let i=n[s++];if(i==="__proto__")return!0;const a=Number.isFinite(+i),l=s>=n.length;return i=!i&&M.isArray(o)?o.length:i,l?(M.hasOwnProp(o,i)?o[i]=[o[i],r]:o[i]=r,!a):((!o[i]||!M.isObject(o[i]))&&(o[i]=[]),t(n,r,o[i],s)&&M.isArray(o[i])&&(o[i]=qm(o[i])),!a)}if(M.isFormData(e)&&M.isFunction(e.entries)){const n={};return M.forEachEntry(e,(r,o)=>{t(Km(r),o,n,0)}),n}return null}function Gm(e,t,n){if(M.isString(e))try{return(t||JSON.parse)(e),M.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const Lr={transitional:xl,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,s=M.isObject(t);if(s&&M.isHTMLForm(t)&&(t=new FormData(t)),M.isFormData(t))return o?JSON.stringify(yl(t)):t;if(M.isArrayBuffer(t)||M.isBuffer(t)||M.isStream(t)||M.isFile(t)||M.isBlob(t)||M.isReadableStream(t))return t;if(M.isArrayBufferView(t))return t.buffer;if(M.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let a;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return Vm(t,this.formSerializer).toString();if((a=M.isFileList(t))||r.indexOf("multipart/form-data")>-1){const l=this.env&&this.env.FormData;return wo(a?{"files[]":t}:t,l&&new l,this.formSerializer)}}return s||o?(n.setContentType("application/json",!1),Gm(t)):t}],transformResponse:[function(t){const n=this.transitional||Lr.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(M.isResponse(t)||M.isReadableStream(t))return t;if(t&&M.isString(t)&&(r&&!this.responseType||o)){const i=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t,this.parseReviver)}catch(a){if(i)throw a.name==="SyntaxError"?Me.from(a,Me.ERR_BAD_RESPONSE,this,null,this.response):a}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Pt.classes.FormData,Blob:Pt.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};M.forEach(["delete","get","head","post","put","patch"],e=>{Lr.headers[e]={}});const Ym=M.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Xm=e=>{const t={};let n,r,o;return e&&e.split(`
31
31
  `).forEach(function(i){o=i.indexOf(":"),n=i.substring(0,o).trim().toLowerCase(),r=i.substring(o+1).trim(),!(!n||t[n]&&Ym[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},vl=Symbol("internals");function $r(e){return e&&String(e).trim().toLowerCase()}function So(e){return e===!1||e==null?e:M.isArray(e)?e.map(So):String(e)}function Jm(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const Zm=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function oi(e,t,n,r,o){if(M.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!M.isString(t)){if(M.isString(r))return t.indexOf(r)!==-1;if(M.isRegExp(r))return r.test(t)}}function Qm(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function eg(e,t){const n=M.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,s,i){return this[r].call(this,t,o,s,i)},configurable:!0})})}let Ht=class{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function s(a,l,c){const d=$r(l);if(!d)throw new Error("header name must be a non-empty string");const f=M.findKey(o,d);(!f||o[f]===void 0||c===!0||c===void 0&&o[f]!==!1)&&(o[f||l]=So(a))}const i=(a,l)=>M.forEach(a,(c,d)=>s(c,d,l));if(M.isPlainObject(t)||t instanceof this.constructor)i(t,n);else if(M.isString(t)&&(t=t.trim())&&!Zm(t))i(Xm(t),n);else if(M.isObject(t)&&M.isIterable(t)){let a={},l,c;for(const d of t){if(!M.isArray(d))throw TypeError("Object iterator must return a key-value pair");a[c=d[0]]=(l=a[c])?M.isArray(l)?[...l,d[1]]:[l,d[1]]:d[1]}i(a,n)}else t!=null&&s(n,t,r);return this}get(t,n){if(t=$r(t),t){const r=M.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return Jm(o);if(M.isFunction(n))return n.call(this,o,r);if(M.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=$r(t),t){const r=M.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||oi(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function s(i){if(i=$r(i),i){const a=M.findKey(r,i);a&&(!n||oi(r,r[a],a,n))&&(delete r[a],o=!0)}}return M.isArray(t)?t.forEach(s):s(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const s=n[r];(!t||oi(this,this[s],s,t,!0))&&(delete this[s],o=!0)}return o}normalize(t){const n=this,r={};return M.forEach(this,(o,s)=>{const i=M.findKey(r,s);if(i){n[i]=So(o),delete n[s];return}const a=t?Qm(s):String(s).trim();a!==s&&delete n[s],n[a]=So(o),r[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return M.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&M.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
32
- `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[vl]=this[vl]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=$r(i);r[a]||(eg(o,i),r[a]=!0)}return M.isArray(t)?t.forEach(s):s(t),this}};Ht.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),M.reduceDescriptors(Ht.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),M.freezeMethods(Ht);function si(e,t){const n=this||Lr,r=t||n,o=Ht.from(r.headers);let s=r.data;return M.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function bl(e){return!!(e&&e.__CANCEL__)}function pr(e,t,n){Me.call(this,e??"canceled",Me.ERR_CANCELED,t,n),this.name="CanceledError"}M.inherits(pr,Me,{__CANCEL__:!0});function wl(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Me("Request failed with status code "+n.status,[Me.ERR_BAD_REQUEST,Me.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function tg(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function ng(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(l){const c=Date.now(),d=r[s];i||(i=c),n[o]=l,r[o]=c;let f=s,p=0;for(;f!==o;)p+=n[f++],f=f%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-i<t)return;const h=d&&c-d;return h?Math.round(p*1e3/h):void 0}}function rg(e,t){let n=0,r=1e3/t,o,s;const i=(c,d=Date.now())=>{n=d,o=null,s&&(clearTimeout(s),s=null),e(...c)};return[(...c)=>{const d=Date.now(),f=d-n;f>=r?i(c,d):(o=c,s||(s=setTimeout(()=>{s=null,i(o)},r-f)))},()=>o&&i(o)]}const Co=(e,t,n=3)=>{let r=0;const o=ng(50,250);return rg(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,l=i-r,c=o(l),d=i<=a;r=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:l,rate:c||void 0,estimated:c&&a&&d?(a-i)/c:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(f)},n)},Sl=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Cl=e=>(...t)=>M.asap(()=>e(...t)),og=Pt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Pt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Pt.origin),Pt.navigator&&/(msie|trident)/i.test(Pt.navigator.userAgent)):()=>!0,sg=Pt.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];M.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),M.isString(r)&&i.push("path="+r),M.isString(o)&&i.push("domain="+o),s===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function ig(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function ag(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Tl(e,t,n){let r=!ig(t);return e&&(r||n==!1)?ag(e,t):t}const kl=e=>e instanceof Ht?{...e}:e;function Yn(e,t){t=t||{};const n={};function r(c,d,f,p){return M.isPlainObject(c)&&M.isPlainObject(d)?M.merge.call({caseless:p},c,d):M.isPlainObject(d)?M.merge({},d):M.isArray(d)?d.slice():d}function o(c,d,f,p){if(M.isUndefined(d)){if(!M.isUndefined(c))return r(void 0,c,f,p)}else return r(c,d,f,p)}function s(c,d){if(!M.isUndefined(d))return r(void 0,d)}function i(c,d){if(M.isUndefined(d)){if(!M.isUndefined(c))return r(void 0,c)}else return r(void 0,d)}function a(c,d,f){if(f in t)return r(c,d);if(f in e)return r(void 0,c)}const l={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(c,d,f)=>o(kl(c),kl(d),f,!0)};return M.forEach(Object.keys({...e,...t}),function(d){const f=l[d]||o,p=f(e[d],t[d],d);M.isUndefined(p)&&f!==a||(n[d]=p)}),n}const El=e=>{const t=Yn({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=Ht.from(i),t.url=ml(Tl(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),M.isFormData(n)){if(Pt.hasStandardBrowserEnv||Pt.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(M.isFunction(n.getHeaders)){const l=n.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([d,f])=>{c.includes(d.toLowerCase())&&i.set(d,f)})}}if(Pt.hasStandardBrowserEnv&&(r&&M.isFunction(r)&&(r=r(t)),r||r!==!1&&og(t.url))){const l=o&&s&&sg.read(s);l&&i.set(o,l)}return t},lg=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=El(e);let s=o.data;const i=Ht.from(o.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=o,d,f,p,h,x;function m(){h&&h(),x&&x(),o.cancelToken&&o.cancelToken.unsubscribe(d),o.signal&&o.signal.removeEventListener("abort",d)}let v=new XMLHttpRequest;v.open(o.method.toUpperCase(),o.url,!0),v.timeout=o.timeout;function g(){if(!v)return;const S=Ht.from("getAllResponseHeaders"in v&&v.getAllResponseHeaders()),C={data:!a||a==="text"||a==="json"?v.responseText:v.response,status:v.status,statusText:v.statusText,headers:S,config:e,request:v};wl(function(E){n(E),m()},function(E){r(E),m()},C),v=null}"onloadend"in v?v.onloadend=g:v.onreadystatechange=function(){!v||v.readyState!==4||v.status===0&&!(v.responseURL&&v.responseURL.indexOf("file:")===0)||setTimeout(g)},v.onabort=function(){v&&(r(new Me("Request aborted",Me.ECONNABORTED,e,v)),v=null)},v.onerror=function(k){const C=k&&k.message?k.message:"Network Error",T=new Me(C,Me.ERR_NETWORK,e,v);T.event=k||null,r(T),v=null},v.ontimeout=function(){let k=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const C=o.transitional||xl;o.timeoutErrorMessage&&(k=o.timeoutErrorMessage),r(new Me(k,C.clarifyTimeoutError?Me.ETIMEDOUT:Me.ECONNABORTED,e,v)),v=null},s===void 0&&i.setContentType(null),"setRequestHeader"in v&&M.forEach(i.toJSON(),function(k,C){v.setRequestHeader(C,k)}),M.isUndefined(o.withCredentials)||(v.withCredentials=!!o.withCredentials),a&&a!=="json"&&(v.responseType=o.responseType),c&&([p,x]=Co(c,!0),v.addEventListener("progress",p)),l&&v.upload&&([f,h]=Co(l),v.upload.addEventListener("progress",f),v.upload.addEventListener("loadend",h)),(o.cancelToken||o.signal)&&(d=S=>{v&&(r(!S||S.type?new pr(null,e,v):S),v.abort(),v=null)},o.cancelToken&&o.cancelToken.subscribe(d),o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d)));const b=tg(o.url);if(b&&Pt.protocols.indexOf(b)===-1){r(new Me("Unsupported protocol "+b+":",Me.ERR_BAD_REQUEST,e));return}v.send(s||null)})},cg=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o;const s=function(c){if(!o){o=!0,a();const d=c instanceof Error?c:this.reason;r.abort(d instanceof Me?d:new pr(d instanceof Error?d.message:d))}};let i=t&&setTimeout(()=>{i=null,s(new Me(`timeout ${t} of ms exceeded`,Me.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(s):c.removeEventListener("abort",s)}),e=null)};e.forEach(c=>c.addEventListener("abort",s));const{signal:l}=r;return l.unsubscribe=()=>M.asap(a),l}},ug=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,o;for(;r<n;)o=r+t,yield e.slice(r,o),r=o},dg=async function*(e,t){for await(const n of fg(e))yield*ug(n,t)},fg=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},Il=(e,t,n,r)=>{const o=dg(e,t);let s=0,i,a=l=>{i||(i=!0,r&&r(l))};return new ReadableStream({async pull(l){try{const{done:c,value:d}=await o.next();if(c){a(),l.close();return}let f=d.byteLength;if(n){let p=s+=f;n(p)}l.enqueue(new Uint8Array(d))}catch(c){throw a(c),c}},cancel(l){return a(l),o.return()}},{highWaterMark:2})},Nl=64*1024,{isFunction:To}=M,pg=(({Request:e,Response:t})=>({Request:e,Response:t}))(M.global),{ReadableStream:Al,TextEncoder:_l}=M.global,jl=(e,...t)=>{try{return!!e(...t)}catch{return!1}},hg=e=>{e=M.merge.call({skipUndefined:!0},pg,e);const{fetch:t,Request:n,Response:r}=e,o=t?To(t):typeof fetch=="function",s=To(n),i=To(r);if(!o)return!1;const a=o&&To(Al),l=o&&(typeof _l=="function"?(x=>m=>x.encode(m))(new _l):async x=>new Uint8Array(await new n(x).arrayBuffer())),c=s&&a&&jl(()=>{let x=!1;const m=new n(Pt.origin,{body:new Al,method:"POST",get duplex(){return x=!0,"half"}}).headers.has("Content-Type");return x&&!m}),d=i&&a&&jl(()=>M.isReadableStream(new r("").body)),f={stream:d&&(x=>x.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(x=>{!f[x]&&(f[x]=(m,v)=>{let g=m&&m[x];if(g)return g.call(m);throw new Me(`Response type '${x}' is not supported`,Me.ERR_NOT_SUPPORT,v)})});const p=async x=>{if(x==null)return 0;if(M.isBlob(x))return x.size;if(M.isSpecCompliantForm(x))return(await new n(Pt.origin,{method:"POST",body:x}).arrayBuffer()).byteLength;if(M.isArrayBufferView(x)||M.isArrayBuffer(x))return x.byteLength;if(M.isURLSearchParams(x)&&(x=x+""),M.isString(x))return(await l(x)).byteLength},h=async(x,m)=>{const v=M.toFiniteNumber(x.getContentLength());return v??p(m)};return async x=>{let{url:m,method:v,data:g,signal:b,cancelToken:S,timeout:k,onDownloadProgress:C,onUploadProgress:T,responseType:E,headers:N,withCredentials:_="same-origin",fetchOptions:P}=El(x),R=t||fetch;E=E?(E+"").toLowerCase():"text";let D=cg([b,S&&S.toAbortSignal()],k),F=null;const A=D&&D.unsubscribe&&(()=>{D.unsubscribe()});let z;try{if(T&&c&&v!=="get"&&v!=="head"&&(z=await h(N,g))!==0){let X=new n(m,{method:"POST",body:g,duplex:"half"}),he;if(M.isFormData(g)&&(he=X.headers.get("content-type"))&&N.setContentType(he),X.body){const[ae,Re]=Sl(z,Co(Cl(T)));g=Il(X.body,Nl,ae,Re)}}M.isString(_)||(_=_?"include":"omit");const j=s&&"credentials"in n.prototype,J={...P,signal:D,method:v.toUpperCase(),headers:N.normalize().toJSON(),body:g,duplex:"half",credentials:j?_:void 0};F=s&&new n(m,J);let B=await(s?R(F,P):R(m,J));const O=d&&(E==="stream"||E==="response");if(d&&(C||O&&A)){const X={};["status","statusText","headers"].forEach(G=>{X[G]=B[G]});const he=M.toFiniteNumber(B.headers.get("content-length")),[ae,Re]=C&&Sl(he,Co(Cl(C),!0))||[];B=new r(Il(B.body,Nl,ae,()=>{Re&&Re(),A&&A()}),X)}E=E||"text";let W=await f[M.findKey(f,E)||"text"](B,x);return!O&&A&&A(),await new Promise((X,he)=>{wl(X,he,{data:W,headers:Ht.from(B.headers),status:B.status,statusText:B.statusText,config:x,request:F})})}catch(j){throw A&&A(),j&&j.name==="TypeError"&&/Load failed|fetch/i.test(j.message)?Object.assign(new Me("Network Error",Me.ERR_NETWORK,x,F),{cause:j.cause||j}):Me.from(j,j&&j.code,x,F)}}},mg=new Map,Rl=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:o}=t,s=[r,o,n];let i=s.length,a=i,l,c,d=mg;for(;a--;)l=s[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:hg(t)),d=c;return c};Rl();const ii={http:Lm,xhr:lg,fetch:{get:Rl}};M.forEach(ii,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Pl=e=>`- ${e}`,gg=e=>M.isFunction(e)||e===null||e===!1,Ol={getAdapter:(e,t)=>{e=M.isArray(e)?e:[e];const{length:n}=e;let r,o;const s={};for(let i=0;i<n;i++){r=e[i];let a;if(o=r,!gg(r)&&(o=ii[(a=String(r)).toLowerCase()],o===void 0))throw new Me(`Unknown adapter '${a}'`);if(o&&(M.isFunction(o)||(o=o.get(t))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([l,c])=>`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
32
+ `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[vl]=this[vl]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=$r(i);r[a]||(eg(o,i),r[a]=!0)}return M.isArray(t)?t.forEach(s):s(t),this}};Ht.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),M.reduceDescriptors(Ht.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),M.freezeMethods(Ht);function si(e,t){const n=this||Lr,r=t||n,o=Ht.from(r.headers);let s=r.data;return M.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function bl(e){return!!(e&&e.__CANCEL__)}function pr(e,t,n){Me.call(this,e??"canceled",Me.ERR_CANCELED,t,n),this.name="CanceledError"}M.inherits(pr,Me,{__CANCEL__:!0});function wl(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Me("Request failed with status code "+n.status,[Me.ERR_BAD_REQUEST,Me.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function tg(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function ng(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(l){const c=Date.now(),d=r[s];i||(i=c),n[o]=l,r[o]=c;let f=s,p=0;for(;f!==o;)p+=n[f++],f=f%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-i<t)return;const h=d&&c-d;return h?Math.round(p*1e3/h):void 0}}function rg(e,t){let n=0,r=1e3/t,o,s;const i=(c,d=Date.now())=>{n=d,o=null,s&&(clearTimeout(s),s=null),e(...c)};return[(...c)=>{const d=Date.now(),f=d-n;f>=r?i(c,d):(o=c,s||(s=setTimeout(()=>{s=null,i(o)},r-f)))},()=>o&&i(o)]}const Co=(e,t,n=3)=>{let r=0;const o=ng(50,250);return rg(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,l=i-r,c=o(l),d=i<=a;r=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:l,rate:c||void 0,estimated:c&&a&&d?(a-i)/c:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(f)},n)},Sl=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Cl=e=>(...t)=>M.asap(()=>e(...t)),og=Pt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Pt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Pt.origin),Pt.navigator&&/(msie|trident)/i.test(Pt.navigator.userAgent)):()=>!0,sg=Pt.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];M.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),M.isString(r)&&i.push("path="+r),M.isString(o)&&i.push("domain="+o),s===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function ig(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function ag(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Tl(e,t,n){let r=!ig(t);return e&&(r||n==!1)?ag(e,t):t}const kl=e=>e instanceof Ht?{...e}:e;function Yn(e,t){t=t||{};const n={};function r(c,d,f,p){return M.isPlainObject(c)&&M.isPlainObject(d)?M.merge.call({caseless:p},c,d):M.isPlainObject(d)?M.merge({},d):M.isArray(d)?d.slice():d}function o(c,d,f,p){if(M.isUndefined(d)){if(!M.isUndefined(c))return r(void 0,c,f,p)}else return r(c,d,f,p)}function s(c,d){if(!M.isUndefined(d))return r(void 0,d)}function i(c,d){if(M.isUndefined(d)){if(!M.isUndefined(c))return r(void 0,c)}else return r(void 0,d)}function a(c,d,f){if(f in t)return r(c,d);if(f in e)return r(void 0,c)}const l={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(c,d,f)=>o(kl(c),kl(d),f,!0)};return M.forEach(Object.keys({...e,...t}),function(d){const f=l[d]||o,p=f(e[d],t[d],d);M.isUndefined(p)&&f!==a||(n[d]=p)}),n}const El=e=>{const t=Yn({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=Ht.from(i),t.url=ml(Tl(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),M.isFormData(n)){if(Pt.hasStandardBrowserEnv||Pt.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(M.isFunction(n.getHeaders)){const l=n.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([d,f])=>{c.includes(d.toLowerCase())&&i.set(d,f)})}}if(Pt.hasStandardBrowserEnv&&(r&&M.isFunction(r)&&(r=r(t)),r||r!==!1&&og(t.url))){const l=o&&s&&sg.read(s);l&&i.set(o,l)}return t},lg=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=El(e);let s=o.data;const i=Ht.from(o.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=o,d,f,p,h,x;function m(){h&&h(),x&&x(),o.cancelToken&&o.cancelToken.unsubscribe(d),o.signal&&o.signal.removeEventListener("abort",d)}let v=new XMLHttpRequest;v.open(o.method.toUpperCase(),o.url,!0),v.timeout=o.timeout;function g(){if(!v)return;const S=Ht.from("getAllResponseHeaders"in v&&v.getAllResponseHeaders()),C={data:!a||a==="text"||a==="json"?v.responseText:v.response,status:v.status,statusText:v.statusText,headers:S,config:e,request:v};wl(function(E){n(E),m()},function(E){r(E),m()},C),v=null}"onloadend"in v?v.onloadend=g:v.onreadystatechange=function(){!v||v.readyState!==4||v.status===0&&!(v.responseURL&&v.responseURL.indexOf("file:")===0)||setTimeout(g)},v.onabort=function(){v&&(r(new Me("Request aborted",Me.ECONNABORTED,e,v)),v=null)},v.onerror=function(k){const C=k&&k.message?k.message:"Network Error",T=new Me(C,Me.ERR_NETWORK,e,v);T.event=k||null,r(T),v=null},v.ontimeout=function(){let k=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const C=o.transitional||xl;o.timeoutErrorMessage&&(k=o.timeoutErrorMessage),r(new Me(k,C.clarifyTimeoutError?Me.ETIMEDOUT:Me.ECONNABORTED,e,v)),v=null},s===void 0&&i.setContentType(null),"setRequestHeader"in v&&M.forEach(i.toJSON(),function(k,C){v.setRequestHeader(C,k)}),M.isUndefined(o.withCredentials)||(v.withCredentials=!!o.withCredentials),a&&a!=="json"&&(v.responseType=o.responseType),c&&([p,x]=Co(c,!0),v.addEventListener("progress",p)),l&&v.upload&&([f,h]=Co(l),v.upload.addEventListener("progress",f),v.upload.addEventListener("loadend",h)),(o.cancelToken||o.signal)&&(d=S=>{v&&(r(!S||S.type?new pr(null,e,v):S),v.abort(),v=null)},o.cancelToken&&o.cancelToken.subscribe(d),o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d)));const b=tg(o.url);if(b&&Pt.protocols.indexOf(b)===-1){r(new Me("Unsupported protocol "+b+":",Me.ERR_BAD_REQUEST,e));return}v.send(s||null)})},cg=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o;const s=function(c){if(!o){o=!0,a();const d=c instanceof Error?c:this.reason;r.abort(d instanceof Me?d:new pr(d instanceof Error?d.message:d))}};let i=t&&setTimeout(()=>{i=null,s(new Me(`timeout ${t} of ms exceeded`,Me.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(s):c.removeEventListener("abort",s)}),e=null)};e.forEach(c=>c.addEventListener("abort",s));const{signal:l}=r;return l.unsubscribe=()=>M.asap(a),l}},ug=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,o;for(;r<n;)o=r+t,yield e.slice(r,o),r=o},dg=async function*(e,t){for await(const n of fg(e))yield*ug(n,t)},fg=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},Il=(e,t,n,r)=>{const o=dg(e,t);let s=0,i,a=l=>{i||(i=!0,r&&r(l))};return new ReadableStream({async pull(l){try{const{done:c,value:d}=await o.next();if(c){a(),l.close();return}let f=d.byteLength;if(n){let p=s+=f;n(p)}l.enqueue(new Uint8Array(d))}catch(c){throw a(c),c}},cancel(l){return a(l),o.return()}},{highWaterMark:2})},Nl=64*1024,{isFunction:To}=M,pg=(({Request:e,Response:t})=>({Request:e,Response:t}))(M.global),{ReadableStream:Al,TextEncoder:_l}=M.global,jl=(e,...t)=>{try{return!!e(...t)}catch{return!1}},hg=e=>{e=M.merge.call({skipUndefined:!0},pg,e);const{fetch:t,Request:n,Response:r}=e,o=t?To(t):typeof fetch=="function",s=To(n),i=To(r);if(!o)return!1;const a=o&&To(Al),l=o&&(typeof _l=="function"?(x=>m=>x.encode(m))(new _l):async x=>new Uint8Array(await new n(x).arrayBuffer())),c=s&&a&&jl(()=>{let x=!1;const m=new n(Pt.origin,{body:new Al,method:"POST",get duplex(){return x=!0,"half"}}).headers.has("Content-Type");return x&&!m}),d=i&&a&&jl(()=>M.isReadableStream(new r("").body)),f={stream:d&&(x=>x.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(x=>{!f[x]&&(f[x]=(m,v)=>{let g=m&&m[x];if(g)return g.call(m);throw new Me(`Response type '${x}' is not supported`,Me.ERR_NOT_SUPPORT,v)})});const p=async x=>{if(x==null)return 0;if(M.isBlob(x))return x.size;if(M.isSpecCompliantForm(x))return(await new n(Pt.origin,{method:"POST",body:x}).arrayBuffer()).byteLength;if(M.isArrayBufferView(x)||M.isArrayBuffer(x))return x.byteLength;if(M.isURLSearchParams(x)&&(x=x+""),M.isString(x))return(await l(x)).byteLength},h=async(x,m)=>{const v=M.toFiniteNumber(x.getContentLength());return v??p(m)};return async x=>{let{url:m,method:v,data:g,signal:b,cancelToken:S,timeout:k,onDownloadProgress:C,onUploadProgress:T,responseType:E,headers:N,withCredentials:_="same-origin",fetchOptions:P}=El(x),R=t||fetch;E=E?(E+"").toLowerCase():"text";let D=cg([b,S&&S.toAbortSignal()],k),F=null;const A=D&&D.unsubscribe&&(()=>{D.unsubscribe()});let z;try{if(T&&c&&v!=="get"&&v!=="head"&&(z=await h(N,g))!==0){let X=new n(m,{method:"POST",body:g,duplex:"half"}),fe;if(M.isFormData(g)&&(fe=X.headers.get("content-type"))&&N.setContentType(fe),X.body){const[ae,Re]=Sl(z,Co(Cl(T)));g=Il(X.body,Nl,ae,Re)}}M.isString(_)||(_=_?"include":"omit");const j=s&&"credentials"in n.prototype,J={...P,signal:D,method:v.toUpperCase(),headers:N.normalize().toJSON(),body:g,duplex:"half",credentials:j?_:void 0};F=s&&new n(m,J);let B=await(s?R(F,P):R(m,J));const O=d&&(E==="stream"||E==="response");if(d&&(C||O&&A)){const X={};["status","statusText","headers"].forEach(G=>{X[G]=B[G]});const fe=M.toFiniteNumber(B.headers.get("content-length")),[ae,Re]=C&&Sl(fe,Co(Cl(C),!0))||[];B=new r(Il(B.body,Nl,ae,()=>{Re&&Re(),A&&A()}),X)}E=E||"text";let W=await f[M.findKey(f,E)||"text"](B,x);return!O&&A&&A(),await new Promise((X,fe)=>{wl(X,fe,{data:W,headers:Ht.from(B.headers),status:B.status,statusText:B.statusText,config:x,request:F})})}catch(j){throw A&&A(),j&&j.name==="TypeError"&&/Load failed|fetch/i.test(j.message)?Object.assign(new Me("Network Error",Me.ERR_NETWORK,x,F),{cause:j.cause||j}):Me.from(j,j&&j.code,x,F)}}},mg=new Map,Rl=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:o}=t,s=[r,o,n];let i=s.length,a=i,l,c,d=mg;for(;a--;)l=s[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:hg(t)),d=c;return c};Rl();const ii={http:Lm,xhr:lg,fetch:{get:Rl}};M.forEach(ii,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Pl=e=>`- ${e}`,gg=e=>M.isFunction(e)||e===null||e===!1,Ol={getAdapter:(e,t)=>{e=M.isArray(e)?e:[e];const{length:n}=e;let r,o;const s={};for(let i=0;i<n;i++){r=e[i];let a;if(o=r,!gg(r)&&(o=ii[(a=String(r)).toLowerCase()],o===void 0))throw new Me(`Unknown adapter '${a}'`);if(o&&(M.isFunction(o)||(o=o.get(t))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([l,c])=>`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
33
33
  `+i.map(Pl).join(`
34
34
  `):" "+Pl(i[0]):"as no adapter specified";throw new Me("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:ii};function ai(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new pr(null,e)}function Ml(e){return ai(e),e.headers=Ht.from(e.headers),e.data=si.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Ol.getAdapter(e.adapter||Lr.adapter,e)(e).then(function(r){return ai(e),r.data=si.call(e,e.transformResponse,r),r.headers=Ht.from(r.headers),r},function(r){return bl(r)||(ai(e),r&&r.response&&(r.response.data=si.call(e,e.transformResponse,r.response),r.response.headers=Ht.from(r.response.headers))),Promise.reject(r)})}const Dl="1.12.2",ko={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ko[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Ll={};ko.transitional=function(t,n,r){function o(s,i){return"[Axios v"+Dl+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,a)=>{if(t===!1)throw new Me(o(i," has been removed"+(n?" in "+n:"")),Me.ERR_DEPRECATED);return n&&!Ll[i]&&(Ll[i]=!0,console.warn(o(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,i,a):!0}},ko.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function xg(e,t,n){if(typeof e!="object")throw new Me("options must be an object",Me.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],i=t[s];if(i){const a=e[s],l=a===void 0||i(a,s,e);if(l!==!0)throw new Me("option "+s+" must be "+l,Me.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Me("Unknown option "+s,Me.ERR_BAD_OPTION)}}const Eo={assertOptions:xg,validators:ko},hn=Eo.validators;let Xn=class{constructor(t){this.defaults=t||{},this.interceptors={request:new gl,response:new gl}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
35
- `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Yn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Eo.assertOptions(r,{silentJSONParsing:hn.transitional(hn.boolean),forcedJSONParsing:hn.transitional(hn.boolean),clarifyTimeoutError:hn.transitional(hn.boolean)},!1),o!=null&&(M.isFunction(o)?n.paramsSerializer={serialize:o}:Eo.assertOptions(o,{encode:hn.function,serialize:hn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Eo.assertOptions(n,{baseUrl:hn.spelling("baseURL"),withXsrfToken:hn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&M.merge(s.common,s[n.method]);s&&M.forEach(["delete","get","head","post","put","patch","common"],x=>{delete s[x]}),n.headers=Ht.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(l=l&&m.synchronous,a.unshift(m.fulfilled,m.rejected))});const c=[];this.interceptors.response.forEach(function(m){c.push(m.fulfilled,m.rejected)});let d,f=0,p;if(!l){const x=[Ml.bind(this),void 0];for(x.unshift(...a),x.push(...c),p=x.length,d=Promise.resolve(n);f<p;)d=d.then(x[f++],x[f++]);return d}p=a.length;let h=n;for(;f<p;){const x=a[f++],m=a[f++];try{h=x(h)}catch(v){m.call(this,v);break}}try{d=Ml.call(this,h)}catch(x){return Promise.reject(x)}for(f=0,p=c.length;f<p;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=Yn(this.defaults,t);const n=Tl(t.baseURL,t.url,t.allowAbsoluteUrls);return ml(n,t.params,t.paramsSerializer)}};M.forEach(["delete","get","head","options"],function(t){Xn.prototype[t]=function(n,r){return this.request(Yn(r||{},{method:t,url:n,data:(r||{}).data}))}}),M.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(Yn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Xn.prototype[t]=n(),Xn.prototype[t+"Form"]=n(!0)});let yg=class Gh{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 pr(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 Gh(function(o){t=o}),cancel:t}}};function vg(e){return function(n){return e.apply(null,n)}}function bg(e){return M.isObject(e)&&e.isAxiosError===!0}const li={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(li).forEach(([e,t])=>{li[t]=e});function $l(e){const t=new Xn(e),n=el(Xn.prototype.request,t);return M.extend(n,Xn.prototype,t,{allOwnKeys:!0}),M.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return $l(Yn(e,o))},n}const Ct=$l(Lr);Ct.Axios=Xn,Ct.CanceledError=pr,Ct.CancelToken=yg,Ct.isCancel=bl,Ct.VERSION=Dl,Ct.toFormData=wo,Ct.AxiosError=Me,Ct.Cancel=Ct.CanceledError,Ct.all=function(t){return Promise.all(t)},Ct.spread=vg,Ct.isAxiosError=bg,Ct.mergeConfig=Yn,Ct.AxiosHeaders=Ht,Ct.formToJSON=e=>yl(M.isHTMLForm(e)?new FormData(e):e),Ct.getAdapter=Ol.getAdapter,Ct.HttpStatusCode=li,Ct.default=Ct;const{Axios:yT,AxiosError:vT,CanceledError:bT,isCancel:wT,CancelToken:ST,VERSION:CT,all:TT,Cancel:kT,isAxiosError:ET,spread:IT,toFormData:NT,AxiosHeaders:AT,HttpStatusCode:_T,formToJSON:jT,getAdapter:RT,mergeConfig:PT}=Ct,Fl=typeof window<"u"?window.__API_BASE_URL__:void 0,zl=Fl?Tn(Fl):void 0;function Tn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let Io=null;const ci=new Set;function Bl(){return Io}function No(e){Io=e,ci.forEach(t=>t(e))}function Ul(e){return ci.add(e),()=>ci.delete(e)}const wg=3e4,Sg=9e4,Xt=Ct.create({...zl?{baseURL:zl}:{},timeout:wg,withCredentials:!0});Xt.interceptors.request.use(e=>(Io&&(e.headers.Authorization=`Bearer ${Io}`),e)),Xt.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,o=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem("authToken",r),No(r)),o&&localStorage.setItem("authTokenExpiresAt",o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function Jt(e,t){return Xt.defaults.baseURL?(await Xt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function ui(e,t,n){return Xt.defaults.baseURL?(await Xt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Hl(e,t,n){return Xt.defaults.baseURL?(await Xt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Wl(e,t){return Xt.defaults.baseURL?(await Xt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Zt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Vl{get baseUrl(){const t=Xt.defaults.baseURL;return t?Tn(String(t)):""}updateConfig(t){t.baseUrl&&(Xt.defaults.baseURL=Tn(String(t.baseUrl))),t.authToken!==void 0&&No(t.authToken)}getAuthToken(){return Bl()}setAuthToken(t){No(t)}onTokenChange(t){return Ul(t)}async listThreads(){const t=await Jt("/threads"),n=Zt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await ui("/threads",t?{title:t}:void 0);return Zt(r)}async updateThread(t,n){const r=await Hl(`/threads/${t}`,{title:n});return Zt(r)}async deleteThread(t){const n=await Wl(`/threads/${t}`);return Zt(n)}async threadInfo(t){const n=await Jt(`/threads/${t}/info`);return Zt(n)}async listAgents(){const t=await Jt("/agents"),n=Zt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await Jt(`/agents/${t}`);return Zt(n)}async getAgentSchema(t){const n=await Jt(`/agents/${t}/schema`);return Zt(n)}async getState(t){const n=await Jt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Zt(n)}async getStateHistory(t){const n=await Jt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:Sg});return Zt(n)}async cancelRun(t){const n=await ui("/runs/cancel",{threadId:t});return Zt(n)}async listCheckpointSummaries(t){const n=await Jt(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=Zt(n);return(r==null?void 0:r.items)??[]}}const jn=new Vl,Kl=w.createContext(null);function Cg({children:e,apiConfig:t}){const n=jn;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 u.jsx(Kl.Provider,{value:r,children:e})}function di(){const e=w.useContext(Kl);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Tg(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 kg(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await Tg(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Eg={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function fi(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 Ig(e,t){return`${e??""}::${t??""}`}function hr(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(!fi(r))return{threadId:n,latest:null,checkpoints:[],timeline:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=Ag(t),i=ql(r,0),a=_g(o);return{threadId:n,latest:i,checkpoints:o,timeline:a,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function ql(e,t){if(!fi(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(_=>!!_&&typeof _=="object").map(_=>({..._})):a===null?null:void 0,c=r.map((_,P)=>Fg(_,P)).filter(_=>!!_),d=Lt(e.config),f=Lt(d==null?void 0:d.configurable),p=mt(f,["checkpoint_id","checkpointId"]),h=mt(f,["checkpoint_ns","checkpointNs"]),x=Lt(e==null?void 0:e.parentConfig),m=Lt(x==null?void 0:x.configurable),v=mt(m,["checkpoint_id","checkpointId"])??null,g=mt(m,["checkpoint_ns","checkpointNs"])??null,b=e==null?void 0:e.createdAt,S=typeof b=="string"&&b.trim()?b:new Date(Date.now()-t).toISOString(),k=c.slice().reverse().find(_=>_.role==="user")??null,C=Lt(e==null?void 0:e.metadata),T=mt(C,["branch_label","branchLabel"]),E=mt(m,["checkpoint_id","checkpointId"]),N=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:p??null,checkpointNs:h??null,nextCursor:v,nextCursorNs:g,interrupt:Ng(a,c,t),createdAt:S,parentId:E??null,branchLabel:T??null,lastUserMessageId:(k==null?void 0:k.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:C??null,config:d??null,parentConfig:x??null,next:N??null,tasks:l??null,values:i??null}}function Ng(e,t,n){const r=Lg(e,n);return r||Dg(t,n)}function Ag(e){const t=new Map;e.forEach((o,s)=>{if(!fi(o))return;const i=ql(o,s);if(!(i!=null&&i.checkpointId))return;const a=Ig(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,Pg(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Yl(s.createdAt??"")-Yl(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function _g(e){var n,r;const t=[];for(const o of e){const s=o.checkpointId??null;if(!s)continue;const i=o.metadata??{},a=mt(i,["label"])??mt(i,["branch_label","branchLabel"])??mt(i,["description"])??"User input",l=Rg(i,["step"]),c=mt(i,["source"]),d=o.createdAt??null,f=((r=(n=o.messages)==null?void 0:n[o.messages.length-1])==null?void 0:r.id)??null,p=o.lastUserMessageId??f,h=jg(o.next);t.push({id:s,label:a,messageId:p,step:l,source:c??null,createdAt:d,next:h??void 0})}return t}function jg(e){if(!Array.isArray(e)||e.length===0)return null;const t=e.map(n=>{if(typeof n=="string")return n.trim();if(n&&typeof n=="object"&&"type"in n){const r=n;if(typeof r.type=="string")return r.type}return null}).filter(n=>!!(n&&n.length));return t.length?t.join(", "):null}function Rg(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function Pg(e,t){return{...e,metadata:Ao(e.metadata,t.metadata)??null,config:Ao(e.config,t.config)??null,parentConfig:Ao(e.parentConfig,t.parentConfig)??null,next:Og(e.next,t.next)??null,tasks:Mg(e.tasks,t.tasks)??null,values:Ao(e.values,t.values)??null}}function Ao(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?e:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function Og(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function Mg(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function Dg(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 Lg(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=$g(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=Fr(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=Fr(r.state,`${o}-state`);if(s)return s}}return null}function $g(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...p]=e,h=typeof a=="string"&&a.trim()?a:t,x=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",m=Array.isArray(d)?d:void 0,v=p.length?p[p.length-1]:void 0;return{id:h,name:x,interrupts:m,state:v!==void 0?v:f}}const n=Lt(e);if(!n)return null;const r=mt(n,["id","thread_id","taskId"])??t,o=mt(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 Fr(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=Gl(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=Fr(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=Fr(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 c=Fr(l,t,n+1,r);if(c)return c}}return null}function Gl(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=mt(n,["type","event","kind"]),o=mt(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=Gl(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 Yl(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Fg(e,t){if(!e||typeof e!="object")return null;const n=e,r=Lt(e)??{},o=Lt(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=Eg[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}`,c=Lt(o.additional_kwargs)??Lt(o.additionalKwargs),d=Lt(o.response_metadata)??Lt(o.responseMetadata),f=mt(c,["createdAt","created_at"])??mt(o,["created_at","createdAt"]),p=mt(c,["checkpointId","checkpoint_id"]),h=mt(c,["checkpointNs","checkpoint_ns"]),x=zg(o.content),m={id:l,role:i,content:x};f&&(m.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(m.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(m.model=String(d.model_name)),!m.model&&typeof o.model=="string"&&(m.model=o.model),p&&(m.checkpointId=p),h&&(m.checkpointNs=h);const v=Hg(Lt(o.artifact??r.artifact??o.artifacts??r.artifacts));v&&(m.artifact=v);const g=qg(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),b=d?{...d}:void 0;g&&Object.keys(g).length&&(m.additionalKwargs=g),b&&Object.keys(b).length&&(m.responseMetadata=b);const S=Bg((c==null?void 0:c.tool_calls)??o.tool_calls);if(S.length&&(m.content=[...m.content,...S]),i==="tool"){const k=Ug(o,m.content);k&&(m.content=k)}return m}function zg(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Xl(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Xl(e);return t?[t]:[]}return[]}function Xl(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=mt(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=mt(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 Jl(t)??null;if(n==="tool_end"){const o="output"in t?t.output:t.content;return o?{type:"text",text:typeof o=="string"?o:JSON.stringify(o)}:null}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=mt(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 Jl(e,t){var s;const n=mt(e,["id","call_id"])??t,r=mt(e,["name"])??mt(Lt(e.function),["name"]);if(!n||!r)return null;const o=Kg(e.args??e.arguments??((s=Lt(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function Bg(e){return Array.isArray(e)?e.map((t,n)=>Jl(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Ug(e,t){const n=e.content??e.output;if(!n)return t;const o={type:"text",text:typeof n=="string"?n:JSON.stringify(n)};return[...t,o]}function Hg(e){return e?{plots:Wg(e.plots)}:void 0}function Wg(e){return Array.isArray(e)?e.map(t=>Vg(t)).filter(t=>!!t):[]}function Vg(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.content_base64=="string"&&t.content_base64.trim()||void 0,r=typeof t.url=="string"&&t.url.trim()||void 0,o=(typeof t.format=="string"?t.format.trim():void 0)||(typeof t.mimeType=="string"?t.mimeType.trim():void 0)||(typeof t.mime_type=="string"?t.mime_type.trim():void 0),s=typeof t.plotId=="string"&&t.plotId.trim()||void 0,i=typeof t.artifactId=="string"&&t.artifactId.trim()||void 0,a={};return n&&(a.content_base64=n),r&&(a.url=r),o&&(a.format=o),s&&(a.plotId=s),i&&(a.artifactId=i),a}function Kg(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 Lt(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function mt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function qg(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}const mr=120;function Gg(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>mr?`${n.slice(0,mr-3)}…`:n:""}function Yg(e){var r,o;const t=[(r=e.additionalKwargs)==null?void 0:r.summary,(o=e.responseMetadata)==null?void 0:o.summary];for(const s of t)if(typeof s=="string"&&s.trim()){const i=s.trim();return i.length>mr?`${i.slice(0,mr-3)}…`:i}const n=(e.name||e.id||"").toString().trim();return n?n.length>mr?`${n.slice(0,mr-3)}…`:n:""}function Zl(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const o=Gg(n.content)||Yg(n);o&&t.set(n.id,o)}return t}function Ql(e={}){const t=w.useMemo(()=>Tn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=w.useState(e.token??null),s=w.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=w.useState(!1),[c,d]=w.useState(null),[f,p]=w.useState(""),[h,x]=w.useState(null),[m,v]=w.useState(0),[g,b]=w.useState(!1),S=w.useRef(null),k=w.useRef(!0),C=w.useRef(0),T=w.useRef(null),E=w.useRef(null),N=w.useRef(null),_=w.useRef(null),P=w.useCallback(A=>{o(A)},[]),R=w.useCallback(()=>{p(""),x(null),d(null),E.current=null,N.current=null,_.current=null},[]),D=w.useCallback(()=>{var A;console.debug("[use-chat] stop() invoked - aborting stream"),(A=S.current)==null||A.abort(),S.current=null,T.current=null,l(!1),b(!1),C.current=0,v(0)},[]),F=w.useCallback((A,z,j)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&p(""),x(null),E.current=null,N.current=null,_.current=null;const J=new AbortController;S.current=J;let B=null,O=null,W=!1;return T.current={threadId:A.threadId??null,headers:{}},(async()=>{var he,ae,Re,G,U,q,$,V,re,oe,se,Se,Qe,Fe,Xe,nt,fe,ge;const X=Le=>{var Be;try{const Ve=JSON.parse(JSON.stringify(Le));return(Be=Ve==null?void 0:Ve.payload)!=null&&Be.files_info&&Array.isArray(Ve.payload.files_info)&&(Ve.payload.files_info=Ve.payload.files_info.map(Je=>({...Je,data:Je!=null&&Je.data?`<base64 ${String(Je.data).length} chars>`:Je==null?void 0:Je.data}))),Ve}catch{return Le}};try{let Le={};try{if(r)Le={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const _e=window.__AUTH_TOKEN__,at=((he=window.localStorage)==null?void 0:he.getItem("authToken"))||null;let Y=null;try{const Ce=(ae=window.localStorage)==null?void 0:ae.getItem("chat-settings");Ce&&(Y=((Re=JSON.parse(Ce))==null?void 0:Re.apiKey)||null)}catch{}const ee=_e||at||Y||null;ee&&(Le={Authorization:`Bearer ${ee}`})}}catch{}console.debug("[use-chat] POST",t+n,X(A));let Be={};if(typeof window<"u")try{const Pe=(G=window.localStorage)==null?void 0:G.getItem("authSessionId");Pe&&(Be={"X-Session-Id":Pe})}catch{}const Ve={...Le,...Be,...s.current},Je={"Content-Type":"application/json",Accept:"text/event-stream",...Ve},ze=await fetch(t+n,{method:"POST",headers:Je,body:JSON.stringify(A),signal:J.signal,credentials:i});if(T.current&&(T.current.headers=Ve),!ze.ok||!ze.body){const Pe=await ze.text().catch(()=>"");console.debug("[use-chat] non-OK response",ze.status,Pe==null?void 0:Pe.slice(0,500));const _e=`stream ${ze.status}${Pe?": "+Pe:""}`;throw(U=j==null?void 0:j.onConnectionError)==null||U.call(j,_e),W=!0,B="error",O=_e,new Error(_e)}b(!0);const Ze=ze.body.getReader(),Et=new TextDecoder;let ft="",Ue=[];C.current=0,v(0);let xt=0,vt=null;const It=()=>{if(Ue.length){const Pe=Ue.join("");Ue=[],k.current&&p(_e=>_e+Pe)}vt=null},bt=()=>{typeof window<"u"&&vt==null&&(vt=requestAnimationFrame(It))};let wt=Date.now();const He=setInterval(()=>{var Pe;if(Date.now()-wt>18e5){const _e="Stream idle timeout";d(_e),B="error",O=_e,J.abort(),(Pe=j==null?void 0:j.onError)==null||Pe.call(j,_e)}},5e3),zt=1024*1024;try{const Pe=ze.headers.get("X-Thread-Id")||ze.headers.get("x-thread-id"),_e=ze.headers.get("X-Thread-Created")||ze.headers.get("x-thread-created"),at=Pe??null,Y=String(_e??"").toLowerCase()==="true";for(T.current&&!T.current.threadId&&(T.current={...T.current,threadId:at}),(q=j==null?void 0:j.onOpen)==null||q.call(j,{threadId:at,created:Y});;){const{value:ee,done:Ce}=await Ze.read();if(Ce)break;ft+=Et.decode(ee,{stream:!0}),ft.length>zt&&(ft="",console.warn("Stream buffer reset: exceeded 1MB"));let Te;for(;(Te=ft.indexOf(`
35
+ `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Yn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Eo.assertOptions(r,{silentJSONParsing:hn.transitional(hn.boolean),forcedJSONParsing:hn.transitional(hn.boolean),clarifyTimeoutError:hn.transitional(hn.boolean)},!1),o!=null&&(M.isFunction(o)?n.paramsSerializer={serialize:o}:Eo.assertOptions(o,{encode:hn.function,serialize:hn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Eo.assertOptions(n,{baseUrl:hn.spelling("baseURL"),withXsrfToken:hn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&M.merge(s.common,s[n.method]);s&&M.forEach(["delete","get","head","post","put","patch","common"],x=>{delete s[x]}),n.headers=Ht.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(l=l&&m.synchronous,a.unshift(m.fulfilled,m.rejected))});const c=[];this.interceptors.response.forEach(function(m){c.push(m.fulfilled,m.rejected)});let d,f=0,p;if(!l){const x=[Ml.bind(this),void 0];for(x.unshift(...a),x.push(...c),p=x.length,d=Promise.resolve(n);f<p;)d=d.then(x[f++],x[f++]);return d}p=a.length;let h=n;for(;f<p;){const x=a[f++],m=a[f++];try{h=x(h)}catch(v){m.call(this,v);break}}try{d=Ml.call(this,h)}catch(x){return Promise.reject(x)}for(f=0,p=c.length;f<p;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=Yn(this.defaults,t);const n=Tl(t.baseURL,t.url,t.allowAbsoluteUrls);return ml(n,t.params,t.paramsSerializer)}};M.forEach(["delete","get","head","options"],function(t){Xn.prototype[t]=function(n,r){return this.request(Yn(r||{},{method:t,url:n,data:(r||{}).data}))}}),M.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(Yn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Xn.prototype[t]=n(),Xn.prototype[t+"Form"]=n(!0)});let yg=class Gh{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 pr(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 Gh(function(o){t=o}),cancel:t}}};function vg(e){return function(n){return e.apply(null,n)}}function bg(e){return M.isObject(e)&&e.isAxiosError===!0}const li={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(li).forEach(([e,t])=>{li[t]=e});function $l(e){const t=new Xn(e),n=el(Xn.prototype.request,t);return M.extend(n,Xn.prototype,t,{allOwnKeys:!0}),M.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return $l(Yn(e,o))},n}const Ct=$l(Lr);Ct.Axios=Xn,Ct.CanceledError=pr,Ct.CancelToken=yg,Ct.isCancel=bl,Ct.VERSION=Dl,Ct.toFormData=wo,Ct.AxiosError=Me,Ct.Cancel=Ct.CanceledError,Ct.all=function(t){return Promise.all(t)},Ct.spread=vg,Ct.isAxiosError=bg,Ct.mergeConfig=Yn,Ct.AxiosHeaders=Ht,Ct.formToJSON=e=>yl(M.isHTMLForm(e)?new FormData(e):e),Ct.getAdapter=Ol.getAdapter,Ct.HttpStatusCode=li,Ct.default=Ct;const{Axios:yT,AxiosError:vT,CanceledError:bT,isCancel:wT,CancelToken:ST,VERSION:CT,all:TT,Cancel:kT,isAxiosError:ET,spread:IT,toFormData:NT,AxiosHeaders:AT,HttpStatusCode:_T,formToJSON:jT,getAdapter:RT,mergeConfig:PT}=Ct,Fl=typeof window<"u"?window.__API_BASE_URL__:void 0,zl=Fl?Tn(Fl):void 0;function Tn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let Io=null;const ci=new Set;function Bl(){return Io}function No(e){Io=e,ci.forEach(t=>t(e))}function Ul(e){return ci.add(e),()=>ci.delete(e)}const wg=3e4,Sg=9e4,Xt=Ct.create({...zl?{baseURL:zl}:{},timeout:wg,withCredentials:!0});Xt.interceptors.request.use(e=>(Io&&(e.headers.Authorization=`Bearer ${Io}`),e)),Xt.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,o=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem("authToken",r),No(r)),o&&localStorage.setItem("authTokenExpiresAt",o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function Jt(e,t){return Xt.defaults.baseURL?(await Xt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function ui(e,t,n){return Xt.defaults.baseURL?(await Xt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Hl(e,t,n){return Xt.defaults.baseURL?(await Xt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Wl(e,t){return Xt.defaults.baseURL?(await Xt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Zt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Vl{get baseUrl(){const t=Xt.defaults.baseURL;return t?Tn(String(t)):""}updateConfig(t){t.baseUrl&&(Xt.defaults.baseURL=Tn(String(t.baseUrl))),t.authToken!==void 0&&No(t.authToken)}getAuthToken(){return Bl()}setAuthToken(t){No(t)}onTokenChange(t){return Ul(t)}async listThreads(){const t=await Jt("/threads"),n=Zt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await ui("/threads",t?{title:t}:void 0);return Zt(r)}async updateThread(t,n){const r=await Hl(`/threads/${t}`,{title:n});return Zt(r)}async deleteThread(t){const n=await Wl(`/threads/${t}`);return Zt(n)}async threadInfo(t){const n=await Jt(`/threads/${t}/info`);return Zt(n)}async listAgents(){const t=await Jt("/agents"),n=Zt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await Jt(`/agents/${t}`);return Zt(n)}async getAgentSchema(t){const n=await Jt(`/agents/${t}/schema`);return Zt(n)}async getState(t){const n=await Jt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Zt(n)}async getStateHistory(t){const n=await Jt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:Sg});return Zt(n)}async cancelRun(t){const n=await ui("/runs/cancel",{threadId:t});return Zt(n)}async listCheckpointSummaries(t){const n=await Jt(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=Zt(n);return(r==null?void 0:r.items)??[]}}const jn=new Vl,Kl=w.createContext(null);function Cg({children:e,apiConfig:t}){const n=jn;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 u.jsx(Kl.Provider,{value:r,children:e})}function di(){const e=w.useContext(Kl);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Tg(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 kg(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await Tg(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Eg={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function fi(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 Ig(e,t){return`${e??""}::${t??""}`}function hr(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(!fi(r))return{threadId:n,latest:null,checkpoints:[],timeline:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=Ag(t),i=ql(r,0),a=_g(o);return{threadId:n,latest:i,checkpoints:o,timeline:a,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function ql(e,t){if(!fi(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(_=>!!_&&typeof _=="object").map(_=>({..._})):a===null?null:void 0,c=r.map((_,P)=>Fg(_,P)).filter(_=>!!_),d=Lt(e.config),f=Lt(d==null?void 0:d.configurable),p=mt(f,["checkpoint_id","checkpointId"]),h=mt(f,["checkpoint_ns","checkpointNs"]),x=Lt(e==null?void 0:e.parentConfig),m=Lt(x==null?void 0:x.configurable),v=mt(m,["checkpoint_id","checkpointId"])??null,g=mt(m,["checkpoint_ns","checkpointNs"])??null,b=e==null?void 0:e.createdAt,S=typeof b=="string"&&b.trim()?b:new Date(Date.now()-t).toISOString(),k=c.slice().reverse().find(_=>_.role==="user")??null,C=Lt(e==null?void 0:e.metadata),T=mt(C,["branch_label","branchLabel"]),E=mt(m,["checkpoint_id","checkpointId"]),N=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:p??null,checkpointNs:h??null,nextCursor:v,nextCursorNs:g,interrupt:Ng(a,c,t),createdAt:S,parentId:E??null,branchLabel:T??null,lastUserMessageId:(k==null?void 0:k.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:C??null,config:d??null,parentConfig:x??null,next:N??null,tasks:l??null,values:i??null}}function Ng(e,t,n){const r=Lg(e,n);return r||Dg(t,n)}function Ag(e){const t=new Map;e.forEach((o,s)=>{if(!fi(o))return;const i=ql(o,s);if(!(i!=null&&i.checkpointId))return;const a=Ig(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,Pg(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Yl(s.createdAt??"")-Yl(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function _g(e){var n,r;const t=[];for(const o of e){const s=o.checkpointId??null;if(!s)continue;const i=o.metadata??{},a=mt(i,["label"])??mt(i,["branch_label","branchLabel"])??mt(i,["description"])??"User input",l=Rg(i,["step"]),c=mt(i,["source"]),d=o.createdAt??null,f=((r=(n=o.messages)==null?void 0:n[o.messages.length-1])==null?void 0:r.id)??null,p=o.lastUserMessageId??f,h=jg(o.next);t.push({id:s,label:a,messageId:p,step:l,source:c??null,createdAt:d,next:h??void 0})}return t}function jg(e){if(!Array.isArray(e)||e.length===0)return null;const t=e.map(n=>{if(typeof n=="string")return n.trim();if(n&&typeof n=="object"&&"type"in n){const r=n;if(typeof r.type=="string")return r.type}return null}).filter(n=>!!(n&&n.length));return t.length?t.join(", "):null}function Rg(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function Pg(e,t){return{...e,metadata:Ao(e.metadata,t.metadata)??null,config:Ao(e.config,t.config)??null,parentConfig:Ao(e.parentConfig,t.parentConfig)??null,next:Og(e.next,t.next)??null,tasks:Mg(e.tasks,t.tasks)??null,values:Ao(e.values,t.values)??null}}function Ao(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?e:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function Og(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function Mg(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function Dg(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 Lg(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=$g(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=Fr(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=Fr(r.state,`${o}-state`);if(s)return s}}return null}function $g(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...p]=e,h=typeof a=="string"&&a.trim()?a:t,x=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",m=Array.isArray(d)?d:void 0,v=p.length?p[p.length-1]:void 0;return{id:h,name:x,interrupts:m,state:v!==void 0?v:f}}const n=Lt(e);if(!n)return null;const r=mt(n,["id","thread_id","taskId"])??t,o=mt(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 Fr(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=Gl(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=Fr(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=Fr(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 c=Fr(l,t,n+1,r);if(c)return c}}return null}function Gl(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=mt(n,["type","event","kind"]),o=mt(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=Gl(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 Yl(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Fg(e,t){if(!e||typeof e!="object")return null;const n=e,r=Lt(e)??{},o=Lt(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=Eg[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}`,c=Lt(o.additional_kwargs)??Lt(o.additionalKwargs),d=Lt(o.response_metadata)??Lt(o.responseMetadata),f=mt(c,["createdAt","created_at"])??mt(o,["created_at","createdAt"]),p=mt(c,["checkpointId","checkpoint_id"]),h=mt(c,["checkpointNs","checkpoint_ns"]),x=zg(o.content),m={id:l,role:i,content:x};f&&(m.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(m.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(m.model=String(d.model_name)),!m.model&&typeof o.model=="string"&&(m.model=o.model),p&&(m.checkpointId=p),h&&(m.checkpointNs=h);const v=Hg(Lt(o.artifact??r.artifact??o.artifacts??r.artifacts));v&&(m.artifact=v);const g=qg(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),b=d?{...d}:void 0;g&&Object.keys(g).length&&(m.additionalKwargs=g),b&&Object.keys(b).length&&(m.responseMetadata=b);const S=Bg((c==null?void 0:c.tool_calls)??o.tool_calls);if(S.length&&(m.content=[...m.content,...S]),i==="tool"){const k=Ug(o,m.content);k&&(m.content=k)}return m}function zg(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Xl(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Xl(e);return t?[t]:[]}return[]}function Xl(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=mt(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=mt(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 Jl(t)??null;if(n==="tool_end"){const o="output"in t?t.output:t.content;return o?{type:"text",text:typeof o=="string"?o:JSON.stringify(o)}:null}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=mt(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 Jl(e,t){var s;const n=mt(e,["id","call_id"])??t,r=mt(e,["name"])??mt(Lt(e.function),["name"]);if(!n||!r)return null;const o=Kg(e.args??e.arguments??((s=Lt(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function Bg(e){return Array.isArray(e)?e.map((t,n)=>Jl(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Ug(e,t){const n=e.content??e.output;if(!n)return t;const o={type:"text",text:typeof n=="string"?n:JSON.stringify(n)};return[...t,o]}function Hg(e){return e?{plots:Wg(e.plots)}:void 0}function Wg(e){return Array.isArray(e)?e.map(t=>Vg(t)).filter(t=>!!t):[]}function Vg(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.content_base64=="string"&&t.content_base64.trim()||void 0,r=typeof t.url=="string"&&t.url.trim()||void 0,o=(typeof t.format=="string"?t.format.trim():void 0)||(typeof t.mimeType=="string"?t.mimeType.trim():void 0)||(typeof t.mime_type=="string"?t.mime_type.trim():void 0),s=typeof t.plotId=="string"&&t.plotId.trim()||void 0,i=typeof t.artifactId=="string"&&t.artifactId.trim()||void 0,a={};return n&&(a.content_base64=n),r&&(a.url=r),o&&(a.format=o),s&&(a.plotId=s),i&&(a.artifactId=i),a}function Kg(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 Lt(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function mt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function qg(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}const mr=120;function Gg(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>mr?`${n.slice(0,mr-3)}…`:n:""}function Yg(e){var r,o;const t=[(r=e.additionalKwargs)==null?void 0:r.summary,(o=e.responseMetadata)==null?void 0:o.summary];for(const s of t)if(typeof s=="string"&&s.trim()){const i=s.trim();return i.length>mr?`${i.slice(0,mr-3)}…`:i}const n=(e.name||e.id||"").toString().trim();return n?n.length>mr?`${n.slice(0,mr-3)}…`:n:""}function Zl(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const o=Gg(n.content)||Yg(n);o&&t.set(n.id,o)}return t}function Ql(e={}){const t=w.useMemo(()=>Tn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=w.useState(e.token??null),s=w.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=w.useState(!1),[c,d]=w.useState(null),[f,p]=w.useState(""),[h,x]=w.useState(null),[m,v]=w.useState(0),[g,b]=w.useState(!1),S=w.useRef(null),k=w.useRef(!0),C=w.useRef(0),T=w.useRef(null),E=w.useRef(null),N=w.useRef(null),_=w.useRef(null),P=w.useCallback(A=>{o(A)},[]),R=w.useCallback(()=>{p(""),x(null),d(null),E.current=null,N.current=null,_.current=null},[]),D=w.useCallback(()=>{var A;console.debug("[use-chat] stop() invoked - aborting stream"),(A=S.current)==null||A.abort(),S.current=null,T.current=null,l(!1),b(!1),C.current=0,v(0)},[]),F=w.useCallback((A,z,j)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&p(""),x(null),E.current=null,N.current=null,_.current=null;const J=new AbortController;S.current=J;let B=null,O=null,W=!1;return T.current={threadId:A.threadId??null,headers:{}},(async()=>{var fe,ae,Re,G,U,q,$,V,re,oe,se,Se,Qe,Fe,Xe,nt,de,me;const X=Le=>{var Be;try{const Ve=JSON.parse(JSON.stringify(Le));return(Be=Ve==null?void 0:Ve.payload)!=null&&Be.files_info&&Array.isArray(Ve.payload.files_info)&&(Ve.payload.files_info=Ve.payload.files_info.map(Je=>({...Je,data:Je!=null&&Je.data?`<base64 ${String(Je.data).length} chars>`:Je==null?void 0:Je.data}))),Ve}catch{return Le}};try{let Le={};try{if(r)Le={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const _e=window.__AUTH_TOKEN__,at=((fe=window.localStorage)==null?void 0:fe.getItem("authToken"))||null;let Y=null;try{const Ce=(ae=window.localStorage)==null?void 0:ae.getItem("chat-settings");Ce&&(Y=((Re=JSON.parse(Ce))==null?void 0:Re.apiKey)||null)}catch{}const ee=_e||at||Y||null;ee&&(Le={Authorization:`Bearer ${ee}`})}}catch{}console.debug("[use-chat] POST",t+n,X(A));let Be={};if(typeof window<"u")try{const Pe=(G=window.localStorage)==null?void 0:G.getItem("authSessionId");Pe&&(Be={"X-Session-Id":Pe})}catch{}const Ve={...Le,...Be,...s.current},Je={"Content-Type":"application/json",Accept:"text/event-stream",...Ve},ze=await fetch(t+n,{method:"POST",headers:Je,body:JSON.stringify(A),signal:J.signal,credentials:i});if(T.current&&(T.current.headers=Ve),!ze.ok||!ze.body){const Pe=await ze.text().catch(()=>"");console.debug("[use-chat] non-OK response",ze.status,Pe==null?void 0:Pe.slice(0,500));const _e=`stream ${ze.status}${Pe?": "+Pe:""}`;throw(U=j==null?void 0:j.onConnectionError)==null||U.call(j,_e),W=!0,B="error",O=_e,new Error(_e)}b(!0);const Ze=ze.body.getReader(),Et=new TextDecoder;let ft="",Ue=[];C.current=0,v(0);let xt=0,vt=null;const It=()=>{if(Ue.length){const Pe=Ue.join("");Ue=[],k.current&&p(_e=>_e+Pe)}vt=null},bt=()=>{typeof window<"u"&&vt==null&&(vt=requestAnimationFrame(It))};let wt=Date.now();const He=setInterval(()=>{var Pe;if(Date.now()-wt>18e5){const _e="Stream idle timeout";d(_e),B="error",O=_e,J.abort(),(Pe=j==null?void 0:j.onError)==null||Pe.call(j,_e)}},5e3),zt=1024*1024;try{const Pe=ze.headers.get("X-Thread-Id")||ze.headers.get("x-thread-id"),_e=ze.headers.get("X-Thread-Created")||ze.headers.get("x-thread-created"),at=Pe??null,Y=String(_e??"").toLowerCase()==="true";for(T.current&&!T.current.threadId&&(T.current={...T.current,threadId:at}),(q=j==null?void 0:j.onOpen)==null||q.call(j,{threadId:at,created:Y});;){const{value:ee,done:Ce}=await Ze.read();if(Ce)break;ft+=Et.decode(ee,{stream:!0}),ft.length>zt&&(ft="",console.warn("Stream buffer reset: exceeded 1MB"));let Te;for(;(Te=ft.indexOf(`
36
36
 
37
- `))>=0;){const L=ft.slice(0,Te);ft=ft.slice(Te+2);const ne=Jg(L);if(!ne)continue;let pe;try{pe=JSON.parse(ne)}catch{console.debug("[use-chat] malformed SSE:",ne.slice(0,200));continue}const ce=Xg(pe)?pe.data:pe;wt=Date.now();const et=ce.seq;if(et!==void 0){if(et<=xt){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:et,lastProcessedSeq:xt,type:ce.type});continue}xt>0&&et>xt+1&&(($=j==null?void 0:j.onGap)==null||$.call(j,{from:xt,to:et})),xt=et,C.current=et,v(et)}if(console.debug("[use-chat] received event",{seq:ce.seq,type:ce.type,preview:(()=>{var ke;try{return ce.type==="message_delta"?{deltaTypes:(ke=ce.delta)==null?void 0:ke.map(ct=>ct.type),textLen:(ce.delta||[]).filter(ct=>ct.type==="text").map(ct=>String(ct.text||"").length)}:ce.content||ce.delta?{hasContent:!0}:{}}catch(ct){return{err:String(ct)}}})()}),ce.type==="checkpoint")E.current=ce.checkpointId??null,N.current=ce.checkpointNs??null,x(ce.checkpointId??null);else if(ce.type==="state_history"){_.current=ce;try{const ct=hr(ce).latest;ct&&(E.current=ct.checkpointId??null,N.current=ct.checkpointNs??null,x(ct.checkpointId??null))}catch(ke){console.warn("[use-chat] Failed to hydrate state_history payload",ke)}}try{z==null||z(ce)}catch(ke){console.error("[use-chat] Error in onEvent callback:",ke,"for event:",ce.type)}if(ce.type==="token"&&e.autoAppendAssistant!==!1)Ue.push(ce.content),bt();else if(ce.type==="message_delta"){const ke=ce.delta.filter(ct=>ct.type==="text").map(ct=>ct.text).join("");ke&&e.autoAppendAssistant!==!1&&(Ue.push(ke),bt())}else if(ce.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(V=j==null?void 0:j.onHeartbeat)==null||V.call(j,ce)}catch(ke){console.warn("[use-chat] heartbeat callback failed",ke)}}else if(vt!==null&&cancelAnimationFrame(vt),It(),ce.type==="checkpoint")x(ce.checkpointId);else if(ce.type==="error"){const ke=ce;if(d(ke.message),B="error",O=ke.message,ke.error_type==="auth_error"||ke.code==="TOKEN_EXPIRED"||((re=ke.message)==null?void 0:re.includes("token"))||((oe=ke.message)==null?void 0:oe.includes("401"))||((se=ke.message)==null?void 0:se.includes("unauthorized"))||((Se=ke.message)==null?void 0:Se.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",ke.message);try{(Qe=j==null?void 0:j.onAuthError)==null||Qe.call(j,ke.message)}catch(Wn){console.warn("[use-chat] onAuthError handler failed",Wn)}J.abort()}}}}It(),B===null&&!J.signal.aborted&&(B="complete")}catch(Pe){if(Pe.name==="AbortError")B=B??"aborted";else{const _e=Pe.message||String(Pe);B="error",O=_e,d(_e),(Fe=j==null?void 0:j.onError)==null||Fe.call(j,_e)}}finally{try{await Ze.cancel()}catch{}finally{(Xe=Ze.releaseLock)==null||Xe.call(Ze)}vt!==null&&typeof window<"u"&&window.cancelAnimationFrame(vt),clearInterval(He)}}catch(Le){if(Le.name==="AbortError")B=B??"aborted";else{const Be=Le.message||String(Le);B="error",O=Be,d(Be),(nt=j==null?void 0:j.onError)==null||nt.call(j,Be),W||((fe=j==null?void 0:j.onConnectionError)==null||fe.call(j,Be),W=!0)}}finally{const Le=C.current,Be=E.current,Ve=N.current,Je=_.current,ze=B??(J.signal.aborted?"aborted":O?"error":"complete");try{(ge=j==null?void 0:j.onClosed)==null||ge.call(j,{reason:ze,lastSeq:Le,lastCheckpointId:Be,lastCheckpointNs:Ve,lastStateHistory:Je,error:O})}catch(Ze){console.warn("[use-chat] onClosed callback failed",Ze)}l(!1),b(!1),S.current=null,C.current=0,v(0),T.current=null}})(),{close:()=>J.abort()}},[t,n,r,e.autoAppendAssistant]);return w.useEffect(()=>()=>{var A;k.current=!1,(A=S.current)==null||A.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:h,lastSeq:m,connected:g,stream:F,stop:D,clear:R,setToken:P}}function Xg(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function Jg(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 Zg(e){return e.type!=="token"}const Qg={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function ex(e,t){var n;switch(t.type){case"reset":return{messages:pi(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};case"seed":{const r=pi(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),o}case"prepend":{const r=pi(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return s.length?{...e,messages:[...s,...e.messages]}: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 tc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>tc(o,s),e):e}case"interrupt_response":return{...e,messages:nc(e.messages),pendingInterrupt:null};default:return e}}function ec(e=[]){const[t,n]=w.useReducer(ex,{...Qg,messages:e}),r=w.useRef([]),o=w.useRef(null),s=w.useRef(null),i=w.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=w.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=w.useCallback(d=>{r.current.push(d),a()},[a]);w.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=w.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,...c}}function tc(e,t){var n,r,o,s,i;if(t.type==="message_start"&&t.role==="assistant"){const a=t.id,l=ox(t.model);if(e.messages.some(f=>f.id===a)){const f=e.messagesStreamMeta??{},p={...f,[a]:f[a]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:a,messagesStreamMeta:p}}const d={id:a,role:"assistant",name:l||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:a,messages:[...e.messages,d]}}if(t.type==="message_delta"){const a=e.assemblingId??rc(e.messages);if(!a)return e;const l=e.messages,c=l.findIndex(k=>k.id===a&&k.role==="assistant");if(c===-1)return e;const d=l[c],f=e.messagesStreamMeta??{},p=f[a]??{lastSeq:null,lastText:ic(d.content)},h=t.seq??null;if(h!==null&&typeof h=="number"&&typeof p.lastSeq=="number"&&h<=p.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:h,lastSeq:p.lastSeq}),e;const{newParts:x,newMeta:m,changed:v}=tx(d.content,t.delta,p,h);if(!v)return e;const g={...d,content:x},b=_o(l,c,g),S={...f,[a]:m};return{...e,messages:b,messagesStreamMeta:S}}if(t.type==="message_end"){const a=e.assemblingId??rc(e.messages);if(!a)return{...e,assemblingId:null};const l=e.messages,c=l.findIndex(d=>d.id===a&&d.role==="assistant");if(c>=0){const d=l[c];if(!((n=d.content)==null?void 0:n.some(p=>{var h;return(p==null?void 0:p.type)==="text"&&((h=p.text)==null?void 0:h.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:d.id,contentTypes:(r=d.content)==null?void 0:r.map(h=>h==null?void 0:h.type),contentPreview:(o=d.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 p=[...l.slice(0,c),...l.slice(c+1)];return{...e,assemblingId:null,messages:p}}}return e}if(t.type==="tool_start"){const a=oc(t),l=a[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),c=t.name??t.tool??"tool";!l&&a.length===0&&a.push(`${c}-${Date.now()}`);const d=a.length?a:l?[l]:[],f=sc(e,d,c),p=f>=0?e.messages[f]:null,h=l??d[0]??`${c}-${Date.now()}`,x=(p==null?void 0:p.id)??`tool-${h}`,m=d[0]??h,v={type:"tool_call",id:m,name:c,args:t.args};if(p){const S=mi(p,d,c,t.args),k={...p,name:p.name??c,additionalKwargs:S},C=f,T=C>=0?_o(e.messages,C,k):e.messages,E=jo(k,d),N=gi(e.toolIndex,x,E);return{...e,messages:T,toolIndex:N}}const g={id:x,role:"tool",name:c,createdAt:new Date().toISOString(),content:[v],additionalKwargs:mi(void 0,d.length?d:[m],c,t.args)},b=jo(g,d.length?d:[m]);return{...e,messages:[...e.messages,g],toolIndex:gi(e.toolIndex,x,b)}}if(t.type==="tool_end"){const a=oc(t);if(!a.length&&!(typeof t.id=="string"&&t.id))return e;const l=t.name??null,c=sc(e,a,l),d=c>=0?e.messages[c]:null,f=l??(d==null?void 0:d.name)??((s=d==null?void 0:d.additionalKwargs)==null?void 0:s.toolName)??"tool",p=a[0]??((i=d==null?void 0:d.id)==null?void 0:i.replace(/^tool-/,""))??`${f}-${Date.now()}`,h=(d==null?void 0:d.id)??`tool-${p}`,x=jo(d,a);let m=t.output;if(typeof t.output=="string")try{const E=t.output.trim();(E.startsWith("{")||E.startsWith("["))&&(m=JSON.parse(E))}catch{m=t.output}const v=t.artifact??(d==null?void 0:d.artifact),g={type:"text",text:typeof m=="string"?m:JSON.stringify(m)},b=(d==null?void 0:d.createdAt)??new Date().toISOString(),S=mi(d??void 0,x.length?x:a,f),k={id:h,role:"tool",name:f??(d==null?void 0:d.name)??"tool",content:[g],createdAt:b,artifact:v??void 0,additionalKwargs:S},C=c>=0?_o(e.messages,c,k):[...e.messages,k],T=jo(k,a.length?a:x);return{...e,messages:C,toolIndex:gi(e.toolIndex,h,T)}}if(t.type==="checkpoint"){const a=t.checkpointNs??e.lastCheckpointNs??null,l=rx(e.messages,t.checkpointId,a);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:a,messages:l}}if(t.type==="branch"){const a=t.checkpointId??e.lastCheckpointId,l=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:a??null,lastCheckpointNs:l??null}}if(t.type==="error"){const a={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,a]}}if(t.type==="state_history"){const a=hr(t),l=a.interrupt,c=a.latest,d=l===null?nc(e.messages):e.messages;return{...e,messages:d,pendingInterrupt:l,lastCheckpointId:(c==null?void 0:c.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(c==null?void 0:c.checkpointNs)??e.lastCheckpointNs}}return t.type==="thread_info",e}function pi(e){return e.filter(t=>{var s;if(t.role!=="assistant")return!0;const n=(t.content||[]).some(i=>{var a;return i&&i.type==="text"&&((a=i.text)==null?void 0:a.trim())}),r=(t.content||[]).some(i=>i&&i.type==="image_url"),o=!!((s=t.artifact)!=null&&s.plots&&t.artifact.plots.length>0);return!!(n||r||o)})}function _o(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function nc(e){let t=!1;const n=e.map(r=>{const o=(r.content??[]).filter(s=>s.type!=="interrupt");return o.length!==r.content.length?(t=!0,{...r,content:o}):r});return t?n:e}function rc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function oc(e){const t=new Set,n=r=>{typeof r=="string"&&r.trim()&&t.add(r.trim())};return n(e.id),n(e==null?void 0:e.call_id),n(e==null?void 0:e.callId),Array.from(t)}function hi(e){if(!e)return[];const t=new Set,n=o=>{typeof o=="string"&&o.trim()&&t.add(o.trim())},r=e.additionalKwargs;if(r){n(r.toolCallId);const o=r.toolCallIds;if(Array.isArray(o))for(const s of o)n(s)}for(const o of e.content??[])(o==null?void 0:o.type)==="tool_call"&&n(o.id);return Array.from(t)}function mi(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};if(e){const l=hi(e);for(const c of l)s(c)}for(const l of t)s(l);const i=Array.from(o),a={...(e==null?void 0:e.additionalKwargs)??{}};if(i.length){a.toolCallIds=i;const l=typeof a.toolCallId=="string"?a.toolCallId.trim():null;a.toolCallId=l&&o.has(l)?l:i[0]}return n&&(a.toolName=n),r!==void 0&&(a.toolArgs=r),a}function jo(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=hi(e);for(const o of r)n.add(o);return Array.from(n)}function gi(e,t,n){if(!n.length)return e;let r=!1;const o={...e};for(const s of n)s&&o[s]!==t&&(o[s]=t,r=!0);return r?o:e}function sc(e,t,n){var o,s;const r=new Set(t.filter(i=>typeof i=="string"&&i.trim()));for(const i of r){const a=e.toolIndex[i];if(a){const l=e.messages.findIndex(c=>c.id===a);if(l!==-1)return l}}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(hi(a).some(c=>r.has(c)))return i}if(typeof n=="string"&&n.trim())for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool"||a.name&&a.name!==n)continue;if(!((o=a.content)==null?void 0:o.some(c=>c.type!=="tool_call")))return i}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(!((s=a.content)==null?void 0:s.some(c=>c.type!=="tool_call")))return i}return-1}function ic(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function tx(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??ic(e);let l="",c=e.slice();if(s){const f=nx(a,s);if(f===""?l="":f===s?l=s:l=f,l){const p=c[c.length-1];if((p==null?void 0:p.type)==="text"){const h=p.text??"",x={...p,text:h+l};c=[...c.slice(0,c.length-1),x]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function ac(e){return e.replace(/\s+/g," ").trim()}function nx(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=ac(e),o=ac(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 rx(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 _o(e,r,s)}return e}function ox(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}const lc=200;function sx({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onStateHistory:r,onUnhandledEvent:o,onSequenceGap:s,onStreamClosed:i,onConnectionError:a,onAuthError:l,onHeartbeat:c}){const d=w.useRef(null),f=w.useRef(null),p=w.useRef(new Map),h=w.useRef(null),x=w.useRef(null),m=w.useCallback(R=>{try{const D=globalThis.structuredClone;if(typeof D=="function")return D(R)}catch{}try{return JSON.parse(JSON.stringify(R))}catch{return R}},[]),v=w.useCallback((R,D)=>{if(!R)return;const F=p.current.get(R)??[],A=m(D),z=F.length>=lc?[...F.slice(F.length-lc+1),A]:[...F,A];p.current.set(R,z)},[m]),g=w.useCallback(R=>{R&&p.current.set(R,[])},[]),b=w.useCallback(R=>{const D=R??f.current;if(!D)return;const F=p.current.get(D);F!=null&&F.length&&F.forEach(A=>{try{n(A)}catch(z){console.error("[useChatStreamingService] Failed to replay buffered event",z)}})},[n]),S=w.useCallback(R=>{var A,z,j,J,B;const D=R.seq??null;if(D!==null){const O=d.current;if(O!==null){if(D<=O)return;D>O+1&&(s==null||s({from:O,to:D}))}d.current=D}if(R.type==="thread_info"){f.current=R.threadId,h.current&&(h.current.threadIdGuess=R.threadId),x.current=R,g(R.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",R);try{t(R)}catch(O){console.error("[useChatStreamingService] Error in onThreadInfo handler:",O)}return}if(R.type==="heartbeat"){try{c==null||c(R)}catch(O){console.error("[useChatStreamingService] Error in onHeartbeat handler:",O)}return}if(R.type==="error"){const O=R;if(O.error_type==="auth_error"||O.code==="TOKEN_EXPIRED"||((A=O.message)==null?void 0:A.includes("token"))||((z=O.message)==null?void 0:z.includes("401"))||((j=O.message)==null?void 0:j.includes("unauthorized"))||((J=O.message)==null?void 0:J.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",O.message);try{l==null||l(O.message)}catch(X){console.warn("[useChatStreamingService] onAuthError handler failed",X)}}}const F=R.threadId??(R.type==="state_history"?R.threadId:void 0)??f.current??((B=h.current)==null?void 0:B.threadIdGuess)??null;if(R.type==="state_history"){f.current=F??f.current;try{r==null||r(R)}catch(O){console.error("[useChatStreamingService] onStateHistory handler failed",O)}}if(Zg(R)){R.type==="checkpoint"||R.type==="state_history"?g(F??null):v(F??null,R);try{n(R)}catch(O){console.error("[useChatStreamingService] Error in onMessageEvent handler:",O)}return}try{o==null||o(R)}catch(O){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",O)}},[v,g,n,s,t,r,o]),{stream:k,stop:C,isStreaming:T,error:E,setToken:N}=Ql({baseUrl:e,token:void 0}),_=w.useCallback((R,D)=>{d.current=null,x.current=null,f.current=R.threadId??null,h.current={request:R,callbacks:D,manualStop:!1,threadIdGuess:R.threadId??null},k(R,S,{onOpen:D==null?void 0:D.onOpen,onError:F=>{var A;(A=D==null?void 0:D.onError)==null||A.call(D,F)},onGap:(D==null?void 0:D.onGap)??s,onConnectionError:F=>{var A;a==null||a(F),(A=D==null?void 0:D.onConnectionError)==null||A.call(D,F)},onAuthError:F=>{var A;l==null||l(F),(A=D==null?void 0:D.onAuthError)==null||A.call(D,F)},onHeartbeat:F=>{var A;try{c==null||c(F)}catch(z){console.warn("[useChatStreamingService] onHeartbeat handler failed",z)}try{(A=D==null?void 0:D.onHeartbeat)==null||A.call(D,F)}catch(z){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",z)}},onClosed:F=>{var J,B,O,W;const A=((J=h.current)==null?void 0:J.manualStop)??!1,z=f.current??((B=h.current)==null?void 0:B.threadIdGuess)??((O=F.lastStateHistory)==null?void 0:O.threadId)??null;(F.reason==="complete"||F.reason==="aborted"&&A)&&g(z);const j={...F,threadId:z,threadInfo:x.current,manualStop:A};try{i==null||i(j)}catch(X){console.warn("[useChatStreamingService] onStreamClosed handler failed",X)}try{(W=D==null?void 0:D.onClosed)==null||W.call(D,j)}catch(X){console.warn("[useChatStreamingService] downstream onClosed handler failed",X)}h.current&&(h.current=null)}})},[g,S,l,a,c,s,i,k]),P=w.useCallback(()=>{h.current&&(h.current.manualStop=!0),C()},[C]);return w.useMemo(()=>({startStream:_,stop:P,isStreaming:T,error:E,setAuthToken:N,replayBufferedEvents:b}),[_,P,T,E,N,b])}const cc=w.createContext(null),uc=w.createContext(null),dc=w.createContext(null);w.createContext(!1);function ix({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a}){const{api:l,baseUrl:c}=di(),d=w.useMemo(()=>Tn(c),[c]),[f,p]=w.useState([]),[h,x]=w.useState(t),[m,v]=w.useState(!1),[g,b]=w.useState(null),[S,k]=w.useState(!1),[C,T]=w.useState(null),{state:E,seed:N,prepend:_,pushUser:P,onEvent:R}=ec(),[D,F]=w.useState(!1),[A,z]=w.useState(!1),[j,J]=w.useState(null),[B,O]=w.useState([]),[W,X]=w.useState([]),[he,ae]=w.useState(!1),Re=w.useMemo(()=>B.flatMap(Y=>Y.messages??[]),[B]),G=w.useMemo(()=>Zl(Re),[Re]),U=w.useRef(h),q=w.useRef(null),$=w.useRef(null),V=w.useRef(null),re=w.useRef(null),oe=w.useRef(!1),se=w.useRef(null),Se=w.useRef(new Map),Qe=w.useRef(new Map);w.useEffect(()=>{U.current=h},[h]);const Fe=w.useCallback(async()=>{v(!0),b(null);try{const Y=await l.listThreads();p(Y??[])}catch(Y){const ee=String(Y);b(ee),s==null||s(ee)}finally{v(!1)}},[l,s]),Xe=w.useCallback(Y=>{if(!(Y!=null&&Y.threadId))return;const ee={threadId:Y.threadId,title:Y.title||`Thread ${Y.threadId.slice(0,8)}`,createdAt:Y.createdAt||new Date().toISOString(),updatedAt:Y.updatedAt||new Date().toISOString(),messageCount:Y.messageCount??1};p(Ce=>Ce.some(L=>L.threadId===ee.threadId)?(console.debug("[ChatSessionProvider] thread_info: thread already in list",ee.threadId),Ce):(console.debug("[ChatSessionProvider] thread_info: adding thread to list",ee.threadId),[ee,...Ce]))},[]),nt=w.useCallback(Y=>{const ee=Y.threadId??U.current;if(!ee||U.current&&U.current!==ee)return;const{checkpoints:Ce,timeline:Te}=hr(Y);if(!Ce.length)return;const L=Ce.find(ne=>ne.messages&&ne.messages.length>0)??Ce.find(ne=>!!ne.checkpointId)??Ce[0];N((L==null?void 0:L.messages)??[],{checkpointId:(L==null?void 0:L.checkpointId)??null,checkpointNs:(L==null?void 0:L.checkpointNs)??null}),X(Te),O(Ce),F(!!(L!=null&&L.nextCursor)),J((L==null?void 0:L.nextCursor)??null),se.current=`${ee}:latest`,$.current=null,V.current=null},[N]),fe=w.useCallback(Y=>{console.log("[ChatSessionProvider] 🎯 Received thread_info:",Y.threadId),Xe(Y),U.current!==Y.threadId&&((Y.created??!U.current)&&($.current=Y.threadId),V.current=Y.threadId,console.log("[ChatSessionProvider] thread_info: marking to skip auto-load for new thread"),x(Y.threadId))},[Xe]),{startStream:ge,stop:Le,isStreaming:Be,error:Ve,setAuthToken:Je}=sx({baseUrl:d,onThreadInfo:fe,onMessageEvent:R,onStateHistory:nt,onUnhandledEvent:Y=>{console.warn("[ChatSessionProvider] Unhandled event:",Y.type)},onAuthError:i}),ze=w.useCallback(async Y=>{try{const ee=await l.createThread(Y);return x(ee.threadId),await Fe(),ee.threadId}catch(ee){return s==null||s(String(ee)),null}},[l,Fe,s]),Ze=w.useCallback(async Y=>{const ee=f;p(Te=>Te.filter(L=>L.threadId!==Y));const Ce=new AbortController;Qe.current.set(Y,Ce);try{await l.deleteThread(Y),U.current===Y&&(x(null),N([],{})),console.log("[ChatSessionProvider] Thread deleted successfully:",Y)}catch(Te){console.error("[ChatSessionProvider] Delete failed, restoring thread:",Y,Te),p(ee),s==null||s(`Failed to delete thread: ${String(Te)}`)}finally{Qe.current.delete(Y)}},[f,l,N,s]),Et=w.useCallback(async(Y,ee)=>{try{await l.updateThread(Y,ee),await Fe()}catch(Ce){s==null||s(String(Ce))}},[l,Fe,s]),ft=w.useCallback(async(Y,ee)=>{if(!Y)return;const Ce=`${Y}:${ee??"latest"}`,Te=Se.current.get(Ce);if(Te)return Te;const L=(async()=>{const ne=Y;k(!0),T(null);try{const pe=await l.getStateHistory({threadId:ne,checkpointId:ee||void 0});if(U.current!==ne){console.log(`[ChatSessionProvider] Thread changed during load (was ${ne}, now ${U.current}), discarding stale data`);return}const{checkpoints:ce,timeline:et}=hr(pe),ke=ce.find(ct=>ct.messages&&ct.messages.length>0)??(ee?ce.find(ct=>ct.checkpointId===ee):null)??ce[0];N((ke==null?void 0:ke.messages)??[],{checkpointId:(ke==null?void 0:ke.checkpointId)??null,checkpointNs:(ke==null?void 0:ke.checkpointNs)??null}),X(et),O(ce),F(!!(ke!=null&&ke.nextCursor)),J((ke==null?void 0:ke.nextCursor)??null)}catch(pe){if(U.current===ne){const ce=String(pe);T(ce),s==null||s(ce)}}finally{k(!1)}})();Se.current.set(Ce,L);try{await L}finally{Se.current.delete(Ce)}return U.current===Y&&(se.current=Ce),L},[l,N,s]),Ue=w.useCallback(async(Y,ee)=>{re.current=Y;try{await ft(Y,ee)}finally{re.current===Y&&(re.current=null)}},[ft]);w.useEffect(()=>{if(!o||!h||S||Be)return;if($.current===h){$.current=null,q.current=h;return}if(V.current===h){q.current=h;return}if(re.current===h){re.current=null,q.current=h;return}if(q.current===h)return;q.current=h;const Y=!oe.current&&!!n&&h===t;let ee;Y&&n?(ee=n,oe.current=!0,console.log("[ChatSessionProvider] Loading thread with checkpoint:",ee,r?`(ns: ${r})`:"")):console.log("[ChatSessionProvider] Loading thread with latest checkpoint");const Ce=`${h}:${ee??"latest"}`;se.current!==Ce&&Ue(h,ee)},[o,h,n,r,t,S,Be,Ue]);const xt=w.useCallback(async(Y,ee)=>{const Ce=U.current;if(!Ce)return;const Te=Ce;ae(!0);try{const L=await l.getStateHistory({threadId:Te,checkpointId:Y,checkpointNs:ee??void 0});if(U.current!==Te){console.log(`[ChatSessionProvider] Thread changed during checkpoint navigation (was ${Te}, now ${U.current}), discarding stale data`);return}const{checkpoints:ne,timeline:pe}=hr(L),ce=ne.find(et=>et.checkpointId===Y&&(ee?et.checkpointNs===ee:!0));if(!ce){console.warn("[ChatSessionProvider] Requested checkpoint not found:",{checkpointId:Y,checkpointNs:ee});return}X(pe),O(ne),N(ce.messages??[],{checkpointId:ce.checkpointId??null,checkpointNs:ce.checkpointNs??null})}catch(L){U.current===Te&&(s==null||s(String(L)))}finally{ae(!1)}},[l,N,s]),vt=w.useCallback((Y,ee)=>{N(E.messages,{checkpointId:Y??null,checkpointNs:ee??null})},[N,E.messages]),It=w.useCallback(async()=>{U.current&&await Ue(U.current)},[Ue]),bt=w.useCallback(async()=>{if(!U.current||!j)return;const Y=U.current;z(!0);try{const ee=await l.getStateHistory({threadId:Y,checkpointId:j});if(U.current!==Y){console.log(`[ChatSessionProvider] Thread changed during history load (was ${Y}, now ${U.current}), discarding stale data`);return}const{checkpoints:Ce}=hr(ee);if(Ce.length>0){const Te=Ce[Ce.length-1];_((Te==null?void 0:Te.messages)??[]),F(!!(Te!=null&&Te.nextCursor)),J((Te==null?void 0:Te.nextCursor)??null)}}catch(ee){U.current===Y&&(s==null||s(String(ee)))}finally{z(!1)}},[l,j,_,s]),wt=w.useCallback(async()=>{N([],{}),x(null),Le(),O([]),X([]),F(!1),J(null),k(!1),ae(!1),z(!1),T(null);try{await l.getAgent("default")}catch(Y){console.warn("[ChatSessionProvider] Failed to refetch agent after clearing thread:",Y)}},[N,Le,l]),He=w.useCallback(async(Y,ee,Ce)=>{const Te=U.current;if(!Te)throw new Error("No active thread to handle interrupt");const L=ee?Ce??!0:!1;try{const ne={threadId:Te,checkpointId:E.lastCheckpointId??void 0,checkpointNs:E.lastCheckpointNs??void 0,command:{kind:"resume",value:L}};ge(ne)}catch(ne){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${Y}:`,ne),ne}},[E.lastCheckpointId,E.lastCheckpointNs,ge]);w.useEffect(()=>{Fe()},[Fe]),w.useEffect(()=>{a==null||a(h)},[h,a]);const zt=w.useCallback(async(Y,ee)=>{let Ce=U.current;const Te=(Y==null?void 0:Y.text)??"";if(!Ce&&!Te)return;if(!Ce&&Te){const et=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),ke=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);Ce=`${et}${ke}`,$.current=Ce,x(Ce)}const{contentParts:L}=await kg(l,(Y==null?void 0:Y.attachments)??[]),ne=[...L];Te!=null&&Te.trim()&&ne.push({type:"text",text:Te});const pe={id:`msg-${Date.now()}`,role:"user",content:ne,createdAt:new Date().toISOString()};P(pe);const ce={threadId:Ce,payload:{messages:[pe]},checkpointId:(ee==null?void 0:ee.checkpointId)??E.lastCheckpointId??void 0,checkpointNs:(ee==null?void 0:ee.checkpointNs)??E.lastCheckpointNs??void 0};ge(ce)},[l,ze,P,E,ge]),Pe=w.useMemo(()=>({threads:f,currentThreadId:h,setCurrentThreadId:x,isLoading:m,error:g,actions:{createThread:ze,deleteThread:Ze,renameThread:Et,refreshThreads:Fe}}),[f,h,m,g,ze,Ze,Et,Fe]),_e=w.useMemo(()=>({threadId:h,messages:E.messages,interrupt:null,checkpoint:{id:E.lastCheckpointId??null,namespace:E.lastCheckpointNs??null},checkpoints:B,timelineCheckpoints:W,metadata:null,isLoading:S,isHistoryLoading:A,isLoadingCheckpoint:he,error:C,hasMore:D,loadOlder:bt,clearState:wt,navigateToCheckpoint:xt,setCurrentCheckpointId:vt,returnToLatest:It,loadThread:Ue,clearThread:wt,respondToInterrupt:He,messagePreviews:G}),[h,E,B,W,S,A,he,C,D,bt,wt,xt,vt,It,Ue,He,G]),at=w.useMemo(()=>({isStreaming:Be,error:Ve,connectionState:Be?"connected":"idle",submit:zt,send:zt,stop:Le,setAuthToken:Je}),[Be,Ve,zt,Le,Je]);return u.jsx(cc.Provider,{value:Pe,children:u.jsx(uc.Provider,{value:_e,children:u.jsx(dc.Provider,{value:at,children:e})})})}function Ro(){const e=w.useContext(cc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Po(){const e=w.useContext(uc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function fc(){const e=w.useContext(dc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Oo({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onError:i,onAuthError:a,onThreadChange:l}){return u.jsx(Cg,{apiConfig:t,children:u.jsx(ix,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:i,onAuthError:a,onThreadChange:l,children:e})})}function te(...e){return Xh.twMerge(Yh.clsx(e))}const ax=mo.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"}}),st=y.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?qn.Slot:"button";return u.jsx(i,{className:te(ax({variant:t,size:n,className:e})),ref:s,...o})});st.displayName="Button";const pc=y.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:te("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}));pc.displayName="Textarea";function hc({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:p="",allowEmptySend:h=!1}){const x=i!==void 0,[m,v]=w.useState(e),g=(x?i:m)??"",[b,S]=w.useTransition(),k=w.useRef(null),C=w.useRef(0),T=w.useRef(null);w.useEffect(()=>{x||(v(e??""),T.current=null,k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`))},[e,t,x]);const E=w.useCallback(()=>{const z=k.current;z&&(z.style.height="auto",z.style.height=`${z.scrollHeight}px`)},[]);w.useEffect(()=>{E()},[E,g]);const N=w.useCallback((z,{fromUser:j})=>{x||v(z),j&&(a==null||a(z))},[x,a]),_=w.useCallback(async z=>{z&&z.preventDefault();const j=(g??"").trim();if(!j&&!h)return;const J=++C.current;T.current={id:J,shouldClear:!0},S(()=>{var B,O,W;try{const X=l(j);X&&typeof X.then=="function"?X.then(()=>{var he,ae;((he=T.current)==null?void 0:he.id)===J&&T.current.shouldClear&&(x||(v(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((ae=T.current)==null?void 0:ae.id)===J&&(T.current=null)}).catch(()=>{var he;((he=T.current)==null?void 0:he.id)===J&&(T.current=null)}):(((B=T.current)==null?void 0:B.id)===J&&T.current.shouldClear&&(x||(v(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((O=T.current)==null?void 0:O.id)===J&&(T.current=null))}catch{((W=T.current)==null?void 0:W.id)===J&&(T.current=null)}})},[g,l,h,x,a]),P=w.useCallback(z=>{const j=z.target.value;N(j,{fromUser:!0}),T.current&&(T.current.shouldClear=!1),k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`)},[N]),R=w.useCallback(z=>{z.key==="Enter"&&!z.shiftKey?(z.preventDefault(),_()):z.key==="Escape"&&t&&(z.preventDefault(),c==null||c())},[_,t,c]),A=`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))]":""} ${p}`;return u.jsx("form",{onSubmit:z=>void _(z),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(pc,{ref:k,value:g,onChange:P,onKeyDown:R,placeholder:t?"Edit your message...":n,className:A,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(st,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(ie.Square,{size:16})}):u.jsx(st,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!g.trim()&&!h||b,children:u.jsx(ie.Send,{size:16})})})]})})}const lx=w.memo(hc);function me(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 mc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function xi(...e){return t=>{let n=!1;const r=e.map(o=>{const s=mc(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():mc(e[o],null)}}}}function Ge(...e){return y.useCallback(xi(...e),e)}function cx(e,t){const n=y.createContext(t),r=s=>{const{children:i,...a}=s,l=y.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=y.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 kn(e,t=[]){let n=[];function r(s,i){const a=y.createContext(i),l=n.length;n=[...n,i];const c=f=>{var g;const{scope:p,children:h,...x}=f,m=((g=p==null?void 0:p[e])==null?void 0:g[l])||a,v=y.useMemo(()=>x,Object.values(x));return u.jsx(m.Provider,{value:v,children:h})};c.displayName=s+"Provider";function d(f,p){var m;const h=((m=p==null?void 0:p[e])==null?void 0:m[l])||a,x=y.useContext(h);if(x)return x;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>y.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return y.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,ux(o,...t)]}function ux(...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:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return y.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var _t=globalThis!=null&&globalThis.document?y.useLayoutEffect:()=>{},dx=y[" useInsertionEffect ".trim().toString()]||_t;function gr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=fx({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=y.useRef(e!==void 0);y.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 c=y.useCallback(d=>{var f;if(a){const p=px(d)?d(e):d;p!==e&&((f=i.current)==null||f.call(i,p))}else s(d)},[a,e,s,i]);return[l,c]}function fx({defaultProp:e,onChange:t}){const[n,r]=y.useState(e),o=y.useRef(n),s=y.useRef(t);return dx(()=>{s.current=t},[t]),y.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function px(e){return typeof e=="function"}var hx=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Oe=hx.reduce((e,t)=>{const n=qn.createSlot(`Primitive.${t}`),r=y.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function gc(e,t){e&&go.flushSync(()=>e.dispatchEvent(t))}function yi(e){const t=e+"CollectionProvider",[n,r]=kn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=m=>{const{scope:v,children:g}=m,b=w.useRef(null),S=w.useRef(new Map).current;return u.jsx(o,{scope:v,itemMap:S,collectionRef:b,children:g})};i.displayName=t;const a=e+"CollectionSlot",l=qn.createSlot(a),c=w.forwardRef((m,v)=>{const{scope:g,children:b}=m,S=s(a,g),k=Ge(v,S.collectionRef);return u.jsx(l,{ref:k,children:b})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",p=qn.createSlot(d),h=w.forwardRef((m,v)=>{const{scope:g,children:b,...S}=m,k=w.useRef(null),C=Ge(v,k),T=s(d,g);return w.useEffect(()=>(T.itemMap.set(k,{ref:k,...S}),()=>void T.itemMap.delete(k))),u.jsx(p,{[f]:"",ref:C,children:b})});h.displayName=d;function x(m){const v=s(e+"CollectionConsumer",m);return w.useCallback(()=>{const b=v.collectionRef.current;if(!b)return[];const S=Array.from(b.querySelectorAll(`[${f}]`));return Array.from(v.itemMap.values()).sort((T,E)=>S.indexOf(T.ref.current)-S.indexOf(E.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:i,Slot:c,ItemSlot:h},x,r]}var mx=y.createContext(void 0);function Mo(e){const t=y.useContext(mx);return e||t||"ltr"}function jt(e){const t=y.useRef(e);return y.useEffect(()=>{t.current=e}),y.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function gx(e,t=globalThis==null?void 0:globalThis.document){const n=jt(e);y.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var xx="DismissableLayer",vi="dismissableLayer.update",yx="dismissableLayer.pointerDownOutside",vx="dismissableLayer.focusOutside",xc,yc=y.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Do=y.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=y.useContext(yc),[d,f]=y.useState(null),p=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=y.useState({}),x=Ge(t,E=>f(E)),m=Array.from(c.layers),[v]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),g=m.indexOf(v),b=d?m.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,k=b>=g,C=Sx(E=>{const N=E.target,_=[...c.branches].some(P=>P.contains(N));!k||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},p),T=Cx(E=>{const N=E.target;[...c.branches].some(P=>P.contains(N))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},p);return gx(E=>{b===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},p),y.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(xc=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),vc(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=xc)}},[d,p,n,c]),y.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),vc())},[d,c]),y.useEffect(()=>{const E=()=>h({});return document.addEventListener(vi,E),()=>document.removeEventListener(vi,E)},[]),u.jsx(Oe.div,{...l,ref:x,style:{pointerEvents:S?k?"auto":"none":void 0,...e.style},onFocusCapture:me(e.onFocusCapture,T.onFocusCapture),onBlurCapture:me(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:me(e.onPointerDownCapture,C.onPointerDownCapture)})});Do.displayName=xx;var bx="DismissableLayerBranch",wx=y.forwardRef((e,t)=>{const n=y.useContext(yc),r=y.useRef(null),o=Ge(t,r);return y.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(Oe.div,{...e,ref:o})});wx.displayName=bx;function Sx(e,t=globalThis==null?void 0:globalThis.document){const n=jt(e),r=y.useRef(!1),o=y.useRef(()=>{});return y.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){bc(yx,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Cx(e,t=globalThis==null?void 0:globalThis.document){const n=jt(e),r=y.useRef(!1);return y.useEffect(()=>{const o=s=>{s.target&&!r.current&&bc(vx,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function vc(){const e=new CustomEvent(vi);document.dispatchEvent(e)}function bc(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?gc(o,s):o.dispatchEvent(s)}var bi=0;function wi(){y.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??wc()),document.body.insertAdjacentElement("beforeend",e[1]??wc()),bi++,()=>{bi===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),bi--}},[])}function wc(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Si="focusScope.autoFocusOnMount",Ci="focusScope.autoFocusOnUnmount",Sc={bubbles:!1,cancelable:!0},Tx="FocusScope",Lo=y.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=y.useState(null),c=jt(o),d=jt(s),f=y.useRef(null),p=Ge(t,m=>l(m)),h=y.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;y.useEffect(()=>{if(r){let m=function(S){if(h.paused||!a)return;const k=S.target;a.contains(k)?f.current=k:Rn(f.current,{select:!0})},v=function(S){if(h.paused||!a)return;const k=S.relatedTarget;k!==null&&(a.contains(k)||Rn(f.current,{select:!0}))},g=function(S){if(document.activeElement===document.body)for(const C of S)C.removedNodes.length>0&&Rn(a)};document.addEventListener("focusin",m),document.addEventListener("focusout",v);const b=new MutationObserver(g);return a&&b.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",v),b.disconnect()}}},[r,a,h.paused]),y.useEffect(()=>{if(a){kc.add(h);const m=document.activeElement;if(!a.contains(m)){const g=new CustomEvent(Si,Sc);a.addEventListener(Si,c),a.dispatchEvent(g),g.defaultPrevented||(kx(_x(Cc(a)),{select:!0}),document.activeElement===m&&Rn(a))}return()=>{a.removeEventListener(Si,c),setTimeout(()=>{const g=new CustomEvent(Ci,Sc);a.addEventListener(Ci,d),a.dispatchEvent(g),g.defaultPrevented||Rn(m??document.body,{select:!0}),a.removeEventListener(Ci,d),kc.remove(h)},0)}}},[a,c,d,h]);const x=y.useCallback(m=>{if(!n&&!r||h.paused)return;const v=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,g=document.activeElement;if(v&&g){const b=m.currentTarget,[S,k]=Ex(b);S&&k?!m.shiftKey&&g===k?(m.preventDefault(),n&&Rn(S,{select:!0})):m.shiftKey&&g===S&&(m.preventDefault(),n&&Rn(k,{select:!0})):g===b&&m.preventDefault()}},[n,r,h.paused]);return u.jsx(Oe.div,{tabIndex:-1,...i,ref:p,onKeyDown:x})});Lo.displayName=Tx;function kx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Rn(r,{select:t}),document.activeElement!==n)return}function Ex(e){const t=Cc(e),n=Tc(t,e),r=Tc(t.reverse(),e);return[n,r]}function Cc(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Tc(e,t){for(const n of e)if(!Ix(n,{upTo:t}))return n}function Ix(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Nx(e){return e instanceof HTMLInputElement&&"select"in e}function Rn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Nx(e)&&t&&e.select()}}var kc=Ax();function Ax(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Ec(e,t),e.unshift(t)},remove(t){var n;e=Ec(e,t),(n=e[0])==null||n.resume()}}}function Ec(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function _x(e){return e.filter(t=>t.tagName!=="A")}var jx=y[" useId ".trim().toString()]||(()=>{}),Rx=0;function En(e){const[t,n]=y.useState(jx());return _t(()=>{n(r=>r??String(Rx++))},[e]),t?`radix-${t}`:""}const Px=["top","right","bottom","left"],Pn=Math.min,Kt=Math.max,$o=Math.round,Fo=Math.floor,mn=e=>({x:e,y:e}),Ox={left:"right",right:"left",bottom:"top",top:"bottom"},Mx={start:"end",end:"start"};function Ti(e,t,n){return Kt(e,Pn(t,n))}function In(e,t){return typeof e=="function"?e(t):e}function Nn(e){return e.split("-")[0]}function xr(e){return e.split("-")[1]}function ki(e){return e==="x"?"y":"x"}function Ei(e){return e==="y"?"height":"width"}const Dx=new Set(["top","bottom"]);function gn(e){return Dx.has(Nn(e))?"y":"x"}function Ii(e){return ki(gn(e))}function Lx(e,t,n){n===void 0&&(n=!1);const r=xr(e),o=Ii(e),s=Ei(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=zo(i)),[i,zo(i)]}function $x(e){const t=zo(e);return[Ni(e),t,Ni(t)]}function Ni(e){return e.replace(/start|end/g,t=>Mx[t])}const Ic=["left","right"],Nc=["right","left"],Fx=["top","bottom"],zx=["bottom","top"];function Bx(e,t,n){switch(e){case"top":case"bottom":return n?t?Nc:Ic:t?Ic:Nc;case"left":case"right":return t?Fx:zx;default:return[]}}function Ux(e,t,n,r){const o=xr(e);let s=Bx(Nn(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Ni)))),s}function zo(e){return e.replace(/left|right|bottom|top/g,t=>Ox[t])}function Hx(e){return{top:0,right:0,bottom:0,left:0,...e}}function Ac(e){return typeof e!="number"?Hx(e):{top:e,right:e,bottom:e,left:e}}function Bo(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 _c(e,t,n){let{reference:r,floating:o}=e;const s=gn(t),i=Ii(t),a=Ei(i),l=Nn(t),c=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,p=r[a]/2-o[a]/2;let h;switch(l){case"top":h={x:d,y:r.y-o.height};break;case"bottom":h={x:d,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:f};break;case"left":h={x:r.x-o.width,y:f};break;default:h={x:r.x,y:r.y}}switch(xr(t)){case"start":h[i]-=p*(n&&c?-1:1);break;case"end":h[i]+=p*(n&&c?-1:1);break}return h}const Wx=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 c=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=_c(c,r,l),p=r,h={},x=0;for(let m=0;m<a.length;m++){const{name:v,fn:g}=a[m],{x:b,y:S,data:k,reset:C}=await g({x:d,y:f,initialPlacement:r,placement:p,strategy:o,middlewareData:h,rects:c,platform:i,elements:{reference:e,floating:t}});d=b??d,f=S??f,h={...h,[v]:{...h[v],...k}},C&&x<=50&&(x++,typeof C=="object"&&(C.placement&&(p=C.placement),C.rects&&(c=C.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):C.rects),{x:d,y:f}=_c(c,p,l)),m=-1)}return{x:d,y:f,placement:p,strategy:o,middlewareData:h}};async function zr(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:p=!1,padding:h=0}=In(t,e),x=Ac(h),v=a[p?f==="floating"?"reference":"floating":f],g=Bo(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(v)))==null||n?v:v.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),b=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)),k=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},C=Bo(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:b,offsetParent:S,strategy:l}):b);return{top:(g.top-C.top+x.top)/k.y,bottom:(C.bottom-g.bottom+x.bottom)/k.y,left:(g.left-C.left+x.left)/k.x,right:(C.right-g.right+x.right)/k.x}}const Vx=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:c,padding:d=0}=In(e,t)||{};if(c==null)return{};const f=Ac(d),p={x:n,y:r},h=Ii(o),x=Ei(h),m=await i.getDimensions(c),v=h==="y",g=v?"top":"left",b=v?"bottom":"right",S=v?"clientHeight":"clientWidth",k=s.reference[x]+s.reference[h]-p[h]-s.floating[x],C=p[h]-s.reference[h],T=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=T?T[S]:0;(!E||!await(i.isElement==null?void 0:i.isElement(T)))&&(E=a.floating[S]||s.floating[x]);const N=k/2-C/2,_=E/2-m[x]/2-1,P=Pn(f[g],_),R=Pn(f[b],_),D=P,F=E-m[x]-R,A=E/2-m[x]/2+N,z=Ti(D,A,F),j=!l.arrow&&xr(o)!=null&&A!==z&&s.reference[x]/2-(A<D?P:R)-m[x]/2<0,J=j?A<D?A-D:A-F:0;return{[h]:p[h]+J,data:{[h]:z,centerOffset:A-z-J,...j&&{alignmentOffset:J}},reset:j}}}),Kx=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:c}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:x="none",flipAlignment:m=!0,...v}=In(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const g=Nn(o),b=gn(a),S=Nn(a)===a,k=await(l.isRTL==null?void 0:l.isRTL(c.floating)),C=p||(S||!m?[zo(a)]:$x(a)),T=x!=="none";!p&&T&&C.push(...Ux(a,m,x,k));const E=[a,...C],N=await zr(t,v),_=[];let P=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&_.push(N[g]),f){const A=Lx(o,i,k);_.push(N[A[0]],N[A[1]])}if(P=[...P,{placement:o,overflows:_}],!_.every(A=>A<=0)){var R,D;const A=(((R=s.flip)==null?void 0:R.index)||0)+1,z=E[A];if(z&&(!(f==="alignment"?b!==gn(z):!1)||P.every(B=>gn(B.placement)===b?B.overflows[0]>0:!0)))return{data:{index:A,overflows:P},reset:{placement:z}};let j=(D=P.filter(J=>J.overflows[0]<=0).sort((J,B)=>J.overflows[1]-B.overflows[1])[0])==null?void 0:D.placement;if(!j)switch(h){case"bestFit":{var F;const J=(F=P.filter(B=>{if(T){const O=gn(B.placement);return O===b||O==="y"}return!0}).map(B=>[B.placement,B.overflows.filter(O=>O>0).reduce((O,W)=>O+W,0)]).sort((B,O)=>B[1]-O[1])[0])==null?void 0:F[0];J&&(j=J);break}case"initialPlacement":j=a;break}if(o!==j)return{reset:{placement:j}}}return{}}}};function jc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Rc(e){return Px.some(t=>e[t]>=0)}const qx=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=In(e,t);switch(r){case"referenceHidden":{const s=await zr(t,{...o,elementContext:"reference"}),i=jc(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Rc(i)}}}case"escaped":{const s=await zr(t,{...o,altBoundary:!0}),i=jc(s,n.floating);return{data:{escapedOffsets:i,escaped:Rc(i)}}}default:return{}}}}},Pc=new Set(["left","top"]);async function Gx(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Nn(n),a=xr(n),l=gn(n)==="y",c=Pc.has(i)?-1:1,d=s&&l?-1:1,f=In(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:x}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof x=="number"&&(h=a==="end"?x*-1:x),l?{x:h*d,y:p*c}:{x:p*c,y:h*d}}const Yx=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 Gx(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}}}}},Xx=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:v=>{let{x:g,y:b}=v;return{x:g,y:b}}},...l}=In(e,t),c={x:n,y:r},d=await zr(t,l),f=gn(Nn(o)),p=ki(f);let h=c[p],x=c[f];if(s){const v=p==="y"?"top":"left",g=p==="y"?"bottom":"right",b=h+d[v],S=h-d[g];h=Ti(b,h,S)}if(i){const v=f==="y"?"top":"left",g=f==="y"?"bottom":"right",b=x+d[v],S=x-d[g];x=Ti(b,x,S)}const m=a.fn({...t,[p]:h,[f]:x});return{...m,data:{x:m.x-n,y:m.y-r,enabled:{[p]:s,[f]:i}}}}}},Jx=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:c=!0}=In(e,t),d={x:n,y:r},f=gn(o),p=ki(f);let h=d[p],x=d[f];const m=In(a,t),v=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(l){const S=p==="y"?"height":"width",k=s.reference[p]-s.floating[S]+v.mainAxis,C=s.reference[p]+s.reference[S]-v.mainAxis;h<k?h=k:h>C&&(h=C)}if(c){var g,b;const S=p==="y"?"width":"height",k=Pc.has(Nn(o)),C=s.reference[f]-s.floating[S]+(k&&((g=i.offset)==null?void 0:g[f])||0)+(k?0:v.crossAxis),T=s.reference[f]+s.reference[S]+(k?0:((b=i.offset)==null?void 0:b[f])||0)-(k?v.crossAxis:0);x<C?x=C:x>T&&(x=T)}return{[p]:h,[f]:x}}}},Zx=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=()=>{},...c}=In(e,t),d=await zr(t,c),f=Nn(o),p=xr(o),h=gn(o)==="y",{width:x,height:m}=s.floating;let v,g;f==="top"||f==="bottom"?(v=f,g=p===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(g=f,v=p==="end"?"top":"bottom");const b=m-d.top-d.bottom,S=x-d.left-d.right,k=Pn(m-d[v],b),C=Pn(x-d[g],S),T=!t.middlewareData.shift;let E=k,N=C;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(N=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=b),T&&!p){const P=Kt(d.left,0),R=Kt(d.right,0),D=Kt(d.top,0),F=Kt(d.bottom,0);h?N=x-2*(P!==0||R!==0?P+R:Kt(d.left,d.right)):E=m-2*(D!==0||F!==0?D+F:Kt(d.top,d.bottom))}await l({...t,availableWidth:N,availableHeight:E});const _=await i.getDimensions(a.floating);return x!==_.width||m!==_.height?{reset:{rects:!0}}:{}}}};function Uo(){return typeof window<"u"}function yr(e){return Oc(e)?(e.nodeName||"").toLowerCase():"#document"}function qt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function xn(e){var t;return(t=(Oc(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Oc(e){return Uo()?e instanceof Node||e instanceof qt(e).Node:!1}function ln(e){return Uo()?e instanceof Element||e instanceof qt(e).Element:!1}function yn(e){return Uo()?e instanceof HTMLElement||e instanceof qt(e).HTMLElement:!1}function Mc(e){return!Uo()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof qt(e).ShadowRoot}const Qx=new Set(["inline","contents"]);function Br(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=cn(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!Qx.has(o)}const ey=new Set(["table","td","th"]);function ty(e){return ey.has(yr(e))}const ny=[":popover-open",":modal"];function Ho(e){return ny.some(t=>{try{return e.matches(t)}catch{return!1}})}const ry=["transform","translate","scale","rotate","perspective"],oy=["transform","translate","scale","rotate","perspective","filter"],sy=["paint","layout","strict","content"];function Ai(e){const t=_i(),n=ln(e)?cn(e):e;return ry.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)||oy.some(r=>(n.willChange||"").includes(r))||sy.some(r=>(n.contain||"").includes(r))}function iy(e){let t=On(e);for(;yn(t)&&!vr(t);){if(Ai(t))return t;if(Ho(t))return null;t=On(t)}return null}function _i(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const ay=new Set(["html","body","#document"]);function vr(e){return ay.has(yr(e))}function cn(e){return qt(e).getComputedStyle(e)}function Wo(e){return ln(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function On(e){if(yr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Mc(e)&&e.host||xn(e);return Mc(t)?t.host:t}function Dc(e){const t=On(e);return vr(t)?e.ownerDocument?e.ownerDocument.body:e.body:yn(t)&&Br(t)?t:Dc(t)}function Ur(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Dc(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=qt(o);if(s){const a=ji(i);return t.concat(i,i.visualViewport||[],Br(o)?o:[],a&&n?Ur(a):[])}return t.concat(o,Ur(o,[],n))}function ji(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lc(e){const t=cn(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=yn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=$o(n)!==s||$o(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function Ri(e){return ln(e)?e:e.contextElement}function br(e){const t=Ri(e);if(!yn(t))return mn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=Lc(t);let i=(s?$o(n.width):n.width)/r,a=(s?$o(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const ly=mn(0);function $c(e){const t=qt(e);return!_i()||!t.visualViewport?ly:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function cy(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==qt(e)?!1:t}function Jn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=Ri(e);let i=mn(1);t&&(r?ln(r)&&(i=br(r)):i=br(e));const a=cy(s,n,r)?$c(s):mn(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const p=qt(s),h=r&&ln(r)?qt(r):r;let x=p,m=ji(x);for(;m&&r&&h!==x;){const v=br(m),g=m.getBoundingClientRect(),b=cn(m),S=g.left+(m.clientLeft+parseFloat(b.paddingLeft))*v.x,k=g.top+(m.clientTop+parseFloat(b.paddingTop))*v.y;l*=v.x,c*=v.y,d*=v.x,f*=v.y,l+=S,c+=k,x=qt(m),m=ji(x)}}return Bo({width:d,height:f,x:l,y:c})}function Vo(e,t){const n=Wo(e).scrollLeft;return t?t.left+n:Jn(xn(e)).left+n}function Fc(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Vo(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function uy(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=xn(r),a=t?Ho(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=mn(1);const d=mn(0),f=yn(r);if((f||!f&&!s)&&((yr(r)!=="body"||Br(i))&&(l=Wo(r)),yn(r))){const h=Jn(r);c=br(r),d.x=h.x+r.clientLeft,d.y=h.y+r.clientTop}const p=i&&!f&&!s?Fc(i,l):mn(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+p.x,y:n.y*c.y-l.scrollTop*c.y+d.y+p.y}}function dy(e){return Array.from(e.getClientRects())}function fy(e){const t=xn(e),n=Wo(e),r=e.ownerDocument.body,o=Kt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Kt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Vo(e);const a=-n.scrollTop;return cn(r).direction==="rtl"&&(i+=Kt(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const zc=25;function py(e,t){const n=qt(e),r=xn(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=_i();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Vo(r);if(c<=0){const d=r.ownerDocument,f=d.body,p=getComputedStyle(f),h=d.compatMode==="CSS1Compat"&&parseFloat(p.marginLeft)+parseFloat(p.marginRight)||0,x=Math.abs(r.clientWidth-f.clientWidth-h);x<=zc&&(s-=x)}else c<=zc&&(s+=c);return{width:s,height:i,x:a,y:l}}const hy=new Set(["absolute","fixed"]);function my(e,t){const n=Jn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=yn(e)?br(e):mn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function Bc(e,t,n){let r;if(t==="viewport")r=py(e,n);else if(t==="document")r=fy(xn(e));else if(ln(t))r=my(t,n);else{const o=$c(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Bo(r)}function Uc(e,t){const n=On(e);return n===t||!ln(n)||vr(n)?!1:cn(n).position==="fixed"||Uc(n,t)}function gy(e,t){const n=t.get(e);if(n)return n;let r=Ur(e,[],!1).filter(a=>ln(a)&&yr(a)!=="body"),o=null;const s=cn(e).position==="fixed";let i=s?On(e):e;for(;ln(i)&&!vr(i);){const a=cn(i),l=Ai(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&hy.has(o.position)||Br(i)&&!l&&Uc(e,i))?r=r.filter(d=>d!==i):o=a,i=On(i)}return t.set(e,r),r}function xy(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Ho(t)?[]:gy(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=Bc(t,d,o);return c.top=Kt(f.top,c.top),c.right=Pn(f.right,c.right),c.bottom=Pn(f.bottom,c.bottom),c.left=Kt(f.left,c.left),c},Bc(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function yy(e){const{width:t,height:n}=Lc(e);return{width:t,height:n}}function vy(e,t,n){const r=yn(t),o=xn(t),s=n==="fixed",i=Jn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=mn(0);function c(){l.x=Vo(o)}if(r||!r&&!s)if((yr(t)!=="body"||Br(o))&&(a=Wo(t)),r){const h=Jn(t,!0,s,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?Fc(o,a):mn(0),f=i.left+a.scrollLeft-l.x-d.x,p=i.top+a.scrollTop-l.y-d.y;return{x:f,y:p,width:i.width,height:i.height}}function Pi(e){return cn(e).position==="static"}function Hc(e,t){if(!yn(e)||cn(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return xn(e)===n&&(n=n.ownerDocument.body),n}function Wc(e,t){const n=qt(e);if(Ho(e))return n;if(!yn(e)){let o=On(e);for(;o&&!vr(o);){if(ln(o)&&!Pi(o))return o;o=On(o)}return n}let r=Hc(e,t);for(;r&&ty(r)&&Pi(r);)r=Hc(r,t);return r&&vr(r)&&Pi(r)&&!Ai(r)?n:r||iy(e)||n}const by=async function(e){const t=this.getOffsetParent||Wc,n=this.getDimensions,r=await n(e.floating);return{reference:vy(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function wy(e){return cn(e).direction==="rtl"}const Sy={convertOffsetParentRelativeRectToViewportRelativeRect:uy,getDocumentElement:xn,getClippingRect:xy,getOffsetParent:Wc,getElementRects:by,getClientRects:dy,getDimensions:yy,getScale:br,isElement:ln,isRTL:wy};function Vc(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Cy(e,t){let n=null,r;const o=xn(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 c=e.getBoundingClientRect(),{left:d,top:f,width:p,height:h}=c;if(a||t(),!p||!h)return;const x=Fo(f),m=Fo(o.clientWidth-(d+p)),v=Fo(o.clientHeight-(f+h)),g=Fo(d),S={rootMargin:-x+"px "+-m+"px "+-v+"px "+-g+"px",threshold:Kt(0,Pn(1,l))||1};let k=!0;function C(T){const E=T[0].intersectionRatio;if(E!==l){if(!k)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!Vc(c,e.getBoundingClientRect())&&i(),k=!1}try{n=new IntersectionObserver(C,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(C,S)}n.observe(e)}return i(!0),s}function Ty(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,c=Ri(e),d=o||s?[...c?Ur(c):[],...Ur(t)]:[];d.forEach(g=>{o&&g.addEventListener("scroll",n,{passive:!0}),s&&g.addEventListener("resize",n)});const f=c&&a?Cy(c,n):null;let p=-1,h=null;i&&(h=new ResizeObserver(g=>{let[b]=g;b&&b.target===c&&h&&(h.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var S;(S=h)==null||S.observe(t)})),n()}),c&&!l&&h.observe(c),h.observe(t));let x,m=l?Jn(e):null;l&&v();function v(){const g=Jn(e);m&&!Vc(m,g)&&n(),m=g,x=requestAnimationFrame(v)}return n(),()=>{var g;d.forEach(b=>{o&&b.removeEventListener("scroll",n),s&&b.removeEventListener("resize",n)}),f==null||f(),(g=h)==null||g.disconnect(),h=null,l&&cancelAnimationFrame(x)}}const ky=Yx,Ey=Xx,Iy=Kx,Ny=Zx,Ay=qx,Kc=Vx,_y=Jx,jy=(e,t,n)=>{const r=new Map,o={platform:Sy,...n},s={...o.platform,_c:r};return Wx(e,t,{...o,platform:s})};var Ry=typeof document<"u",Py=function(){},Ko=Ry?w.useLayoutEffect:Py;function qo(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(!qo(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)&&!qo(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function qc(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Gc(e,t){const n=qc(e);return Math.round(t*n)/n}function Oi(e){const t=y.useRef(e);return Ko(()=>{t.current=e}),t}function Oy(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:c}=e,[d,f]=y.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[p,h]=y.useState(r);qo(p,r)||h(r);const[x,m]=y.useState(null),[v,g]=y.useState(null),b=y.useCallback(B=>{B!==T.current&&(T.current=B,m(B))},[]),S=y.useCallback(B=>{B!==E.current&&(E.current=B,g(B))},[]),k=s||x,C=i||v,T=y.useRef(null),E=y.useRef(null),N=y.useRef(d),_=l!=null,P=Oi(l),R=Oi(o),D=Oi(c),F=y.useCallback(()=>{if(!T.current||!E.current)return;const B={placement:t,strategy:n,middleware:p};R.current&&(B.platform=R.current),jy(T.current,E.current,B).then(O=>{const W={...O,isPositioned:D.current!==!1};A.current&&!qo(N.current,W)&&(N.current=W,go.flushSync(()=>{f(W)}))})},[p,t,n,R,D]);Ko(()=>{c===!1&&N.current.isPositioned&&(N.current.isPositioned=!1,f(B=>({...B,isPositioned:!1})))},[c]);const A=y.useRef(!1);Ko(()=>(A.current=!0,()=>{A.current=!1}),[]),Ko(()=>{if(k&&(T.current=k),C&&(E.current=C),k&&C){if(P.current)return P.current(k,C,F);F()}},[k,C,F,P,_]);const z=y.useMemo(()=>({reference:T,floating:E,setReference:b,setFloating:S}),[b,S]),j=y.useMemo(()=>({reference:k,floating:C}),[k,C]),J=y.useMemo(()=>{const B={position:n,left:0,top:0};if(!j.floating)return B;const O=Gc(j.floating,d.x),W=Gc(j.floating,d.y);return a?{...B,transform:"translate("+O+"px, "+W+"px)",...qc(j.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:O,top:W}},[n,a,j.floating,d.x,d.y]);return y.useMemo(()=>({...d,update:F,refs:z,elements:j,floatingStyles:J}),[d,F,z,j,J])}const My=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?Kc({element:r.current,padding:o}).fn(n):{}:r?Kc({element:r,padding:o}).fn(n):{}}}},Dy=(e,t)=>({...ky(e),options:[e,t]}),Ly=(e,t)=>({...Ey(e),options:[e,t]}),$y=(e,t)=>({..._y(e),options:[e,t]}),Fy=(e,t)=>({...Iy(e),options:[e,t]}),zy=(e,t)=>({...Ny(e),options:[e,t]}),By=(e,t)=>({...Ay(e),options:[e,t]}),Uy=(e,t)=>({...My(e),options:[e,t]});var Hy="Arrow",Yc=y.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(Oe.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});Yc.displayName=Hy;var Wy=Yc;function Xc(e){const[t,n]=y.useState(void 0);return _t(()=>{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,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.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 Mi="Popper",[Jc,Go]=kn(Mi),[Vy,Zc]=Jc(Mi),Qc=e=>{const{__scopePopper:t,children:n}=e,[r,o]=y.useState(null);return u.jsx(Vy,{scope:t,anchor:r,onAnchorChange:o,children:n})};Qc.displayName=Mi;var eu="PopperAnchor",tu=y.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=Zc(eu,n),i=y.useRef(null),a=Ge(t,i),l=y.useRef(null);return y.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||i.current,c!==l.current&&s.onAnchorChange(l.current)}),r?null:u.jsx(Oe.div,{...o,ref:a})});tu.displayName=eu;var Di="PopperContent",[Ky,qy]=Jc(Di),nu=y.forwardRef((e,t)=>{var q,$,V,re,oe,se;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:p=!1,updatePositionStrategy:h="optimized",onPlaced:x,...m}=e,v=Zc(Di,n),[g,b]=y.useState(null),S=Ge(t,Se=>b(Se)),[k,C]=y.useState(null),T=Xc(k),E=(T==null?void 0:T.width)??0,N=(T==null?void 0:T.height)??0,_=r+(s!=="center"?"-"+s:""),P=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},R=Array.isArray(c)?c:[c],D=R.length>0,F={padding:P,boundary:R.filter(Yy),altBoundary:D},{refs:A,floatingStyles:z,placement:j,isPositioned:J,middlewareData:B}=Oy({strategy:"fixed",placement:_,whileElementsMounted:(...Se)=>Ty(...Se,{animationFrame:h==="always"}),elements:{reference:v.anchor},middleware:[Dy({mainAxis:o+N,alignmentAxis:i}),l&&Ly({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?$y():void 0,...F}),l&&Fy({...F}),zy({...F,apply:({elements:Se,rects:Qe,availableWidth:Fe,availableHeight:Xe})=>{const{width:nt,height:fe}=Qe.reference,ge=Se.floating.style;ge.setProperty("--radix-popper-available-width",`${Fe}px`),ge.setProperty("--radix-popper-available-height",`${Xe}px`),ge.setProperty("--radix-popper-anchor-width",`${nt}px`),ge.setProperty("--radix-popper-anchor-height",`${fe}px`)}}),k&&Uy({element:k,padding:a}),Xy({arrowWidth:E,arrowHeight:N}),p&&By({strategy:"referenceHidden",...F})]}),[O,W]=su(j),X=jt(x);_t(()=>{J&&(X==null||X())},[J,X]);const he=(q=B.arrow)==null?void 0:q.x,ae=($=B.arrow)==null?void 0:$.y,Re=((V=B.arrow)==null?void 0:V.centerOffset)!==0,[G,U]=y.useState();return _t(()=>{g&&U(window.getComputedStyle(g).zIndex)},[g]),u.jsx("div",{ref:A.setFloating,"data-radix-popper-content-wrapper":"",style:{...z,transform:J?z.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:G,"--radix-popper-transform-origin":[(re=B.transformOrigin)==null?void 0:re.x,(oe=B.transformOrigin)==null?void 0:oe.y].join(" "),...((se=B.hide)==null?void 0:se.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(Ky,{scope:n,placedSide:O,onArrowChange:C,arrowX:he,arrowY:ae,shouldHideArrow:Re,children:u.jsx(Oe.div,{"data-side":O,"data-align":W,...m,ref:S,style:{...m.style,animation:J?void 0:"none"}})})})});nu.displayName=Di;var ru="PopperArrow",Gy={top:"bottom",right:"left",bottom:"top",left:"right"},ou=y.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=qy(ru,r),i=Gy[s.placedSide];return u.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:u.jsx(Wy,{...o,ref:n,style:{...o.style,display:"block"}})})});ou.displayName=ru;function Yy(e){return e!==null}var Xy=e=>({name:"transformOrigin",options:e,fn(t){var v,g,b;const{placement:n,rects:r,middlewareData:o}=t,i=((v=o.arrow)==null?void 0:v.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,d]=su(n),f={start:"0%",center:"50%",end:"100%"}[d],p=(((g=o.arrow)==null?void 0:g.x)??0)+a/2,h=(((b=o.arrow)==null?void 0:b.y)??0)+l/2;let x="",m="";return c==="bottom"?(x=i?f:`${p}px`,m=`${-l}px`):c==="top"?(x=i?f:`${p}px`,m=`${r.floating.height+l}px`):c==="right"?(x=`${-l}px`,m=i?f:`${h}px`):c==="left"&&(x=`${r.floating.width+l}px`,m=i?f:`${h}px`),{data:{x,y:m}}}});function su(e){const[t,n="center"]=e.split("-");return[t,n]}var iu=Qc,au=tu,lu=nu,cu=ou,Jy="Portal",Yo=y.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=y.useState(!1);_t(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Ys.createPortal(u.jsx(Oe.div,{...r,ref:t}),i):null});Yo.displayName=Jy;function Zy(e,t){return y.useReducer((n,r)=>t[n][r]??n,e)}var Qt=e=>{const{present:t,children:n}=e,r=Qy(t),o=typeof n=="function"?n({present:r.isPresent}):y.Children.only(n),s=Ge(r.ref,ev(o));return typeof n=="function"||r.isPresent?y.cloneElement(o,{ref:s}):null};Qt.displayName="Presence";function Qy(e){const[t,n]=y.useState(),r=y.useRef(null),o=y.useRef(e),s=y.useRef("none"),i=e?"mounted":"unmounted",[a,l]=Zy(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return y.useEffect(()=>{const c=Xo(r.current);s.current=a==="mounted"?c:"none"},[a]),_t(()=>{const c=r.current,d=o.current;if(d!==e){const p=s.current,h=Xo(c);e?l("MOUNT"):h==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&p!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),_t(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=h=>{const m=Xo(r.current).includes(CSS.escape(h.animationName));if(h.target===t&&m&&(l("ANIMATION_END"),!o.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},p=h=>{h.target===t&&(s.current=Xo(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:y.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Xo(e){return(e==null?void 0:e.animationName)||"none"}function ev(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 Li="rovingFocusGroup.onEntryFocus",tv={bubbles:!1,cancelable:!0},Hr="RovingFocusGroup",[$i,uu,nv]=yi(Hr),[rv,du]=kn(Hr,[nv]),[ov,sv]=rv(Hr),fu=y.forwardRef((e,t)=>u.jsx($i.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx($i.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(iv,{...e,ref:t})})}));fu.displayName=Hr;var iv=y.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...f}=e,p=y.useRef(null),h=Ge(t,p),x=Mo(s),[m,v]=gr({prop:i,defaultProp:a??null,onChange:l,caller:Hr}),[g,b]=y.useState(!1),S=jt(c),k=uu(n),C=y.useRef(!1),[T,E]=y.useState(0);return y.useEffect(()=>{const N=p.current;if(N)return N.addEventListener(Li,S),()=>N.removeEventListener(Li,S)},[S]),u.jsx(ov,{scope:n,orientation:r,dir:x,loop:o,currentTabStopId:m,onItemFocus:y.useCallback(N=>v(N),[v]),onItemShiftTab:y.useCallback(()=>b(!0),[]),onFocusableItemAdd:y.useCallback(()=>E(N=>N+1),[]),onFocusableItemRemove:y.useCallback(()=>E(N=>N-1),[]),children:u.jsx(Oe.div,{tabIndex:g||T===0?-1:0,"data-orientation":r,...f,ref:h,style:{outline:"none",...e.style},onMouseDown:me(e.onMouseDown,()=>{C.current=!0}),onFocus:me(e.onFocus,N=>{const _=!C.current;if(N.target===N.currentTarget&&_&&!g){const P=new CustomEvent(Li,tv);if(N.currentTarget.dispatchEvent(P),!P.defaultPrevented){const R=k().filter(j=>j.focusable),D=R.find(j=>j.active),F=R.find(j=>j.id===m),z=[D,F,...R].filter(Boolean).map(j=>j.ref.current);mu(z,d)}}C.current=!1}),onBlur:me(e.onBlur,()=>b(!1))})})}),pu="RovingFocusGroupItem",hu=y.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=En(),c=s||l,d=sv(pu,n),f=d.currentTabStopId===c,p=uu(n),{onFocusableItemAdd:h,onFocusableItemRemove:x,currentTabStopId:m}=d;return y.useEffect(()=>{if(r)return h(),()=>x()},[r,h,x]),u.jsx($i.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(Oe.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:me(e.onMouseDown,v=>{r?d.onItemFocus(c):v.preventDefault()}),onFocus:me(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:me(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){d.onItemShiftTab();return}if(v.target!==v.currentTarget)return;const g=cv(v,d.orientation,d.dir);if(g!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let S=p().filter(k=>k.focusable).map(k=>k.ref.current);if(g==="last")S.reverse();else if(g==="prev"||g==="next"){g==="prev"&&S.reverse();const k=S.indexOf(v.currentTarget);S=d.loop?uv(S,k+1):S.slice(k+1)}setTimeout(()=>mu(S))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:m!=null}):i})})});hu.displayName=pu;var av={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function lv(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function cv(e,t,n){const r=lv(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return av[r]}function mu(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function uv(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var dv=fu,fv=hu,pv=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},wr=new WeakMap,Jo=new WeakMap,Zo={},Fi=0,gu=function(e){return e&&(e.host||gu(e.parentNode))},hv=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=gu(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},mv=function(e,t,n,r){var o=hv(t,Array.isArray(e)?e:[e]);Zo[n]||(Zo[n]=new WeakMap);var s=Zo[n],i=[],a=new Set,l=new Set(o),c=function(f){!f||a.has(f)||(a.add(f),c(f.parentNode))};o.forEach(c);var d=function(f){!f||l.has(f)||Array.prototype.forEach.call(f.children,function(p){if(a.has(p))d(p);else try{var h=p.getAttribute(r),x=h!==null&&h!=="false",m=(wr.get(p)||0)+1,v=(s.get(p)||0)+1;wr.set(p,m),s.set(p,v),i.push(p),m===1&&x&&Jo.set(p,!0),v===1&&p.setAttribute(n,"true"),x||p.setAttribute(r,"true")}catch(g){console.error("aria-hidden: cannot operate on ",p,g)}})};return d(t),a.clear(),Fi++,function(){i.forEach(function(f){var p=wr.get(f)-1,h=s.get(f)-1;wr.set(f,p),s.set(f,h),p||(Jo.has(f)||f.removeAttribute(r),Jo.delete(f)),h||f.removeAttribute(n)}),Fi--,Fi||(wr=new WeakMap,wr=new WeakMap,Jo=new WeakMap,Zo={})}},zi=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=pv(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),mv(r,o,n,"aria-hidden")):function(){return null}},vn=function(){return vn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},vn.apply(this,arguments)};function xu(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function gv(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var Qo="right-scroll-bar-position",es="width-before-scroll-bar",xv="with-scroll-bars-hidden",yv="--removed-body-scroll-bar-size";function Bi(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function vv(e,t){var n=w.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var bv=typeof window<"u"?y.useLayoutEffect:y.useEffect,yu=new WeakMap;function wv(e,t){var n=vv(null,function(r){return e.forEach(function(o){return Bi(o,r)})});return bv(function(){var r=yu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Bi(a,null)}),s.forEach(function(a){o.has(a)||Bi(a,i)})}yu.set(n,e)},[e]),n}function Sv(e){return e}function Cv(e,t){t===void 0&&(t=Sv);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function Tv(e){e===void 0&&(e={});var t=Cv(null);return t.options=vn({async:!0,ssr:!1},e),t}var vu=function(e){var t=e.sideCar,n=xu(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return y.createElement(r,vn({},n))};vu.isSideCarExport=!0;function kv(e,t){return e.useMedium(t),vu}var bu=Tv(),Ui=function(){},ts=y.forwardRef(function(e,t){var n=y.useRef(null),r=y.useState({onScrollCapture:Ui,onWheelCapture:Ui,onTouchMoveCapture:Ui}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,p=e.sideCar,h=e.noRelative,x=e.noIsolation,m=e.inert,v=e.allowPinchZoom,g=e.as,b=g===void 0?"div":g,S=e.gapMode,k=xu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=p,T=wv([n,t]),E=vn(vn({},k),o);return y.createElement(y.Fragment,null,d&&y.createElement(C,{sideCar:bu,removeScrollBar:c,shards:f,noRelative:h,noIsolation:x,inert:m,setCallbacks:s,allowPinchZoom:!!v,lockRef:n,gapMode:S}),i?y.cloneElement(y.Children.only(a),vn(vn({},E),{ref:T})):y.createElement(b,vn({},E,{className:l,ref:T}),a))});ts.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},ts.classNames={fullWidth:es,zeroRight:Qo};var Ev=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Iv(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Ev();return t&&e.setAttribute("nonce",t),e}function Nv(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Av(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var _v=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Iv())&&(Nv(t,n),Av(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},jv=function(){var e=_v();return function(t,n){y.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},wu=function(){var e=jv(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Rv={left:0,top:0,right:0,gap:0},Hi=function(e){return parseInt(e||"",10)||0},Pv=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Hi(n),Hi(r),Hi(o)]},Ov=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Rv;var t=Pv(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Mv=wu(),Sr="data-scroll-locked",Dv=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
37
+ `))>=0;){const L=ft.slice(0,Te);ft=ft.slice(Te+2);const ne=Jg(L);if(!ne)continue;let ge;try{ge=JSON.parse(ne)}catch{console.debug("[use-chat] malformed SSE:",ne.slice(0,200));continue}const pe=Xg(ge)?ge.data:ge;wt=Date.now();const et=pe.seq;if(et!==void 0){if(et<=xt){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:et,lastProcessedSeq:xt,type:pe.type});continue}xt>0&&et>xt+1&&(($=j==null?void 0:j.onGap)==null||$.call(j,{from:xt,to:et})),xt=et,C.current=et,v(et)}if(console.debug("[use-chat] received event",{seq:pe.seq,type:pe.type,preview:(()=>{var ke;try{return pe.type==="message_delta"?{deltaTypes:(ke=pe.delta)==null?void 0:ke.map(ct=>ct.type),textLen:(pe.delta||[]).filter(ct=>ct.type==="text").map(ct=>String(ct.text||"").length)}:pe.content||pe.delta?{hasContent:!0}:{}}catch(ct){return{err:String(ct)}}})()}),pe.type==="checkpoint")E.current=pe.checkpointId??null,N.current=pe.checkpointNs??null,x(pe.checkpointId??null);else if(pe.type==="state_history"){_.current=pe;try{const ct=hr(pe).latest;ct&&(E.current=ct.checkpointId??null,N.current=ct.checkpointNs??null,x(ct.checkpointId??null))}catch(ke){console.warn("[use-chat] Failed to hydrate state_history payload",ke)}}try{z==null||z(pe)}catch(ke){console.error("[use-chat] Error in onEvent callback:",ke,"for event:",pe.type)}if(pe.type==="token"&&e.autoAppendAssistant!==!1)Ue.push(pe.content),bt();else if(pe.type==="message_delta"){const ke=pe.delta.filter(ct=>ct.type==="text").map(ct=>ct.text).join("");ke&&e.autoAppendAssistant!==!1&&(Ue.push(ke),bt())}else if(pe.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(V=j==null?void 0:j.onHeartbeat)==null||V.call(j,pe)}catch(ke){console.warn("[use-chat] heartbeat callback failed",ke)}}else if(vt!==null&&cancelAnimationFrame(vt),It(),pe.type==="checkpoint")x(pe.checkpointId);else if(pe.type==="error"){const ke=pe;if(d(ke.message),B="error",O=ke.message,ke.error_type==="auth_error"||ke.code==="TOKEN_EXPIRED"||((re=ke.message)==null?void 0:re.includes("token"))||((oe=ke.message)==null?void 0:oe.includes("401"))||((se=ke.message)==null?void 0:se.includes("unauthorized"))||((Se=ke.message)==null?void 0:Se.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",ke.message);try{(Qe=j==null?void 0:j.onAuthError)==null||Qe.call(j,ke.message)}catch(Wn){console.warn("[use-chat] onAuthError handler failed",Wn)}J.abort()}}}}It(),B===null&&!J.signal.aborted&&(B="complete")}catch(Pe){if(Pe.name==="AbortError")B=B??"aborted";else{const _e=Pe.message||String(Pe);B="error",O=_e,d(_e),(Fe=j==null?void 0:j.onError)==null||Fe.call(j,_e)}}finally{try{await Ze.cancel()}catch{}finally{(Xe=Ze.releaseLock)==null||Xe.call(Ze)}vt!==null&&typeof window<"u"&&window.cancelAnimationFrame(vt),clearInterval(He)}}catch(Le){if(Le.name==="AbortError")B=B??"aborted";else{const Be=Le.message||String(Le);B="error",O=Be,d(Be),(nt=j==null?void 0:j.onError)==null||nt.call(j,Be),W||((de=j==null?void 0:j.onConnectionError)==null||de.call(j,Be),W=!0)}}finally{const Le=C.current,Be=E.current,Ve=N.current,Je=_.current,ze=B??(J.signal.aborted?"aborted":O?"error":"complete");try{(me=j==null?void 0:j.onClosed)==null||me.call(j,{reason:ze,lastSeq:Le,lastCheckpointId:Be,lastCheckpointNs:Ve,lastStateHistory:Je,error:O})}catch(Ze){console.warn("[use-chat] onClosed callback failed",Ze)}l(!1),b(!1),S.current=null,C.current=0,v(0),T.current=null}})(),{close:()=>J.abort()}},[t,n,r,e.autoAppendAssistant]);return w.useEffect(()=>()=>{var A;k.current=!1,(A=S.current)==null||A.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:h,lastSeq:m,connected:g,stream:F,stop:D,clear:R,setToken:P}}function Xg(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function Jg(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 Zg(e){return e.type!=="token"}const Qg={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function ex(e,t){var n;switch(t.type){case"reset":return{messages:pi(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};case"seed":{const r=pi(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),o}case"prepend":{const r=pi(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return s.length?{...e,messages:[...s,...e.messages]}: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 tc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>tc(o,s),e):e}case"interrupt_response":return{...e,messages:nc(e.messages),pendingInterrupt:null};default:return e}}function ec(e=[]){const[t,n]=w.useReducer(ex,{...Qg,messages:e}),r=w.useRef([]),o=w.useRef(null),s=w.useRef(null),i=w.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=w.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=w.useCallback(d=>{r.current.push(d),a()},[a]);w.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=w.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,...c}}function tc(e,t){var n,r,o,s,i;if(t.type==="message_start"&&t.role==="assistant"){const a=t.id,l=ox(t.model);if(e.messages.some(f=>f.id===a)){const f=e.messagesStreamMeta??{},p={...f,[a]:f[a]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:a,messagesStreamMeta:p}}const d={id:a,role:"assistant",name:l||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:a,messages:[...e.messages,d]}}if(t.type==="message_delta"){const a=e.assemblingId??rc(e.messages);if(!a)return e;const l=e.messages,c=l.findIndex(k=>k.id===a&&k.role==="assistant");if(c===-1)return e;const d=l[c],f=e.messagesStreamMeta??{},p=f[a]??{lastSeq:null,lastText:ic(d.content)},h=t.seq??null;if(h!==null&&typeof h=="number"&&typeof p.lastSeq=="number"&&h<=p.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:h,lastSeq:p.lastSeq}),e;const{newParts:x,newMeta:m,changed:v}=tx(d.content,t.delta,p,h);if(!v)return e;const g={...d,content:x},b=_o(l,c,g),S={...f,[a]:m};return{...e,messages:b,messagesStreamMeta:S}}if(t.type==="message_end"){const a=e.assemblingId??rc(e.messages);if(!a)return{...e,assemblingId:null};const l=e.messages,c=l.findIndex(d=>d.id===a&&d.role==="assistant");if(c>=0){const d=l[c];if(!((n=d.content)==null?void 0:n.some(p=>{var h;return(p==null?void 0:p.type)==="text"&&((h=p.text)==null?void 0:h.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:d.id,contentTypes:(r=d.content)==null?void 0:r.map(h=>h==null?void 0:h.type),contentPreview:(o=d.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 p=[...l.slice(0,c),...l.slice(c+1)];return{...e,assemblingId:null,messages:p}}}return e}if(t.type==="tool_start"){const a=oc(t),l=a[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),c=t.name??t.tool??"tool";!l&&a.length===0&&a.push(`${c}-${Date.now()}`);const d=a.length?a:l?[l]:[],f=sc(e,d,c),p=f>=0?e.messages[f]:null,h=l??d[0]??`${c}-${Date.now()}`,x=(p==null?void 0:p.id)??`tool-${h}`,m=d[0]??h,v={type:"tool_call",id:m,name:c,args:t.args};if(p){const S=mi(p,d,c,t.args),k={...p,name:p.name??c,additionalKwargs:S},C=f,T=C>=0?_o(e.messages,C,k):e.messages,E=jo(k,d),N=gi(e.toolIndex,x,E);return{...e,messages:T,toolIndex:N}}const g={id:x,role:"tool",name:c,createdAt:new Date().toISOString(),content:[v],additionalKwargs:mi(void 0,d.length?d:[m],c,t.args)},b=jo(g,d.length?d:[m]);return{...e,messages:[...e.messages,g],toolIndex:gi(e.toolIndex,x,b)}}if(t.type==="tool_end"){const a=oc(t);if(!a.length&&!(typeof t.id=="string"&&t.id))return e;const l=t.name??null,c=sc(e,a,l),d=c>=0?e.messages[c]:null,f=l??(d==null?void 0:d.name)??((s=d==null?void 0:d.additionalKwargs)==null?void 0:s.toolName)??"tool",p=a[0]??((i=d==null?void 0:d.id)==null?void 0:i.replace(/^tool-/,""))??`${f}-${Date.now()}`,h=(d==null?void 0:d.id)??`tool-${p}`,x=jo(d,a);let m=t.output;if(typeof t.output=="string")try{const E=t.output.trim();(E.startsWith("{")||E.startsWith("["))&&(m=JSON.parse(E))}catch{m=t.output}const v=t.artifact??(d==null?void 0:d.artifact),g={type:"text",text:typeof m=="string"?m:JSON.stringify(m)},b=(d==null?void 0:d.createdAt)??new Date().toISOString(),S=mi(d??void 0,x.length?x:a,f),k={id:h,role:"tool",name:f??(d==null?void 0:d.name)??"tool",content:[g],createdAt:b,artifact:v??void 0,additionalKwargs:S},C=c>=0?_o(e.messages,c,k):[...e.messages,k],T=jo(k,a.length?a:x);return{...e,messages:C,toolIndex:gi(e.toolIndex,h,T)}}if(t.type==="checkpoint"){const a=t.checkpointNs??e.lastCheckpointNs??null,l=rx(e.messages,t.checkpointId,a);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:a,messages:l}}if(t.type==="branch"){const a=t.checkpointId??e.lastCheckpointId,l=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:a??null,lastCheckpointNs:l??null}}if(t.type==="error"){const a={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,a]}}if(t.type==="state_history"){const a=hr(t),l=a.interrupt,c=a.latest,d=l===null?nc(e.messages):e.messages;return{...e,messages:d,pendingInterrupt:l,lastCheckpointId:(c==null?void 0:c.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(c==null?void 0:c.checkpointNs)??e.lastCheckpointNs}}return t.type==="thread_info",e}function pi(e){return e.filter(t=>{var s;if(t.role!=="assistant")return!0;const n=(t.content||[]).some(i=>{var a;return i&&i.type==="text"&&((a=i.text)==null?void 0:a.trim())}),r=(t.content||[]).some(i=>i&&i.type==="image_url"),o=!!((s=t.artifact)!=null&&s.plots&&t.artifact.plots.length>0);return!!(n||r||o)})}function _o(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function nc(e){let t=!1;const n=e.map(r=>{const o=(r.content??[]).filter(s=>s.type!=="interrupt");return o.length!==r.content.length?(t=!0,{...r,content:o}):r});return t?n:e}function rc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function oc(e){const t=new Set,n=r=>{typeof r=="string"&&r.trim()&&t.add(r.trim())};return n(e.id),n(e==null?void 0:e.call_id),n(e==null?void 0:e.callId),Array.from(t)}function hi(e){if(!e)return[];const t=new Set,n=o=>{typeof o=="string"&&o.trim()&&t.add(o.trim())},r=e.additionalKwargs;if(r){n(r.toolCallId);const o=r.toolCallIds;if(Array.isArray(o))for(const s of o)n(s)}for(const o of e.content??[])(o==null?void 0:o.type)==="tool_call"&&n(o.id);return Array.from(t)}function mi(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};if(e){const l=hi(e);for(const c of l)s(c)}for(const l of t)s(l);const i=Array.from(o),a={...(e==null?void 0:e.additionalKwargs)??{}};if(i.length){a.toolCallIds=i;const l=typeof a.toolCallId=="string"?a.toolCallId.trim():null;a.toolCallId=l&&o.has(l)?l:i[0]}return n&&(a.toolName=n),r!==void 0&&(a.toolArgs=r),a}function jo(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=hi(e);for(const o of r)n.add(o);return Array.from(n)}function gi(e,t,n){if(!n.length)return e;let r=!1;const o={...e};for(const s of n)s&&o[s]!==t&&(o[s]=t,r=!0);return r?o:e}function sc(e,t,n){var o,s;const r=new Set(t.filter(i=>typeof i=="string"&&i.trim()));for(const i of r){const a=e.toolIndex[i];if(a){const l=e.messages.findIndex(c=>c.id===a);if(l!==-1)return l}}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(hi(a).some(c=>r.has(c)))return i}if(typeof n=="string"&&n.trim())for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool"||a.name&&a.name!==n)continue;if(!((o=a.content)==null?void 0:o.some(c=>c.type!=="tool_call")))return i}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(!((s=a.content)==null?void 0:s.some(c=>c.type!=="tool_call")))return i}return-1}function ic(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function tx(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??ic(e);let l="",c=e.slice();if(s){const f=nx(a,s);if(f===""?l="":f===s?l=s:l=f,l){const p=c[c.length-1];if((p==null?void 0:p.type)==="text"){const h=p.text??"",x={...p,text:h+l};c=[...c.slice(0,c.length-1),x]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function ac(e){return e.replace(/\s+/g," ").trim()}function nx(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=ac(e),o=ac(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 rx(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 _o(e,r,s)}return e}function ox(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}const lc=200;function sx({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onStateHistory:r,onUnhandledEvent:o,onSequenceGap:s,onStreamClosed:i,onConnectionError:a,onAuthError:l,onHeartbeat:c}){const d=w.useRef(null),f=w.useRef(null),p=w.useRef(new Map),h=w.useRef(null),x=w.useRef(null),m=w.useCallback(R=>{try{const D=globalThis.structuredClone;if(typeof D=="function")return D(R)}catch{}try{return JSON.parse(JSON.stringify(R))}catch{return R}},[]),v=w.useCallback((R,D)=>{if(!R)return;const F=p.current.get(R)??[],A=m(D),z=F.length>=lc?[...F.slice(F.length-lc+1),A]:[...F,A];p.current.set(R,z)},[m]),g=w.useCallback(R=>{R&&p.current.set(R,[])},[]),b=w.useCallback(R=>{const D=R??f.current;if(!D)return;const F=p.current.get(D);F!=null&&F.length&&F.forEach(A=>{try{n(A)}catch(z){console.error("[useChatStreamingService] Failed to replay buffered event",z)}})},[n]),S=w.useCallback(R=>{var A,z,j,J,B;const D=R.seq??null;if(D!==null){const O=d.current;if(O!==null){if(D<=O)return;D>O+1&&(s==null||s({from:O,to:D}))}d.current=D}if(R.type==="thread_info"){f.current=R.threadId,h.current&&(h.current.threadIdGuess=R.threadId),x.current=R,g(R.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",R);try{t(R)}catch(O){console.error("[useChatStreamingService] Error in onThreadInfo handler:",O)}return}if(R.type==="heartbeat"){try{c==null||c(R)}catch(O){console.error("[useChatStreamingService] Error in onHeartbeat handler:",O)}return}if(R.type==="error"){const O=R;if(O.error_type==="auth_error"||O.code==="TOKEN_EXPIRED"||((A=O.message)==null?void 0:A.includes("token"))||((z=O.message)==null?void 0:z.includes("401"))||((j=O.message)==null?void 0:j.includes("unauthorized"))||((J=O.message)==null?void 0:J.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",O.message);try{l==null||l(O.message)}catch(X){console.warn("[useChatStreamingService] onAuthError handler failed",X)}}}const F=R.threadId??(R.type==="state_history"?R.threadId:void 0)??f.current??((B=h.current)==null?void 0:B.threadIdGuess)??null;if(R.type==="state_history"){f.current=F??f.current;try{r==null||r(R)}catch(O){console.error("[useChatStreamingService] onStateHistory handler failed",O)}}if(Zg(R)){R.type==="checkpoint"||R.type==="state_history"?g(F??null):v(F??null,R);try{n(R)}catch(O){console.error("[useChatStreamingService] Error in onMessageEvent handler:",O)}return}try{o==null||o(R)}catch(O){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",O)}},[v,g,n,s,t,r,o]),{stream:k,stop:C,isStreaming:T,error:E,setToken:N}=Ql({baseUrl:e,token:void 0}),_=w.useCallback((R,D)=>{d.current=null,x.current=null,f.current=R.threadId??null,h.current={request:R,callbacks:D,manualStop:!1,threadIdGuess:R.threadId??null},k(R,S,{onOpen:D==null?void 0:D.onOpen,onError:F=>{var A;(A=D==null?void 0:D.onError)==null||A.call(D,F)},onGap:(D==null?void 0:D.onGap)??s,onConnectionError:F=>{var A;a==null||a(F),(A=D==null?void 0:D.onConnectionError)==null||A.call(D,F)},onAuthError:F=>{var A;l==null||l(F),(A=D==null?void 0:D.onAuthError)==null||A.call(D,F)},onHeartbeat:F=>{var A;try{c==null||c(F)}catch(z){console.warn("[useChatStreamingService] onHeartbeat handler failed",z)}try{(A=D==null?void 0:D.onHeartbeat)==null||A.call(D,F)}catch(z){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",z)}},onClosed:F=>{var J,B,O,W;const A=((J=h.current)==null?void 0:J.manualStop)??!1,z=f.current??((B=h.current)==null?void 0:B.threadIdGuess)??((O=F.lastStateHistory)==null?void 0:O.threadId)??null;(F.reason==="complete"||F.reason==="aborted"&&A)&&g(z);const j={...F,threadId:z,threadInfo:x.current,manualStop:A};try{i==null||i(j)}catch(X){console.warn("[useChatStreamingService] onStreamClosed handler failed",X)}try{(W=D==null?void 0:D.onClosed)==null||W.call(D,j)}catch(X){console.warn("[useChatStreamingService] downstream onClosed handler failed",X)}h.current&&(h.current=null)}})},[g,S,l,a,c,s,i,k]),P=w.useCallback(()=>{h.current&&(h.current.manualStop=!0),C()},[C]);return w.useMemo(()=>({startStream:_,stop:P,isStreaming:T,error:E,setAuthToken:N,replayBufferedEvents:b}),[_,P,T,E,N,b])}const cc=w.createContext(null),uc=w.createContext(null),dc=w.createContext(null);w.createContext(!1);function ix({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a}){const{api:l,baseUrl:c}=di(),d=w.useMemo(()=>Tn(c),[c]),[f,p]=w.useState([]),[h,x]=w.useState(t),[m,v]=w.useState(!1),[g,b]=w.useState(null),[S,k]=w.useState(!1),[C,T]=w.useState(null),{state:E,seed:N,prepend:_,pushUser:P,onEvent:R}=ec(),[D,F]=w.useState(!1),[A,z]=w.useState(!1),[j,J]=w.useState(null),[B,O]=w.useState([]),[W,X]=w.useState([]),[fe,ae]=w.useState(!1),Re=w.useMemo(()=>B.flatMap(Y=>Y.messages??[]),[B]),G=w.useMemo(()=>Zl(Re),[Re]),U=w.useRef(h),q=w.useRef(null),$=w.useRef(null),V=w.useRef(null),re=w.useRef(null),oe=w.useRef(!1),se=w.useRef(null),Se=w.useRef(new Map),Qe=w.useRef(new Map);w.useEffect(()=>{U.current=h},[h]);const Fe=w.useCallback(async()=>{v(!0),b(null);try{const Y=await l.listThreads();p(Y??[])}catch(Y){const ee=String(Y);b(ee),s==null||s(ee)}finally{v(!1)}},[l,s]),Xe=w.useCallback(Y=>{if(!(Y!=null&&Y.threadId))return;const ee={threadId:Y.threadId,title:Y.title||`Thread ${Y.threadId.slice(0,8)}`,createdAt:Y.createdAt||new Date().toISOString(),updatedAt:Y.updatedAt||new Date().toISOString(),messageCount:Y.messageCount??1};p(Ce=>Ce.some(L=>L.threadId===ee.threadId)?(console.debug("[ChatSessionProvider] thread_info: thread already in list",ee.threadId),Ce):(console.debug("[ChatSessionProvider] thread_info: adding thread to list",ee.threadId),[ee,...Ce]))},[]),nt=w.useCallback(Y=>{const ee=Y.threadId??U.current;if(!ee||U.current&&U.current!==ee)return;const{checkpoints:Ce,timeline:Te}=hr(Y);if(!Ce.length)return;const L=Ce.find(ne=>ne.messages&&ne.messages.length>0)??Ce.find(ne=>!!ne.checkpointId)??Ce[0];N((L==null?void 0:L.messages)??[],{checkpointId:(L==null?void 0:L.checkpointId)??null,checkpointNs:(L==null?void 0:L.checkpointNs)??null}),X(Te),O(Ce),F(!!(L!=null&&L.nextCursor)),J((L==null?void 0:L.nextCursor)??null),se.current=`${ee}:latest`,$.current=null,V.current=null},[N]),de=w.useCallback(Y=>{console.log("[ChatSessionProvider] 🎯 Received thread_info:",Y.threadId),Xe(Y),U.current!==Y.threadId&&((Y.created??!U.current)&&($.current=Y.threadId),V.current=Y.threadId,console.log("[ChatSessionProvider] thread_info: marking to skip auto-load for new thread"),x(Y.threadId))},[Xe]),{startStream:me,stop:Le,isStreaming:Be,error:Ve,setAuthToken:Je}=sx({baseUrl:d,onThreadInfo:de,onMessageEvent:R,onStateHistory:nt,onUnhandledEvent:Y=>{console.warn("[ChatSessionProvider] Unhandled event:",Y.type)},onAuthError:i}),ze=w.useCallback(async Y=>{try{const ee=await l.createThread(Y);return x(ee.threadId),await Fe(),ee.threadId}catch(ee){return s==null||s(String(ee)),null}},[l,Fe,s]),Ze=w.useCallback(async Y=>{const ee=f;p(Te=>Te.filter(L=>L.threadId!==Y));const Ce=new AbortController;Qe.current.set(Y,Ce);try{await l.deleteThread(Y),U.current===Y&&(x(null),N([],{})),console.log("[ChatSessionProvider] Thread deleted successfully:",Y)}catch(Te){console.error("[ChatSessionProvider] Delete failed, restoring thread:",Y,Te),p(ee),s==null||s(`Failed to delete thread: ${String(Te)}`)}finally{Qe.current.delete(Y)}},[f,l,N,s]),Et=w.useCallback(async(Y,ee)=>{try{await l.updateThread(Y,ee),await Fe()}catch(Ce){s==null||s(String(Ce))}},[l,Fe,s]),ft=w.useCallback(async(Y,ee)=>{if(!Y)return;const Ce=`${Y}:${ee??"latest"}`,Te=Se.current.get(Ce);if(Te)return Te;const L=(async()=>{const ne=Y;k(!0),T(null);try{const ge=await l.getStateHistory({threadId:ne,checkpointId:ee||void 0});if(U.current!==ne){console.log(`[ChatSessionProvider] Thread changed during load (was ${ne}, now ${U.current}), discarding stale data`);return}const{checkpoints:pe,timeline:et}=hr(ge),ke=pe.find(ct=>ct.messages&&ct.messages.length>0)??(ee?pe.find(ct=>ct.checkpointId===ee):null)??pe[0];N((ke==null?void 0:ke.messages)??[],{checkpointId:(ke==null?void 0:ke.checkpointId)??null,checkpointNs:(ke==null?void 0:ke.checkpointNs)??null}),X(et),O(pe),F(!!(ke!=null&&ke.nextCursor)),J((ke==null?void 0:ke.nextCursor)??null)}catch(ge){if(U.current===ne){const pe=String(ge);T(pe),s==null||s(pe)}}finally{k(!1)}})();Se.current.set(Ce,L);try{await L}finally{Se.current.delete(Ce)}return U.current===Y&&(se.current=Ce),L},[l,N,s]),Ue=w.useCallback(async(Y,ee)=>{re.current=Y;try{await ft(Y,ee)}finally{re.current===Y&&(re.current=null)}},[ft]);w.useEffect(()=>{if(!o||!h||S||Be)return;if($.current===h){$.current=null,q.current=h;return}if(V.current===h){q.current=h;return}if(re.current===h){re.current=null,q.current=h;return}if(q.current===h)return;q.current=h;const Y=!oe.current&&!!n&&h===t;let ee;Y&&n?(ee=n,oe.current=!0,console.log("[ChatSessionProvider] Loading thread with checkpoint:",ee,r?`(ns: ${r})`:"")):console.log("[ChatSessionProvider] Loading thread with latest checkpoint");const Ce=`${h}:${ee??"latest"}`;se.current!==Ce&&Ue(h,ee)},[o,h,n,r,t,S,Be,Ue]);const xt=w.useCallback(async(Y,ee)=>{const Ce=U.current;if(!Ce)return;const Te=Ce;ae(!0);try{const L=await l.getStateHistory({threadId:Te,checkpointId:Y,checkpointNs:ee??void 0});if(U.current!==Te){console.log(`[ChatSessionProvider] Thread changed during checkpoint navigation (was ${Te}, now ${U.current}), discarding stale data`);return}const{checkpoints:ne,timeline:ge}=hr(L),pe=ne.find(et=>et.checkpointId===Y&&(ee?et.checkpointNs===ee:!0));if(!pe){console.warn("[ChatSessionProvider] Requested checkpoint not found:",{checkpointId:Y,checkpointNs:ee});return}X(ge),O(ne),N(pe.messages??[],{checkpointId:pe.checkpointId??null,checkpointNs:pe.checkpointNs??null})}catch(L){U.current===Te&&(s==null||s(String(L)))}finally{ae(!1)}},[l,N,s]),vt=w.useCallback((Y,ee)=>{N(E.messages,{checkpointId:Y??null,checkpointNs:ee??null})},[N,E.messages]),It=w.useCallback(async()=>{U.current&&await Ue(U.current)},[Ue]),bt=w.useCallback(async()=>{if(!U.current||!j)return;const Y=U.current;z(!0);try{const ee=await l.getStateHistory({threadId:Y,checkpointId:j});if(U.current!==Y){console.log(`[ChatSessionProvider] Thread changed during history load (was ${Y}, now ${U.current}), discarding stale data`);return}const{checkpoints:Ce}=hr(ee);if(Ce.length>0){const Te=Ce[Ce.length-1];_((Te==null?void 0:Te.messages)??[]),F(!!(Te!=null&&Te.nextCursor)),J((Te==null?void 0:Te.nextCursor)??null)}}catch(ee){U.current===Y&&(s==null||s(String(ee)))}finally{z(!1)}},[l,j,_,s]),wt=w.useCallback(async()=>{N([],{}),x(null),Le(),O([]),X([]),F(!1),J(null),k(!1),ae(!1),z(!1),T(null);try{await l.getAgent("default")}catch(Y){console.warn("[ChatSessionProvider] Failed to refetch agent after clearing thread:",Y)}},[N,Le,l]),He=w.useCallback(async(Y,ee,Ce)=>{const Te=U.current;if(!Te)throw new Error("No active thread to handle interrupt");const L=ee?Ce??!0:!1;try{const ne={threadId:Te,checkpointId:E.lastCheckpointId??void 0,checkpointNs:E.lastCheckpointNs??void 0,command:{kind:"resume",value:L}};me(ne)}catch(ne){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${Y}:`,ne),ne}},[E.lastCheckpointId,E.lastCheckpointNs,me]);w.useEffect(()=>{Fe()},[Fe]),w.useEffect(()=>{a==null||a(h)},[h,a]);const zt=w.useCallback(async(Y,ee)=>{let Ce=U.current;const Te=(Y==null?void 0:Y.text)??"";if(!Ce&&!Te)return;if(!Ce&&Te){const et=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),ke=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);Ce=`${et}${ke}`,$.current=Ce,x(Ce)}const{contentParts:L}=await kg(l,(Y==null?void 0:Y.attachments)??[]),ne=[...L];Te!=null&&Te.trim()&&ne.push({type:"text",text:Te});const ge={id:`msg-${Date.now()}`,role:"user",content:ne,createdAt:new Date().toISOString()};P(ge);const pe={threadId:Ce,payload:{messages:[ge]},checkpointId:(ee==null?void 0:ee.checkpointId)??E.lastCheckpointId??void 0,checkpointNs:(ee==null?void 0:ee.checkpointNs)??E.lastCheckpointNs??void 0};me(pe)},[l,ze,P,E,me]),Pe=w.useMemo(()=>({threads:f,currentThreadId:h,setCurrentThreadId:x,isLoading:m,error:g,actions:{createThread:ze,deleteThread:Ze,renameThread:Et,refreshThreads:Fe}}),[f,h,m,g,ze,Ze,Et,Fe]),_e=w.useMemo(()=>({threadId:h,messages:E.messages,interrupt:null,checkpoint:{id:E.lastCheckpointId??null,namespace:E.lastCheckpointNs??null},checkpoints:B,timelineCheckpoints:W,metadata:null,isLoading:S,isHistoryLoading:A,isLoadingCheckpoint:fe,error:C,hasMore:D,loadOlder:bt,clearState:wt,navigateToCheckpoint:xt,setCurrentCheckpointId:vt,returnToLatest:It,loadThread:Ue,clearThread:wt,respondToInterrupt:He,messagePreviews:G}),[h,E,B,W,S,A,fe,C,D,bt,wt,xt,vt,It,Ue,He,G]),at=w.useMemo(()=>({isStreaming:Be,error:Ve,connectionState:Be?"connected":"idle",submit:zt,send:zt,stop:Le,setAuthToken:Je}),[Be,Ve,zt,Le,Je]);return u.jsx(cc.Provider,{value:Pe,children:u.jsx(uc.Provider,{value:_e,children:u.jsx(dc.Provider,{value:at,children:e})})})}function Ro(){const e=w.useContext(cc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Po(){const e=w.useContext(uc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function fc(){const e=w.useContext(dc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Oo({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onError:i,onAuthError:a,onThreadChange:l}){return u.jsx(Cg,{apiConfig:t,children:u.jsx(ix,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:i,onAuthError:a,onThreadChange:l,children:e})})}function te(...e){return Xh.twMerge(Yh.clsx(e))}const ax=mo.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"}}),st=y.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?qn.Slot:"button";return u.jsx(i,{className:te(ax({variant:t,size:n,className:e})),ref:s,...o})});st.displayName="Button";const pc=y.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:te("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}));pc.displayName="Textarea";function hc({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:p="",allowEmptySend:h=!1}){const x=i!==void 0,[m,v]=w.useState(e),g=(x?i:m)??"",[b,S]=w.useTransition(),k=w.useRef(null),C=w.useRef(0),T=w.useRef(null);w.useEffect(()=>{x||(v(e??""),T.current=null,k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`))},[e,t,x]);const E=w.useCallback(()=>{const z=k.current;z&&(z.style.height="auto",z.style.height=`${z.scrollHeight}px`)},[]);w.useEffect(()=>{E()},[E,g]);const N=w.useCallback((z,{fromUser:j})=>{x||v(z),j&&(a==null||a(z))},[x,a]),_=w.useCallback(async z=>{z&&z.preventDefault();const j=(g??"").trim();if(!j&&!h)return;const J=++C.current;T.current={id:J,shouldClear:!0},S(()=>{var B,O,W;try{const X=l(j);X&&typeof X.then=="function"?X.then(()=>{var fe,ae;((fe=T.current)==null?void 0:fe.id)===J&&T.current.shouldClear&&(x||(v(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((ae=T.current)==null?void 0:ae.id)===J&&(T.current=null)}).catch(()=>{var fe;((fe=T.current)==null?void 0:fe.id)===J&&(T.current=null)}):(((B=T.current)==null?void 0:B.id)===J&&T.current.shouldClear&&(x||(v(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((O=T.current)==null?void 0:O.id)===J&&(T.current=null))}catch{((W=T.current)==null?void 0:W.id)===J&&(T.current=null)}})},[g,l,h,x,a]),P=w.useCallback(z=>{const j=z.target.value;N(j,{fromUser:!0}),T.current&&(T.current.shouldClear=!1),k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`)},[N]),R=w.useCallback(z=>{z.key==="Enter"&&!z.shiftKey?(z.preventDefault(),_()):z.key==="Escape"&&t&&(z.preventDefault(),c==null||c())},[_,t,c]),A=`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))]":""} ${p}`;return u.jsx("form",{onSubmit:z=>void _(z),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(pc,{ref:k,value:g,onChange:P,onKeyDown:R,placeholder:t?"Edit your message...":n,className:A,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(st,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(ie.Square,{size:16})}):u.jsx(st,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!g.trim()&&!h||b,children:u.jsx(ie.Send,{size:16})})})]})})}const lx=w.memo(hc);function he(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 mc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function xi(...e){return t=>{let n=!1;const r=e.map(o=>{const s=mc(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():mc(e[o],null)}}}}function Ge(...e){return y.useCallback(xi(...e),e)}function cx(e,t){const n=y.createContext(t),r=s=>{const{children:i,...a}=s,l=y.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=y.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 kn(e,t=[]){let n=[];function r(s,i){const a=y.createContext(i),l=n.length;n=[...n,i];const c=f=>{var g;const{scope:p,children:h,...x}=f,m=((g=p==null?void 0:p[e])==null?void 0:g[l])||a,v=y.useMemo(()=>x,Object.values(x));return u.jsx(m.Provider,{value:v,children:h})};c.displayName=s+"Provider";function d(f,p){var m;const h=((m=p==null?void 0:p[e])==null?void 0:m[l])||a,x=y.useContext(h);if(x)return x;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>y.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return y.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,ux(o,...t)]}function ux(...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:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return y.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var _t=globalThis!=null&&globalThis.document?y.useLayoutEffect:()=>{},dx=y[" useInsertionEffect ".trim().toString()]||_t;function gr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=fx({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=y.useRef(e!==void 0);y.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 c=y.useCallback(d=>{var f;if(a){const p=px(d)?d(e):d;p!==e&&((f=i.current)==null||f.call(i,p))}else s(d)},[a,e,s,i]);return[l,c]}function fx({defaultProp:e,onChange:t}){const[n,r]=y.useState(e),o=y.useRef(n),s=y.useRef(t);return dx(()=>{s.current=t},[t]),y.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function px(e){return typeof e=="function"}var hx=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Oe=hx.reduce((e,t)=>{const n=qn.createSlot(`Primitive.${t}`),r=y.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function gc(e,t){e&&go.flushSync(()=>e.dispatchEvent(t))}function yi(e){const t=e+"CollectionProvider",[n,r]=kn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=m=>{const{scope:v,children:g}=m,b=w.useRef(null),S=w.useRef(new Map).current;return u.jsx(o,{scope:v,itemMap:S,collectionRef:b,children:g})};i.displayName=t;const a=e+"CollectionSlot",l=qn.createSlot(a),c=w.forwardRef((m,v)=>{const{scope:g,children:b}=m,S=s(a,g),k=Ge(v,S.collectionRef);return u.jsx(l,{ref:k,children:b})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",p=qn.createSlot(d),h=w.forwardRef((m,v)=>{const{scope:g,children:b,...S}=m,k=w.useRef(null),C=Ge(v,k),T=s(d,g);return w.useEffect(()=>(T.itemMap.set(k,{ref:k,...S}),()=>void T.itemMap.delete(k))),u.jsx(p,{[f]:"",ref:C,children:b})});h.displayName=d;function x(m){const v=s(e+"CollectionConsumer",m);return w.useCallback(()=>{const b=v.collectionRef.current;if(!b)return[];const S=Array.from(b.querySelectorAll(`[${f}]`));return Array.from(v.itemMap.values()).sort((T,E)=>S.indexOf(T.ref.current)-S.indexOf(E.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:i,Slot:c,ItemSlot:h},x,r]}var mx=y.createContext(void 0);function Mo(e){const t=y.useContext(mx);return e||t||"ltr"}function jt(e){const t=y.useRef(e);return y.useEffect(()=>{t.current=e}),y.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function gx(e,t=globalThis==null?void 0:globalThis.document){const n=jt(e);y.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var xx="DismissableLayer",vi="dismissableLayer.update",yx="dismissableLayer.pointerDownOutside",vx="dismissableLayer.focusOutside",xc,yc=y.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Do=y.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=y.useContext(yc),[d,f]=y.useState(null),p=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=y.useState({}),x=Ge(t,E=>f(E)),m=Array.from(c.layers),[v]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),g=m.indexOf(v),b=d?m.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,k=b>=g,C=Sx(E=>{const N=E.target,_=[...c.branches].some(P=>P.contains(N));!k||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},p),T=Cx(E=>{const N=E.target;[...c.branches].some(P=>P.contains(N))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},p);return gx(E=>{b===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},p),y.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(xc=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),vc(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=xc)}},[d,p,n,c]),y.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),vc())},[d,c]),y.useEffect(()=>{const E=()=>h({});return document.addEventListener(vi,E),()=>document.removeEventListener(vi,E)},[]),u.jsx(Oe.div,{...l,ref:x,style:{pointerEvents:S?k?"auto":"none":void 0,...e.style},onFocusCapture:he(e.onFocusCapture,T.onFocusCapture),onBlurCapture:he(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:he(e.onPointerDownCapture,C.onPointerDownCapture)})});Do.displayName=xx;var bx="DismissableLayerBranch",wx=y.forwardRef((e,t)=>{const n=y.useContext(yc),r=y.useRef(null),o=Ge(t,r);return y.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(Oe.div,{...e,ref:o})});wx.displayName=bx;function Sx(e,t=globalThis==null?void 0:globalThis.document){const n=jt(e),r=y.useRef(!1),o=y.useRef(()=>{});return y.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){bc(yx,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Cx(e,t=globalThis==null?void 0:globalThis.document){const n=jt(e),r=y.useRef(!1);return y.useEffect(()=>{const o=s=>{s.target&&!r.current&&bc(vx,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function vc(){const e=new CustomEvent(vi);document.dispatchEvent(e)}function bc(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?gc(o,s):o.dispatchEvent(s)}var bi=0;function wi(){y.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??wc()),document.body.insertAdjacentElement("beforeend",e[1]??wc()),bi++,()=>{bi===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),bi--}},[])}function wc(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Si="focusScope.autoFocusOnMount",Ci="focusScope.autoFocusOnUnmount",Sc={bubbles:!1,cancelable:!0},Tx="FocusScope",Lo=y.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=y.useState(null),c=jt(o),d=jt(s),f=y.useRef(null),p=Ge(t,m=>l(m)),h=y.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;y.useEffect(()=>{if(r){let m=function(S){if(h.paused||!a)return;const k=S.target;a.contains(k)?f.current=k:Rn(f.current,{select:!0})},v=function(S){if(h.paused||!a)return;const k=S.relatedTarget;k!==null&&(a.contains(k)||Rn(f.current,{select:!0}))},g=function(S){if(document.activeElement===document.body)for(const C of S)C.removedNodes.length>0&&Rn(a)};document.addEventListener("focusin",m),document.addEventListener("focusout",v);const b=new MutationObserver(g);return a&&b.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",v),b.disconnect()}}},[r,a,h.paused]),y.useEffect(()=>{if(a){kc.add(h);const m=document.activeElement;if(!a.contains(m)){const g=new CustomEvent(Si,Sc);a.addEventListener(Si,c),a.dispatchEvent(g),g.defaultPrevented||(kx(_x(Cc(a)),{select:!0}),document.activeElement===m&&Rn(a))}return()=>{a.removeEventListener(Si,c),setTimeout(()=>{const g=new CustomEvent(Ci,Sc);a.addEventListener(Ci,d),a.dispatchEvent(g),g.defaultPrevented||Rn(m??document.body,{select:!0}),a.removeEventListener(Ci,d),kc.remove(h)},0)}}},[a,c,d,h]);const x=y.useCallback(m=>{if(!n&&!r||h.paused)return;const v=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,g=document.activeElement;if(v&&g){const b=m.currentTarget,[S,k]=Ex(b);S&&k?!m.shiftKey&&g===k?(m.preventDefault(),n&&Rn(S,{select:!0})):m.shiftKey&&g===S&&(m.preventDefault(),n&&Rn(k,{select:!0})):g===b&&m.preventDefault()}},[n,r,h.paused]);return u.jsx(Oe.div,{tabIndex:-1,...i,ref:p,onKeyDown:x})});Lo.displayName=Tx;function kx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Rn(r,{select:t}),document.activeElement!==n)return}function Ex(e){const t=Cc(e),n=Tc(t,e),r=Tc(t.reverse(),e);return[n,r]}function Cc(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Tc(e,t){for(const n of e)if(!Ix(n,{upTo:t}))return n}function Ix(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Nx(e){return e instanceof HTMLInputElement&&"select"in e}function Rn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Nx(e)&&t&&e.select()}}var kc=Ax();function Ax(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Ec(e,t),e.unshift(t)},remove(t){var n;e=Ec(e,t),(n=e[0])==null||n.resume()}}}function Ec(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function _x(e){return e.filter(t=>t.tagName!=="A")}var jx=y[" useId ".trim().toString()]||(()=>{}),Rx=0;function En(e){const[t,n]=y.useState(jx());return _t(()=>{n(r=>r??String(Rx++))},[e]),t?`radix-${t}`:""}const Px=["top","right","bottom","left"],Pn=Math.min,Kt=Math.max,$o=Math.round,Fo=Math.floor,mn=e=>({x:e,y:e}),Ox={left:"right",right:"left",bottom:"top",top:"bottom"},Mx={start:"end",end:"start"};function Ti(e,t,n){return Kt(e,Pn(t,n))}function In(e,t){return typeof e=="function"?e(t):e}function Nn(e){return e.split("-")[0]}function xr(e){return e.split("-")[1]}function ki(e){return e==="x"?"y":"x"}function Ei(e){return e==="y"?"height":"width"}const Dx=new Set(["top","bottom"]);function gn(e){return Dx.has(Nn(e))?"y":"x"}function Ii(e){return ki(gn(e))}function Lx(e,t,n){n===void 0&&(n=!1);const r=xr(e),o=Ii(e),s=Ei(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=zo(i)),[i,zo(i)]}function $x(e){const t=zo(e);return[Ni(e),t,Ni(t)]}function Ni(e){return e.replace(/start|end/g,t=>Mx[t])}const Ic=["left","right"],Nc=["right","left"],Fx=["top","bottom"],zx=["bottom","top"];function Bx(e,t,n){switch(e){case"top":case"bottom":return n?t?Nc:Ic:t?Ic:Nc;case"left":case"right":return t?Fx:zx;default:return[]}}function Ux(e,t,n,r){const o=xr(e);let s=Bx(Nn(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Ni)))),s}function zo(e){return e.replace(/left|right|bottom|top/g,t=>Ox[t])}function Hx(e){return{top:0,right:0,bottom:0,left:0,...e}}function Ac(e){return typeof e!="number"?Hx(e):{top:e,right:e,bottom:e,left:e}}function Bo(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 _c(e,t,n){let{reference:r,floating:o}=e;const s=gn(t),i=Ii(t),a=Ei(i),l=Nn(t),c=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,p=r[a]/2-o[a]/2;let h;switch(l){case"top":h={x:d,y:r.y-o.height};break;case"bottom":h={x:d,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:f};break;case"left":h={x:r.x-o.width,y:f};break;default:h={x:r.x,y:r.y}}switch(xr(t)){case"start":h[i]-=p*(n&&c?-1:1);break;case"end":h[i]+=p*(n&&c?-1:1);break}return h}const Wx=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 c=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=_c(c,r,l),p=r,h={},x=0;for(let m=0;m<a.length;m++){const{name:v,fn:g}=a[m],{x:b,y:S,data:k,reset:C}=await g({x:d,y:f,initialPlacement:r,placement:p,strategy:o,middlewareData:h,rects:c,platform:i,elements:{reference:e,floating:t}});d=b??d,f=S??f,h={...h,[v]:{...h[v],...k}},C&&x<=50&&(x++,typeof C=="object"&&(C.placement&&(p=C.placement),C.rects&&(c=C.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):C.rects),{x:d,y:f}=_c(c,p,l)),m=-1)}return{x:d,y:f,placement:p,strategy:o,middlewareData:h}};async function zr(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:p=!1,padding:h=0}=In(t,e),x=Ac(h),v=a[p?f==="floating"?"reference":"floating":f],g=Bo(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(v)))==null||n?v:v.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),b=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)),k=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},C=Bo(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:b,offsetParent:S,strategy:l}):b);return{top:(g.top-C.top+x.top)/k.y,bottom:(C.bottom-g.bottom+x.bottom)/k.y,left:(g.left-C.left+x.left)/k.x,right:(C.right-g.right+x.right)/k.x}}const Vx=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:c,padding:d=0}=In(e,t)||{};if(c==null)return{};const f=Ac(d),p={x:n,y:r},h=Ii(o),x=Ei(h),m=await i.getDimensions(c),v=h==="y",g=v?"top":"left",b=v?"bottom":"right",S=v?"clientHeight":"clientWidth",k=s.reference[x]+s.reference[h]-p[h]-s.floating[x],C=p[h]-s.reference[h],T=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=T?T[S]:0;(!E||!await(i.isElement==null?void 0:i.isElement(T)))&&(E=a.floating[S]||s.floating[x]);const N=k/2-C/2,_=E/2-m[x]/2-1,P=Pn(f[g],_),R=Pn(f[b],_),D=P,F=E-m[x]-R,A=E/2-m[x]/2+N,z=Ti(D,A,F),j=!l.arrow&&xr(o)!=null&&A!==z&&s.reference[x]/2-(A<D?P:R)-m[x]/2<0,J=j?A<D?A-D:A-F:0;return{[h]:p[h]+J,data:{[h]:z,centerOffset:A-z-J,...j&&{alignmentOffset:J}},reset:j}}}),Kx=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:c}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:x="none",flipAlignment:m=!0,...v}=In(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const g=Nn(o),b=gn(a),S=Nn(a)===a,k=await(l.isRTL==null?void 0:l.isRTL(c.floating)),C=p||(S||!m?[zo(a)]:$x(a)),T=x!=="none";!p&&T&&C.push(...Ux(a,m,x,k));const E=[a,...C],N=await zr(t,v),_=[];let P=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&_.push(N[g]),f){const A=Lx(o,i,k);_.push(N[A[0]],N[A[1]])}if(P=[...P,{placement:o,overflows:_}],!_.every(A=>A<=0)){var R,D;const A=(((R=s.flip)==null?void 0:R.index)||0)+1,z=E[A];if(z&&(!(f==="alignment"?b!==gn(z):!1)||P.every(B=>gn(B.placement)===b?B.overflows[0]>0:!0)))return{data:{index:A,overflows:P},reset:{placement:z}};let j=(D=P.filter(J=>J.overflows[0]<=0).sort((J,B)=>J.overflows[1]-B.overflows[1])[0])==null?void 0:D.placement;if(!j)switch(h){case"bestFit":{var F;const J=(F=P.filter(B=>{if(T){const O=gn(B.placement);return O===b||O==="y"}return!0}).map(B=>[B.placement,B.overflows.filter(O=>O>0).reduce((O,W)=>O+W,0)]).sort((B,O)=>B[1]-O[1])[0])==null?void 0:F[0];J&&(j=J);break}case"initialPlacement":j=a;break}if(o!==j)return{reset:{placement:j}}}return{}}}};function jc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Rc(e){return Px.some(t=>e[t]>=0)}const qx=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=In(e,t);switch(r){case"referenceHidden":{const s=await zr(t,{...o,elementContext:"reference"}),i=jc(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Rc(i)}}}case"escaped":{const s=await zr(t,{...o,altBoundary:!0}),i=jc(s,n.floating);return{data:{escapedOffsets:i,escaped:Rc(i)}}}default:return{}}}}},Pc=new Set(["left","top"]);async function Gx(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Nn(n),a=xr(n),l=gn(n)==="y",c=Pc.has(i)?-1:1,d=s&&l?-1:1,f=In(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:x}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof x=="number"&&(h=a==="end"?x*-1:x),l?{x:h*d,y:p*c}:{x:p*c,y:h*d}}const Yx=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 Gx(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}}}}},Xx=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:v=>{let{x:g,y:b}=v;return{x:g,y:b}}},...l}=In(e,t),c={x:n,y:r},d=await zr(t,l),f=gn(Nn(o)),p=ki(f);let h=c[p],x=c[f];if(s){const v=p==="y"?"top":"left",g=p==="y"?"bottom":"right",b=h+d[v],S=h-d[g];h=Ti(b,h,S)}if(i){const v=f==="y"?"top":"left",g=f==="y"?"bottom":"right",b=x+d[v],S=x-d[g];x=Ti(b,x,S)}const m=a.fn({...t,[p]:h,[f]:x});return{...m,data:{x:m.x-n,y:m.y-r,enabled:{[p]:s,[f]:i}}}}}},Jx=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:c=!0}=In(e,t),d={x:n,y:r},f=gn(o),p=ki(f);let h=d[p],x=d[f];const m=In(a,t),v=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(l){const S=p==="y"?"height":"width",k=s.reference[p]-s.floating[S]+v.mainAxis,C=s.reference[p]+s.reference[S]-v.mainAxis;h<k?h=k:h>C&&(h=C)}if(c){var g,b;const S=p==="y"?"width":"height",k=Pc.has(Nn(o)),C=s.reference[f]-s.floating[S]+(k&&((g=i.offset)==null?void 0:g[f])||0)+(k?0:v.crossAxis),T=s.reference[f]+s.reference[S]+(k?0:((b=i.offset)==null?void 0:b[f])||0)-(k?v.crossAxis:0);x<C?x=C:x>T&&(x=T)}return{[p]:h,[f]:x}}}},Zx=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=()=>{},...c}=In(e,t),d=await zr(t,c),f=Nn(o),p=xr(o),h=gn(o)==="y",{width:x,height:m}=s.floating;let v,g;f==="top"||f==="bottom"?(v=f,g=p===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(g=f,v=p==="end"?"top":"bottom");const b=m-d.top-d.bottom,S=x-d.left-d.right,k=Pn(m-d[v],b),C=Pn(x-d[g],S),T=!t.middlewareData.shift;let E=k,N=C;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(N=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=b),T&&!p){const P=Kt(d.left,0),R=Kt(d.right,0),D=Kt(d.top,0),F=Kt(d.bottom,0);h?N=x-2*(P!==0||R!==0?P+R:Kt(d.left,d.right)):E=m-2*(D!==0||F!==0?D+F:Kt(d.top,d.bottom))}await l({...t,availableWidth:N,availableHeight:E});const _=await i.getDimensions(a.floating);return x!==_.width||m!==_.height?{reset:{rects:!0}}:{}}}};function Uo(){return typeof window<"u"}function yr(e){return Oc(e)?(e.nodeName||"").toLowerCase():"#document"}function qt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function xn(e){var t;return(t=(Oc(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Oc(e){return Uo()?e instanceof Node||e instanceof qt(e).Node:!1}function ln(e){return Uo()?e instanceof Element||e instanceof qt(e).Element:!1}function yn(e){return Uo()?e instanceof HTMLElement||e instanceof qt(e).HTMLElement:!1}function Mc(e){return!Uo()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof qt(e).ShadowRoot}const Qx=new Set(["inline","contents"]);function Br(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=cn(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!Qx.has(o)}const ey=new Set(["table","td","th"]);function ty(e){return ey.has(yr(e))}const ny=[":popover-open",":modal"];function Ho(e){return ny.some(t=>{try{return e.matches(t)}catch{return!1}})}const ry=["transform","translate","scale","rotate","perspective"],oy=["transform","translate","scale","rotate","perspective","filter"],sy=["paint","layout","strict","content"];function Ai(e){const t=_i(),n=ln(e)?cn(e):e;return ry.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)||oy.some(r=>(n.willChange||"").includes(r))||sy.some(r=>(n.contain||"").includes(r))}function iy(e){let t=On(e);for(;yn(t)&&!vr(t);){if(Ai(t))return t;if(Ho(t))return null;t=On(t)}return null}function _i(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const ay=new Set(["html","body","#document"]);function vr(e){return ay.has(yr(e))}function cn(e){return qt(e).getComputedStyle(e)}function Wo(e){return ln(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function On(e){if(yr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Mc(e)&&e.host||xn(e);return Mc(t)?t.host:t}function Dc(e){const t=On(e);return vr(t)?e.ownerDocument?e.ownerDocument.body:e.body:yn(t)&&Br(t)?t:Dc(t)}function Ur(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Dc(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=qt(o);if(s){const a=ji(i);return t.concat(i,i.visualViewport||[],Br(o)?o:[],a&&n?Ur(a):[])}return t.concat(o,Ur(o,[],n))}function ji(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Lc(e){const t=cn(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=yn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=$o(n)!==s||$o(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function Ri(e){return ln(e)?e:e.contextElement}function br(e){const t=Ri(e);if(!yn(t))return mn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=Lc(t);let i=(s?$o(n.width):n.width)/r,a=(s?$o(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const ly=mn(0);function $c(e){const t=qt(e);return!_i()||!t.visualViewport?ly:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function cy(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==qt(e)?!1:t}function Jn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=Ri(e);let i=mn(1);t&&(r?ln(r)&&(i=br(r)):i=br(e));const a=cy(s,n,r)?$c(s):mn(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const p=qt(s),h=r&&ln(r)?qt(r):r;let x=p,m=ji(x);for(;m&&r&&h!==x;){const v=br(m),g=m.getBoundingClientRect(),b=cn(m),S=g.left+(m.clientLeft+parseFloat(b.paddingLeft))*v.x,k=g.top+(m.clientTop+parseFloat(b.paddingTop))*v.y;l*=v.x,c*=v.y,d*=v.x,f*=v.y,l+=S,c+=k,x=qt(m),m=ji(x)}}return Bo({width:d,height:f,x:l,y:c})}function Vo(e,t){const n=Wo(e).scrollLeft;return t?t.left+n:Jn(xn(e)).left+n}function Fc(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Vo(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function uy(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=xn(r),a=t?Ho(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=mn(1);const d=mn(0),f=yn(r);if((f||!f&&!s)&&((yr(r)!=="body"||Br(i))&&(l=Wo(r)),yn(r))){const h=Jn(r);c=br(r),d.x=h.x+r.clientLeft,d.y=h.y+r.clientTop}const p=i&&!f&&!s?Fc(i,l):mn(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+p.x,y:n.y*c.y-l.scrollTop*c.y+d.y+p.y}}function dy(e){return Array.from(e.getClientRects())}function fy(e){const t=xn(e),n=Wo(e),r=e.ownerDocument.body,o=Kt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Kt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Vo(e);const a=-n.scrollTop;return cn(r).direction==="rtl"&&(i+=Kt(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const zc=25;function py(e,t){const n=qt(e),r=xn(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=_i();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Vo(r);if(c<=0){const d=r.ownerDocument,f=d.body,p=getComputedStyle(f),h=d.compatMode==="CSS1Compat"&&parseFloat(p.marginLeft)+parseFloat(p.marginRight)||0,x=Math.abs(r.clientWidth-f.clientWidth-h);x<=zc&&(s-=x)}else c<=zc&&(s+=c);return{width:s,height:i,x:a,y:l}}const hy=new Set(["absolute","fixed"]);function my(e,t){const n=Jn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=yn(e)?br(e):mn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function Bc(e,t,n){let r;if(t==="viewport")r=py(e,n);else if(t==="document")r=fy(xn(e));else if(ln(t))r=my(t,n);else{const o=$c(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Bo(r)}function Uc(e,t){const n=On(e);return n===t||!ln(n)||vr(n)?!1:cn(n).position==="fixed"||Uc(n,t)}function gy(e,t){const n=t.get(e);if(n)return n;let r=Ur(e,[],!1).filter(a=>ln(a)&&yr(a)!=="body"),o=null;const s=cn(e).position==="fixed";let i=s?On(e):e;for(;ln(i)&&!vr(i);){const a=cn(i),l=Ai(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&hy.has(o.position)||Br(i)&&!l&&Uc(e,i))?r=r.filter(d=>d!==i):o=a,i=On(i)}return t.set(e,r),r}function xy(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Ho(t)?[]:gy(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=Bc(t,d,o);return c.top=Kt(f.top,c.top),c.right=Pn(f.right,c.right),c.bottom=Pn(f.bottom,c.bottom),c.left=Kt(f.left,c.left),c},Bc(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function yy(e){const{width:t,height:n}=Lc(e);return{width:t,height:n}}function vy(e,t,n){const r=yn(t),o=xn(t),s=n==="fixed",i=Jn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=mn(0);function c(){l.x=Vo(o)}if(r||!r&&!s)if((yr(t)!=="body"||Br(o))&&(a=Wo(t)),r){const h=Jn(t,!0,s,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?Fc(o,a):mn(0),f=i.left+a.scrollLeft-l.x-d.x,p=i.top+a.scrollTop-l.y-d.y;return{x:f,y:p,width:i.width,height:i.height}}function Pi(e){return cn(e).position==="static"}function Hc(e,t){if(!yn(e)||cn(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return xn(e)===n&&(n=n.ownerDocument.body),n}function Wc(e,t){const n=qt(e);if(Ho(e))return n;if(!yn(e)){let o=On(e);for(;o&&!vr(o);){if(ln(o)&&!Pi(o))return o;o=On(o)}return n}let r=Hc(e,t);for(;r&&ty(r)&&Pi(r);)r=Hc(r,t);return r&&vr(r)&&Pi(r)&&!Ai(r)?n:r||iy(e)||n}const by=async function(e){const t=this.getOffsetParent||Wc,n=this.getDimensions,r=await n(e.floating);return{reference:vy(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function wy(e){return cn(e).direction==="rtl"}const Sy={convertOffsetParentRelativeRectToViewportRelativeRect:uy,getDocumentElement:xn,getClippingRect:xy,getOffsetParent:Wc,getElementRects:by,getClientRects:dy,getDimensions:yy,getScale:br,isElement:ln,isRTL:wy};function Vc(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Cy(e,t){let n=null,r;const o=xn(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 c=e.getBoundingClientRect(),{left:d,top:f,width:p,height:h}=c;if(a||t(),!p||!h)return;const x=Fo(f),m=Fo(o.clientWidth-(d+p)),v=Fo(o.clientHeight-(f+h)),g=Fo(d),S={rootMargin:-x+"px "+-m+"px "+-v+"px "+-g+"px",threshold:Kt(0,Pn(1,l))||1};let k=!0;function C(T){const E=T[0].intersectionRatio;if(E!==l){if(!k)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!Vc(c,e.getBoundingClientRect())&&i(),k=!1}try{n=new IntersectionObserver(C,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(C,S)}n.observe(e)}return i(!0),s}function Ty(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,c=Ri(e),d=o||s?[...c?Ur(c):[],...Ur(t)]:[];d.forEach(g=>{o&&g.addEventListener("scroll",n,{passive:!0}),s&&g.addEventListener("resize",n)});const f=c&&a?Cy(c,n):null;let p=-1,h=null;i&&(h=new ResizeObserver(g=>{let[b]=g;b&&b.target===c&&h&&(h.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var S;(S=h)==null||S.observe(t)})),n()}),c&&!l&&h.observe(c),h.observe(t));let x,m=l?Jn(e):null;l&&v();function v(){const g=Jn(e);m&&!Vc(m,g)&&n(),m=g,x=requestAnimationFrame(v)}return n(),()=>{var g;d.forEach(b=>{o&&b.removeEventListener("scroll",n),s&&b.removeEventListener("resize",n)}),f==null||f(),(g=h)==null||g.disconnect(),h=null,l&&cancelAnimationFrame(x)}}const ky=Yx,Ey=Xx,Iy=Kx,Ny=Zx,Ay=qx,Kc=Vx,_y=Jx,jy=(e,t,n)=>{const r=new Map,o={platform:Sy,...n},s={...o.platform,_c:r};return Wx(e,t,{...o,platform:s})};var Ry=typeof document<"u",Py=function(){},Ko=Ry?w.useLayoutEffect:Py;function qo(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(!qo(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)&&!qo(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function qc(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Gc(e,t){const n=qc(e);return Math.round(t*n)/n}function Oi(e){const t=y.useRef(e);return Ko(()=>{t.current=e}),t}function Oy(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:c}=e,[d,f]=y.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[p,h]=y.useState(r);qo(p,r)||h(r);const[x,m]=y.useState(null),[v,g]=y.useState(null),b=y.useCallback(B=>{B!==T.current&&(T.current=B,m(B))},[]),S=y.useCallback(B=>{B!==E.current&&(E.current=B,g(B))},[]),k=s||x,C=i||v,T=y.useRef(null),E=y.useRef(null),N=y.useRef(d),_=l!=null,P=Oi(l),R=Oi(o),D=Oi(c),F=y.useCallback(()=>{if(!T.current||!E.current)return;const B={placement:t,strategy:n,middleware:p};R.current&&(B.platform=R.current),jy(T.current,E.current,B).then(O=>{const W={...O,isPositioned:D.current!==!1};A.current&&!qo(N.current,W)&&(N.current=W,go.flushSync(()=>{f(W)}))})},[p,t,n,R,D]);Ko(()=>{c===!1&&N.current.isPositioned&&(N.current.isPositioned=!1,f(B=>({...B,isPositioned:!1})))},[c]);const A=y.useRef(!1);Ko(()=>(A.current=!0,()=>{A.current=!1}),[]),Ko(()=>{if(k&&(T.current=k),C&&(E.current=C),k&&C){if(P.current)return P.current(k,C,F);F()}},[k,C,F,P,_]);const z=y.useMemo(()=>({reference:T,floating:E,setReference:b,setFloating:S}),[b,S]),j=y.useMemo(()=>({reference:k,floating:C}),[k,C]),J=y.useMemo(()=>{const B={position:n,left:0,top:0};if(!j.floating)return B;const O=Gc(j.floating,d.x),W=Gc(j.floating,d.y);return a?{...B,transform:"translate("+O+"px, "+W+"px)",...qc(j.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:O,top:W}},[n,a,j.floating,d.x,d.y]);return y.useMemo(()=>({...d,update:F,refs:z,elements:j,floatingStyles:J}),[d,F,z,j,J])}const My=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?Kc({element:r.current,padding:o}).fn(n):{}:r?Kc({element:r,padding:o}).fn(n):{}}}},Dy=(e,t)=>({...ky(e),options:[e,t]}),Ly=(e,t)=>({...Ey(e),options:[e,t]}),$y=(e,t)=>({..._y(e),options:[e,t]}),Fy=(e,t)=>({...Iy(e),options:[e,t]}),zy=(e,t)=>({...Ny(e),options:[e,t]}),By=(e,t)=>({...Ay(e),options:[e,t]}),Uy=(e,t)=>({...My(e),options:[e,t]});var Hy="Arrow",Yc=y.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(Oe.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});Yc.displayName=Hy;var Wy=Yc;function Xc(e){const[t,n]=y.useState(void 0);return _t(()=>{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,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.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 Mi="Popper",[Jc,Go]=kn(Mi),[Vy,Zc]=Jc(Mi),Qc=e=>{const{__scopePopper:t,children:n}=e,[r,o]=y.useState(null);return u.jsx(Vy,{scope:t,anchor:r,onAnchorChange:o,children:n})};Qc.displayName=Mi;var eu="PopperAnchor",tu=y.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=Zc(eu,n),i=y.useRef(null),a=Ge(t,i),l=y.useRef(null);return y.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||i.current,c!==l.current&&s.onAnchorChange(l.current)}),r?null:u.jsx(Oe.div,{...o,ref:a})});tu.displayName=eu;var Di="PopperContent",[Ky,qy]=Jc(Di),nu=y.forwardRef((e,t)=>{var q,$,V,re,oe,se;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:p=!1,updatePositionStrategy:h="optimized",onPlaced:x,...m}=e,v=Zc(Di,n),[g,b]=y.useState(null),S=Ge(t,Se=>b(Se)),[k,C]=y.useState(null),T=Xc(k),E=(T==null?void 0:T.width)??0,N=(T==null?void 0:T.height)??0,_=r+(s!=="center"?"-"+s:""),P=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},R=Array.isArray(c)?c:[c],D=R.length>0,F={padding:P,boundary:R.filter(Yy),altBoundary:D},{refs:A,floatingStyles:z,placement:j,isPositioned:J,middlewareData:B}=Oy({strategy:"fixed",placement:_,whileElementsMounted:(...Se)=>Ty(...Se,{animationFrame:h==="always"}),elements:{reference:v.anchor},middleware:[Dy({mainAxis:o+N,alignmentAxis:i}),l&&Ly({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?$y():void 0,...F}),l&&Fy({...F}),zy({...F,apply:({elements:Se,rects:Qe,availableWidth:Fe,availableHeight:Xe})=>{const{width:nt,height:de}=Qe.reference,me=Se.floating.style;me.setProperty("--radix-popper-available-width",`${Fe}px`),me.setProperty("--radix-popper-available-height",`${Xe}px`),me.setProperty("--radix-popper-anchor-width",`${nt}px`),me.setProperty("--radix-popper-anchor-height",`${de}px`)}}),k&&Uy({element:k,padding:a}),Xy({arrowWidth:E,arrowHeight:N}),p&&By({strategy:"referenceHidden",...F})]}),[O,W]=su(j),X=jt(x);_t(()=>{J&&(X==null||X())},[J,X]);const fe=(q=B.arrow)==null?void 0:q.x,ae=($=B.arrow)==null?void 0:$.y,Re=((V=B.arrow)==null?void 0:V.centerOffset)!==0,[G,U]=y.useState();return _t(()=>{g&&U(window.getComputedStyle(g).zIndex)},[g]),u.jsx("div",{ref:A.setFloating,"data-radix-popper-content-wrapper":"",style:{...z,transform:J?z.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:G,"--radix-popper-transform-origin":[(re=B.transformOrigin)==null?void 0:re.x,(oe=B.transformOrigin)==null?void 0:oe.y].join(" "),...((se=B.hide)==null?void 0:se.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(Ky,{scope:n,placedSide:O,onArrowChange:C,arrowX:fe,arrowY:ae,shouldHideArrow:Re,children:u.jsx(Oe.div,{"data-side":O,"data-align":W,...m,ref:S,style:{...m.style,animation:J?void 0:"none"}})})})});nu.displayName=Di;var ru="PopperArrow",Gy={top:"bottom",right:"left",bottom:"top",left:"right"},ou=y.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=qy(ru,r),i=Gy[s.placedSide];return u.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:u.jsx(Wy,{...o,ref:n,style:{...o.style,display:"block"}})})});ou.displayName=ru;function Yy(e){return e!==null}var Xy=e=>({name:"transformOrigin",options:e,fn(t){var v,g,b;const{placement:n,rects:r,middlewareData:o}=t,i=((v=o.arrow)==null?void 0:v.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,d]=su(n),f={start:"0%",center:"50%",end:"100%"}[d],p=(((g=o.arrow)==null?void 0:g.x)??0)+a/2,h=(((b=o.arrow)==null?void 0:b.y)??0)+l/2;let x="",m="";return c==="bottom"?(x=i?f:`${p}px`,m=`${-l}px`):c==="top"?(x=i?f:`${p}px`,m=`${r.floating.height+l}px`):c==="right"?(x=`${-l}px`,m=i?f:`${h}px`):c==="left"&&(x=`${r.floating.width+l}px`,m=i?f:`${h}px`),{data:{x,y:m}}}});function su(e){const[t,n="center"]=e.split("-");return[t,n]}var iu=Qc,au=tu,lu=nu,cu=ou,Jy="Portal",Yo=y.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=y.useState(!1);_t(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Ys.createPortal(u.jsx(Oe.div,{...r,ref:t}),i):null});Yo.displayName=Jy;function Zy(e,t){return y.useReducer((n,r)=>t[n][r]??n,e)}var Qt=e=>{const{present:t,children:n}=e,r=Qy(t),o=typeof n=="function"?n({present:r.isPresent}):y.Children.only(n),s=Ge(r.ref,ev(o));return typeof n=="function"||r.isPresent?y.cloneElement(o,{ref:s}):null};Qt.displayName="Presence";function Qy(e){const[t,n]=y.useState(),r=y.useRef(null),o=y.useRef(e),s=y.useRef("none"),i=e?"mounted":"unmounted",[a,l]=Zy(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return y.useEffect(()=>{const c=Xo(r.current);s.current=a==="mounted"?c:"none"},[a]),_t(()=>{const c=r.current,d=o.current;if(d!==e){const p=s.current,h=Xo(c);e?l("MOUNT"):h==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&p!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),_t(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=h=>{const m=Xo(r.current).includes(CSS.escape(h.animationName));if(h.target===t&&m&&(l("ANIMATION_END"),!o.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},p=h=>{h.target===t&&(s.current=Xo(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:y.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Xo(e){return(e==null?void 0:e.animationName)||"none"}function ev(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 Li="rovingFocusGroup.onEntryFocus",tv={bubbles:!1,cancelable:!0},Hr="RovingFocusGroup",[$i,uu,nv]=yi(Hr),[rv,du]=kn(Hr,[nv]),[ov,sv]=rv(Hr),fu=y.forwardRef((e,t)=>u.jsx($i.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx($i.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(iv,{...e,ref:t})})}));fu.displayName=Hr;var iv=y.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...f}=e,p=y.useRef(null),h=Ge(t,p),x=Mo(s),[m,v]=gr({prop:i,defaultProp:a??null,onChange:l,caller:Hr}),[g,b]=y.useState(!1),S=jt(c),k=uu(n),C=y.useRef(!1),[T,E]=y.useState(0);return y.useEffect(()=>{const N=p.current;if(N)return N.addEventListener(Li,S),()=>N.removeEventListener(Li,S)},[S]),u.jsx(ov,{scope:n,orientation:r,dir:x,loop:o,currentTabStopId:m,onItemFocus:y.useCallback(N=>v(N),[v]),onItemShiftTab:y.useCallback(()=>b(!0),[]),onFocusableItemAdd:y.useCallback(()=>E(N=>N+1),[]),onFocusableItemRemove:y.useCallback(()=>E(N=>N-1),[]),children:u.jsx(Oe.div,{tabIndex:g||T===0?-1:0,"data-orientation":r,...f,ref:h,style:{outline:"none",...e.style},onMouseDown:he(e.onMouseDown,()=>{C.current=!0}),onFocus:he(e.onFocus,N=>{const _=!C.current;if(N.target===N.currentTarget&&_&&!g){const P=new CustomEvent(Li,tv);if(N.currentTarget.dispatchEvent(P),!P.defaultPrevented){const R=k().filter(j=>j.focusable),D=R.find(j=>j.active),F=R.find(j=>j.id===m),z=[D,F,...R].filter(Boolean).map(j=>j.ref.current);mu(z,d)}}C.current=!1}),onBlur:he(e.onBlur,()=>b(!1))})})}),pu="RovingFocusGroupItem",hu=y.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=En(),c=s||l,d=sv(pu,n),f=d.currentTabStopId===c,p=uu(n),{onFocusableItemAdd:h,onFocusableItemRemove:x,currentTabStopId:m}=d;return y.useEffect(()=>{if(r)return h(),()=>x()},[r,h,x]),u.jsx($i.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(Oe.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:he(e.onMouseDown,v=>{r?d.onItemFocus(c):v.preventDefault()}),onFocus:he(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:he(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){d.onItemShiftTab();return}if(v.target!==v.currentTarget)return;const g=cv(v,d.orientation,d.dir);if(g!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let S=p().filter(k=>k.focusable).map(k=>k.ref.current);if(g==="last")S.reverse();else if(g==="prev"||g==="next"){g==="prev"&&S.reverse();const k=S.indexOf(v.currentTarget);S=d.loop?uv(S,k+1):S.slice(k+1)}setTimeout(()=>mu(S))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:m!=null}):i})})});hu.displayName=pu;var av={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function lv(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function cv(e,t,n){const r=lv(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return av[r]}function mu(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function uv(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var dv=fu,fv=hu,pv=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},wr=new WeakMap,Jo=new WeakMap,Zo={},Fi=0,gu=function(e){return e&&(e.host||gu(e.parentNode))},hv=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=gu(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},mv=function(e,t,n,r){var o=hv(t,Array.isArray(e)?e:[e]);Zo[n]||(Zo[n]=new WeakMap);var s=Zo[n],i=[],a=new Set,l=new Set(o),c=function(f){!f||a.has(f)||(a.add(f),c(f.parentNode))};o.forEach(c);var d=function(f){!f||l.has(f)||Array.prototype.forEach.call(f.children,function(p){if(a.has(p))d(p);else try{var h=p.getAttribute(r),x=h!==null&&h!=="false",m=(wr.get(p)||0)+1,v=(s.get(p)||0)+1;wr.set(p,m),s.set(p,v),i.push(p),m===1&&x&&Jo.set(p,!0),v===1&&p.setAttribute(n,"true"),x||p.setAttribute(r,"true")}catch(g){console.error("aria-hidden: cannot operate on ",p,g)}})};return d(t),a.clear(),Fi++,function(){i.forEach(function(f){var p=wr.get(f)-1,h=s.get(f)-1;wr.set(f,p),s.set(f,h),p||(Jo.has(f)||f.removeAttribute(r),Jo.delete(f)),h||f.removeAttribute(n)}),Fi--,Fi||(wr=new WeakMap,wr=new WeakMap,Jo=new WeakMap,Zo={})}},zi=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=pv(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),mv(r,o,n,"aria-hidden")):function(){return null}},vn=function(){return vn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},vn.apply(this,arguments)};function xu(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function gv(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var Qo="right-scroll-bar-position",es="width-before-scroll-bar",xv="with-scroll-bars-hidden",yv="--removed-body-scroll-bar-size";function Bi(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function vv(e,t){var n=w.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var bv=typeof window<"u"?y.useLayoutEffect:y.useEffect,yu=new WeakMap;function wv(e,t){var n=vv(null,function(r){return e.forEach(function(o){return Bi(o,r)})});return bv(function(){var r=yu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Bi(a,null)}),s.forEach(function(a){o.has(a)||Bi(a,i)})}yu.set(n,e)},[e]),n}function Sv(e){return e}function Cv(e,t){t===void 0&&(t=Sv);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function Tv(e){e===void 0&&(e={});var t=Cv(null);return t.options=vn({async:!0,ssr:!1},e),t}var vu=function(e){var t=e.sideCar,n=xu(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return y.createElement(r,vn({},n))};vu.isSideCarExport=!0;function kv(e,t){return e.useMedium(t),vu}var bu=Tv(),Ui=function(){},ts=y.forwardRef(function(e,t){var n=y.useRef(null),r=y.useState({onScrollCapture:Ui,onWheelCapture:Ui,onTouchMoveCapture:Ui}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,p=e.sideCar,h=e.noRelative,x=e.noIsolation,m=e.inert,v=e.allowPinchZoom,g=e.as,b=g===void 0?"div":g,S=e.gapMode,k=xu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=p,T=wv([n,t]),E=vn(vn({},k),o);return y.createElement(y.Fragment,null,d&&y.createElement(C,{sideCar:bu,removeScrollBar:c,shards:f,noRelative:h,noIsolation:x,inert:m,setCallbacks:s,allowPinchZoom:!!v,lockRef:n,gapMode:S}),i?y.cloneElement(y.Children.only(a),vn(vn({},E),{ref:T})):y.createElement(b,vn({},E,{className:l,ref:T}),a))});ts.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},ts.classNames={fullWidth:es,zeroRight:Qo};var Ev=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Iv(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Ev();return t&&e.setAttribute("nonce",t),e}function Nv(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Av(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var _v=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Iv())&&(Nv(t,n),Av(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},jv=function(){var e=_v();return function(t,n){y.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},wu=function(){var e=jv(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Rv={left:0,top:0,right:0,gap:0},Hi=function(e){return parseInt(e||"",10)||0},Pv=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Hi(n),Hi(r),Hi(o)]},Ov=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Rv;var t=Pv(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Mv=wu(),Sr="data-scroll-locked",Dv=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
39
39
  .`.concat(xv,` {
40
40
  overflow: hidden `).concat(r,`;
41
41
  padding-right: `).concat(a,"px ").concat(r,`;
@@ -75,7 +75,7 @@ React keys must be passed directly to JSX without using spread:
75
75
  `)},Su=function(){var e=parseInt(document.body.getAttribute(Sr)||"0",10);return isFinite(e)?e:0},Lv=function(){y.useEffect(function(){return document.body.setAttribute(Sr,(Su()+1).toString()),function(){var e=Su()-1;e<=0?document.body.removeAttribute(Sr):document.body.setAttribute(Sr,e.toString())}},[])},$v=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;Lv();var s=y.useMemo(function(){return Ov(o)},[o]);return y.createElement(Mv,{styles:Dv(s,!t,o,n?"":"!important")})},Wi=!1;if(typeof window<"u")try{var ns=Object.defineProperty({},"passive",{get:function(){return Wi=!0,!0}});window.addEventListener("test",ns,ns),window.removeEventListener("test",ns,ns)}catch{Wi=!1}var Cr=Wi?{passive:!1}:!1,Fv=function(e){return e.tagName==="TEXTAREA"},Cu=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Fv(e)&&n[t]==="visible")},zv=function(e){return Cu(e,"overflowY")},Bv=function(e){return Cu(e,"overflowX")},Tu=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=ku(e,r);if(o){var s=Eu(e,r),i=s[1],a=s[2];if(i>a)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Uv=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},Hv=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},ku=function(e,t){return e==="v"?zv(t):Bv(t)},Eu=function(e,t){return e==="v"?Uv(t):Hv(t)},Wv=function(e,t){return e==="h"&&t==="rtl"?-1:1},Vv=function(e,t,n,r,o){var s=Wv(e,window.getComputedStyle(t).direction),i=s*r,a=n.target,l=t.contains(a),c=!1,d=i>0,f=0,p=0;do{if(!a)break;var h=Eu(e,a),x=h[0],m=h[1],v=h[2],g=m-v-s*x;(x||g)&&ku(e,a)&&(f+=g,p+=x);var b=a.parentNode;a=b&&b.nodeType===Node.DOCUMENT_FRAGMENT_NODE?b.host:b}while(!l&&a!==document.body||l&&(t.contains(a)||t===a));return(d&&Math.abs(f)<1||!d&&Math.abs(p)<1)&&(c=!0),c},rs=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Iu=function(e){return[e.deltaX,e.deltaY]},Nu=function(e){return e&&"current"in e?e.current:e},Kv=function(e,t){return e[0]===t[0]&&e[1]===t[1]},qv=function(e){return`
76
76
  .block-interactivity-`.concat(e,` {pointer-events: none;}
77
77
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
78
- `)},Gv=0,Tr=[];function Yv(e){var t=y.useRef([]),n=y.useRef([0,0]),r=y.useRef(),o=y.useState(Gv++)[0],s=y.useState(wu)[0],i=y.useRef(e);y.useEffect(function(){i.current=e},[e]),y.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var m=gv([e.lockRef.current],(e.shards||[]).map(Nu),!0).filter(Boolean);return m.forEach(function(v){return v.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),m.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var a=y.useCallback(function(m,v){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!i.current.allowPinchZoom;var g=rs(m),b=n.current,S="deltaX"in m?m.deltaX:b[0]-g[0],k="deltaY"in m?m.deltaY:b[1]-g[1],C,T=m.target,E=Math.abs(S)>Math.abs(k)?"h":"v";if("touches"in m&&E==="h"&&T.type==="range")return!1;var N=Tu(E,T);if(!N)return!0;if(N?C=E:(C=E==="v"?"h":"v",N=Tu(E,T)),!N)return!1;if(!r.current&&"changedTouches"in m&&(S||k)&&(r.current=C),!C)return!0;var _=r.current||C;return Vv(_,v,m,_==="h"?S:k)},[]),l=y.useCallback(function(m){var v=m;if(!(!Tr.length||Tr[Tr.length-1]!==s)){var g="deltaY"in v?Iu(v):rs(v),b=t.current.filter(function(C){return C.name===v.type&&(C.target===v.target||v.target===C.shadowParent)&&Kv(C.delta,g)})[0];if(b&&b.should){v.cancelable&&v.preventDefault();return}if(!b){var S=(i.current.shards||[]).map(Nu).filter(Boolean).filter(function(C){return C.contains(v.target)}),k=S.length>0?a(v,S[0]):!i.current.noIsolation;k&&v.cancelable&&v.preventDefault()}}},[]),c=y.useCallback(function(m,v,g,b){var S={name:m,delta:v,target:g,should:b,shadowParent:Xv(g)};t.current.push(S),setTimeout(function(){t.current=t.current.filter(function(k){return k!==S})},1)},[]),d=y.useCallback(function(m){n.current=rs(m),r.current=void 0},[]),f=y.useCallback(function(m){c(m.type,Iu(m),m.target,a(m,e.lockRef.current))},[]),p=y.useCallback(function(m){c(m.type,rs(m),m.target,a(m,e.lockRef.current))},[]);y.useEffect(function(){return Tr.push(s),e.setCallbacks({onScrollCapture:f,onWheelCapture:f,onTouchMoveCapture:p}),document.addEventListener("wheel",l,Cr),document.addEventListener("touchmove",l,Cr),document.addEventListener("touchstart",d,Cr),function(){Tr=Tr.filter(function(m){return m!==s}),document.removeEventListener("wheel",l,Cr),document.removeEventListener("touchmove",l,Cr),document.removeEventListener("touchstart",d,Cr)}},[]);var h=e.removeScrollBar,x=e.inert;return y.createElement(y.Fragment,null,x?y.createElement(s,{styles:qv(o)}):null,h?y.createElement($v,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Xv(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Jv=kv(bu,Yv);var os=y.forwardRef(function(e,t){return y.createElement(ts,vn({},e,{ref:t,sideCar:Jv}))});os.classNames=ts.classNames;var Vi=["Enter"," "],Zv=["ArrowDown","PageUp","Home"],Au=["ArrowUp","PageDown","End"],Qv=[...Zv,...Au],eb={ltr:[...Vi,"ArrowRight"],rtl:[...Vi,"ArrowLeft"]},tb={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Wr="Menu",[Vr,nb,rb]=yi(Wr),[Zn,_u]=kn(Wr,[rb,Go,du]),ss=Go(),ju=du(),[ob,Qn]=Zn(Wr),[sb,Kr]=Zn(Wr),Ru=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:s,modal:i=!0}=e,a=ss(t),[l,c]=y.useState(null),d=y.useRef(!1),f=jt(s),p=Mo(o);return y.useEffect(()=>{const h=()=>{d.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>d.current=!1;return document.addEventListener("keydown",h,{capture:!0}),()=>{document.removeEventListener("keydown",h,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),u.jsx(iu,{...a,children:u.jsx(ob,{scope:t,open:n,onOpenChange:f,content:l,onContentChange:c,children:u.jsx(sb,{scope:t,onClose:y.useCallback(()=>f(!1),[f]),isUsingKeyboardRef:d,dir:p,modal:i,children:r})})})};Ru.displayName=Wr;var ib="MenuAnchor",Ki=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ss(n);return u.jsx(au,{...o,...r,ref:t})});Ki.displayName=ib;var qi="MenuPortal",[ab,Pu]=Zn(qi,{forceMount:void 0}),Ou=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,s=Qn(qi,t);return u.jsx(ab,{scope:t,forceMount:n,children:u.jsx(Qt,{present:n||s.open,children:u.jsx(Yo,{asChild:!0,container:o,children:r})})})};Ou.displayName=qi;var en="MenuContent",[lb,Gi]=Zn(en),Mu=y.forwardRef((e,t)=>{const n=Pu(en,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Qn(en,e.__scopeMenu),i=Kr(en,e.__scopeMenu);return u.jsx(Vr.Provider,{scope:e.__scopeMenu,children:u.jsx(Qt,{present:r||s.open,children:u.jsx(Vr.Slot,{scope:e.__scopeMenu,children:i.modal?u.jsx(cb,{...o,ref:t}):u.jsx(ub,{...o,ref:t})})})})}),cb=y.forwardRef((e,t)=>{const n=Qn(en,e.__scopeMenu),r=y.useRef(null),o=Ge(t,r);return y.useEffect(()=>{const s=r.current;if(s)return zi(s)},[]),u.jsx(Yi,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:me(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),ub=y.forwardRef((e,t)=>{const n=Qn(en,e.__scopeMenu);return u.jsx(Yi,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),db=qn.createSlot("MenuContent.ScrollLock"),Yi=y.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:p,onDismiss:h,disableOutsideScroll:x,...m}=e,v=Qn(en,n),g=Kr(en,n),b=ss(n),S=ju(n),k=nb(n),[C,T]=y.useState(null),E=y.useRef(null),N=Ge(t,E,v.onContentChange),_=y.useRef(0),P=y.useRef(""),R=y.useRef(0),D=y.useRef(null),F=y.useRef("right"),A=y.useRef(0),z=x?os:y.Fragment,j=x?{as:db,allowPinchZoom:!0}:void 0,J=O=>{var q,$;const W=P.current+O,X=k().filter(V=>!V.disabled),he=document.activeElement,ae=(q=X.find(V=>V.ref.current===he))==null?void 0:q.textValue,Re=X.map(V=>V.textValue),G=Cb(Re,W,ae),U=($=X.find(V=>V.textValue===G))==null?void 0:$.ref.current;(function V(re){P.current=re,window.clearTimeout(_.current),re!==""&&(_.current=window.setTimeout(()=>V(""),1e3))})(W),U&&setTimeout(()=>U.focus())};y.useEffect(()=>()=>window.clearTimeout(_.current),[]),wi();const B=y.useCallback(O=>{var X,he;return F.current===((X=D.current)==null?void 0:X.side)&&kb(O,(he=D.current)==null?void 0:he.area)},[]);return u.jsx(lb,{scope:n,searchRef:P,onItemEnter:y.useCallback(O=>{B(O)&&O.preventDefault()},[B]),onItemLeave:y.useCallback(O=>{var W;B(O)||((W=E.current)==null||W.focus(),T(null))},[B]),onTriggerLeave:y.useCallback(O=>{B(O)&&O.preventDefault()},[B]),pointerGraceTimerRef:R,onPointerGraceIntentChange:y.useCallback(O=>{D.current=O},[]),children:u.jsx(z,{...j,children:u.jsx(Lo,{asChild:!0,trapped:o,onMountAutoFocus:me(s,O=>{var W;O.preventDefault(),(W=E.current)==null||W.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:u.jsx(Do,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:p,onDismiss:h,children:u.jsx(dv,{asChild:!0,...S,dir:g.dir,orientation:"vertical",loop:r,currentTabStopId:C,onCurrentTabStopIdChange:T,onEntryFocus:me(l,O=>{g.isUsingKeyboardRef.current||O.preventDefault()}),preventScrollOnEntryFocus:!0,children:u.jsx(lu,{role:"menu","aria-orientation":"vertical","data-state":Zu(v.open),"data-radix-menu-content":"",dir:g.dir,...b,...m,ref:N,style:{outline:"none",...m.style},onKeyDown:me(m.onKeyDown,O=>{const X=O.target.closest("[data-radix-menu-content]")===O.currentTarget,he=O.ctrlKey||O.altKey||O.metaKey,ae=O.key.length===1;X&&(O.key==="Tab"&&O.preventDefault(),!he&&ae&&J(O.key));const Re=E.current;if(O.target!==Re||!Qv.includes(O.key))return;O.preventDefault();const U=k().filter(q=>!q.disabled).map(q=>q.ref.current);Au.includes(O.key)&&U.reverse(),wb(U)}),onBlur:me(e.onBlur,O=>{O.currentTarget.contains(O.target)||(window.clearTimeout(_.current),P.current="")}),onPointerMove:me(e.onPointerMove,Gr(O=>{const W=O.target,X=A.current!==O.clientX;if(O.currentTarget.contains(W)&&X){const he=O.clientX>A.current?"right":"left";F.current=he,A.current=O.clientX}}))})})})})})})});Mu.displayName=en;var fb="MenuGroup",Xi=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Oe.div,{role:"group",...r,ref:t})});Xi.displayName=fb;var pb="MenuLabel",Du=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Oe.div,{...r,ref:t})});Du.displayName=pb;var is="MenuItem",Lu="menu.itemSelect",as=y.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,s=y.useRef(null),i=Kr(is,e.__scopeMenu),a=Gi(is,e.__scopeMenu),l=Ge(t,s),c=y.useRef(!1),d=()=>{const f=s.current;if(!n&&f){const p=new CustomEvent(Lu,{bubbles:!0,cancelable:!0});f.addEventListener(Lu,h=>r==null?void 0:r(h),{once:!0}),gc(f,p),p.defaultPrevented?c.current=!1:i.onClose()}};return u.jsx($u,{...o,ref:l,disabled:n,onClick:me(e.onClick,d),onPointerDown:f=>{var p;(p=e.onPointerDown)==null||p.call(e,f),c.current=!0},onPointerUp:me(e.onPointerUp,f=>{var p;c.current||(p=f.currentTarget)==null||p.click()}),onKeyDown:me(e.onKeyDown,f=>{const p=a.searchRef.current!=="";n||p&&f.key===" "||Vi.includes(f.key)&&(f.currentTarget.click(),f.preventDefault())})})});as.displayName=is;var $u=y.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...s}=e,i=Gi(is,n),a=ju(n),l=y.useRef(null),c=Ge(t,l),[d,f]=y.useState(!1),[p,h]=y.useState("");return y.useEffect(()=>{const x=l.current;x&&h((x.textContent??"").trim())},[s.children]),u.jsx(Vr.ItemSlot,{scope:n,disabled:r,textValue:o??p,children:u.jsx(fv,{asChild:!0,...a,focusable:!r,children:u.jsx(Oe.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:c,onPointerMove:me(e.onPointerMove,Gr(x=>{r?i.onItemLeave(x):(i.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:me(e.onPointerLeave,Gr(x=>i.onItemLeave(x))),onFocus:me(e.onFocus,()=>f(!0)),onBlur:me(e.onBlur,()=>f(!1))})})})}),hb="MenuCheckboxItem",Fu=y.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return u.jsx(Wu,{scope:e.__scopeMenu,checked:n,children:u.jsx(as,{role:"menuitemcheckbox","aria-checked":ls(n)?"mixed":n,...o,ref:t,"data-state":Zi(n),onSelect:me(o.onSelect,()=>r==null?void 0:r(ls(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Fu.displayName=hb;var zu="MenuRadioGroup",[mb,gb]=Zn(zu,{value:void 0,onValueChange:()=>{}}),Bu=y.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,s=jt(r);return u.jsx(mb,{scope:e.__scopeMenu,value:n,onValueChange:s,children:u.jsx(Xi,{...o,ref:t})})});Bu.displayName=zu;var Uu="MenuRadioItem",Hu=y.forwardRef((e,t)=>{const{value:n,...r}=e,o=gb(Uu,e.__scopeMenu),s=n===o.value;return u.jsx(Wu,{scope:e.__scopeMenu,checked:s,children:u.jsx(as,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":Zi(s),onSelect:me(r.onSelect,()=>{var i;return(i=o.onValueChange)==null?void 0:i.call(o,n)},{checkForDefaultPrevented:!1})})})});Hu.displayName=Uu;var Ji="MenuItemIndicator",[Wu,xb]=Zn(Ji,{checked:!1}),Vu=y.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,s=xb(Ji,n);return u.jsx(Qt,{present:r||ls(s.checked)||s.checked===!0,children:u.jsx(Oe.span,{...o,ref:t,"data-state":Zi(s.checked)})})});Vu.displayName=Ji;var yb="MenuSeparator",Ku=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Oe.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Ku.displayName=yb;var vb="MenuArrow",qu=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ss(n);return u.jsx(cu,{...o,...r,ref:t})});qu.displayName=vb;var bb="MenuSub",[OT,Gu]=Zn(bb),qr="MenuSubTrigger",Yu=y.forwardRef((e,t)=>{const n=Qn(qr,e.__scopeMenu),r=Kr(qr,e.__scopeMenu),o=Gu(qr,e.__scopeMenu),s=Gi(qr,e.__scopeMenu),i=y.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=s,c={__scopeMenu:e.__scopeMenu},d=y.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return y.useEffect(()=>d,[d]),y.useEffect(()=>{const f=a.current;return()=>{window.clearTimeout(f),l(null)}},[a,l]),u.jsx(Ki,{asChild:!0,...c,children:u.jsx($u,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":Zu(n.open),...e,ref:xi(t,o.onTriggerChange),onClick:f=>{var p;(p=e.onClick)==null||p.call(e,f),!(e.disabled||f.defaultPrevented)&&(f.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:me(e.onPointerMove,Gr(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:me(e.onPointerLeave,Gr(f=>{var h,x;d();const p=(h=n.content)==null?void 0:h.getBoundingClientRect();if(p){const m=(x=n.content)==null?void 0:x.dataset.side,v=m==="right",g=v?-5:5,b=p[v?"left":"right"],S=p[v?"right":"left"];s.onPointerGraceIntentChange({area:[{x:f.clientX+g,y:f.clientY},{x:b,y:p.top},{x:S,y:p.top},{x:S,y:p.bottom},{x:b,y:p.bottom}],side:m}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(f),f.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:me(e.onKeyDown,f=>{var h;const p=s.searchRef.current!=="";e.disabled||p&&f.key===" "||eb[r.dir].includes(f.key)&&(n.onOpenChange(!0),(h=n.content)==null||h.focus(),f.preventDefault())})})})});Yu.displayName=qr;var Xu="MenuSubContent",Ju=y.forwardRef((e,t)=>{const n=Pu(en,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Qn(en,e.__scopeMenu),i=Kr(en,e.__scopeMenu),a=Gu(Xu,e.__scopeMenu),l=y.useRef(null),c=Ge(t,l);return u.jsx(Vr.Provider,{scope:e.__scopeMenu,children:u.jsx(Qt,{present:r||s.open,children:u.jsx(Vr.Slot,{scope:e.__scopeMenu,children:u.jsx(Yi,{id:a.contentId,"aria-labelledby":a.triggerId,...o,ref:c,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:me(e.onFocusOutside,d=>{d.target!==a.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:me(e.onEscapeKeyDown,d=>{i.onClose(),d.preventDefault()}),onKeyDown:me(e.onKeyDown,d=>{var h;const f=d.currentTarget.contains(d.target),p=tb[i.dir].includes(d.key);f&&p&&(s.onOpenChange(!1),(h=a.trigger)==null||h.focus(),d.preventDefault())})})})})})});Ju.displayName=Xu;function Zu(e){return e?"open":"closed"}function ls(e){return e==="indeterminate"}function Zi(e){return ls(e)?"indeterminate":e?"checked":"unchecked"}function wb(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Sb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Cb(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=Sb(e,Math.max(s,0));o.length===1&&(i=i.filter(c=>c!==n));const l=i.find(c=>c.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function Tb(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],c=a.x,d=a.y,f=l.x,p=l.y;d>r!=p>r&&n<(f-c)*(r-d)/(p-d)+c&&(o=!o)}return o}function kb(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Tb(n,t)}function Gr(e){return t=>t.pointerType==="mouse"?e(t):void 0}var Eb=Ru,Ib=Ki,Nb=Ou,Ab=Mu,_b=Xi,jb=Du,Rb=as,Pb=Fu,Ob=Bu,Mb=Hu,Db=Vu,Lb=Ku,$b=qu,Fb=Yu,zb=Ju,cs="DropdownMenu",[Bb,MT]=kn(cs,[_u]),$t=_u(),[Ub,Qu]=Bb(cs),ed=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:s,onOpenChange:i,modal:a=!0}=e,l=$t(t),c=y.useRef(null),[d,f]=gr({prop:o,defaultProp:s??!1,onChange:i,caller:cs});return u.jsx(Ub,{scope:t,triggerId:En(),triggerRef:c,contentId:En(),open:d,onOpenChange:f,onOpenToggle:y.useCallback(()=>f(p=>!p),[f]),modal:a,children:u.jsx(Eb,{...l,open:d,onOpenChange:f,dir:r,modal:a,children:n})})};ed.displayName=cs;var td="DropdownMenuTrigger",nd=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,s=Qu(td,n),i=$t(n);return u.jsx(Ib,{asChild:!0,...i,children:u.jsx(Oe.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:xi(t,s.triggerRef),onPointerDown:me(e.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(s.onOpenToggle(),s.open||a.preventDefault())}),onKeyDown:me(e.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&s.onOpenToggle(),a.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});nd.displayName=td;var Hb="DropdownMenuPortal",rd=e=>{const{__scopeDropdownMenu:t,...n}=e,r=$t(t);return u.jsx(Nb,{...r,...n})};rd.displayName=Hb;var od="DropdownMenuContent",sd=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Qu(od,n),s=$t(n),i=y.useRef(!1);return u.jsx(Ab,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...r,ref:t,onCloseAutoFocus:me(e.onCloseAutoFocus,a=>{var l;i.current||(l=o.triggerRef.current)==null||l.focus(),i.current=!1,a.preventDefault()}),onInteractOutside:me(e.onInteractOutside,a=>{const l=a.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,d=l.button===2||c;(!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)"}})});sd.displayName=od;var Wb="DropdownMenuGroup",Vb=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(_b,{...o,...r,ref:t})});Vb.displayName=Wb;var Kb="DropdownMenuLabel",id=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(jb,{...o,...r,ref:t})});id.displayName=Kb;var qb="DropdownMenuItem",ad=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(Rb,{...o,...r,ref:t})});ad.displayName=qb;var Gb="DropdownMenuCheckboxItem",ld=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(Pb,{...o,...r,ref:t})});ld.displayName=Gb;var Yb="DropdownMenuRadioGroup",Xb=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(Ob,{...o,...r,ref:t})});Xb.displayName=Yb;var Jb="DropdownMenuRadioItem",cd=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(Mb,{...o,...r,ref:t})});cd.displayName=Jb;var Zb="DropdownMenuItemIndicator",ud=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(Db,{...o,...r,ref:t})});ud.displayName=Zb;var Qb="DropdownMenuSeparator",dd=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(Lb,{...o,...r,ref:t})});dd.displayName=Qb;var ew="DropdownMenuArrow",tw=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx($b,{...o,...r,ref:t})});tw.displayName=ew;var nw="DropdownMenuSubTrigger",fd=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(Fb,{...o,...r,ref:t})});fd.displayName=nw;var rw="DropdownMenuSubContent",pd=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(zb,{...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)"}})});pd.displayName=rw;var ow=ed,sw=nd,iw=rd,hd=sd,md=id,gd=ad,xd=ld,yd=cd,vd=ud,bd=dd,wd=fd,Sd=pd;const aw=ow,lw=sw,cw=y.forwardRef(({className:e,inset:t,children:n,...r},o)=>u.jsxs(wd,{ref:o,className:te("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,u.jsx(ie.ChevronRight,{className:"ml-auto h-4 w-4"})]}));cw.displayName=wd.displayName;const uw=y.forwardRef(({className:e,...t},n)=>u.jsx(Sd,{ref:n,className:te("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}));uw.displayName=Sd.displayName;const Cd=y.forwardRef(({className:e,sideOffset:t=4,...n},r)=>u.jsx(iw,{children:u.jsx(hd,{ref:r,sideOffset:t,className:te("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})}));Cd.displayName=hd.displayName;const Qi=y.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(gd,{ref:r,className:te("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}));Qi.displayName=gd.displayName;const dw=y.forwardRef(({className:e,children:t,checked:n,...r},o)=>u.jsxs(xd,{ref:o,className:te("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:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(vd,{children:u.jsx(ie.Check,{className:"h-4 w-4"})})}),t]}));dw.displayName=xd.displayName;const fw=y.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(yd,{ref:r,className:te("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:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(vd,{children:u.jsx(ie.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));fw.displayName=yd.displayName;const pw=y.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(md,{ref:r,className:te("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));pw.displayName=md.displayName;const hw=y.forwardRef(({className:e,...t},n)=>u.jsx(bd,{ref:n,className:te("-mx-1 my-1 h-px bg-muted",e),...t}));hw.displayName=bd.displayName;function mw(e){const t=new Map;console.log("[attemptDetection] groupCheckpointsByLastUserMessageId processing",e.length,"checkpoints");for(const n of e){const o=[...n.messages??[]].reverse().find(s=>s.role==="user");if(o!=null&&o.id){const s=t.get(o.id)??[];s.push(n),t.set(o.id,s),s.length===1?console.log(`[attemptDetection] New user message group: "${o.id}" checkpoint ${n.checkpointId}`):console.log(`[attemptDetection] Adding to existing group: "${o.id}" now has ${s.length} checkpoints`)}else console.log(`[attemptDetection] Checkpoint ${n.checkpointId} has no user messages`)}return console.log("[attemptDetection] Final grouping:",{totalGroups:t.size,groupSizes:Array.from(t.entries()).map(([n,r])=>({userMessageId:n,count:r.length}))}),t}function gw(e){console.log("[attemptDetection] buildAttemptMetadataMap called with",e.length,"checkpoints");const t=new Map,n=mw(e);console.log("[attemptDetection] Grouped into",n.size,"unique user message IDs");for(const[r,o]of n.entries())o.length>1&&console.log(`[attemptDetection] User message "${r}" found in ${o.length} checkpoints (EDITS DETECTED)`,{checkpointIds:o.map(s=>s.checkpointId),createdAts:o.map(s=>s.createdAt)});for(const[r,o]of n.entries())if(o.length===1){const s=o[0];s.checkpointId&&t.set(s.checkpointId,{attemptIndex:0,attemptCount:1,isLatestAttempt:!0,baseUserMessageId:r})}else{const s=[...o].sort((i,a)=>Date.parse(a.createdAt??"0")-Date.parse(i.createdAt??"0"));console.log(`[attemptDetection] Sorted ${s.length} versions for user message "${r}":`,{versionOrder:s.map((i,a)=>`v${a}: ${i.checkpointId} (${i.createdAt})`)}),s.forEach((i,a)=>{i.checkpointId&&t.set(i.checkpointId,{attemptIndex:a,attemptCount:s.length,isLatestAttempt:a===s.length-1,baseUserMessageId:r})})}return console.log("[attemptDetection] Final versionMetadata:",{totalCheckpoints:t.size,editedMessages:Array.from(t.entries()).filter(([r,o])=>o.attemptCount>1).map(([r,o])=>({checkpointId:r,attemptIndex:o.attemptIndex,attemptCount:o.attemptCount,isLatestAttempt:o.isLatestAttempt}))}),t}function xw(e){const t=new Map;for(const[n,r]of e.entries())if(r.baseUserMessageId&&r.attemptCount>1){const o=t.get(r.baseUserMessageId)??[];o.push({checkpointId:n,attemptIndex:r.attemptIndex,attemptCount:r.attemptCount,isLatestAttempt:r.isLatestAttempt}),t.set(r.baseUserMessageId,o)}return t}const us=1e4;function yw(e){if(typeof e!="string")return String(e);const t=[/<script[^>]*>.*?<\/script>/gi,/<iframe[^>]*>.*?<\/iframe>/gi,/javascript:/gi,/vbscript:/gi,/on\w+\s*=/gi,/<object[^>]*>.*?<\/object>/gi,/<embed[^>]*>.*?<\/embed>/gi,/<form[^>]*>.*?<\/form>/gi];let n=e;for(const o of t)n=n.replace(o,"");return/<[^>]+>/.test(n)&&!/<(?!\/?(?:code|strong|em|b|i|br|p|ul|ol|li|h[1-6])\b)[^>]+>/i.test(n)?n.replace(/<code>(.*?)<\/code>/gi,"`$1`").replace(/<strong>(.*?)<\/strong>/gi,"**$1**").replace(/<b>(.*?)<\/b>/gi,"**$1**").replace(/<em>(.*?)<\/em>/gi,"*$1*").replace(/<i>(.*?)<\/i>/gi,"*$1*").replace(/<br\s*\/?>/gi,`
78
+ `)},Gv=0,Tr=[];function Yv(e){var t=y.useRef([]),n=y.useRef([0,0]),r=y.useRef(),o=y.useState(Gv++)[0],s=y.useState(wu)[0],i=y.useRef(e);y.useEffect(function(){i.current=e},[e]),y.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var m=gv([e.lockRef.current],(e.shards||[]).map(Nu),!0).filter(Boolean);return m.forEach(function(v){return v.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),m.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var a=y.useCallback(function(m,v){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!i.current.allowPinchZoom;var g=rs(m),b=n.current,S="deltaX"in m?m.deltaX:b[0]-g[0],k="deltaY"in m?m.deltaY:b[1]-g[1],C,T=m.target,E=Math.abs(S)>Math.abs(k)?"h":"v";if("touches"in m&&E==="h"&&T.type==="range")return!1;var N=Tu(E,T);if(!N)return!0;if(N?C=E:(C=E==="v"?"h":"v",N=Tu(E,T)),!N)return!1;if(!r.current&&"changedTouches"in m&&(S||k)&&(r.current=C),!C)return!0;var _=r.current||C;return Vv(_,v,m,_==="h"?S:k)},[]),l=y.useCallback(function(m){var v=m;if(!(!Tr.length||Tr[Tr.length-1]!==s)){var g="deltaY"in v?Iu(v):rs(v),b=t.current.filter(function(C){return C.name===v.type&&(C.target===v.target||v.target===C.shadowParent)&&Kv(C.delta,g)})[0];if(b&&b.should){v.cancelable&&v.preventDefault();return}if(!b){var S=(i.current.shards||[]).map(Nu).filter(Boolean).filter(function(C){return C.contains(v.target)}),k=S.length>0?a(v,S[0]):!i.current.noIsolation;k&&v.cancelable&&v.preventDefault()}}},[]),c=y.useCallback(function(m,v,g,b){var S={name:m,delta:v,target:g,should:b,shadowParent:Xv(g)};t.current.push(S),setTimeout(function(){t.current=t.current.filter(function(k){return k!==S})},1)},[]),d=y.useCallback(function(m){n.current=rs(m),r.current=void 0},[]),f=y.useCallback(function(m){c(m.type,Iu(m),m.target,a(m,e.lockRef.current))},[]),p=y.useCallback(function(m){c(m.type,rs(m),m.target,a(m,e.lockRef.current))},[]);y.useEffect(function(){return Tr.push(s),e.setCallbacks({onScrollCapture:f,onWheelCapture:f,onTouchMoveCapture:p}),document.addEventListener("wheel",l,Cr),document.addEventListener("touchmove",l,Cr),document.addEventListener("touchstart",d,Cr),function(){Tr=Tr.filter(function(m){return m!==s}),document.removeEventListener("wheel",l,Cr),document.removeEventListener("touchmove",l,Cr),document.removeEventListener("touchstart",d,Cr)}},[]);var h=e.removeScrollBar,x=e.inert;return y.createElement(y.Fragment,null,x?y.createElement(s,{styles:qv(o)}):null,h?y.createElement($v,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Xv(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Jv=kv(bu,Yv);var os=y.forwardRef(function(e,t){return y.createElement(ts,vn({},e,{ref:t,sideCar:Jv}))});os.classNames=ts.classNames;var Vi=["Enter"," "],Zv=["ArrowDown","PageUp","Home"],Au=["ArrowUp","PageDown","End"],Qv=[...Zv,...Au],eb={ltr:[...Vi,"ArrowRight"],rtl:[...Vi,"ArrowLeft"]},tb={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Wr="Menu",[Vr,nb,rb]=yi(Wr),[Zn,_u]=kn(Wr,[rb,Go,du]),ss=Go(),ju=du(),[ob,Qn]=Zn(Wr),[sb,Kr]=Zn(Wr),Ru=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:s,modal:i=!0}=e,a=ss(t),[l,c]=y.useState(null),d=y.useRef(!1),f=jt(s),p=Mo(o);return y.useEffect(()=>{const h=()=>{d.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>d.current=!1;return document.addEventListener("keydown",h,{capture:!0}),()=>{document.removeEventListener("keydown",h,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),u.jsx(iu,{...a,children:u.jsx(ob,{scope:t,open:n,onOpenChange:f,content:l,onContentChange:c,children:u.jsx(sb,{scope:t,onClose:y.useCallback(()=>f(!1),[f]),isUsingKeyboardRef:d,dir:p,modal:i,children:r})})})};Ru.displayName=Wr;var ib="MenuAnchor",Ki=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ss(n);return u.jsx(au,{...o,...r,ref:t})});Ki.displayName=ib;var qi="MenuPortal",[ab,Pu]=Zn(qi,{forceMount:void 0}),Ou=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,s=Qn(qi,t);return u.jsx(ab,{scope:t,forceMount:n,children:u.jsx(Qt,{present:n||s.open,children:u.jsx(Yo,{asChild:!0,container:o,children:r})})})};Ou.displayName=qi;var en="MenuContent",[lb,Gi]=Zn(en),Mu=y.forwardRef((e,t)=>{const n=Pu(en,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Qn(en,e.__scopeMenu),i=Kr(en,e.__scopeMenu);return u.jsx(Vr.Provider,{scope:e.__scopeMenu,children:u.jsx(Qt,{present:r||s.open,children:u.jsx(Vr.Slot,{scope:e.__scopeMenu,children:i.modal?u.jsx(cb,{...o,ref:t}):u.jsx(ub,{...o,ref:t})})})})}),cb=y.forwardRef((e,t)=>{const n=Qn(en,e.__scopeMenu),r=y.useRef(null),o=Ge(t,r);return y.useEffect(()=>{const s=r.current;if(s)return zi(s)},[]),u.jsx(Yi,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:he(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),ub=y.forwardRef((e,t)=>{const n=Qn(en,e.__scopeMenu);return u.jsx(Yi,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),db=qn.createSlot("MenuContent.ScrollLock"),Yi=y.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:p,onDismiss:h,disableOutsideScroll:x,...m}=e,v=Qn(en,n),g=Kr(en,n),b=ss(n),S=ju(n),k=nb(n),[C,T]=y.useState(null),E=y.useRef(null),N=Ge(t,E,v.onContentChange),_=y.useRef(0),P=y.useRef(""),R=y.useRef(0),D=y.useRef(null),F=y.useRef("right"),A=y.useRef(0),z=x?os:y.Fragment,j=x?{as:db,allowPinchZoom:!0}:void 0,J=O=>{var q,$;const W=P.current+O,X=k().filter(V=>!V.disabled),fe=document.activeElement,ae=(q=X.find(V=>V.ref.current===fe))==null?void 0:q.textValue,Re=X.map(V=>V.textValue),G=Cb(Re,W,ae),U=($=X.find(V=>V.textValue===G))==null?void 0:$.ref.current;(function V(re){P.current=re,window.clearTimeout(_.current),re!==""&&(_.current=window.setTimeout(()=>V(""),1e3))})(W),U&&setTimeout(()=>U.focus())};y.useEffect(()=>()=>window.clearTimeout(_.current),[]),wi();const B=y.useCallback(O=>{var X,fe;return F.current===((X=D.current)==null?void 0:X.side)&&kb(O,(fe=D.current)==null?void 0:fe.area)},[]);return u.jsx(lb,{scope:n,searchRef:P,onItemEnter:y.useCallback(O=>{B(O)&&O.preventDefault()},[B]),onItemLeave:y.useCallback(O=>{var W;B(O)||((W=E.current)==null||W.focus(),T(null))},[B]),onTriggerLeave:y.useCallback(O=>{B(O)&&O.preventDefault()},[B]),pointerGraceTimerRef:R,onPointerGraceIntentChange:y.useCallback(O=>{D.current=O},[]),children:u.jsx(z,{...j,children:u.jsx(Lo,{asChild:!0,trapped:o,onMountAutoFocus:he(s,O=>{var W;O.preventDefault(),(W=E.current)==null||W.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:u.jsx(Do,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:p,onDismiss:h,children:u.jsx(dv,{asChild:!0,...S,dir:g.dir,orientation:"vertical",loop:r,currentTabStopId:C,onCurrentTabStopIdChange:T,onEntryFocus:he(l,O=>{g.isUsingKeyboardRef.current||O.preventDefault()}),preventScrollOnEntryFocus:!0,children:u.jsx(lu,{role:"menu","aria-orientation":"vertical","data-state":Zu(v.open),"data-radix-menu-content":"",dir:g.dir,...b,...m,ref:N,style:{outline:"none",...m.style},onKeyDown:he(m.onKeyDown,O=>{const X=O.target.closest("[data-radix-menu-content]")===O.currentTarget,fe=O.ctrlKey||O.altKey||O.metaKey,ae=O.key.length===1;X&&(O.key==="Tab"&&O.preventDefault(),!fe&&ae&&J(O.key));const Re=E.current;if(O.target!==Re||!Qv.includes(O.key))return;O.preventDefault();const U=k().filter(q=>!q.disabled).map(q=>q.ref.current);Au.includes(O.key)&&U.reverse(),wb(U)}),onBlur:he(e.onBlur,O=>{O.currentTarget.contains(O.target)||(window.clearTimeout(_.current),P.current="")}),onPointerMove:he(e.onPointerMove,Gr(O=>{const W=O.target,X=A.current!==O.clientX;if(O.currentTarget.contains(W)&&X){const fe=O.clientX>A.current?"right":"left";F.current=fe,A.current=O.clientX}}))})})})})})})});Mu.displayName=en;var fb="MenuGroup",Xi=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Oe.div,{role:"group",...r,ref:t})});Xi.displayName=fb;var pb="MenuLabel",Du=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Oe.div,{...r,ref:t})});Du.displayName=pb;var is="MenuItem",Lu="menu.itemSelect",as=y.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,s=y.useRef(null),i=Kr(is,e.__scopeMenu),a=Gi(is,e.__scopeMenu),l=Ge(t,s),c=y.useRef(!1),d=()=>{const f=s.current;if(!n&&f){const p=new CustomEvent(Lu,{bubbles:!0,cancelable:!0});f.addEventListener(Lu,h=>r==null?void 0:r(h),{once:!0}),gc(f,p),p.defaultPrevented?c.current=!1:i.onClose()}};return u.jsx($u,{...o,ref:l,disabled:n,onClick:he(e.onClick,d),onPointerDown:f=>{var p;(p=e.onPointerDown)==null||p.call(e,f),c.current=!0},onPointerUp:he(e.onPointerUp,f=>{var p;c.current||(p=f.currentTarget)==null||p.click()}),onKeyDown:he(e.onKeyDown,f=>{const p=a.searchRef.current!=="";n||p&&f.key===" "||Vi.includes(f.key)&&(f.currentTarget.click(),f.preventDefault())})})});as.displayName=is;var $u=y.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...s}=e,i=Gi(is,n),a=ju(n),l=y.useRef(null),c=Ge(t,l),[d,f]=y.useState(!1),[p,h]=y.useState("");return y.useEffect(()=>{const x=l.current;x&&h((x.textContent??"").trim())},[s.children]),u.jsx(Vr.ItemSlot,{scope:n,disabled:r,textValue:o??p,children:u.jsx(fv,{asChild:!0,...a,focusable:!r,children:u.jsx(Oe.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:c,onPointerMove:he(e.onPointerMove,Gr(x=>{r?i.onItemLeave(x):(i.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:he(e.onPointerLeave,Gr(x=>i.onItemLeave(x))),onFocus:he(e.onFocus,()=>f(!0)),onBlur:he(e.onBlur,()=>f(!1))})})})}),hb="MenuCheckboxItem",Fu=y.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return u.jsx(Wu,{scope:e.__scopeMenu,checked:n,children:u.jsx(as,{role:"menuitemcheckbox","aria-checked":ls(n)?"mixed":n,...o,ref:t,"data-state":Zi(n),onSelect:he(o.onSelect,()=>r==null?void 0:r(ls(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Fu.displayName=hb;var zu="MenuRadioGroup",[mb,gb]=Zn(zu,{value:void 0,onValueChange:()=>{}}),Bu=y.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,s=jt(r);return u.jsx(mb,{scope:e.__scopeMenu,value:n,onValueChange:s,children:u.jsx(Xi,{...o,ref:t})})});Bu.displayName=zu;var Uu="MenuRadioItem",Hu=y.forwardRef((e,t)=>{const{value:n,...r}=e,o=gb(Uu,e.__scopeMenu),s=n===o.value;return u.jsx(Wu,{scope:e.__scopeMenu,checked:s,children:u.jsx(as,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":Zi(s),onSelect:he(r.onSelect,()=>{var i;return(i=o.onValueChange)==null?void 0:i.call(o,n)},{checkForDefaultPrevented:!1})})})});Hu.displayName=Uu;var Ji="MenuItemIndicator",[Wu,xb]=Zn(Ji,{checked:!1}),Vu=y.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,s=xb(Ji,n);return u.jsx(Qt,{present:r||ls(s.checked)||s.checked===!0,children:u.jsx(Oe.span,{...o,ref:t,"data-state":Zi(s.checked)})})});Vu.displayName=Ji;var yb="MenuSeparator",Ku=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Oe.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Ku.displayName=yb;var vb="MenuArrow",qu=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ss(n);return u.jsx(cu,{...o,...r,ref:t})});qu.displayName=vb;var bb="MenuSub",[OT,Gu]=Zn(bb),qr="MenuSubTrigger",Yu=y.forwardRef((e,t)=>{const n=Qn(qr,e.__scopeMenu),r=Kr(qr,e.__scopeMenu),o=Gu(qr,e.__scopeMenu),s=Gi(qr,e.__scopeMenu),i=y.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=s,c={__scopeMenu:e.__scopeMenu},d=y.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return y.useEffect(()=>d,[d]),y.useEffect(()=>{const f=a.current;return()=>{window.clearTimeout(f),l(null)}},[a,l]),u.jsx(Ki,{asChild:!0,...c,children:u.jsx($u,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":Zu(n.open),...e,ref:xi(t,o.onTriggerChange),onClick:f=>{var p;(p=e.onClick)==null||p.call(e,f),!(e.disabled||f.defaultPrevented)&&(f.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:he(e.onPointerMove,Gr(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:he(e.onPointerLeave,Gr(f=>{var h,x;d();const p=(h=n.content)==null?void 0:h.getBoundingClientRect();if(p){const m=(x=n.content)==null?void 0:x.dataset.side,v=m==="right",g=v?-5:5,b=p[v?"left":"right"],S=p[v?"right":"left"];s.onPointerGraceIntentChange({area:[{x:f.clientX+g,y:f.clientY},{x:b,y:p.top},{x:S,y:p.top},{x:S,y:p.bottom},{x:b,y:p.bottom}],side:m}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(f),f.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:he(e.onKeyDown,f=>{var h;const p=s.searchRef.current!=="";e.disabled||p&&f.key===" "||eb[r.dir].includes(f.key)&&(n.onOpenChange(!0),(h=n.content)==null||h.focus(),f.preventDefault())})})})});Yu.displayName=qr;var Xu="MenuSubContent",Ju=y.forwardRef((e,t)=>{const n=Pu(en,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Qn(en,e.__scopeMenu),i=Kr(en,e.__scopeMenu),a=Gu(Xu,e.__scopeMenu),l=y.useRef(null),c=Ge(t,l);return u.jsx(Vr.Provider,{scope:e.__scopeMenu,children:u.jsx(Qt,{present:r||s.open,children:u.jsx(Vr.Slot,{scope:e.__scopeMenu,children:u.jsx(Yi,{id:a.contentId,"aria-labelledby":a.triggerId,...o,ref:c,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:he(e.onFocusOutside,d=>{d.target!==a.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:he(e.onEscapeKeyDown,d=>{i.onClose(),d.preventDefault()}),onKeyDown:he(e.onKeyDown,d=>{var h;const f=d.currentTarget.contains(d.target),p=tb[i.dir].includes(d.key);f&&p&&(s.onOpenChange(!1),(h=a.trigger)==null||h.focus(),d.preventDefault())})})})})})});Ju.displayName=Xu;function Zu(e){return e?"open":"closed"}function ls(e){return e==="indeterminate"}function Zi(e){return ls(e)?"indeterminate":e?"checked":"unchecked"}function wb(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Sb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Cb(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=Sb(e,Math.max(s,0));o.length===1&&(i=i.filter(c=>c!==n));const l=i.find(c=>c.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function Tb(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],c=a.x,d=a.y,f=l.x,p=l.y;d>r!=p>r&&n<(f-c)*(r-d)/(p-d)+c&&(o=!o)}return o}function kb(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Tb(n,t)}function Gr(e){return t=>t.pointerType==="mouse"?e(t):void 0}var Eb=Ru,Ib=Ki,Nb=Ou,Ab=Mu,_b=Xi,jb=Du,Rb=as,Pb=Fu,Ob=Bu,Mb=Hu,Db=Vu,Lb=Ku,$b=qu,Fb=Yu,zb=Ju,cs="DropdownMenu",[Bb,MT]=kn(cs,[_u]),$t=_u(),[Ub,Qu]=Bb(cs),ed=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:s,onOpenChange:i,modal:a=!0}=e,l=$t(t),c=y.useRef(null),[d,f]=gr({prop:o,defaultProp:s??!1,onChange:i,caller:cs});return u.jsx(Ub,{scope:t,triggerId:En(),triggerRef:c,contentId:En(),open:d,onOpenChange:f,onOpenToggle:y.useCallback(()=>f(p=>!p),[f]),modal:a,children:u.jsx(Eb,{...l,open:d,onOpenChange:f,dir:r,modal:a,children:n})})};ed.displayName=cs;var td="DropdownMenuTrigger",nd=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,s=Qu(td,n),i=$t(n);return u.jsx(Ib,{asChild:!0,...i,children:u.jsx(Oe.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:xi(t,s.triggerRef),onPointerDown:he(e.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(s.onOpenToggle(),s.open||a.preventDefault())}),onKeyDown:he(e.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&s.onOpenToggle(),a.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});nd.displayName=td;var Hb="DropdownMenuPortal",rd=e=>{const{__scopeDropdownMenu:t,...n}=e,r=$t(t);return u.jsx(Nb,{...r,...n})};rd.displayName=Hb;var od="DropdownMenuContent",sd=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Qu(od,n),s=$t(n),i=y.useRef(!1);return u.jsx(Ab,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...r,ref:t,onCloseAutoFocus:he(e.onCloseAutoFocus,a=>{var l;i.current||(l=o.triggerRef.current)==null||l.focus(),i.current=!1,a.preventDefault()}),onInteractOutside:he(e.onInteractOutside,a=>{const l=a.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,d=l.button===2||c;(!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)"}})});sd.displayName=od;var Wb="DropdownMenuGroup",Vb=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(_b,{...o,...r,ref:t})});Vb.displayName=Wb;var Kb="DropdownMenuLabel",id=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(jb,{...o,...r,ref:t})});id.displayName=Kb;var qb="DropdownMenuItem",ad=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(Rb,{...o,...r,ref:t})});ad.displayName=qb;var Gb="DropdownMenuCheckboxItem",ld=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(Pb,{...o,...r,ref:t})});ld.displayName=Gb;var Yb="DropdownMenuRadioGroup",Xb=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(Ob,{...o,...r,ref:t})});Xb.displayName=Yb;var Jb="DropdownMenuRadioItem",cd=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(Mb,{...o,...r,ref:t})});cd.displayName=Jb;var Zb="DropdownMenuItemIndicator",ud=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(Db,{...o,...r,ref:t})});ud.displayName=Zb;var Qb="DropdownMenuSeparator",dd=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(Lb,{...o,...r,ref:t})});dd.displayName=Qb;var ew="DropdownMenuArrow",tw=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx($b,{...o,...r,ref:t})});tw.displayName=ew;var nw="DropdownMenuSubTrigger",fd=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(Fb,{...o,...r,ref:t})});fd.displayName=nw;var rw="DropdownMenuSubContent",pd=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$t(n);return u.jsx(zb,{...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)"}})});pd.displayName=rw;var ow=ed,sw=nd,iw=rd,hd=sd,md=id,gd=ad,xd=ld,yd=cd,vd=ud,bd=dd,wd=fd,Sd=pd;const aw=ow,lw=sw,cw=y.forwardRef(({className:e,inset:t,children:n,...r},o)=>u.jsxs(wd,{ref:o,className:te("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,u.jsx(ie.ChevronRight,{className:"ml-auto h-4 w-4"})]}));cw.displayName=wd.displayName;const uw=y.forwardRef(({className:e,...t},n)=>u.jsx(Sd,{ref:n,className:te("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}));uw.displayName=Sd.displayName;const Cd=y.forwardRef(({className:e,sideOffset:t=4,...n},r)=>u.jsx(iw,{children:u.jsx(hd,{ref:r,sideOffset:t,className:te("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})}));Cd.displayName=hd.displayName;const Qi=y.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(gd,{ref:r,className:te("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}));Qi.displayName=gd.displayName;const dw=y.forwardRef(({className:e,children:t,checked:n,...r},o)=>u.jsxs(xd,{ref:o,className:te("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:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(vd,{children:u.jsx(ie.Check,{className:"h-4 w-4"})})}),t]}));dw.displayName=xd.displayName;const fw=y.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(yd,{ref:r,className:te("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:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(vd,{children:u.jsx(ie.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));fw.displayName=yd.displayName;const pw=y.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(md,{ref:r,className:te("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));pw.displayName=md.displayName;const hw=y.forwardRef(({className:e,...t},n)=>u.jsx(bd,{ref:n,className:te("-mx-1 my-1 h-px bg-muted",e),...t}));hw.displayName=bd.displayName;function mw(e){const t=new Map;console.log("[attemptDetection] groupCheckpointsByLastUserMessageId processing",e.length,"checkpoints");for(const n of e){const o=[...n.messages??[]].reverse().find(s=>s.role==="user");if(o!=null&&o.id){const s=t.get(o.id)??[];s.push(n),t.set(o.id,s),s.length===1?console.log(`[attemptDetection] New user message group: "${o.id}" checkpoint ${n.checkpointId}`):console.log(`[attemptDetection] Adding to existing group: "${o.id}" now has ${s.length} checkpoints`)}else console.log(`[attemptDetection] Checkpoint ${n.checkpointId} has no user messages`)}return console.log("[attemptDetection] Final grouping:",{totalGroups:t.size,groupSizes:Array.from(t.entries()).map(([n,r])=>({userMessageId:n,count:r.length}))}),t}function gw(e){console.log("[attemptDetection] buildAttemptMetadataMap called with",e.length,"checkpoints");const t=new Map,n=mw(e);console.log("[attemptDetection] Grouped into",n.size,"unique user message IDs");for(const[r,o]of n.entries())o.length>1&&console.log(`[attemptDetection] User message "${r}" found in ${o.length} checkpoints (EDITS DETECTED)`,{checkpointIds:o.map(s=>s.checkpointId),createdAts:o.map(s=>s.createdAt)});for(const[r,o]of n.entries())if(o.length===1){const s=o[0];s.checkpointId&&t.set(s.checkpointId,{attemptIndex:0,attemptCount:1,isLatestAttempt:!0,baseUserMessageId:r})}else{const s=[...o].sort((i,a)=>Date.parse(a.createdAt??"0")-Date.parse(i.createdAt??"0"));console.log(`[attemptDetection] Sorted ${s.length} versions for user message "${r}":`,{versionOrder:s.map((i,a)=>`v${a}: ${i.checkpointId} (${i.createdAt})`)}),s.forEach((i,a)=>{i.checkpointId&&t.set(i.checkpointId,{attemptIndex:a,attemptCount:s.length,isLatestAttempt:a===s.length-1,baseUserMessageId:r})})}return console.log("[attemptDetection] Final versionMetadata:",{totalCheckpoints:t.size,editedMessages:Array.from(t.entries()).filter(([r,o])=>o.attemptCount>1).map(([r,o])=>({checkpointId:r,attemptIndex:o.attemptIndex,attemptCount:o.attemptCount,isLatestAttempt:o.isLatestAttempt}))}),t}function xw(e){const t=new Map;for(const[n,r]of e.entries())if(r.baseUserMessageId&&r.attemptCount>1){const o=t.get(r.baseUserMessageId)??[];o.push({checkpointId:n,attemptIndex:r.attemptIndex,attemptCount:r.attemptCount,isLatestAttempt:r.isLatestAttempt}),t.set(r.baseUserMessageId,o)}return t}const us=1e4;function yw(e){if(typeof e!="string")return String(e);const t=[/<script[^>]*>.*?<\/script>/gi,/<iframe[^>]*>.*?<\/iframe>/gi,/javascript:/gi,/vbscript:/gi,/on\w+\s*=/gi,/<object[^>]*>.*?<\/object>/gi,/<embed[^>]*>.*?<\/embed>/gi,/<form[^>]*>.*?<\/form>/gi];let n=e;for(const o of t)n=n.replace(o,"");return/<[^>]+>/.test(n)&&!/<(?!\/?(?:code|strong|em|b|i|br|p|ul|ol|li|h[1-6])\b)[^>]+>/i.test(n)?n.replace(/<code>(.*?)<\/code>/gi,"`$1`").replace(/<strong>(.*?)<\/strong>/gi,"**$1**").replace(/<b>(.*?)<\/b>/gi,"**$1**").replace(/<em>(.*?)<\/em>/gi,"*$1*").replace(/<i>(.*?)<\/i>/gi,"*$1*").replace(/<br\s*\/?>/gi,`
79
79
  `).replace(/<p>(.*?)<\/p>/gi,`$1
80
80
 
81
81
  `).replace(/<h([1-6])>(.*?)<\/h[1-6]>/gi,(o,s,i)=>`${"#".repeat(parseInt(s))} ${i}
@@ -83,7 +83,7 @@ React keys must be passed directly to JSX without using spread:
83
83
  `).replace(/<ul>/gi,"").replace(/<\/ul>/gi,`
84
84
  `).replace(/<ol>/gi,"").replace(/<\/ol>/gi,`
85
85
  `).replace(/<li>(.*?)<\/li>/gi,`- $1
86
- `).trim():n.replace(/</g,"&lt;").replace(/>/g,"&gt;").trim()}function vw(e,t=us){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 bw(e){let t;return typeof e=="string"?t=e:typeof e=="object"&&e!==null?t=JSON.stringify(e):t=String(e),vw(t),yw(t)}const ds=0,Mn=1,kr=2,Td=4;function kd(e){return()=>e}function ww(e){e()}function Ed(e,t){return n=>e(t(n))}function Id(e,t){return()=>e(t)}function Sw(e,t){return n=>e(t,n)}function ea(e){return e!==void 0}function Cw(...e){return()=>{e.map(ww)}}function Er(){}function fs(e,t){return t(e),e}function Tw(e,t){return t(e)}function pt(...e){return e}function it(e,t){return e(Mn,t)}function De(e,t){e(ds,t)}function ta(e){e(kr)}function Tt(e){return e(Td)}function ve(e,t){return it(e,Sw(t,ds))}function un(e,t){const n=e(Mn,r=>{n(),t(r)});return n}function Nd(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function Ad(e,t){return e===t}function ht(e=Ad){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function Ae(e){return t=>n=>{e(n)&&t(n)}}function ue(e){return t=>Ed(t,e)}function bn(e){return t=>()=>{t(e)}}function H(e,...t){const n=kw(...t);return(r,o)=>{switch(r){case kr:ta(e);return;case Mn:return it(e,n(o))}}}function wn(e,t){return n=>r=>{n(t=e(t,r))}}function er(e){return t=>n=>{e>0?e--:t(n)}}function An(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function $e(...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);it(s,l=>{const c=n;n=n|a,t[i]=l,c!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function kw(...e){return t=>e.reduceRight(Tw,t)}function Ew(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case Mn:return s?n===s?void 0:(r(),n=s,t=it(e,s),t):(r(),Er);case kr:r(),n=null;return}}}function Q(e){let t=e;const n=Ye();return(r,o)=>{switch(r){case ds:t=o;break;case Mn:{o(t);break}case Td:return t}return n(r,o)}}function Ot(e,t){return fs(Q(t),n=>ve(e,n))}function Ye(){const e=[];return(t,n)=>{switch(t){case ds:e.slice().forEach(r=>{r(n)});return;case kr:e.splice(0,e.length);return;case Mn:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function Gt(e){return fs(Ye(),t=>ve(e,t))}function tt(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:Iw(),singleton:n}}const Iw=()=>Symbol();function Nw(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 kt(...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);it(s,l=>{n[i]=l,r=r|a,r===o&&De(t,n)})}),function(s,i){switch(s){case kr:{ta(t);return}case Mn:return r===o&&i(n),it(t,i)}}}function Ie(e,t=Ad){return H(e,ht(t))}function na(...e){return function(t,n){switch(t){case kr:return;case Mn:return Cw(...e.map(r=>it(r,n)))}}}var Wt=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(Wt||{});const Aw={0:"debug",3:"error",1:"log",2:"warn"},_w=()=>typeof globalThis>"u"?window:globalThis,Dn=tt(()=>{const e=Q(3);return{log:Q((t,n,r=1)=>{var o;const s=(o=_w().VIRTUOSO_LOG_LEVEL)!=null?o:Tt(e);r>=s&&console[Aw[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function tr(e,t,n){return ra(e,t,n).callbackRef}function ra(e,t,n){const r=w.useRef(null);let o=i=>{};const s=w.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 jw(e,t,n,r,o,s,i,a,l){const c=w.useCallback(d=>{const f=Rw(d.children,t,a?"offsetWidth":"offsetHeight",o);let p=d.parentElement;for(;!p.dataset.virtuosoScroller;)p=p.parentElement;const h=p.lastElementChild.dataset.viewportType==="window";let x;h&&(x=p.ownerDocument.defaultView);const m=i?a?i.scrollLeft:i.scrollTop:h?a?x.scrollX||x.document.documentElement.scrollLeft:x.scrollY||x.document.documentElement.scrollTop:a?p.scrollLeft:p.scrollTop,v=i?a?i.scrollWidth:i.scrollHeight:h?a?x.document.documentElement.scrollWidth:x.document.documentElement.scrollHeight:a?p.scrollWidth:p.scrollHeight,g=i?a?i.offsetWidth:i.offsetHeight:h?a?x.innerWidth:x.innerHeight:a?p.offsetWidth:p.offsetHeight;r({scrollHeight:v,scrollTop:Math.max(m,0),viewportHeight:g}),s==null||s(a?_d("column-gap",getComputedStyle(d).columnGap,o):_d("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return ra(c,n,l)}function Rw(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),c=parseFloat(a.dataset.knownSize),d=t(a,n);if(d===0&&r("Zero-sized element, this should not happen",{child:a},Wt.ERROR),d===c)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 _d(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Wt.WARN),t==="normal"?0:parseInt(t??"0",10)}function jd(e,t,n){const r=w.useRef(null),o=w.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const c=l.getBoundingClientRect(),d=c.width;let f,p;if(t){const h=t.getBoundingClientRect(),x=c.top-h.top;p=h.height-Math.max(0,x),f=x+t.scrollTop}else{const h=i.current.ownerDocument.defaultView;p=h.innerHeight-Math.max(0,c.top),f=c.top+h.scrollY}r.current={offsetTop:f,visibleHeight:p,visibleWidth:d},e(r.current)},[e,t]),{callbackRef:s,ref:i}=ra(o,!0,n),a=w.useCallback(()=>{o(i.current)},[o,i]);return w.useEffect(()=>{var l;if(t){t.addEventListener("scroll",a);const c=new ResizeObserver(()=>{requestAnimationFrame(a)});return c.observe(t),()=>{t.removeEventListener("scroll",a),c.unobserve(t)}}else{const c=(l=i.current)==null?void 0:l.ownerDocument.defaultView;return c==null||c.addEventListener("scroll",a),c==null||c.addEventListener("resize",a),()=>{c==null||c.removeEventListener("scroll",a),c==null||c.removeEventListener("resize",a)}}},[a,t,i]),s}const Ft=tt(()=>{const e=Ye(),t=Ye(),n=Q(0),r=Ye(),o=Q(0),s=Ye(),i=Ye(),a=Q(0),l=Q(0),c=Q(0),d=Q(0),f=Ye(),p=Ye(),h=Q(!1),x=Q(!1),m=Q(!1);return ve(H(e,ue(({scrollTop:v})=>v)),t),ve(H(e,ue(({scrollHeight:v})=>v)),i),ve(t,o),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:x,scrollBy:p,scrollContainerState:e,scrollHeight:i,scrollingInProgress:h,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:m,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),Yr={lvl:0};function Rd(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 ut(e){return e===Yr}function Xr(e,t){if(!ut(e))return t===e.k?e.v:t<e.k?Xr(e.l,t):Xr(e.r,t)}function dn(e,t,n="k"){if(ut(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=dn(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return dn(e.l,t,n)}function Yt(e,t,n){return ut(e)?Md(t,n,1):t===e.k?At(e,{k:t,v:n}):t<e.k?Dd(At(e,{l:Yt(e.l,t,n)})):Dd(At(e,{r:Yt(e.r,t,n)}))}function Ir(){return Yr}function ps(e,t,n){if(ut(e))return[];const r=dn(e,t)[0];return Pw(sa(e,r,n))}function oa(e,t){if(ut(e))return Yr;const{k:n,l:r,r:o}=e;if(t===n){if(ut(r))return o;if(ut(o))return r;{const[s,i]=Od(r);return hs(At(e,{k:s,l:Pd(r),v:i}))}}else return t<n?hs(At(e,{l:oa(r,t)})):hs(At(e,{r:oa(o,t)}))}function nr(e){return ut(e)?[]:[...nr(e.l),{k:e.k,v:e.v},...nr(e.r)]}function sa(e,t,n){if(ut(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(sa(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(sa(s,t,n))),a}function hs(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(ia(t))return Ld(At(e,{lvl:n-1}));if(!ut(t)&&!ut(t.r))return At(t.r,{l:At(t,{r:t.r.l}),lvl:n,r:At(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(ia(e))return aa(At(e,{lvl:n-1}));if(!ut(r)&&!ut(r.l)){const o=r.l,s=ia(o)?r.lvl-1:r.lvl;return At(o,{l:At(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:aa(At(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function At(e,t){return Md(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 Pd(e){return ut(e.r)?e.l:hs(At(e,{r:Pd(e.r)}))}function ia(e){return ut(e)||e.lvl>e.r.lvl}function Od(e){return ut(e.r)?[e.k,e.v]:Od(e.r)}function Md(e,t,n,r=Yr,o=Yr){return{k:e,l:r,lvl:n,r:o,v:t}}function Dd(e){return aa(Ld(e))}function Ld(e){const{l:t}=e;return!ut(t)&&t.lvl===e.lvl?At(t,{r:At(e,{l:t.r})}):e}function aa(e){const{lvl:t,r:n}=e;return!ut(n)&&!ut(n.r)&&n.lvl===t&&n.r.lvl===t?At(n,{l:At(e,{r:n.l}),lvl:t+1}):e}function Pw(e){return Rd(e,({k:t,v:n})=>({index:t,value:n}))}function $d(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function Jr(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const la=tt(()=>({recalcInProgress:Q(!1)}),[],{singleton:!0});function Fd(e,t,n){return e[ms(e,t,n)]}function ms(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 Ow(e,t,n,r){const o=ms(e,t,r),s=ms(e,n,r,o);return e.slice(o,s+1)}function Ln(e,t){return Math.round(e.getBoundingClientRect()[t])}function gs(e){return!ut(e.groupOffsetTree)}function ca({index:e},t){return t===e?0:t<e?-1:1}function Mw(){return{groupIndices:[],groupOffsetTree:Ir(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:Ir()}}function Dw(e,t){let n=ut(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),ut(e)){e=Yt(e,0,s);continue}const a=ps(e,i-1,o+1);if(a.some(Hw(r)))continue;let l=!1,c=!1;for(const{end:d,start:f,value:p}of a)l?(o>=f||s===p)&&(e=oa(e,f)):(c=p!==s,l=!0),d>o&&o>=f&&p!==s&&(e=Yt(e,o+1,p));c&&(e=Yt(e,i,s))}return[e,n]}function Lw(e){return typeof e.groupIndex<"u"}function $w({offset:e},t){return t===e?0:t<e?-1:1}function Zr(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=Fd(t,e,ca),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function zd(e,t){if(!gs(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function Bd(e,t,n){if(Lw(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=zd(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function Fw(e,t,n,r=0){return r>0&&(t=Math.max(t,Fd(e,r,ca).offset)),Rd(Ow(e,t,n,$w),Uw)}function zw(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,Wt.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&ut(s)&&t.length===2){const p=t[0].size,h=t[1].size;i=n.reduce((x,m)=>Yt(Yt(x,m,p),m+1,h),i)}else[i,a]=Dw(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f}=ua(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((p,h)=>Yt(p,h,Zr(h,f,o)),Ir()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f,sizeTree:i}}function Bw(e){return nr(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 Ud(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 ua(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=ms(o,t-1,ca),a=o[l].offset;const c=dn(n,t-1);s=c[0],i=c[1],o.length&&o[l].size===dn(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:c,value:d}of ps(n,t,1/0)){const f=c-s,p=f*i+a+f*r;o.push({index:c,offset:p,size:d}),s=c,a=p,i=d}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function Uw(e){return{index:e.index,value:e}}function Hw(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 Ww={offsetHeight:"height",offsetWidth:"width"},Sn=tt(([{log:e},{recalcInProgress:t}])=>{const n=Ye(),r=Ye(),o=Ot(r,0),s=Ye(),i=Ye(),a=Q(0),l=Q([]),c=Q(void 0),d=Q(void 0),f=Q((C,T)=>Ln(C,Ww[T])),p=Q(void 0),h=Q(0),x=Mw(),m=Ot(H(n,$e(l,e,h),wn(zw,x),ht()),x),v=Ot(H(l,ht(),wn((C,T)=>({current:T,prev:C.current}),{current:[],prev:[]}),ue(({prev:C})=>C)),[]);ve(H(l,Ae(C=>C.length>0),$e(m,h),ue(([C,T,E])=>{const N=C.reduce((_,P,R)=>Yt(_,P,Zr(P,T.offsetTree,E)||R),Ir());return{...T,groupIndices:C,groupOffsetTree:N}})),m),ve(H(r,$e(m),Ae(([C,{lastIndex:T}])=>C<T),ue(([C,{lastIndex:T,lastSize:E}])=>[{endIndex:T,size:E,startIndex:C}])),n),ve(c,d);const g=Ot(H(c,ue(C=>C===void 0)),!0);ve(H(d,Ae(C=>C!==void 0&&ut(Tt(m).sizeTree)),ue(C=>[{endIndex:0,size:C,startIndex:0}])),n);const b=Gt(H(n,$e(m),wn(({sizes:C},[T,E])=>({changed:E!==C,sizes:E}),{changed:!1,sizes:x}),ue(C=>C.changed)));it(H(a,wn((C,T)=>({diff:C.prev-T,prev:T}),{diff:0,prev:0}),ue(C=>C.diff)),C=>{const{groupIndices:T}=Tt(m);if(C>0)De(t,!0),De(s,C+Ud(C,T));else if(C<0){const E=Tt(v);E.length>0&&(C-=Ud(-C,E)),De(i,C)}}),it(H(a,$e(e)),([C,T])=>{C<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},Wt.ERROR)});const S=Gt(s);ve(H(s,$e(m),ue(([C,T])=>{const E=T.groupIndices.length>0,N=[],_=T.lastSize;if(E){const P=Xr(T.sizeTree,0);let R=0,D=0;for(;R<C;){const A=T.groupIndices[D],z=T.groupIndices.length===D+1?1/0:T.groupIndices[D+1]-A-1;N.push({endIndex:A,size:P,startIndex:A}),N.push({endIndex:A+1+z-1,size:_,startIndex:A+1}),D++,R+=z+1}const F=nr(T.sizeTree);return R!==C&&F.shift(),F.reduce((A,{k:z,v:j})=>{let J=A.ranges;return A.prevSize!==0&&(J=[...A.ranges,{endIndex:z+C-1,size:A.prevSize,startIndex:A.prevIndex}]),{prevIndex:z+C,prevSize:j,ranges:J}},{prevIndex:C,prevSize:0,ranges:N}).ranges}return nr(T.sizeTree).reduce((P,{k:R,v:D})=>({prevIndex:R+C,prevSize:D,ranges:[...P.ranges,{endIndex:R+C-1,size:P.prevSize,startIndex:P.prevIndex}]}),{prevIndex:0,prevSize:_,ranges:[]}).ranges})),n);const k=Gt(H(i,$e(m,h),ue(([C,{offsetTree:T},E])=>{const N=-C;return Zr(N,T,E)})));return ve(H(i,$e(m,h),ue(([C,T,E])=>{if(T.groupIndices.length>0){if(ut(T.sizeTree))return T;let N=Ir();const _=Tt(v);let P=0,R=0,D=0;for(;P<-C;){D=_[R];const F=_[R+1]-D-1;R++,P+=F+1}if(N=nr(T.sizeTree).reduce((F,{k:A,v:z})=>Yt(F,Math.max(0,A+C),z),N),P!==-C){const F=Xr(T.sizeTree,D);N=Yt(N,0,F);const A=dn(T.sizeTree,-C+1)[1];N=Yt(N,1,A)}return{...T,sizeTree:N,...ua(T.offsetTree,0,N,E)}}else{const N=nr(T.sizeTree).reduce((_,{k:P,v:R})=>Yt(_,Math.max(0,P+C),R),Ir());return{...T,sizeTree:N,...ua(T.offsetTree,0,N,E)}}})),m),{beforeUnshiftWith:S,data:p,defaultItemSize:d,firstItemIndex:a,fixedItemSize:c,gap:h,groupIndices:l,itemSize:f,listRefresh:b,shiftWith:i,shiftWithOffset:k,sizeRanges:n,sizes:m,statefulTotalCount:o,totalCount:r,trackItemSizes:g,unshiftWith:s}},pt(Dn,la),{singleton:!0});function Vw(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const Hd=tt(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=Ye(),i=Ye(),a=Gt(H(s,ue(Vw)));return ve(H(a,ue(l=>l.totalCount)),n),ve(H(a,ue(l=>l.groupIndices)),e),ve(H(kt(o,t,r),Ae(([l,c])=>gs(c)),ue(([l,c,d])=>dn(c.groupOffsetTree,Math.max(l-d,0),"v")[0]),ht(),ue(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},pt(Sn,Ft)),$n=tt(([{log:e}])=>{const t=Q(!1),n=Gt(H(t,Ae(r=>r),ht()));return it(t,r=>{r&&Tt(e)("props updated",{},Wt.DEBUG)}),{didMount:n,propsReady:t}},pt(Dn),{singleton:!0}),Kw=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Wd(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!Kw)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const Qr=tt(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:l,scrollTo:c,smoothScrollTargetReached:d,viewportHeight:f},{log:p}])=>{const h=Ye(),x=Ye(),m=Q(0);let v=null,g=null,b=null;function S(){v&&(v(),v=null),b&&(b(),b=null),g&&(clearTimeout(g),g=null),De(l,!1)}return ve(H(h,$e(n,f,r,m,a,i,p),$e(e,s,o),ue(([[k,C,T,E,N,_,P,R],D,F,A])=>{const z=Wd(k),{align:j,behavior:J,offset:B}=z,O=E-1,W=Bd(z,C,O);let X=Zr(W,C.offsetTree,D)+_;j==="end"?(X+=F+dn(C.sizeTree,W)[1]-T+A,W===O&&(X+=P)):j==="center"?X+=(F+dn(C.sizeTree,W)[1]-T+A)/2:X-=N,B&&(X+=B);const he=ae=>{S(),ae?(R("retrying to scroll to",{location:k},Wt.DEBUG),De(h,k)):(De(x,!0),R("list did not change, scroll successful",{},Wt.DEBUG))};if(S(),J==="smooth"){let ae=!1;b=it(t,Re=>{ae=ae||Re}),v=un(d,()=>{he(ae)})}else v=un(H(t,qw(150)),he);return g=setTimeout(()=>{S()},1200),De(l,!0),R("scrolling from index to",{behavior:J,index:W,top:X},Wt.DEBUG),{behavior:J,top:X}})),c),{scrollTargetReached:x,scrollToIndex:h,topListHeight:m}},pt(Sn,Ft,Dn),{singleton:!0});function qw(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function da(e,t){e==0?t():requestAnimationFrame(()=>{da(e-1,t)})}function fa(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const eo=tt(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=Q(!0),l=Q(0),c=Q(!0);return ve(H(i,$e(l),Ae(([d,f])=>!!f),bn(!1)),a),ve(H(i,$e(l),Ae(([d,f])=>!!f),bn(!1)),c),it(H(kt(t,i),$e(a,n,e,c),Ae(([[,d],f,{sizeTree:p},h,x])=>d&&(!ut(p)||ea(h))&&!f&&!x),$e(l)),([,d])=>{un(o,()=>{De(c,!0)}),da(4,()=>{un(r,()=>{De(a,!0)}),De(s,d)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:a}},pt(Sn,Ft,Qr,$n),{singleton:!0});function Vd(e,t){return Math.abs(e-t)<1.01}const to="up",no="down",Gw="none",Yw={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},Xw=0,ro=tt(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=Q(!1),a=Q(!0),l=Ye(),c=Ye(),d=Q(4),f=Q(Xw),p=Ot(H(na(H(Ie(o),er(1),bn(!0)),H(Ie(o),er(1),bn(!1),Nd(100))),ht()),!1),h=Ot(H(na(H(n,bn(!0)),H(n,bn(!1),Nd(200))),ht()),!1);ve(H(kt(Ie(o),Ie(f)),ue(([b,S])=>b<=S),ht()),a),ve(H(a,An(50)),c);const x=Gt(H(kt(r,Ie(s),Ie(t),Ie(e),Ie(d)),wn((b,[{scrollHeight:S,scrollTop:k},C,T,E,N])=>{const _=k+C-S>-N,P={scrollHeight:S,scrollTop:k,viewportHeight:C};if(_){let D,F;return k>b.state.scrollTop?(D="SCROLLED_DOWN",F=b.state.scrollTop-k):(D="SIZE_DECREASED",F=b.state.scrollTop-k||b.scrollTopDelta),{atBottom:!0,atBottomBecause:D,scrollTopDelta:F,state:P}}let R;return P.scrollHeight>b.state.scrollHeight?R="SIZE_INCREASED":C<b.state.viewportHeight?R="VIEWPORT_HEIGHT_DECREASING":k<b.state.scrollTop?R="SCROLLING_UPWARDS":R="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:R,state:P}},Yw),ht((b,S)=>b&&b.atBottom===S.atBottom))),m=Ot(H(r,wn((b,{scrollHeight:S,scrollTop:k,viewportHeight:C})=>{if(Vd(b.scrollHeight,S))return{changed:!1,jump:0,scrollHeight:S,scrollTop:k};{const T=S-(k+C)<1;return b.scrollTop!==k&&T?{changed:!0,jump:b.scrollTop-k,scrollHeight:S,scrollTop:k}:{changed:!0,jump:0,scrollHeight:S,scrollTop:k}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Ae(b=>b.changed),ue(b=>b.jump)),0);ve(H(x,ue(b=>b.atBottom)),i),ve(H(i,An(50)),l);const v=Q(no);ve(H(r,ue(({scrollTop:b})=>b),ht(),wn((b,S)=>Tt(h)?{direction:b.direction,prevScrollTop:S}:{direction:S<b.prevScrollTop?to:no,prevScrollTop:S},{direction:no,prevScrollTop:0}),ue(b=>b.direction)),v),ve(H(r,An(50),bn(Gw)),v);const g=Q(0);return ve(H(p,Ae(b=>!b),bn(0)),g),ve(H(o,An(100),$e(p),Ae(([b,S])=>!!S),wn(([b,S],[k])=>[S,k],[0,0]),ue(([b,S])=>S-b)),g),{atBottomState:x,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:p,lastJumpDueToItemResize:m,scrollDirection:v,scrollVelocity:g}},pt(Ft)),xs="top",ys="bottom",Kd="none";function qd(e,t,n){return typeof e=="number"?n===to&&t===xs||n===no&&t===ys?e:0:n===to?t===xs?e.main:e.reverse:t===ys?e.main:e.reverse}function Gd(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const pa=tt(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=Ye(),i=Q(0),a=Q(0),l=Q(0),c=Ot(H(kt(Ie(r),Ie(o),Ie(n),Ie(s,Jr),Ie(l),Ie(i),Ie(t),Ie(e),Ie(a)),ue(([d,f,p,[h,x],m,v,g,b,S])=>{const k=d-b,C=v+g,T=Math.max(p-k,0);let E=Kd;const N=Gd(S,xs),_=Gd(S,ys);return h-=b,h+=p+g,x+=p+g,x-=b,h>d+C-N&&(E=to),x<d-T+f+_&&(E=no),E!==Kd?[Math.max(k-p-qd(m,xs,E)-N,0),k-T-g+f+qd(m,ys,E)+_]:null}),Ae(d=>d!=null),ht(Jr)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:c}},pt(Ft),{singleton:!0});function Jw(e,t,n){if(gs(t)){const r=zd(e,t);return[{index:dn(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 ha={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function vs(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:l}=o;let c=0,d=0;if(e.length>0){c=e[0].offset;const m=e[e.length-1];d=m.offset+m.size}const f=n-i,p=a+f*l+(f-1)*r,h=c,x=p-d;return{bottom:d,firstItemIndex:s,items:Xd(e,o,s),offsetBottom:x,offsetTop:c,top:h,topItems:Xd(t,o,s),topListHeight:t.reduce((m,v)=>v.size+m,0),totalCount:n}}function Yd(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=fa(t,a),c=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return vs(c,[],a,o,n,r)}function Xd(e,t,n){if(e.length===0)return[];if(!gs(t))return e.map(c=>({...c,index:c.index+n,originalIndex:c.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=ps(t.groupOffsetTree,r,o);let a,l=0;for(const c of e){(!a||a.end<c.index)&&(a=i.shift(),l=t.groupIndices.indexOf(a.start));let d;c.index===a.start?d={index:l,type:"group"}:d={groupIndex:l,index:c.index-(l+1)+n},s.push({...d,data:c.data,offset:c.offset,originalIndex:c.index,size:c.size})}return s}const rr=tt(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:l},{initialTopMostItemIndex:c,scrolledToInitialItem:d},{topListHeight:f},p,{didMount:h},{recalcInProgress:x}])=>{const m=Q([]),v=Q(0),g=Ye();ve(s.topItemsIndexes,m);const b=Ot(H(kt(h,x,Ie(l,Jr),Ie(o),Ie(r),Ie(c),d,Ie(m),Ie(t),Ie(n),e),Ae(([T,E,,N,,,,,,,_])=>{const P=_&&_.length!==N;return T&&!E&&!P}),ue(([,,[T,E],N,_,P,R,D,F,A,z])=>{const j=_,{offsetTree:J,sizeTree:B}=j,O=Tt(v);if(N===0)return{...ha,totalCount:N};if(T===0&&E===0)return O===0?{...ha,totalCount:N}:Yd(O,P,_,F,A,z||[]);if(ut(B))return O>0?null:vs(Jw(fa(P,N),j,z),[],N,A,j,F);const W=[];if(D.length>0){const G=D[0],U=D[D.length-1];let q=0;for(const $ of ps(B,G,U)){const V=$.value,re=Math.max($.start,G),oe=Math.min($.end,U);for(let se=re;se<=oe;se++)W.push({data:z==null?void 0:z[se],index:se,offset:q,size:V}),q+=V}}if(!R)return vs([],W,N,A,j,F);const X=D.length>0?D[D.length-1]+1:0,he=Fw(J,T,E,X);if(he.length===0)return null;const ae=N-1,Re=fs([],G=>{for(const U of he){const q=U.value;let $=q.offset,V=U.start;const re=q.size;if(q.offset<T){V+=Math.floor((T-q.offset+A)/(re+A));const se=V-U.start;$+=se*re+se*A}V<X&&($+=(X-V)*re,V=X);const oe=Math.min(U.end,ae);for(let se=V;se<=oe&&!($>=E);se++)G.push({data:z==null?void 0:z[se],index:se,offset:$,size:re}),$+=re+A}});return vs(Re,W,N,A,j,F)}),Ae(T=>T!==null),ht()),ha);ve(H(e,Ae(ea),ue(T=>T==null?void 0:T.length)),o),ve(H(b,ue(T=>T.topListHeight)),f),ve(f,a),ve(H(b,ue(T=>[T.top,T.bottom])),i),ve(H(b,ue(T=>T.items)),g);const S=Gt(H(b,Ae(({items:T})=>T.length>0),$e(o,e),Ae(([{items:T},E])=>T[T.length-1].originalIndex===E-1),ue(([,T,E])=>[T-1,E]),ht(Jr),ue(([T])=>T))),k=Gt(H(b,An(200),Ae(({items:T,topItems:E})=>T.length>0&&T[0].originalIndex===E.length),ue(({items:T})=>T[0].index),ht())),C=Gt(H(b,Ae(({items:T})=>T.length>0),ue(({items:T})=>{let E=0,N=T.length-1;for(;T[E].type==="group"&&E<N;)E++;for(;T[N].type==="group"&&N>E;)N--;return{endIndex:T[N].index,startIndex:T[E].index}}),ht($d)));return{endReached:S,initialItemCount:v,itemsRendered:g,listState:b,rangeChanged:C,startReached:k,topItemsIndexes:m,...p}},pt(Sn,Hd,pa,eo,Qr,ro,$n,la),{singleton:!0}),Jd=tt(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=Ye(),i=Ot(H(kt(n,e,r,t,o),ue(([a,l,c,d,f])=>a+l+c+d+f.offsetBottom+f.bottom)),0);return ve(Ie(i),s),{totalListHeight:i,totalListHeightChanged:s}},pt(Ft,rr),{singleton:!0}),Zw=tt(([{viewportHeight:e},{totalListHeight:t}])=>{const n=Q(!1),r=Ot(H(kt(n,e,t),Ae(([o])=>o),ue(([,o,s])=>Math.max(0,o-s)),An(0),ht()),0);return{alignToBottom:n,paddingTopAddition:r}},pt(Ft,Jd),{singleton:!0}),Zd=tt(()=>({context:Q(null)})),Qw=({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,Qd=tt(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:c}])=>{const d=Ye();return ve(H(d,$e(t,l,n,s,o,r,a),$e(e),ue(([[f,p,h,x,m,v,g,b],S])=>{const{align:k,behavior:C,calculateViewLocation:T=Qw,done:E,...N}=f,_=Bd(f,p,x-1),P=Zr(_,p.offsetTree,S)+m+v,R=P+dn(p.sizeTree,_)[1],D=b+v,F=b+h-g,A=T({itemBottom:R,itemTop:P,locationParams:{align:k,behavior:C,...N},viewportBottom:F,viewportTop:D});return A?E&&un(H(i,Ae(z=>!z),er(Tt(i)?1:2)),E):E&&E(),A}),Ae(f=>f!==null)),c),{scrollIntoView:d}},pt(Sn,Ft,Qr,rr,Dn),{singleton:!0});function ef(e){return e?e==="smooth"?"smooth":"auto":!1}const e0=(e,t)=>typeof e=="function"?ef(e(t)):t&&ef(e),t0=tt(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:l,propsReady:c},{log:d},{scrollingInProgress:f},{context:p},{scrollIntoView:h}])=>{const x=Q(!1),m=Ye();let v=null;function g(C){De(i,{align:"end",behavior:C,index:"LAST"})}it(H(kt(H(Ie(t),er(1)),l),$e(Ie(x),s,a,f),ue(([[C,T],E,N,_,P])=>{let R=T&&_,D="auto";return R&&(D=e0(E,N||P),R=R&&!!D),{followOutputBehavior:D,shouldFollow:R,totalCount:C}}),Ae(({shouldFollow:C})=>C)),({followOutputBehavior:C,totalCount:T})=>{v&&(v(),v=null),Tt(n)?requestAnimationFrame(()=>{Tt(d)("following output to ",{totalCount:T},Wt.DEBUG),g(C)}):v=un(e,()=>{Tt(d)("following output to ",{totalCount:T},Wt.DEBUG),g(C),v=null})});function b(C){const T=un(o,E=>{C&&!E.atBottom&&E.notAtBottomBecause==="SIZE_INCREASED"&&!v&&(Tt(d)("scrolling to bottom due to increased size",{},Wt.DEBUG),g("auto"))});setTimeout(T,100)}it(H(kt(Ie(x),t,c),Ae(([C,,T])=>C&&T),wn(({value:C},[,T])=>({refreshed:C===T,value:T}),{refreshed:!1,value:0}),Ae(({refreshed:C})=>C),$e(x,t)),([,C])=>{Tt(a)&&b(C!==!1)}),it(m,()=>{b(Tt(x)!==!1)}),it(kt(Ie(x),o),([C,T])=>{C&&!T.atBottom&&T.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&g("auto")});const S=Q(null),k=Ye();return ve(na(H(Ie(r),ue(C=>{var T;return(T=C==null?void 0:C.length)!=null?T:0})),H(Ie(t))),k),it(H(kt(H(k,er(1)),l),$e(Ie(S),a,f,p),ue(([[C,T],E,N,_,P])=>T&&N&&(E==null?void 0:E({context:P,totalCount:C,scrollingInProgress:_}))),Ae(C=>!!C),An(0)),C=>{v&&(v(),v=null),Tt(n)?requestAnimationFrame(()=>{Tt(d)("scrolling into view",{}),De(h,C)}):v=un(e,()=>{Tt(d)("scrolling into view",{}),De(h,C),v=null})}),{autoscrollToBottom:m,followOutput:x,scrollIntoViewOnChange:S}},pt(Sn,ro,Qr,eo,$n,Dn,Ft,Zd,Qd)),n0=tt(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(ve(H(a,$e(s),Ae(([,l])=>l!==0),$e(o,r,t,n,e),ue(([[,l],c,d,f,p,h=[]])=>Yd(l,c,d,f,p,h))),i),{}),pt(Sn,eo,rr,$n),{singleton:!0}),r0=tt(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=Q(0);return it(H(e,$e(r),Ae(([,o])=>o!==0),ue(([,o])=>({top:o}))),o=>{un(H(n,er(1),Ae(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{De(t,o)})})}),{initialScrollTop:r}},pt($n,Ft,rr),{singleton:!0}),tf=tt(([{scrollVelocity:e}])=>{const t=Q(!1),n=Ye(),r=Q(!1);return ve(H(e,$e(r,t,n),Ae(([o,s])=>!!s),ue(([o,s,i,a])=>{const{enter:l,exit:c}=s;if(i){if(c(o,a))return!1}else if(l(o,a))return!0;return i}),ht()),t),it(H(kt(t,e,n),$e(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},pt(ro),{singleton:!0}),ma=tt(([{scrollContainerState:e,scrollTo:t}])=>{const n=Ye(),r=Ye(),o=Ye(),s=Q(!1),i=Q(void 0);return ve(H(kt(n,r),ue(([{scrollHeight:a,scrollTop:l,viewportHeight:c},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),ve(H(t,$e(r),ue(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},pt(Ft)),o0=tt(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const c=Ye(),d=Q(void 0),f=Q(null),p=Q(null);return ve(a,f),ve(l,p),it(H(c,$e(t,r,i,f,p,n)),([h,x,m,v,g,b,S])=>{const k=Bw(x.sizeTree);v&&g!==null&&b!==null&&(m=g.scrollTop-b.offsetTop),m-=S,h({ranges:k,scrollTop:m})}),ve(H(d,Ae(ea),ue(s0)),o),ve(H(s,$e(d),Ae(([,h])=>h!==void 0),ht(),ue(([,h])=>h.ranges)),e),{getState:c,restoreStateFrom:d}},pt(Sn,Ft,eo,$n,ma));function s0(e){return{align:"start",index:0,offset:e.scrollTop}}const i0=tt(([{topItemsIndexes:e}])=>{const t=Q(0);return ve(H(t,Ae(n=>n>=0),ue(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},pt(rr));function nf(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const a0=nf(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),l0=tt(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:l},{beforeUnshiftWith:c,gap:d,shiftWithOffset:f,sizes:p},{log:h},{recalcInProgress:x}])=>{const m=Gt(H(l,$e(i),wn(([,g,b,S],[{bottom:k,items:C,offsetBottom:T,totalCount:E},N])=>{const _=k+T;let P=0;return b===E&&g.length>0&&C.length>0&&(C[0].originalIndex===0&&g[0].originalIndex===0||(P=_-S,P!==0&&(P+=N))),[P,C,E,_]},[0,[],0,0]),Ae(([g])=>g!==0),$e(r,a,n,o,h,x),Ae(([,g,b,S,,,k])=>!k&&!S&&g!==0&&b===to),ue(([[g],,,,,b])=>(b("Upward scrolling compensation",{amount:g},Wt.DEBUG),g))));function v(g){g>0?(De(t,{behavior:"auto",top:-g}),De(e,0)):(De(e,0),De(t,{behavior:"auto",top:-g}))}return it(H(m,$e(e,s)),([g,b,S])=>{S&&a0()?De(e,b-g):v(-g)}),it(H(kt(Ot(s,!1),e,x),Ae(([g,b,S])=>!g&&!S&&b!==0),ue(([g,b])=>b),An(1)),v),ve(H(f,ue(g=>({top:-g}))),t),it(H(c,$e(p,d),ue(([g,{groupIndices:b,lastSize:S,sizeTree:k},C])=>{function T(E){return E*(S+C)}if(b.length===0)return T(g);{let E=0;const N=Xr(k,0);let _=0,P=0;for(;_<g;){_++,E+=N;let R=b.length===P+1?1/0:b[P+1]-b[P]-1;_+R>g&&(E-=N,R=g-_+1),_+=R,E+=T(R),P++}return E}})),g=>{De(e,g),requestAnimationFrame(()=>{De(t,{top:g}),requestAnimationFrame(()=>{De(e,0),De(x,!1)})})}),{deviation:e}},pt(Ft,ro,rr,Sn,Dn,la)),c0=tt(([e,t,n,r,o,s,i,a,l,c,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...c,...d}),pt(pa,n0,$n,tf,Jd,r0,Zw,ma,Qd,Dn,Zd)),rf=tt(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:l,statefulTotalCount:c,totalCount:d,trackItemSizes:f},{initialItemFinalLocationReached:p,initialTopMostItemIndex:h,scrolledToInitialItem:x},m,v,g,{listState:b,topItemsIndexes:S,...k},{scrollToIndex:C},T,{topItemCount:E},{groupCounts:N},_])=>(ve(k.rangeChanged,_.scrollSeekRangeChanged),ve(H(_.windowViewportRect,ue(P=>P.visibleHeight)),m.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:N,initialItemFinalLocationReached:p,initialTopMostItemIndex:h,scrolledToInitialItem:x,sizeRanges:a,topItemCount:E,topItemsIndexes:S,totalCount:d,...g,groupIndices:s,itemSize:i,listState:b,scrollToIndex:C,statefulTotalCount:c,trackItemSizes:f,...k,..._,...m,sizes:l,...v}),pt(Sn,eo,Ft,o0,t0,rr,Qr,l0,i0,Hd,c0));function u0(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 bs=typeof document<"u"?w.useLayoutEffect:w.useEffect;function of(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=w.createContext({});function l(v,g){v.propsReady&&De(v.propsReady,!1);for(const b of r){const S=v[t.required[b]];De(S,g[b])}for(const b of o)if(b in g){const S=v[t.optional[b]];De(S,g[b])}v.propsReady&&De(v.propsReady,!0)}function c(v){return s.reduce((g,b)=>(g[b]=S=>{const k=v[t.methods[b]];De(k,S)},g),{})}function d(v){return i.reduce((g,b)=>(g[b]=Ew(v[t.events[b]]),g),{})}const f=w.forwardRef((v,g)=>{const{children:b,...S}=v,[k]=w.useState(()=>fs(Nw(e),E=>{l(E,S)})),[C]=w.useState(Id(d,k));bs(()=>{for(const E of i)E in S&&it(C[E],S[E]);return()=>{Object.values(C).map(ta)}},[S,C,k]),bs(()=>{l(k,S)}),w.useImperativeHandle(g,kd(c(k)));const T=n;return u.jsx(a.Provider,{value:k,children:n?u.jsx(T,{...u0([...r,...o,...i],S),children:b}):b})}),p=v=>{const g=w.useContext(a);return w.useCallback(b=>{De(g[v],b)},[g,v])},h=v=>{const g=w.useContext(a)[v],b=w.useCallback(S=>it(g,S),[g]);return w.useSyncExternalStore(b,()=>Tt(g),()=>Tt(g))},x=v=>{const g=w.useContext(a)[v],[b,S]=w.useState(Id(Tt,g));return bs(()=>it(g,k=>{k!==b&&S(kd(k))}),[g,b]),b},m=w.version.startsWith("18")?h:x;return{Component:f,useEmitter:(v,g)=>{const b=w.useContext(a)[v];bs(()=>it(b,g),[g,b])},useEmitterValue:m,usePublisher:p}}const sf=w.createContext(void 0),af=w.createContext(void 0),lf=typeof document<"u"?w.useLayoutEffect:w.useEffect;function ga(e){return"self"in e}function d0(e){return"body"in e}function cf(e,t,n,r=Er,o,s){const i=w.useRef(null),a=w.useRef(null),l=w.useRef(null),c=w.useCallback(p=>{let h,x,m;const v=p.target;if(d0(v)||ga(v)){const b=ga(v)?v:v.defaultView;m=s?b.scrollX:b.scrollY,h=s?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight,x=s?b.innerWidth:b.innerHeight}else m=s?v.scrollLeft:v.scrollTop,h=s?v.scrollWidth:v.scrollHeight,x=s?v.offsetWidth:v.offsetHeight;const g=()=>{e({scrollHeight:h,scrollTop:Math.max(m,0),viewportHeight:x})};p.suppressFlushSync?g():Ys.flushSync(g),a.current!==null&&(m===a.current||m<=0||m===h-x)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);w.useEffect(()=>{const p=o||i.current;return r(o||i.current),c({suppressFlushSync:!0,target:p}),p.addEventListener("scroll",c,{passive:!0}),()=>{r(null),p.removeEventListener("scroll",c)}},[i,c,n,r,o]);function d(p){const h=i.current;if(!h||(s?"offsetWidth"in h&&h.offsetWidth===0:"offsetHeight"in h&&h.offsetHeight===0))return;const x=p.behavior==="smooth";let m,v,g;ga(h)?(v=Math.max(Ln(h.document.documentElement,s?"width":"height"),s?h.document.documentElement.scrollWidth:h.document.documentElement.scrollHeight),m=s?h.innerWidth:h.innerHeight,g=s?window.scrollX:window.scrollY):(v=h[s?"scrollWidth":"scrollHeight"],m=Ln(h,s?"width":"height"),g=h[s?"scrollLeft":"scrollTop"]);const b=v-m;if(p.top=Math.ceil(Math.max(Math.min(b,p.top),0)),Vd(m,v)||p.top===g){e({scrollHeight:v,scrollTop:g,viewportHeight:m}),x&&t(!0);return}x?(a.current=p.top,l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{l.current=null,a.current=null,t(!0)},1e3)):a.current=null,s&&(p={behavior:p.behavior,left:p.top}),h.scrollTo(p)}function f(p){s&&(p={behavior:p.behavior,left:p.top}),i.current.scrollBy(p)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:d}}const xa="-webkit-sticky",uf="sticky",ya=nf(()=>{if(typeof document>"u")return uf;const e=document.createElement("div");return e.style.position=xa,e.style.position===xa?xa:uf});function va(e){return e}const f0=tt(()=>{const e=Q(a=>`Item ${a}`),t=Q(a=>`Group ${a}`),n=Q({}),r=Q(va),o=Q("div"),s=Q(Er),i=(a,l=null)=>Ot(H(n,ue(c=>c[a]),ht()),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")}}),p0=tt(([e,t])=>({...e,...t}),pt(rf,f0)),h0=({height:e})=>u.jsx("div",{style:{height:e}}),m0={overflowAnchor:"none",position:ya(),zIndex:1},df={overflowAnchor:"none"},g0={...df,display:"inline-block",height:"100%"},ff=w.memo(function({showTopList:e=!1}){const t=je("listState"),n=tn("sizeRanges"),r=je("useWindowScroll"),o=je("customScrollParent"),s=tn("windowScrollContainerState"),i=tn("scrollContainerState"),a=o||r?s:i,l=je("itemContent"),c=je("context"),d=je("groupContent"),f=je("trackItemSizes"),p=je("itemSize"),h=je("log"),x=tn("gap"),m=je("horizontalDirection"),{callbackRef:v}=jw(n,p,f,e?Er:a,h,x,o,m,je("skipAnimationFrameInResizeObserver")),[g,b]=w.useState(0);ba("deviation",A=>{g!==A&&b(A)});const S=je("EmptyPlaceholder"),k=je("ScrollSeekPlaceholder")||h0,C=je("ListComponent"),T=je("ItemComponent"),E=je("GroupComponent"),N=je("computeItemKey"),_=je("isSeeking"),P=je("groupIndices").length>0,R=je("alignToBottom"),D=je("initialItemFinalLocationReached"),F=e?{}:{boxSizing:"border-box",...m?{display:"inline-block",height:"100%",marginLeft:g!==0?g:R?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:g!==0?g:R?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...D?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&S?u.jsx(S,{...Mt(S,c)}):u.jsx(C,{...Mt(C,c),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:v,style:F,children:(e?t.topItems:t.items).map(A=>{const z=A.originalIndex,j=N(z+t.firstItemIndex,A.data,c);return _?w.createElement(k,{...Mt(k,c),height:A.size,index:A.index,key:j,type:A.type||"item",...A.type==="group"?{}:{groupIndex:A.groupIndex}}):A.type==="group"?w.createElement(E,{...Mt(E,c),"data-index":z,"data-item-index":A.index,"data-known-size":A.size,key:j,style:m0},d(A.index,c)):w.createElement(T,{...Mt(T,c),...b0(T,A.data),"data-index":z,"data-item-group-index":A.groupIndex,"data-item-index":A.index,"data-known-size":A.size,key:j,style:m?g0:df},P?l(A.index,A.groupIndex,A.data,c):l(A.index,A.data,c))})})}),x0={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},y0={outline:"none",overflowX:"auto",position:"relative"},ws=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),v0={position:ya(),top:0,width:"100%",zIndex:1};function Mt(e,t){if(typeof e!="string")return{context:t}}function b0(e,t){return{item:typeof e=="string"?void 0:t}}const w0=w.memo(function(){const e=je("HeaderComponent"),t=tn("headerHeight"),n=je("HeaderFooterTag"),r=tr(w.useMemo(()=>s=>{t(Ln(s,"height"))},[t]),!0,je("skipAnimationFrameInResizeObserver")),o=je("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Mt(e,o)})}):null}),S0=w.memo(function(){const e=je("FooterComponent"),t=tn("footerHeight"),n=je("HeaderFooterTag"),r=tr(w.useMemo(()=>s=>{t(Ln(s,"height"))},[t]),!0,je("skipAnimationFrameInResizeObserver")),o=je("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Mt(e,o)})}):null});function pf({useEmitter:e,useEmitterValue:t,usePublisher:n}){return w.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:p,scrollerRef:h,scrollToCallback:x}=cf(a,c,l,d,void 0,f);return e("scrollTo",x),e("scrollBy",p),u.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:h,style:{...f?y0:x0,...o},tabIndex:0,...i,...Mt(l,s),children:r})})}function hf({useEmitter:e,useEmitterValue:t,usePublisher:n}){return w.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("totalListHeight"),f=t("deviation"),p=t("customScrollParent"),h=w.useRef(null),x=t("scrollerRef"),{scrollByCallback:m,scrollerRef:v,scrollToCallback:g}=cf(a,c,l,x,p);return lf(()=>{var b;return v.current=p||((b=h.current)==null?void 0:b.ownerDocument.defaultView),()=>{v.current=null}},[v,p]),e("windowScrollTo",g),e("scrollBy",m),u.jsx(l,{ref:h,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...d!==0?{height:d+f}:{}},...i,...Mt(l,s),children:r})})}const C0=({children:e})=>{const t=w.useContext(sf),n=tn("viewportHeight"),r=tn("fixedItemHeight"),o=je("alignToBottom"),s=je("horizontalDirection"),i=w.useMemo(()=>Ed(n,l=>Ln(l,s?"width":"height")),[n,s]),a=tr(i,!0,je("skipAnimationFrameInResizeObserver"));return w.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),u.jsx("div",{"data-viewport-type":"element",ref:a,style:ws(o),children:e})},T0=({children:e})=>{const t=w.useContext(sf),n=tn("windowViewportRect"),r=tn("fixedItemHeight"),o=je("customScrollParent"),s=jd(n,o,je("skipAnimationFrameInResizeObserver")),i=je("alignToBottom");return w.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),u.jsx("div",{"data-viewport-type":"window",ref:s,style:ws(i),children:e})},k0=({children:e})=>{const t=je("TopItemListComponent")||"div",n=je("headerHeight"),r={...v0,marginTop:`${n}px`},o=je("context");return u.jsx(t,{style:r,...Mt(t,o),children:e})},E0=w.memo(function(e){const t=je("useWindowScroll"),n=je("topItemsIndexes").length>0,r=je("customScrollParent"),o=je("context");return u.jsxs(r||t?A0:N0,{...e,context:o,children:[n&&u.jsx(k0,{children:u.jsx(ff,{showTopList:!0})}),u.jsxs(r||t?T0:C0,{children:[u.jsx(w0,{}),u.jsx(ff,{}),u.jsx(S0,{})]})]})}),{Component:I0,useEmitter:ba,useEmitterValue:je,usePublisher:tn}=of(p0,{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"}},E0),N0=pf({useEmitter:ba,useEmitterValue:je,usePublisher:tn}),A0=hf({useEmitter:ba,useEmitterValue:je,usePublisher:tn}),_0=I0;pt(rf,tt(()=>{const e=Q(c=>u.jsxs("td",{children:["Item $",c]})),t=Q(null),n=Q(c=>u.jsxs("td",{colSpan:1e3,children:["Group ",c]})),r=Q(null),o=Q(null),s=Q({}),i=Q(va),a=Q(Er),l=(c,d=null)=>Ot(H(s,ue(f=>f[c]),ht()),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")}})),ya();const mf={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},j0={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:gf,floor:Ss,max:oo,min:wa,round:xf}=Math;function yf(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function R0(e){return{...j0,items:e}}function Cs(e,t){return e&&e.width===t.width&&e.height===t.height}function P0(e,t){return e&&e.column===t.column&&e.row===t.row}const O0=tt(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:l,scrollTop:c,smoothScrollTargetReached:d,viewportHeight:f},p,h,{didMount:x,propsReady:m},{customScrollParent:v,useWindowScroll:g,windowScrollContainerState:b,windowScrollTo:S,windowViewportRect:k},C])=>{const T=Q(0),E=Q(0),N=Q(mf),_=Q({height:0,width:0}),P=Q({height:0,width:0}),R=Ye(),D=Ye(),F=Q(0),A=Q(null),z=Q({column:0,row:0}),j=Ye(),J=Ye(),B=Q(!1),O=Q(0),W=Q(!0),X=Q(!1),he=Q(!1);it(H(x,$e(O),Ae(([$,V])=>!!V)),()=>{De(W,!1)}),it(H(kt(x,W,P,_,O,X),Ae(([$,V,re,oe,,se])=>$&&!V&&re.height!==0&&oe.height!==0&&!se)),([,,,,$])=>{De(X,!0),da(1,()=>{De(R,$)}),un(H(c),()=>{De(t,[0,0]),De(W,!0)})}),ve(H(J,Ae($=>$!=null&&$.scrollTop>0),bn(0)),E),it(H(x,$e(J),Ae(([,$])=>$!=null)),([,$])=>{$&&(De(_,$.viewport),De(P,$.item),De(z,$.gap),$.scrollTop>0&&(De(B,!0),un(H(c,er(1)),V=>{De(B,!1)}),De(l,{top:$.scrollTop})))}),ve(H(_,ue(({height:$})=>$)),f),ve(H(kt(Ie(_,Cs),Ie(P,Cs),Ie(z,($,V)=>$&&$.column===V.column&&$.row===V.row),Ie(c)),ue(([$,V,re,oe])=>({gap:re,item:V,scrollTop:oe,viewport:$}))),j),ve(H(kt(Ie(T),r,Ie(z,P0),Ie(P,Cs),Ie(_,Cs),Ie(A),Ie(E),Ie(B),Ie(W),Ie(O)),Ae(([,,,,,,,$])=>!$),ue(([$,[V,re],oe,se,Se,Qe,Fe,,Xe,nt])=>{const{column:fe,row:ge}=oe,{height:Le,width:Be}=se,{width:Ve}=Se;if(Fe===0&&($===0||Ve===0))return mf;if(Be===0){const It=fa(nt,$),bt=It+Math.max(Fe-1,0);return R0(yf(It,bt,Qe))}const Je=vf(Ve,Be,fe);let ze,Ze;Xe?V===0&&re===0&&Fe>0?(ze=0,Ze=Fe-1):(ze=Je*Ss((V+ge)/(Le+ge)),Ze=Je*gf((re+ge)/(Le+ge))-1,Ze=wa($-1,oo(Ze,Je-1)),ze=wa(Ze,oo(0,ze))):(ze=0,Ze=-1);const Et=yf(ze,Ze,Qe),{bottom:ft,top:Ue}=bf(Se,oe,se,Et),xt=gf($/Je),vt=xt*Le+(xt-1)*ge-ft;return{bottom:ft,itemHeight:Le,items:Et,itemWidth:Be,offsetBottom:vt,offsetTop:Ue,top:Ue}})),N),ve(H(A,Ae($=>$!==null),ue($=>$.length)),T),ve(H(kt(_,P,N,z),Ae(([$,V,{items:re}])=>re.length>0&&V.height!==0&&$.height!==0),ue(([$,V,{items:re},oe])=>{const{bottom:se,top:Se}=bf($,oe,V,re);return[Se,se]}),ht(Jr)),t);const ae=Q(!1);ve(H(c,$e(ae),ue(([$,V])=>V||$!==0)),ae);const Re=Gt(H(kt(N,T),Ae(([{items:$}])=>$.length>0),$e(ae),Ae(([[$,V],re])=>{const oe=$.items[$.items.length-1].index===V-1;return(re||$.bottom>0&&$.itemHeight>0&&$.offsetBottom===0&&$.items.length===V)&&oe}),ue(([[,$]])=>$-1),ht())),G=Gt(H(Ie(N),Ae(({items:$})=>$.length>0&&$[0].index===0),bn(0),ht())),U=Gt(H(Ie(N),$e(B),Ae(([{items:$},V])=>$.length>0&&!V),ue(([{items:$}])=>({endIndex:$[$.length-1].index,startIndex:$[0].index})),ht($d),An(0)));ve(U,h.scrollSeekRangeChanged),ve(H(R,$e(_,P,T,z),ue(([$,V,re,oe,se])=>{const Se=Wd($),{align:Qe,behavior:Fe,offset:Xe}=Se;let nt=Se.index;nt==="LAST"&&(nt=oe-1),nt=oo(0,nt,wa(oe-1,nt));let fe=Sa(V,se,re,nt);return Qe==="end"?fe=xf(fe-V.height+re.height):Qe==="center"&&(fe=xf(fe-V.height/2+re.height/2)),Xe&&(fe+=Xe),{behavior:Fe,top:fe}})),l);const q=Ot(H(N,ue($=>$.offsetBottom+$.bottom)),0);return ve(H(k,ue($=>({height:$.visibleHeight,width:$.visibleWidth}))),_),{customScrollParent:v,data:A,deviation:F,footerHeight:o,gap:z,headerHeight:s,increaseViewportBy:e,initialItemCount:E,itemDimensions:P,overscan:n,restoreStateFrom:J,scrollBy:i,scrollContainerState:a,scrollHeight:D,scrollTo:l,scrollToIndex:R,scrollTop:c,smoothScrollTargetReached:d,totalCount:T,useWindowScroll:g,viewportDimensions:_,windowScrollContainerState:b,windowScrollTo:S,windowViewportRect:k,...h,gridState:N,horizontalDirection:he,initialTopMostItemIndex:O,totalListHeight:q,...p,endReached:Re,propsReady:m,rangeChanged:U,startReached:G,stateChanged:j,stateRestoreInProgress:B,...C}},pt(pa,Ft,ro,tf,$n,ma,Dn));function vf(e,t,n){return oo(1,Ss((e+n)/(Ss(t)+n)))}function bf(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=Sa(e,t,n,r[0].index);return{bottom:Sa(e,t,n,r[r.length-1].index)+o,top:s}}function Sa(e,t,n,r){const o=vf(e.width,n.width,t.column),s=Ss(r/o),i=s*n.height+oo(0,s-1)*t.row;return i>0?i+t.row:i}const M0=tt(()=>{const e=Q(f=>`Item ${f}`),t=Q({}),n=Q(null),r=Q("virtuoso-grid-item"),o=Q("virtuoso-grid-list"),s=Q(va),i=Q("div"),a=Q(Er),l=(f,p=null)=>Ot(H(t,ue(h=>h[f]),ht()),p),c=Q(!1),d=Q(!1);return ve(Ie(d),c),{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:c,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),D0=tt(([e,t])=>({...e,...t}),pt(O0,M0)),L0=w.memo(function(){const e=gt("gridState"),t=gt("listClassName"),n=gt("itemClassName"),r=gt("itemContent"),o=gt("computeItemKey"),s=gt("isSeeking"),i=nn("scrollHeight"),a=gt("ItemComponent"),l=gt("ListComponent"),c=gt("ScrollSeekPlaceholder"),d=gt("context"),f=nn("itemDimensions"),p=nn("gap"),h=gt("log"),x=gt("stateRestoreInProgress"),m=nn("reportReadyState"),v=tr(w.useMemo(()=>g=>{const b=g.parentElement.parentElement.scrollHeight;i(b);const S=g.firstChild;if(S){const{height:k,width:C}=S.getBoundingClientRect();f({height:k,width:C})}p({column:Sf("column-gap",getComputedStyle(g).columnGap,h),row:Sf("row-gap",getComputedStyle(g).rowGap,h)})},[i,f,p,h]),!0,!1);return lf(()=>{e.itemHeight>0&&e.itemWidth>0&&m(!0)},[e]),x?null:u.jsx(l,{className:t,ref:v,...Mt(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(g=>{const b=o(g.index,g.data,d);return s?u.jsx(c,{...Mt(c,d),height:e.itemHeight,index:g.index,width:e.itemWidth},b):w.createElement(a,{...Mt(a,d),className:n,"data-index":g.index,key:b},r(g.index,g.data,d))})})}),$0=w.memo(function(){const e=gt("HeaderComponent"),t=nn("headerHeight"),n=gt("headerFooterTag"),r=tr(w.useMemo(()=>s=>{t(Ln(s,"height"))},[t]),!0,!1),o=gt("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Mt(e,o)})}):null}),F0=w.memo(function(){const e=gt("FooterComponent"),t=nn("footerHeight"),n=gt("headerFooterTag"),r=tr(w.useMemo(()=>s=>{t(Ln(s,"height"))},[t]),!0,!1),o=gt("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Mt(e,o)})}):null}),z0=({children:e})=>{const t=w.useContext(af),n=nn("itemDimensions"),r=nn("viewportDimensions"),o=tr(w.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return w.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),u.jsx("div",{ref:o,style:ws(!1),children:e})},B0=({children:e})=>{const t=w.useContext(af),n=nn("windowViewportRect"),r=nn("itemDimensions"),o=gt("customScrollParent"),s=jd(n,o,!1);return w.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),u.jsx("div",{ref:s,style:ws(!1),children:e})},U0=w.memo(function({...e}){const t=gt("useWindowScroll"),n=gt("customScrollParent"),r=n||t?W0:H0,o=n||t?B0:z0,s=gt("context");return u.jsx(r,{...e,...Mt(r,s),children:u.jsxs(o,{children:[u.jsx($0,{}),u.jsx(L0,{}),u.jsx(F0,{})]})})}),{useEmitter:wf,useEmitterValue:gt,usePublisher:nn}=of(D0,{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"}},U0),H0=pf({useEmitter:wf,useEmitterValue:gt,usePublisher:nn}),W0=hf({useEmitter:wf,useEmitterValue:gt,usePublisher:nn});function Sf(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Wt.WARN),t==="normal"?0:parseInt(t??"0",10)}const V0=mo.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 Cf({className:e,variant:t,...n}){return u.jsx("div",{className:te(V0({variant:t}),e),...n})}const so=y.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:te("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));so.displayName="Card";const io=y.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:te("flex flex-col space-y-1.5 p-6",e),...t}));io.displayName="CardHeader";const ao=y.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:te("text-2xl font-semibold leading-none tracking-tight",e),...t}));ao.displayName="CardTitle";const Tf=y.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:te("text-sm text-muted-foreground",e),...t}));Tf.displayName="CardDescription";const lo=y.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:te("p-6 pt-0",e),...t}));lo.displayName="CardContent";const kf=y.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:te("flex items-center p-6 pt-0",e),...t}));kf.displayName="CardFooter";const K0=1,q0=1e6;let Ca=0;function G0(){return Ca=(Ca+1)%Number.MAX_SAFE_INTEGER,Ca.toString()}const Ta=new Map,Ef=e=>{if(Ta.has(e))return;const t=setTimeout(()=>{Ta.delete(e),co({type:"REMOVE_TOAST",toastId:e})},q0);Ta.set(e,t)},Y0=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,K0)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?Ef(n):e.toasts.forEach(r=>{Ef(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Ts=[];let ks={toasts:[]};function co(e){ks=Y0(ks,e),Ts.forEach(t=>{t(ks)})}function X0({...e}){const t=G0(),n=o=>co({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>co({type:"DISMISS_TOAST",toastId:t});return co({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function ka(){const[e,t]=y.useState(ks);return y.useEffect(()=>(Ts.push(t),()=>{const n=Ts.indexOf(t);n>-1&&Ts.splice(n,1)}),[e]),{...e,toast:X0,dismiss:n=>co({type:"DISMISS_TOAST",toastId:n})}}async function If(e,t){return await Jt(e,{responseType:"blob",onDownloadProgress:r=>{try{t&&r.lengthComputable}catch{}},maxBodyLength:1/0})}async function Nf(e,t){return await(await If(`/files/${e}/view`,t)).text()}async function J0(e,t){const n=await If(`/files/${e}/download`,t),r=URL.createObjectURL(n);let o=`file_${e}`;try{const i=await Jt(`/files/${e}`);o=(i==null?void 0:i.filename)??o}catch{}const s=document.createElement("a");s.href=r,s.download=o,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}async function Z0(e,t=50,n=0){const r={limit:t,offset:n};return e&&(r.thread_id=e),await Jt("/files",{params:r})}function Ea(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{return null}}function Af(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function uo(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(uo).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(Af(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const o=uo(r);o!==void 0&&(t[n]=o)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function fo(e){if(typeof e=="string")return e;if(Af(e))return"";try{const t=uo(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function Q0(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function eS(e){const t=fo(e);return typeof e=="string"&&Q0(e)?{content:e,isMarkdown:!0}:{content:t,isMarkdown:!1}}function Es(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")||t.startsWith("[")){const n=Ea(t);if(n!==null)return Es(n)}return e}return typeof e=="object"&&!Array.isArray(e)&&e.content!==void 0?Es(e.content):e}const tS={MODE:"library"};function nS(){var i;const e=typeof globalThis<"u"?globalThis.process:void 0,t=typeof((i=e==null?void 0:e.env)==null?void 0:i.NODE_ENV)=="string"?e.env.NODE_ENV:void 0;if(t)return t==="production";const n=typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Xs&&Xs.tagName.toUpperCase()==="SCRIPT"&&Xs.src||new URL("index.umd.js",document.baseURI).href}<"u"?tS:void 0,r=typeof(n==null?void 0:n.MODE)=="string"?n.MODE:void 0,o=typeof(n==null?void 0:n.NODE_ENV)=="string"?n.NODE_ENV:void 0;return(r??o)==="production"}function rS(){return!nS()}function oS(){return typeof window>"u"?!1:window.__ARTIFACT_DEBUG__===!0}function sS(){return rS()||oS()}var Is="Dialog",[_f,LT]=kn(Is),[iS,fn]=_f(Is),jf=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:s,modal:i=!0}=e,a=y.useRef(null),l=y.useRef(null),[c,d]=gr({prop:r,defaultProp:o??!1,onChange:s,caller:Is});return u.jsx(iS,{scope:t,triggerRef:a,contentRef:l,contentId:En(),titleId:En(),descriptionId:En(),open:c,onOpenChange:d,onOpenToggle:y.useCallback(()=>d(f=>!f),[d]),modal:i,children:n})};jf.displayName=Is;var Rf="DialogTrigger",Pf=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=fn(Rf,n),s=Ge(t,o.triggerRef);return u.jsx(Oe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Aa(o.open),...r,ref:s,onClick:me(e.onClick,o.onOpenToggle)})});Pf.displayName=Rf;var Ia="DialogPortal",[aS,Of]=_f(Ia,{forceMount:void 0}),Mf=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,s=fn(Ia,t);return u.jsx(aS,{scope:t,forceMount:n,children:y.Children.map(r,i=>u.jsx(Qt,{present:n||s.open,children:u.jsx(Yo,{asChild:!0,container:o,children:i})}))})};Mf.displayName=Ia;var Ns="DialogOverlay",Df=y.forwardRef((e,t)=>{const n=Of(Ns,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=fn(Ns,e.__scopeDialog);return s.modal?u.jsx(Qt,{present:r||s.open,children:u.jsx(cS,{...o,ref:t})}):null});Df.displayName=Ns;var lS=qn.createSlot("DialogOverlay.RemoveScroll"),cS=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=fn(Ns,n);return u.jsx(os,{as:lS,allowPinchZoom:!0,shards:[o.contentRef],children:u.jsx(Oe.div,{"data-state":Aa(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),or="DialogContent",Lf=y.forwardRef((e,t)=>{const n=Of(or,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=fn(or,e.__scopeDialog);return u.jsx(Qt,{present:r||s.open,children:s.modal?u.jsx(uS,{...o,ref:t}):u.jsx(dS,{...o,ref:t})})});Lf.displayName=or;var uS=y.forwardRef((e,t)=>{const n=fn(or,e.__scopeDialog),r=y.useRef(null),o=Ge(t,n.contentRef,r);return y.useEffect(()=>{const s=r.current;if(s)return zi(s)},[]),u.jsx($f,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:me(e.onCloseAutoFocus,s=>{var i;s.preventDefault(),(i=n.triggerRef.current)==null||i.focus()}),onPointerDownOutside:me(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,a=i.button===0&&i.ctrlKey===!0;(i.button===2||a)&&s.preventDefault()}),onFocusOutside:me(e.onFocusOutside,s=>s.preventDefault())})}),dS=y.forwardRef((e,t)=>{const n=fn(or,e.__scopeDialog),r=y.useRef(!1),o=y.useRef(!1);return u.jsx($f,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,s),s.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),s.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:s=>{var l,c;(l=e.onInteractOutside)==null||l.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;((c=n.triggerRef.current)==null?void 0:c.contains(i))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),$f=y.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,...i}=e,a=fn(or,n),l=y.useRef(null),c=Ge(t,l);return wi(),u.jsxs(u.Fragment,{children:[u.jsx(Lo,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:u.jsx(Do,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":Aa(a.open),...i,ref:c,onDismiss:()=>a.onOpenChange(!1)})}),u.jsxs(u.Fragment,{children:[u.jsx(fS,{titleId:a.titleId}),u.jsx(hS,{contentRef:l,descriptionId:a.descriptionId})]})]})}),Na="DialogTitle",Ff=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=fn(Na,n);return u.jsx(Oe.h2,{id:o.titleId,...r,ref:t})});Ff.displayName=Na;var zf="DialogDescription",Bf=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=fn(zf,n);return u.jsx(Oe.p,{id:o.descriptionId,...r,ref:t})});Bf.displayName=zf;var Uf="DialogClose",Hf=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=fn(Uf,n);return u.jsx(Oe.button,{type:"button",...r,ref:t,onClick:me(e.onClick,()=>o.onOpenChange(!1))})});Hf.displayName=Uf;function Aa(e){return e?"open":"closed"}var Wf="DialogTitleWarning",[$T,Vf]=cx(Wf,{contentName:or,titleName:Na,docsSlug:"dialog"}),fS=({titleId:e})=>{const t=Vf(Wf),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
86
+ `).trim():n.replace(/</g,"&lt;").replace(/>/g,"&gt;").trim()}function vw(e,t=us){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 bw(e){let t;return typeof e=="string"?t=e:typeof e=="object"&&e!==null?t=JSON.stringify(e):t=String(e),vw(t),yw(t)}const ds=0,Mn=1,kr=2,Td=4;function kd(e){return()=>e}function ww(e){e()}function Ed(e,t){return n=>e(t(n))}function Id(e,t){return()=>e(t)}function Sw(e,t){return n=>e(t,n)}function ea(e){return e!==void 0}function Cw(...e){return()=>{e.map(ww)}}function Er(){}function fs(e,t){return t(e),e}function Tw(e,t){return t(e)}function pt(...e){return e}function it(e,t){return e(Mn,t)}function De(e,t){e(ds,t)}function ta(e){e(kr)}function Tt(e){return e(Td)}function ve(e,t){return it(e,Sw(t,ds))}function un(e,t){const n=e(Mn,r=>{n(),t(r)});return n}function Nd(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function Ad(e,t){return e===t}function ht(e=Ad){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function Ae(e){return t=>n=>{e(n)&&t(n)}}function ce(e){return t=>Ed(t,e)}function bn(e){return t=>()=>{t(e)}}function H(e,...t){const n=kw(...t);return(r,o)=>{switch(r){case kr:ta(e);return;case Mn:return it(e,n(o))}}}function wn(e,t){return n=>r=>{n(t=e(t,r))}}function er(e){return t=>n=>{e>0?e--:t(n)}}function An(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function $e(...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);it(s,l=>{const c=n;n=n|a,t[i]=l,c!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function kw(...e){return t=>e.reduceRight(Tw,t)}function Ew(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case Mn:return s?n===s?void 0:(r(),n=s,t=it(e,s),t):(r(),Er);case kr:r(),n=null;return}}}function Q(e){let t=e;const n=Ye();return(r,o)=>{switch(r){case ds:t=o;break;case Mn:{o(t);break}case Td:return t}return n(r,o)}}function Ot(e,t){return fs(Q(t),n=>ve(e,n))}function Ye(){const e=[];return(t,n)=>{switch(t){case ds:e.slice().forEach(r=>{r(n)});return;case kr:e.splice(0,e.length);return;case Mn:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function Gt(e){return fs(Ye(),t=>ve(e,t))}function tt(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:Iw(),singleton:n}}const Iw=()=>Symbol();function Nw(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 kt(...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);it(s,l=>{n[i]=l,r=r|a,r===o&&De(t,n)})}),function(s,i){switch(s){case kr:{ta(t);return}case Mn:return r===o&&i(n),it(t,i)}}}function Ie(e,t=Ad){return H(e,ht(t))}function na(...e){return function(t,n){switch(t){case kr:return;case Mn:return Cw(...e.map(r=>it(r,n)))}}}var Wt=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(Wt||{});const Aw={0:"debug",3:"error",1:"log",2:"warn"},_w=()=>typeof globalThis>"u"?window:globalThis,Dn=tt(()=>{const e=Q(3);return{log:Q((t,n,r=1)=>{var o;const s=(o=_w().VIRTUOSO_LOG_LEVEL)!=null?o:Tt(e);r>=s&&console[Aw[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function tr(e,t,n){return ra(e,t,n).callbackRef}function ra(e,t,n){const r=w.useRef(null);let o=i=>{};const s=w.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 jw(e,t,n,r,o,s,i,a,l){const c=w.useCallback(d=>{const f=Rw(d.children,t,a?"offsetWidth":"offsetHeight",o);let p=d.parentElement;for(;!p.dataset.virtuosoScroller;)p=p.parentElement;const h=p.lastElementChild.dataset.viewportType==="window";let x;h&&(x=p.ownerDocument.defaultView);const m=i?a?i.scrollLeft:i.scrollTop:h?a?x.scrollX||x.document.documentElement.scrollLeft:x.scrollY||x.document.documentElement.scrollTop:a?p.scrollLeft:p.scrollTop,v=i?a?i.scrollWidth:i.scrollHeight:h?a?x.document.documentElement.scrollWidth:x.document.documentElement.scrollHeight:a?p.scrollWidth:p.scrollHeight,g=i?a?i.offsetWidth:i.offsetHeight:h?a?x.innerWidth:x.innerHeight:a?p.offsetWidth:p.offsetHeight;r({scrollHeight:v,scrollTop:Math.max(m,0),viewportHeight:g}),s==null||s(a?_d("column-gap",getComputedStyle(d).columnGap,o):_d("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return ra(c,n,l)}function Rw(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),c=parseFloat(a.dataset.knownSize),d=t(a,n);if(d===0&&r("Zero-sized element, this should not happen",{child:a},Wt.ERROR),d===c)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 _d(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Wt.WARN),t==="normal"?0:parseInt(t??"0",10)}function jd(e,t,n){const r=w.useRef(null),o=w.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const c=l.getBoundingClientRect(),d=c.width;let f,p;if(t){const h=t.getBoundingClientRect(),x=c.top-h.top;p=h.height-Math.max(0,x),f=x+t.scrollTop}else{const h=i.current.ownerDocument.defaultView;p=h.innerHeight-Math.max(0,c.top),f=c.top+h.scrollY}r.current={offsetTop:f,visibleHeight:p,visibleWidth:d},e(r.current)},[e,t]),{callbackRef:s,ref:i}=ra(o,!0,n),a=w.useCallback(()=>{o(i.current)},[o,i]);return w.useEffect(()=>{var l;if(t){t.addEventListener("scroll",a);const c=new ResizeObserver(()=>{requestAnimationFrame(a)});return c.observe(t),()=>{t.removeEventListener("scroll",a),c.unobserve(t)}}else{const c=(l=i.current)==null?void 0:l.ownerDocument.defaultView;return c==null||c.addEventListener("scroll",a),c==null||c.addEventListener("resize",a),()=>{c==null||c.removeEventListener("scroll",a),c==null||c.removeEventListener("resize",a)}}},[a,t,i]),s}const Ft=tt(()=>{const e=Ye(),t=Ye(),n=Q(0),r=Ye(),o=Q(0),s=Ye(),i=Ye(),a=Q(0),l=Q(0),c=Q(0),d=Q(0),f=Ye(),p=Ye(),h=Q(!1),x=Q(!1),m=Q(!1);return ve(H(e,ce(({scrollTop:v})=>v)),t),ve(H(e,ce(({scrollHeight:v})=>v)),i),ve(t,o),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:x,scrollBy:p,scrollContainerState:e,scrollHeight:i,scrollingInProgress:h,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:m,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),Yr={lvl:0};function Rd(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 ut(e){return e===Yr}function Xr(e,t){if(!ut(e))return t===e.k?e.v:t<e.k?Xr(e.l,t):Xr(e.r,t)}function dn(e,t,n="k"){if(ut(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=dn(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return dn(e.l,t,n)}function Yt(e,t,n){return ut(e)?Md(t,n,1):t===e.k?At(e,{k:t,v:n}):t<e.k?Dd(At(e,{l:Yt(e.l,t,n)})):Dd(At(e,{r:Yt(e.r,t,n)}))}function Ir(){return Yr}function ps(e,t,n){if(ut(e))return[];const r=dn(e,t)[0];return Pw(sa(e,r,n))}function oa(e,t){if(ut(e))return Yr;const{k:n,l:r,r:o}=e;if(t===n){if(ut(r))return o;if(ut(o))return r;{const[s,i]=Od(r);return hs(At(e,{k:s,l:Pd(r),v:i}))}}else return t<n?hs(At(e,{l:oa(r,t)})):hs(At(e,{r:oa(o,t)}))}function nr(e){return ut(e)?[]:[...nr(e.l),{k:e.k,v:e.v},...nr(e.r)]}function sa(e,t,n){if(ut(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(sa(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(sa(s,t,n))),a}function hs(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(ia(t))return Ld(At(e,{lvl:n-1}));if(!ut(t)&&!ut(t.r))return At(t.r,{l:At(t,{r:t.r.l}),lvl:n,r:At(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(ia(e))return aa(At(e,{lvl:n-1}));if(!ut(r)&&!ut(r.l)){const o=r.l,s=ia(o)?r.lvl-1:r.lvl;return At(o,{l:At(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:aa(At(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function At(e,t){return Md(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 Pd(e){return ut(e.r)?e.l:hs(At(e,{r:Pd(e.r)}))}function ia(e){return ut(e)||e.lvl>e.r.lvl}function Od(e){return ut(e.r)?[e.k,e.v]:Od(e.r)}function Md(e,t,n,r=Yr,o=Yr){return{k:e,l:r,lvl:n,r:o,v:t}}function Dd(e){return aa(Ld(e))}function Ld(e){const{l:t}=e;return!ut(t)&&t.lvl===e.lvl?At(t,{r:At(e,{l:t.r})}):e}function aa(e){const{lvl:t,r:n}=e;return!ut(n)&&!ut(n.r)&&n.lvl===t&&n.r.lvl===t?At(n,{l:At(e,{r:n.l}),lvl:t+1}):e}function Pw(e){return Rd(e,({k:t,v:n})=>({index:t,value:n}))}function $d(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function Jr(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const la=tt(()=>({recalcInProgress:Q(!1)}),[],{singleton:!0});function Fd(e,t,n){return e[ms(e,t,n)]}function ms(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 Ow(e,t,n,r){const o=ms(e,t,r),s=ms(e,n,r,o);return e.slice(o,s+1)}function Ln(e,t){return Math.round(e.getBoundingClientRect()[t])}function gs(e){return!ut(e.groupOffsetTree)}function ca({index:e},t){return t===e?0:t<e?-1:1}function Mw(){return{groupIndices:[],groupOffsetTree:Ir(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:Ir()}}function Dw(e,t){let n=ut(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),ut(e)){e=Yt(e,0,s);continue}const a=ps(e,i-1,o+1);if(a.some(Hw(r)))continue;let l=!1,c=!1;for(const{end:d,start:f,value:p}of a)l?(o>=f||s===p)&&(e=oa(e,f)):(c=p!==s,l=!0),d>o&&o>=f&&p!==s&&(e=Yt(e,o+1,p));c&&(e=Yt(e,i,s))}return[e,n]}function Lw(e){return typeof e.groupIndex<"u"}function $w({offset:e},t){return t===e?0:t<e?-1:1}function Zr(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=Fd(t,e,ca),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function zd(e,t){if(!gs(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function Bd(e,t,n){if(Lw(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=zd(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function Fw(e,t,n,r=0){return r>0&&(t=Math.max(t,Fd(e,r,ca).offset)),Rd(Ow(e,t,n,$w),Uw)}function zw(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,Wt.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&ut(s)&&t.length===2){const p=t[0].size,h=t[1].size;i=n.reduce((x,m)=>Yt(Yt(x,m,p),m+1,h),i)}else[i,a]=Dw(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f}=ua(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((p,h)=>Yt(p,h,Zr(h,f,o)),Ir()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f,sizeTree:i}}function Bw(e){return nr(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 Ud(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 ua(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=ms(o,t-1,ca),a=o[l].offset;const c=dn(n,t-1);s=c[0],i=c[1],o.length&&o[l].size===dn(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:c,value:d}of ps(n,t,1/0)){const f=c-s,p=f*i+a+f*r;o.push({index:c,offset:p,size:d}),s=c,a=p,i=d}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function Uw(e){return{index:e.index,value:e}}function Hw(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 Ww={offsetHeight:"height",offsetWidth:"width"},Sn=tt(([{log:e},{recalcInProgress:t}])=>{const n=Ye(),r=Ye(),o=Ot(r,0),s=Ye(),i=Ye(),a=Q(0),l=Q([]),c=Q(void 0),d=Q(void 0),f=Q((C,T)=>Ln(C,Ww[T])),p=Q(void 0),h=Q(0),x=Mw(),m=Ot(H(n,$e(l,e,h),wn(zw,x),ht()),x),v=Ot(H(l,ht(),wn((C,T)=>({current:T,prev:C.current}),{current:[],prev:[]}),ce(({prev:C})=>C)),[]);ve(H(l,Ae(C=>C.length>0),$e(m,h),ce(([C,T,E])=>{const N=C.reduce((_,P,R)=>Yt(_,P,Zr(P,T.offsetTree,E)||R),Ir());return{...T,groupIndices:C,groupOffsetTree:N}})),m),ve(H(r,$e(m),Ae(([C,{lastIndex:T}])=>C<T),ce(([C,{lastIndex:T,lastSize:E}])=>[{endIndex:T,size:E,startIndex:C}])),n),ve(c,d);const g=Ot(H(c,ce(C=>C===void 0)),!0);ve(H(d,Ae(C=>C!==void 0&&ut(Tt(m).sizeTree)),ce(C=>[{endIndex:0,size:C,startIndex:0}])),n);const b=Gt(H(n,$e(m),wn(({sizes:C},[T,E])=>({changed:E!==C,sizes:E}),{changed:!1,sizes:x}),ce(C=>C.changed)));it(H(a,wn((C,T)=>({diff:C.prev-T,prev:T}),{diff:0,prev:0}),ce(C=>C.diff)),C=>{const{groupIndices:T}=Tt(m);if(C>0)De(t,!0),De(s,C+Ud(C,T));else if(C<0){const E=Tt(v);E.length>0&&(C-=Ud(-C,E)),De(i,C)}}),it(H(a,$e(e)),([C,T])=>{C<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},Wt.ERROR)});const S=Gt(s);ve(H(s,$e(m),ce(([C,T])=>{const E=T.groupIndices.length>0,N=[],_=T.lastSize;if(E){const P=Xr(T.sizeTree,0);let R=0,D=0;for(;R<C;){const A=T.groupIndices[D],z=T.groupIndices.length===D+1?1/0:T.groupIndices[D+1]-A-1;N.push({endIndex:A,size:P,startIndex:A}),N.push({endIndex:A+1+z-1,size:_,startIndex:A+1}),D++,R+=z+1}const F=nr(T.sizeTree);return R!==C&&F.shift(),F.reduce((A,{k:z,v:j})=>{let J=A.ranges;return A.prevSize!==0&&(J=[...A.ranges,{endIndex:z+C-1,size:A.prevSize,startIndex:A.prevIndex}]),{prevIndex:z+C,prevSize:j,ranges:J}},{prevIndex:C,prevSize:0,ranges:N}).ranges}return nr(T.sizeTree).reduce((P,{k:R,v:D})=>({prevIndex:R+C,prevSize:D,ranges:[...P.ranges,{endIndex:R+C-1,size:P.prevSize,startIndex:P.prevIndex}]}),{prevIndex:0,prevSize:_,ranges:[]}).ranges})),n);const k=Gt(H(i,$e(m,h),ce(([C,{offsetTree:T},E])=>{const N=-C;return Zr(N,T,E)})));return ve(H(i,$e(m,h),ce(([C,T,E])=>{if(T.groupIndices.length>0){if(ut(T.sizeTree))return T;let N=Ir();const _=Tt(v);let P=0,R=0,D=0;for(;P<-C;){D=_[R];const F=_[R+1]-D-1;R++,P+=F+1}if(N=nr(T.sizeTree).reduce((F,{k:A,v:z})=>Yt(F,Math.max(0,A+C),z),N),P!==-C){const F=Xr(T.sizeTree,D);N=Yt(N,0,F);const A=dn(T.sizeTree,-C+1)[1];N=Yt(N,1,A)}return{...T,sizeTree:N,...ua(T.offsetTree,0,N,E)}}else{const N=nr(T.sizeTree).reduce((_,{k:P,v:R})=>Yt(_,Math.max(0,P+C),R),Ir());return{...T,sizeTree:N,...ua(T.offsetTree,0,N,E)}}})),m),{beforeUnshiftWith:S,data:p,defaultItemSize:d,firstItemIndex:a,fixedItemSize:c,gap:h,groupIndices:l,itemSize:f,listRefresh:b,shiftWith:i,shiftWithOffset:k,sizeRanges:n,sizes:m,statefulTotalCount:o,totalCount:r,trackItemSizes:g,unshiftWith:s}},pt(Dn,la),{singleton:!0});function Vw(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const Hd=tt(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=Ye(),i=Ye(),a=Gt(H(s,ce(Vw)));return ve(H(a,ce(l=>l.totalCount)),n),ve(H(a,ce(l=>l.groupIndices)),e),ve(H(kt(o,t,r),Ae(([l,c])=>gs(c)),ce(([l,c,d])=>dn(c.groupOffsetTree,Math.max(l-d,0),"v")[0]),ht(),ce(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},pt(Sn,Ft)),$n=tt(([{log:e}])=>{const t=Q(!1),n=Gt(H(t,Ae(r=>r),ht()));return it(t,r=>{r&&Tt(e)("props updated",{},Wt.DEBUG)}),{didMount:n,propsReady:t}},pt(Dn),{singleton:!0}),Kw=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Wd(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!Kw)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const Qr=tt(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:l,scrollTo:c,smoothScrollTargetReached:d,viewportHeight:f},{log:p}])=>{const h=Ye(),x=Ye(),m=Q(0);let v=null,g=null,b=null;function S(){v&&(v(),v=null),b&&(b(),b=null),g&&(clearTimeout(g),g=null),De(l,!1)}return ve(H(h,$e(n,f,r,m,a,i,p),$e(e,s,o),ce(([[k,C,T,E,N,_,P,R],D,F,A])=>{const z=Wd(k),{align:j,behavior:J,offset:B}=z,O=E-1,W=Bd(z,C,O);let X=Zr(W,C.offsetTree,D)+_;j==="end"?(X+=F+dn(C.sizeTree,W)[1]-T+A,W===O&&(X+=P)):j==="center"?X+=(F+dn(C.sizeTree,W)[1]-T+A)/2:X-=N,B&&(X+=B);const fe=ae=>{S(),ae?(R("retrying to scroll to",{location:k},Wt.DEBUG),De(h,k)):(De(x,!0),R("list did not change, scroll successful",{},Wt.DEBUG))};if(S(),J==="smooth"){let ae=!1;b=it(t,Re=>{ae=ae||Re}),v=un(d,()=>{fe(ae)})}else v=un(H(t,qw(150)),fe);return g=setTimeout(()=>{S()},1200),De(l,!0),R("scrolling from index to",{behavior:J,index:W,top:X},Wt.DEBUG),{behavior:J,top:X}})),c),{scrollTargetReached:x,scrollToIndex:h,topListHeight:m}},pt(Sn,Ft,Dn),{singleton:!0});function qw(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function da(e,t){e==0?t():requestAnimationFrame(()=>{da(e-1,t)})}function fa(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const eo=tt(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=Q(!0),l=Q(0),c=Q(!0);return ve(H(i,$e(l),Ae(([d,f])=>!!f),bn(!1)),a),ve(H(i,$e(l),Ae(([d,f])=>!!f),bn(!1)),c),it(H(kt(t,i),$e(a,n,e,c),Ae(([[,d],f,{sizeTree:p},h,x])=>d&&(!ut(p)||ea(h))&&!f&&!x),$e(l)),([,d])=>{un(o,()=>{De(c,!0)}),da(4,()=>{un(r,()=>{De(a,!0)}),De(s,d)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:a}},pt(Sn,Ft,Qr,$n),{singleton:!0});function Vd(e,t){return Math.abs(e-t)<1.01}const to="up",no="down",Gw="none",Yw={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},Xw=0,ro=tt(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=Q(!1),a=Q(!0),l=Ye(),c=Ye(),d=Q(4),f=Q(Xw),p=Ot(H(na(H(Ie(o),er(1),bn(!0)),H(Ie(o),er(1),bn(!1),Nd(100))),ht()),!1),h=Ot(H(na(H(n,bn(!0)),H(n,bn(!1),Nd(200))),ht()),!1);ve(H(kt(Ie(o),Ie(f)),ce(([b,S])=>b<=S),ht()),a),ve(H(a,An(50)),c);const x=Gt(H(kt(r,Ie(s),Ie(t),Ie(e),Ie(d)),wn((b,[{scrollHeight:S,scrollTop:k},C,T,E,N])=>{const _=k+C-S>-N,P={scrollHeight:S,scrollTop:k,viewportHeight:C};if(_){let D,F;return k>b.state.scrollTop?(D="SCROLLED_DOWN",F=b.state.scrollTop-k):(D="SIZE_DECREASED",F=b.state.scrollTop-k||b.scrollTopDelta),{atBottom:!0,atBottomBecause:D,scrollTopDelta:F,state:P}}let R;return P.scrollHeight>b.state.scrollHeight?R="SIZE_INCREASED":C<b.state.viewportHeight?R="VIEWPORT_HEIGHT_DECREASING":k<b.state.scrollTop?R="SCROLLING_UPWARDS":R="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:R,state:P}},Yw),ht((b,S)=>b&&b.atBottom===S.atBottom))),m=Ot(H(r,wn((b,{scrollHeight:S,scrollTop:k,viewportHeight:C})=>{if(Vd(b.scrollHeight,S))return{changed:!1,jump:0,scrollHeight:S,scrollTop:k};{const T=S-(k+C)<1;return b.scrollTop!==k&&T?{changed:!0,jump:b.scrollTop-k,scrollHeight:S,scrollTop:k}:{changed:!0,jump:0,scrollHeight:S,scrollTop:k}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Ae(b=>b.changed),ce(b=>b.jump)),0);ve(H(x,ce(b=>b.atBottom)),i),ve(H(i,An(50)),l);const v=Q(no);ve(H(r,ce(({scrollTop:b})=>b),ht(),wn((b,S)=>Tt(h)?{direction:b.direction,prevScrollTop:S}:{direction:S<b.prevScrollTop?to:no,prevScrollTop:S},{direction:no,prevScrollTop:0}),ce(b=>b.direction)),v),ve(H(r,An(50),bn(Gw)),v);const g=Q(0);return ve(H(p,Ae(b=>!b),bn(0)),g),ve(H(o,An(100),$e(p),Ae(([b,S])=>!!S),wn(([b,S],[k])=>[S,k],[0,0]),ce(([b,S])=>S-b)),g),{atBottomState:x,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:p,lastJumpDueToItemResize:m,scrollDirection:v,scrollVelocity:g}},pt(Ft)),xs="top",ys="bottom",Kd="none";function qd(e,t,n){return typeof e=="number"?n===to&&t===xs||n===no&&t===ys?e:0:n===to?t===xs?e.main:e.reverse:t===ys?e.main:e.reverse}function Gd(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const pa=tt(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=Ye(),i=Q(0),a=Q(0),l=Q(0),c=Ot(H(kt(Ie(r),Ie(o),Ie(n),Ie(s,Jr),Ie(l),Ie(i),Ie(t),Ie(e),Ie(a)),ce(([d,f,p,[h,x],m,v,g,b,S])=>{const k=d-b,C=v+g,T=Math.max(p-k,0);let E=Kd;const N=Gd(S,xs),_=Gd(S,ys);return h-=b,h+=p+g,x+=p+g,x-=b,h>d+C-N&&(E=to),x<d-T+f+_&&(E=no),E!==Kd?[Math.max(k-p-qd(m,xs,E)-N,0),k-T-g+f+qd(m,ys,E)+_]:null}),Ae(d=>d!=null),ht(Jr)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:c}},pt(Ft),{singleton:!0});function Jw(e,t,n){if(gs(t)){const r=zd(e,t);return[{index:dn(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 ha={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function vs(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:l}=o;let c=0,d=0;if(e.length>0){c=e[0].offset;const m=e[e.length-1];d=m.offset+m.size}const f=n-i,p=a+f*l+(f-1)*r,h=c,x=p-d;return{bottom:d,firstItemIndex:s,items:Xd(e,o,s),offsetBottom:x,offsetTop:c,top:h,topItems:Xd(t,o,s),topListHeight:t.reduce((m,v)=>v.size+m,0),totalCount:n}}function Yd(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=fa(t,a),c=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return vs(c,[],a,o,n,r)}function Xd(e,t,n){if(e.length===0)return[];if(!gs(t))return e.map(c=>({...c,index:c.index+n,originalIndex:c.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=ps(t.groupOffsetTree,r,o);let a,l=0;for(const c of e){(!a||a.end<c.index)&&(a=i.shift(),l=t.groupIndices.indexOf(a.start));let d;c.index===a.start?d={index:l,type:"group"}:d={groupIndex:l,index:c.index-(l+1)+n},s.push({...d,data:c.data,offset:c.offset,originalIndex:c.index,size:c.size})}return s}const rr=tt(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:l},{initialTopMostItemIndex:c,scrolledToInitialItem:d},{topListHeight:f},p,{didMount:h},{recalcInProgress:x}])=>{const m=Q([]),v=Q(0),g=Ye();ve(s.topItemsIndexes,m);const b=Ot(H(kt(h,x,Ie(l,Jr),Ie(o),Ie(r),Ie(c),d,Ie(m),Ie(t),Ie(n),e),Ae(([T,E,,N,,,,,,,_])=>{const P=_&&_.length!==N;return T&&!E&&!P}),ce(([,,[T,E],N,_,P,R,D,F,A,z])=>{const j=_,{offsetTree:J,sizeTree:B}=j,O=Tt(v);if(N===0)return{...ha,totalCount:N};if(T===0&&E===0)return O===0?{...ha,totalCount:N}:Yd(O,P,_,F,A,z||[]);if(ut(B))return O>0?null:vs(Jw(fa(P,N),j,z),[],N,A,j,F);const W=[];if(D.length>0){const G=D[0],U=D[D.length-1];let q=0;for(const $ of ps(B,G,U)){const V=$.value,re=Math.max($.start,G),oe=Math.min($.end,U);for(let se=re;se<=oe;se++)W.push({data:z==null?void 0:z[se],index:se,offset:q,size:V}),q+=V}}if(!R)return vs([],W,N,A,j,F);const X=D.length>0?D[D.length-1]+1:0,fe=Fw(J,T,E,X);if(fe.length===0)return null;const ae=N-1,Re=fs([],G=>{for(const U of fe){const q=U.value;let $=q.offset,V=U.start;const re=q.size;if(q.offset<T){V+=Math.floor((T-q.offset+A)/(re+A));const se=V-U.start;$+=se*re+se*A}V<X&&($+=(X-V)*re,V=X);const oe=Math.min(U.end,ae);for(let se=V;se<=oe&&!($>=E);se++)G.push({data:z==null?void 0:z[se],index:se,offset:$,size:re}),$+=re+A}});return vs(Re,W,N,A,j,F)}),Ae(T=>T!==null),ht()),ha);ve(H(e,Ae(ea),ce(T=>T==null?void 0:T.length)),o),ve(H(b,ce(T=>T.topListHeight)),f),ve(f,a),ve(H(b,ce(T=>[T.top,T.bottom])),i),ve(H(b,ce(T=>T.items)),g);const S=Gt(H(b,Ae(({items:T})=>T.length>0),$e(o,e),Ae(([{items:T},E])=>T[T.length-1].originalIndex===E-1),ce(([,T,E])=>[T-1,E]),ht(Jr),ce(([T])=>T))),k=Gt(H(b,An(200),Ae(({items:T,topItems:E})=>T.length>0&&T[0].originalIndex===E.length),ce(({items:T})=>T[0].index),ht())),C=Gt(H(b,Ae(({items:T})=>T.length>0),ce(({items:T})=>{let E=0,N=T.length-1;for(;T[E].type==="group"&&E<N;)E++;for(;T[N].type==="group"&&N>E;)N--;return{endIndex:T[N].index,startIndex:T[E].index}}),ht($d)));return{endReached:S,initialItemCount:v,itemsRendered:g,listState:b,rangeChanged:C,startReached:k,topItemsIndexes:m,...p}},pt(Sn,Hd,pa,eo,Qr,ro,$n,la),{singleton:!0}),Jd=tt(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=Ye(),i=Ot(H(kt(n,e,r,t,o),ce(([a,l,c,d,f])=>a+l+c+d+f.offsetBottom+f.bottom)),0);return ve(Ie(i),s),{totalListHeight:i,totalListHeightChanged:s}},pt(Ft,rr),{singleton:!0}),Zw=tt(([{viewportHeight:e},{totalListHeight:t}])=>{const n=Q(!1),r=Ot(H(kt(n,e,t),Ae(([o])=>o),ce(([,o,s])=>Math.max(0,o-s)),An(0),ht()),0);return{alignToBottom:n,paddingTopAddition:r}},pt(Ft,Jd),{singleton:!0}),Zd=tt(()=>({context:Q(null)})),Qw=({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,Qd=tt(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:c}])=>{const d=Ye();return ve(H(d,$e(t,l,n,s,o,r,a),$e(e),ce(([[f,p,h,x,m,v,g,b],S])=>{const{align:k,behavior:C,calculateViewLocation:T=Qw,done:E,...N}=f,_=Bd(f,p,x-1),P=Zr(_,p.offsetTree,S)+m+v,R=P+dn(p.sizeTree,_)[1],D=b+v,F=b+h-g,A=T({itemBottom:R,itemTop:P,locationParams:{align:k,behavior:C,...N},viewportBottom:F,viewportTop:D});return A?E&&un(H(i,Ae(z=>!z),er(Tt(i)?1:2)),E):E&&E(),A}),Ae(f=>f!==null)),c),{scrollIntoView:d}},pt(Sn,Ft,Qr,rr,Dn),{singleton:!0});function ef(e){return e?e==="smooth"?"smooth":"auto":!1}const e0=(e,t)=>typeof e=="function"?ef(e(t)):t&&ef(e),t0=tt(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:l,propsReady:c},{log:d},{scrollingInProgress:f},{context:p},{scrollIntoView:h}])=>{const x=Q(!1),m=Ye();let v=null;function g(C){De(i,{align:"end",behavior:C,index:"LAST"})}it(H(kt(H(Ie(t),er(1)),l),$e(Ie(x),s,a,f),ce(([[C,T],E,N,_,P])=>{let R=T&&_,D="auto";return R&&(D=e0(E,N||P),R=R&&!!D),{followOutputBehavior:D,shouldFollow:R,totalCount:C}}),Ae(({shouldFollow:C})=>C)),({followOutputBehavior:C,totalCount:T})=>{v&&(v(),v=null),Tt(n)?requestAnimationFrame(()=>{Tt(d)("following output to ",{totalCount:T},Wt.DEBUG),g(C)}):v=un(e,()=>{Tt(d)("following output to ",{totalCount:T},Wt.DEBUG),g(C),v=null})});function b(C){const T=un(o,E=>{C&&!E.atBottom&&E.notAtBottomBecause==="SIZE_INCREASED"&&!v&&(Tt(d)("scrolling to bottom due to increased size",{},Wt.DEBUG),g("auto"))});setTimeout(T,100)}it(H(kt(Ie(x),t,c),Ae(([C,,T])=>C&&T),wn(({value:C},[,T])=>({refreshed:C===T,value:T}),{refreshed:!1,value:0}),Ae(({refreshed:C})=>C),$e(x,t)),([,C])=>{Tt(a)&&b(C!==!1)}),it(m,()=>{b(Tt(x)!==!1)}),it(kt(Ie(x),o),([C,T])=>{C&&!T.atBottom&&T.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&g("auto")});const S=Q(null),k=Ye();return ve(na(H(Ie(r),ce(C=>{var T;return(T=C==null?void 0:C.length)!=null?T:0})),H(Ie(t))),k),it(H(kt(H(k,er(1)),l),$e(Ie(S),a,f,p),ce(([[C,T],E,N,_,P])=>T&&N&&(E==null?void 0:E({context:P,totalCount:C,scrollingInProgress:_}))),Ae(C=>!!C),An(0)),C=>{v&&(v(),v=null),Tt(n)?requestAnimationFrame(()=>{Tt(d)("scrolling into view",{}),De(h,C)}):v=un(e,()=>{Tt(d)("scrolling into view",{}),De(h,C),v=null})}),{autoscrollToBottom:m,followOutput:x,scrollIntoViewOnChange:S}},pt(Sn,ro,Qr,eo,$n,Dn,Ft,Zd,Qd)),n0=tt(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(ve(H(a,$e(s),Ae(([,l])=>l!==0),$e(o,r,t,n,e),ce(([[,l],c,d,f,p,h=[]])=>Yd(l,c,d,f,p,h))),i),{}),pt(Sn,eo,rr,$n),{singleton:!0}),r0=tt(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=Q(0);return it(H(e,$e(r),Ae(([,o])=>o!==0),ce(([,o])=>({top:o}))),o=>{un(H(n,er(1),Ae(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{De(t,o)})})}),{initialScrollTop:r}},pt($n,Ft,rr),{singleton:!0}),tf=tt(([{scrollVelocity:e}])=>{const t=Q(!1),n=Ye(),r=Q(!1);return ve(H(e,$e(r,t,n),Ae(([o,s])=>!!s),ce(([o,s,i,a])=>{const{enter:l,exit:c}=s;if(i){if(c(o,a))return!1}else if(l(o,a))return!0;return i}),ht()),t),it(H(kt(t,e,n),$e(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},pt(ro),{singleton:!0}),ma=tt(([{scrollContainerState:e,scrollTo:t}])=>{const n=Ye(),r=Ye(),o=Ye(),s=Q(!1),i=Q(void 0);return ve(H(kt(n,r),ce(([{scrollHeight:a,scrollTop:l,viewportHeight:c},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),ve(H(t,$e(r),ce(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},pt(Ft)),o0=tt(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const c=Ye(),d=Q(void 0),f=Q(null),p=Q(null);return ve(a,f),ve(l,p),it(H(c,$e(t,r,i,f,p,n)),([h,x,m,v,g,b,S])=>{const k=Bw(x.sizeTree);v&&g!==null&&b!==null&&(m=g.scrollTop-b.offsetTop),m-=S,h({ranges:k,scrollTop:m})}),ve(H(d,Ae(ea),ce(s0)),o),ve(H(s,$e(d),Ae(([,h])=>h!==void 0),ht(),ce(([,h])=>h.ranges)),e),{getState:c,restoreStateFrom:d}},pt(Sn,Ft,eo,$n,ma));function s0(e){return{align:"start",index:0,offset:e.scrollTop}}const i0=tt(([{topItemsIndexes:e}])=>{const t=Q(0);return ve(H(t,Ae(n=>n>=0),ce(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},pt(rr));function nf(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const a0=nf(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),l0=tt(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:l},{beforeUnshiftWith:c,gap:d,shiftWithOffset:f,sizes:p},{log:h},{recalcInProgress:x}])=>{const m=Gt(H(l,$e(i),wn(([,g,b,S],[{bottom:k,items:C,offsetBottom:T,totalCount:E},N])=>{const _=k+T;let P=0;return b===E&&g.length>0&&C.length>0&&(C[0].originalIndex===0&&g[0].originalIndex===0||(P=_-S,P!==0&&(P+=N))),[P,C,E,_]},[0,[],0,0]),Ae(([g])=>g!==0),$e(r,a,n,o,h,x),Ae(([,g,b,S,,,k])=>!k&&!S&&g!==0&&b===to),ce(([[g],,,,,b])=>(b("Upward scrolling compensation",{amount:g},Wt.DEBUG),g))));function v(g){g>0?(De(t,{behavior:"auto",top:-g}),De(e,0)):(De(e,0),De(t,{behavior:"auto",top:-g}))}return it(H(m,$e(e,s)),([g,b,S])=>{S&&a0()?De(e,b-g):v(-g)}),it(H(kt(Ot(s,!1),e,x),Ae(([g,b,S])=>!g&&!S&&b!==0),ce(([g,b])=>b),An(1)),v),ve(H(f,ce(g=>({top:-g}))),t),it(H(c,$e(p,d),ce(([g,{groupIndices:b,lastSize:S,sizeTree:k},C])=>{function T(E){return E*(S+C)}if(b.length===0)return T(g);{let E=0;const N=Xr(k,0);let _=0,P=0;for(;_<g;){_++,E+=N;let R=b.length===P+1?1/0:b[P+1]-b[P]-1;_+R>g&&(E-=N,R=g-_+1),_+=R,E+=T(R),P++}return E}})),g=>{De(e,g),requestAnimationFrame(()=>{De(t,{top:g}),requestAnimationFrame(()=>{De(e,0),De(x,!1)})})}),{deviation:e}},pt(Ft,ro,rr,Sn,Dn,la)),c0=tt(([e,t,n,r,o,s,i,a,l,c,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...c,...d}),pt(pa,n0,$n,tf,Jd,r0,Zw,ma,Qd,Dn,Zd)),rf=tt(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:l,statefulTotalCount:c,totalCount:d,trackItemSizes:f},{initialItemFinalLocationReached:p,initialTopMostItemIndex:h,scrolledToInitialItem:x},m,v,g,{listState:b,topItemsIndexes:S,...k},{scrollToIndex:C},T,{topItemCount:E},{groupCounts:N},_])=>(ve(k.rangeChanged,_.scrollSeekRangeChanged),ve(H(_.windowViewportRect,ce(P=>P.visibleHeight)),m.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:N,initialItemFinalLocationReached:p,initialTopMostItemIndex:h,scrolledToInitialItem:x,sizeRanges:a,topItemCount:E,topItemsIndexes:S,totalCount:d,...g,groupIndices:s,itemSize:i,listState:b,scrollToIndex:C,statefulTotalCount:c,trackItemSizes:f,...k,..._,...m,sizes:l,...v}),pt(Sn,eo,Ft,o0,t0,rr,Qr,l0,i0,Hd,c0));function u0(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 bs=typeof document<"u"?w.useLayoutEffect:w.useEffect;function of(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=w.createContext({});function l(v,g){v.propsReady&&De(v.propsReady,!1);for(const b of r){const S=v[t.required[b]];De(S,g[b])}for(const b of o)if(b in g){const S=v[t.optional[b]];De(S,g[b])}v.propsReady&&De(v.propsReady,!0)}function c(v){return s.reduce((g,b)=>(g[b]=S=>{const k=v[t.methods[b]];De(k,S)},g),{})}function d(v){return i.reduce((g,b)=>(g[b]=Ew(v[t.events[b]]),g),{})}const f=w.forwardRef((v,g)=>{const{children:b,...S}=v,[k]=w.useState(()=>fs(Nw(e),E=>{l(E,S)})),[C]=w.useState(Id(d,k));bs(()=>{for(const E of i)E in S&&it(C[E],S[E]);return()=>{Object.values(C).map(ta)}},[S,C,k]),bs(()=>{l(k,S)}),w.useImperativeHandle(g,kd(c(k)));const T=n;return u.jsx(a.Provider,{value:k,children:n?u.jsx(T,{...u0([...r,...o,...i],S),children:b}):b})}),p=v=>{const g=w.useContext(a);return w.useCallback(b=>{De(g[v],b)},[g,v])},h=v=>{const g=w.useContext(a)[v],b=w.useCallback(S=>it(g,S),[g]);return w.useSyncExternalStore(b,()=>Tt(g),()=>Tt(g))},x=v=>{const g=w.useContext(a)[v],[b,S]=w.useState(Id(Tt,g));return bs(()=>it(g,k=>{k!==b&&S(kd(k))}),[g,b]),b},m=w.version.startsWith("18")?h:x;return{Component:f,useEmitter:(v,g)=>{const b=w.useContext(a)[v];bs(()=>it(b,g),[g,b])},useEmitterValue:m,usePublisher:p}}const sf=w.createContext(void 0),af=w.createContext(void 0),lf=typeof document<"u"?w.useLayoutEffect:w.useEffect;function ga(e){return"self"in e}function d0(e){return"body"in e}function cf(e,t,n,r=Er,o,s){const i=w.useRef(null),a=w.useRef(null),l=w.useRef(null),c=w.useCallback(p=>{let h,x,m;const v=p.target;if(d0(v)||ga(v)){const b=ga(v)?v:v.defaultView;m=s?b.scrollX:b.scrollY,h=s?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight,x=s?b.innerWidth:b.innerHeight}else m=s?v.scrollLeft:v.scrollTop,h=s?v.scrollWidth:v.scrollHeight,x=s?v.offsetWidth:v.offsetHeight;const g=()=>{e({scrollHeight:h,scrollTop:Math.max(m,0),viewportHeight:x})};p.suppressFlushSync?g():Ys.flushSync(g),a.current!==null&&(m===a.current||m<=0||m===h-x)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);w.useEffect(()=>{const p=o||i.current;return r(o||i.current),c({suppressFlushSync:!0,target:p}),p.addEventListener("scroll",c,{passive:!0}),()=>{r(null),p.removeEventListener("scroll",c)}},[i,c,n,r,o]);function d(p){const h=i.current;if(!h||(s?"offsetWidth"in h&&h.offsetWidth===0:"offsetHeight"in h&&h.offsetHeight===0))return;const x=p.behavior==="smooth";let m,v,g;ga(h)?(v=Math.max(Ln(h.document.documentElement,s?"width":"height"),s?h.document.documentElement.scrollWidth:h.document.documentElement.scrollHeight),m=s?h.innerWidth:h.innerHeight,g=s?window.scrollX:window.scrollY):(v=h[s?"scrollWidth":"scrollHeight"],m=Ln(h,s?"width":"height"),g=h[s?"scrollLeft":"scrollTop"]);const b=v-m;if(p.top=Math.ceil(Math.max(Math.min(b,p.top),0)),Vd(m,v)||p.top===g){e({scrollHeight:v,scrollTop:g,viewportHeight:m}),x&&t(!0);return}x?(a.current=p.top,l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{l.current=null,a.current=null,t(!0)},1e3)):a.current=null,s&&(p={behavior:p.behavior,left:p.top}),h.scrollTo(p)}function f(p){s&&(p={behavior:p.behavior,left:p.top}),i.current.scrollBy(p)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:d}}const xa="-webkit-sticky",uf="sticky",ya=nf(()=>{if(typeof document>"u")return uf;const e=document.createElement("div");return e.style.position=xa,e.style.position===xa?xa:uf});function va(e){return e}const f0=tt(()=>{const e=Q(a=>`Item ${a}`),t=Q(a=>`Group ${a}`),n=Q({}),r=Q(va),o=Q("div"),s=Q(Er),i=(a,l=null)=>Ot(H(n,ce(c=>c[a]),ht()),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")}}),p0=tt(([e,t])=>({...e,...t}),pt(rf,f0)),h0=({height:e})=>u.jsx("div",{style:{height:e}}),m0={overflowAnchor:"none",position:ya(),zIndex:1},df={overflowAnchor:"none"},g0={...df,display:"inline-block",height:"100%"},ff=w.memo(function({showTopList:e=!1}){const t=je("listState"),n=tn("sizeRanges"),r=je("useWindowScroll"),o=je("customScrollParent"),s=tn("windowScrollContainerState"),i=tn("scrollContainerState"),a=o||r?s:i,l=je("itemContent"),c=je("context"),d=je("groupContent"),f=je("trackItemSizes"),p=je("itemSize"),h=je("log"),x=tn("gap"),m=je("horizontalDirection"),{callbackRef:v}=jw(n,p,f,e?Er:a,h,x,o,m,je("skipAnimationFrameInResizeObserver")),[g,b]=w.useState(0);ba("deviation",A=>{g!==A&&b(A)});const S=je("EmptyPlaceholder"),k=je("ScrollSeekPlaceholder")||h0,C=je("ListComponent"),T=je("ItemComponent"),E=je("GroupComponent"),N=je("computeItemKey"),_=je("isSeeking"),P=je("groupIndices").length>0,R=je("alignToBottom"),D=je("initialItemFinalLocationReached"),F=e?{}:{boxSizing:"border-box",...m?{display:"inline-block",height:"100%",marginLeft:g!==0?g:R?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:g!==0?g:R?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...D?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&S?u.jsx(S,{...Mt(S,c)}):u.jsx(C,{...Mt(C,c),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:v,style:F,children:(e?t.topItems:t.items).map(A=>{const z=A.originalIndex,j=N(z+t.firstItemIndex,A.data,c);return _?w.createElement(k,{...Mt(k,c),height:A.size,index:A.index,key:j,type:A.type||"item",...A.type==="group"?{}:{groupIndex:A.groupIndex}}):A.type==="group"?w.createElement(E,{...Mt(E,c),"data-index":z,"data-item-index":A.index,"data-known-size":A.size,key:j,style:m0},d(A.index,c)):w.createElement(T,{...Mt(T,c),...b0(T,A.data),"data-index":z,"data-item-group-index":A.groupIndex,"data-item-index":A.index,"data-known-size":A.size,key:j,style:m?g0:df},P?l(A.index,A.groupIndex,A.data,c):l(A.index,A.data,c))})})}),x0={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},y0={outline:"none",overflowX:"auto",position:"relative"},ws=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),v0={position:ya(),top:0,width:"100%",zIndex:1};function Mt(e,t){if(typeof e!="string")return{context:t}}function b0(e,t){return{item:typeof e=="string"?void 0:t}}const w0=w.memo(function(){const e=je("HeaderComponent"),t=tn("headerHeight"),n=je("HeaderFooterTag"),r=tr(w.useMemo(()=>s=>{t(Ln(s,"height"))},[t]),!0,je("skipAnimationFrameInResizeObserver")),o=je("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Mt(e,o)})}):null}),S0=w.memo(function(){const e=je("FooterComponent"),t=tn("footerHeight"),n=je("HeaderFooterTag"),r=tr(w.useMemo(()=>s=>{t(Ln(s,"height"))},[t]),!0,je("skipAnimationFrameInResizeObserver")),o=je("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Mt(e,o)})}):null});function pf({useEmitter:e,useEmitterValue:t,usePublisher:n}){return w.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:p,scrollerRef:h,scrollToCallback:x}=cf(a,c,l,d,void 0,f);return e("scrollTo",x),e("scrollBy",p),u.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:h,style:{...f?y0:x0,...o},tabIndex:0,...i,...Mt(l,s),children:r})})}function hf({useEmitter:e,useEmitterValue:t,usePublisher:n}){return w.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("totalListHeight"),f=t("deviation"),p=t("customScrollParent"),h=w.useRef(null),x=t("scrollerRef"),{scrollByCallback:m,scrollerRef:v,scrollToCallback:g}=cf(a,c,l,x,p);return lf(()=>{var b;return v.current=p||((b=h.current)==null?void 0:b.ownerDocument.defaultView),()=>{v.current=null}},[v,p]),e("windowScrollTo",g),e("scrollBy",m),u.jsx(l,{ref:h,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...d!==0?{height:d+f}:{}},...i,...Mt(l,s),children:r})})}const C0=({children:e})=>{const t=w.useContext(sf),n=tn("viewportHeight"),r=tn("fixedItemHeight"),o=je("alignToBottom"),s=je("horizontalDirection"),i=w.useMemo(()=>Ed(n,l=>Ln(l,s?"width":"height")),[n,s]),a=tr(i,!0,je("skipAnimationFrameInResizeObserver"));return w.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),u.jsx("div",{"data-viewport-type":"element",ref:a,style:ws(o),children:e})},T0=({children:e})=>{const t=w.useContext(sf),n=tn("windowViewportRect"),r=tn("fixedItemHeight"),o=je("customScrollParent"),s=jd(n,o,je("skipAnimationFrameInResizeObserver")),i=je("alignToBottom");return w.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),u.jsx("div",{"data-viewport-type":"window",ref:s,style:ws(i),children:e})},k0=({children:e})=>{const t=je("TopItemListComponent")||"div",n=je("headerHeight"),r={...v0,marginTop:`${n}px`},o=je("context");return u.jsx(t,{style:r,...Mt(t,o),children:e})},E0=w.memo(function(e){const t=je("useWindowScroll"),n=je("topItemsIndexes").length>0,r=je("customScrollParent"),o=je("context");return u.jsxs(r||t?A0:N0,{...e,context:o,children:[n&&u.jsx(k0,{children:u.jsx(ff,{showTopList:!0})}),u.jsxs(r||t?T0:C0,{children:[u.jsx(w0,{}),u.jsx(ff,{}),u.jsx(S0,{})]})]})}),{Component:I0,useEmitter:ba,useEmitterValue:je,usePublisher:tn}=of(p0,{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"}},E0),N0=pf({useEmitter:ba,useEmitterValue:je,usePublisher:tn}),A0=hf({useEmitter:ba,useEmitterValue:je,usePublisher:tn}),_0=I0;pt(rf,tt(()=>{const e=Q(c=>u.jsxs("td",{children:["Item $",c]})),t=Q(null),n=Q(c=>u.jsxs("td",{colSpan:1e3,children:["Group ",c]})),r=Q(null),o=Q(null),s=Q({}),i=Q(va),a=Q(Er),l=(c,d=null)=>Ot(H(s,ce(f=>f[c]),ht()),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")}})),ya();const mf={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},j0={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:gf,floor:Ss,max:oo,min:wa,round:xf}=Math;function yf(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function R0(e){return{...j0,items:e}}function Cs(e,t){return e&&e.width===t.width&&e.height===t.height}function P0(e,t){return e&&e.column===t.column&&e.row===t.row}const O0=tt(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:l,scrollTop:c,smoothScrollTargetReached:d,viewportHeight:f},p,h,{didMount:x,propsReady:m},{customScrollParent:v,useWindowScroll:g,windowScrollContainerState:b,windowScrollTo:S,windowViewportRect:k},C])=>{const T=Q(0),E=Q(0),N=Q(mf),_=Q({height:0,width:0}),P=Q({height:0,width:0}),R=Ye(),D=Ye(),F=Q(0),A=Q(null),z=Q({column:0,row:0}),j=Ye(),J=Ye(),B=Q(!1),O=Q(0),W=Q(!0),X=Q(!1),fe=Q(!1);it(H(x,$e(O),Ae(([$,V])=>!!V)),()=>{De(W,!1)}),it(H(kt(x,W,P,_,O,X),Ae(([$,V,re,oe,,se])=>$&&!V&&re.height!==0&&oe.height!==0&&!se)),([,,,,$])=>{De(X,!0),da(1,()=>{De(R,$)}),un(H(c),()=>{De(t,[0,0]),De(W,!0)})}),ve(H(J,Ae($=>$!=null&&$.scrollTop>0),bn(0)),E),it(H(x,$e(J),Ae(([,$])=>$!=null)),([,$])=>{$&&(De(_,$.viewport),De(P,$.item),De(z,$.gap),$.scrollTop>0&&(De(B,!0),un(H(c,er(1)),V=>{De(B,!1)}),De(l,{top:$.scrollTop})))}),ve(H(_,ce(({height:$})=>$)),f),ve(H(kt(Ie(_,Cs),Ie(P,Cs),Ie(z,($,V)=>$&&$.column===V.column&&$.row===V.row),Ie(c)),ce(([$,V,re,oe])=>({gap:re,item:V,scrollTop:oe,viewport:$}))),j),ve(H(kt(Ie(T),r,Ie(z,P0),Ie(P,Cs),Ie(_,Cs),Ie(A),Ie(E),Ie(B),Ie(W),Ie(O)),Ae(([,,,,,,,$])=>!$),ce(([$,[V,re],oe,se,Se,Qe,Fe,,Xe,nt])=>{const{column:de,row:me}=oe,{height:Le,width:Be}=se,{width:Ve}=Se;if(Fe===0&&($===0||Ve===0))return mf;if(Be===0){const It=fa(nt,$),bt=It+Math.max(Fe-1,0);return R0(yf(It,bt,Qe))}const Je=vf(Ve,Be,de);let ze,Ze;Xe?V===0&&re===0&&Fe>0?(ze=0,Ze=Fe-1):(ze=Je*Ss((V+me)/(Le+me)),Ze=Je*gf((re+me)/(Le+me))-1,Ze=wa($-1,oo(Ze,Je-1)),ze=wa(Ze,oo(0,ze))):(ze=0,Ze=-1);const Et=yf(ze,Ze,Qe),{bottom:ft,top:Ue}=bf(Se,oe,se,Et),xt=gf($/Je),vt=xt*Le+(xt-1)*me-ft;return{bottom:ft,itemHeight:Le,items:Et,itemWidth:Be,offsetBottom:vt,offsetTop:Ue,top:Ue}})),N),ve(H(A,Ae($=>$!==null),ce($=>$.length)),T),ve(H(kt(_,P,N,z),Ae(([$,V,{items:re}])=>re.length>0&&V.height!==0&&$.height!==0),ce(([$,V,{items:re},oe])=>{const{bottom:se,top:Se}=bf($,oe,V,re);return[Se,se]}),ht(Jr)),t);const ae=Q(!1);ve(H(c,$e(ae),ce(([$,V])=>V||$!==0)),ae);const Re=Gt(H(kt(N,T),Ae(([{items:$}])=>$.length>0),$e(ae),Ae(([[$,V],re])=>{const oe=$.items[$.items.length-1].index===V-1;return(re||$.bottom>0&&$.itemHeight>0&&$.offsetBottom===0&&$.items.length===V)&&oe}),ce(([[,$]])=>$-1),ht())),G=Gt(H(Ie(N),Ae(({items:$})=>$.length>0&&$[0].index===0),bn(0),ht())),U=Gt(H(Ie(N),$e(B),Ae(([{items:$},V])=>$.length>0&&!V),ce(([{items:$}])=>({endIndex:$[$.length-1].index,startIndex:$[0].index})),ht($d),An(0)));ve(U,h.scrollSeekRangeChanged),ve(H(R,$e(_,P,T,z),ce(([$,V,re,oe,se])=>{const Se=Wd($),{align:Qe,behavior:Fe,offset:Xe}=Se;let nt=Se.index;nt==="LAST"&&(nt=oe-1),nt=oo(0,nt,wa(oe-1,nt));let de=Sa(V,se,re,nt);return Qe==="end"?de=xf(de-V.height+re.height):Qe==="center"&&(de=xf(de-V.height/2+re.height/2)),Xe&&(de+=Xe),{behavior:Fe,top:de}})),l);const q=Ot(H(N,ce($=>$.offsetBottom+$.bottom)),0);return ve(H(k,ce($=>({height:$.visibleHeight,width:$.visibleWidth}))),_),{customScrollParent:v,data:A,deviation:F,footerHeight:o,gap:z,headerHeight:s,increaseViewportBy:e,initialItemCount:E,itemDimensions:P,overscan:n,restoreStateFrom:J,scrollBy:i,scrollContainerState:a,scrollHeight:D,scrollTo:l,scrollToIndex:R,scrollTop:c,smoothScrollTargetReached:d,totalCount:T,useWindowScroll:g,viewportDimensions:_,windowScrollContainerState:b,windowScrollTo:S,windowViewportRect:k,...h,gridState:N,horizontalDirection:fe,initialTopMostItemIndex:O,totalListHeight:q,...p,endReached:Re,propsReady:m,rangeChanged:U,startReached:G,stateChanged:j,stateRestoreInProgress:B,...C}},pt(pa,Ft,ro,tf,$n,ma,Dn));function vf(e,t,n){return oo(1,Ss((e+n)/(Ss(t)+n)))}function bf(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=Sa(e,t,n,r[0].index);return{bottom:Sa(e,t,n,r[r.length-1].index)+o,top:s}}function Sa(e,t,n,r){const o=vf(e.width,n.width,t.column),s=Ss(r/o),i=s*n.height+oo(0,s-1)*t.row;return i>0?i+t.row:i}const M0=tt(()=>{const e=Q(f=>`Item ${f}`),t=Q({}),n=Q(null),r=Q("virtuoso-grid-item"),o=Q("virtuoso-grid-list"),s=Q(va),i=Q("div"),a=Q(Er),l=(f,p=null)=>Ot(H(t,ce(h=>h[f]),ht()),p),c=Q(!1),d=Q(!1);return ve(Ie(d),c),{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:c,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),D0=tt(([e,t])=>({...e,...t}),pt(O0,M0)),L0=w.memo(function(){const e=gt("gridState"),t=gt("listClassName"),n=gt("itemClassName"),r=gt("itemContent"),o=gt("computeItemKey"),s=gt("isSeeking"),i=nn("scrollHeight"),a=gt("ItemComponent"),l=gt("ListComponent"),c=gt("ScrollSeekPlaceholder"),d=gt("context"),f=nn("itemDimensions"),p=nn("gap"),h=gt("log"),x=gt("stateRestoreInProgress"),m=nn("reportReadyState"),v=tr(w.useMemo(()=>g=>{const b=g.parentElement.parentElement.scrollHeight;i(b);const S=g.firstChild;if(S){const{height:k,width:C}=S.getBoundingClientRect();f({height:k,width:C})}p({column:Sf("column-gap",getComputedStyle(g).columnGap,h),row:Sf("row-gap",getComputedStyle(g).rowGap,h)})},[i,f,p,h]),!0,!1);return lf(()=>{e.itemHeight>0&&e.itemWidth>0&&m(!0)},[e]),x?null:u.jsx(l,{className:t,ref:v,...Mt(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(g=>{const b=o(g.index,g.data,d);return s?u.jsx(c,{...Mt(c,d),height:e.itemHeight,index:g.index,width:e.itemWidth},b):w.createElement(a,{...Mt(a,d),className:n,"data-index":g.index,key:b},r(g.index,g.data,d))})})}),$0=w.memo(function(){const e=gt("HeaderComponent"),t=nn("headerHeight"),n=gt("headerFooterTag"),r=tr(w.useMemo(()=>s=>{t(Ln(s,"height"))},[t]),!0,!1),o=gt("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Mt(e,o)})}):null}),F0=w.memo(function(){const e=gt("FooterComponent"),t=nn("footerHeight"),n=gt("headerFooterTag"),r=tr(w.useMemo(()=>s=>{t(Ln(s,"height"))},[t]),!0,!1),o=gt("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Mt(e,o)})}):null}),z0=({children:e})=>{const t=w.useContext(af),n=nn("itemDimensions"),r=nn("viewportDimensions"),o=tr(w.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return w.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),u.jsx("div",{ref:o,style:ws(!1),children:e})},B0=({children:e})=>{const t=w.useContext(af),n=nn("windowViewportRect"),r=nn("itemDimensions"),o=gt("customScrollParent"),s=jd(n,o,!1);return w.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),u.jsx("div",{ref:s,style:ws(!1),children:e})},U0=w.memo(function({...e}){const t=gt("useWindowScroll"),n=gt("customScrollParent"),r=n||t?W0:H0,o=n||t?B0:z0,s=gt("context");return u.jsx(r,{...e,...Mt(r,s),children:u.jsxs(o,{children:[u.jsx($0,{}),u.jsx(L0,{}),u.jsx(F0,{})]})})}),{useEmitter:wf,useEmitterValue:gt,usePublisher:nn}=of(D0,{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"}},U0),H0=pf({useEmitter:wf,useEmitterValue:gt,usePublisher:nn}),W0=hf({useEmitter:wf,useEmitterValue:gt,usePublisher:nn});function Sf(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Wt.WARN),t==="normal"?0:parseInt(t??"0",10)}const V0=mo.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 Cf({className:e,variant:t,...n}){return u.jsx("div",{className:te(V0({variant:t}),e),...n})}const so=y.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:te("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));so.displayName="Card";const io=y.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:te("flex flex-col space-y-1.5 p-6",e),...t}));io.displayName="CardHeader";const ao=y.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:te("text-2xl font-semibold leading-none tracking-tight",e),...t}));ao.displayName="CardTitle";const Tf=y.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:te("text-sm text-muted-foreground",e),...t}));Tf.displayName="CardDescription";const lo=y.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:te("p-6 pt-0",e),...t}));lo.displayName="CardContent";const kf=y.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:te("flex items-center p-6 pt-0",e),...t}));kf.displayName="CardFooter";const K0=1,q0=1e6;let Ca=0;function G0(){return Ca=(Ca+1)%Number.MAX_SAFE_INTEGER,Ca.toString()}const Ta=new Map,Ef=e=>{if(Ta.has(e))return;const t=setTimeout(()=>{Ta.delete(e),co({type:"REMOVE_TOAST",toastId:e})},q0);Ta.set(e,t)},Y0=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,K0)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?Ef(n):e.toasts.forEach(r=>{Ef(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Ts=[];let ks={toasts:[]};function co(e){ks=Y0(ks,e),Ts.forEach(t=>{t(ks)})}function X0({...e}){const t=G0(),n=o=>co({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>co({type:"DISMISS_TOAST",toastId:t});return co({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function ka(){const[e,t]=y.useState(ks);return y.useEffect(()=>(Ts.push(t),()=>{const n=Ts.indexOf(t);n>-1&&Ts.splice(n,1)}),[e]),{...e,toast:X0,dismiss:n=>co({type:"DISMISS_TOAST",toastId:n})}}async function If(e,t){return await Jt(e,{responseType:"blob",onDownloadProgress:r=>{try{t&&r.lengthComputable}catch{}},maxBodyLength:1/0})}async function Nf(e,t){return await(await If(`/files/${e}/view`,t)).text()}async function J0(e,t){const n=await If(`/files/${e}/download`,t),r=URL.createObjectURL(n);let o=`file_${e}`;try{const i=await Jt(`/files/${e}`);o=(i==null?void 0:i.filename)??o}catch{}const s=document.createElement("a");s.href=r,s.download=o,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}async function Z0(e,t=50,n=0){const r={limit:t,offset:n};return e&&(r.thread_id=e),await Jt("/files",{params:r})}function Ea(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{return null}}function Af(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function uo(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(uo).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(Af(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const o=uo(r);o!==void 0&&(t[n]=o)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function fo(e){if(typeof e=="string")return e;if(Af(e))return"";try{const t=uo(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function Q0(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function eS(e){const t=fo(e);return typeof e=="string"&&Q0(e)?{content:e,isMarkdown:!0}:{content:t,isMarkdown:!1}}function Es(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")||t.startsWith("[")){const n=Ea(t);if(n!==null)return Es(n)}return e}return typeof e=="object"&&!Array.isArray(e)&&e.content!==void 0?Es(e.content):e}const tS={MODE:"library"};function nS(){var i;const e=typeof globalThis<"u"?globalThis.process:void 0,t=typeof((i=e==null?void 0:e.env)==null?void 0:i.NODE_ENV)=="string"?e.env.NODE_ENV:void 0;if(t)return t==="production";const n=typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Xs&&Xs.tagName.toUpperCase()==="SCRIPT"&&Xs.src||new URL("index.umd.js",document.baseURI).href}<"u"?tS:void 0,r=typeof(n==null?void 0:n.MODE)=="string"?n.MODE:void 0,o=typeof(n==null?void 0:n.NODE_ENV)=="string"?n.NODE_ENV:void 0;return(r??o)==="production"}function rS(){return!nS()}function oS(){return typeof window>"u"?!1:window.__ARTIFACT_DEBUG__===!0}function sS(){return rS()||oS()}var Is="Dialog",[_f,LT]=kn(Is),[iS,fn]=_f(Is),jf=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:s,modal:i=!0}=e,a=y.useRef(null),l=y.useRef(null),[c,d]=gr({prop:r,defaultProp:o??!1,onChange:s,caller:Is});return u.jsx(iS,{scope:t,triggerRef:a,contentRef:l,contentId:En(),titleId:En(),descriptionId:En(),open:c,onOpenChange:d,onOpenToggle:y.useCallback(()=>d(f=>!f),[d]),modal:i,children:n})};jf.displayName=Is;var Rf="DialogTrigger",Pf=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=fn(Rf,n),s=Ge(t,o.triggerRef);return u.jsx(Oe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Aa(o.open),...r,ref:s,onClick:he(e.onClick,o.onOpenToggle)})});Pf.displayName=Rf;var Ia="DialogPortal",[aS,Of]=_f(Ia,{forceMount:void 0}),Mf=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,s=fn(Ia,t);return u.jsx(aS,{scope:t,forceMount:n,children:y.Children.map(r,i=>u.jsx(Qt,{present:n||s.open,children:u.jsx(Yo,{asChild:!0,container:o,children:i})}))})};Mf.displayName=Ia;var Ns="DialogOverlay",Df=y.forwardRef((e,t)=>{const n=Of(Ns,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=fn(Ns,e.__scopeDialog);return s.modal?u.jsx(Qt,{present:r||s.open,children:u.jsx(cS,{...o,ref:t})}):null});Df.displayName=Ns;var lS=qn.createSlot("DialogOverlay.RemoveScroll"),cS=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=fn(Ns,n);return u.jsx(os,{as:lS,allowPinchZoom:!0,shards:[o.contentRef],children:u.jsx(Oe.div,{"data-state":Aa(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),or="DialogContent",Lf=y.forwardRef((e,t)=>{const n=Of(or,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=fn(or,e.__scopeDialog);return u.jsx(Qt,{present:r||s.open,children:s.modal?u.jsx(uS,{...o,ref:t}):u.jsx(dS,{...o,ref:t})})});Lf.displayName=or;var uS=y.forwardRef((e,t)=>{const n=fn(or,e.__scopeDialog),r=y.useRef(null),o=Ge(t,n.contentRef,r);return y.useEffect(()=>{const s=r.current;if(s)return zi(s)},[]),u.jsx($f,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:he(e.onCloseAutoFocus,s=>{var i;s.preventDefault(),(i=n.triggerRef.current)==null||i.focus()}),onPointerDownOutside:he(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,a=i.button===0&&i.ctrlKey===!0;(i.button===2||a)&&s.preventDefault()}),onFocusOutside:he(e.onFocusOutside,s=>s.preventDefault())})}),dS=y.forwardRef((e,t)=>{const n=fn(or,e.__scopeDialog),r=y.useRef(!1),o=y.useRef(!1);return u.jsx($f,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,s),s.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),s.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:s=>{var l,c;(l=e.onInteractOutside)==null||l.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;((c=n.triggerRef.current)==null?void 0:c.contains(i))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),$f=y.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,...i}=e,a=fn(or,n),l=y.useRef(null),c=Ge(t,l);return wi(),u.jsxs(u.Fragment,{children:[u.jsx(Lo,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:u.jsx(Do,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":Aa(a.open),...i,ref:c,onDismiss:()=>a.onOpenChange(!1)})}),u.jsxs(u.Fragment,{children:[u.jsx(fS,{titleId:a.titleId}),u.jsx(hS,{contentRef:l,descriptionId:a.descriptionId})]})]})}),Na="DialogTitle",Ff=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=fn(Na,n);return u.jsx(Oe.h2,{id:o.titleId,...r,ref:t})});Ff.displayName=Na;var zf="DialogDescription",Bf=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=fn(zf,n);return u.jsx(Oe.p,{id:o.descriptionId,...r,ref:t})});Bf.displayName=zf;var Uf="DialogClose",Hf=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=fn(Uf,n);return u.jsx(Oe.button,{type:"button",...r,ref:t,onClick:he(e.onClick,()=>o.onOpenChange(!1))})});Hf.displayName=Uf;function Aa(e){return e?"open":"closed"}var Wf="DialogTitleWarning",[$T,Vf]=cx(Wf,{contentName:or,titleName:Na,docsSlug:"dialog"}),fS=({titleId:e})=>{const t=Vf(Wf),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
87
87
 
88
88
  If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
89
89
 
@@ -100,7 +100,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/${t.do
100
100
  `,t=t.substring(p.length+1),d=f.slice(i)}}g.loose||(c?g.loose=!0:/\n *\n *$/.test(r)&&(c=!0)),this.options.gfm&&(o=/^\[[ xX]\] /.exec(h),o&&(s=o[0]!=="[ ] ",h=h.replace(/^\[[ xX]\] +/,""))),g.items.push({type:"list_item",raw:r,task:!!o,checked:s,loose:!1,text:h}),g.raw+=r}g.items[g.items.length-1].raw=r.trimRight(),g.items[g.items.length-1].text=h.trimRight(),g.raw=g.raw.trimRight();const S=g.items.length;for(a=0;a<S;a++)if(this.lexer.state.top=!1,g.items[a].tokens=this.lexer.blockTokens(g.items[a].text,[]),!g.loose){const k=g.items[a].tokens.filter(T=>T.type==="space"),C=k.length>0&&k.some(T=>/\n.*\n/.test(T.raw));g.loose=C}if(g.loose)for(a=0;a<S;a++)g.items[a].loose=!0;return g}}html(t){const n=this.rules.block.html.exec(t);if(n){const r={type:"html",raw:n[0],pre:!this.options.sanitizer&&(n[1]==="pre"||n[1]==="script"||n[1]==="style"),text:n[0]};if(this.options.sanitize){const o=this.options.sanitizer?this.options.sanitizer(n[0]):Dt(n[0]);r.type="paragraph",r.text=o,r.tokens=this.lexer.inline(o)}return r}}def(t){const n=this.rules.block.def.exec(t);if(n){const r=n[1].toLowerCase().replace(/\s+/g," "),o=n[2]?n[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline._escapes,"$1"):"",s=n[3]?n[3].substring(1,n[3].length-1).replace(this.rules.inline._escapes,"$1"):n[3];return{type:"def",tag:r,raw:n[0],href:o,title:s}}}table(t){const n=this.rules.block.table.exec(t);if(n){const r={type:"table",header:sp(n[1]).map(o=>({text:o})),align:n[2].replace(/^ *|\| *$/g,"").split(/ *\| */),rows:n[3]&&n[3].trim()?n[3].replace(/\n[ \t]*$/,"").split(`
101
101
  `):[]};if(r.header.length===r.align.length){r.raw=n[0];let o=r.align.length,s,i,a,l;for(s=0;s<o;s++)/^ *-+: *$/.test(r.align[s])?r.align[s]="right":/^ *:-+: *$/.test(r.align[s])?r.align[s]="center":/^ *:-+ *$/.test(r.align[s])?r.align[s]="left":r.align[s]=null;for(o=r.rows.length,s=0;s<o;s++)r.rows[s]=sp(r.rows[s],r.header.length).map(c=>({text:c}));for(o=r.header.length,i=0;i<o;i++)r.header[i].tokens=this.lexer.inline(r.header[i].text);for(o=r.rows.length,i=0;i<o;i++)for(l=r.rows[i],a=0;a<l.length;a++)l[a].tokens=this.lexer.inline(l[a].text);return r}}}lheading(t){const n=this.rules.block.lheading.exec(t);if(n)return{type:"heading",raw:n[0],depth:n[2].charAt(0)==="="?1:2,text:n[1],tokens:this.lexer.inline(n[1])}}paragraph(t){const n=this.rules.block.paragraph.exec(t);if(n){const r=n[1].charAt(n[1].length-1)===`
102
102
  `?n[1].slice(0,-1):n[1];return{type:"paragraph",raw:n[0],text:r,tokens:this.lexer.inline(r)}}}text(t){const n=this.rules.block.text.exec(t);if(n)return{type:"text",raw:n[0],text:n[0],tokens:this.lexer.inline(n[0])}}escape(t){const n=this.rules.inline.escape.exec(t);if(n)return{type:"escape",raw:n[0],text:Dt(n[1])}}tag(t){const n=this.rules.inline.tag.exec(t);if(n)return!this.lexer.state.inLink&&/^<a /i.test(n[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(n[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(n[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(n[0])&&(this.lexer.state.inRawBlock=!1),{type:this.options.sanitize?"text":"html",raw:n[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(n[0]):Dt(n[0]):n[0]}}link(t){const n=this.rules.inline.link.exec(t);if(n){const r=n[2].trim();if(!this.options.pedantic&&/^</.test(r)){if(!/>$/.test(r))return;const i=Os(r.slice(0,-1),"\\");if((r.length-i.length)%2===0)return}else{const i=RS(n[2],"()");if(i>-1){const l=(n[0].indexOf("!")===0?5:4)+n[1].length+i;n[2]=n[2].substring(0,i),n[0]=n[0].substring(0,l).trim(),n[3]=""}}let o=n[2],s="";if(this.options.pedantic){const i=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(o);i&&(o=i[1],s=i[3])}else s=n[3]?n[3].slice(1,-1):"";return o=o.trim(),/^</.test(o)&&(this.options.pedantic&&!/>$/.test(r)?o=o.slice(1):o=o.slice(1,-1)),ap(n,{href:o&&o.replace(this.rules.inline._escapes,"$1"),title:s&&s.replace(this.rules.inline._escapes,"$1")},n[0],this.lexer)}}reflink(t,n){let r;if((r=this.rules.inline.reflink.exec(t))||(r=this.rules.inline.nolink.exec(t))){let o=(r[2]||r[1]).replace(/\s+/g," ");if(o=n[o.toLowerCase()],!o){const s=r[0].charAt(0);return{type:"text",raw:s,text:s}}return ap(r,o,r[0],this.lexer)}}emStrong(t,n,r=""){let o=this.rules.inline.emStrong.lDelim.exec(t);if(!o||o[3]&&r.match(/[\p{L}\p{N}]/u))return;const s=o[1]||o[2]||"";if(!s||s&&(r===""||this.rules.inline.punctuation.exec(r))){const i=o[0].length-1;let a,l,c=i,d=0;const f=o[0][0]==="*"?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(f.lastIndex=0,n=n.slice(-1*t.length+i);(o=f.exec(n))!=null;){if(a=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!a)continue;if(l=a.length,o[3]||o[4]){c+=l;continue}else if((o[5]||o[6])&&i%3&&!((i+l)%3)){d+=l;continue}if(c-=l,c>0)continue;l=Math.min(l,l+c+d);const p=t.slice(0,i+o.index+(o[0].length-a.length)+l);if(Math.min(i,l)%2){const x=p.slice(1,-1);return{type:"em",raw:p,text:x,tokens:this.lexer.inlineTokens(x)}}const h=p.slice(2,-2);return{type:"strong",raw:p,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(t){const n=this.rules.inline.code.exec(t);if(n){let r=n[2].replace(/\n/g," ");const o=/[^ ]/.test(r),s=/^ /.test(r)&&/ $/.test(r);return o&&s&&(r=r.substring(1,r.length-1)),r=Dt(r,!0),{type:"codespan",raw:n[0],text:r}}}br(t){const n=this.rules.inline.br.exec(t);if(n)return{type:"br",raw:n[0]}}del(t){const n=this.rules.inline.del.exec(t);if(n)return{type:"del",raw:n[0],text:n[2],tokens:this.lexer.inlineTokens(n[2])}}autolink(t,n){const r=this.rules.inline.autolink.exec(t);if(r){let o,s;return r[2]==="@"?(o=Dt(this.options.mangle?n(r[1]):r[1]),s="mailto:"+o):(o=Dt(r[1]),s=o),{type:"link",raw:r[0],text:o,href:s,tokens:[{type:"text",raw:o,text:o}]}}}url(t,n){let r;if(r=this.rules.inline.url.exec(t)){let o,s;if(r[2]==="@")o=Dt(this.options.mangle?n(r[0]):r[0]),s="mailto:"+o;else{let i;do i=r[0],r[0]=this.rules.inline._backpedal.exec(r[0])[0];while(i!==r[0]);o=Dt(r[0]),r[1]==="www."?s="http://"+r[0]:s=r[0]}return{type:"link",raw:r[0],text:o,href:s,tokens:[{type:"text",raw:o,text:o}]}}}inlineText(t,n){const r=this.rules.inline.text.exec(t);if(r){let o;return this.lexer.state.inRawBlock?o=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(r[0]):Dt(r[0]):r[0]:o=Dt(this.options.smartypants?n(r[0]):r[0]),{type:"text",raw:r[0],text:o}}}}const we={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr:/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,html:"^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,table:Ps,lheading:/^((?:.|\n(?!\n))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,text:/^[^\n]+/};we._label=/(?!\s*\])(?:\\.|[^\[\]\\])+/,we._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/,we.def=dt(we.def).replace("label",we._label).replace("title",we._title).getRegex(),we.bullet=/(?:[*+-]|\d{1,9}[.)])/,we.listItemStart=dt(/^( *)(bull) */).replace("bull",we.bullet).getRegex(),we.list=dt(we.list).replace(/bull/g,we.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+we.def.source+")").getRegex(),we._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",we._comment=/<!--(?!-?>)[\s\S]*?(?:-->|$)/,we.html=dt(we.html,"i").replace("comment",we._comment).replace("tag",we._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),we.paragraph=dt(we._paragraph).replace("hr",we.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",we._tag).getRegex(),we.blockquote=dt(we.blockquote).replace("paragraph",we.paragraph).getRegex(),we.normal={...we},we.gfm={...we.normal,table:"^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"},we.gfm.table=dt(we.gfm.table).replace("hr",we.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",we._tag).getRegex(),we.gfm.paragraph=dt(we._paragraph).replace("hr",we.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("table",we.gfm.table).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",we._tag).getRegex(),we.pedantic={...we.normal,html:dt(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",we._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ps,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:dt(we.normal._paragraph).replace("hr",we.hr).replace("heading",` *#{1,6} *[^
103
- ]`).replace("lheading",we.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()};const de={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:Ps,tag:"^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/,rDelimUnd:/^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:Ps,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,punctuation:/^([\spunctuation])/};de._punctuation="!\"#$%&'()+\\-.,/:;<=>?@\\[\\]`^{|}~",de.punctuation=dt(de.punctuation).replace(/punctuation/g,de._punctuation).getRegex(),de.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g,de.escapedEmSt=/(?:^|[^\\])(?:\\\\)*\\[*_]/g,de._comment=dt(we._comment).replace("(?:-->|$)","-->").getRegex(),de.emStrong.lDelim=dt(de.emStrong.lDelim).replace(/punct/g,de._punctuation).getRegex(),de.emStrong.rDelimAst=dt(de.emStrong.rDelimAst,"g").replace(/punct/g,de._punctuation).getRegex(),de.emStrong.rDelimUnd=dt(de.emStrong.rDelimUnd,"g").replace(/punct/g,de._punctuation).getRegex(),de._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,de._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,de._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,de.autolink=dt(de.autolink).replace("scheme",de._scheme).replace("email",de._email).getRegex(),de._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,de.tag=dt(de.tag).replace("comment",de._comment).replace("attribute",de._attribute).getRegex(),de._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,de._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,de._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,de.link=dt(de.link).replace("label",de._label).replace("href",de._href).replace("title",de._title).getRegex(),de.reflink=dt(de.reflink).replace("label",de._label).replace("ref",we._label).getRegex(),de.nolink=dt(de.nolink).replace("ref",we._label).getRegex(),de.reflinkSearch=dt(de.reflinkSearch,"g").replace("reflink",de.reflink).replace("nolink",de.nolink).getRegex(),de.normal={...de},de.pedantic={...de.normal,strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:dt(/^!?\[(label)\]\((.*?)\)/).replace("label",de._label).getRegex(),reflink:dt(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",de._label).getRegex()},de.gfm={...de.normal,escape:dt(de.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},de.gfm.url=dt(de.gfm.url,"i").replace("email",de.gfm._extended_email).getRegex(),de.breaks={...de.gfm,br:dt(de.br).replace("{2,}","*").getRegex(),text:dt(de.gfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()};function MS(e){return e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…")}function lp(e){let t="",n,r;const o=e.length;for(n=0;n<o;n++)r=e.charCodeAt(n),Math.random()>.5&&(r="x"+r.toString(16)),t+="&#"+r+";";return t}class Fn{constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||ir,this.options.tokenizer=this.options.tokenizer||new _a,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const n={block:we.normal,inline:de.normal};this.options.pedantic?(n.block=we.pedantic,n.inline=de.pedantic):this.options.gfm&&(n.block=we.gfm,this.options.breaks?n.inline=de.breaks:n.inline=de.gfm),this.tokenizer.rules=n}static get rules(){return{block:we,inline:de}}static lex(t,n){return new Fn(n).lex(t)}static lexInline(t,n){return new Fn(n).inlineTokens(t)}lex(t){t=t.replace(/\r\n|\r/g,`
103
+ ]`).replace("lheading",we.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()};const ue={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:Ps,tag:"^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/,rDelimUnd:/^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:Ps,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,punctuation:/^([\spunctuation])/};ue._punctuation="!\"#$%&'()+\\-.,/:;<=>?@\\[\\]`^{|}~",ue.punctuation=dt(ue.punctuation).replace(/punctuation/g,ue._punctuation).getRegex(),ue.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g,ue.escapedEmSt=/(?:^|[^\\])(?:\\\\)*\\[*_]/g,ue._comment=dt(we._comment).replace("(?:-->|$)","-->").getRegex(),ue.emStrong.lDelim=dt(ue.emStrong.lDelim).replace(/punct/g,ue._punctuation).getRegex(),ue.emStrong.rDelimAst=dt(ue.emStrong.rDelimAst,"g").replace(/punct/g,ue._punctuation).getRegex(),ue.emStrong.rDelimUnd=dt(ue.emStrong.rDelimUnd,"g").replace(/punct/g,ue._punctuation).getRegex(),ue._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,ue._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,ue._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,ue.autolink=dt(ue.autolink).replace("scheme",ue._scheme).replace("email",ue._email).getRegex(),ue._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,ue.tag=dt(ue.tag).replace("comment",ue._comment).replace("attribute",ue._attribute).getRegex(),ue._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,ue._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,ue._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,ue.link=dt(ue.link).replace("label",ue._label).replace("href",ue._href).replace("title",ue._title).getRegex(),ue.reflink=dt(ue.reflink).replace("label",ue._label).replace("ref",we._label).getRegex(),ue.nolink=dt(ue.nolink).replace("ref",we._label).getRegex(),ue.reflinkSearch=dt(ue.reflinkSearch,"g").replace("reflink",ue.reflink).replace("nolink",ue.nolink).getRegex(),ue.normal={...ue},ue.pedantic={...ue.normal,strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:dt(/^!?\[(label)\]\((.*?)\)/).replace("label",ue._label).getRegex(),reflink:dt(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ue._label).getRegex()},ue.gfm={...ue.normal,escape:dt(ue.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},ue.gfm.url=dt(ue.gfm.url,"i").replace("email",ue.gfm._extended_email).getRegex(),ue.breaks={...ue.gfm,br:dt(ue.br).replace("{2,}","*").getRegex(),text:dt(ue.gfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()};function MS(e){return e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…")}function lp(e){let t="",n,r;const o=e.length;for(n=0;n<o;n++)r=e.charCodeAt(n),Math.random()>.5&&(r="x"+r.toString(16)),t+="&#"+r+";";return t}class Fn{constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||ir,this.options.tokenizer=this.options.tokenizer||new _a,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const n={block:we.normal,inline:ue.normal};this.options.pedantic?(n.block=we.pedantic,n.inline=ue.pedantic):this.options.gfm&&(n.block=we.gfm,this.options.breaks?n.inline=ue.breaks:n.inline=ue.gfm),this.tokenizer.rules=n}static get rules(){return{block:we,inline:ue}}static lex(t,n){return new Fn(n).lex(t)}static lexInline(t,n){return new Fn(n).inlineTokens(t)}lex(t){t=t.replace(/\r\n|\r/g,`
104
104
  `),this.blockTokens(t,this.tokens);let n;for(;n=this.inlineQueue.shift();)this.inlineTokens(n.src,n.tokens);return this.tokens}blockTokens(t,n=[]){this.options.pedantic?t=t.replace(/\t/g," ").replace(/^ +$/gm,""):t=t.replace(/^( *)(\t+)/gm,(a,l,c)=>l+" ".repeat(c.length));let r,o,s,i;for(;t;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(a=>(r=a.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))){if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length),r.raw.length===1&&n.length>0?n[n.length-1].raw+=`
105
105
  `:n.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length),o=n[n.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
106
106
  `+r.raw,o.text+=`
@@ -133,5 +133,5 @@ ${t}</tr>
133
133
  `}strong(t){return`<strong>${t}</strong>`}em(t){return`<em>${t}</em>`}codespan(t){return`<code>${t}</code>`}br(){return this.options.xhtml?"<br/>":"<br>"}del(t){return`<del>${t}</del>`}link(t,n,r){if(t=op(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o='<a href="'+t+'"';return n&&(o+=' title="'+n+'"'),o+=">"+r+"</a>",o}image(t,n,r){if(t=op(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o=`<img src="${t}" alt="${r}"`;return n&&(o+=` title="${n}"`),o+=this.options.xhtml?"/>":">",o}text(t){return t}}class cp{strong(t){return t}em(t){return t}codespan(t){return t}del(t){return t}html(t){return t}text(t){return t}link(t,n,r){return""+r}image(t,n,r){return""+r}br(){return""}}class up{constructor(){this.seen={}}serialize(t){return t.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(t,n){let r=t,o=0;if(this.seen.hasOwnProperty(r)){o=this.seen[t];do o++,r=t+"-"+o;while(this.seen.hasOwnProperty(r))}return n||(this.seen[t]=o,this.seen[r]=0),r}slug(t,n={}){const r=this.serialize(t);return this.getNextSafeSlug(r,n.dryrun)}}class zn{constructor(t){this.options=t||ir,this.options.renderer=this.options.renderer||new ja,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new cp,this.slugger=new up}static parse(t,n){return new zn(n).parse(t)}static parseInline(t,n){return new zn(n).parseInline(t)}parse(t,n=!0){let r="",o,s,i,a,l,c,d,f,p,h,x,m,v,g,b,S,k,C,T;const E=t.length;for(o=0;o<E;o++){if(h=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[h.type]&&(T=this.options.extensions.renderers[h.type].call({parser:this},h),T!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(h.type))){r+=T||"";continue}switch(h.type){case"space":continue;case"hr":{r+=this.renderer.hr();continue}case"heading":{r+=this.renderer.heading(this.parseInline(h.tokens),h.depth,rp(this.parseInline(h.tokens,this.textRenderer)),this.slugger);continue}case"code":{r+=this.renderer.code(h.text,h.lang,h.escaped);continue}case"table":{for(f="",d="",a=h.header.length,s=0;s<a;s++)d+=this.renderer.tablecell(this.parseInline(h.header[s].tokens),{header:!0,align:h.align[s]});for(f+=this.renderer.tablerow(d),p="",a=h.rows.length,s=0;s<a;s++){for(c=h.rows[s],d="",l=c.length,i=0;i<l;i++)d+=this.renderer.tablecell(this.parseInline(c[i].tokens),{header:!1,align:h.align[i]});p+=this.renderer.tablerow(d)}r+=this.renderer.table(f,p);continue}case"blockquote":{p=this.parse(h.tokens),r+=this.renderer.blockquote(p);continue}case"list":{for(x=h.ordered,m=h.start,v=h.loose,a=h.items.length,p="",s=0;s<a;s++)b=h.items[s],S=b.checked,k=b.task,g="",b.task&&(C=this.renderer.checkbox(S),v?b.tokens.length>0&&b.tokens[0].type==="paragraph"?(b.tokens[0].text=C+" "+b.tokens[0].text,b.tokens[0].tokens&&b.tokens[0].tokens.length>0&&b.tokens[0].tokens[0].type==="text"&&(b.tokens[0].tokens[0].text=C+" "+b.tokens[0].tokens[0].text)):b.tokens.unshift({type:"text",text:C}):g+=C),g+=this.parse(b.tokens,v),p+=this.renderer.listitem(g,k,S);r+=this.renderer.list(p,x,m);continue}case"html":{r+=this.renderer.html(h.text);continue}case"paragraph":{r+=this.renderer.paragraph(this.parseInline(h.tokens));continue}case"text":{for(p=h.tokens?this.parseInline(h.tokens):h.text;o+1<E&&t[o+1].type==="text";)h=t[++o],p+=`
134
134
  `+(h.tokens?this.parseInline(h.tokens):h.text);r+=n?this.renderer.paragraph(p):p;continue}default:{const N='Token with "'+h.type+'" type was not found.';if(this.options.silent){console.error(N);return}else throw new Error(N)}}}return r}parseInline(t,n){n=n||this.renderer;let r="",o,s,i;const a=t.length;for(o=0;o<a;o++){if(s=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]&&(i=this.options.extensions.renderers[s.type].call({parser:this},s),i!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type))){r+=i||"";continue}switch(s.type){case"escape":{r+=n.text(s.text);break}case"html":{r+=n.html(s.text);break}case"link":{r+=n.link(s.href,s.title,this.parseInline(s.tokens,n));break}case"image":{r+=n.image(s.href,s.title,s.text);break}case"strong":{r+=n.strong(this.parseInline(s.tokens,n));break}case"em":{r+=n.em(this.parseInline(s.tokens,n));break}case"codespan":{r+=n.codespan(s.text);break}case"br":{r+=n.br();break}case"del":{r+=n.del(this.parseInline(s.tokens,n));break}case"text":{r+=n.text(s.text);break}default:{const l='Token with "'+s.type+'" type was not found.';if(this.options.silent){console.error(l);return}else throw new Error(l)}}}return r}}class Ms{constructor(t){this.options=t||ir}preprocess(t){return t}postprocess(t){return t}}qh(Ms,"passThroughHooks",new Set(["preprocess","postprocess"]));function DS(e,t,n){return r=>{if(r.message+=`
135
135
  Please report this to https://github.com/markedjs/marked.`,e){const o="<p>An error occurred:</p><pre>"+Dt(r.message+"",!0)+"</pre>";if(t)return Promise.resolve(o);if(n){n(null,o);return}return o}if(t)return Promise.reject(r);if(n){n(r);return}throw r}}function dp(e,t){return(n,r,o)=>{typeof r=="function"&&(o=r,r=null);const s={...r};r={...be.defaults,...s};const i=DS(r.silent,r.async,o);if(typeof n>"u"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(PS(r),r.hooks&&(r.hooks.options=r),o){const a=r.highlight;let l;try{r.hooks&&(n=r.hooks.preprocess(n)),l=e(n,r)}catch(f){return i(f)}const c=function(f){let p;if(!f)try{r.walkTokens&&be.walkTokens(l,r.walkTokens),p=t(l,r),r.hooks&&(p=r.hooks.postprocess(p))}catch(h){f=h}return r.highlight=a,f?i(f):o(null,p)};if(!a||a.length<3||(delete r.highlight,!l.length))return c();let d=0;be.walkTokens(l,function(f){f.type==="code"&&(d++,setTimeout(()=>{a(f.text,f.lang,function(p,h){if(p)return c(p);h!=null&&h!==f.text&&(f.text=h,f.escaped=!0),d--,d===0&&c()})},0))}),d===0&&c();return}if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(n):n).then(a=>e(a,r)).then(a=>r.walkTokens?Promise.all(be.walkTokens(a,r.walkTokens)).then(()=>a):a).then(a=>t(a,r)).then(a=>r.hooks?r.hooks.postprocess(a):a).catch(i);try{r.hooks&&(n=r.hooks.preprocess(n));const a=e(n,r);r.walkTokens&&be.walkTokens(a,r.walkTokens);let l=t(a,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(a){return i(a)}}}function be(e,t,n){return dp(Fn.lex,zn.parse)(e,t,n)}be.options=be.setOptions=function(e){return be.defaults={...be.defaults,...e},bS(be.defaults),be},be.getDefaults=Qf,be.defaults=ir,be.use=function(...e){const t=be.defaults.extensions||{renderers:{},childTokens:{}};e.forEach(n=>{const r={...n};if(r.async=be.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if(o.renderer){const s=t.renderers[o.name];s?t.renderers[o.name]=function(...i){let a=o.renderer.apply(this,i);return a===!1&&(a=s.apply(this,i)),a}:t.renderers[o.name]=o.renderer}if(o.tokenizer){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");t[o.level]?t[o.level].unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),r.extensions=t),n.renderer){const o=be.defaults.renderer||new ja;for(const s in n.renderer){const i=o[s];o[s]=(...a)=>{let l=n.renderer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.renderer=o}if(n.tokenizer){const o=be.defaults.tokenizer||new _a;for(const s in n.tokenizer){const i=o[s];o[s]=(...a)=>{let l=n.tokenizer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.tokenizer=o}if(n.hooks){const o=be.defaults.hooks||new Ms;for(const s in n.hooks){const i=o[s];Ms.passThroughHooks.has(s)?o[s]=a=>{if(be.defaults.async)return Promise.resolve(n.hooks[s].call(o,a)).then(c=>i.call(o,c));const l=n.hooks[s].call(o,a);return i.call(o,l)}:o[s]=(...a)=>{let l=n.hooks[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.hooks=o}if(n.walkTokens){const o=be.defaults.walkTokens;r.walkTokens=function(s){let i=[];return i.push(n.walkTokens.call(this,s)),o&&(i=i.concat(o.call(this,s))),i}}be.setOptions(r)})},be.walkTokens=function(e,t){let n=[];for(const r of e)switch(n=n.concat(t.call(be,r)),r.type){case"table":{for(const o of r.header)n=n.concat(be.walkTokens(o.tokens,t));for(const o of r.rows)for(const s of o)n=n.concat(be.walkTokens(s.tokens,t));break}case"list":{n=n.concat(be.walkTokens(r.items,t));break}default:be.defaults.extensions&&be.defaults.extensions.childTokens&&be.defaults.extensions.childTokens[r.type]?be.defaults.extensions.childTokens[r.type].forEach(function(o){n=n.concat(be.walkTokens(r[o],t))}):r.tokens&&(n=n.concat(be.walkTokens(r.tokens,t)))}return n},be.parseInline=dp(Fn.lexInline,zn.parseInline),be.Parser=zn,be.parser=zn.parse,be.Renderer=ja,be.TextRenderer=cp,be.Lexer=Fn,be.lexer=Fn.lex,be.Tokenizer=_a,be.Slugger=up,be.Hooks=Ms,be.parse=be,be.options,be.setOptions,be.use,be.walkTokens,be.parseInline,zn.parse,Fn.lex;function po({content:e,className:t="",allowHtml:n=!1,style:r}){const o=w.useMemo(()=>{try{if(!n){const i=e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");return typeof be.parse=="function"?be.parse(i):be(i)}return typeof be.parse=="function"?be.parse(e):be(e)}catch(i){return console.error("[MarkdownContent] parse error",i),`<pre class="font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words">Error rendering markdown: ${String(i)}</pre>`}},[e,n]),s=w.useMemo(()=>{const i={color:"currentColor",...r};if(r&&r.color){const a=r.color;return{...i,"--tw-prose-body":a,"--tw-prose-headings":a,"--tw-prose-links":a,"--tw-prose-bold":a,"--tw-prose-counters":a,"--tw-prose-bullets":a,"--tw-prose-hr":a,"--tw-prose-quotes":a,"--tw-prose-quote-borders":a,"--tw-prose-captions":a,"--tw-prose-code":a,"--tw-prose-pre-code":a,"--tw-prose-pre-bg":"inherit","--tw-prose-th-borders":a,"--tw-prose-td-borders":a}}return i},[r]);return u.jsx("div",{className:te("markdown prose prose-sm max-w-none break-words","dark:prose-invert","text-current","prose-headings:text-current prose-p:text-current prose-li:text-current prose-a:text-current prose-strong:text-current","prose-em:text-current prose-blockquote:text-current prose-table:text-current prose-td:text-current prose-th:text-current","prose-pre:font-mono prose-pre:text-xs prose-pre:bg-background/50 prose-pre:border prose-pre:rounded prose-pre:p-3 prose-pre:whitespace-pre prose-pre:overflow-x-auto","prose-code:font-mono prose-code:text-sm prose-code:bg-background/50 prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-current",t),style:s,dangerouslySetInnerHTML:{__html:o}})}const LS="prose prose-sm max-w-none break-words dark:prose-invert prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words prose-a:break-all prose-code:break-words prose-blockquote:break-words";function $S(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function fp(e){const t=e.content.find(s=>s.type==="tool_call"),n=e.additionalKwargs??{},r=typeof(t==null?void 0:t.id)=="string"&&t.id||typeof n.toolCallId=="string"&&n.toolCallId||(e.id.startsWith("tool-")?e.id.slice(5):void 0);return{name:(typeof(t==null?void 0:t.name)=="string"&&t.name||typeof n.toolName=="string"&&n.toolName||e.name&&String(e.name))??void 0,toolCallId:r??void 0}}function Ds(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function FS(e){const t=o=>{try{const s=uo(o);return typeof s=="string"?s:JSON.stringify(s??"")}catch{return""}},n=e.filter(o=>o.type==="text");let r="";return n.length?r=t(n.map(o=>o.text).join(`
136
- `)):r=t(e),r||""}function zS(e){return e.name&&e.name.trim()?e.name:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function pp(e){if("type"in e&&e.type==="default_message")return`default:${e.content.length}`;const t=e.updatedAt??e.createdAt??"",n=Array.isArray(e.content)?e.content.map(r=>{switch(r.type){case"text":return`t:${r.text.length}`;case"image_url":return"img";case"file":return"file";case"tool_call":return"call";case"interrupt":return"interrupt";default:return"unknown"}}).join("|"):"";return`${e.id}:${t}:${n}`}function BS(e){if(!e)return"image/png";const t=e.trim();return t?t.includes("/")?t:`image/${t}`:"image/png"}function US(e){const t=[],n=r=>{r&&r.trim()&&t.push(r.trim())};return e&&(n(e.plotId),n(e.artifactId)),t}function HS({base64:e,url:t,formatHint:n,extras:r}){const o=typeof e=="string"&&e.length>0,s=BS(n),i=o?`data:${s};base64,${e}`:t,a=US(r),l=a.length?a.join(" / "):void 0,c=l?`${l} artifact`:"artifact image";return{src:i,alt:c,label:l}}function WS(e){var s,i;const t=((s=e.content_base64)==null?void 0:s.trim())||void 0,n=((i=e.url)==null?void 0:i.trim())||void 0,r=e.format||e.mimeType||e.mime_type;return HS({base64:t,url:n,formatHint:r,extras:{plotId:e.plotId,artifactId:e.artifactId}})}function VS({className:e}){const[t,n]=w.useState(0);return w.useEffect(()=>{const r=setInterval(()=>n(o=>(o+1)%4),500);return()=>clearInterval(r)},[]),u.jsxs("span",{"aria-live":"polite",className:te("inline-block text-xs opacity-70 ml-1",e),children:["Is thinking",".".repeat(t)]})}const Ra=w.memo(function({message:t,messageIndex:n,isStreamingMessage:r=!1,isEditing:o=!1,showActions:s=!0,showTimestamp:i=!0,showAgentName:a=!0,layoutSize:l="desktop",truncateUserMessages:c=!0,userMessagePreviewLength:d=500,showToolMessages:f=!0,showArtifactPreviews:p=!0,customStyles:h={},onEdit:x,onRegenerate:m,onCancelEdit:v,onCopy:g,activeInterrupt:b,disableInterruptActions:S=!1,onInterruptActionStart:k,onInterruptActionEnd:C,checkpointCandidates:T=[],activeCheckpointId:E=null,onSelectCheckpoint:N,defaultCheckpointId:_=null,messageParentCheckpointId:P=null,attemptMeta:R=null}){const[D,F]=w.useState(!1),[A,z]=w.useState("preview"),[j,J]=w.useState(!1),{currentThreadId:B}=Ro(),{respondToInterrupt:O}=Po(),W=l==="phone"||l==="half-screen",X=t.role,he=X==="tool",ae=w.useMemo(()=>"type"in t&&t.type==="default_message"?t:null,[t]),Re=!!ae,G=!(r&&X!=="user"),{uploadingFiles:U,handleFileClick:q,fileViewerOpen:$,currentFileInfo:V,closeFileViewer:re}=qS({allowFileOpen:G,currentThreadId:B}),oe=w.useMemo(()=>{switch(X){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-[hsl(var(--chat-bubble-ai-text))]"}},[X]),se=w.useMemo(()=>ae?"":$S(t.content),[ae,t]),Se=w.useMemo(()=>ae?{}:fp(t),[ae,t]),Qe=w.useMemo(()=>ae?[]:t.content.filter(L=>L.type==="image_url"),[ae,t]),Fe=w.useMemo(()=>ae?[]:t.content.filter(L=>L.type==="file"),[ae,t]),Xe=w.useMemo(()=>ae?[]:t.content.filter(L=>L.type==="interrupt"),[ae,t]),nt=(b==null?void 0:b.id)??(b==null?void 0:b.interrupt_id),fe=Ds(nt),ge=b==null?void 0:b.value,Le=w.useMemo(()=>ae?"":FS(t.content),[ae,t]),Be=w.useMemo(()=>{if(ae||!p)return[];const ne=t.artifact;if(!ne)return[];const pe=[],ce=[...Array.isArray(ne.plots)?ne.plots:[]];for(const et of ce){const ke=WS(et);ke&&pe.push(ke)}return pe},[ae,t,p]),Ve=w.useCallback(async()=>{const L=he?Le:se;async function ne(pe){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(pe);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const ce=new Blob([pe],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":ce})]);return}throw new Error("Clipboard API not supported in this context.")}try{await ne(L),F(!0),setTimeout(()=>F(!1),2e3),g==null||g(L)}catch(pe){console.error("Failed to copy:",pe)}},[he,Le,se,g]),Je=w.useCallback(()=>{if(!x)return;const L=he?Le:se,ne="type"in t&&t.type==="default_message"?void 0:{checkpointId:t.checkpointId??null,checkpointNs:t.checkpointNs??null};x(t.id,L,ne)},[x,t.id,he,Le,se,t]),ze=w.useCallback(()=>{m==null||m(n)},[m,n]),Ze=w.useCallback(()=>{const ne=te(W?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",oe);switch(X){case"user":return u.jsx(ie.User,{className:ne});case"assistant":return u.jsx(ie.Bot,{className:ne});case"tool":return u.jsx(ie.Wrench,{className:ne});default:return u.jsx(ie.Bot,{className:ne})}},[W,oe,X]),Et=w.useCallback(()=>{const L="group relative mb-4 flex w-full";switch(X){case"user":return te(L,"justify-end");case"assistant":case"tool":case"system":return te(L,"justify-start");default:return L}},[X]),ft=w.useCallback(()=>{const L=te("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",W&&"px-3 py-2 text-sm");if(Re)return te(L,"w-full","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40 shadow-sm");switch(X){case"user":return te(L,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return te(L,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40");case"tool":return te(L,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return te(L,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return te(L,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40")}},[W,Re,X]);if(Re&&ae)return u.jsx("div",{className:te(Et(),h.container),children:u.jsxs("div",{className:te(ft(),h.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(ie.Bot,{className:te("h-4 w-4",oe)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(po,{content:ae.content,className:"text-current"})]})});const Ue=w.useCallback(async L=>{if(S)return;const ne=Ds((L==null?void 0:L.id)??(L==null?void 0:L.interrupt_id));if(!ne){console.warn("Interrupt part missing id",L);return}try{k==null||k(),await O(ne,!0)}catch(pe){console.error("Failed to approve interrupt:",pe)}finally{C==null||C()}},[S,C,k,O]),xt=w.useCallback(async L=>{if(S)return;const ne=Ds((L==null?void 0:L.id)??(L==null?void 0:L.interrupt_id));if(!ne){console.warn("Interrupt part missing id",L);return}try{k==null||k(),await O(ne,!1)}catch(pe){console.error("Failed to reject interrupt:",pe)}finally{C==null||C()}},[S,C,k,O]),vt=w.useCallback(({part:L,i:ne})=>{if(L.type==="text"){const pe=L.text??"",ce=pe.trim(),et=Ea(ce);return et&&X!=="tool"?u.jsx(hp,{data:et},ne):X==="user"&&c&&ce.length>d?u.jsx(GS,{text:ce,expanded:j,onExpandedChange:J,previewLength:d,isCompact:W},ne):u.jsx(po,{content:pe,allowHtml:!1},ne)}if(L.type==="image_url"){const pe=L;return u.jsx("div",{className:"my-2",children:u.jsx("img",{src:pe.url,alt:pe.alt??"",loading:"lazy",className:"border rounded max-h-[420px] w-auto object-contain"})},ne)}if(L.type==="file"){const pe=L,ce=pe.name||"file";return u.jsxs("a",{href:pe.url,onClick:et=>q(et.nativeEvent,pe,ne),className:`inline-flex items-center gap-2 rounded px-2 py-1 text-xs bg-gray-100 border hover:bg-gray-200
137
- dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[U[ne]?u.jsx(ie.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[ce,U[ne]?" (processing)":""]})]},ne)}if(L.type==="interrupt"){const pe=L,ce=Ds((pe==null?void 0:pe.id)??(pe==null?void 0:pe.interrupt_id)),et=!!(fe&&ce&&ce===fe),ke=et?ge??(pe==null?void 0:pe.value):pe==null?void 0:pe.value,ct=ce?{...pe,id:ce,interrupt_id:ce}:pe;return u.jsx(KS,{interruptPart:ct,onApprove:Ue,onReject:xt,disabled:S,isActive:et,payload:ke},ne)}return null},[q,U,Ue,xt,X,c,d,j,W,fe,ge,b,S,Xe]),It=w.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(ie.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),bt=w.useCallback(()=>{const L=se.trim().length>0||Qe.length>0||Fe.length>0||Xe.length>0;if(!he&&Fe.length>0&&!r)return It();if(!he&&!L&&!r)return null;if(he)return!f&&Be.length>0?null:f?u.jsx(YS,{message:t,viewMode:A},t.id):null;if(!he&&!ae){const ne=t,pe=u.jsx("div",{className:"space-y-2",children:ne.content.map((ce,et)=>u.jsx(vt,{part:ce,i:et},et))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[pe,u.jsx(VS,{className:oe})]}):pe}},[se,Qe.length,Fe.length,Xe.length,r,he,A,f,Be.length,It,oe]),wt=w.useMemo(()=>ae?"Assistant":zS(t),[ae,t]),He=w.useMemo(()=>ae?[]:Array.isArray(T)?T:[],[T,ae]),zt=w.useMemo(()=>{var L;return He.length?_&&He.some(ne=>ne.id===_)?_:((L=He[0])==null?void 0:L.id)??null:null},[_,He]),_e=w.useMemo(()=>!He.length||!E?null:He.some(L=>L.id===E)?E:null,[E,He])??zt,at=X==="user"&&He.length>0&&typeof N=="function",Y=w.useCallback(L=>{if(!N)return;const ne=(L==null?void 0:L.id)??null,pe=(L==null?void 0:L.parentId)??P??null;N(ne,pe)},[P,N]),ee=w.useMemo(()=>_e?He.findIndex(L=>L.id===_e):-1,[_e,He]),Ce=w.useMemo(()=>ee<0?null:He[ee]??null,[ee,He]),Te=w.useCallback(L=>{const ne=[];if(L.step!==null&&ne.push(`Step ${L.step}`),L.source&&ne.push(L.source),!L.createdAt)return ne.length?ne.join(" • "):L.id.slice(0,8);let pe="";try{const ce=new Date(L.createdAt);Number.isNaN(ce.getTime())||(pe=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(ce))}catch{pe=""}return`${pe}`},[]);return he&&!f&&Be.length===0?null:u.jsxs(u.Fragment,{children:[u.jsx("div",{className:te(Et(),h.container),children:u.jsxs("div",{className:te(ft(),h.content),children:[(i||a||he)&&u.jsxs("div",{className:te("flex items-center justify-between mb-2 pb-2 border-b border-current/10",W&&"mb-1 pb-1",oe,h.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[Ze(),a&&wt&&u.jsx("span",{className:te("font-medium",W?"text-xs":"text-sm"),children:wt}),he&&u.jsxs(Cf,{variant:"outline",className:te("text-xs flex items-center gap-1 cursor-pointer select-none",oe,"border border-current/40",W&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":A==="expanded",onClick:()=>z(L=>L==="expanded"?"preview":"expanded"),onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),z(ne=>ne==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:Se.name??"Tool Output"}),Se.toolCallId&&u.jsx("span",{className:"opacity-70",children:Se.toolCallId.slice(0,8)}),A==="expanded"?u.jsx(ie.ChevronUp,{className:"h-3 w-3"}):u.jsx(ie.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[at&&Ce&&ee>=0&&u.jsx("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{type:"button",className:te("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",ee>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(ee<=0)return;const L=He[ee-1];L&&Y(L)},"aria-label":"Previous checkpoint",disabled:ee<=0,children:u.jsx(ie.ChevronLeft,{className:"h-3 w-3"})}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("span",{className:"whitespace-nowrap",children:[He.length-ee," / ",He.length]}),u.jsx("span",{className:"text-muted-foreground",children:Te(Ce)})]}),u.jsx("button",{type:"button",className:te("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",ee<He.length-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(ee>=He.length-1)return;const L=He[ee+1];L&&Y(L)},"aria-label":"Next checkpoint",disabled:ee>=He.length-1,children:u.jsx(ie.ChevronRight,{className:"h-3 w-3"})})]})}),i&&t.createdAt&&u.jsx("time",{className:te("text-xs opacity-60",oe,W&&"text-xs"),dateTime:new Date(t.createdAt).toISOString(),title:new Date(t.createdAt).toLocaleString(),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(t.createdAt))}),s&&!o&&u.jsxs("div",{className:te("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx("div",{className:"relative",children:u.jsx(st,{variant:"ghost",size:"sm",onClick:()=>Ve(),className:te("h-6 w-6 p-0 hover:bg-foreground/10",oe,W&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(ie.Copy,{className:te(D?"text-success":oe,W?"h-3 w-3":"h-4 w-4")})})}),X==="user"&&x&&u.jsx(st,{variant:"ghost",size:"sm",onClick:Je,className:te("h-6 w-6 p-0 hover:bg-foreground/10",oe,W&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(ie.Edit,{className:te(oe,W?"h-3 w-3":"h-4 w-4")})}),X==="assistant"&&m&&u.jsx(st,{variant:"ghost",size:"sm",onClick:ze,className:te("h-6 w-6 p-0 hover:bg-foreground/10",oe,W&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(ie.RotateCcw,{className:te(oe,W?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsxs("div",{className:"relative",children:[bt(),p&&Be.length>0&&u.jsx("div",{className:"mt-3 space-y-4",children:Be.map((L,ne)=>(w.useEffect(()=>{sS()&&console.debug(`[MessageComponent] Preview ${ne} mounted:`,{src:L.src.substring(0,100),alt:L.alt,label:L.label})},[]),u.jsxs("div",{className:"space-y-2",children:[L.label&&u.jsxs("p",{className:"text-[0.65rem] uppercase tracking-wide text-muted-foreground",children:["Artifact: ",L.label]}),u.jsx("div",{className:"overflow-hidden rounded border border-border/60 bg-background/60 p-1 shadow-sm",children:u.jsx("img",{src:L.src,alt:L.alt,title:L.label,loading:"lazy",className:"h-auto max-h-[420px] w-full rounded object-contain",onLoad:()=>{},onError:pe=>{console.error(`[MessageComponent] ❌ Image failed to load for artifact ${ne}:`,{alt:L.alt,label:L.label,message:pe.target.alt})}})})]},`artifact-${ne}`)))})]}),he&&A==="expanded"&&(Se.toolCallId||Se.name)&&u.jsxs("div",{className:te("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",W&&"text-xs"),children:[Se.name&&u.jsxs("div",{children:["Function: ",Se.name]}),Se.toolCallId&&u.jsxs("div",{children:["Call ID: ",Se.toolCallId]})]}),!(i||a||he)&&s&&!o&&u.jsxs("div",{className:te("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx(st,{variant:"ghost",size:"sm",onClick:()=>Ve(),className:te("h-6 w-6 p-0 hover:bg-background/50 text-current",W&&"h-5 w-5"),children:u.jsx(ie.Copy,{className:te(D?"text-success":"text-current",W?"h-3 w-3":"h-4 w-4")})}),X==="user"&&x&&u.jsx(st,{variant:"ghost",size:"sm",onClick:Je,className:te("h-6 w-6 p-0 hover:bg-background/50 text-current",W&&"h-5 w-5"),children:u.jsx(ie.Edit,{className:te("text-current",W?"h-3 w-3":"h-4 w-4")})}),X==="assistant"&&m&&u.jsx(st,{variant:"ghost",size:"sm",onClick:ze,className:te("h-6 w-6 p-0 hover:bg-background/50 text-current",W&&"h-5 w-5"),children:u.jsx(ie.RotateCcw,{className:te("text-current",W?"h-3 w-3":"h-4 w-4")})})]})]})}),V&&u.jsx(vS,{isOpen:$,onClose:re,fileId:V.id,fileName:V.name,mimeType:V.mimeType})]})},(e,t)=>{var i,a,l,c,d,f,p,h;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&pp(e.message)===pp(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages","attemptMeta"].every(x=>e[x]===t[x]),s=((i=e.customStyles)==null?void 0:i.container)===((a=t.customStyles)==null?void 0:a.container)&&((l=e.customStyles)==null?void 0:l.content)===((c=t.customStyles)==null?void 0:c.content)&&((d=e.customStyles)==null?void 0:d.actions)===((f=t.customStyles)==null?void 0:f.actions)&&((p=e.customStyles)==null?void 0:p.header)===((h=t.customStyles)==null?void 0:h.header);return o&&s});function hp({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:LS,children:u.jsx("ul",{className:"list-disc pl-5",children:e.map((n,r)=>u.jsx("li",{children:String(n)},r))})}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:fo(e)}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:fo(e)})}function KS({interruptPart:e,onApprove:t,onReject:n,disabled:r,isActive:o,payload:s}){const i=e.title??"Approve the result?";let a=null;if(s!=null)if(typeof s=="string")a=u.jsx("p",{className:"text-sm leading-relaxed text-blue-800/90 dark:text-blue-200/90 whitespace-pre-wrap",children:s});else{const c=fo(s);a=u.jsx("pre",{className:"max-h-48 overflow-auto rounded bg-blue-100/60 p-2 text-xs text-blue-900/90 dark:bg-blue-900/40 dark:text-blue-100/80",children:c})}const l=o?"Please approve or reject this action to resume the workflow.":"Waiting for approval from another participant.";return u.jsxs(so,{className:te("border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-950/10 transition-shadow",o?"shadow-md ring-1 ring-blue-300 dark:ring-blue-500/70":"opacity-80"),children:[u.jsxs(io,{className:"pb-3",children:[u.jsx(ao,{className:"text-blue-900 dark:text-blue-100 text-base",children:i}),u.jsx(Tf,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a&&u.jsx(lo,{className:"pt-0 pb-3",children:a}),u.jsx(kf,{className:"pt-0",children:u.jsxs("div",{className:"flex gap-2 ml-auto",children:[u.jsx(st,{size:"sm",variant:"outline",onClick:()=>n(e),className:"border-red-300 text-red-700 hover:bg-red-50 dark:border-red-700 dark:text-red-300 dark:hover:bg-red-950/50",disabled:r||!o,children:"Reject"}),u.jsx(st,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:r||!o,children:"Approve"})]})})]})}function qS(e){const{allowFileOpen:t,currentThreadId:n}=e,{toast:r}=ka(),[o,s]=w.useState({}),[i,a]=w.useState(null),[l,c]=w.useState(!1),d=w.useCallback(()=>{c(!1),a(null)},[]),f=w.useCallback(h=>{a(h),c(!0)},[]),p=w.useCallback(async(h,x,m)=>{var v,g;if(!t){h.preventDefault();return}if(o[m]){h.preventDefault();return}try{const b=String(x.url??""),S=b.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(S){h.preventDefault();const k=S[1],C=x.name||`file_${k}`,T=x.mimeType||"application/octet-stream";f({id:k,name:C,mimeType:T});return}if(b.startsWith("data:")){h.preventDefault(),s(C=>({...C,[m]:!0}));const k=r({title:"Fetching file...",description:"",open:!0});try{const C=await Z0(n??void 0);if(!C||!Array.isArray(C))throw new Error("Invalid file list response");const T=C.find(E=>!E||typeof E!="object"||!((E.filename??"")===(x.name??""))?!1:typeof x.size=="number"&&typeof E.size=="number"?E.size===x.size:!0);if(!(T!=null&&T.id))throw new Error(`File "${x.name}" is not yet available on the server`);if(!T.id||!T.filename)throw new Error("Invalid file data received from server");f({id:T.id,name:x.name||T.filename||`file_${T.id}`,mimeType:x.mimeType||T.mime_type||"application/octet-stream"}),(v=k.update)==null||v.call(k,{id:k.id,title:"Success",description:`Opened ${x.name}`,open:!0})}catch(C){console.error("Failed to fetch server file:",C);const T=C instanceof Error?C.message:"Unknown error occurred";(g=k.update)==null||g.call(k,{id:k.id,title:"Failed",description:T}),r({title:"Failed to fetch file",description:T,open:!0})}finally{s(C=>({...C,[m]:!1}))}}}catch(b){console.error("File click error:",b),s(S=>({...S,[m]:!1}))}},[t,o,r,n,f]);return{uploadingFiles:o,handleFileClick:p,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:d}}function GS({text:e,expanded:t,onExpandedChange:n,previewLength:r,isCompact:o}){const s=Math.max(e.length-r,0),i=e.substring(0,r);return u.jsxs("div",{className:"flex flex-col gap-1",children:[u.jsx("div",{className:te("text-sm text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:t?u.jsx(po,{content:e,allowHtml:!1}):u.jsxs("pre",{className:te("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:[i,"..."]})}),u.jsx(st,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",onClick:()=>n(!t),children:t?u.jsxs(u.Fragment,{children:[u.jsx(ie.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(ie.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",s," chars)"]})})]})}function YS({message:e,viewMode:t}){const r=fp(e).name||"tool",o=c=>{if(c==null)return null;const d=typeof c=="string"?Ea(c)??c:c;if(d&&typeof d=="object")return u.jsx(hp,{data:d});const f=typeof d=="string"?d:(()=>{try{return fo(d)}catch{return String(d??"")}})();return u.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm text-foreground/90",children:f})},s=c=>{if(c==null)return null;const{content:d,isMarkdown:f}=eS(c);return f?u.jsx(po,{content:d,className:"text-current"}):o(c)};if(t==="preview")return null;const i=e.content.find(c=>c.type!=="tool_call");if(!i)return u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(ie.Loader,{className:"h-4 w-4 animate-spin"}),u.jsxs("span",{children:["Waiting for ",r," output…"]})]});if(i.type==="text"){const d=(i.text??"").trim();if(!d)return null;const f=Es(d);return s(f)}const a=uo(i),l=Es(a);return s(l)}const XS=({timelineEntries:e,activeCheckpointId:t,onSelectCheckpoint:n,messagePreviews:r})=>{const o=e??[],s=o.length>0,i=w.useMemo(()=>s?[...o].reverse():[],[o,s]),a=t??(o.length?o[o.length-1].id:null);return w.useEffect(()=>{console.debug("[TimelineColumn] entries:",o.length)},[o.length]),s?u.jsxs("div",{className:"w-32 flex-shrink-0 flex-col border-r border-border/40 pr-2 flex",children:[u.jsxs("div",{className:"relative flex-1 overflow-y-auto pt-4 pb-2 pr-1",children:[u.jsxs("div",{className:"absolute left-0 right-0 top-1 flex items-center justify-between px-2 pb-3 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:[u.jsx("span",{children:"Timeline"}),u.jsxs("div",{className:"group relative z-50",children:[u.jsx(ie.Info,{className:"h-3 w-3 text-muted-foreground cursor-help"}),u.jsx("div",{className:"pointer-events-auto fixed hidden w-56 rounded-md border bg-background p-3 text-[10px] font-normal text-muted-foreground shadow-lg group-hover:block whitespace-normal leading-relaxed",style:{zIndex:9999},children:"Backend pre-selects user inputs + latest loop checkpoint. Click a dot to jump, or use “Latest” to return to the newest messages."})]})]}),u.jsx("div",{className:"pointer-events-none absolute left-3 top-0 bottom-0 w-px bg-border/40"}),u.jsx("div",{className:"flex flex-col gap-3 pt-6 pr-2",children:i.map(l=>{const c=a===l.id,d=l.messageId?(r==null?void 0:r.get(l.messageId))??null:null;return u.jsxs("button",{type:"button",disabled:!n,onClick:()=>n==null?void 0:n(l.id),className:`relative flex items-start gap-2 text-left text-[11px] transition ${c?"text-primary":"text-muted-foreground"} ${n?"hover:text-foreground":"cursor-default opacity-70"}`,children:[u.jsx("span",{className:`mt-1 inline-flex h-3 w-3 items-center justify-center rounded-full border ${c?"border-primary bg-primary/10 text-primary":"border-border bg-background"}`,children:u.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${c?"bg-primary":"bg-border"}`})}),u.jsxs("span",{className:"flex-1",children:[u.jsx("span",{className:"block font-medium leading-tight",children:l.label||"User input"}),u.jsxs("span",{className:"text-[9px] uppercase tracking-wide text-muted-foreground/70",children:[l.step!==null?`STEP ${l.step}`:"STEP —",l.next?` - ${l.next}`:""]}),d&&u.jsx("p",{className:"text-[10px] text-muted-foreground/80 mt-1 line-clamp-2",title:d,children:d})]})]},l.id)})})]}),n&&u.jsx("button",{type:"button",onClick:()=>n==null?void 0:n(null),className:"mt-auto mb-3 rounded-md border border-border/70 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground transition hover:border-foreground/60 hover:text-foreground",children:"Latest"})]}):null},mp=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,Pa=w.forwardRef(({messages:e,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onStartReached:a,onEdit:l,onRegenerate:c,onCancelEdit:d,className:f,style:p,emptyMessage:h,followNewMessages:x=!0,isNavigatingCheckpoint:m=!1,onScrollAway:v,onAtBottom:g,activeInterrupt:b,disableInterruptActions:S=!1,onInterruptActionStart:k,onInterruptActionEnd:C,showToolMessages:T=!0,showArtifactPreviews:E=!0,checkpointMetaById:N,checkpointIndexByKey:_,attemptMetaById:P,userMessageIdToAttempts:R,activeCheckpointId:D,onSelectCheckpoint:F,timelineCheckpoints:A,messagePreviews:z,createSyntheticThinkingMessage:j=!1},J)=>{const B=w.useRef(null),O=w.useRef(null),W=w.useRef(!1),[X,he]=w.useState(!0),ae=w.useMemo(()=>b?e.some(fe=>"type"in fe&&fe.type==="default_message"?!1:Array.isArray(fe==null?void 0:fe.content)&&fe.content.some(ge=>ge&&ge.type==="interrupt"&&(ge.id??ge.interrupt_id)===b.id)):!1,[b,e]),Re=w.useMemo(()=>{if(!b||ae)return null;const fe=b.id&&String(b.id).trim()?String(b.id).trim():"pending-interrupt";let ge;const Le=b.value;if(Le&&typeof Le=="object"&&!Array.isArray(Le)){const Be=Le.title;typeof Be=="string"&&Be.trim()&&(ge=Be.trim())}return{id:`interrupt-${fe}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:fe,value:Le,title:ge}]}},[b,ae]),G=w.useMemo(()=>Re?[...e,Re]:e,[e,Re]),U=w.useMemo(()=>!j||!t?G:!G.some(ge=>ge.role==="assistant")&&G.length>0?[...G,{id:"thinking-assistant",role:"assistant",content:[],createdAt:new Date().toISOString()}]:G,[G,t,j]),q=w.useMemo(()=>T?U:U.filter(fe=>(fe==null?void 0:fe.role)!=="tool"),[U,T]),$=w.useCallback(fe=>{he(fe),v&&v(!fe),g&&g(fe)},[v,g]),V=w.useMemo(()=>{if(a)return async()=>{if(!W.current){W.current=!0;try{await a()}finally{W.current=!1}}}},[a]),re=w.useMemo(()=>!x||m?!1:X?"auto":!1,[X,x,m]),oe=A??[],se=oe.length>0,Se=w.useMemo(()=>{if(typeof h!="string")return null;const fe=h.trim();return fe?{id:"default-message",role:"assistant",type:"default_message",content:fe,createdAt:new Date().toISOString()}:null},[h]),Qe=se?u.jsx(XS,{timelineEntries:oe,activeCheckpointId:D??null,onSelectCheckpoint:F,messagePreviews:z}):null,Fe=["flex h-full flex-col md:flex-row",f].filter(Boolean).join(" "),Xe=()=>Se?u.jsx("div",{className:"p-6 h-full overflow-y-auto",children:u.jsx("div",{className:"w-full max-w-full",children:u.jsx(Ra,{message:Se,messageIndex:0,isStreamingMessage:!1,showActions:!1,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:()=>{},onRegenerate:()=>{},onCancelEdit:()=>{},showArtifactPreviews:E})})}):u.jsx("div",{className:"flex h-full items-center justify-center py-8 text-center text-muted-foreground",children:h??"No messages yet. Start a conversation!"}),nt=q.length>0;return w.useImperativeHandle(J,()=>({scrollToLatest:()=>{var fe,ge;if(B.current&&q.length>0){const Le=q.length-1;(ge=(fe=B.current).scrollToIndex)==null||ge.call(fe,{index:Le,align:"end",behavior:"auto"})}else O.current&&(O.current.scrollTop=O.current.scrollHeight)},scrollToTop:()=>{var fe,ge;B.current&&q.length>0?(ge=(fe=B.current).scrollToIndex)==null||ge.call(fe,{index:0,align:"start",behavior:"auto"}):O.current&&(O.current.scrollTop=0)}}),[q]),u.jsxs("div",{className:Fe,style:p,children:[Qe,u.jsx("div",{className:"relative flex-1 min-h-0",children:nt?u.jsx(_0,{ref:fe=>{B.current=fe},scrollerRef:fe=>{O.current=fe instanceof HTMLDivElement?fe:null},data:q,followOutput:re,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,alignToBottom:!0,startReached:()=>{V&&V()},atBottomStateChange:$,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(fe,ge)=>mp(ge,fe),itemContent:(fe,ge)=>{var vt;const Le=mp(ge,fe),Be="type"in ge&&ge.type==="default_message";let Ve=[],Je=null,ze={},Ze={},Et=null,ft=null,Ue=null;if(!Be){const It=ge,bt=It.checkpointId??null;ze=It.additionalKwargs??{},Ze=It.responseMetadata??{};const wt=bt&&N?N.get(bt)??null:null;Et=typeof ze.step=="number"?ze.step:typeof Ze.step=="number"?Ze.step:(wt==null?void 0:wt.step)??null;const He=typeof ze.source=="string"?ze.source:typeof Ze.source=="string"?Ze.source:(wt==null?void 0:wt.source)??null;ft=He?String(He):null;const zt=Et!==null&&ft?`${Et}:${ft}`:null;if(zt&&(_!=null&&_.has(zt))?Ve=_.get(zt)??[]:bt&&wt&&(Ve=[wt]),Je=bt??((vt=Ve[0])==null?void 0:vt.id)??null,Ue=bt?(P==null?void 0:P.get(bt))??null:null,!Ue&&(ge==null?void 0:ge.role)==="user"&&(ge!=null&&ge.id)&&R){const Pe=R.get(ge.id);if(Pe&&Pe.length>0){const _e=Pe[0].checkpointId;Ue=(P==null?void 0:P.get(_e))??null,console.log(`[MessageList] Found attempt by user message ID "${ge.id}":`,Pe.length,"versions")}}if(!Ue&&Ve.length>0&&P){const Pe=P.get(Ve[0].id);Pe&&(Ue=Pe)}if(Ue&&Ue.attemptCount>1&&P){const Pe=Ue.baseUserMessageId;if(Pe){const _e=[];for(const[at,Y]of P.entries())if(Y.baseUserMessageId===Pe){const ee=N==null?void 0:N.get(at);ee&&_e.push(ee)}_e.length>0&&(Ve=_e)}}if(Ue&&Ue.attemptCount>1&&N&&P){const Pe=[];for(const[_e,at]of N.entries()){const Y=P.get(_e);Y&&Y.attemptCount===Ue.attemptCount&&Y.baseUserMessageId===Ue.baseUserMessageId&&Pe.push(at)}Pe.sort((_e,at)=>{const Y=_e.createdAt?Date.parse(_e.createdAt):0;return(at.createdAt?Date.parse(at.createdAt):0)-Y}),Pe.length>0&&(Ve=Pe,console.log("[MessageList] Populated checkpointCandidates with all attempts:",{messageId:ge.id,attemptCount:Ue.attemptCount,candidateIds:Ve.map(_e=>_e.id)}))}}const xt=(()=>{if(typeof ze.parentCheckpointId=="string")return ze.parentCheckpointId;if(typeof Ze.parentCheckpointId=="string")return Ze.parentCheckpointId})();return u.jsx("div",{className:"relative mb-4 last:mb-0","data-message-id":Le,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:u.jsx(Ra,{message:ge,messageIndex:fe,isStreamingMessage:t&&n===ge.id,streamingDebounceMs:r,isEditing:i===ge.id,showActions:s,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:l,onRegenerate:()=>c(fe),onCancelEdit:d,activeInterrupt:b,disableInterruptActions:S,onInterruptActionStart:k,onInterruptActionEnd:C,showToolMessages:T,showArtifactPreviews:E,checkpointCandidates:Ve,activeCheckpointId:D??null,onSelectCheckpoint:F,defaultCheckpointId:Je,messageParentCheckpointId:xt,attemptMeta:Ue})})}}):Xe()})]})});Pa.displayName="MessageList";const gp={value:""};function Ls({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:c=!0,showToolMessages:d=!0,showArtifactPreviews:f=!0,customStyles:p={},onMessageSent:h,onExcelUploadSuccess:x,onError:m}){const{api:v}=di(),{currentThreadId:g}=Ro(),{threadId:b,messages:S,isHistoryLoading:k,isLoading:C,navigateToCheckpoint:T,returnToLatest:E,checkpoint:N,checkpoints:_,interrupt:P,metadata:R,timelineCheckpoints:D,messagePreviews:F}=Po(),{isStreaming:A,error:z,connectionState:j,submit:J,stop:B}=fc(),O=b??g??null,W=(N==null?void 0:N.id)??null,X=(N==null?void 0:N.namespace)??null,he=(R==null?void 0:R.assemblingMessageId)??null,ae=P,[Re,G]=w.useState(!1);w.useEffect(()=>{ae||G(!1)},[ae]);const U=w.useCallback(()=>{G(!0)},[]),q=w.useCallback(()=>{G(!1)},[]),$=!!ae||Re,[V,re]=w.useState(null),[oe,se]=w.useState(""),[Se,Qe]=w.useState(null),[Fe,Xe]=w.useState(null),[nt,fe]=w.useState([]),[ge,Le]=w.useState(0),[Be,Ve]=w.useState(0),[Je,ze]=w.useState(!1),[Ze,Et]=w.useState(null),[ft,Ue]=w.useState(null),[xt,vt]=w.useState(!1),[It,bt]=w.useState(null),wt=w.useRef(!1),[He,zt]=w.useState(()=>gp.value),Pe=w.useRef(He),_e=w.useRef(null),at=w.useCallback(Z=>{gp.value=Z,zt(Z)},[]),[Y,ee]=w.useState(!1),Ce=w.useRef(null),Te=w.useCallback((Z,xe)=>{if(!Z||typeof Z!="object")return null;const ye=Z[xe];return typeof ye=="number"?ye:null},[]),L=w.useCallback((Z,xe)=>{if(!Z||typeof Z!="object")return null;const ye=Z[xe];return typeof ye=="string"&&ye.trim()?ye:null},[]),ne=w.useMemo(()=>{const Z=Ke=>{if(!Array.isArray(Ke)||Ke.length===0)return null;const Nt=Ke.map(ot=>{if(typeof ot=="string")return ot.trim();if(ot&&typeof ot=="object"&&"type"in ot){const Bt=ot;if(typeof Bt.type=="string")return Bt.type}return null}).filter(ot=>!!(ot&&ot.length));return Nt.length?Nt.join(", "):null},xe=Array.isArray(_)?_.map(Ke=>{const Nt=Z(Ke.next);return Nt?{...Ke,metadata:{...Ke.metadata??{},next:Nt}}:Ke}):[];return xe.some(Ke=>Te(Ke.metadata,"step")!==null)&&xe.sort((Ke,Nt)=>{const ot=Te(Ke.metadata,"step"),Bt=Te(Nt.metadata,"step");if(ot!==null||Bt!==null)return(Bt??Number.NEGATIVE_INFINITY)-(ot??Number.NEGATIVE_INFINITY);const sn=Date.parse(Ke.createdAt??""),jr=Date.parse(Nt.createdAt??"");return Number.isNaN(sn)||Number.isNaN(jr)?0:jr-sn}),xe},[_,Te]),{checkpointMetaById:pe,checkpointIndexByKey:ce,attemptMetaById:et,userMessageIdToAttempts:ke}=w.useMemo(()=>{const Z=new Map,xe=new Map,ye=new Map;for(const ot of ne){const Bt=ot.checkpointId??null;if(!Bt)continue;const sn=Te(ot.metadata,"step"),jr=L(ot.metadata,"source"),Wh={id:Bt,step:sn,source:jr,createdAt:ot.createdAt??null,namespace:ot.checkpointNs??null,parentId:ot.parentId??null};if(Z.set(Bt,Wh),sn!==null&&jr){const Vh=`${sn}:${jr}`,Kh=xe.get(Vh)??[];Kh.push(Wh),xe.set(Vh,Kh)}}console.log("[ChatInterface] Building attempt metadata for",ne.length,"checkpoints");const Ke=gw(ne);for(const[ot,Bt]of Z.entries()){const sn=Ke.get(ot);sn?ye.set(ot,{...Bt,attemptIndex:sn.attemptIndex,attemptCount:sn.attemptCount,isLatestAttempt:sn.isLatestAttempt,baseUserMessageId:sn.baseUserMessageId??null}):ye.set(ot,{...Bt,attemptIndex:0,attemptCount:1,isLatestAttempt:!0,baseUserMessageId:null})}console.log("[ChatInterface] Final attemptMetaById:",{totalCheckpoints:ye.size,withMultipleAttempts:Array.from(ye.values()).filter(ot=>ot.attemptCount>1).length,samples:Array.from(ye.entries()).slice(0,3).map(([ot,Bt])=>({checkpointId:ot,attemptIndex:Bt.attemptIndex,attemptCount:Bt.attemptCount}))});const Nt=xw(ye);return console.log("[ChatInterface] userMessageIdToAttempts map built with",Nt.size,"user message IDs with multiple attempts"),{checkpointMetaById:Z,checkpointIndexByKey:xe,attemptMetaById:ye,userMessageIdToAttempts:Nt}},[ne,Te,L]),ct=D??[],Wn=w.useRef(null),ur=w.useRef(null),Vn=w.useCallback(()=>{Wn.current&&(Wn.current.value=""),ur.current&&(ur.current.value=""),Le(Z=>Z+1),Ve(Z=>Z+1)},[]),Ga=w.useCallback(Z=>{at(Z)},[at]),Gs=w.useRef(!1);w.useEffect(()=>{Gs.current&&!A&&(fe([]),Vn()),Gs.current=A},[A,Vn]);const[Ya,Xa]=w.useState("desktop");w.useEffect(()=>{const Z=()=>{const xe=window.innerWidth;Xa(xe<640?"phone":xe<1024?"tablet":"desktop")};return Z(),window.addEventListener("resize",Z),()=>window.removeEventListener("resize",Z)},[]),w.useEffect(()=>{wt.current=!1},[O]),w.useEffect(()=>{Pe.current=He},[He]),w.useEffect(()=>{if(!V){_e.current=null;return}_e.current===null&&(_e.current=Pe.current),at(oe??"")},[oe,V,at]),w.useEffect(()=>{(async()=>{if(!v.baseUrl){bt(null);return}try{const ye=(await v.getAgent("default")).uiDefaultMessage||"";bt(ye||null)}catch(xe){console.warn("Failed to fetch default message:",xe),bt(null)}})()},[v.baseUrl]),w.useEffect(()=>{z&&!xt&&(m==null||m(z))},[z,xt,m]);const I=Z=>{if(Z.length>us)return`Message too long (${Z.length}/${us} characters)`;try{return bw(Z),null}catch(xe){return(xe==null?void 0:xe.message)||"Invalid message"}},K=async Z=>{const xe=Z.trim();if(!(!xe&&nt.length===0)){if(xe){const ye=I(xe);if(ye){Xe(ye);return}}try{const ye=W??void 0,Ke=X??void 0,Nt=V?{edit:!0,originalMessageId:V,...Se!=null&&Se.checkpointId?{originalCheckpointId:Se.checkpointId}:{},...Se!=null&&Se.checkpointNs?{originalCheckpointNs:Se.checkpointNs}:{}}:void 0;await J({text:xe||"",attachments:nt,messageAdditionalKwargs:Nt},{checkpointId:ye,checkpointNs:Ke}),h==null||h(xe),at(""),Xe(null),fe([]),Vn(),re(null),se(""),Qe(null)}catch(ye){const Ke=(ye==null?void 0:ye.message)||"Failed to send message";Xe(Ke),m==null||m(Ke)}}},le=w.useCallback((Z,xe,ye)=>{c&&(_e.current=He,re(Z),se(xe),at(xe),Xe(null),Qe({checkpointId:(ye==null?void 0:ye.checkpointId)??null,checkpointNs:(ye==null?void 0:ye.checkpointNs)??null}))},[He,c,at]),Ee=w.useCallback(()=>{re(null),se(""),Qe(null),Xe(null),at(_e.current??He),_e.current=null},[He,at]),rt=w.useCallback((Z,xe,ye)=>{le(Z,xe,ye)},[le]),lt=w.useCallback(Z=>{for(let xe=Z-1;xe>=0;xe--)if(S[xe].role==="user"){const ye=S[xe].content||[],Nt=ye.filter(ot=>ot.type==="text").map(ot=>ot.text).join("")||(()=>{try{return JSON.stringify(ye,null,2)}catch{return String(ye)}})();Nt&&J({text:Nt},{checkpointId:W??void 0,checkpointNs:X??void 0});break}},[S,J,W,X]),qe=Z=>{const xe=Array.from(Z.target.files||[]);fe(ye=>[...ye,...xe]),Z.target.value=""},We=Z=>{fe(xe=>{const ye=xe.filter((Ke,Nt)=>Z!==Nt);return ye.length===0&&Vn(),ye})},Rt=async Z=>{const xe=(Z.target.files||[])[0];if(xe){Et(null),Ue(null),ze(!0);try{await J({attachments:[xe]},{checkpointId:W??void 0,checkpointNs:X??void 0});const ye=`Uploaded ${xe.name} - processing through chat stream`;Ue(ye)}catch(ye){const Ke=ye instanceof Error?ye.message:"Failed to upload Excel file";console.error("Excel upload failed",ye),Et(Ke),m==null||m(Ke)}finally{ze(!1),Z.target.value="",Vn()}}},yt=async Z=>{if(g){ee(!0);try{if(!Z){await E(),requestAnimationFrame(()=>{var Ke;(Ke=Ce.current)==null||Ke.scrollToLatest()});return}const xe=ne.find(Ke=>Ke.checkpointId===Z),ye=(xe==null?void 0:xe.checkpointNs)??null;await T(Z,ye),requestAnimationFrame(()=>{var Ke;(Ke=Ce.current)==null||Ke.scrollToTop()})}finally{ee(!1)}}},St=w.useCallback(async Z=>{await yt(Z)},[yt]),Vt=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${p.container||""}`,Kn=`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 ${p.messagesArea||""}`,_n=`flex-shrink-0 w-full border-t p-4 bg-transparent ${p.inputArea||""}`;return w.useCallback(Z=>{if(!Z)return"Latest";const xe=[];Z.step!==null&&xe.push(`Step ${Z.step}`),Z.source&&xe.push(Z.source);const ye=Z.createdAt?new Date(Z.createdAt):null,Ke=ye&&!Number.isNaN(ye.getTime())?ye.toLocaleString():Z.createdAt??Z.id,Nt=xe.length?` — ${xe.join(" • ")}`:"";return`${Ke}${Nt}`},[]),u.jsxs("div",{className:Vt,children:[!!z&&!xt&&u.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:[u.jsx("span",{children:z}),u.jsx(st,{variant:"ghost",size:"sm",onClick:()=>vt(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:u.jsx(ie.X,{size:16})})]}),u.jsxs("div",{className:`relative ${Kn}`,style:r?{maxHeight:r}:void 0,children:[u.jsx(Pa,{ref:Ce,className:"h-full",style:{height:"100%"},messages:S,isStreaming:A,streamingAssistantId:he,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:Ya,enableMessageEditing:c,editingMessageId:V,onEdit:rt,onRegenerate:lt,onCancelEdit:Ee,emptyMessage:It??void 0,isNavigatingCheckpoint:Y,activeInterrupt:ae,disableInterruptActions:Re,onInterruptActionStart:U,onInterruptActionEnd:q,showToolMessages:d,showArtifactPreviews:f,checkpointMetaById:pe,checkpointIndexByKey:ce,attemptMetaById:et,userMessageIdToAttempts:ke,activeCheckpointId:W,onSelectCheckpoint:St,timelineCheckpoints:ct,messagePreviews:F}),(j==="reconnecting"||j==="connecting")&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-muted/80 px-3 py-1 text-xs font-medium text-foreground shadow-sm backdrop-blur-sm dark:bg-muted/60",children:u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx(ie.Loader2,{className:"h-3 w-3 animate-spin"}),j==="reconnecting"?"Reconnecting…":"Connecting…"]})}),j==="error"&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-destructive/10 px-3 py-1 text-xs font-semibold text-destructive shadow-sm",children:"Connection lost"}),C&&u.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:[u.jsx(ie.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]}),(k||Y)&&u.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:[u.jsx(ie.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading checkpoint…"})]})]}),u.jsxs("div",{className:_n,children:[V&&u.jsx("div",{className:"mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(ie.Edit3,{size:16,className:"text-blue-600"}),u.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),u.jsx(st,{variant:"ghost",size:"sm",onClick:Ee,className:"text-blue-600 hover:bg-blue-100",children:u.jsx(ie.X,{size:16})})]})}),(a||l)&&u.jsxs("div",{className:"mb-3 space-y-3",children:[a&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Wn,type:"file",multiple:!0,onChange:Z=>qe(Z),className:"hidden"},ge),nt.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2",children:nt.map((Z,xe)=>u.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:[u.jsx(ie.Paperclip,{size:14}),u.jsx("span",{className:"truncate max-w-[150px]",children:Z.name}),u.jsx(st,{variant:"ghost",size:"sm",onClick:()=>We(xe),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 ${Z.name}`,children:u.jsx(ie.X,{size:12})})]},xe))})]}),l&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:ur,type:"file",accept:".xls,.xlsx,.xlsm",onChange:Rt,className:"hidden"},Be),Je&&u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(ie.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),ft&&!Je&&u.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:ft}),Ze&&!Je&&u.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:Ze})]})]}),Fe&&u.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:Fe}),u.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&u.jsxs(aw,{children:[u.jsx(lw,{asChild:!0,children:u.jsx(st,{type:"button",size:"icon",variant:"outline",disabled:A||$,title:"More input actions",className:p.moreButton||"",children:u.jsx(ie.Plus,{size:16})})}),u.jsxs(Cd,{align:"start",sideOffset:6,className:"w-52",children:[a&&u.jsxs(Qi,{onClick:()=>{var Z;return(Z=Wn.current)==null?void 0:Z.click()},className:"cursor-pointer",children:[u.jsx(ie.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&u.jsxs(Qi,{onClick:()=>{var Z;Je||(Z=ur.current)==null||Z.click()},className:`cursor-pointer ${Je?"opacity-60 pointer-events-none":""}`,children:[u.jsx(ie.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),u.jsx("div",{className:"flex-1",children:u.jsx(lx,{initialValue:oe,editingMessageId:V,value:He,onValueChange:Ga,placeholder:V?"Edit your message...":t,isStreaming:A,disabled:$,maxLength:us,onSend:K,onCancelEdit:Ee,onStop:B,allowEmptySend:nt.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${V?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${Fe?"border-red-400":""} ${p.textarea||""}`})})]})]})]})}const $s=y.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{type:t,className:te("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}));$s.displayName="Input";function Oa(e,[t,n]){return Math.min(n,Math.max(t,e))}function JS(e,t){return y.useReducer((n,r)=>t[n][r]??n,e)}var Ma="ScrollArea",[xp,FT]=kn(Ma),[ZS,rn]=xp(Ma),yp=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,l]=y.useState(null),[c,d]=y.useState(null),[f,p]=y.useState(null),[h,x]=y.useState(null),[m,v]=y.useState(null),[g,b]=y.useState(0),[S,k]=y.useState(0),[C,T]=y.useState(!1),[E,N]=y.useState(!1),_=Ge(t,R=>l(R)),P=Mo(o);return u.jsx(ZS,{scope:n,type:r,dir:P,scrollHideDelay:s,scrollArea:a,viewport:c,onViewportChange:d,content:f,onContentChange:p,scrollbarX:h,onScrollbarXChange:x,scrollbarXEnabled:C,onScrollbarXEnabledChange:T,scrollbarY:m,onScrollbarYChange:v,scrollbarYEnabled:E,onScrollbarYEnabledChange:N,onCornerWidthChange:b,onCornerHeightChange:k,children:u.jsx(Oe.div,{dir:P,...i,ref:_,style:{position:"relative","--radix-scroll-area-corner-width":g+"px","--radix-scroll-area-corner-height":S+"px",...e.style}})})});yp.displayName=Ma;var vp="ScrollAreaViewport",bp=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=rn(vp,n),a=y.useRef(null),l=Ge(t,a,i.onViewportChange);return u.jsxs(u.Fragment,{children:[u.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}),u.jsx(Oe.div,{"data-radix-scroll-area-viewport":"",...s,ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:u.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});bp.displayName=vp;var Cn="ScrollAreaScrollbar",Da=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=rn(Cn,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return y.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?u.jsx(QS,{...r,ref:t,forceMount:n}):o.type==="scroll"?u.jsx(eC,{...r,ref:t,forceMount:n}):o.type==="auto"?u.jsx(wp,{...r,ref:t,forceMount:n}):o.type==="always"?u.jsx(La,{...r,ref:t}):null});Da.displayName=Cn;var QS=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=rn(Cn,e.__scopeScrollArea),[s,i]=y.useState(!1);return y.useEffect(()=>{const a=o.scrollArea;let l=0;if(a){const c=()=>{window.clearTimeout(l),i(!0)},d=()=>{l=window.setTimeout(()=>i(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",c),a.addEventListener("pointerleave",d),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",c),a.removeEventListener("pointerleave",d)}}},[o.scrollArea,o.scrollHideDelay]),u.jsx(Qt,{present:n||s,children:u.jsx(wp,{"data-state":s?"visible":"hidden",...r,ref:t})})}),eC=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=rn(Cn,e.__scopeScrollArea),s=e.orientation==="horizontal",i=Us(()=>l("SCROLL_END"),100),[a,l]=JS("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 y.useEffect(()=>{if(a==="idle"){const c=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(c)}},[a,o.scrollHideDelay,l]),y.useEffect(()=>{const c=o.viewport,d=s?"scrollLeft":"scrollTop";if(c){let f=c[d];const p=()=>{const h=c[d];f!==h&&(l("SCROLL"),i()),f=h};return c.addEventListener("scroll",p),()=>c.removeEventListener("scroll",p)}},[o.viewport,s,l,i]),u.jsx(Qt,{present:n||a!=="hidden",children:u.jsx(La,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:me(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:me(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),wp=y.forwardRef((e,t)=>{const n=rn(Cn,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=y.useState(!1),a=e.orientation==="horizontal",l=Us(()=>{if(n.viewport){const c=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?c:d)}},10);return Nr(n.viewport,l),Nr(n.content,l),u.jsx(Qt,{present:r||s,children:u.jsx(La,{"data-state":s?"visible":"hidden",...o,ref:t})})}),La=y.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=rn(Cn,e.__scopeScrollArea),s=y.useRef(null),i=y.useRef(0),[a,l]=y.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=Ep(a.viewport,a.content),d={...r,sizes:a,onSizesChange:l,hasThumb:c>0&&c<1,onThumbChange:p=>s.current=p,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:p=>i.current=p};function f(p,h){return iC(p,i.current,a,h)}return n==="horizontal"?u.jsx(tC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const p=o.viewport.scrollLeft,h=Ip(p,a,o.dir);s.current.style.transform=`translate3d(${h}px, 0, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollLeft=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollLeft=f(p,o.dir))}}):n==="vertical"?u.jsx(nC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const p=o.viewport.scrollTop,h=Ip(p,a);s.current.style.transform=`translate3d(0, ${h}px, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollTop=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollTop=f(p))}}):null}),tC=y.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=rn(Cn,e.__scopeScrollArea),[i,a]=y.useState(),l=y.useRef(null),c=Ge(t,l,s.onScrollbarXChange);return y.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Cp,{"data-orientation":"horizontal",...o,ref:c,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":Bs(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,f)=>{if(s.viewport){const p=s.viewport.scrollLeft+d.deltaX;e.onWheelScroll(p),Ap(p,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:zs(i.paddingLeft),paddingEnd:zs(i.paddingRight)}})}})}),nC=y.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=rn(Cn,e.__scopeScrollArea),[i,a]=y.useState(),l=y.useRef(null),c=Ge(t,l,s.onScrollbarYChange);return y.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Cp,{"data-orientation":"vertical",...o,ref:c,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":Bs(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,f)=>{if(s.viewport){const p=s.viewport.scrollTop+d.deltaY;e.onWheelScroll(p),Ap(p,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:zs(i.paddingTop),paddingEnd:zs(i.paddingBottom)}})}})}),[rC,Sp]=xp(Cn),Cp=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:c,onWheelScroll:d,onResize:f,...p}=e,h=rn(Cn,n),[x,m]=y.useState(null),v=Ge(t,_=>m(_)),g=y.useRef(null),b=y.useRef(""),S=h.viewport,k=r.content-r.viewport,C=jt(d),T=jt(l),E=Us(f,10);function N(_){if(g.current){const P=_.clientX-g.current.left,R=_.clientY-g.current.top;c({x:P,y:R})}}return y.useEffect(()=>{const _=P=>{const R=P.target;(x==null?void 0:x.contains(R))&&C(P,k)};return document.addEventListener("wheel",_,{passive:!1}),()=>document.removeEventListener("wheel",_,{passive:!1})},[S,x,k,C]),y.useEffect(T,[r,T]),Nr(x,E),Nr(h.content,E),u.jsx(rC,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:jt(s),onThumbPointerUp:jt(i),onThumbPositionChange:T,onThumbPointerDown:jt(a),children:u.jsx(Oe.div,{...p,ref:v,style:{position:"absolute",...p.style},onPointerDown:me(e.onPointerDown,_=>{_.button===0&&(_.target.setPointerCapture(_.pointerId),g.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",h.viewport&&(h.viewport.style.scrollBehavior="auto"),N(_))}),onPointerMove:me(e.onPointerMove,N),onPointerUp:me(e.onPointerUp,_=>{const P=_.target;P.hasPointerCapture(_.pointerId)&&P.releasePointerCapture(_.pointerId),document.body.style.webkitUserSelect=b.current,h.viewport&&(h.viewport.style.scrollBehavior=""),g.current=null})})})}),Fs="ScrollAreaThumb",Tp=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Sp(Fs,e.__scopeScrollArea);return u.jsx(Qt,{present:n||o.hasThumb,children:u.jsx(oC,{ref:t,...r})})}),oC=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=rn(Fs,n),i=Sp(Fs,n),{onThumbPositionChange:a}=i,l=Ge(t,f=>i.onThumbChange(f)),c=y.useRef(void 0),d=Us(()=>{c.current&&(c.current(),c.current=void 0)},100);return y.useEffect(()=>{const f=s.viewport;if(f){const p=()=>{if(d(),!c.current){const h=aC(f,a);c.current=h,a()}};return a(),f.addEventListener("scroll",p),()=>f.removeEventListener("scroll",p)}},[s.viewport,d,a]),u.jsx(Oe.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:me(e.onPointerDownCapture,f=>{const h=f.target.getBoundingClientRect(),x=f.clientX-h.left,m=f.clientY-h.top;i.onThumbPointerDown({x,y:m})}),onPointerUp:me(e.onPointerUp,i.onThumbPointerUp)})});Tp.displayName=Fs;var $a="ScrollAreaCorner",kp=y.forwardRef((e,t)=>{const n=rn($a,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(sC,{...e,ref:t}):null});kp.displayName=$a;var sC=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=rn($a,n),[s,i]=y.useState(0),[a,l]=y.useState(0),c=!!(s&&a);return Nr(o.scrollbarX,()=>{var f;const d=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(d),l(d)}),Nr(o.scrollbarY,()=>{var f;const d=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(d),i(d)}),c?u.jsx(Oe.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 zs(e){return e?parseInt(e,10):0}function Ep(e,t){const n=e/t;return isNaN(n)?0:n}function Bs(e){const t=Ep(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function iC(e,t,n,r="ltr"){const o=Bs(n),s=o/2,i=t||s,a=o-i,l=n.scrollbar.paddingStart+i,c=n.scrollbar.size-n.scrollbar.paddingEnd-a,d=n.content-n.viewport,f=r==="ltr"?[0,d]:[d*-1,0];return Np([l,c],f)(e)}function Ip(e,t,n="ltr"){const r=Bs(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],c=Oa(e,l);return Np([0,i],[0,a])(c)}function Np(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 Ap(e,t){return e>0&&e<t}var aC=(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 Us(e,t){const n=jt(e),r=y.useRef(0);return y.useEffect(()=>()=>window.clearTimeout(r.current),[]),y.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function Nr(e,t){const n=jt(t);_t(()=>{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 _p=yp,lC=bp,cC=kp;const jp=y.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(_p,{ref:r,className:te("relative overflow-hidden",e),...n,children:[u.jsx(lC,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),u.jsx(Rp,{}),u.jsx(cC,{})]}));jp.displayName=_p.displayName;const Rp=y.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(Da,{ref:r,orientation:t,className:te("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:u.jsx(Tp,{className:"relative flex-1 rounded-full bg-border"})}));Rp.displayName=Da.displayName;const Pp=25;function Fa({className:e="",showCreateButton:t=!0,showDeleteButton:n=!0,showEditTitle:r=!0,maxHeight:o="400px",customStyles:s={},currentThreadId:i=null,navigateToThread:a,onThreadSelect:l,onThreadCreate:c,onThreadDelete:d}){const{threads:f,currentThreadId:p,setCurrentThreadId:h,isLoading:x,actions:m}=Ro(),{loadThread:v}=Po(),{createThread:g,deleteThread:b,renameThread:S}=m,[k,C]=w.useState(Array.isArray(f)?f:[]),T=w.useRef(k.length>0),E=w.useRef(null),N=w.useRef(0),[_,P]=w.useState(null),[R,D]=w.useState(""),[F,A]=w.useState(!1);w.useEffect(()=>{const G=Array.isArray(f)?f:[];if(G.length>0){T.current=!0,C(G);return}x||(T.current=!1,C(G))},[f,x]),w.useEffect(()=>{if(!E.current)return;const G=E.current.querySelector("[data-radix-scroll-area-viewport]");if(!G)return;let U=null,q=null;return U=requestAnimationFrame(()=>{q=requestAnimationFrame(()=>{G.scrollTop=N.current})}),()=>{U!==null&&cancelAnimationFrame(U),q!==null&&cancelAnimationFrame(q)}},[k]);const z=async G=>{try{h(G),await v(G),a==null||a(G),l==null||l(G)}catch(U){console.error("Failed to select thread:",U)}},j=async()=>{try{A(!0);const G=await g();G&&(c==null||c(G),a==null||a(G))}catch(G){console.error("Failed to create thread:",G)}finally{A(!1)}},J=async(G,U)=>{if(U.stopPropagation(),!!confirm("Delete this thread?")){if(E.current){const q=E.current.querySelector("[data-radix-scroll-area-viewport]");q&&(N.current=q.scrollTop)}try{await b(G),d==null||d(G)}catch(q){console.error("Failed to delete thread:",q)}}},B=(G,U)=>{U.stopPropagation(),P(G.threadId),D(G.title||`Thread ${G.threadId.slice(0,8)}`)},O=async G=>{if(R.trim())try{await S(G,R.trim()),P(null),D("")}catch(U){console.error("Failed to update title:",U)}},W=()=>{P(null),D("")},X=(G,U)=>{G.key==="Enter"?O(U):G.key==="Escape"&&W()},he=G=>{if(!G)return"";try{const U=new Date(G),$=new Date().getTime()-U.getTime(),V=Math.floor($/(1e3*60*60*24));return V===0?U.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):V===1?"Yesterday":V<7?`${V} days ago`:U.toLocaleDateString()}catch{return""}},ae=G=>G.title||`Thread ${G.threadId.slice(0,8)}`,Re=G=>{const U=ae(G);return U.length<=Pp?U:`${U.slice(0,Pp)}...`};return u.jsxs("div",{className:`flex flex-col h-full ${e} ${s.container||""}`,children:[t&&u.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:u.jsx(st,{onClick:j,disabled:F||x,className:s.createButton||"p-2",size:"sm",variant:"ghost",title:F?"Creating...":"New Chat",children:u.jsx(ie.MessageSquarePlus,{size:20})})}),u.jsx(jp,{ref:E,className:`flex-1 min-h-0 ${s.threadList||""}`,style:o?{maxHeight:o}:void 0,children:u.jsx("div",{className:"p-2 space-y-1 pb-4",children:x?u.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[u.jsx(ie.Loader2,{className:"h-5 w-5 animate-spin"}),u.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):k.length===0?u.jsxs("div",{className:"text-center py-8 text-slate-400",children:[u.jsx(ie.MessageSquare,{className:"w-8 h-8 mx-auto mb-2 opacity-40 text-slate-500"}),u.jsx("p",{className:"text-sm text-slate-500",children:"No conversations yet"})]}):k.slice().sort((G,U)=>new Date(U.updatedAt||U.createdAt||"").getTime()-new Date(G.updatedAt||G.createdAt||"").getTime()).map(G=>u.jsxs("div",{onClick:()=>z(G.threadId),className:`group relative p-3 rounded-lg cursor-pointer transition-colors border ${(i??p)===G.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:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("div",{className:"flex-1 min-w-0",children:_===G.threadId?u.jsxs("div",{className:"flex items-center gap-2",onClick:U=>U.stopPropagation(),children:[u.jsx($s,{value:R,onChange:U=>D(U.target.value),onKeyDown:U=>X(U,G.threadId),className:"h-6 text-sm",autoFocus:!0}),u.jsx(st,{variant:"ghost",size:"sm",onClick:()=>O(G.threadId),className:"h-6 w-6 p-0",children:u.jsx(ie.Check,{size:12})}),u.jsx(st,{variant:"ghost",size:"sm",onClick:W,className:"h-6 w-6 p-0",children:u.jsx(ie.X,{size:12})})]}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"font-medium text-sm truncate text-gray-900 dark:text-slate-100",children:Re(G)}),u.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mt-1",children:[u.jsx(ie.Calendar,{size:10}),u.jsx("span",{children:he(G.updatedAt||G.createdAt)})]})]})}),u.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2",children:[r&&_!==G.threadId&&u.jsx(st,{variant:"ghost",size:"sm",onClick:U=>B(G,U),className:"h-6 w-6 p-0",title:"Edit title",children:u.jsx(ie.Edit3,{size:12})}),n&&u.jsx(st,{variant:"ghost",size:"sm",onClick:U=>J(G.threadId,U),className:"h-6 w-6 p-0 text-red-400 hover:text-red-300 hover:bg-red-900/20",title:"Delete thread",children:u.jsx(ie.Trash2,{size:12})})]})]}),i===G.threadId&&u.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-blue-400 rounded-r"})]},G.threadId))})})]})}function Ar(e){if(!(typeof globalThis>"u"))return globalThis[e]}function uC(e){if(typeof e!="string")return;const t=e.trim();if(t)return Tn(t)}function Op(){const e=[Ar("__API_BASE_URL__"),Ar("__CHAT_API_BASE_URL__"),Ar("__CHAT_API_URL__")];for(const t of e){const n=uC(t);if(n)return n}}function Mp(){const e=[Ar("__API_AUTH_TOKEN__"),Ar("__CHAT_API_KEY__"),Ar("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function Dp(...e){for(const t of e)if(typeof t=="string"&&t.trim())return Tn(t);return Tn()}function Lp(){const e={},t=Op(),n=Mp();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function $p(){const e=Lp(),t=jn.getAuthToken(),n=Op();return{apiBaseUrl:Dp(e.baseUrl,jn.baseUrl,n),apiKey:t||e.apiKey||Mp()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const Fp="chat-settings";function dC(){try{const e=localStorage.getItem(Fp);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function fC(e){try{const t={...e,apiBaseUrl:Tn(e.apiBaseUrl)};localStorage.setItem(Fp,JSON.stringify(t)),t.apiKey&&jn.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function pC(){const e=$p(),t=dC(),n=jn.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:Dp(jn.baseUrl,r,e.apiBaseUrl)}}function hC(e){jn.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),fC(e)}var mC="Label",zp=y.forwardRef((e,t)=>u.jsx(Oe.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())}}));zp.displayName=mC;var Bp=zp;const gC=mo.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),on=y.forwardRef(({className:e,...t},n)=>u.jsx(Bp,{ref:n,className:te(gC(),e),...t}));on.displayName=Bp.displayName;function Up(e){const t=y.useRef({value:e,previous:e});return y.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Hp=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"}),xC="VisuallyHidden",yC=y.forwardRef((e,t)=>u.jsx(Oe.span,{...e,ref:t,style:{...Hp,...e.style}}));yC.displayName=xC;var vC=[" ","Enter","ArrowUp","ArrowDown"],bC=[" ","Enter"],ar="Select",[Hs,Ws,wC]=yi(ar),[_r,zT]=kn(ar,[wC,Go]),Vs=Go(),[SC,Bn]=_r(ar),[CC,TC]=_r(ar),Wp=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:s,value:i,defaultValue:a,onValueChange:l,dir:c,name:d,autoComplete:f,disabled:p,required:h,form:x}=e,m=Vs(t),[v,g]=y.useState(null),[b,S]=y.useState(null),[k,C]=y.useState(!1),T=Mo(c),[E,N]=gr({prop:r,defaultProp:o??!1,onChange:s,caller:ar}),[_,P]=gr({prop:i,defaultProp:a,onChange:l,caller:ar}),R=y.useRef(null),D=v?x||!!v.closest("form"):!0,[F,A]=y.useState(new Set),z=Array.from(F).map(j=>j.props.value).join(";");return u.jsx(iu,{...m,children:u.jsxs(SC,{required:h,scope:t,trigger:v,onTriggerChange:g,valueNode:b,onValueNodeChange:S,valueNodeHasChildren:k,onValueNodeHasChildrenChange:C,contentId:En(),value:_,onValueChange:P,open:E,onOpenChange:N,dir:T,triggerPointerDownPosRef:R,disabled:p,children:[u.jsx(Hs.Provider,{scope:t,children:u.jsx(CC,{scope:e.__scopeSelect,onNativeOptionAdd:y.useCallback(j=>{A(J=>new Set(J).add(j))},[]),onNativeOptionRemove:y.useCallback(j=>{A(J=>{const B=new Set(J);return B.delete(j),B})},[]),children:n})}),D?u.jsxs(hh,{"aria-hidden":!0,required:h,tabIndex:-1,name:d,autoComplete:f,value:_,onChange:j=>P(j.target.value),disabled:p,form:x,children:[_===void 0?u.jsx("option",{value:""}):null,Array.from(F)]},z):null]})})};Wp.displayName=ar;var Vp="SelectTrigger",Kp=y.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=Vs(n),i=Bn(Vp,n),a=i.disabled||r,l=Ge(t,i.onTriggerChange),c=Ws(n),d=y.useRef("touch"),[f,p,h]=gh(m=>{const v=c().filter(S=>!S.disabled),g=v.find(S=>S.value===i.value),b=xh(v,m,g);b!==void 0&&i.onValueChange(b.value)}),x=m=>{a||(i.onOpenChange(!0),h()),m&&(i.triggerPointerDownPosRef.current={x:Math.round(m.pageX),y:Math.round(m.pageY)})};return u.jsx(au,{asChild:!0,...s,children:u.jsx(Oe.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":mh(i.value)?"":void 0,...o,ref:l,onClick:me(o.onClick,m=>{m.currentTarget.focus(),d.current!=="mouse"&&x(m)}),onPointerDown:me(o.onPointerDown,m=>{d.current=m.pointerType;const v=m.target;v.hasPointerCapture(m.pointerId)&&v.releasePointerCapture(m.pointerId),m.button===0&&m.ctrlKey===!1&&m.pointerType==="mouse"&&(x(m),m.preventDefault())}),onKeyDown:me(o.onKeyDown,m=>{const v=f.current!=="";!(m.ctrlKey||m.altKey||m.metaKey)&&m.key.length===1&&p(m.key),!(v&&m.key===" ")&&vC.includes(m.key)&&(x(),m.preventDefault())})})})});Kp.displayName=Vp;var qp="SelectValue",Gp=y.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=Bn(qp,n),{onValueNodeHasChildrenChange:c}=l,d=s!==void 0,f=Ge(t,l.onValueNodeChange);return _t(()=>{c(d)},[c,d]),u.jsx(Oe.span,{...a,ref:f,style:{pointerEvents:"none"},children:mh(l.value)?u.jsx(u.Fragment,{children:i}):s})});Gp.displayName=qp;var kC="SelectIcon",Yp=y.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return u.jsx(Oe.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});Yp.displayName=kC;var EC="SelectPortal",Xp=e=>u.jsx(Yo,{asChild:!0,...e});Xp.displayName=EC;var lr="SelectContent",Jp=y.forwardRef((e,t)=>{const n=Bn(lr,e.__scopeSelect),[r,o]=y.useState();if(_t(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?go.createPortal(u.jsx(Zp,{scope:e.__scopeSelect,children:u.jsx(Hs.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),s):null}return u.jsx(Qp,{...e,ref:t})});Jp.displayName=lr;var pn=10,[Zp,Un]=_r(lr),IC="SelectContentImpl",NC=qn.createSlot("SelectContent.RemoveScroll"),Qp=y.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:s,onPointerDownOutside:i,side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:p,collisionPadding:h,sticky:x,hideWhenDetached:m,avoidCollisions:v,...g}=e,b=Bn(lr,n),[S,k]=y.useState(null),[C,T]=y.useState(null),E=Ge(t,q=>k(q)),[N,_]=y.useState(null),[P,R]=y.useState(null),D=Ws(n),[F,A]=y.useState(!1),z=y.useRef(!1);y.useEffect(()=>{if(S)return zi(S)},[S]),wi();const j=y.useCallback(q=>{const[$,...V]=D().map(se=>se.ref.current),[re]=V.slice(-1),oe=document.activeElement;for(const se of q)if(se===oe||(se==null||se.scrollIntoView({block:"nearest"}),se===$&&C&&(C.scrollTop=0),se===re&&C&&(C.scrollTop=C.scrollHeight),se==null||se.focus(),document.activeElement!==oe))return},[D,C]),J=y.useCallback(()=>j([N,S]),[j,N,S]);y.useEffect(()=>{F&&J()},[F,J]);const{onOpenChange:B,triggerPointerDownPosRef:O}=b;y.useEffect(()=>{if(S){let q={x:0,y:0};const $=re=>{var oe,se;q={x:Math.abs(Math.round(re.pageX)-(((oe=O.current)==null?void 0:oe.x)??0)),y:Math.abs(Math.round(re.pageY)-(((se=O.current)==null?void 0:se.y)??0))}},V=re=>{q.x<=10&&q.y<=10?re.preventDefault():S.contains(re.target)||B(!1),document.removeEventListener("pointermove",$),O.current=null};return O.current!==null&&(document.addEventListener("pointermove",$),document.addEventListener("pointerup",V,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",$),document.removeEventListener("pointerup",V,{capture:!0})}}},[S,B,O]),y.useEffect(()=>{const q=()=>B(!1);return window.addEventListener("blur",q),window.addEventListener("resize",q),()=>{window.removeEventListener("blur",q),window.removeEventListener("resize",q)}},[B]);const[W,X]=gh(q=>{const $=D().filter(oe=>!oe.disabled),V=$.find(oe=>oe.ref.current===document.activeElement),re=xh($,q,V);re&&setTimeout(()=>re.ref.current.focus())}),he=y.useCallback((q,$,V)=>{const re=!z.current&&!V;(b.value!==void 0&&b.value===$||re)&&(_(q),re&&(z.current=!0))},[b.value]),ae=y.useCallback(()=>S==null?void 0:S.focus(),[S]),Re=y.useCallback((q,$,V)=>{const re=!z.current&&!V;(b.value!==void 0&&b.value===$||re)&&R(q)},[b.value]),G=r==="popper"?za:eh,U=G===za?{side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:p,collisionPadding:h,sticky:x,hideWhenDetached:m,avoidCollisions:v}:{};return u.jsx(Zp,{scope:n,content:S,viewport:C,onViewportChange:T,itemRefCallback:he,selectedItem:N,onItemLeave:ae,itemTextRefCallback:Re,focusSelectedItem:J,selectedItemText:P,position:r,isPositioned:F,searchRef:W,children:u.jsx(os,{as:NC,allowPinchZoom:!0,children:u.jsx(Lo,{asChild:!0,trapped:b.open,onMountAutoFocus:q=>{q.preventDefault()},onUnmountAutoFocus:me(o,q=>{var $;($=b.trigger)==null||$.focus({preventScroll:!0}),q.preventDefault()}),children:u.jsx(Do,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:q=>q.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:u.jsx(G,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:q=>q.preventDefault(),...g,...U,onPlaced:()=>A(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...g.style},onKeyDown:me(g.onKeyDown,q=>{const $=q.ctrlKey||q.altKey||q.metaKey;if(q.key==="Tab"&&q.preventDefault(),!$&&q.key.length===1&&X(q.key),["ArrowUp","ArrowDown","Home","End"].includes(q.key)){let re=D().filter(oe=>!oe.disabled).map(oe=>oe.ref.current);if(["ArrowUp","End"].includes(q.key)&&(re=re.slice().reverse()),["ArrowUp","ArrowDown"].includes(q.key)){const oe=q.target,se=re.indexOf(oe);re=re.slice(se+1)}setTimeout(()=>j(re)),q.preventDefault()}})})})})})})});Qp.displayName=IC;var AC="SelectItemAlignedPosition",eh=y.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=Bn(lr,n),i=Un(lr,n),[a,l]=y.useState(null),[c,d]=y.useState(null),f=Ge(t,E=>d(E)),p=Ws(n),h=y.useRef(!1),x=y.useRef(!0),{viewport:m,selectedItem:v,selectedItemText:g,focusSelectedItem:b}=i,S=y.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&c&&m&&v&&g){const E=s.trigger.getBoundingClientRect(),N=c.getBoundingClientRect(),_=s.valueNode.getBoundingClientRect(),P=g.getBoundingClientRect();if(s.dir!=="rtl"){const oe=P.left-N.left,se=_.left-oe,Se=E.left-se,Qe=E.width+Se,Fe=Math.max(Qe,N.width),Xe=window.innerWidth-pn,nt=Oa(se,[pn,Math.max(pn,Xe-Fe)]);a.style.minWidth=Qe+"px",a.style.left=nt+"px"}else{const oe=N.right-P.right,se=window.innerWidth-_.right-oe,Se=window.innerWidth-E.right-se,Qe=E.width+Se,Fe=Math.max(Qe,N.width),Xe=window.innerWidth-pn,nt=Oa(se,[pn,Math.max(pn,Xe-Fe)]);a.style.minWidth=Qe+"px",a.style.right=nt+"px"}const R=p(),D=window.innerHeight-pn*2,F=m.scrollHeight,A=window.getComputedStyle(c),z=parseInt(A.borderTopWidth,10),j=parseInt(A.paddingTop,10),J=parseInt(A.borderBottomWidth,10),B=parseInt(A.paddingBottom,10),O=z+j+F+B+J,W=Math.min(v.offsetHeight*5,O),X=window.getComputedStyle(m),he=parseInt(X.paddingTop,10),ae=parseInt(X.paddingBottom,10),Re=E.top+E.height/2-pn,G=D-Re,U=v.offsetHeight/2,q=v.offsetTop+U,$=z+j+q,V=O-$;if($<=Re){const oe=R.length>0&&v===R[R.length-1].ref.current;a.style.bottom="0px";const se=c.clientHeight-m.offsetTop-m.offsetHeight,Se=Math.max(G,U+(oe?ae:0)+se+J),Qe=$+Se;a.style.height=Qe+"px"}else{const oe=R.length>0&&v===R[0].ref.current;a.style.top="0px";const Se=Math.max(Re,z+m.offsetTop+(oe?he:0)+U)+V;a.style.height=Se+"px",m.scrollTop=$-Re+m.offsetTop}a.style.margin=`${pn}px 0`,a.style.minHeight=W+"px",a.style.maxHeight=D+"px",r==null||r(),requestAnimationFrame(()=>h.current=!0)}},[p,s.trigger,s.valueNode,a,c,m,v,g,s.dir,r]);_t(()=>S(),[S]);const[k,C]=y.useState();_t(()=>{c&&C(window.getComputedStyle(c).zIndex)},[c]);const T=y.useCallback(E=>{E&&x.current===!0&&(S(),b==null||b(),x.current=!1)},[S,b]);return u.jsx(jC,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:h,onScrollButtonChange:T,children:u.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k},children:u.jsx(Oe.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});eh.displayName=AC;var _C="SelectPopperPosition",za=y.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=pn,...s}=e,i=Vs(n);return u.jsx(lu,{...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)"}})});za.displayName=_C;var[jC,Ba]=_r(lr,{}),Ua="SelectViewport",th=y.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=Un(Ua,n),i=Ba(Ua,n),a=Ge(t,s.onViewportChange),l=y.useRef(0);return u.jsxs(u.Fragment,{children:[u.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}),u.jsx(Hs.Slot,{scope:n,children:u.jsx(Oe.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:me(o.onScroll,c=>{const d=c.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:p}=i;if(p!=null&&p.current&&f){const h=Math.abs(l.current-d.scrollTop);if(h>0){const x=window.innerHeight-pn*2,m=parseFloat(f.style.minHeight),v=parseFloat(f.style.height),g=Math.max(m,v);if(g<x){const b=g+h,S=Math.min(x,b),k=b-S;f.style.height=S+"px",f.style.bottom==="0px"&&(d.scrollTop=k>0?k:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});th.displayName=Ua;var nh="SelectGroup",[RC,PC]=_r(nh),OC=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=En();return u.jsx(RC,{scope:n,id:o,children:u.jsx(Oe.div,{role:"group","aria-labelledby":o,...r,ref:t})})});OC.displayName=nh;var rh="SelectLabel",oh=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=PC(rh,n);return u.jsx(Oe.div,{id:o.id,...r,ref:t})});oh.displayName=rh;var Ks="SelectItem",[MC,sh]=_r(Ks),ih=y.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=Bn(Ks,n),l=Un(Ks,n),c=a.value===r,[d,f]=y.useState(s??""),[p,h]=y.useState(!1),x=Ge(t,b=>{var S;return(S=l.itemRefCallback)==null?void 0:S.call(l,b,r,o)}),m=En(),v=y.useRef("touch"),g=()=>{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 u.jsx(MC,{scope:n,value:r,disabled:o,textId:m,isSelected:c,onItemTextChange:y.useCallback(b=>{f(S=>S||((b==null?void 0:b.textContent)??"").trim())},[]),children:u.jsx(Hs.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:u.jsx(Oe.div,{role:"option","aria-labelledby":m,"data-highlighted":p?"":void 0,"aria-selected":c&&p,"data-state":c?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:x,onFocus:me(i.onFocus,()=>h(!0)),onBlur:me(i.onBlur,()=>h(!1)),onClick:me(i.onClick,()=>{v.current!=="mouse"&&g()}),onPointerUp:me(i.onPointerUp,()=>{v.current==="mouse"&&g()}),onPointerDown:me(i.onPointerDown,b=>{v.current=b.pointerType}),onPointerMove:me(i.onPointerMove,b=>{var S;v.current=b.pointerType,o?(S=l.onItemLeave)==null||S.call(l):v.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:me(i.onPointerLeave,b=>{var S;b.currentTarget===document.activeElement&&((S=l.onItemLeave)==null||S.call(l))}),onKeyDown:me(i.onKeyDown,b=>{var k;((k=l.searchRef)==null?void 0:k.current)!==""&&b.key===" "||(bC.includes(b.key)&&g(),b.key===" "&&b.preventDefault())})})})})});ih.displayName=Ks;var ho="SelectItemText",ah=y.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=Bn(ho,n),a=Un(ho,n),l=sh(ho,n),c=TC(ho,n),[d,f]=y.useState(null),p=Ge(t,g=>f(g),l.onItemTextChange,g=>{var b;return(b=a.itemTextRefCallback)==null?void 0:b.call(a,g,l.value,l.disabled)}),h=d==null?void 0:d.textContent,x=y.useMemo(()=>u.jsx("option",{value:l.value,disabled:l.disabled,children:h},l.value),[l.disabled,l.value,h]),{onNativeOptionAdd:m,onNativeOptionRemove:v}=c;return _t(()=>(m(x),()=>v(x)),[m,v,x]),u.jsxs(u.Fragment,{children:[u.jsx(Oe.span,{id:l.textId,...s,ref:p}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?go.createPortal(s.children,i.valueNode):null]})});ah.displayName=ho;var lh="SelectItemIndicator",ch=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return sh(lh,n).isSelected?u.jsx(Oe.span,{"aria-hidden":!0,...r,ref:t}):null});ch.displayName=lh;var Ha="SelectScrollUpButton",uh=y.forwardRef((e,t)=>{const n=Un(Ha,e.__scopeSelect),r=Ba(Ha,e.__scopeSelect),[o,s]=y.useState(!1),i=Ge(t,r.onScrollButtonChange);return _t(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollTop>0;s(c)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(fh,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});uh.displayName=Ha;var Wa="SelectScrollDownButton",dh=y.forwardRef((e,t)=>{const n=Un(Wa,e.__scopeSelect),r=Ba(Wa,e.__scopeSelect),[o,s]=y.useState(!1),i=Ge(t,r.onScrollButtonChange);return _t(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollHeight-l.clientHeight,d=Math.ceil(l.scrollTop)<c;s(d)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(fh,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});dh.displayName=Wa;var fh=y.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=Un("SelectScrollButton",n),i=y.useRef(null),a=Ws(n),l=y.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return y.useEffect(()=>()=>l(),[l]),_t(()=>{var d;const c=a().find(f=>f.ref.current===document.activeElement);(d=c==null?void 0:c.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),u.jsx(Oe.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:me(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:me(o.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:me(o.onPointerLeave,()=>{l()})})}),DC="SelectSeparator",ph=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(Oe.div,{"aria-hidden":!0,...r,ref:t})});ph.displayName=DC;var Va="SelectArrow",LC=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Vs(n),s=Bn(Va,n),i=Un(Va,n);return s.open&&i.position==="popper"?u.jsx(cu,{...o,...r,ref:t}):null});LC.displayName=Va;var $C="SelectBubbleInput",hh=y.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=y.useRef(null),s=Ge(r,o),i=Up(t);return y.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]),u.jsx(Oe.select,{...n,style:{...Hp,...n.style},ref:s,defaultValue:t})});hh.displayName=$C;function mh(e){return e===""||e===void 0}function gh(e){const t=jt(e),n=y.useRef(""),r=y.useRef(0),o=y.useCallback(i=>{const a=n.current+i;t(a),function l(c){n.current=c,window.clearTimeout(r.current),c!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}(a)},[t]),s=y.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return y.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,s]}function xh(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=FC(e,Math.max(s,0));o.length===1&&(i=i.filter(c=>c!==n));const l=i.find(c=>c.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function FC(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var zC=Wp,yh=Kp,BC=Gp,UC=Yp,HC=Xp,vh=Jp,WC=th,bh=oh,wh=ih,VC=ah,KC=ch,Sh=uh,Ch=dh,Th=ph;const kh=zC,Eh=BC,Ka=y.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(yh,{ref:r,className:te("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,u.jsx(UC,{asChild:!0,children:u.jsx(ie.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Ka.displayName=yh.displayName;const Ih=y.forwardRef(({className:e,...t},n)=>u.jsx(Sh,{ref:n,className:te("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(ie.ChevronUp,{className:"h-4 w-4"})}));Ih.displayName=Sh.displayName;const Nh=y.forwardRef(({className:e,...t},n)=>u.jsx(Ch,{ref:n,className:te("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(ie.ChevronDown,{className:"h-4 w-4"})}));Nh.displayName=Ch.displayName;const qa=y.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>u.jsx(HC,{children:u.jsxs(vh,{ref:o,className:te("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:[u.jsx(Ih,{}),u.jsx(WC,{className:te("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(Nh,{})]})}));qa.displayName=vh.displayName;const qC=y.forwardRef(({className:e,...t},n)=>u.jsx(bh,{ref:n,className:te("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));qC.displayName=bh.displayName;const cr=y.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(wh,{ref:r,className:te("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:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(KC,{children:u.jsx(ie.Check,{className:"h-4 w-4"})})}),u.jsx(VC,{children:t})]}));cr.displayName=wh.displayName;const GC=y.forwardRef(({className:e,...t},n)=>u.jsx(Th,{ref:n,className:te("-mx-1 my-1 h-px bg-muted",e),...t}));GC.displayName=Th.displayName;var YC="Separator",Ah="horizontal",XC=["horizontal","vertical"],_h=y.forwardRef((e,t)=>{const{decorative:n,orientation:r=Ah,...o}=e,s=JC(r)?r:Ah,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return u.jsx(Oe.div,{"data-orientation":s,...a,...o,ref:t})});_h.displayName=YC;function JC(e){return XC.includes(e)}var jh=_h;const Rh=y.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>u.jsx(jh,{ref:o,decorative:n,orientation:t,className:te("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Rh.displayName=jh.displayName;const ZC=Kf,QC=mS,eT=qf,Ph=y.forwardRef(({className:e,...t},n)=>u.jsx(As,{className:te("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}));Ph.displayName=As.displayName;const tT=mo.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"}}),Oh=y.forwardRef(({side:e="right",className:t,children:n,...r},o)=>u.jsxs(eT,{children:[u.jsx(Ph,{}),u.jsxs(_s,{ref:o,className:te(tT({side:e}),t),...r,children:[n,u.jsxs(Gf,{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:[u.jsx(ie.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Oh.displayName=_s.displayName;const Mh=({className:e,...t})=>u.jsx("div",{className:te("flex flex-col space-y-2 text-center sm:text-left",e),...t});Mh.displayName="SheetHeader";const Dh=y.forwardRef(({className:e,...t},n)=>u.jsx(sr,{ref:n,className:te("text-lg font-semibold text-foreground",e),...t}));Dh.displayName=sr.displayName;const Lh=y.forwardRef(({className:e,...t},n)=>u.jsx(js,{ref:n,className:te("text-sm text-muted-foreground",e),...t}));Lh.displayName=js.displayName;var qs="Switch",[nT,BT]=kn(qs),[rT,oT]=nT(qs),$h=y.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:s,required:i,disabled:a,value:l="on",onCheckedChange:c,form:d,...f}=e,[p,h]=y.useState(null),x=Ge(t,S=>h(S)),m=y.useRef(!1),v=p?d||!!p.closest("form"):!0,[g,b]=gr({prop:o,defaultProp:s??!1,onChange:c,caller:qs});return u.jsxs(rT,{scope:n,checked:g,disabled:a,children:[u.jsx(Oe.button,{type:"button",role:"switch","aria-checked":g,"aria-required":i,"data-state":Uh(g),"data-disabled":a?"":void 0,disabled:a,value:l,...f,ref:x,onClick:me(e.onClick,S=>{b(k=>!k),v&&(m.current=S.isPropagationStopped(),m.current||S.stopPropagation())})}),v&&u.jsx(Bh,{control:p,bubbles:!m.current,name:r,value:l,checked:g,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});$h.displayName=qs;var Fh="SwitchThumb",zh=y.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=oT(Fh,n);return u.jsx(Oe.span,{"data-state":Uh(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});zh.displayName=Fh;var sT="SwitchBubbleInput",Bh=y.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=y.useRef(null),a=Ge(i,s),l=Up(n),c=Xc(t);return y.useEffect(()=>{const d=i.current;if(!d)return;const f=window.HTMLInputElement.prototype,h=Object.getOwnPropertyDescriptor(f,"checked").set;if(l!==n&&h){const x=new Event("click",{bubbles:r});h.call(d,n),d.dispatchEvent(x)}},[l,n,r]),u.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...o,tabIndex:-1,ref:a,style:{...o.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Bh.displayName=sT;function Uh(e){return e?"checked":"unchecked"}var Hh=$h,iT=zh;const Hn=y.forwardRef(({className:e,...t},n)=>u.jsx(Hh,{className:te("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:u.jsx(iT,{className:te("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")})}));Hn.displayName=Hh.displayName;const aT={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 lT({settings:e,onSettingsChange:t,className:n=""}){const[r,o]=w.useState(!1),[s,i]=w.useState(!1),[a,l]=w.useState(e),[c,d]=w.useState(!1),{toast:f}=ka();w.useEffect(()=>{const v=JSON.stringify(a)!==JSON.stringify(e);d(v)},[a,e]),w.useEffect(()=>{l(e)},[e]);const p=()=>{t(a),d(!1),f({title:"Settings saved",description:"Your chat configuration has been updated successfully."})},h=()=>{l(aT),d(!0),f({title:"Settings reset",description:"Configuration has been reset to defaults."})},x=()=>{l(e),d(!1),o(!1)},m=async()=>{try{const g=await(await fetch(`${a.api.baseUrl}/health`)).json();f({title:"Connection successful",description:`API is ${g.status||"healthy"}`})}catch{f({title:"Connection failed",description:"Unable to connect to the API endpoint.",variant:"destructive"})}};return u.jsxs(ZC,{open:r,onOpenChange:o,children:[u.jsx(QC,{asChild:!0,children:u.jsxs(st,{variant:"outline",size:"sm",className:n,children:[u.jsx(ie.Settings,{className:"h-4 w-4 mr-2"}),"Settings",c&&u.jsx(Cf,{variant:"destructive",className:"ml-2 h-4 w-4 p-0"})]})}),u.jsxs(Oh,{className:"w-[500px] sm:w-[600px] overflow-y-auto",children:[u.jsxs(Mh,{children:[u.jsx(Dh,{children:"Chat Settings"}),u.jsx(Lh,{children:"Configure your chat interface, API connection, and behavior preferences."})]}),u.jsxs("div",{className:"space-y-6 py-6",children:[u.jsxs(so,{children:[u.jsx(io,{className:"pb-3",children:u.jsxs(ao,{className:"text-lg flex items-center gap-2",children:[u.jsx(ie.Server,{className:"h-5 w-5"}),"API Configuration"]})}),u.jsxs(lo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(on,{htmlFor:"api-url",children:"API Base URL"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx($s,{id:"api-url",value:a.api.baseUrl,onChange:v=>l(g=>({...g,api:{...g.api,baseUrl:v.target.value}})),placeholder:"http://localhost:8000/api"}),u.jsx(st,{variant:"outline",onClick:m,children:"Test"})]})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(on,{htmlFor:"enable-auth",children:"Enable Authentication"}),u.jsx(Hn,{id:"enable-auth",checked:a.api.enableAuth,onCheckedChange:v=>l(g=>({...g,api:{...g.api,enableAuth:v}}))})]}),a.api.enableAuth&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(on,{htmlFor:"auth-token",children:"Authentication Token"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx($s,{id:"auth-token",type:s?"text":"password",value:a.api.authToken,onChange:v=>l(g=>({...g,api:{...g.api,authToken:v.target.value}})),placeholder:"Enter your Bearer token"}),u.jsx(st,{variant:"outline",size:"icon",onClick:()=>i(!s),children:s?u.jsx(ie.EyeOff,{className:"h-4 w-4"}):u.jsx(ie.Eye,{className:"h-4 w-4"})})]})]})]})]}),u.jsxs(so,{children:[u.jsx(io,{className:"pb-3",children:u.jsxs(ao,{className:"text-lg flex items-center gap-2",children:[u.jsx(ie.Layout,{className:"h-5 w-5"}),"Interface Settings"]})}),u.jsxs(lo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(on,{htmlFor:"layout",children:"Layout Style"}),u.jsxs(kh,{value:a.ui.layout,onValueChange:v=>l(g=>({...g,ui:{...g.ui,layout:v}})),children:[u.jsx(Ka,{children:u.jsx(Eh,{})}),u.jsxs(qa,{children:[u.jsx(cr,{value:"sidebar",children:"Sidebar Layout"}),u.jsx(cr,{value:"fullscreen",children:"Fullscreen"}),u.jsx(cr,{value:"tabs",children:"Tabbed Interface"})]})]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(on,{htmlFor:"theme",children:"Theme"}),u.jsxs(kh,{value:a.ui.theme,onValueChange:v=>l(g=>({...g,ui:{...g.ui,theme:v}})),children:[u.jsx(Ka,{children:u.jsx(Eh,{})}),u.jsxs(qa,{children:[u.jsx(cr,{value:"light",children:"Light"}),u.jsx(cr,{value:"dark",children:"Dark"}),u.jsx(cr,{value:"system",children:"System"})]})]})]}),u.jsx(Rh,{}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(on,{htmlFor:"show-timestamps",children:"Show Timestamps"}),u.jsx(Hn,{id:"show-timestamps",checked:a.ui.showTimestamps,onCheckedChange:v=>l(g=>({...g,ui:{...g.ui,showTimestamps:v}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(on,{htmlFor:"show-agent-names",children:"Show Agent Names"}),u.jsx(Hn,{id:"show-agent-names",checked:a.ui.showAgentNames,onCheckedChange:v=>l(g=>({...g,ui:{...g.ui,showAgentNames:v}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(on,{htmlFor:"compact-messages",children:"Compact Messages"}),u.jsx(Hn,{id:"compact-messages",checked:a.ui.compactMessages,onCheckedChange:v=>l(g=>({...g,ui:{...g.ui,compactMessages:v}}))})]})]})]})]}),u.jsxs(so,{children:[u.jsx(io,{className:"pb-3",children:u.jsxs(ao,{className:"text-lg flex items-center gap-2",children:[u.jsx(ie.MessageCircle,{className:"h-5 w-5"}),"Behavior Settings"]})}),u.jsxs(lo,{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(on,{htmlFor:"auto-save",children:"Auto-save Conversations"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically save messages to threads"})]}),u.jsx(Hn,{id:"auto-save",checked:a.behavior.autoSave,onCheckedChange:v=>l(g=>({...g,behavior:{...g.behavior,autoSave:v}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(on,{htmlFor:"enable-streaming",children:"Enable Streaming"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Stream responses in real-time"})]}),u.jsx(Hn,{id:"enable-streaming",checked:a.behavior.enableStreaming,onCheckedChange:v=>l(g=>({...g,behavior:{...g.behavior,enableStreaming:v}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(on,{htmlFor:"typing-indicator",children:"Typing Indicator"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Show typing indicator during responses"})]}),u.jsx(Hn,{id:"typing-indicator",checked:a.behavior.showTypingIndicator,onCheckedChange:v=>l(g=>({...g,behavior:{...g.behavior,showTypingIndicator:v}}))})]})]})]})]}),u.jsxs("div",{className:"flex items-center justify-between pt-6 border-t",children:[u.jsxs(st,{variant:"outline",onClick:h,children:[u.jsx(ie.RotateCcw,{className:"h-4 w-4 mr-2"}),"Reset"]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(st,{variant:"outline",onClick:x,children:"Cancel"}),u.jsxs(st,{onClick:p,disabled:!c,children:[u.jsx(ie.Save,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})]})}function cT({layout:e="sidebar",layoutSize:t="desktop",showThreads:n=!0,className:r="",customStyles:o={},...s}){const i=c=>{const d="h-full";switch(c){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=c=>({"--chat-sidebar-width":c==="phone"?"100%":c==="tablet"?"280px":c==="half-screen"?"240px":"320px","--chat-message-max-width":c==="phone"?"95%":c==="tablet"?"90%":c==="half-screen"?"85%":"80%","--chat-input-height":c==="phone"?"120px":"100px"}),l=w.useCallback(c=>{var d;(d=s.onThreadChange)==null||d.call(s,c)},[s]);return e==="fullscreen"?u.jsx(Oo,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsx(Ls,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?u.jsx(Oo,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsxs("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:[n&&u.jsx("div",{className:`w-80 border-r flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(Fa,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx(Ls,{onError:s.onError,enableFileUpload:!0})})]})})}):u.jsx(Oo,{...s,onThreadChange:l,children:u.jsxs("div",{className:`${i(t)} flex overflow-hidden ${r} ${o.container||""}`,style:a(t),children:[n&&u.jsx("div",{className:`w-80 border-r bg-gray-50 flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(Fa,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx(Ls,{onError:s.onError,enableFileUpload:!0})})]})})}Ne.ChatApi=Vl,Ne.ChatInput=hc,Ne.ChatInterface=Ls,Ne.ChatProviders=Oo,Ne.ChatSettings=lT,Ne.MarkdownContent=po,Ne.MessageComponent=Ra,Ne.MessageList=Pa,Ne.ThreadManager=Fa,Ne.applySettings=hC,Ne.buildMessagePreviewMap=Zl,Ne.chatApiClient=jn,Ne.default=cT,Ne.del=Wl,Ne.get=Jt,Ne.getChatToken=Bl,Ne.getCurrentSettings=pC,Ne.getDefaultApiConfig=Lp,Ne.getDefaultChatSettings=$p,Ne.onChatTokenChanged=Ul,Ne.post=ui,Ne.put=Hl,Ne.setChatToken=No,Ne.useApi=di,Ne.useChatStream=Ql,Ne.useMessagesReducer=ec,Ne.useStream=fc,Ne.useThreadState=Po,Ne.useThreads=Ro,Object.defineProperties(Ne,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
136
+ `)):r=t(e),r||""}function zS(e){return e.name&&e.name.trim()?e.name:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function pp(e){if("type"in e&&e.type==="default_message")return`default:${e.content.length}`;const t=e.updatedAt??e.createdAt??"",n=Array.isArray(e.content)?e.content.map(r=>{switch(r.type){case"text":return`t:${r.text.length}`;case"image_url":return"img";case"file":return"file";case"tool_call":return"call";case"interrupt":return"interrupt";default:return"unknown"}}).join("|"):"";return`${e.id}:${t}:${n}`}function BS(e){if(!e)return"image/png";const t=e.trim();return t?t.includes("/")?t:`image/${t}`:"image/png"}function US(e){const t=[],n=r=>{r&&r.trim()&&t.push(r.trim())};return e&&(n(e.plotId),n(e.artifactId)),t}function HS({base64:e,url:t,formatHint:n,extras:r}){const o=typeof e=="string"&&e.length>0,s=BS(n),i=o?`data:${s};base64,${e}`:t,a=US(r),l=a.length?a.join(" / "):void 0,c=l?`${l} artifact`:"artifact image";return{src:i,alt:c,label:l}}function WS(e){var s,i;const t=((s=e.content_base64)==null?void 0:s.trim())||void 0,n=((i=e.url)==null?void 0:i.trim())||void 0,r=e.format||e.mimeType||e.mime_type;return HS({base64:t,url:n,formatHint:r,extras:{plotId:e.plotId,artifactId:e.artifactId}})}function VS({className:e}){const[t,n]=w.useState(0);return w.useEffect(()=>{const r=setInterval(()=>n(o=>(o+1)%4),500);return()=>clearInterval(r)},[]),u.jsxs("span",{"aria-live":"polite",className:te("inline-block text-xs opacity-70 ml-1",e),children:["Is thinking",".".repeat(t)]})}const Ra=w.memo(function({message:t,messageIndex:n,isStreamingMessage:r=!1,isEditing:o=!1,showActions:s=!0,showTimestamp:i=!0,showAgentName:a=!0,layoutSize:l="desktop",truncateUserMessages:c=!0,userMessagePreviewLength:d=500,showToolMessages:f=!0,showArtifactPreviews:p=!0,customStyles:h={},onEdit:x,onRegenerate:m,onCancelEdit:v,onCopy:g,activeInterrupt:b,disableInterruptActions:S=!1,onInterruptActionStart:k,onInterruptActionEnd:C,checkpointCandidates:T=[],activeCheckpointId:E=null,onSelectCheckpoint:N,defaultCheckpointId:_=null,messageParentCheckpointId:P=null,attemptMeta:R=null}){const[D,F]=w.useState(!1),[A,z]=w.useState("preview"),[j,J]=w.useState(!1),{currentThreadId:B}=Ro(),{respondToInterrupt:O}=Po(),W=l==="phone"||l==="half-screen",X=t.role,fe=X==="tool",ae=w.useMemo(()=>"type"in t&&t.type==="default_message"?t:null,[t]),Re=!!ae,G=!(r&&X!=="user"),{uploadingFiles:U,handleFileClick:q,fileViewerOpen:$,currentFileInfo:V,closeFileViewer:re}=qS({allowFileOpen:G,currentThreadId:B}),oe=w.useMemo(()=>{switch(X){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-[hsl(var(--chat-bubble-ai-text))]"}},[X]),se=w.useMemo(()=>ae?"":$S(t.content),[ae,t]),Se=w.useMemo(()=>ae?{}:fp(t),[ae,t]),Qe=w.useMemo(()=>ae?[]:t.content.filter(L=>L.type==="image_url"),[ae,t]),Fe=w.useMemo(()=>ae?[]:t.content.filter(L=>L.type==="file"),[ae,t]),Xe=w.useMemo(()=>ae?[]:t.content.filter(L=>L.type==="interrupt"),[ae,t]),nt=(b==null?void 0:b.id)??(b==null?void 0:b.interrupt_id),de=Ds(nt),me=b==null?void 0:b.value,Le=w.useMemo(()=>ae?"":FS(t.content),[ae,t]),Be=w.useMemo(()=>{if(ae||!p)return[];const ne=t.artifact;if(!ne)return[];const ge=[],pe=[...Array.isArray(ne.plots)?ne.plots:[]];for(const et of pe){const ke=WS(et);ke&&ge.push(ke)}return ge},[ae,t,p]),Ve=w.useCallback(async()=>{const L=fe?Le:se;async function ne(ge){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(ge);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const pe=new Blob([ge],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":pe})]);return}throw new Error("Clipboard API not supported in this context.")}try{await ne(L),F(!0),setTimeout(()=>F(!1),2e3),g==null||g(L)}catch(ge){console.error("Failed to copy:",ge)}},[fe,Le,se,g]),Je=w.useCallback(()=>{if(!x)return;const L=fe?Le:se,ne="type"in t&&t.type==="default_message"?void 0:{checkpointId:t.checkpointId??null,checkpointNs:t.checkpointNs??null};x(t.id,L,ne)},[x,t.id,fe,Le,se,t]),ze=w.useCallback(()=>{m==null||m(n)},[m,n]),Ze=w.useCallback(()=>{const ne=te(W?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",oe);switch(X){case"user":return u.jsx(ie.User,{className:ne});case"assistant":return u.jsx(ie.Bot,{className:ne});case"tool":return u.jsx(ie.Wrench,{className:ne});default:return u.jsx(ie.Bot,{className:ne})}},[W,oe,X]),Et=w.useCallback(()=>{const L="group relative mb-4 flex w-full";switch(X){case"user":return te(L,"justify-end");case"assistant":case"tool":case"system":return te(L,"justify-start");default:return L}},[X]),ft=w.useCallback(()=>{const L=te("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",W&&"px-3 py-2 text-sm");if(Re)return te(L,"w-full","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40 shadow-sm");switch(X){case"user":return te(L,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return te(L,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40");case"tool":return te(L,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return te(L,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return te(L,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40")}},[W,Re,X]);if(Re&&ae)return u.jsx("div",{className:te(Et(),h.container),children:u.jsxs("div",{className:te(ft(),h.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(ie.Bot,{className:te("h-4 w-4",oe)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(po,{content:ae.content,className:"text-current"})]})});const Ue=w.useCallback(async L=>{if(S)return;const ne=Ds((L==null?void 0:L.id)??(L==null?void 0:L.interrupt_id));if(!ne){console.warn("Interrupt part missing id",L);return}try{k==null||k(),await O(ne,!0)}catch(ge){console.error("Failed to approve interrupt:",ge)}finally{C==null||C()}},[S,C,k,O]),xt=w.useCallback(async L=>{if(S)return;const ne=Ds((L==null?void 0:L.id)??(L==null?void 0:L.interrupt_id));if(!ne){console.warn("Interrupt part missing id",L);return}try{k==null||k(),await O(ne,!1)}catch(ge){console.error("Failed to reject interrupt:",ge)}finally{C==null||C()}},[S,C,k,O]),vt=w.useCallback(({part:L,i:ne})=>{if(L.type==="text"){const ge=L.text??"",pe=ge.trim(),et=Ea(pe);return et&&X!=="tool"?u.jsx(hp,{data:et},ne):X==="user"&&c&&pe.length>d?u.jsx(GS,{text:pe,expanded:j,onExpandedChange:J,previewLength:d,isCompact:W},ne):u.jsx(po,{content:ge,allowHtml:!1},ne)}if(L.type==="image_url"){const ge=L;return u.jsx("div",{className:"my-2",children:u.jsx("img",{src:ge.url,alt:ge.alt??"",loading:"lazy",className:"border rounded max-h-[420px] w-auto object-contain"})},ne)}if(L.type==="file"){const ge=L,pe=ge.name||"file";return u.jsxs("a",{href:ge.url,onClick:et=>q(et.nativeEvent,ge,ne),className:`inline-flex items-center gap-2 rounded px-2 py-1 text-xs bg-gray-100 border hover:bg-gray-200
137
+ dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[U[ne]?u.jsx(ie.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[pe,U[ne]?" (processing)":""]})]},ne)}if(L.type==="interrupt"){const ge=L,pe=Ds((ge==null?void 0:ge.id)??(ge==null?void 0:ge.interrupt_id)),et=!!(de&&pe&&pe===de),ke=et?me??(ge==null?void 0:ge.value):ge==null?void 0:ge.value,ct=pe?{...ge,id:pe,interrupt_id:pe}:ge;return u.jsx(KS,{interruptPart:ct,onApprove:Ue,onReject:xt,disabled:S,isActive:et,payload:ke},ne)}return null},[q,U,Ue,xt,X,c,d,j,W,de,me,b,S,Xe]),It=w.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(ie.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),bt=w.useCallback(()=>{const L=se.trim().length>0||Qe.length>0||Fe.length>0||Xe.length>0;if(!fe&&Fe.length>0&&!r)return It();if(!fe&&!L&&!r)return null;if(fe)return!f&&Be.length>0?null:f?u.jsx(YS,{message:t,viewMode:A},t.id):null;if(!fe&&!ae){const ne=t,ge=u.jsx("div",{className:"space-y-2",children:ne.content.map((pe,et)=>u.jsx(vt,{part:pe,i:et},et))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[ge,u.jsx(VS,{className:oe})]}):ge}},[se,Qe.length,Fe.length,Xe.length,r,fe,A,f,Be.length,It,oe]),wt=w.useMemo(()=>ae?"Assistant":zS(t),[ae,t]),He=w.useMemo(()=>ae?[]:Array.isArray(T)?T:[],[T,ae]),zt=w.useMemo(()=>{var L;return He.length?_&&He.some(ne=>ne.id===_)?_:((L=He[0])==null?void 0:L.id)??null:null},[_,He]),_e=w.useMemo(()=>!He.length||!E?null:He.some(L=>L.id===E)?E:null,[E,He])??zt,at=X==="user"&&He.length>0&&typeof N=="function",Y=w.useCallback(L=>{if(!N)return;const ne=(L==null?void 0:L.id)??null,ge=(L==null?void 0:L.parentId)??P??null;N(ne,ge)},[P,N]),ee=w.useMemo(()=>_e?He.findIndex(L=>L.id===_e):-1,[_e,He]),Ce=w.useMemo(()=>ee<0?null:He[ee]??null,[ee,He]),Te=w.useCallback(L=>{const ne=[];return L.step!==null&&ne.push(`Step ${L.step}`),L.source&&ne.push(L.source),ne.length?ne.join(" • "):L.id.slice(0,8)},[]);return fe&&!f&&Be.length===0?null:u.jsxs(u.Fragment,{children:[u.jsx("div",{className:te(Et(),h.container),children:u.jsxs("div",{className:te(ft(),h.content),children:[(i||a||fe)&&u.jsxs("div",{className:te("flex items-center justify-between mb-2 pb-2 border-b border-current/10",W&&"mb-1 pb-1",oe,h.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[Ze(),a&&wt&&u.jsx("span",{className:te("font-medium",W?"text-xs":"text-sm"),children:wt}),fe&&u.jsxs(Cf,{variant:"outline",className:te("text-xs flex items-center gap-1 cursor-pointer select-none",oe,"border border-current/40",W&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":A==="expanded",onClick:()=>z(L=>L==="expanded"?"preview":"expanded"),onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),z(ne=>ne==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:Se.name??"Tool Output"}),Se.toolCallId&&u.jsx("span",{className:"opacity-70",children:Se.toolCallId.slice(0,8)}),A==="expanded"?u.jsx(ie.ChevronUp,{className:"h-3 w-3"}):u.jsx(ie.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[at&&Ce&&ee>=0&&u.jsx("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{type:"button",className:te("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",ee<He.length-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(ee>=He.length-1)return;const L=He[ee+1];L&&Y(L)},"aria-label":"Older checkpoint (back in time)",disabled:ee>=He.length-1,children:u.jsx(ie.ChevronLeft,{className:"h-3 w-3"})}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("span",{className:"whitespace-nowrap",children:[He.length-ee," / ",He.length]}),u.jsx("span",{className:"text-muted-foreground",children:Te(Ce)})]}),u.jsx("button",{type:"button",className:te("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",ee>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(ee<=0)return;const L=He[ee-1];L&&Y(L)},"aria-label":"Newer checkpoint (forward in time)",disabled:ee<=0,children:u.jsx(ie.ChevronRight,{className:"h-3 w-3"})})]})}),i&&t.createdAt&&u.jsx("time",{className:te("text-xs opacity-60",oe,W&&"text-xs"),dateTime:new Date(t.createdAt).toISOString(),title:new Date(t.createdAt).toLocaleString(),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(t.createdAt))}),s&&!o&&u.jsxs("div",{className:te("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx("div",{className:"relative",children:u.jsx(st,{variant:"ghost",size:"sm",onClick:()=>Ve(),className:te("h-6 w-6 p-0 hover:bg-foreground/10",oe,W&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(ie.Copy,{className:te(D?"text-success":oe,W?"h-3 w-3":"h-4 w-4")})})}),X==="user"&&x&&u.jsx(st,{variant:"ghost",size:"sm",onClick:Je,className:te("h-6 w-6 p-0 hover:bg-foreground/10",oe,W&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(ie.Edit,{className:te(oe,W?"h-3 w-3":"h-4 w-4")})}),X==="assistant"&&m&&u.jsx(st,{variant:"ghost",size:"sm",onClick:ze,className:te("h-6 w-6 p-0 hover:bg-foreground/10",oe,W&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(ie.RotateCcw,{className:te(oe,W?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsxs("div",{className:"relative",children:[bt(),p&&Be.length>0&&u.jsx("div",{className:"mt-3 space-y-4",children:Be.map((L,ne)=>(w.useEffect(()=>{sS()&&console.debug(`[MessageComponent] Preview ${ne} mounted:`,{src:L.src.substring(0,100),alt:L.alt,label:L.label})},[]),u.jsxs("div",{className:"space-y-2",children:[L.label&&u.jsxs("p",{className:"text-[0.65rem] uppercase tracking-wide text-muted-foreground",children:["Artifact: ",L.label]}),u.jsx("div",{className:"overflow-hidden rounded border border-border/60 bg-background/60 p-1 shadow-sm",children:u.jsx("img",{src:L.src,alt:L.alt,title:L.label,loading:"lazy",className:"h-auto max-h-[420px] w-full rounded object-contain",onLoad:()=>{},onError:ge=>{console.error(`[MessageComponent] ❌ Image failed to load for artifact ${ne}:`,{alt:L.alt,label:L.label,message:ge.target.alt})}})})]},`artifact-${ne}`)))})]}),fe&&A==="expanded"&&(Se.toolCallId||Se.name)&&u.jsxs("div",{className:te("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",W&&"text-xs"),children:[Se.name&&u.jsxs("div",{children:["Function: ",Se.name]}),Se.toolCallId&&u.jsxs("div",{children:["Call ID: ",Se.toolCallId]})]}),!(i||a||fe)&&s&&!o&&u.jsxs("div",{className:te("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx(st,{variant:"ghost",size:"sm",onClick:()=>Ve(),className:te("h-6 w-6 p-0 hover:bg-background/50 text-current",W&&"h-5 w-5"),children:u.jsx(ie.Copy,{className:te(D?"text-success":"text-current",W?"h-3 w-3":"h-4 w-4")})}),X==="user"&&x&&u.jsx(st,{variant:"ghost",size:"sm",onClick:Je,className:te("h-6 w-6 p-0 hover:bg-background/50 text-current",W&&"h-5 w-5"),children:u.jsx(ie.Edit,{className:te("text-current",W?"h-3 w-3":"h-4 w-4")})}),X==="assistant"&&m&&u.jsx(st,{variant:"ghost",size:"sm",onClick:ze,className:te("h-6 w-6 p-0 hover:bg-background/50 text-current",W&&"h-5 w-5"),children:u.jsx(ie.RotateCcw,{className:te("text-current",W?"h-3 w-3":"h-4 w-4")})})]})]})}),V&&u.jsx(vS,{isOpen:$,onClose:re,fileId:V.id,fileName:V.name,mimeType:V.mimeType})]})},(e,t)=>{var i,a,l,c,d,f,p,h;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&pp(e.message)===pp(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages","attemptMeta"].every(x=>e[x]===t[x]),s=((i=e.customStyles)==null?void 0:i.container)===((a=t.customStyles)==null?void 0:a.container)&&((l=e.customStyles)==null?void 0:l.content)===((c=t.customStyles)==null?void 0:c.content)&&((d=e.customStyles)==null?void 0:d.actions)===((f=t.customStyles)==null?void 0:f.actions)&&((p=e.customStyles)==null?void 0:p.header)===((h=t.customStyles)==null?void 0:h.header);return o&&s});function hp({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:LS,children:u.jsx("ul",{className:"list-disc pl-5",children:e.map((n,r)=>u.jsx("li",{children:String(n)},r))})}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:fo(e)}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:fo(e)})}function KS({interruptPart:e,onApprove:t,onReject:n,disabled:r,isActive:o,payload:s}){const i=e.title??"Approve the result?";let a=null;if(s!=null)if(typeof s=="string")a=u.jsx("p",{className:"text-sm leading-relaxed text-blue-800/90 dark:text-blue-200/90 whitespace-pre-wrap",children:s});else{const c=fo(s);a=u.jsx("pre",{className:"max-h-48 overflow-auto rounded bg-blue-100/60 p-2 text-xs text-blue-900/90 dark:bg-blue-900/40 dark:text-blue-100/80",children:c})}const l=o?"Please approve or reject this action to resume the workflow.":"Waiting for approval from another participant.";return u.jsxs(so,{className:te("border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-950/10 transition-shadow",o?"shadow-md ring-1 ring-blue-300 dark:ring-blue-500/70":"opacity-80"),children:[u.jsxs(io,{className:"pb-3",children:[u.jsx(ao,{className:"text-blue-900 dark:text-blue-100 text-base",children:i}),u.jsx(Tf,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a&&u.jsx(lo,{className:"pt-0 pb-3",children:a}),u.jsx(kf,{className:"pt-0",children:u.jsxs("div",{className:"flex gap-2 ml-auto",children:[u.jsx(st,{size:"sm",variant:"outline",onClick:()=>n(e),className:"border-red-300 text-red-700 hover:bg-red-50 dark:border-red-700 dark:text-red-300 dark:hover:bg-red-950/50",disabled:r||!o,children:"Reject"}),u.jsx(st,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:r||!o,children:"Approve"})]})})]})}function qS(e){const{allowFileOpen:t,currentThreadId:n}=e,{toast:r}=ka(),[o,s]=w.useState({}),[i,a]=w.useState(null),[l,c]=w.useState(!1),d=w.useCallback(()=>{c(!1),a(null)},[]),f=w.useCallback(h=>{a(h),c(!0)},[]),p=w.useCallback(async(h,x,m)=>{var v,g;if(!t){h.preventDefault();return}if(o[m]){h.preventDefault();return}try{const b=String(x.url??""),S=b.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(S){h.preventDefault();const k=S[1],C=x.name||`file_${k}`,T=x.mimeType||"application/octet-stream";f({id:k,name:C,mimeType:T});return}if(b.startsWith("data:")){h.preventDefault(),s(C=>({...C,[m]:!0}));const k=r({title:"Fetching file...",description:"",open:!0});try{const C=await Z0(n??void 0);if(!C||!Array.isArray(C))throw new Error("Invalid file list response");const T=C.find(E=>!E||typeof E!="object"||!((E.filename??"")===(x.name??""))?!1:typeof x.size=="number"&&typeof E.size=="number"?E.size===x.size:!0);if(!(T!=null&&T.id))throw new Error(`File "${x.name}" is not yet available on the server`);if(!T.id||!T.filename)throw new Error("Invalid file data received from server");f({id:T.id,name:x.name||T.filename||`file_${T.id}`,mimeType:x.mimeType||T.mime_type||"application/octet-stream"}),(v=k.update)==null||v.call(k,{id:k.id,title:"Success",description:`Opened ${x.name}`,open:!0})}catch(C){console.error("Failed to fetch server file:",C);const T=C instanceof Error?C.message:"Unknown error occurred";(g=k.update)==null||g.call(k,{id:k.id,title:"Failed",description:T}),r({title:"Failed to fetch file",description:T,open:!0})}finally{s(C=>({...C,[m]:!1}))}}}catch(b){console.error("File click error:",b),s(S=>({...S,[m]:!1}))}},[t,o,r,n,f]);return{uploadingFiles:o,handleFileClick:p,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:d}}function GS({text:e,expanded:t,onExpandedChange:n,previewLength:r,isCompact:o}){const s=Math.max(e.length-r,0),i=e.substring(0,r);return u.jsxs("div",{className:"flex flex-col gap-1",children:[u.jsx("div",{className:te("text-sm text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:t?u.jsx(po,{content:e,allowHtml:!1}):u.jsxs("pre",{className:te("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:[i,"..."]})}),u.jsx(st,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",onClick:()=>n(!t),children:t?u.jsxs(u.Fragment,{children:[u.jsx(ie.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(ie.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",s," chars)"]})})]})}function YS({message:e,viewMode:t}){const r=fp(e).name||"tool",o=c=>{if(c==null)return null;const d=typeof c=="string"?Ea(c)??c:c;if(d&&typeof d=="object")return u.jsx(hp,{data:d});const f=typeof d=="string"?d:(()=>{try{return fo(d)}catch{return String(d??"")}})();return u.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm text-foreground/90",children:f})},s=c=>{if(c==null)return null;const{content:d,isMarkdown:f}=eS(c);return f?u.jsx(po,{content:d,className:"text-current"}):o(c)};if(t==="preview")return null;const i=e.content.find(c=>c.type!=="tool_call");if(!i)return u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(ie.Loader,{className:"h-4 w-4 animate-spin"}),u.jsxs("span",{children:["Waiting for ",r," output…"]})]});if(i.type==="text"){const d=(i.text??"").trim();if(!d)return null;const f=Es(d);return s(f)}const a=uo(i),l=Es(a);return s(l)}const XS=({timelineEntries:e,activeCheckpointId:t,onSelectCheckpoint:n,messagePreviews:r})=>{const o=e??[],s=o.length>0,i=w.useMemo(()=>s?[...o].reverse():[],[o,s]),a=t??(o.length?o[o.length-1].id:null);return w.useEffect(()=>{console.debug("[TimelineColumn] entries:",o.length)},[o.length]),s?u.jsxs("div",{className:"w-32 flex-shrink-0 flex-col border-r border-border/40 pr-2 flex",children:[u.jsxs("div",{className:"relative flex-1 overflow-y-auto pt-4 pb-2 pr-1",children:[u.jsxs("div",{className:"absolute left-0 right-0 top-1 flex items-center justify-between px-2 pb-3 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:[u.jsx("span",{children:"Timeline"}),u.jsxs("div",{className:"group relative z-50",children:[u.jsx(ie.Info,{className:"h-3 w-3 text-muted-foreground cursor-help"}),u.jsx("div",{className:"pointer-events-auto fixed hidden w-56 rounded-md border bg-background p-3 text-[10px] font-normal text-muted-foreground shadow-lg group-hover:block whitespace-normal leading-relaxed",style:{zIndex:9999},children:"Backend pre-selects user inputs + latest loop checkpoint. Click a dot to jump, or use “Latest” to return to the newest messages."})]})]}),u.jsx("div",{className:"pointer-events-none absolute left-3 top-0 bottom-0 w-px bg-border/40"}),u.jsx("div",{className:"flex flex-col gap-3 pt-6 pr-2",children:i.map(l=>{const c=a===l.id,d=l.messageId?(r==null?void 0:r.get(l.messageId))??null:null;return u.jsxs("button",{type:"button",disabled:!n,onClick:()=>n==null?void 0:n(l.id),className:`relative flex items-start gap-2 text-left text-[11px] transition ${c?"text-primary":"text-muted-foreground"} ${n?"hover:text-foreground":"cursor-default opacity-70"}`,children:[u.jsx("span",{className:`mt-1 inline-flex h-3 w-3 items-center justify-center rounded-full border ${c?"border-primary bg-primary/10 text-primary":"border-border bg-background"}`,children:u.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${c?"bg-primary":"bg-border"}`})}),u.jsxs("span",{className:"flex-1",children:[u.jsx("span",{className:"block font-medium leading-tight",children:l.label||"User input"}),u.jsxs("span",{className:"text-[9px] uppercase tracking-wide text-muted-foreground/70",children:[l.step!==null?`STEP ${l.step}`:"STEP —",l.next?` - ${l.next}`:""]}),d&&u.jsx("p",{className:"text-[10px] text-muted-foreground/80 mt-1 line-clamp-2",title:d,children:d})]})]},l.id)})})]}),n&&u.jsx("button",{type:"button",onClick:()=>n==null?void 0:n(null),className:"mt-auto mb-3 rounded-md border border-border/70 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground transition hover:border-foreground/60 hover:text-foreground",children:"Latest"})]}):null},mp=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,Pa=w.forwardRef(({messages:e,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onStartReached:a,onEdit:l,onRegenerate:c,onCancelEdit:d,className:f,style:p,emptyMessage:h,followNewMessages:x=!0,isNavigatingCheckpoint:m=!1,onScrollAway:v,onAtBottom:g,activeInterrupt:b,disableInterruptActions:S=!1,onInterruptActionStart:k,onInterruptActionEnd:C,showToolMessages:T=!0,showArtifactPreviews:E=!0,checkpointMetaById:N,checkpointIndexByKey:_,attemptMetaById:P,userMessageIdToAttempts:R,activeCheckpointId:D,onSelectCheckpoint:F,timelineCheckpoints:A,messagePreviews:z,createSyntheticThinkingMessage:j=!1},J)=>{const B=w.useRef(null),O=w.useRef(null),W=w.useRef(!1),[X,fe]=w.useState(!0),ae=w.useMemo(()=>b?e.some(de=>"type"in de&&de.type==="default_message"?!1:Array.isArray(de==null?void 0:de.content)&&de.content.some(me=>me&&me.type==="interrupt"&&(me.id??me.interrupt_id)===b.id)):!1,[b,e]),Re=w.useMemo(()=>{if(!b||ae)return null;const de=b.id&&String(b.id).trim()?String(b.id).trim():"pending-interrupt";let me;const Le=b.value;if(Le&&typeof Le=="object"&&!Array.isArray(Le)){const Be=Le.title;typeof Be=="string"&&Be.trim()&&(me=Be.trim())}return{id:`interrupt-${de}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:de,value:Le,title:me}]}},[b,ae]),G=w.useMemo(()=>Re?[...e,Re]:e,[e,Re]),U=w.useMemo(()=>!j||!t?G:!G.some(me=>me.role==="assistant")&&G.length>0?[...G,{id:"thinking-assistant",role:"assistant",content:[],createdAt:new Date().toISOString()}]:G,[G,t,j]),q=w.useMemo(()=>T?U:U.filter(de=>(de==null?void 0:de.role)!=="tool"),[U,T]),$=w.useCallback(de=>{fe(de),v&&v(!de),g&&g(de)},[v,g]),V=w.useMemo(()=>{if(a)return async()=>{if(!W.current){W.current=!0;try{await a()}finally{W.current=!1}}}},[a]),re=w.useMemo(()=>!x||m?!1:X?"auto":!1,[X,x,m]),oe=A??[],se=oe.length>0,Se=w.useMemo(()=>{if(typeof h!="string")return null;const de=h.trim();return de?{id:"default-message",role:"assistant",type:"default_message",content:de,createdAt:new Date().toISOString()}:null},[h]),Qe=se?u.jsx(XS,{timelineEntries:oe,activeCheckpointId:D??null,onSelectCheckpoint:F,messagePreviews:z}):null,Fe=["flex h-full flex-col md:flex-row",f].filter(Boolean).join(" "),Xe=()=>Se?u.jsx("div",{className:"p-6 h-full overflow-y-auto",children:u.jsx("div",{className:"w-full max-w-full",children:u.jsx(Ra,{message:Se,messageIndex:0,isStreamingMessage:!1,showActions:!1,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:()=>{},onRegenerate:()=>{},onCancelEdit:()=>{},showArtifactPreviews:E})})}):u.jsx("div",{className:"flex h-full items-center justify-center py-8 text-center text-muted-foreground",children:h??"No messages yet. Start a conversation!"}),nt=q.length>0;return w.useImperativeHandle(J,()=>({scrollToLatest:()=>{var de,me;if(B.current&&q.length>0){const Le=q.length-1;(me=(de=B.current).scrollToIndex)==null||me.call(de,{index:Le,align:"end",behavior:"auto"})}else O.current&&(O.current.scrollTop=O.current.scrollHeight)},scrollToTop:()=>{var de,me;B.current&&q.length>0?(me=(de=B.current).scrollToIndex)==null||me.call(de,{index:0,align:"start",behavior:"auto"}):O.current&&(O.current.scrollTop=0)}}),[q]),u.jsxs("div",{className:Fe,style:p,children:[Qe,u.jsx("div",{className:"relative flex-1 min-h-0",children:nt?u.jsx(_0,{ref:de=>{B.current=de},scrollerRef:de=>{O.current=de instanceof HTMLDivElement?de:null},data:q,followOutput:re,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,alignToBottom:!0,startReached:()=>{V&&V()},atBottomStateChange:$,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(de,me)=>mp(me,de),itemContent:(de,me)=>{var vt;const Le=mp(me,de),Be="type"in me&&me.type==="default_message";let Ve=[],Je=null,ze={},Ze={},Et=null,ft=null,Ue=null;if(!Be){const It=me,bt=It.checkpointId??null;ze=It.additionalKwargs??{},Ze=It.responseMetadata??{};const wt=bt&&N?N.get(bt)??null:null;Et=typeof ze.step=="number"?ze.step:typeof Ze.step=="number"?Ze.step:(wt==null?void 0:wt.step)??null;const He=typeof ze.source=="string"?ze.source:typeof Ze.source=="string"?Ze.source:(wt==null?void 0:wt.source)??null;ft=He?String(He):null;const zt=Et!==null&&ft?`${Et}:${ft}`:null;if(zt&&(_!=null&&_.has(zt))?Ve=_.get(zt)??[]:bt&&wt&&(Ve=[wt]),Je=bt??((vt=Ve[0])==null?void 0:vt.id)??null,Ue=bt?(P==null?void 0:P.get(bt))??null:null,!Ue&&(me==null?void 0:me.role)==="user"&&(me!=null&&me.id)&&R){const Pe=R.get(me.id);if(Pe&&Pe.length>0){const _e=Pe[0].checkpointId;Ue=(P==null?void 0:P.get(_e))??null,console.log(`[MessageList] Found attempt by user message ID "${me.id}":`,Pe.length,"versions")}}if(!Ue&&Ve.length>0&&P){const Pe=P.get(Ve[0].id);Pe&&(Ue=Pe)}if(Ue&&Ue.attemptCount>1&&P){const Pe=Ue.baseUserMessageId;if(Pe){const _e=[];for(const[at,Y]of P.entries())if(Y.baseUserMessageId===Pe){const ee=N==null?void 0:N.get(at);ee&&_e.push(ee)}_e.length>0&&(Ve=_e)}}if(Ue&&Ue.attemptCount>1&&N&&P){const Pe=[];for(const[_e,at]of N.entries()){const Y=P.get(_e);Y&&Y.attemptCount===Ue.attemptCount&&Y.baseUserMessageId===Ue.baseUserMessageId&&Pe.push(at)}Pe.sort((_e,at)=>{const Y=_e.createdAt?Date.parse(_e.createdAt):0;return(at.createdAt?Date.parse(at.createdAt):0)-Y}),Pe.length>0&&(Ve=Pe,console.log("[MessageList] Populated checkpointCandidates with all attempts:",{messageId:me.id,attemptCount:Ue.attemptCount,candidateIds:Ve.map(_e=>_e.id)}))}}const xt=(()=>{if(typeof ze.parentCheckpointId=="string")return ze.parentCheckpointId;if(typeof Ze.parentCheckpointId=="string")return Ze.parentCheckpointId})();return u.jsx("div",{className:"relative mb-4 last:mb-0","data-message-id":Le,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:u.jsx(Ra,{message:me,messageIndex:de,isStreamingMessage:t&&n===me.id,streamingDebounceMs:r,isEditing:i===me.id,showActions:s,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:l,onRegenerate:()=>c(de),onCancelEdit:d,activeInterrupt:b,disableInterruptActions:S,onInterruptActionStart:k,onInterruptActionEnd:C,showToolMessages:T,showArtifactPreviews:E,checkpointCandidates:Ve,activeCheckpointId:D??null,onSelectCheckpoint:F,defaultCheckpointId:Je,messageParentCheckpointId:xt,attemptMeta:Ue})})}}):Xe()})]})});Pa.displayName="MessageList";const gp={value:""};function Ls({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:c=!0,showToolMessages:d=!0,showArtifactPreviews:f=!0,customStyles:p={},onMessageSent:h,onExcelUploadSuccess:x,onError:m}){const{api:v}=di(),{currentThreadId:g}=Ro(),{threadId:b,messages:S,isHistoryLoading:k,isLoading:C,navigateToCheckpoint:T,returnToLatest:E,checkpoint:N,checkpoints:_,interrupt:P,metadata:R,timelineCheckpoints:D,messagePreviews:F}=Po(),{isStreaming:A,error:z,connectionState:j,submit:J,stop:B}=fc(),O=b??g??null,W=(N==null?void 0:N.id)??null,X=(N==null?void 0:N.namespace)??null,fe=(R==null?void 0:R.assemblingMessageId)??null,ae=P,[Re,G]=w.useState(!1);w.useEffect(()=>{ae||G(!1)},[ae]);const U=w.useCallback(()=>{G(!0)},[]),q=w.useCallback(()=>{G(!1)},[]),$=!!ae||Re,[V,re]=w.useState(null),[oe,se]=w.useState(""),[Se,Qe]=w.useState(null),[Fe,Xe]=w.useState(null),[nt,de]=w.useState([]),[me,Le]=w.useState(0),[Be,Ve]=w.useState(0),[Je,ze]=w.useState(!1),[Ze,Et]=w.useState(null),[ft,Ue]=w.useState(null),[xt,vt]=w.useState(!1),[It,bt]=w.useState(null),wt=w.useRef(!1),[He,zt]=w.useState(()=>gp.value),Pe=w.useRef(He),_e=w.useRef(null),at=w.useCallback(Z=>{gp.value=Z,zt(Z)},[]),[Y,ee]=w.useState(!1),Ce=w.useRef(null),Te=w.useCallback((Z,xe)=>{if(!Z||typeof Z!="object")return null;const ye=Z[xe];return typeof ye=="number"?ye:null},[]),L=w.useCallback((Z,xe)=>{if(!Z||typeof Z!="object")return null;const ye=Z[xe];return typeof ye=="string"&&ye.trim()?ye:null},[]),ne=w.useMemo(()=>{const Z=Ke=>{if(!Array.isArray(Ke)||Ke.length===0)return null;const Nt=Ke.map(ot=>{if(typeof ot=="string")return ot.trim();if(ot&&typeof ot=="object"&&"type"in ot){const Bt=ot;if(typeof Bt.type=="string")return Bt.type}return null}).filter(ot=>!!(ot&&ot.length));return Nt.length?Nt.join(", "):null},xe=Array.isArray(_)?_.map(Ke=>{const Nt=Z(Ke.next);return Nt?{...Ke,metadata:{...Ke.metadata??{},next:Nt}}:Ke}):[];return xe.some(Ke=>Te(Ke.metadata,"step")!==null)&&xe.sort((Ke,Nt)=>{const ot=Te(Ke.metadata,"step"),Bt=Te(Nt.metadata,"step");if(ot!==null||Bt!==null)return(Bt??Number.NEGATIVE_INFINITY)-(ot??Number.NEGATIVE_INFINITY);const sn=Date.parse(Ke.createdAt??""),jr=Date.parse(Nt.createdAt??"");return Number.isNaN(sn)||Number.isNaN(jr)?0:jr-sn}),xe},[_,Te]),{checkpointMetaById:ge,checkpointIndexByKey:pe,attemptMetaById:et,userMessageIdToAttempts:ke}=w.useMemo(()=>{const Z=new Map,xe=new Map,ye=new Map;for(const ot of ne){const Bt=ot.checkpointId??null;if(!Bt)continue;const sn=Te(ot.metadata,"step"),jr=L(ot.metadata,"source"),Wh={id:Bt,step:sn,source:jr,createdAt:ot.createdAt??null,namespace:ot.checkpointNs??null,parentId:ot.parentId??null};if(Z.set(Bt,Wh),sn!==null&&jr){const Vh=`${sn}:${jr}`,Kh=xe.get(Vh)??[];Kh.push(Wh),xe.set(Vh,Kh)}}console.log("[ChatInterface] Building attempt metadata for",ne.length,"checkpoints");const Ke=gw(ne);for(const[ot,Bt]of Z.entries()){const sn=Ke.get(ot);sn?ye.set(ot,{...Bt,attemptIndex:sn.attemptIndex,attemptCount:sn.attemptCount,isLatestAttempt:sn.isLatestAttempt,baseUserMessageId:sn.baseUserMessageId??null}):ye.set(ot,{...Bt,attemptIndex:0,attemptCount:1,isLatestAttempt:!0,baseUserMessageId:null})}console.log("[ChatInterface] Final attemptMetaById:",{totalCheckpoints:ye.size,withMultipleAttempts:Array.from(ye.values()).filter(ot=>ot.attemptCount>1).length,samples:Array.from(ye.entries()).slice(0,3).map(([ot,Bt])=>({checkpointId:ot,attemptIndex:Bt.attemptIndex,attemptCount:Bt.attemptCount}))});const Nt=xw(ye);return console.log("[ChatInterface] userMessageIdToAttempts map built with",Nt.size,"user message IDs with multiple attempts"),{checkpointMetaById:Z,checkpointIndexByKey:xe,attemptMetaById:ye,userMessageIdToAttempts:Nt}},[ne,Te,L]),ct=D??[],Wn=w.useRef(null),ur=w.useRef(null),Vn=w.useCallback(()=>{Wn.current&&(Wn.current.value=""),ur.current&&(ur.current.value=""),Le(Z=>Z+1),Ve(Z=>Z+1)},[]),Ga=w.useCallback(Z=>{at(Z)},[at]),Gs=w.useRef(!1);w.useEffect(()=>{Gs.current&&!A&&(de([]),Vn()),Gs.current=A},[A,Vn]);const[Ya,Xa]=w.useState("desktop");w.useEffect(()=>{const Z=()=>{const xe=window.innerWidth;Xa(xe<640?"phone":xe<1024?"tablet":"desktop")};return Z(),window.addEventListener("resize",Z),()=>window.removeEventListener("resize",Z)},[]),w.useEffect(()=>{wt.current=!1},[O]),w.useEffect(()=>{Pe.current=He},[He]),w.useEffect(()=>{if(!V){_e.current=null;return}_e.current===null&&(_e.current=Pe.current),at(oe??"")},[oe,V,at]),w.useEffect(()=>{(async()=>{if(!v.baseUrl){bt(null);return}try{const ye=(await v.getAgent("default")).uiDefaultMessage||"";bt(ye||null)}catch(xe){console.warn("Failed to fetch default message:",xe),bt(null)}})()},[v.baseUrl]),w.useEffect(()=>{z&&!xt&&(m==null||m(z))},[z,xt,m]);const I=Z=>{if(Z.length>us)return`Message too long (${Z.length}/${us} characters)`;try{return bw(Z),null}catch(xe){return(xe==null?void 0:xe.message)||"Invalid message"}},K=async Z=>{const xe=Z.trim();if(!(!xe&&nt.length===0)){if(xe){const ye=I(xe);if(ye){Xe(ye);return}}try{const ye=W??void 0,Ke=X??void 0,Nt=V?{edit:!0,originalMessageId:V,...Se!=null&&Se.checkpointId?{originalCheckpointId:Se.checkpointId}:{},...Se!=null&&Se.checkpointNs?{originalCheckpointNs:Se.checkpointNs}:{}}:void 0;await J({text:xe||"",attachments:nt,messageAdditionalKwargs:Nt},{checkpointId:ye,checkpointNs:Ke}),h==null||h(xe),at(""),Xe(null),de([]),Vn(),re(null),se(""),Qe(null)}catch(ye){const Ke=(ye==null?void 0:ye.message)||"Failed to send message";Xe(Ke),m==null||m(Ke)}}},le=w.useCallback((Z,xe,ye)=>{c&&(_e.current=He,re(Z),se(xe),at(xe),Xe(null),Qe({checkpointId:(ye==null?void 0:ye.checkpointId)??null,checkpointNs:(ye==null?void 0:ye.checkpointNs)??null}))},[He,c,at]),Ee=w.useCallback(()=>{re(null),se(""),Qe(null),Xe(null),at(_e.current??He),_e.current=null},[He,at]),rt=w.useCallback((Z,xe,ye)=>{le(Z,xe,ye)},[le]),lt=w.useCallback(Z=>{for(let xe=Z-1;xe>=0;xe--)if(S[xe].role==="user"){const ye=S[xe].content||[],Nt=ye.filter(ot=>ot.type==="text").map(ot=>ot.text).join("")||(()=>{try{return JSON.stringify(ye,null,2)}catch{return String(ye)}})();Nt&&J({text:Nt},{checkpointId:W??void 0,checkpointNs:X??void 0});break}},[S,J,W,X]),qe=Z=>{const xe=Array.from(Z.target.files||[]);de(ye=>[...ye,...xe]),Z.target.value=""},We=Z=>{de(xe=>{const ye=xe.filter((Ke,Nt)=>Z!==Nt);return ye.length===0&&Vn(),ye})},Rt=async Z=>{const xe=(Z.target.files||[])[0];if(xe){Et(null),Ue(null),ze(!0);try{await J({attachments:[xe]},{checkpointId:W??void 0,checkpointNs:X??void 0});const ye=`Uploaded ${xe.name} - processing through chat stream`;Ue(ye)}catch(ye){const Ke=ye instanceof Error?ye.message:"Failed to upload Excel file";console.error("Excel upload failed",ye),Et(Ke),m==null||m(Ke)}finally{ze(!1),Z.target.value="",Vn()}}},yt=async Z=>{if(g){ee(!0);try{if(!Z){await E(),requestAnimationFrame(()=>{var Ke;(Ke=Ce.current)==null||Ke.scrollToLatest()});return}const xe=ne.find(Ke=>Ke.checkpointId===Z),ye=(xe==null?void 0:xe.checkpointNs)??null;await T(Z,ye),requestAnimationFrame(()=>{var Ke;(Ke=Ce.current)==null||Ke.scrollToTop()})}finally{ee(!1)}}},St=w.useCallback(async Z=>{await yt(Z)},[yt]),Vt=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${p.container||""}`,Kn=`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 ${p.messagesArea||""}`,_n=`flex-shrink-0 w-full border-t p-4 bg-transparent ${p.inputArea||""}`;return w.useCallback(Z=>{if(!Z)return"Latest";const xe=[];Z.step!==null&&xe.push(`Step ${Z.step}`),Z.source&&xe.push(Z.source);const ye=Z.createdAt?new Date(Z.createdAt):null,Ke=ye&&!Number.isNaN(ye.getTime())?ye.toLocaleString():Z.createdAt??Z.id,Nt=xe.length?` — ${xe.join(" • ")}`:"";return`${Ke}${Nt}`},[]),u.jsxs("div",{className:Vt,children:[!!z&&!xt&&u.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:[u.jsx("span",{children:z}),u.jsx(st,{variant:"ghost",size:"sm",onClick:()=>vt(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:u.jsx(ie.X,{size:16})})]}),u.jsxs("div",{className:`relative ${Kn}`,style:r?{maxHeight:r}:void 0,children:[u.jsx(Pa,{ref:Ce,className:"h-full",style:{height:"100%"},messages:S,isStreaming:A,streamingAssistantId:fe,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:Ya,enableMessageEditing:c,editingMessageId:V,onEdit:rt,onRegenerate:lt,onCancelEdit:Ee,emptyMessage:It??void 0,isNavigatingCheckpoint:Y,activeInterrupt:ae,disableInterruptActions:Re,onInterruptActionStart:U,onInterruptActionEnd:q,showToolMessages:d,showArtifactPreviews:f,checkpointMetaById:ge,checkpointIndexByKey:pe,attemptMetaById:et,userMessageIdToAttempts:ke,activeCheckpointId:W,onSelectCheckpoint:St,timelineCheckpoints:ct,messagePreviews:F}),(j==="reconnecting"||j==="connecting")&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-muted/80 px-3 py-1 text-xs font-medium text-foreground shadow-sm backdrop-blur-sm dark:bg-muted/60",children:u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx(ie.Loader2,{className:"h-3 w-3 animate-spin"}),j==="reconnecting"?"Reconnecting…":"Connecting…"]})}),j==="error"&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-destructive/10 px-3 py-1 text-xs font-semibold text-destructive shadow-sm",children:"Connection lost"}),C&&u.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:[u.jsx(ie.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]}),(k||Y)&&u.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:[u.jsx(ie.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading checkpoint…"})]})]}),u.jsxs("div",{className:_n,children:[V&&u.jsx("div",{className:"mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(ie.Edit3,{size:16,className:"text-blue-600"}),u.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),u.jsx(st,{variant:"ghost",size:"sm",onClick:Ee,className:"text-blue-600 hover:bg-blue-100",children:u.jsx(ie.X,{size:16})})]})}),(a||l)&&u.jsxs("div",{className:"mb-3 space-y-3",children:[a&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Wn,type:"file",multiple:!0,onChange:Z=>qe(Z),className:"hidden"},me),nt.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2",children:nt.map((Z,xe)=>u.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:[u.jsx(ie.Paperclip,{size:14}),u.jsx("span",{className:"truncate max-w-[150px]",children:Z.name}),u.jsx(st,{variant:"ghost",size:"sm",onClick:()=>We(xe),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 ${Z.name}`,children:u.jsx(ie.X,{size:12})})]},xe))})]}),l&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:ur,type:"file",accept:".xls,.xlsx,.xlsm",onChange:Rt,className:"hidden"},Be),Je&&u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(ie.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),ft&&!Je&&u.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:ft}),Ze&&!Je&&u.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:Ze})]})]}),Fe&&u.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:Fe}),u.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&u.jsxs(aw,{children:[u.jsx(lw,{asChild:!0,children:u.jsx(st,{type:"button",size:"icon",variant:"outline",disabled:A||$,title:"More input actions",className:p.moreButton||"",children:u.jsx(ie.Plus,{size:16})})}),u.jsxs(Cd,{align:"start",sideOffset:6,className:"w-52",children:[a&&u.jsxs(Qi,{onClick:()=>{var Z;return(Z=Wn.current)==null?void 0:Z.click()},className:"cursor-pointer",children:[u.jsx(ie.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&u.jsxs(Qi,{onClick:()=>{var Z;Je||(Z=ur.current)==null||Z.click()},className:`cursor-pointer ${Je?"opacity-60 pointer-events-none":""}`,children:[u.jsx(ie.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),u.jsx("div",{className:"flex-1",children:u.jsx(lx,{initialValue:oe,editingMessageId:V,value:He,onValueChange:Ga,placeholder:V?"Edit your message...":t,isStreaming:A,disabled:$,maxLength:us,onSend:K,onCancelEdit:Ee,onStop:B,allowEmptySend:nt.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${V?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${Fe?"border-red-400":""} ${p.textarea||""}`})})]})]})]})}const $s=y.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{type:t,className:te("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}));$s.displayName="Input";function Oa(e,[t,n]){return Math.min(n,Math.max(t,e))}function JS(e,t){return y.useReducer((n,r)=>t[n][r]??n,e)}var Ma="ScrollArea",[xp,FT]=kn(Ma),[ZS,rn]=xp(Ma),yp=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,l]=y.useState(null),[c,d]=y.useState(null),[f,p]=y.useState(null),[h,x]=y.useState(null),[m,v]=y.useState(null),[g,b]=y.useState(0),[S,k]=y.useState(0),[C,T]=y.useState(!1),[E,N]=y.useState(!1),_=Ge(t,R=>l(R)),P=Mo(o);return u.jsx(ZS,{scope:n,type:r,dir:P,scrollHideDelay:s,scrollArea:a,viewport:c,onViewportChange:d,content:f,onContentChange:p,scrollbarX:h,onScrollbarXChange:x,scrollbarXEnabled:C,onScrollbarXEnabledChange:T,scrollbarY:m,onScrollbarYChange:v,scrollbarYEnabled:E,onScrollbarYEnabledChange:N,onCornerWidthChange:b,onCornerHeightChange:k,children:u.jsx(Oe.div,{dir:P,...i,ref:_,style:{position:"relative","--radix-scroll-area-corner-width":g+"px","--radix-scroll-area-corner-height":S+"px",...e.style}})})});yp.displayName=Ma;var vp="ScrollAreaViewport",bp=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=rn(vp,n),a=y.useRef(null),l=Ge(t,a,i.onViewportChange);return u.jsxs(u.Fragment,{children:[u.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}),u.jsx(Oe.div,{"data-radix-scroll-area-viewport":"",...s,ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:u.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});bp.displayName=vp;var Cn="ScrollAreaScrollbar",Da=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=rn(Cn,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return y.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?u.jsx(QS,{...r,ref:t,forceMount:n}):o.type==="scroll"?u.jsx(eC,{...r,ref:t,forceMount:n}):o.type==="auto"?u.jsx(wp,{...r,ref:t,forceMount:n}):o.type==="always"?u.jsx(La,{...r,ref:t}):null});Da.displayName=Cn;var QS=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=rn(Cn,e.__scopeScrollArea),[s,i]=y.useState(!1);return y.useEffect(()=>{const a=o.scrollArea;let l=0;if(a){const c=()=>{window.clearTimeout(l),i(!0)},d=()=>{l=window.setTimeout(()=>i(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",c),a.addEventListener("pointerleave",d),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",c),a.removeEventListener("pointerleave",d)}}},[o.scrollArea,o.scrollHideDelay]),u.jsx(Qt,{present:n||s,children:u.jsx(wp,{"data-state":s?"visible":"hidden",...r,ref:t})})}),eC=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=rn(Cn,e.__scopeScrollArea),s=e.orientation==="horizontal",i=Us(()=>l("SCROLL_END"),100),[a,l]=JS("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 y.useEffect(()=>{if(a==="idle"){const c=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(c)}},[a,o.scrollHideDelay,l]),y.useEffect(()=>{const c=o.viewport,d=s?"scrollLeft":"scrollTop";if(c){let f=c[d];const p=()=>{const h=c[d];f!==h&&(l("SCROLL"),i()),f=h};return c.addEventListener("scroll",p),()=>c.removeEventListener("scroll",p)}},[o.viewport,s,l,i]),u.jsx(Qt,{present:n||a!=="hidden",children:u.jsx(La,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:he(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:he(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),wp=y.forwardRef((e,t)=>{const n=rn(Cn,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=y.useState(!1),a=e.orientation==="horizontal",l=Us(()=>{if(n.viewport){const c=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?c:d)}},10);return Nr(n.viewport,l),Nr(n.content,l),u.jsx(Qt,{present:r||s,children:u.jsx(La,{"data-state":s?"visible":"hidden",...o,ref:t})})}),La=y.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=rn(Cn,e.__scopeScrollArea),s=y.useRef(null),i=y.useRef(0),[a,l]=y.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=Ep(a.viewport,a.content),d={...r,sizes:a,onSizesChange:l,hasThumb:c>0&&c<1,onThumbChange:p=>s.current=p,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:p=>i.current=p};function f(p,h){return iC(p,i.current,a,h)}return n==="horizontal"?u.jsx(tC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const p=o.viewport.scrollLeft,h=Ip(p,a,o.dir);s.current.style.transform=`translate3d(${h}px, 0, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollLeft=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollLeft=f(p,o.dir))}}):n==="vertical"?u.jsx(nC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const p=o.viewport.scrollTop,h=Ip(p,a);s.current.style.transform=`translate3d(0, ${h}px, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollTop=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollTop=f(p))}}):null}),tC=y.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=rn(Cn,e.__scopeScrollArea),[i,a]=y.useState(),l=y.useRef(null),c=Ge(t,l,s.onScrollbarXChange);return y.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Cp,{"data-orientation":"horizontal",...o,ref:c,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":Bs(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,f)=>{if(s.viewport){const p=s.viewport.scrollLeft+d.deltaX;e.onWheelScroll(p),Ap(p,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:zs(i.paddingLeft),paddingEnd:zs(i.paddingRight)}})}})}),nC=y.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=rn(Cn,e.__scopeScrollArea),[i,a]=y.useState(),l=y.useRef(null),c=Ge(t,l,s.onScrollbarYChange);return y.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Cp,{"data-orientation":"vertical",...o,ref:c,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":Bs(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,f)=>{if(s.viewport){const p=s.viewport.scrollTop+d.deltaY;e.onWheelScroll(p),Ap(p,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:zs(i.paddingTop),paddingEnd:zs(i.paddingBottom)}})}})}),[rC,Sp]=xp(Cn),Cp=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:c,onWheelScroll:d,onResize:f,...p}=e,h=rn(Cn,n),[x,m]=y.useState(null),v=Ge(t,_=>m(_)),g=y.useRef(null),b=y.useRef(""),S=h.viewport,k=r.content-r.viewport,C=jt(d),T=jt(l),E=Us(f,10);function N(_){if(g.current){const P=_.clientX-g.current.left,R=_.clientY-g.current.top;c({x:P,y:R})}}return y.useEffect(()=>{const _=P=>{const R=P.target;(x==null?void 0:x.contains(R))&&C(P,k)};return document.addEventListener("wheel",_,{passive:!1}),()=>document.removeEventListener("wheel",_,{passive:!1})},[S,x,k,C]),y.useEffect(T,[r,T]),Nr(x,E),Nr(h.content,E),u.jsx(rC,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:jt(s),onThumbPointerUp:jt(i),onThumbPositionChange:T,onThumbPointerDown:jt(a),children:u.jsx(Oe.div,{...p,ref:v,style:{position:"absolute",...p.style},onPointerDown:he(e.onPointerDown,_=>{_.button===0&&(_.target.setPointerCapture(_.pointerId),g.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",h.viewport&&(h.viewport.style.scrollBehavior="auto"),N(_))}),onPointerMove:he(e.onPointerMove,N),onPointerUp:he(e.onPointerUp,_=>{const P=_.target;P.hasPointerCapture(_.pointerId)&&P.releasePointerCapture(_.pointerId),document.body.style.webkitUserSelect=b.current,h.viewport&&(h.viewport.style.scrollBehavior=""),g.current=null})})})}),Fs="ScrollAreaThumb",Tp=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Sp(Fs,e.__scopeScrollArea);return u.jsx(Qt,{present:n||o.hasThumb,children:u.jsx(oC,{ref:t,...r})})}),oC=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=rn(Fs,n),i=Sp(Fs,n),{onThumbPositionChange:a}=i,l=Ge(t,f=>i.onThumbChange(f)),c=y.useRef(void 0),d=Us(()=>{c.current&&(c.current(),c.current=void 0)},100);return y.useEffect(()=>{const f=s.viewport;if(f){const p=()=>{if(d(),!c.current){const h=aC(f,a);c.current=h,a()}};return a(),f.addEventListener("scroll",p),()=>f.removeEventListener("scroll",p)}},[s.viewport,d,a]),u.jsx(Oe.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:he(e.onPointerDownCapture,f=>{const h=f.target.getBoundingClientRect(),x=f.clientX-h.left,m=f.clientY-h.top;i.onThumbPointerDown({x,y:m})}),onPointerUp:he(e.onPointerUp,i.onThumbPointerUp)})});Tp.displayName=Fs;var $a="ScrollAreaCorner",kp=y.forwardRef((e,t)=>{const n=rn($a,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(sC,{...e,ref:t}):null});kp.displayName=$a;var sC=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=rn($a,n),[s,i]=y.useState(0),[a,l]=y.useState(0),c=!!(s&&a);return Nr(o.scrollbarX,()=>{var f;const d=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(d),l(d)}),Nr(o.scrollbarY,()=>{var f;const d=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(d),i(d)}),c?u.jsx(Oe.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 zs(e){return e?parseInt(e,10):0}function Ep(e,t){const n=e/t;return isNaN(n)?0:n}function Bs(e){const t=Ep(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function iC(e,t,n,r="ltr"){const o=Bs(n),s=o/2,i=t||s,a=o-i,l=n.scrollbar.paddingStart+i,c=n.scrollbar.size-n.scrollbar.paddingEnd-a,d=n.content-n.viewport,f=r==="ltr"?[0,d]:[d*-1,0];return Np([l,c],f)(e)}function Ip(e,t,n="ltr"){const r=Bs(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],c=Oa(e,l);return Np([0,i],[0,a])(c)}function Np(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 Ap(e,t){return e>0&&e<t}var aC=(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 Us(e,t){const n=jt(e),r=y.useRef(0);return y.useEffect(()=>()=>window.clearTimeout(r.current),[]),y.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function Nr(e,t){const n=jt(t);_t(()=>{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 _p=yp,lC=bp,cC=kp;const jp=y.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(_p,{ref:r,className:te("relative overflow-hidden",e),...n,children:[u.jsx(lC,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),u.jsx(Rp,{}),u.jsx(cC,{})]}));jp.displayName=_p.displayName;const Rp=y.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(Da,{ref:r,orientation:t,className:te("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:u.jsx(Tp,{className:"relative flex-1 rounded-full bg-border"})}));Rp.displayName=Da.displayName;const Pp=25;function Fa({className:e="",showCreateButton:t=!0,showDeleteButton:n=!0,showEditTitle:r=!0,maxHeight:o="400px",customStyles:s={},currentThreadId:i=null,navigateToThread:a,onThreadSelect:l,onThreadCreate:c,onThreadDelete:d}){const{threads:f,currentThreadId:p,setCurrentThreadId:h,isLoading:x,actions:m}=Ro(),{loadThread:v}=Po(),{createThread:g,deleteThread:b,renameThread:S}=m,[k,C]=w.useState(Array.isArray(f)?f:[]),T=w.useRef(k.length>0),E=w.useRef(null),N=w.useRef(0),[_,P]=w.useState(null),[R,D]=w.useState(""),[F,A]=w.useState(!1);w.useEffect(()=>{const G=Array.isArray(f)?f:[];if(G.length>0){T.current=!0,C(G);return}x||(T.current=!1,C(G))},[f,x]),w.useEffect(()=>{if(!E.current)return;const G=E.current.querySelector("[data-radix-scroll-area-viewport]");if(!G)return;let U=null,q=null;return U=requestAnimationFrame(()=>{q=requestAnimationFrame(()=>{G.scrollTop=N.current})}),()=>{U!==null&&cancelAnimationFrame(U),q!==null&&cancelAnimationFrame(q)}},[k]);const z=async G=>{try{h(G),await v(G),a==null||a(G),l==null||l(G)}catch(U){console.error("Failed to select thread:",U)}},j=async()=>{try{A(!0);const G=await g();G&&(c==null||c(G),a==null||a(G))}catch(G){console.error("Failed to create thread:",G)}finally{A(!1)}},J=async(G,U)=>{if(U.stopPropagation(),!!confirm("Delete this thread?")){if(E.current){const q=E.current.querySelector("[data-radix-scroll-area-viewport]");q&&(N.current=q.scrollTop)}try{await b(G),d==null||d(G)}catch(q){console.error("Failed to delete thread:",q)}}},B=(G,U)=>{U.stopPropagation(),P(G.threadId),D(G.title||`Thread ${G.threadId.slice(0,8)}`)},O=async G=>{if(R.trim())try{await S(G,R.trim()),P(null),D("")}catch(U){console.error("Failed to update title:",U)}},W=()=>{P(null),D("")},X=(G,U)=>{G.key==="Enter"?O(U):G.key==="Escape"&&W()},fe=G=>{if(!G)return"";try{const U=new Date(G),$=new Date().getTime()-U.getTime(),V=Math.floor($/(1e3*60*60*24));return V===0?U.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):V===1?"Yesterday":V<7?`${V} days ago`:U.toLocaleDateString()}catch{return""}},ae=G=>G.title||`Thread ${G.threadId.slice(0,8)}`,Re=G=>{const U=ae(G);return U.length<=Pp?U:`${U.slice(0,Pp)}...`};return u.jsxs("div",{className:`flex flex-col h-full ${e} ${s.container||""}`,children:[t&&u.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:u.jsx(st,{onClick:j,disabled:F||x,className:s.createButton||"p-2",size:"sm",variant:"ghost",title:F?"Creating...":"New Chat",children:u.jsx(ie.MessageSquarePlus,{size:20})})}),u.jsx(jp,{ref:E,className:`flex-1 min-h-0 ${s.threadList||""}`,style:o?{maxHeight:o}:void 0,children:u.jsx("div",{className:"p-2 space-y-1 pb-4",children:x?u.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[u.jsx(ie.Loader2,{className:"h-5 w-5 animate-spin"}),u.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):k.length===0?u.jsxs("div",{className:"text-center py-8 text-slate-400",children:[u.jsx(ie.MessageSquare,{className:"w-8 h-8 mx-auto mb-2 opacity-40 text-slate-500"}),u.jsx("p",{className:"text-sm text-slate-500",children:"No conversations yet"})]}):k.slice().sort((G,U)=>new Date(U.updatedAt||U.createdAt||"").getTime()-new Date(G.updatedAt||G.createdAt||"").getTime()).map(G=>u.jsxs("div",{onClick:()=>z(G.threadId),className:`group relative p-3 rounded-lg cursor-pointer transition-colors border ${(i??p)===G.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:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("div",{className:"flex-1 min-w-0",children:_===G.threadId?u.jsxs("div",{className:"flex items-center gap-2",onClick:U=>U.stopPropagation(),children:[u.jsx($s,{value:R,onChange:U=>D(U.target.value),onKeyDown:U=>X(U,G.threadId),className:"h-6 text-sm",autoFocus:!0}),u.jsx(st,{variant:"ghost",size:"sm",onClick:()=>O(G.threadId),className:"h-6 w-6 p-0",children:u.jsx(ie.Check,{size:12})}),u.jsx(st,{variant:"ghost",size:"sm",onClick:W,className:"h-6 w-6 p-0",children:u.jsx(ie.X,{size:12})})]}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"font-medium text-sm truncate text-gray-900 dark:text-slate-100",children:Re(G)}),u.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mt-1",children:[u.jsx(ie.Calendar,{size:10}),u.jsx("span",{children:fe(G.updatedAt||G.createdAt)})]})]})}),u.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2",children:[r&&_!==G.threadId&&u.jsx(st,{variant:"ghost",size:"sm",onClick:U=>B(G,U),className:"h-6 w-6 p-0",title:"Edit title",children:u.jsx(ie.Edit3,{size:12})}),n&&u.jsx(st,{variant:"ghost",size:"sm",onClick:U=>J(G.threadId,U),className:"h-6 w-6 p-0 text-red-400 hover:text-red-300 hover:bg-red-900/20",title:"Delete thread",children:u.jsx(ie.Trash2,{size:12})})]})]}),i===G.threadId&&u.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-blue-400 rounded-r"})]},G.threadId))})})]})}function Ar(e){if(!(typeof globalThis>"u"))return globalThis[e]}function uC(e){if(typeof e!="string")return;const t=e.trim();if(t)return Tn(t)}function Op(){const e=[Ar("__API_BASE_URL__"),Ar("__CHAT_API_BASE_URL__"),Ar("__CHAT_API_URL__")];for(const t of e){const n=uC(t);if(n)return n}}function Mp(){const e=[Ar("__API_AUTH_TOKEN__"),Ar("__CHAT_API_KEY__"),Ar("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function Dp(...e){for(const t of e)if(typeof t=="string"&&t.trim())return Tn(t);return Tn()}function Lp(){const e={},t=Op(),n=Mp();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function $p(){const e=Lp(),t=jn.getAuthToken(),n=Op();return{apiBaseUrl:Dp(e.baseUrl,jn.baseUrl,n),apiKey:t||e.apiKey||Mp()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const Fp="chat-settings";function dC(){try{const e=localStorage.getItem(Fp);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function fC(e){try{const t={...e,apiBaseUrl:Tn(e.apiBaseUrl)};localStorage.setItem(Fp,JSON.stringify(t)),t.apiKey&&jn.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function pC(){const e=$p(),t=dC(),n=jn.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:Dp(jn.baseUrl,r,e.apiBaseUrl)}}function hC(e){jn.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),fC(e)}var mC="Label",zp=y.forwardRef((e,t)=>u.jsx(Oe.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())}}));zp.displayName=mC;var Bp=zp;const gC=mo.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),on=y.forwardRef(({className:e,...t},n)=>u.jsx(Bp,{ref:n,className:te(gC(),e),...t}));on.displayName=Bp.displayName;function Up(e){const t=y.useRef({value:e,previous:e});return y.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Hp=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"}),xC="VisuallyHidden",yC=y.forwardRef((e,t)=>u.jsx(Oe.span,{...e,ref:t,style:{...Hp,...e.style}}));yC.displayName=xC;var vC=[" ","Enter","ArrowUp","ArrowDown"],bC=[" ","Enter"],ar="Select",[Hs,Ws,wC]=yi(ar),[_r,zT]=kn(ar,[wC,Go]),Vs=Go(),[SC,Bn]=_r(ar),[CC,TC]=_r(ar),Wp=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:s,value:i,defaultValue:a,onValueChange:l,dir:c,name:d,autoComplete:f,disabled:p,required:h,form:x}=e,m=Vs(t),[v,g]=y.useState(null),[b,S]=y.useState(null),[k,C]=y.useState(!1),T=Mo(c),[E,N]=gr({prop:r,defaultProp:o??!1,onChange:s,caller:ar}),[_,P]=gr({prop:i,defaultProp:a,onChange:l,caller:ar}),R=y.useRef(null),D=v?x||!!v.closest("form"):!0,[F,A]=y.useState(new Set),z=Array.from(F).map(j=>j.props.value).join(";");return u.jsx(iu,{...m,children:u.jsxs(SC,{required:h,scope:t,trigger:v,onTriggerChange:g,valueNode:b,onValueNodeChange:S,valueNodeHasChildren:k,onValueNodeHasChildrenChange:C,contentId:En(),value:_,onValueChange:P,open:E,onOpenChange:N,dir:T,triggerPointerDownPosRef:R,disabled:p,children:[u.jsx(Hs.Provider,{scope:t,children:u.jsx(CC,{scope:e.__scopeSelect,onNativeOptionAdd:y.useCallback(j=>{A(J=>new Set(J).add(j))},[]),onNativeOptionRemove:y.useCallback(j=>{A(J=>{const B=new Set(J);return B.delete(j),B})},[]),children:n})}),D?u.jsxs(hh,{"aria-hidden":!0,required:h,tabIndex:-1,name:d,autoComplete:f,value:_,onChange:j=>P(j.target.value),disabled:p,form:x,children:[_===void 0?u.jsx("option",{value:""}):null,Array.from(F)]},z):null]})})};Wp.displayName=ar;var Vp="SelectTrigger",Kp=y.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=Vs(n),i=Bn(Vp,n),a=i.disabled||r,l=Ge(t,i.onTriggerChange),c=Ws(n),d=y.useRef("touch"),[f,p,h]=gh(m=>{const v=c().filter(S=>!S.disabled),g=v.find(S=>S.value===i.value),b=xh(v,m,g);b!==void 0&&i.onValueChange(b.value)}),x=m=>{a||(i.onOpenChange(!0),h()),m&&(i.triggerPointerDownPosRef.current={x:Math.round(m.pageX),y:Math.round(m.pageY)})};return u.jsx(au,{asChild:!0,...s,children:u.jsx(Oe.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":mh(i.value)?"":void 0,...o,ref:l,onClick:he(o.onClick,m=>{m.currentTarget.focus(),d.current!=="mouse"&&x(m)}),onPointerDown:he(o.onPointerDown,m=>{d.current=m.pointerType;const v=m.target;v.hasPointerCapture(m.pointerId)&&v.releasePointerCapture(m.pointerId),m.button===0&&m.ctrlKey===!1&&m.pointerType==="mouse"&&(x(m),m.preventDefault())}),onKeyDown:he(o.onKeyDown,m=>{const v=f.current!=="";!(m.ctrlKey||m.altKey||m.metaKey)&&m.key.length===1&&p(m.key),!(v&&m.key===" ")&&vC.includes(m.key)&&(x(),m.preventDefault())})})})});Kp.displayName=Vp;var qp="SelectValue",Gp=y.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=Bn(qp,n),{onValueNodeHasChildrenChange:c}=l,d=s!==void 0,f=Ge(t,l.onValueNodeChange);return _t(()=>{c(d)},[c,d]),u.jsx(Oe.span,{...a,ref:f,style:{pointerEvents:"none"},children:mh(l.value)?u.jsx(u.Fragment,{children:i}):s})});Gp.displayName=qp;var kC="SelectIcon",Yp=y.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return u.jsx(Oe.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});Yp.displayName=kC;var EC="SelectPortal",Xp=e=>u.jsx(Yo,{asChild:!0,...e});Xp.displayName=EC;var lr="SelectContent",Jp=y.forwardRef((e,t)=>{const n=Bn(lr,e.__scopeSelect),[r,o]=y.useState();if(_t(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?go.createPortal(u.jsx(Zp,{scope:e.__scopeSelect,children:u.jsx(Hs.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),s):null}return u.jsx(Qp,{...e,ref:t})});Jp.displayName=lr;var pn=10,[Zp,Un]=_r(lr),IC="SelectContentImpl",NC=qn.createSlot("SelectContent.RemoveScroll"),Qp=y.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:s,onPointerDownOutside:i,side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:p,collisionPadding:h,sticky:x,hideWhenDetached:m,avoidCollisions:v,...g}=e,b=Bn(lr,n),[S,k]=y.useState(null),[C,T]=y.useState(null),E=Ge(t,q=>k(q)),[N,_]=y.useState(null),[P,R]=y.useState(null),D=Ws(n),[F,A]=y.useState(!1),z=y.useRef(!1);y.useEffect(()=>{if(S)return zi(S)},[S]),wi();const j=y.useCallback(q=>{const[$,...V]=D().map(se=>se.ref.current),[re]=V.slice(-1),oe=document.activeElement;for(const se of q)if(se===oe||(se==null||se.scrollIntoView({block:"nearest"}),se===$&&C&&(C.scrollTop=0),se===re&&C&&(C.scrollTop=C.scrollHeight),se==null||se.focus(),document.activeElement!==oe))return},[D,C]),J=y.useCallback(()=>j([N,S]),[j,N,S]);y.useEffect(()=>{F&&J()},[F,J]);const{onOpenChange:B,triggerPointerDownPosRef:O}=b;y.useEffect(()=>{if(S){let q={x:0,y:0};const $=re=>{var oe,se;q={x:Math.abs(Math.round(re.pageX)-(((oe=O.current)==null?void 0:oe.x)??0)),y:Math.abs(Math.round(re.pageY)-(((se=O.current)==null?void 0:se.y)??0))}},V=re=>{q.x<=10&&q.y<=10?re.preventDefault():S.contains(re.target)||B(!1),document.removeEventListener("pointermove",$),O.current=null};return O.current!==null&&(document.addEventListener("pointermove",$),document.addEventListener("pointerup",V,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",$),document.removeEventListener("pointerup",V,{capture:!0})}}},[S,B,O]),y.useEffect(()=>{const q=()=>B(!1);return window.addEventListener("blur",q),window.addEventListener("resize",q),()=>{window.removeEventListener("blur",q),window.removeEventListener("resize",q)}},[B]);const[W,X]=gh(q=>{const $=D().filter(oe=>!oe.disabled),V=$.find(oe=>oe.ref.current===document.activeElement),re=xh($,q,V);re&&setTimeout(()=>re.ref.current.focus())}),fe=y.useCallback((q,$,V)=>{const re=!z.current&&!V;(b.value!==void 0&&b.value===$||re)&&(_(q),re&&(z.current=!0))},[b.value]),ae=y.useCallback(()=>S==null?void 0:S.focus(),[S]),Re=y.useCallback((q,$,V)=>{const re=!z.current&&!V;(b.value!==void 0&&b.value===$||re)&&R(q)},[b.value]),G=r==="popper"?za:eh,U=G===za?{side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:p,collisionPadding:h,sticky:x,hideWhenDetached:m,avoidCollisions:v}:{};return u.jsx(Zp,{scope:n,content:S,viewport:C,onViewportChange:T,itemRefCallback:fe,selectedItem:N,onItemLeave:ae,itemTextRefCallback:Re,focusSelectedItem:J,selectedItemText:P,position:r,isPositioned:F,searchRef:W,children:u.jsx(os,{as:NC,allowPinchZoom:!0,children:u.jsx(Lo,{asChild:!0,trapped:b.open,onMountAutoFocus:q=>{q.preventDefault()},onUnmountAutoFocus:he(o,q=>{var $;($=b.trigger)==null||$.focus({preventScroll:!0}),q.preventDefault()}),children:u.jsx(Do,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:q=>q.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:u.jsx(G,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:q=>q.preventDefault(),...g,...U,onPlaced:()=>A(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...g.style},onKeyDown:he(g.onKeyDown,q=>{const $=q.ctrlKey||q.altKey||q.metaKey;if(q.key==="Tab"&&q.preventDefault(),!$&&q.key.length===1&&X(q.key),["ArrowUp","ArrowDown","Home","End"].includes(q.key)){let re=D().filter(oe=>!oe.disabled).map(oe=>oe.ref.current);if(["ArrowUp","End"].includes(q.key)&&(re=re.slice().reverse()),["ArrowUp","ArrowDown"].includes(q.key)){const oe=q.target,se=re.indexOf(oe);re=re.slice(se+1)}setTimeout(()=>j(re)),q.preventDefault()}})})})})})})});Qp.displayName=IC;var AC="SelectItemAlignedPosition",eh=y.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=Bn(lr,n),i=Un(lr,n),[a,l]=y.useState(null),[c,d]=y.useState(null),f=Ge(t,E=>d(E)),p=Ws(n),h=y.useRef(!1),x=y.useRef(!0),{viewport:m,selectedItem:v,selectedItemText:g,focusSelectedItem:b}=i,S=y.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&c&&m&&v&&g){const E=s.trigger.getBoundingClientRect(),N=c.getBoundingClientRect(),_=s.valueNode.getBoundingClientRect(),P=g.getBoundingClientRect();if(s.dir!=="rtl"){const oe=P.left-N.left,se=_.left-oe,Se=E.left-se,Qe=E.width+Se,Fe=Math.max(Qe,N.width),Xe=window.innerWidth-pn,nt=Oa(se,[pn,Math.max(pn,Xe-Fe)]);a.style.minWidth=Qe+"px",a.style.left=nt+"px"}else{const oe=N.right-P.right,se=window.innerWidth-_.right-oe,Se=window.innerWidth-E.right-se,Qe=E.width+Se,Fe=Math.max(Qe,N.width),Xe=window.innerWidth-pn,nt=Oa(se,[pn,Math.max(pn,Xe-Fe)]);a.style.minWidth=Qe+"px",a.style.right=nt+"px"}const R=p(),D=window.innerHeight-pn*2,F=m.scrollHeight,A=window.getComputedStyle(c),z=parseInt(A.borderTopWidth,10),j=parseInt(A.paddingTop,10),J=parseInt(A.borderBottomWidth,10),B=parseInt(A.paddingBottom,10),O=z+j+F+B+J,W=Math.min(v.offsetHeight*5,O),X=window.getComputedStyle(m),fe=parseInt(X.paddingTop,10),ae=parseInt(X.paddingBottom,10),Re=E.top+E.height/2-pn,G=D-Re,U=v.offsetHeight/2,q=v.offsetTop+U,$=z+j+q,V=O-$;if($<=Re){const oe=R.length>0&&v===R[R.length-1].ref.current;a.style.bottom="0px";const se=c.clientHeight-m.offsetTop-m.offsetHeight,Se=Math.max(G,U+(oe?ae:0)+se+J),Qe=$+Se;a.style.height=Qe+"px"}else{const oe=R.length>0&&v===R[0].ref.current;a.style.top="0px";const Se=Math.max(Re,z+m.offsetTop+(oe?fe:0)+U)+V;a.style.height=Se+"px",m.scrollTop=$-Re+m.offsetTop}a.style.margin=`${pn}px 0`,a.style.minHeight=W+"px",a.style.maxHeight=D+"px",r==null||r(),requestAnimationFrame(()=>h.current=!0)}},[p,s.trigger,s.valueNode,a,c,m,v,g,s.dir,r]);_t(()=>S(),[S]);const[k,C]=y.useState();_t(()=>{c&&C(window.getComputedStyle(c).zIndex)},[c]);const T=y.useCallback(E=>{E&&x.current===!0&&(S(),b==null||b(),x.current=!1)},[S,b]);return u.jsx(jC,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:h,onScrollButtonChange:T,children:u.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k},children:u.jsx(Oe.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});eh.displayName=AC;var _C="SelectPopperPosition",za=y.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=pn,...s}=e,i=Vs(n);return u.jsx(lu,{...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)"}})});za.displayName=_C;var[jC,Ba]=_r(lr,{}),Ua="SelectViewport",th=y.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=Un(Ua,n),i=Ba(Ua,n),a=Ge(t,s.onViewportChange),l=y.useRef(0);return u.jsxs(u.Fragment,{children:[u.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}),u.jsx(Hs.Slot,{scope:n,children:u.jsx(Oe.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:he(o.onScroll,c=>{const d=c.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:p}=i;if(p!=null&&p.current&&f){const h=Math.abs(l.current-d.scrollTop);if(h>0){const x=window.innerHeight-pn*2,m=parseFloat(f.style.minHeight),v=parseFloat(f.style.height),g=Math.max(m,v);if(g<x){const b=g+h,S=Math.min(x,b),k=b-S;f.style.height=S+"px",f.style.bottom==="0px"&&(d.scrollTop=k>0?k:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});th.displayName=Ua;var nh="SelectGroup",[RC,PC]=_r(nh),OC=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=En();return u.jsx(RC,{scope:n,id:o,children:u.jsx(Oe.div,{role:"group","aria-labelledby":o,...r,ref:t})})});OC.displayName=nh;var rh="SelectLabel",oh=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=PC(rh,n);return u.jsx(Oe.div,{id:o.id,...r,ref:t})});oh.displayName=rh;var Ks="SelectItem",[MC,sh]=_r(Ks),ih=y.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=Bn(Ks,n),l=Un(Ks,n),c=a.value===r,[d,f]=y.useState(s??""),[p,h]=y.useState(!1),x=Ge(t,b=>{var S;return(S=l.itemRefCallback)==null?void 0:S.call(l,b,r,o)}),m=En(),v=y.useRef("touch"),g=()=>{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 u.jsx(MC,{scope:n,value:r,disabled:o,textId:m,isSelected:c,onItemTextChange:y.useCallback(b=>{f(S=>S||((b==null?void 0:b.textContent)??"").trim())},[]),children:u.jsx(Hs.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:u.jsx(Oe.div,{role:"option","aria-labelledby":m,"data-highlighted":p?"":void 0,"aria-selected":c&&p,"data-state":c?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:x,onFocus:he(i.onFocus,()=>h(!0)),onBlur:he(i.onBlur,()=>h(!1)),onClick:he(i.onClick,()=>{v.current!=="mouse"&&g()}),onPointerUp:he(i.onPointerUp,()=>{v.current==="mouse"&&g()}),onPointerDown:he(i.onPointerDown,b=>{v.current=b.pointerType}),onPointerMove:he(i.onPointerMove,b=>{var S;v.current=b.pointerType,o?(S=l.onItemLeave)==null||S.call(l):v.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:he(i.onPointerLeave,b=>{var S;b.currentTarget===document.activeElement&&((S=l.onItemLeave)==null||S.call(l))}),onKeyDown:he(i.onKeyDown,b=>{var k;((k=l.searchRef)==null?void 0:k.current)!==""&&b.key===" "||(bC.includes(b.key)&&g(),b.key===" "&&b.preventDefault())})})})})});ih.displayName=Ks;var ho="SelectItemText",ah=y.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=Bn(ho,n),a=Un(ho,n),l=sh(ho,n),c=TC(ho,n),[d,f]=y.useState(null),p=Ge(t,g=>f(g),l.onItemTextChange,g=>{var b;return(b=a.itemTextRefCallback)==null?void 0:b.call(a,g,l.value,l.disabled)}),h=d==null?void 0:d.textContent,x=y.useMemo(()=>u.jsx("option",{value:l.value,disabled:l.disabled,children:h},l.value),[l.disabled,l.value,h]),{onNativeOptionAdd:m,onNativeOptionRemove:v}=c;return _t(()=>(m(x),()=>v(x)),[m,v,x]),u.jsxs(u.Fragment,{children:[u.jsx(Oe.span,{id:l.textId,...s,ref:p}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?go.createPortal(s.children,i.valueNode):null]})});ah.displayName=ho;var lh="SelectItemIndicator",ch=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return sh(lh,n).isSelected?u.jsx(Oe.span,{"aria-hidden":!0,...r,ref:t}):null});ch.displayName=lh;var Ha="SelectScrollUpButton",uh=y.forwardRef((e,t)=>{const n=Un(Ha,e.__scopeSelect),r=Ba(Ha,e.__scopeSelect),[o,s]=y.useState(!1),i=Ge(t,r.onScrollButtonChange);return _t(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollTop>0;s(c)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(fh,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});uh.displayName=Ha;var Wa="SelectScrollDownButton",dh=y.forwardRef((e,t)=>{const n=Un(Wa,e.__scopeSelect),r=Ba(Wa,e.__scopeSelect),[o,s]=y.useState(!1),i=Ge(t,r.onScrollButtonChange);return _t(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollHeight-l.clientHeight,d=Math.ceil(l.scrollTop)<c;s(d)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(fh,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});dh.displayName=Wa;var fh=y.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=Un("SelectScrollButton",n),i=y.useRef(null),a=Ws(n),l=y.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return y.useEffect(()=>()=>l(),[l]),_t(()=>{var d;const c=a().find(f=>f.ref.current===document.activeElement);(d=c==null?void 0:c.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),u.jsx(Oe.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:he(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:he(o.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:he(o.onPointerLeave,()=>{l()})})}),DC="SelectSeparator",ph=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(Oe.div,{"aria-hidden":!0,...r,ref:t})});ph.displayName=DC;var Va="SelectArrow",LC=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Vs(n),s=Bn(Va,n),i=Un(Va,n);return s.open&&i.position==="popper"?u.jsx(cu,{...o,...r,ref:t}):null});LC.displayName=Va;var $C="SelectBubbleInput",hh=y.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=y.useRef(null),s=Ge(r,o),i=Up(t);return y.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]),u.jsx(Oe.select,{...n,style:{...Hp,...n.style},ref:s,defaultValue:t})});hh.displayName=$C;function mh(e){return e===""||e===void 0}function gh(e){const t=jt(e),n=y.useRef(""),r=y.useRef(0),o=y.useCallback(i=>{const a=n.current+i;t(a),function l(c){n.current=c,window.clearTimeout(r.current),c!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}(a)},[t]),s=y.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return y.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,s]}function xh(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=FC(e,Math.max(s,0));o.length===1&&(i=i.filter(c=>c!==n));const l=i.find(c=>c.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function FC(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var zC=Wp,yh=Kp,BC=Gp,UC=Yp,HC=Xp,vh=Jp,WC=th,bh=oh,wh=ih,VC=ah,KC=ch,Sh=uh,Ch=dh,Th=ph;const kh=zC,Eh=BC,Ka=y.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(yh,{ref:r,className:te("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,u.jsx(UC,{asChild:!0,children:u.jsx(ie.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Ka.displayName=yh.displayName;const Ih=y.forwardRef(({className:e,...t},n)=>u.jsx(Sh,{ref:n,className:te("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(ie.ChevronUp,{className:"h-4 w-4"})}));Ih.displayName=Sh.displayName;const Nh=y.forwardRef(({className:e,...t},n)=>u.jsx(Ch,{ref:n,className:te("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(ie.ChevronDown,{className:"h-4 w-4"})}));Nh.displayName=Ch.displayName;const qa=y.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>u.jsx(HC,{children:u.jsxs(vh,{ref:o,className:te("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:[u.jsx(Ih,{}),u.jsx(WC,{className:te("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(Nh,{})]})}));qa.displayName=vh.displayName;const qC=y.forwardRef(({className:e,...t},n)=>u.jsx(bh,{ref:n,className:te("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));qC.displayName=bh.displayName;const cr=y.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(wh,{ref:r,className:te("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:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(KC,{children:u.jsx(ie.Check,{className:"h-4 w-4"})})}),u.jsx(VC,{children:t})]}));cr.displayName=wh.displayName;const GC=y.forwardRef(({className:e,...t},n)=>u.jsx(Th,{ref:n,className:te("-mx-1 my-1 h-px bg-muted",e),...t}));GC.displayName=Th.displayName;var YC="Separator",Ah="horizontal",XC=["horizontal","vertical"],_h=y.forwardRef((e,t)=>{const{decorative:n,orientation:r=Ah,...o}=e,s=JC(r)?r:Ah,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return u.jsx(Oe.div,{"data-orientation":s,...a,...o,ref:t})});_h.displayName=YC;function JC(e){return XC.includes(e)}var jh=_h;const Rh=y.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>u.jsx(jh,{ref:o,decorative:n,orientation:t,className:te("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Rh.displayName=jh.displayName;const ZC=Kf,QC=mS,eT=qf,Ph=y.forwardRef(({className:e,...t},n)=>u.jsx(As,{className:te("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}));Ph.displayName=As.displayName;const tT=mo.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"}}),Oh=y.forwardRef(({side:e="right",className:t,children:n,...r},o)=>u.jsxs(eT,{children:[u.jsx(Ph,{}),u.jsxs(_s,{ref:o,className:te(tT({side:e}),t),...r,children:[n,u.jsxs(Gf,{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:[u.jsx(ie.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Oh.displayName=_s.displayName;const Mh=({className:e,...t})=>u.jsx("div",{className:te("flex flex-col space-y-2 text-center sm:text-left",e),...t});Mh.displayName="SheetHeader";const Dh=y.forwardRef(({className:e,...t},n)=>u.jsx(sr,{ref:n,className:te("text-lg font-semibold text-foreground",e),...t}));Dh.displayName=sr.displayName;const Lh=y.forwardRef(({className:e,...t},n)=>u.jsx(js,{ref:n,className:te("text-sm text-muted-foreground",e),...t}));Lh.displayName=js.displayName;var qs="Switch",[nT,BT]=kn(qs),[rT,oT]=nT(qs),$h=y.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:s,required:i,disabled:a,value:l="on",onCheckedChange:c,form:d,...f}=e,[p,h]=y.useState(null),x=Ge(t,S=>h(S)),m=y.useRef(!1),v=p?d||!!p.closest("form"):!0,[g,b]=gr({prop:o,defaultProp:s??!1,onChange:c,caller:qs});return u.jsxs(rT,{scope:n,checked:g,disabled:a,children:[u.jsx(Oe.button,{type:"button",role:"switch","aria-checked":g,"aria-required":i,"data-state":Uh(g),"data-disabled":a?"":void 0,disabled:a,value:l,...f,ref:x,onClick:he(e.onClick,S=>{b(k=>!k),v&&(m.current=S.isPropagationStopped(),m.current||S.stopPropagation())})}),v&&u.jsx(Bh,{control:p,bubbles:!m.current,name:r,value:l,checked:g,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});$h.displayName=qs;var Fh="SwitchThumb",zh=y.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=oT(Fh,n);return u.jsx(Oe.span,{"data-state":Uh(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});zh.displayName=Fh;var sT="SwitchBubbleInput",Bh=y.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=y.useRef(null),a=Ge(i,s),l=Up(n),c=Xc(t);return y.useEffect(()=>{const d=i.current;if(!d)return;const f=window.HTMLInputElement.prototype,h=Object.getOwnPropertyDescriptor(f,"checked").set;if(l!==n&&h){const x=new Event("click",{bubbles:r});h.call(d,n),d.dispatchEvent(x)}},[l,n,r]),u.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...o,tabIndex:-1,ref:a,style:{...o.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Bh.displayName=sT;function Uh(e){return e?"checked":"unchecked"}var Hh=$h,iT=zh;const Hn=y.forwardRef(({className:e,...t},n)=>u.jsx(Hh,{className:te("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:u.jsx(iT,{className:te("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")})}));Hn.displayName=Hh.displayName;const aT={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 lT({settings:e,onSettingsChange:t,className:n=""}){const[r,o]=w.useState(!1),[s,i]=w.useState(!1),[a,l]=w.useState(e),[c,d]=w.useState(!1),{toast:f}=ka();w.useEffect(()=>{const v=JSON.stringify(a)!==JSON.stringify(e);d(v)},[a,e]),w.useEffect(()=>{l(e)},[e]);const p=()=>{t(a),d(!1),f({title:"Settings saved",description:"Your chat configuration has been updated successfully."})},h=()=>{l(aT),d(!0),f({title:"Settings reset",description:"Configuration has been reset to defaults."})},x=()=>{l(e),d(!1),o(!1)},m=async()=>{try{const g=await(await fetch(`${a.api.baseUrl}/health`)).json();f({title:"Connection successful",description:`API is ${g.status||"healthy"}`})}catch{f({title:"Connection failed",description:"Unable to connect to the API endpoint.",variant:"destructive"})}};return u.jsxs(ZC,{open:r,onOpenChange:o,children:[u.jsx(QC,{asChild:!0,children:u.jsxs(st,{variant:"outline",size:"sm",className:n,children:[u.jsx(ie.Settings,{className:"h-4 w-4 mr-2"}),"Settings",c&&u.jsx(Cf,{variant:"destructive",className:"ml-2 h-4 w-4 p-0"})]})}),u.jsxs(Oh,{className:"w-[500px] sm:w-[600px] overflow-y-auto",children:[u.jsxs(Mh,{children:[u.jsx(Dh,{children:"Chat Settings"}),u.jsx(Lh,{children:"Configure your chat interface, API connection, and behavior preferences."})]}),u.jsxs("div",{className:"space-y-6 py-6",children:[u.jsxs(so,{children:[u.jsx(io,{className:"pb-3",children:u.jsxs(ao,{className:"text-lg flex items-center gap-2",children:[u.jsx(ie.Server,{className:"h-5 w-5"}),"API Configuration"]})}),u.jsxs(lo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(on,{htmlFor:"api-url",children:"API Base URL"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx($s,{id:"api-url",value:a.api.baseUrl,onChange:v=>l(g=>({...g,api:{...g.api,baseUrl:v.target.value}})),placeholder:"http://localhost:8000/api"}),u.jsx(st,{variant:"outline",onClick:m,children:"Test"})]})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(on,{htmlFor:"enable-auth",children:"Enable Authentication"}),u.jsx(Hn,{id:"enable-auth",checked:a.api.enableAuth,onCheckedChange:v=>l(g=>({...g,api:{...g.api,enableAuth:v}}))})]}),a.api.enableAuth&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(on,{htmlFor:"auth-token",children:"Authentication Token"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx($s,{id:"auth-token",type:s?"text":"password",value:a.api.authToken,onChange:v=>l(g=>({...g,api:{...g.api,authToken:v.target.value}})),placeholder:"Enter your Bearer token"}),u.jsx(st,{variant:"outline",size:"icon",onClick:()=>i(!s),children:s?u.jsx(ie.EyeOff,{className:"h-4 w-4"}):u.jsx(ie.Eye,{className:"h-4 w-4"})})]})]})]})]}),u.jsxs(so,{children:[u.jsx(io,{className:"pb-3",children:u.jsxs(ao,{className:"text-lg flex items-center gap-2",children:[u.jsx(ie.Layout,{className:"h-5 w-5"}),"Interface Settings"]})}),u.jsxs(lo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(on,{htmlFor:"layout",children:"Layout Style"}),u.jsxs(kh,{value:a.ui.layout,onValueChange:v=>l(g=>({...g,ui:{...g.ui,layout:v}})),children:[u.jsx(Ka,{children:u.jsx(Eh,{})}),u.jsxs(qa,{children:[u.jsx(cr,{value:"sidebar",children:"Sidebar Layout"}),u.jsx(cr,{value:"fullscreen",children:"Fullscreen"}),u.jsx(cr,{value:"tabs",children:"Tabbed Interface"})]})]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(on,{htmlFor:"theme",children:"Theme"}),u.jsxs(kh,{value:a.ui.theme,onValueChange:v=>l(g=>({...g,ui:{...g.ui,theme:v}})),children:[u.jsx(Ka,{children:u.jsx(Eh,{})}),u.jsxs(qa,{children:[u.jsx(cr,{value:"light",children:"Light"}),u.jsx(cr,{value:"dark",children:"Dark"}),u.jsx(cr,{value:"system",children:"System"})]})]})]}),u.jsx(Rh,{}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(on,{htmlFor:"show-timestamps",children:"Show Timestamps"}),u.jsx(Hn,{id:"show-timestamps",checked:a.ui.showTimestamps,onCheckedChange:v=>l(g=>({...g,ui:{...g.ui,showTimestamps:v}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(on,{htmlFor:"show-agent-names",children:"Show Agent Names"}),u.jsx(Hn,{id:"show-agent-names",checked:a.ui.showAgentNames,onCheckedChange:v=>l(g=>({...g,ui:{...g.ui,showAgentNames:v}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(on,{htmlFor:"compact-messages",children:"Compact Messages"}),u.jsx(Hn,{id:"compact-messages",checked:a.ui.compactMessages,onCheckedChange:v=>l(g=>({...g,ui:{...g.ui,compactMessages:v}}))})]})]})]})]}),u.jsxs(so,{children:[u.jsx(io,{className:"pb-3",children:u.jsxs(ao,{className:"text-lg flex items-center gap-2",children:[u.jsx(ie.MessageCircle,{className:"h-5 w-5"}),"Behavior Settings"]})}),u.jsxs(lo,{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(on,{htmlFor:"auto-save",children:"Auto-save Conversations"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically save messages to threads"})]}),u.jsx(Hn,{id:"auto-save",checked:a.behavior.autoSave,onCheckedChange:v=>l(g=>({...g,behavior:{...g.behavior,autoSave:v}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(on,{htmlFor:"enable-streaming",children:"Enable Streaming"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Stream responses in real-time"})]}),u.jsx(Hn,{id:"enable-streaming",checked:a.behavior.enableStreaming,onCheckedChange:v=>l(g=>({...g,behavior:{...g.behavior,enableStreaming:v}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(on,{htmlFor:"typing-indicator",children:"Typing Indicator"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Show typing indicator during responses"})]}),u.jsx(Hn,{id:"typing-indicator",checked:a.behavior.showTypingIndicator,onCheckedChange:v=>l(g=>({...g,behavior:{...g.behavior,showTypingIndicator:v}}))})]})]})]})]}),u.jsxs("div",{className:"flex items-center justify-between pt-6 border-t",children:[u.jsxs(st,{variant:"outline",onClick:h,children:[u.jsx(ie.RotateCcw,{className:"h-4 w-4 mr-2"}),"Reset"]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(st,{variant:"outline",onClick:x,children:"Cancel"}),u.jsxs(st,{onClick:p,disabled:!c,children:[u.jsx(ie.Save,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})]})}function cT({layout:e="sidebar",layoutSize:t="desktop",showThreads:n=!0,className:r="",customStyles:o={},...s}){const i=c=>{const d="h-full";switch(c){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=c=>({"--chat-sidebar-width":c==="phone"?"100%":c==="tablet"?"280px":c==="half-screen"?"240px":"320px","--chat-message-max-width":c==="phone"?"95%":c==="tablet"?"90%":c==="half-screen"?"85%":"80%","--chat-input-height":c==="phone"?"120px":"100px"}),l=w.useCallback(c=>{var d;(d=s.onThreadChange)==null||d.call(s,c)},[s]);return e==="fullscreen"?u.jsx(Oo,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsx(Ls,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?u.jsx(Oo,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsxs("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:[n&&u.jsx("div",{className:`w-80 border-r flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(Fa,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx(Ls,{onError:s.onError,enableFileUpload:!0})})]})})}):u.jsx(Oo,{...s,onThreadChange:l,children:u.jsxs("div",{className:`${i(t)} flex overflow-hidden ${r} ${o.container||""}`,style:a(t),children:[n&&u.jsx("div",{className:`w-80 border-r bg-gray-50 flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(Fa,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx(Ls,{onError:s.onError,enableFileUpload:!0})})]})})}Ne.ChatApi=Vl,Ne.ChatInput=hc,Ne.ChatInterface=Ls,Ne.ChatProviders=Oo,Ne.ChatSettings=lT,Ne.MarkdownContent=po,Ne.MessageComponent=Ra,Ne.MessageList=Pa,Ne.ThreadManager=Fa,Ne.applySettings=hC,Ne.buildMessagePreviewMap=Zl,Ne.chatApiClient=jn,Ne.default=cT,Ne.del=Wl,Ne.get=Jt,Ne.getChatToken=Bl,Ne.getCurrentSettings=pC,Ne.getDefaultApiConfig=Lp,Ne.getDefaultChatSettings=$p,Ne.onChatTokenChanged=Ul,Ne.post=ui,Ne.put=Hl,Ne.setChatToken=No,Ne.useApi=di,Ne.useChatStream=Ql,Ne.useMessagesReducer=ec,Ne.useStream=fc,Ne.useThreadState=Po,Ne.useThreads=Ro,Object.defineProperties(Ne,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});