orbitchat 3.11.10 → 3.11.11

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.
Files changed (52) hide show
  1. package/dist/assets/{ChartRenderer-CCrXq7kR.js → ChartRenderer-Dl6Q8n8G.js} +1 -1
  2. package/dist/assets/{MermaidRenderer-A09LzrdE.js → MermaidRenderer-DABRS6vO.js} +4 -4
  3. package/dist/assets/{MusicRenderer-DwFODlWd.js → MusicRenderer-DhhgLEOM.js} +1 -1
  4. package/dist/assets/{SVGRenderer-DLsB46JM.js → SVGRenderer-DjrOz9Zj.js} +1 -1
  5. package/dist/assets/{architectureDiagram-3BPJPVTR-T7zHWeVb.js → architectureDiagram-3BPJPVTR-DE9p7DqJ.js} +1 -1
  6. package/dist/assets/{blockDiagram-GPEHLZMM-CaeP2MGH.js → blockDiagram-GPEHLZMM-BlqSr47-.js} +1 -1
  7. package/dist/assets/{c4Diagram-AAUBKEIU-B7MySRCv.js → c4Diagram-AAUBKEIU-BTJyz3Dj.js} +1 -1
  8. package/dist/assets/channel-B_bfJYMv.js +1 -0
  9. package/dist/assets/{chunk-2J33WTMH-Cr39EA9i.js → chunk-2J33WTMH-C3FjBYqe.js} +1 -1
  10. package/dist/assets/{chunk-4BX2VUAB-CvlYh7sK.js → chunk-4BX2VUAB-SsvX7aRT.js} +1 -1
  11. package/dist/assets/{chunk-55IACEB6-C3__9MKa.js → chunk-55IACEB6-CIX6iTod.js} +1 -1
  12. package/dist/assets/{chunk-727SXJPM-Dp1P9Wrn.js → chunk-727SXJPM-BSsG5j2X.js} +1 -1
  13. package/dist/assets/{chunk-AQP2D5EJ-CbH8mC11.js → chunk-AQP2D5EJ-DMJX99gb.js} +1 -1
  14. package/dist/assets/{chunk-FMBD7UC4-DWzuQnZ-.js → chunk-FMBD7UC4-C7BbG1p3.js} +1 -1
  15. package/dist/assets/{chunk-ND2GUHAM-oHUu5FId.js → chunk-ND2GUHAM-BzPlsMer.js} +1 -1
  16. package/dist/assets/{chunk-QZHKN3VN-gmSqZB6F.js → chunk-QZHKN3VN-MJcbc2N-.js} +1 -1
  17. package/dist/assets/classDiagram-4FO5ZUOK-BbL1zWQQ.js +1 -0
  18. package/dist/assets/classDiagram-v2-Q7XG4LA2-BbL1zWQQ.js +1 -0
  19. package/dist/assets/{cose-bilkent-S5V4N54A-Dw41ubkb.js → cose-bilkent-S5V4N54A-C41I5ueg.js} +1 -1
  20. package/dist/assets/{dagre-BM42HDAG-BhCOaQ2W.js → dagre-BM42HDAG-DXP_Z5ds.js} +1 -1
  21. package/dist/assets/{diagram-2AECGRRQ-DYM2NnFn.js → diagram-2AECGRRQ-BsgnoZNr.js} +1 -1
  22. package/dist/assets/{diagram-5GNKFQAL-BaK-H3LS.js → diagram-5GNKFQAL-DNC-YlEk.js} +1 -1
  23. package/dist/assets/{diagram-KO2AKTUF-atNCKT9A.js → diagram-KO2AKTUF-D0xNGJUK.js} +1 -1
  24. package/dist/assets/{diagram-LMA3HP47-BxQ0ztgq.js → diagram-LMA3HP47-YahrQIFx.js} +1 -1
  25. package/dist/assets/{diagram-OG6HWLK6-DD0B-jxQ.js → diagram-OG6HWLK6-F6nQx0QL.js} +1 -1
  26. package/dist/assets/{erDiagram-TEJ5UH35-CKxyKoFJ.js → erDiagram-TEJ5UH35-uLldWH4y.js} +1 -1
  27. package/dist/assets/{flowDiagram-I6XJVG4X-ZqWMKMPZ.js → flowDiagram-I6XJVG4X-BLqYPptO.js} +1 -1
  28. package/dist/assets/{ganttDiagram-6RSMTGT7-DotYh_Md.js → ganttDiagram-6RSMTGT7-BHmnmCh5.js} +1 -1
  29. package/dist/assets/{gitGraphDiagram-PVQCEYII-Di8yRQFr.js → gitGraphDiagram-PVQCEYII-zGZRc9-Y.js} +1 -1
  30. package/dist/assets/index-Bn1wDYpA.js +376 -0
  31. package/dist/assets/{infoDiagram-5YYISTIA-D7fTFpy1.js → infoDiagram-5YYISTIA-C-WFJ-Wl.js} +1 -1
  32. package/dist/assets/{ishikawaDiagram-YF4QCWOH-CGD2n02P.js → ishikawaDiagram-YF4QCWOH-DAiQwoYQ.js} +1 -1
  33. package/dist/assets/{journeyDiagram-JHISSGLW-BknW9hgH.js → journeyDiagram-JHISSGLW-CZkuusEQ.js} +1 -1
  34. package/dist/assets/{kanban-definition-UN3LZRKU-D_7-hvSz.js → kanban-definition-UN3LZRKU-rzFlU4vu.js} +1 -1
  35. package/dist/assets/{mindmap-definition-RKZ34NQL-CcQhTMWo.js → mindmap-definition-RKZ34NQL-Bdk2sflj.js} +1 -1
  36. package/dist/assets/{pieDiagram-4H26LBE5-DsAzTX-s.js → pieDiagram-4H26LBE5-DX4jD51d.js} +1 -1
  37. package/dist/assets/{quadrantDiagram-W4KKPZXB-Drew7FRJ.js → quadrantDiagram-W4KKPZXB-CFTdwoep.js} +1 -1
  38. package/dist/assets/{requirementDiagram-4Y6WPE33-DCBo6YYc.js → requirementDiagram-4Y6WPE33-D8iyWT_K.js} +1 -1
  39. package/dist/assets/{sankeyDiagram-5OEKKPKP-BdCP_Kx6.js → sankeyDiagram-5OEKKPKP-EoCfbhAo.js} +1 -1
  40. package/dist/assets/{sequenceDiagram-3UESZ5HK-DspnkgEH.js → sequenceDiagram-3UESZ5HK-DGaK60xH.js} +1 -1
  41. package/dist/assets/{stateDiagram-AJRCARHV-wD4RP_W7.js → stateDiagram-AJRCARHV-CqMufEdo.js} +1 -1
  42. package/dist/assets/{stateDiagram-v2-BHNVJYJU-WK6ws0K2.js → stateDiagram-v2-BHNVJYJU-Cr4h60cY.js} +1 -1
  43. package/dist/assets/{timeline-definition-PNZ67QCA-B3MvfA9Z.js → timeline-definition-PNZ67QCA-vItoJc0t.js} +1 -1
  44. package/dist/assets/{vennDiagram-CIIHVFJN-DILGMAAR.js → vennDiagram-CIIHVFJN-Di5EHX6_.js} +1 -1
  45. package/dist/assets/{wardleyDiagram-YWT4CUSO-z6JFT4rR.js → wardleyDiagram-YWT4CUSO-DAPdWBli.js} +1 -1
  46. package/dist/assets/{xychartDiagram-2RQKCTM6-BycLxqUf.js → xychartDiagram-2RQKCTM6-DBhhRQSk.js} +1 -1
  47. package/dist/index.html +1 -1
  48. package/package.json +1 -1
  49. package/dist/assets/channel-DugFdw6v.js +0 -1
  50. package/dist/assets/classDiagram-4FO5ZUOK-CujsjY5Y.js +0 -1
  51. package/dist/assets/classDiagram-v2-Q7XG4LA2-CujsjY5Y.js +0 -1
  52. package/dist/assets/index-qkqlLUVz.js +0 -376
@@ -0,0 +1,376 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MermaidRenderer-DABRS6vO.js","assets/vendor-react-BbEy7z12.js","assets/vendor-syntax-INF7-xC_.js","assets/purify.es-D6gMnemd.js","assets/isPrototype-DezZrpQP.js","assets/graphExportUtils-DrqBjeAI.js","assets/SVGRenderer-DjrOz9Zj.js","assets/locales-CcBtm6Ky.js","assets/vendor-markdown-Cy_-N5ZX.js","assets/vendor-markdown-dRWncRqa.css","assets/vendor-auth-aD_bwYde.js","assets/ChartRenderer-Dl6Q8n8G.js","assets/band-CquvqAHh.js","assets/init-Dmth1JHB.js","assets/ordinal-DILIJJjt.js","assets/linear-BGneeY6s.js","assets/defaultLocale-DX6XiGOO.js","assets/time-DJ0lCX4i.js","assets/MusicRenderer-DhhgLEOM.js","assets/papaparse.min-D13ujVVP.js","assets/docx-preview-DehBmhog.js"])))=>i.map(i=>d[i]);
2
+ var Uo=Object.defineProperty;var Oo=(t,e,r)=>e in t?Uo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Ze=(t,e,r)=>Oo(t,typeof e!="symbol"?e+"":e,r);import{r as h,j as i,a as zo,R as gt,b as As,d as Bo}from"./vendor-react-BbEy7z12.js";import{z as Ho,p as Vo,j as qo,f as Wo,e as Ko,a as Go,d as Xo}from"./locales-CcBtm6Ky.js";import{M as Yo,r as oa,a as Qo,b as Zo}from"./vendor-markdown-Cy_-N5ZX.js";import{_ as Nt,h as Jo,v as el,a as tl}from"./vendor-syntax-INF7-xC_.js";import{u as Nn,a as In,b as rl,P as sl,M as nl,A as al}from"./vendor-auth-aD_bwYde.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function r(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function n(s){if(s.ep)return;s.ep=!0;const a=r(s);fetch(s.href,a)}})();const gi=h.createContext(void 0);function la({children:t}){const[e,r]=h.useState(()=>{const o=localStorage.getItem("chat-theme");if(o){const l=JSON.parse(o);return{mode:l.mode||"dark",highContrast:!!l.highContrast}}return{mode:"dark",highContrast:!1}}),[n,s]=h.useState(!1);h.useEffect(()=>{const o=()=>{let l=!1;e.mode==="dark"?l=!0:e.mode==="light"?l=!1:l=window.matchMedia("(prefers-color-scheme: dark)").matches,s(l);const c=document.documentElement;c.dataset.theme=l?"dark":"light",l?c.classList.add("dark"):c.classList.remove("dark"),e.highContrast?c.classList.add("high-contrast"):c.classList.remove("high-contrast"),c.classList.remove("text-sm","text-lg"),c.classList.add("text-base")};if(o(),e.mode==="system"){const l=window.matchMedia("(prefers-color-scheme: dark)"),c=()=>{o()};return l.addEventListener("change",c),()=>l.removeEventListener("change",c)}},[e]),h.useEffect(()=>{localStorage.setItem("chat-theme",JSON.stringify(e))},[e]);const a=o=>{r(l=>({...l,...o}))};return i.jsx(gi.Provider,{value:{theme:e,updateTheme:a,isDark:n},children:t})}function tr(){const t=h.useContext(gi);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}const xi=h.createContext(void 0),Xs={voiceEnabled:!1,soundEnabled:!1,autoSend:!1};function il({children:t}){const[e,r]=h.useState(()=>{const s=localStorage.getItem("chat-settings");if(s)try{const a=JSON.parse(s);return{...Xs,...a,voiceEnabled:!1}}catch{return Xs}return Xs});h.useEffect(()=>{localStorage.setItem("chat-settings",JSON.stringify(e))},[e]);const n=s=>{r(a=>({...a,...s}))};return i.jsx(xi.Provider,{value:{settings:e,updateSettings:n},children:t})}function Ns(){const t=h.useContext(xi);if(!t)throw new Error("useSettings must be used within SettingsProvider");return t}const he=t=>typeof t=="string",Ir=()=>{let t,e;const r=new Promise((n,s)=>{t=n,e=s});return r.resolve=t,r.reject=e,r},ca=t=>t==null?"":String(t),ol=(t,e,r)=>{t.forEach(n=>{e[n]&&(r[n]=e[n])})},ll=/###/g,da=t=>t&&t.includes("###")?t.replace(ll,"."):t,ua=t=>!t||he(t),Tr=(t,e,r)=>{const n=he(e)?e.split("."):e;let s=0;for(;s<n.length-1;){if(ua(t))return{};const a=da(n[s]);!t[a]&&r&&(t[a]=new r),Object.prototype.hasOwnProperty.call(t,a)?t=t[a]:t={},++s}return ua(t)?{}:{obj:t,k:da(n[s])}},fa=(t,e,r)=>{const{obj:n,k:s}=Tr(t,e,Object);if(n!==void 0||e.length===1){n[s]=r;return}let a=e[e.length-1],o=e.slice(0,e.length-1),l=Tr(t,o,Object);for(;l.obj===void 0&&o.length;)a=`${o[o.length-1]}.${a}`,o=o.slice(0,o.length-1),l=Tr(t,o,Object),l!=null&&l.obj&&typeof l.obj[`${l.k}.${a}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${a}`]=r},cl=(t,e,r,n)=>{const{obj:s,k:a}=Tr(t,e,Object);s[a]=s[a]||[],s[a].push(r)},ps=(t,e)=>{const{obj:r,k:n}=Tr(t,e);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},dl=(t,e,r)=>{const n=ps(t,r);return n!==void 0?n:ps(e,r)},bi=(t,e,r)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(Object.prototype.hasOwnProperty.call(t,n)?he(t[n])||t[n]instanceof String||he(e[n])||e[n]instanceof String?r&&(t[n]=e[n]):bi(t[n],e[n],r):t[n]=e[n]);return t},Mt=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),ul={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"},fl=t=>he(t)?t.replace(/[&<>"'\/]/g,e=>ul[e]):t;class hl{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const r=this.regExpMap.get(e);if(r!==void 0)return r;const n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}}const ml=[" ",",","?","!",";"],pl=new hl(20),gl=(t,e,r)=>{e=e||"",r=r||"";const n=ml.filter(o=>!e.includes(o)&&!r.includes(o));if(n.length===0)return!0;const s=pl.getRegExp(`(${n.map(o=>o==="?"?"\\?":o).join("|")})`);let a=!s.test(t);if(!a){const o=t.indexOf(r);o>0&&!s.test(t.substring(0,o))&&(a=!0)}return a},dn=(t,e,r=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const n=e.split(r);let s=t;for(let a=0;a<n.length;){if(!s||typeof s!="object")return;let o,l="";for(let c=a;c<n.length;++c)if(c!==a&&(l+=r),l+=n[c],o=s[l],o!==void 0){if(["string","number","boolean"].includes(typeof o)&&c<n.length-1)continue;a+=c-a+1;break}s=o}return s},Rr=t=>t==null?void 0:t.replace(/_/g,"-"),xl={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){var r,n;(n=(r=console==null?void 0:console[t])==null?void 0:r.apply)==null||n.call(r,console,e)}};class gs{constructor(e,r={}){this.init(e,r)}init(e,r={}){this.prefix=r.prefix||"i18next:",this.logger=e||xl,this.options=r,this.debug=r.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,r,n,s){return s&&!this.debug?null:(e=e.map(a=>he(a)?a.replace(/[\r\n\x00-\x1F\x7F]/g," "):a),he(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[r](e))}create(e){return new gs(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new gs(this.logger,e)}}var It=new gs;class Is{constructor(){this.observers={}}on(e,r){return e.split(" ").forEach(n=>{this.observers[n]||(this.observers[n]=new Map);const s=this.observers[n].get(r)||0;this.observers[n].set(r,s+1)}),this}off(e,r){if(this.observers[e]){if(!r){delete this.observers[e];return}this.observers[e].delete(r)}}once(e,r){const n=(...s)=>{r(...s),this.off(e,n)};return this.on(e,n),this}emit(e,...r){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([s,a])=>{for(let o=0;o<a;o++)s(...r)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([s,a])=>{for(let o=0;o<a;o++)s(e,...r)})}}class ha extends Is{constructor(e,r={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.includes(e)||this.options.ns.push(e)}removeNamespaces(e){const r=this.options.ns.indexOf(e);r>-1&&this.options.ns.splice(r,1)}getResource(e,r,n,s={}){var d,u;const a=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,o=s.ignoreJSONStructure!==void 0?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let l;e.includes(".")?l=e.split("."):(l=[e,r],n&&(Array.isArray(n)?l.push(...n):he(n)&&a?l.push(...n.split(a)):l.push(n)));const c=ps(this.data,l);return!c&&!r&&!n&&e.includes(".")&&(e=l[0],r=l[1],n=l.slice(2).join(".")),c||!o||!he(n)?c:dn((u=(d=this.data)==null?void 0:d[e])==null?void 0:u[r],n,a)}addResource(e,r,n,s,a={silent:!1}){const o=a.keySeparator!==void 0?a.keySeparator:this.options.keySeparator;let l=[e,r];n&&(l=l.concat(o?n.split(o):n)),e.includes(".")&&(l=e.split("."),s=r,r=l[1]),this.addNamespaces(r),fa(this.data,l,s),a.silent||this.emit("added",e,r,n,s)}addResources(e,r,n,s={silent:!1}){for(const a in n)(he(n[a])||Array.isArray(n[a]))&&this.addResource(e,r,a,n[a],{silent:!0});s.silent||this.emit("added",e,r,n)}addResourceBundle(e,r,n,s,a,o={silent:!1,skipCopy:!1}){let l=[e,r];e.includes(".")&&(l=e.split("."),s=n,n=r,r=l[1]),this.addNamespaces(r);let c=ps(this.data,l)||{};o.skipCopy||(n=JSON.parse(JSON.stringify(n))),s?bi(c,n,a):c={...c,...n},fa(this.data,l,c),o.silent||this.emit("added",e,r,n)}removeResourceBundle(e,r){this.hasResourceBundle(e,r)&&delete this.data[e][r],this.removeNamespaces(r),this.emit("removed",e,r)}hasResourceBundle(e,r){return this.getResource(e,r)!==void 0}getResourceBundle(e,r){return r||(r=this.options.defaultNS),this.getResource(e,r)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const r=this.getDataByLanguage(e);return!!(r&&Object.keys(r)||[]).find(s=>r[s]&&Object.keys(r[s]).length>0)}toJSON(){return this.data}}var yi={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,r,n,s){return t.forEach(a=>{var o;e=((o=this.processors[a])==null?void 0:o.process(e,r,n,s))??e}),e}};const wi=Symbol("i18next/PATH_KEY");function bl(){const t=[],e=Object.create(null);let r;return e.get=(n,s)=>{var a;return(a=r==null?void 0:r.revoke)==null||a.call(r),s===wi?t:(t.push(s),r=Proxy.revocable(n,e),r.proxy)},Proxy.revocable(Object.create(null),e).proxy}function dr(t,e){const{[wi]:r}=t(bl()),n=(e==null?void 0:e.keySeparator)??".",s=(e==null?void 0:e.nsSeparator)??":",a=(e==null?void 0:e.enableSelector)==="strict";if(r.length>1&&s){const o=e==null?void 0:e.ns,l=a?Array.isArray(o)?o:o?[o]:null:Array.isArray(o)?o:null;if(l&&(a?l:l.length>1?l.slice(1):[]).includes(r[0]))return`${r[0]}${s}${r.slice(1).join(n)}`}return r.join(n)}const Ys=t=>!he(t)&&typeof t!="boolean"&&typeof t!="number";class xs extends Is{constructor(e,r={}){super(),ol(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=It.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,r={interpolation:{}}){const n={...r};if(e==null)return!1;const s=this.resolve(e,n);if((s==null?void 0:s.res)===void 0)return!1;const a=Ys(s.res);return!(n.returnObjects===!1&&a)}extractFromKey(e,r){let n=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;n===void 0&&(n=":");const s=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator;let a=r.ns||this.options.defaultNS||[];const o=n&&e.includes(n),l=!this.options.userDefinedKeySeparator&&!r.keySeparator&&!this.options.userDefinedNsSeparator&&!r.nsSeparator&&!gl(e,n,s);if(o&&!l){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:he(a)?[a]:a};const d=e.split(n);(n!==s||n===s&&this.options.ns.includes(d[0]))&&(a=d.shift()),e=d.join(s)}return{key:e,namespaces:he(a)?[a]:a}}translate(e,r,n){let s=typeof r=="object"?{...r}:r;if(typeof s!="object"&&this.options.overloadTranslationOptionHandler&&(s=this.options.overloadTranslationOptionHandler(arguments)),typeof s=="object"&&(s={...s}),s||(s={}),e==null)return"";typeof e=="function"&&(e=dr(e,{...this.options,...s})),Array.isArray(e)||(e=[String(e)]),e=e.map(T=>typeof T=="function"?dr(T,{...this.options,...s}):String(T));const a=s.returnDetails!==void 0?s.returnDetails:this.options.returnDetails,o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,{key:l,namespaces:c}=this.extractFromKey(e[e.length-1],s),d=c[c.length-1];let u=s.nsSeparator!==void 0?s.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const f=s.lng||this.language,m=s.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if((f==null?void 0:f.toLowerCase())==="cimode")return m?a?{res:`${d}${u}${l}`,usedKey:l,exactUsedKey:l,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(s)}:`${d}${u}${l}`:a?{res:l,usedKey:l,exactUsedKey:l,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(s)}:l;const g=this.resolve(e,s);let p=g==null?void 0:g.res;const x=(g==null?void 0:g.usedKey)||l,y=(g==null?void 0:g.exactUsedKey)||l,v=["[object Number]","[object Function]","[object RegExp]"],A=s.joinArrays!==void 0?s.joinArrays:this.options.joinArrays,I=!this.i18nFormat||this.i18nFormat.handleAsObject,C=s.count!==void 0&&!he(s.count),S=xs.hasDefaultValue(s),E=C?this.pluralResolver.getSuffix(f,s.count,s):"",_=s.ordinal&&C?this.pluralResolver.getSuffix(f,s.count,{ordinal:!1}):"",b=C&&!s.ordinal&&s.count===0,F=b&&s[`defaultValue${this.options.pluralSeparator}zero`]||s[`defaultValue${E}`]||s[`defaultValue${_}`]||s.defaultValue;let k=p;I&&!p&&S&&(k=F);const N=Ys(k),U=Object.prototype.toString.apply(k);if(I&&k&&N&&!v.includes(U)&&!(he(A)&&Array.isArray(k))){if(!s.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const T=this.options.returnedObjectHandler?this.options.returnedObjectHandler(x,k,{...s,ns:c}):`key '${l} (${this.language})' returned an object instead of string.`;return a?(g.res=T,g.usedParams=this.getUsedParamsDetails(s),g):T}if(o){const T=Array.isArray(k),H=T?[]:{},j=T?y:x;for(const L in k)if(Object.prototype.hasOwnProperty.call(k,L)){const O=`${j}${o}${L}`;S&&!p?H[L]=this.translate(O,{...s,defaultValue:Ys(F)?F[L]:void 0,joinArrays:!1,ns:c}):H[L]=this.translate(O,{...s,joinArrays:!1,ns:c}),H[L]===O&&(H[L]=k[L])}p=H}}else if(I&&he(A)&&Array.isArray(p))p=p.join(A),p&&(p=this.extendTranslation(p,e,s,n));else{let T=!1,H=!1;!this.isValidLookup(p)&&S&&(T=!0,p=F),this.isValidLookup(p)||(H=!0,p=l);const L=(s.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&H?void 0:p,O=S&&F!==p&&this.options.updateMissing;if(H||T||O){if(this.logger.log(O?"updateKey":"missingKey",f,d,C&&!O?`${l}${this.pluralResolver.getSuffix(f,s.count,s)}`:l,O?F:p),o){const V=this.resolve(l,{...s,keySeparator:!1});V&&V.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let M=[];const Y=this.languageUtils.getFallbackCodes(this.options.fallbackLng,s.lng||this.language);if(this.options.saveMissingTo==="fallback"&&Y&&Y[0])for(let V=0;V<Y.length;V++)M.push(Y[V]);else this.options.saveMissingTo==="all"?M=this.languageUtils.toResolveHierarchy(s.lng||this.language):M.push(s.lng||this.language);const G=(V,J,ue)=>{var $;const Ee=S&&ue!==p?ue:L;this.options.missingKeyHandler?this.options.missingKeyHandler(V,d,J,Ee,O,s):($=this.backendConnector)!=null&&$.saveMissing&&this.backendConnector.saveMissing(V,d,J,Ee,O,s),this.emit("missingKey",V,d,J,p)};this.options.saveMissing&&(this.options.saveMissingPlurals&&C?M.forEach(V=>{const J=this.pluralResolver.getSuffixes(V,s);b&&s[`defaultValue${this.options.pluralSeparator}zero`]&&!J.includes(`${this.options.pluralSeparator}zero`)&&J.push(`${this.options.pluralSeparator}zero`),J.forEach(ue=>{G([V],l+ue,s[`defaultValue${ue}`]||F)})}):G(M,l,F))}p=this.extendTranslation(p,e,s,g,n),H&&p===l&&this.options.appendNamespaceToMissingKey&&(p=`${d}${u}${l}`),(H||T)&&this.options.parseMissingKeyHandler&&(p=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${l}`:l,T?p:void 0,s))}return a?(g.res=p,g.usedParams=this.getUsedParamsDetails(s),g):p}extendTranslation(e,r,n,s,a){var c,d;if((c=this.i18nFormat)!=null&&c.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});const u=he(e)&&(((d=n==null?void 0:n.interpolation)==null?void 0:d.skipOnVariables)!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let f;if(u){const g=e.match(this.interpolator.nestingRegexp);f=g&&g.length}let m=n.replace&&!he(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(m={...this.options.interpolation.defaultVariables,...m}),e=this.interpolator.interpolate(e,m,n.lng||this.language||s.usedLng,n),u){const g=e.match(this.interpolator.nestingRegexp),p=g&&g.length;f<p&&(n.nest=!1)}!n.lng&&s&&s.res&&(n.lng=this.language||s.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...g)=>(a==null?void 0:a[0])===g[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${g[0]} in key: ${r[0]}`),null):this.translate(...g,r),n)),n.interpolation&&this.interpolator.reset()}const o=n.postProcess||this.options.postProcess,l=he(o)?[o]:o;return e!=null&&(l!=null&&l.length)&&n.applyPostProcessor!==!1&&(e=yi.handle(l,e,r,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...s,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,r={}){let n,s,a,o,l;return he(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(c=>typeof c=="function"?dr(c,{...this.options,...r}):c)),e.forEach(c=>{if(this.isValidLookup(n))return;const d=this.extractFromKey(c,r),u=d.key;s=u;let f=d.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const m=r.count!==void 0&&!he(r.count),g=m&&!r.ordinal&&r.count===0,p=r.context!==void 0&&(he(r.context)||typeof r.context=="number")&&r.context!=="",x=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);f.forEach(y=>{var v,A;this.isValidLookup(n)||(l=y,!this.checkedLoadedFor[`${x[0]}-${y}`]&&((v=this.utils)!=null&&v.hasLoadedNamespace)&&!((A=this.utils)!=null&&A.hasLoadedNamespace(l))&&(this.checkedLoadedFor[`${x[0]}-${y}`]=!0,this.logger.warn(`key "${s}" for languages "${x.join(", ")}" won't get resolved as namespace "${l}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),x.forEach(I=>{var E;if(this.isValidLookup(n))return;o=I;const C=[u];if((E=this.i18nFormat)!=null&&E.addLookupKeys)this.i18nFormat.addLookupKeys(C,u,I,y,r);else{let _;m&&(_=this.pluralResolver.getSuffix(I,r.count,r));const b=`${this.options.pluralSeparator}zero`,F=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(m&&(r.ordinal&&_.startsWith(F)&&C.push(u+_.replace(F,this.options.pluralSeparator)),C.push(u+_),g&&C.push(u+b)),p){const k=`${u}${this.options.contextSeparator||"_"}${r.context}`;C.push(k),m&&(r.ordinal&&_.startsWith(F)&&C.push(k+_.replace(F,this.options.pluralSeparator)),C.push(k+_),g&&C.push(k+b))}}let S;for(;S=C.pop();)this.isValidLookup(n)||(a=S,n=this.getResource(I,y,S,r))}))})}),{res:n,usedKey:s,exactUsedKey:a,usedLng:o,usedNS:l}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,r,n,s={}){var a;return(a=this.i18nFormat)!=null&&a.getResource?this.i18nFormat.getResource(e,r,n,s):this.resourceStore.getResource(e,r,n,s)}getUsedParamsDetails(e={}){const r=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=e.replace&&!he(e.replace);let s=n?e.replace:e;if(n&&typeof e.count<"u"&&(s.count=e.count),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!n){s={...s};for(const a of r)delete s[a]}return s}static hasDefaultValue(e){const r="defaultValue";for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&n.startsWith(r)&&e[n]!==void 0)return!0;return!1}}class ma{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=It.create("languageUtils")}getScriptPartFromCode(e){if(e=Rr(e),!e||!e.includes("-"))return null;const r=e.split("-");return r.length===2||(r.pop(),r[r.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(r.join("-"))}getLanguagePartFromCode(e){if(e=Rr(e),!e||!e.includes("-"))return e;const r=e.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(e){if(he(e)&&e.includes("-")){let r;try{r=Intl.getCanonicalLocales(e)[0]}catch{}return r&&this.options.lowerCaseLng&&(r=r.toLowerCase()),r||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(e)}getBestMatchFromCodes(e){if(!e)return null;let r;return e.forEach(n=>{if(r)return;const s=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(s))&&(r=s)}),!r&&this.options.supportedLngs&&e.forEach(n=>{if(r)return;const s=this.getScriptPartFromCode(n);if(this.isSupportedCode(s))return r=s;const a=this.getLanguagePartFromCode(n);if(this.isSupportedCode(a))return r=a;r=this.options.supportedLngs.find(o=>o===a?!0:!o.includes("-")&&!a.includes("-")?!1:!!(o.includes("-")&&!a.includes("-")&&o.slice(0,o.indexOf("-"))===a||o.startsWith(a)&&a.length>1))}),r||(r=this.getFallbackCodes(this.options.fallbackLng)[0]),r}getFallbackCodes(e,r){if(!e)return[];if(typeof e=="function"&&(e=e(r)),he(e)&&(e=[e]),Array.isArray(e))return e;if(!r)return e.default||[];let n=e[r];return n||(n=e[this.getScriptPartFromCode(r)]),n||(n=e[this.formatLanguageCode(r)]),n||(n=e[this.getLanguagePartFromCode(r)]),n||(n=e.default),n||[]}toResolveHierarchy(e,r){const n=this.getFallbackCodes((r===!1?[]:r)||this.options.fallbackLng||[],e),s=[],a=o=>{o&&(this.isSupportedCode(o)?s.push(o):this.logger.warn(`rejecting language code not found in supportedLngs: ${o}`))};return he(e)&&(e.includes("-")||e.includes("_"))?(this.options.load!=="languageOnly"&&a(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&a(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&a(this.getLanguagePartFromCode(e))):he(e)&&a(this.formatLanguageCode(e)),n.forEach(o=>{s.includes(o)||a(this.formatLanguageCode(o))}),s}}const pa={zero:0,one:1,two:2,few:3,many:4,other:5},ga={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class yl{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=It.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,r={}){const n=Rr(e==="dev"?"en":e),s=r.ordinal?"ordinal":"cardinal",a=JSON.stringify({cleanedCode:n,type:s});if(a in this.pluralRulesCache)return this.pluralRulesCache[a];let o;try{o=new Intl.PluralRules(n,{type:s})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),ga;if(!e.match(/-|_/))return ga;const c=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(c,r)}return this.pluralRulesCache[a]=o,o}needsPlural(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),(n==null?void 0:n.resolvedOptions().pluralCategories.length)>1}getPluralFormsOfKey(e,r,n={}){return this.getSuffixes(e,n).map(s=>`${r}${s}`)}getSuffixes(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),n?n.resolvedOptions().pluralCategories.sort((s,a)=>pa[s]-pa[a]).map(s=>`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${s}`):[]}getSuffix(e,r,n={}){const s=this.getRule(e,n);return s?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${s.select(r)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",r,n))}}const xa=(t,e,r,n=".",s=!0)=>{let a=dl(t,e,r);return!a&&s&&he(r)&&(a=dn(t,r,n),a===void 0&&(a=dn(e,r,n))),a},Qs=t=>t.replace(/\$/g,"$$$$");class ba{constructor(e={}){var r;this.logger=It.create("interpolator"),this.options=e,this.format=((r=e==null?void 0:e.interpolation)==null?void 0:r.format)||(n=>n),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:r,escapeValue:n,useRawValueToEscape:s,prefix:a,prefixEscaped:o,suffix:l,suffixEscaped:c,formatSeparator:d,unescapeSuffix:u,unescapePrefix:f,nestingPrefix:m,nestingPrefixEscaped:g,nestingSuffix:p,nestingSuffixEscaped:x,nestingOptionsSeparator:y,maxReplaces:v,alwaysFormat:A}=e.interpolation;this.escape=r!==void 0?r:fl,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=s!==void 0?s:!1,this.prefix=a?Mt(a):o||"{{",this.suffix=l?Mt(l):c||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":f?Mt(f):"-",this.unescapeSuffix=this.unescapePrefix?"":u?Mt(u):"",this.nestingPrefix=m?Mt(m):g||Mt("$t("),this.nestingSuffix=p?Mt(p):x||Mt(")"),this.nestingOptionsSeparator=y||",",this.maxReplaces=v||1e3,this.alwaysFormat=A!==void 0?A:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(r,n)=>(r==null?void 0:r.source)===n?(r.lastIndex=0,r):new RegExp(n,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,r,n,s){var g;let a,o,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=p=>{if(!p.includes(this.formatSeparator)){const A=xa(r,c,p,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(A,void 0,n,{...s,...r,interpolationkey:p}):A}const x=p.split(this.formatSeparator),y=x.shift().trim(),v=x.join(this.formatSeparator).trim();return this.format(xa(r,c,y,this.options.keySeparator,this.options.ignoreJSONStructure),v,n,{...s,...r,interpolationkey:y})};this.resetRegExp(),!this.escapeValue&&typeof e=="string"&&/\$t\([^)]*\{[^}]*\{\{/.test(e)&&this.logger.warn("nesting options string contains interpolated variables with escapeValue: false — if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true.");const u=(s==null?void 0:s.missingInterpolationHandler)||this.options.missingInterpolationHandler,f=((g=s==null?void 0:s.interpolation)==null?void 0:g.skipOnVariables)!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:p=>Qs(p)},{regex:this.regexp,safeValue:p=>this.escapeValue?Qs(this.escape(p)):Qs(p)}].forEach(p=>{for(l=0;a=p.regex.exec(e);){const x=a[1].trim();if(o=d(x),o===void 0)if(typeof u=="function"){const v=u(e,a,s);o=he(v)?v:""}else if(s&&Object.prototype.hasOwnProperty.call(s,x))o="";else if(f){o=a[0];continue}else this.logger.warn(`missed to pass in variable ${x} for interpolating ${e}`),o="";else!he(o)&&!this.useRawValueToEscape&&(o=ca(o));const y=p.safeValue(o);if(e=e.replace(a[0],y),f?(p.regex.lastIndex+=o.length,p.regex.lastIndex-=a[0].length):p.regex.lastIndex=0,l++,l>=this.maxReplaces)break}}),e}nest(e,r,n={}){let s,a,o;const l=(c,d)=>{const u=this.nestingOptionsSeparator;if(!c.includes(u))return c;const f=c.split(new RegExp(`${Mt(u)}[ ]*{`));let m=`{${f[1]}`;c=f[0],m=this.interpolate(m,o);const g=m.match(/'/g),p=m.match(/"/g);(((g==null?void 0:g.length)??0)%2===0&&!p||((p==null?void 0:p.length)??0)%2!==0)&&(m=m.replace(/'/g,'"'));try{o=JSON.parse(m),d&&(o={...d,...o})}catch(x){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,x),`${c}${u}${m}`}return o.defaultValue&&o.defaultValue.includes(this.prefix)&&delete o.defaultValue,c};for(;s=this.nestingRegexp.exec(e);){let c=[];o={...n},o=o.replace&&!he(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const d=/{.*}/.test(s[1])?s[1].lastIndexOf("}")+1:s[1].indexOf(this.formatSeparator);if(d!==-1&&(c=s[1].slice(d).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),s[1]=s[1].slice(0,d)),a=r(l.call(this,s[1].trim(),o),o),a&&s[0]===e&&!he(a))return a;he(a)||(a=ca(a)),a||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${e}`),a=""),c.length&&(a=c.reduce((u,f)=>this.format(u,f,n.lng,{...n,interpolationkey:s[1].trim()}),a.trim())),e=e.replace(s[0],a),this.regexp.lastIndex=0}return e}}const wl=t=>{let e=t.toLowerCase().trim();const r={};if(t.includes("(")){const n=t.split("(");e=n[0].toLowerCase().trim();const s=n[1].slice(0,-1);e==="currency"&&!s.includes(":")?r.currency||(r.currency=s.trim()):e==="relativetime"&&!s.includes(":")?r.range||(r.range=s.trim()):s.split(";").forEach(o=>{if(o){const[l,...c]=o.split(":"),d=c.join(":").trim().replace(/^'+|'+$/g,""),u=l.trim();r[u]||(r[u]=d),d==="false"&&(r[u]=!1),d==="true"&&(r[u]=!0),isNaN(d)||(r[u]=parseInt(d,10))}})}return{formatName:e,formatOptions:r}},ya=t=>{const e={};return(r,n,s)=>{let a=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(a={...a,[s.interpolationkey]:void 0});const o=n+JSON.stringify(a);let l=e[o];return l||(l=t(Rr(n),s),e[o]=l),l(r)}},vl=t=>(e,r,n)=>t(Rr(r),n)(e);class kl{constructor(e={}){this.logger=It.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?ya:vl;this.formats={number:n((s,a)=>{const o=new Intl.NumberFormat(s,{...a});return l=>o.format(l)}),currency:n((s,a)=>{const o=new Intl.NumberFormat(s,{...a,style:"currency"});return l=>o.format(l)}),datetime:n((s,a)=>{const o=new Intl.DateTimeFormat(s,{...a});return l=>o.format(l)}),relativetime:n((s,a)=>{const o=new Intl.RelativeTimeFormat(s,{...a});return l=>o.format(l,a.range||"day")}),list:n((s,a)=>{const o=new Intl.ListFormat(s,{...a});return l=>o.format(l)})}}add(e,r){this.formats[e.toLowerCase().trim()]=r}addCached(e,r){this.formats[e.toLowerCase().trim()]=ya(r)}format(e,r,n,s={}){if(!r||e==null)return e;const a=r.split(this.formatSeparator),o=[];for(let c=0;c<a.length;c++){let d=a[c];for(;d.indexOf("(")>-1&&!d.includes(")")&&c+1<a.length;)d=`${d}${this.formatSeparator}${a[++c]}`;o.push(d)}return o.reduce((c,d)=>{var m;const{formatName:u,formatOptions:f}=wl(d);if(this.formats[u]){let g=c;try{const p=((m=s==null?void 0:s.formatParams)==null?void 0:m[s.interpolationkey])||{},x=p.locale||p.lng||s.locale||s.lng||n;g=this.formats[u](c,x,{...f,...s,...p})}catch(p){this.logger.warn(p)}return g}else this.logger.warn(`there was no format function for ${u}`);return c},e)}}const Sl=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class jl extends Is{constructor(e,r,n,s={}){var a,o;super(),this.backend=e,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=s,this.logger=It.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],(o=(a=this.backend)==null?void 0:a.init)==null||o.call(a,n,s.backend,s)}queueLoad(e,r,n,s){const a={},o={},l={},c={};return e.forEach(d=>{let u=!0;r.forEach(f=>{const m=`${d}|${f}`;!n.reload&&this.store.hasResourceBundle(d,f)?this.state[m]=2:this.state[m]<0||(this.state[m]===1?o[m]===void 0&&(o[m]=!0):(this.state[m]=1,u=!1,o[m]===void 0&&(o[m]=!0),a[m]===void 0&&(a[m]=!0),c[f]===void 0&&(c[f]=!0)))}),u||(l[d]=!0)}),(Object.keys(a).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(a),pending:Object.keys(o),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(e,r,n){const s=e.split("|"),a=s[0],o=s[1];r&&this.emit("failedLoading",a,o,r),!r&&n&&this.store.addResourceBundle(a,o,n,void 0,void 0,{skipCopy:!0}),this.state[e]=r?-1:2,r&&n&&(this.state[e]=0);const l={};this.queue.forEach(c=>{cl(c.loaded,[a],o),Sl(c,e),r&&c.errors.push(r),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(d=>{l[d]||(l[d]={});const u=c.loaded[d];u.length&&u.forEach(f=>{l[d][f]===void 0&&(l[d][f]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",l),this.queue=this.queue.filter(c=>!c.done)}read(e,r,n,s=0,a=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:r,fcName:n,tried:s,wait:a,callback:o});return}this.readingCalls++;const l=(d,u)=>{if(this.readingCalls--,this.waitingReads.length>0){const f=this.waitingReads.shift();this.read(f.lng,f.ns,f.fcName,f.tried,f.wait,f.callback)}if(d&&u&&s<this.maxRetries){setTimeout(()=>{this.read(e,r,n,s+1,a*2,o)},a);return}o(d,u)},c=this.backend[n].bind(this.backend);if(c.length===2){try{const d=c(e,r);d&&typeof d.then=="function"?d.then(u=>l(null,u)).catch(l):l(null,d)}catch(d){l(d)}return}return c(e,r,l)}prepareLoading(e,r,n={},s){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();he(e)&&(e=this.languageUtils.toResolveHierarchy(e)),he(r)&&(r=[r]);const a=this.queueLoad(e,r,n,s);if(!a.toLoad.length)return a.pending.length||s(),null;a.toLoad.forEach(o=>{this.loadOne(o)})}load(e,r,n){this.prepareLoading(e,r,{},n)}reload(e,r,n){this.prepareLoading(e,r,{reload:!0},n)}loadOne(e,r=""){const n=e.split("|"),s=n[0],a=n[1];this.read(s,a,"read",void 0,void 0,(o,l)=>{o&&this.logger.warn(`${r}loading namespace ${a} for language ${s} failed`,o),!o&&l&&this.logger.log(`${r}loaded namespace ${a} for language ${s}`,l),this.loaded(e,o,l)})}saveMissing(e,r,n,s,a,o={},l=()=>{}){var c,d,u,f,m;if((d=(c=this.services)==null?void 0:c.utils)!=null&&d.hasLoadedNamespace&&!((f=(u=this.services)==null?void 0:u.utils)!=null&&f.hasLoadedNamespace(r))){this.logger.warn(`did not save key "${n}" as the namespace "${r}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(n==null||n==="")){if((m=this.backend)!=null&&m.create){const g={...o,isUpdate:a},p=this.backend.create.bind(this.backend);if(p.length<6)try{let x;p.length===5?x=p(e,r,n,s,g):x=p(e,r,n,s),x&&typeof x.then=="function"?x.then(y=>l(null,y)).catch(l):l(null,x)}catch(x){l(x)}else p(e,r,n,s,l,g)}!e||!e[0]||this.store.addResource(e[0],r,n,s)}}}const Zs=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",enableSelector:!1,partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),he(t[1])&&(e.defaultValue=t[1]),he(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const r=t[3]||t[2];Object.keys(r).forEach(n=>{e[n]=r[n]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),wa=t=>(he(t.ns)&&(t.ns=[t.ns]),he(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),he(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs&&!t.supportedLngs.includes("cimode")&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),t),ts=()=>{},Cl=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})};class Mr extends Is{constructor(e={},r){if(super(),this.options=wa(e),this.services={},this.logger=It,this.modules={external:[]},Cl(this),r&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,r),this;setTimeout(()=>{this.init(e,r)},0)}}init(e={},r){this.isInitializing=!0,typeof e=="function"&&(r=e,e={}),e.defaultNS==null&&e.ns&&(he(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const n=Zs();this.options={...n,...this.options,...wa(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler);const s=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?It.init(s(this.modules.logger),this.options):It.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=kl;const u=new ma(this.options);this.store=new ha(this.options.resources,this.options);const f=this.services;f.logger=It,f.resourceStore=this.store,f.languageUtils=u,f.pluralResolver=new yl(u,{prepend:this.options.pluralSeparator}),d&&(f.formatter=s(d),f.formatter.init&&f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new ba(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new jl(s(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(m,...g)=>{this.emit(m,...g)}),this.modules.languageDetector&&(f.languageDetector=s(this.modules.languageDetector),f.languageDetector.init&&f.languageDetector.init(f,this.options.detection,this.options)),this.modules.i18nFormat&&(f.i18nFormat=s(this.modules.i18nFormat),f.i18nFormat.init&&f.i18nFormat.init(this)),this.translator=new xs(this.services,this.options),this.translator.on("*",(m,...g)=>{this.emit(m,...g)}),this.modules.external.forEach(m=>{m.init&&m.init(this)})}if(this.format=this.options.interpolation.format,r||(r=ts),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(d=>{this[d]=(...u)=>this.store[d](...u)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=(...u)=>(this.store[d](...u),this)});const l=Ir(),c=()=>{const d=(u,f)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),l.resolve(f),r(u,f)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),l}loadResources(e,r=ts){var a,o;let n=r;const s=he(e)?e:this.language;if(typeof e=="function"&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if((s==null?void 0:s.toLowerCase())==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();const l=[],c=d=>{if(!d||d==="cimode")return;this.services.languageUtils.toResolveHierarchy(d).forEach(f=>{f!=="cimode"&&(l.includes(f)||l.push(f))})};s?c(s):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>c(u)),(o=(a=this.options.preload)==null?void 0:a.forEach)==null||o.call(a,d=>c(d)),this.services.backendConnector.load(l,this.options.ns,d=>{!d&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(d)})}else n(null)}reloadResources(e,r,n){const s=Ir();return typeof e=="function"&&(n=e,e=void 0),typeof r=="function"&&(n=r,r=void 0),e||(e=this.languages),r||(r=this.options.ns),n||(n=ts),this.services.backendConnector.reload(e,r,a=>{s.resolve(),n(a)}),s}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&yi.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!["cimode","dev"].includes(e)){for(let r=0;r<this.languages.length;r++){const n=this.languages[r];if(!["cimode","dev"].includes(n)&&this.store.hasLanguageSomeTranslations(n)){this.resolvedLanguage=n;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,r){this.isLanguageChangingTo=e;const n=Ir();this.emit("languageChanging",e);const s=l=>{this.language=l,this.languages=this.services.languageUtils.toResolveHierarchy(l),this.resolvedLanguage=void 0,this.setResolvedLanguage(l)},a=(l,c)=>{c?this.isLanguageChangingTo===e&&(s(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,n.resolve((...d)=>this.t(...d)),r&&r(l,(...d)=>this.t(...d))},o=l=>{var u,f;!e&&!l&&this.services.languageDetector&&(l=[]);const c=he(l)?l:l&&l[0],d=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(he(l)?[l]:l);d&&(this.language||s(d),this.translator.language||this.translator.changeLanguage(d),(f=(u=this.services.languageDetector)==null?void 0:u.cacheUserLanguage)==null||f.call(u,d)),this.loadResources(d,m=>{a(m,d)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?o(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(e),n}getFixedT(e,r,n,s){const a=s==null?void 0:s.scopeNs,o=(l,c,...d)=>{let u;typeof c!="object"?u=this.options.overloadTranslationOptionHandler([l,c].concat(d)):u={...c},u.lng=u.lng||o.lng,u.lngs=u.lngs||o.lngs;const f=u.ns!==void 0&&u.ns!==null;u.ns=u.ns||o.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||n||o.keyPrefix);const m={...this.options,...u};Array.isArray(a)&&!f&&(m.ns=a),typeof u.keyPrefix=="function"&&(u.keyPrefix=dr(u.keyPrefix,m));const g=this.options.keySeparator||".";let p;return u.keyPrefix&&Array.isArray(l)?p=l.map(x=>(typeof x=="function"&&(x=dr(x,m)),`${u.keyPrefix}${g}${x}`)):(typeof l=="function"&&(l=dr(l,m)),p=u.keyPrefix?`${u.keyPrefix}${g}${l}`:l),this.t(p,u)};return he(e)?o.lng=e:o.lngs=e,o.ns=r,o.keyPrefix=n,o}t(...e){var r;return(r=this.translator)==null?void 0:r.translate(...e)}exists(...e){var r;return(r=this.translator)==null?void 0:r.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,r={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const n=r.lng||this.resolvedLanguage||this.languages[0],s=this.options?this.options.fallbackLng:!1,a=this.languages[this.languages.length-1];if(n.toLowerCase()==="cimode")return!0;const o=(l,c)=>{const d=this.services.backendConnector.state[`${l}|${c}`];return d===-1||d===0||d===2};if(r.precheck){const l=r.precheck(this,o);if(l!==void 0)return l}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(n,e)&&(!s||o(a,e)))}loadNamespaces(e,r){const n=Ir();return this.options.ns?(he(e)&&(e=[e]),e.forEach(s=>{this.options.ns.includes(s)||this.options.ns.push(s)}),this.loadResources(s=>{n.resolve(),r&&r(s)}),n):(r&&r(),Promise.resolve())}loadLanguages(e,r){const n=Ir();he(e)&&(e=[e]);const s=this.options.preload||[],a=e.filter(o=>!s.includes(o)&&this.services.languageUtils.isSupportedCode(o));return a.length?(this.options.preload=s.concat(a),this.loadResources(o=>{n.resolve(),r&&r(o)}),n):(r&&r(),Promise.resolve())}dir(e){var s,a;if(e||(e=this.resolvedLanguage||(((s=this.languages)==null?void 0:s.length)>0?this.languages[0]:this.language)),!e)return"rtl";try{const o=new Intl.Locale(e);if(o&&o.getTextInfo){const l=o.getTextInfo();if(l&&l.direction)return l.direction}}catch{}const r=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],n=((a=this.services)==null?void 0:a.languageUtils)||new ma(Zs());return e.toLowerCase().indexOf("-latn")>1?"ltr":r.includes(n.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},r){const n=new Mr(e,r);return n.createInstance=Mr.createInstance,n}cloneInstance(e={},r=ts){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const s={...this.options,...e,isClone:!0},a=new Mr(s);if((e.debug!==void 0||e.prefix!==void 0)&&(a.logger=a.logger.clone(e)),["store","services","language"].forEach(l=>{a[l]=this[l]}),a.services={...this.services},a.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},n){const l=Object.keys(this.store.data).reduce((c,d)=>(c[d]={...this.store.data[d]},c[d]=Object.keys(c[d]).reduce((u,f)=>(u[f]={...c[d][f]},u),c[d]),c),{});a.store=new ha(l,s),a.services.resourceStore=a.store}if(e.interpolation){const c={...Zs().interpolation,...this.options.interpolation,...e.interpolation},d={...s,interpolation:c};a.services.interpolator=new ba(d)}return a.translator=new xs(a.services,s),a.translator.on("*",(l,...c)=>{a.emit(l,...c)}),a.init(s,r),a.translator.options=s,a.translator.backendConnector.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},a}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const Xe=Mr.createInstance();Xe.createInstance;Xe.dir;Xe.init;Xe.loadResources;Xe.reloadResources;Xe.use;Xe.changeLanguage;Xe.getFixedT;Xe.t;Xe.exists;Xe.setDefaultNamespace;Xe.hasLoadedNamespace;Xe.loadNamespaces;Xe.loadLanguages;const Al=(t,e,r,n)=>{var a,o,l,c;const s=[r,{code:e,...n||{}}];if((o=(a=t==null?void 0:t.services)==null?void 0:a.logger)!=null&&o.forward)return t.services.logger.forward(s,"warn","react-i18next::",!0);er(s[0])&&(s[0]=`react-i18next:: ${s[0]}`),(c=(l=t==null?void 0:t.services)==null?void 0:l.logger)!=null&&c.warn?t.services.logger.warn(...s):console!=null&&console.warn&&console.warn(...s)},va={},un=(t,e,r,n)=>{er(r)&&va[r]||(er(r)&&(va[r]=new Date),Al(t,e,r,n))},vi=(t,e)=>()=>{if(t.isInitialized)e();else{const r=()=>{setTimeout(()=>{t.off("initialized",r)},0),e()};t.on("initialized",r)}},fn=(t,e,r)=>{t.loadNamespaces(e,vi(t,r))},ka=(t,e,r,n)=>{if(er(r)&&(r=[r]),t.options.preload&&t.options.preload.indexOf(e)>-1)return fn(t,r,n);r.forEach(s=>{t.options.ns.indexOf(s)<0&&t.options.ns.push(s)}),t.loadLanguages(e,vi(t,n))},Nl=(t,e,r={})=>!e.languages||!e.languages.length?(un(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(t,{lng:r.lng,precheck:(n,s)=>{if(r.bindI18n&&r.bindI18n.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!s(n.isLanguageChangingTo,t))return!1}}),er=t=>typeof t=="string",Il=t=>typeof t=="object"&&t!==null,Ll=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,El={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},_l=t=>El[t],Tl=t=>t.replace(Ll,_l);let hn={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:Tl,transDefaultProps:void 0};const Ml=(t={})=>{hn={...hn,...t}},Fl=()=>hn;let ki;const $l=t=>{ki=t},Rl=()=>ki,Pl={type:"3rdParty",init(t){Ml(t.options.react),$l(t)}},Dl=h.createContext();class Ul{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(r=>{this.usedNamespaces[r]||(this.usedNamespaces[r]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var Js={exports:{}},en={};/**
3
+ * @license React
4
+ * use-sync-external-store-shim.production.js
5
+ *
6
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
7
+ *
8
+ * This source code is licensed under the MIT license found in the
9
+ * LICENSE file in the root directory of this source tree.
10
+ */var Sa;function Ol(){if(Sa)return en;Sa=1;var t=zo();function e(f,m){return f===m&&(f!==0||1/f===1/m)||f!==f&&m!==m}var r=typeof Object.is=="function"?Object.is:e,n=t.useState,s=t.useEffect,a=t.useLayoutEffect,o=t.useDebugValue;function l(f,m){var g=m(),p=n({inst:{value:g,getSnapshot:m}}),x=p[0].inst,y=p[1];return a(function(){x.value=g,x.getSnapshot=m,c(x)&&y({inst:x})},[f,g,m]),s(function(){return c(x)&&y({inst:x}),f(function(){c(x)&&y({inst:x})})},[f]),o(g),g}function c(f){var m=f.getSnapshot;f=f.value;try{var g=m();return!r(f,g)}catch{return!0}}function d(f,m){return m()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:l;return en.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:u,en}var ja;function zl(){return ja||(ja=1,Js.exports=Ol()),Js.exports}var Bl=zl();const Hl=(t,e)=>{if(er(e))return e;if(Il(e)&&er(e.defaultValue))return e.defaultValue;if(typeof t=="function")return"";if(Array.isArray(t)){const r=t[t.length-1];return typeof r=="function"?"":r}return t},Vl={t:Hl,ready:!1},ql=()=>()=>{},Ie=(t,e={})=>{var F,k,N;const{i18n:r}=e,{i18n:n,defaultNS:s}=h.useContext(Dl)||{},a=r||n||Rl();a&&!a.reportNamespaces&&(a.reportNamespaces=new Ul),a||un(a,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=h.useMemo(()=>{var U;return{...Fl(),...(U=a==null?void 0:a.options)==null?void 0:U.react,...e}},[a,e]),{useSuspense:l,keyPrefix:c}=o,d=s||((F=a==null?void 0:a.options)==null?void 0:F.defaultNS),u=er(d)?[d]:d||["translation"],f=h.useMemo(()=>u,u);(N=(k=a==null?void 0:a.reportNamespaces)==null?void 0:k.addUsedNamespaces)==null||N.call(k,f);const m=h.useRef(0),g=h.useCallback(U=>{if(!a)return ql;const{bindI18n:T,bindI18nStore:H}=o,j=()=>{m.current+=1,U()};return T&&a.on(T,j),H&&a.store.on(H,j),()=>{T&&T.split(" ").forEach(L=>a.off(L,j)),H&&H.split(" ").forEach(L=>a.store.off(L,j))}},[a,o]),p=h.useRef(),x=h.useCallback(()=>{if(!a)return Vl;const U=!!(a.isInitialized||a.initializedStoreOnce)&&f.every(M=>Nl(M,a,o)),T=e.lng||a.language,H=m.current,j=p.current;if(j&&j.ready===U&&j.lng===T&&j.keyPrefix===c&&j.revision===H)return j;const O={t:a.getFixedT(T,o.nsMode==="fallback"?f:f[0],c,{scopeNs:f}),ready:U,lng:T,keyPrefix:c,revision:H};return p.current=O,O},[a,f,c,o,e.lng]),[y,v]=h.useState(0),{t:A,ready:I}=Bl.useSyncExternalStore(g,x,x);h.useEffect(()=>{if(a&&!I&&!l){const U=()=>v(T=>T+1);e.lng?ka(a,e.lng,f,U):fn(a,f,U)}},[a,e.lng,f,I,l,y]);const C=a||{},S=h.useRef(null),E=h.useRef(),_=U=>{const T=Object.getOwnPropertyDescriptors(U);T.__original&&delete T.__original;const H=Object.create(Object.getPrototypeOf(U),T);if(!Object.prototype.hasOwnProperty.call(H,"__original"))try{Object.defineProperty(H,"__original",{value:U,writable:!1,enumerable:!1,configurable:!1})}catch{}return H},b=h.useMemo(()=>{const U=C,T=U==null?void 0:U.language;let H=U;U&&(S.current&&S.current.__original===U?E.current!==T?(H=_(U),S.current=H,E.current=T):H=S.current:(H=_(U),S.current=H,E.current=T));const j=!I&&!l?(...O)=>(un(a,"USE_T_BEFORE_READY","useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t."),A(...O)):A,L=[j,H,I];return L.t=j,L.i18n=H,L.ready=I,L},[A,C,I,C.resolvedLanguage,C.language,C.languages]);if(a&&l&&!I)throw new Promise(U=>{const T=()=>U();e.lng?ka(a,e.lng,f,T):fn(a,f,T)});return b},Wl={de:{translation:Xo},en:{translation:Go},es:{translation:Ko},fr:{translation:Wo},ja:{translation:qo},pt:{translation:Vo},zh:{translation:Ho}};Xe.use(Pl).init({resources:Wl,lng:"en",fallbackLng:"en",interpolation:{escapeValue:!1},returnNull:!1});var Kl={agentMode:{mode:"multi",defaultAdapterId:"chat-with-files"},application:{name:"ORBIT Chat",description:"Explore ideas with ORBIT's AI copilots, share context, and build together.",inputPlaceholder:"Message ORBIT...",settingsAboutMsg:"ORBIT Chat",locale:"en-US",favicon:null},i18n:{activeLanguages:["en","fr","es","pt","de","ja","zh"],defaultLanguage:"en"},seo:{includeSitemap:!1,siteUrl:"http://localhost:5173",exposeAgentNotes:!0},debug:{consoleDebug:!1},features:{enableUpload:!0,enableAudioOutput:!0,enableAudioInput:!0,enableFeedbackButtons:!0,enableConversationThreads:!0,enableAutocomplete:!0},voice:{silenceTimeoutMs:4e3,recognitionLanguage:""},limits:{files:{perConversation:5,maxSizeMB:50,totalFiles:100},conversations:{maxConversations:10,messagesPerConversation:1e3,messagesPerThread:1e3,totalMessages:1e4},messages:{maxLength:1e4}},guestLimits:{files:{perConversation:1,maxSizeMB:5,totalFiles:1},conversations:{maxConversations:2,messagesPerConversation:5,messagesPerThread:2,totalMessages:10},messages:{maxLength:500},rateLimit:{enabled:!0,windowMs:6e4,maxRequests:60,chat:{windowMs:6e4,maxRequests:10}}},auth:{enabled:!1,provider:"entra"},header:{enabled:!0,logoUrl:"",logoUrlLight:"",logoUrlDark:"",logoHeight:"3.5rem",logoWidth:"auto",bgColor:"",textColor:"",showBorder:!1,navLinks:[{label:"Docs",url:"/"},{label:"About",url:"/about"}]},footer:{enabled:!0,text:"Copyright © 2025 Schmitech Inc.",bgColor:"",textColor:"",showBorder:!1,layout:"stacked",align:"center",topPadding:"large",navLinks:[{label:"Support",url:"/"},{label:"Privacy",url:"/about"}]},adapters:[{id:"simple-chat",name:"Simple AI Chat",apiUrl:"http://localhost:3000",description:"Basic chat interface using the default conversational agent (Similar to ChatGPT - no files).",inputPlaceholder:"Simple chat, ask anything..."},{id:"web-search",name:"Simple AI Chat (Web Search)",apiUrl:"http://localhost:3000",description:"Basic chat interface using the default conversational agent with web search supports.",inputPlaceholder:"Simple chat, ask anything..."},{id:"chat-with-files",name:"Simple AI Chat (Multimodal)",apiUrl:"http://localhost:3000",description:"Extract knowledge from PDF, Images, Word, etc. (Similar to ChatGPT Multimodal)",inputPlaceholder:"Files chat, ask anything..."},{id:"image-generator",name:"AI Image Generator",apiUrl:"http://localhost:3000",description:"Generate images from text descriptions using DALL-E 3 or Imagen 3.",inputPlaceholder:"Describe the image you want to create..."},{id:"video-generator",name:"AI Video Generator",apiUrl:"http://localhost:3000",description:"Generate videos from text descriptions.",inputPlaceholder:"Describe the video you want to create..."},{id:"audio-generator",name:"AI Audio Generator",apiUrl:"http://localhost:3000",description:"Convert text to natural-sounding speech using AI voices.",inputPlaceholder:"Type the text you want to convert to speech..."},{id:"qa-sql",name:"City FAQ Assistant (SQLite)",apiUrl:"http://localhost:3000",description:"Quick-test QA assistant over the sample city Q&A SQLite database.",inputPlaceholder:"Ask a city services question..."},{id:"qa-vector-chroma",name:"City FAQ Assistant (Chroma)",apiUrl:"http://localhost:3000",description:"Quick-test semantic QA assistant over the sample city Q&A Chroma collection.",inputPlaceholder:"Ask a city services question..."},{id:"hr-db-chatbot",name:"HR System Assistant",apiUrl:"http://localhost:3000",description:"HR database assistant: natural language queries over SQLite HR data via intent templates.",inputPlaceholder:"Ask HR questions..."},{id:"intent-sql-postgres",name:"Customer Orders Assistant",apiUrl:"http://localhost:3000",description:"Customer orders assistant: natural language queries over PostgreSQL customer orders data."},{id:"ecomm-analytics",name:"Business Analytics Assistant",apiUrl:"http://localhost:3000",description:"DuckDB analytics assistant: natural language analytics queries over the analytics demo. This agent is the perfect example of how to use something like OLAP to quickly discover insigths."},{id:"composite-multi-source-explorer",name:"Multi-Source Explorer",apiUrl:"http://localhost:3000",description:"Multi-domain assistant: natural language over HR (SQLite), customer orders (PostgreSQL), and sales analytics (DuckDB)—one chat, retrieval routes each question to the best source.",inputPlaceholder:"Ask about employees, orders, or sales analytics..."},{id:"intent-http-jsonplaceholder",name:"REST API Chat",apiUrl:"http://localhost:3000",description:"Natural language queries over the fake REST API."},{id:"intent-http-paris-opendata",name:"City of Paris Chat",apiUrl:"http://localhost:3000",description:"Paris open data: events and activities (Que Faire à Paris) via natural language."},{id:"intent-mongodb-mflix",name:"Chat With Movies DB",apiUrl:"http://localhost:3000",description:"MFlix movies assistant: query the sample_mflix MongoDB database via intent templates."},{id:"intent-graphql-spacex",name:"GraphQL Chatbot",apiUrl:"http://localhost:3000",description:"SpaceX GraphQL assistant: natural language queries over the SpaceX API.",inputPlaceholder:"Ask SpaceX questions..."},{id:"audio-transcription",name:"Audio Transcription",apiUrl:"http://localhost:3000",description:"Audio Transcription Test.",inputPlaceholder:"Use the microphone for voice..."},{id:"voice-chat",name:"Voice Chat",apiUrl:"http://localhost:3000",description:"Voice chat adapter test.",inputPlaceholder:"Use the microphone for voice..."},{id:"real-time-voice-chat",name:"Real-Time Voice Chat",apiUrl:"http://localhost:3000",description:"Real-time voice chat adapter test (websocket).",inputPlaceholder:"Use the microphone for voice..."},{id:"intent-elasticsearch-log",name:"Log Analysis Assistant",apiUrl:"http://localhost:3000",description:"Analyze app logs, troubleshoot errors, and monitor performance via Elasticsearch."}]};const mn="http://localhost:3000",Gl="/favicon.svg",Xl="/orbit-logo-light.png",Yl="/orbit-logo-dark.png",Ql={agentMode:{mode:"multi",defaultAdapterId:""},i18n:{activeLanguages:["en"],defaultLanguage:"en"},application:{name:"ORBIT Chat",description:"Explore ideas with ORBIT's AI copilots, share context, and build together.",inputPlaceholder:"Message ORBIT...",settingsAboutMsg:"ORBIT Chat",locale:"en-US",favicon:""},debug:{consoleDebug:!1},seo:{includeSitemap:!1,siteUrl:"",alternateSiteUrls:[],hostPatterns:[],exposeAgentNotes:!0},features:{enableUpload:!1,enableAudioOutput:!1,enableAudioInput:!1,enableFeedbackButtons:!1,enableConversationThreads:!0,enableAutocomplete:!1},voice:{silenceTimeoutMs:4e3,recognitionLanguage:""},outOfServiceMessage:null,limits:{files:{perConversation:5,maxSizeMB:50,totalFiles:100},conversations:{maxConversations:10,messagesPerConversation:1e3,messagesPerThread:1e3,totalMessages:1e4},messages:{maxLength:1e3}},guestLimits:{files:{perConversation:1,maxSizeMB:10,totalFiles:2},conversations:{maxConversations:1,messagesPerConversation:10,messagesPerThread:10,totalMessages:10},messages:{maxLength:500}},auth:{enabled:!1,provider:"auth0",domain:"",clientId:"",audience:"",tenantId:"",scopes:[]},header:{enabled:!1,logoUrl:"",logoUrlLight:"",logoUrlDark:"",logoHeight:"",logoWidth:"",bgColor:"",textColor:"",showBorder:!0,navLinks:[]},footer:{enabled:!1,text:"",bgColor:"",textColor:"",showBorder:!1,layout:"stacked",align:"center",topPadding:"large",navLinks:[]},startupScripts:[],adapters:[]};function rs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function pn(t,e){if(!rs(t)||!rs(e))return e;const r={...t};return Object.keys(e).forEach(n=>{if(n==="__proto__"||n==="constructor"||n==="prototype")return;const s=r[n],a=e[n];rs(s)&&rs(a)?r[n]=pn(s,a):a!==void 0&&(r[n]=a)}),r}function Zl(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;const r=e.toLowerCase();return r==="false"||r==="0"||r==="off"||r==="disabled"?null:e}function Jl(t){return t==="single"?"single":"multi"}function ec(t){const e=t.trim();if(e.startsWith("["))try{const r=JSON.parse(e);return Array.isArray(r)?r.filter(Boolean):[]}catch{return[]}return e.split(/\s+/).filter(Boolean)}function tc(){const t=Kl||{},e=typeof window<"u"&&window.ORBIT_CHAT_CONFIG||{},r=!!(typeof window<"u"&&window.ORBIT_CHAT_CONFIG);let n=pn(Ql,t);return n=pn(n,e),(!r||!n.auth.domain)&&(n.auth.domain="dev-3c4dpzhecz4gundm.us.auth0.com"),(!r||!n.auth.clientId)&&(n.auth.clientId="9JSe5xtoi5mLXRuov2K7FHYU10ojCQLH"),!r||n.auth.audience,!r||n.auth.provider,!r||n.auth.tenantId,(!r||n.auth.scopes.length===0)&&(n.auth.scopes=ec("openid profile email User.Read")),n.outOfServiceMessage=Zl(n.outOfServiceMessage),n.agentMode.mode=Jl(n.agentMode.mode),n.agentMode.defaultAdapterId=typeof n.agentMode.defaultAdapterId=="string"?n.agentMode.defaultAdapterId.trim():"",n}const Q=tc();function $e(){var e;const t=Q.adapters;if(Array.isArray(t)&&t.length>0){const r=(e=t[0].apiUrl)==null?void 0:e.trim();if(r)return r}return mn}function lt(t){const e=t==null?void 0:t.trim();return e&&e.length>0?e:$e()}function rc(){const t=Q.adapters;return Array.isArray(t)&&t.length>0?t[0].id:"default-key"}function sc(){return Q.agentMode.mode}function Ls(){return sc()==="single"}function Ln(){if(!Ls())return null;const t=Q.agentMode.defaultAdapterId;return t&&Q.adapters.some(r=>{var n;return((n=r==null?void 0:r.id)==null?void 0:n.trim())===t})?t:null}function Si(){const t=Array.isArray(Q.i18n.activeLanguages)?Q.i18n.activeLanguages.filter(e=>typeof e=="string"):[];return t.length>0?t:["en"]}function nc(){var e;const t=(e=Q.i18n.defaultLanguage)==null?void 0:e.trim();return t&&Si().includes(t)?t:"en"}function En(){return Q.application.name}function _n(){return Q.application.description}function ji(){return Q.application.inputPlaceholder}function ac(t){var s;const e=t==null?void 0:t.trim();if(!e)return null;const r=Q.adapters.find(a=>{var o;return((o=a==null?void 0:a.id)==null?void 0:o.trim())===e});return((s=r==null?void 0:r.name)==null?void 0:s.trim())||null}function ic(t){var s;const e=t==null?void 0:t.trim();if(!e)return null;const r=Q.adapters.find(a=>{var o;return((o=a==null?void 0:a.id)==null?void 0:o.trim())===e});return((s=r==null?void 0:r.inputPlaceholder)==null?void 0:s.trim())||null}function Ci(){return Q.seo.siteUrl.trim()}function oc(){return Array.isArray(Q.seo.alternateSiteUrls)?Q.seo.alternateSiteUrls.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function lc(){return Array.isArray(Q.seo.hostPatterns)?Q.seo.hostPatterns.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function cc(){return Q.seo.exposeAgentNotes}function dc(){var e;return((e=Q.application.favicon)==null?void 0:e.trim())||Gl}function uc(){return Q.features.enableUpload}function fc(){return Q.features.enableAudioOutput}function hc(){return Q.features.enableAudioInput}function Ca(){return Q.features.enableFeedbackButtons}function mc(){return Q.features.enableConversationThreads}function Ai(){return Q.features.enableAutocomplete}function pc(){return Math.max(1e3,Q.voice.silenceTimeoutMs)}function gc(){return Q.voice.recognitionLanguage}function xc(){const t=Ln();if(t)return t;const e=Q.adapters;if(Array.isArray(e)&&e.length>0)for(const r of e){const n=typeof(r==null?void 0:r.id)=="string"?r.id.trim():"";if(n)return n}return null}function bc(){return Q.outOfServiceMessage}function Tn(){return Q.auth.enabled}function rt(){const{enabled:t,provider:e,domain:r,clientId:n,tenantId:s}=Q.auth;return!t||!n?!1:e==="entra"?!!s:!!r}function yc(){return Q.auth.domain}function Ni(){return Q.auth.clientId}function wc(){return Q.auth.audience}function Es(){return Q.auth.provider}function vc(){return Q.auth.tenantId}function Mn(){const t=Q.auth.scopes;return t.length>0?t:["openid","profile","email"]}function gn(){return Q.header.enabled}function kc(){return Q.header.logoUrl}function Sc(){var e;return((e=Q.header.logoUrlLight)==null?void 0:e.trim())||Xl}function jc(){var e;return((e=Q.header.logoUrlDark)==null?void 0:e.trim())||Yl}function Cc(){var t;return((t=Q.header.logoHeight)==null?void 0:t.trim())||""}function Ac(){var t;return((t=Q.header.logoWidth)==null?void 0:t.trim())||""}function Nc(){return Q.header.bgColor}function Ic(){return Q.header.textColor}function Lc(){return Q.header.showBorder}function Ii(t){if(Array.isArray(t))return t;if(typeof t=="string")try{const e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}return[]}function Li(){return Ii(Q.header.navLinks)}function Ei(){return Q.footer.enabled}function Ec(){return Q.footer.text}function _c(){return Q.footer.bgColor}function Tc(){return Q.footer.textColor}function Mc(){return Q.footer.showBorder}function Fc(){return Q.footer.layout==="inline"?"inline":"stacked"}function $c(){return Q.footer.topPadding==="normal"?"normal":"large"}function Rc(){const t=Q.startupScripts;return Array.isArray(t)?t.filter(e=>!!(e&&typeof e=="object")).map(e=>{const r=typeof e.src=="string"?e.src.trim():"",n=typeof e.content=="string"?e.content.trim():"",s=typeof e.id=="string"?e.id.trim():"";return{...e,src:r||void 0,content:n||void 0,id:s||void 0}}).filter(e=>!!(e.src||e.content)):[]}function Pc(){return Ii(Q.footer.navLinks)}const _i=["de","en","es","fr","ja","pt","zh"],ss={de:"Deutsch",en:"English",es:"Español",fr:"Français",ja:"日本語",pt:"Português",zh:"中文"};function hs(t){return _i.includes(t)}const Ti=h.createContext(void 0),Mi="orbit-chat-language";function Dc(){const t=Si().filter(hs);return t.length>0?t:["en"]}function Uc(t){const e=localStorage.getItem(Mi);if(e&&hs(e)&&t.includes(e))return e;const r=[...navigator.languages||[],navigator.language].filter(Boolean);for(const s of r){const a=s.split("-")[0].toLowerCase();if(hs(a)&&t.includes(a))return a}const n=nc();return hs(n)&&t.includes(n)?n:t[0]??"en"}function Oc({children:t}){const[e]=h.useState(()=>Dc()),[r,n]=h.useState(()=>Uc(e));h.useEffect(()=>{Xe.changeLanguage(r)},[r]),h.useEffect(()=>{localStorage.setItem(Mi,r)},[r]);const s=a=>{_i.includes(a)&&n(a)};return i.jsx(Ti.Provider,{value:{currentLanguage:r,activeLanguages:e,setLanguage:s},children:t})}function zc(){const t=h.useContext(Ti);if(!t)throw new Error("useLanguage must be used within LanguageProvider");return t}/**
11
+ * @license lucide-react v0.469.0 - ISC
12
+ *
13
+ * This source code is licensed under the ISC license.
14
+ * See the LICENSE file in the root directory of this source tree.
15
+ */const Bc=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Fi=(...t)=>t.filter((e,r,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===r).join(" ").trim();/**
16
+ * @license lucide-react v0.469.0 - ISC
17
+ *
18
+ * This source code is licensed under the ISC license.
19
+ * See the LICENSE file in the root directory of this source tree.
20
+ */var Hc={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
21
+ * @license lucide-react v0.469.0 - ISC
22
+ *
23
+ * This source code is licensed under the ISC license.
24
+ * See the LICENSE file in the root directory of this source tree.
25
+ */const Vc=h.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:s="",children:a,iconNode:o,...l},c)=>h.createElement("svg",{ref:c,...Hc,width:e,height:e,stroke:t,strokeWidth:n?Number(r)*24/Number(e):r,className:Fi("lucide",s),...l},[...o.map(([d,u])=>h.createElement(d,u)),...Array.isArray(a)?a:[a]]));/**
26
+ * @license lucide-react v0.469.0 - ISC
27
+ *
28
+ * This source code is licensed under the ISC license.
29
+ * See the LICENSE file in the root directory of this source tree.
30
+ */const se=(t,e)=>{const r=h.forwardRef(({className:n,...s},a)=>h.createElement(Vc,{ref:a,iconNode:e,className:Fi(`lucide-${Bc(t)}`,n),...s}));return r.displayName=`${t}`,r};/**
31
+ * @license lucide-react v0.469.0 - ISC
32
+ *
33
+ * This source code is licensed under the ISC license.
34
+ * See the LICENSE file in the root directory of this source tree.
35
+ */const xn=se("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/**
36
+ * @license lucide-react v0.469.0 - ISC
37
+ *
38
+ * This source code is licensed under the ISC license.
39
+ * See the LICENSE file in the root directory of this source tree.
40
+ */const ur=se("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
41
+ * @license lucide-react v0.469.0 - ISC
42
+ *
43
+ * This source code is licensed under the ISC license.
44
+ * See the LICENSE file in the root directory of this source tree.
45
+ */const hr=se("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/**
46
+ * @license lucide-react v0.469.0 - ISC
47
+ *
48
+ * This source code is licensed under the ISC license.
49
+ * See the LICENSE file in the root directory of this source tree.
50
+ */const Aa=se("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
51
+ * @license lucide-react v0.469.0 - ISC
52
+ *
53
+ * This source code is licensed under the ISC license.
54
+ * See the LICENSE file in the root directory of this source tree.
55
+ */const bs=se("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/**
56
+ * @license lucide-react v0.469.0 - ISC
57
+ *
58
+ * This source code is licensed under the ISC license.
59
+ * See the LICENSE file in the root directory of this source tree.
60
+ */const bn=se("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/**
61
+ * @license lucide-react v0.469.0 - ISC
62
+ *
63
+ * This source code is licensed under the ISC license.
64
+ * See the LICENSE file in the root directory of this source tree.
65
+ */const qc=se("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/**
66
+ * @license lucide-react v0.469.0 - ISC
67
+ *
68
+ * This source code is licensed under the ISC license.
69
+ * See the LICENSE file in the root directory of this source tree.
70
+ */const Na=se("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
71
+ * @license lucide-react v0.469.0 - ISC
72
+ *
73
+ * This source code is licensed under the ISC license.
74
+ * See the LICENSE file in the root directory of this source tree.
75
+ */const Ia=se("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
76
+ * @license lucide-react v0.469.0 - ISC
77
+ *
78
+ * This source code is licensed under the ISC license.
79
+ * See the LICENSE file in the root directory of this source tree.
80
+ */const _s=se("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/**
81
+ * @license lucide-react v0.469.0 - ISC
82
+ *
83
+ * This source code is licensed under the ISC license.
84
+ * See the LICENSE file in the root directory of this source tree.
85
+ */const Wc=se("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/**
86
+ * @license lucide-react v0.469.0 - ISC
87
+ *
88
+ * This source code is licensed under the ISC license.
89
+ * See the LICENSE file in the root directory of this source tree.
90
+ */const Kc=se("FileArchive",[["path",{d:"M10 12v-1",key:"v7bkov"}],["path",{d:"M10 18v-2",key:"1cjy8d"}],["path",{d:"M10 7V6",key:"dljcrl"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v16a2 2 0 0 0 .274 1.01",key:"gkbcor"}],["circle",{cx:"10",cy:"20",r:"2",key:"1xzdoj"}]]);/**
91
+ * @license lucide-react v0.469.0 - ISC
92
+ *
93
+ * This source code is licensed under the ISC license.
94
+ * See the LICENSE file in the root directory of this source tree.
95
+ */const Gc=se("FileAudio",[["path",{d:"M17.5 22h.5a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"rslqgf"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 19a2 2 0 1 1 4 0v1a2 2 0 1 1-4 0v-4a6 6 0 0 1 12 0v4a2 2 0 1 1-4 0v-1a2 2 0 1 1 4 0",key:"9f7x3i"}]]);/**
96
+ * @license lucide-react v0.469.0 - ISC
97
+ *
98
+ * This source code is licensed under the ISC license.
99
+ * See the LICENSE file in the root directory of this source tree.
100
+ */const $i=se("FileCode",[["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}]]);/**
101
+ * @license lucide-react v0.469.0 - ISC
102
+ *
103
+ * This source code is licensed under the ISC license.
104
+ * See the LICENSE file in the root directory of this source tree.
105
+ */const Xc=se("FileImage",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]]);/**
106
+ * @license lucide-react v0.469.0 - ISC
107
+ *
108
+ * This source code is licensed under the ISC license.
109
+ * See the LICENSE file in the root directory of this source tree.
110
+ */const Ri=se("FileSpreadsheet",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]]);/**
111
+ * @license lucide-react v0.469.0 - ISC
112
+ *
113
+ * This source code is licensed under the ISC license.
114
+ * See the LICENSE file in the root directory of this source tree.
115
+ */const yn=se("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/**
116
+ * @license lucide-react v0.469.0 - ISC
117
+ *
118
+ * This source code is licensed under the ISC license.
119
+ * See the LICENSE file in the root directory of this source tree.
120
+ */const Yc=se("FileVideo",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m10 11 5 3-5 3v-6Z",key:"7ntvm4"}]]);/**
121
+ * @license lucide-react v0.469.0 - ISC
122
+ *
123
+ * This source code is licensed under the ISC license.
124
+ * See the LICENSE file in the root directory of this source tree.
125
+ */const Qc=se("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);/**
126
+ * @license lucide-react v0.469.0 - ISC
127
+ *
128
+ * This source code is licensed under the ISC license.
129
+ * See the LICENSE file in the root directory of this source tree.
130
+ */const Zc=se("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/**
131
+ * @license lucide-react v0.469.0 - ISC
132
+ *
133
+ * This source code is licensed under the ISC license.
134
+ * See the LICENSE file in the root directory of this source tree.
135
+ */const Jc=se("Languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]);/**
136
+ * @license lucide-react v0.469.0 - ISC
137
+ *
138
+ * This source code is licensed under the ISC license.
139
+ * See the LICENSE file in the root directory of this source tree.
140
+ */const Pi=se("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
141
+ * @license lucide-react v0.469.0 - ISC
142
+ *
143
+ * This source code is licensed under the ISC license.
144
+ * See the LICENSE file in the root directory of this source tree.
145
+ */const Di=se("LogIn",[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]]);/**
146
+ * @license lucide-react v0.469.0 - ISC
147
+ *
148
+ * This source code is licensed under the ISC license.
149
+ * See the LICENSE file in the root directory of this source tree.
150
+ */const ed=se("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/**
151
+ * @license lucide-react v0.469.0 - ISC
152
+ *
153
+ * This source code is licensed under the ISC license.
154
+ * See the LICENSE file in the root directory of this source tree.
155
+ */const td=se("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/**
156
+ * @license lucide-react v0.469.0 - ISC
157
+ *
158
+ * This source code is licensed under the ISC license.
159
+ * See the LICENSE file in the root directory of this source tree.
160
+ */const rd=se("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/**
161
+ * @license lucide-react v0.469.0 - ISC
162
+ *
163
+ * This source code is licensed under the ISC license.
164
+ * See the LICENSE file in the root directory of this source tree.
165
+ */const La=se("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/**
166
+ * @license lucide-react v0.469.0 - ISC
167
+ *
168
+ * This source code is licensed under the ISC license.
169
+ * See the LICENSE file in the root directory of this source tree.
170
+ */const sd=se("MicOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
171
+ * @license lucide-react v0.469.0 - ISC
172
+ *
173
+ * This source code is licensed under the ISC license.
174
+ * See the LICENSE file in the root directory of this source tree.
175
+ */const nd=se("Mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
176
+ * @license lucide-react v0.469.0 - ISC
177
+ *
178
+ * This source code is licensed under the ISC license.
179
+ * See the LICENSE file in the root directory of this source tree.
180
+ */const ad=se("Monitor",[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]]);/**
181
+ * @license lucide-react v0.469.0 - ISC
182
+ *
183
+ * This source code is licensed under the ISC license.
184
+ * See the LICENSE file in the root directory of this source tree.
185
+ */const id=se("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
186
+ * @license lucide-react v0.469.0 - ISC
187
+ *
188
+ * This source code is licensed under the ISC license.
189
+ * See the LICENSE file in the root directory of this source tree.
190
+ */const od=se("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
191
+ * @license lucide-react v0.469.0 - ISC
192
+ *
193
+ * This source code is licensed under the ISC license.
194
+ * See the LICENSE file in the root directory of this source tree.
195
+ */const ld=se("PanelLeftClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);/**
196
+ * @license lucide-react v0.469.0 - ISC
197
+ *
198
+ * This source code is licensed under the ISC license.
199
+ * See the LICENSE file in the root directory of this source tree.
200
+ */const cd=se("PanelLeftOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]);/**
201
+ * @license lucide-react v0.469.0 - ISC
202
+ *
203
+ * This source code is licensed under the ISC license.
204
+ * See the LICENSE file in the root directory of this source tree.
205
+ */const dd=se("Paperclip",[["path",{d:"M13.234 20.252 21 12.3",key:"1cbrk9"}],["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 0 2.828 2 2 0 0 0 2.828 0l8.414-8.586a4 4 0 0 0 0-5.656 4 4 0 0 0-5.656 0l-8.415 8.585a6 6 0 1 0 8.486 8.486",key:"1pkts6"}]]);/**
206
+ * @license lucide-react v0.469.0 - ISC
207
+ *
208
+ * This source code is licensed under the ISC license.
209
+ * See the LICENSE file in the root directory of this source tree.
210
+ */const ud=se("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/**
211
+ * @license lucide-react v0.469.0 - ISC
212
+ *
213
+ * This source code is licensed under the ISC license.
214
+ * See the LICENSE file in the root directory of this source tree.
215
+ */const Ui=se("Pen",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]]);/**
216
+ * @license lucide-react v0.469.0 - ISC
217
+ *
218
+ * This source code is licensed under the ISC license.
219
+ * See the LICENSE file in the root directory of this source tree.
220
+ */const fd=se("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
221
+ * @license lucide-react v0.469.0 - ISC
222
+ *
223
+ * This source code is licensed under the ISC license.
224
+ * See the LICENSE file in the root directory of this source tree.
225
+ */const hd=se("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/**
226
+ * @license lucide-react v0.469.0 - ISC
227
+ *
228
+ * This source code is licensed under the ISC license.
229
+ * See the LICENSE file in the root directory of this source tree.
230
+ */const Oi=se("Presentation",[["path",{d:"M2 3h20",key:"91anmk"}],["path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3",key:"2k9sn8"}],["path",{d:"m7 21 5-5 5 5",key:"bip4we"}]]);/**
231
+ * @license lucide-react v0.469.0 - ISC
232
+ *
233
+ * This source code is licensed under the ISC license.
234
+ * See the LICENSE file in the root directory of this source tree.
235
+ */const md=se("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
236
+ * @license lucide-react v0.469.0 - ISC
237
+ *
238
+ * This source code is licensed under the ISC license.
239
+ * See the LICENSE file in the root directory of this source tree.
240
+ */const pd=se("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
241
+ * @license lucide-react v0.469.0 - ISC
242
+ *
243
+ * This source code is licensed under the ISC license.
244
+ * See the LICENSE file in the root directory of this source tree.
245
+ */const Fn=se("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
246
+ * @license lucide-react v0.469.0 - ISC
247
+ *
248
+ * This source code is licensed under the ISC license.
249
+ * See the LICENSE file in the root directory of this source tree.
250
+ */const Ea=se("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
251
+ * @license lucide-react v0.469.0 - ISC
252
+ *
253
+ * This source code is licensed under the ISC license.
254
+ * See the LICENSE file in the root directory of this source tree.
255
+ */const $n=se("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/**
256
+ * @license lucide-react v0.469.0 - ISC
257
+ *
258
+ * This source code is licensed under the ISC license.
259
+ * See the LICENSE file in the root directory of this source tree.
260
+ */const gd=se("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
261
+ * @license lucide-react v0.469.0 - ISC
262
+ *
263
+ * This source code is licensed under the ISC license.
264
+ * See the LICENSE file in the root directory of this source tree.
265
+ */const xd=se("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/**
266
+ * @license lucide-react v0.469.0 - ISC
267
+ *
268
+ * This source code is licensed under the ISC license.
269
+ * See the LICENSE file in the root directory of this source tree.
270
+ */const zi=se("ThumbsDown",[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]]);/**
271
+ * @license lucide-react v0.469.0 - ISC
272
+ *
273
+ * This source code is licensed under the ISC license.
274
+ * See the LICENSE file in the root directory of this source tree.
275
+ */const Bi=se("ThumbsUp",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
276
+ * @license lucide-react v0.469.0 - ISC
277
+ *
278
+ * This source code is licensed under the ISC license.
279
+ * See the LICENSE file in the root directory of this source tree.
280
+ */const Hi=se("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/**
281
+ * @license lucide-react v0.469.0 - ISC
282
+ *
283
+ * This source code is licensed under the ISC license.
284
+ * See the LICENSE file in the root directory of this source tree.
285
+ */const bd=se("Trash",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}]]);/**
286
+ * @license lucide-react v0.469.0 - ISC
287
+ *
288
+ * This source code is licensed under the ISC license.
289
+ * See the LICENSE file in the root directory of this source tree.
290
+ */const Rn=se("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
291
+ * @license lucide-react v0.469.0 - ISC
292
+ *
293
+ * This source code is licensed under the ISC license.
294
+ * See the LICENSE file in the root directory of this source tree.
295
+ */const yd=se("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/**
296
+ * @license lucide-react v0.469.0 - ISC
297
+ *
298
+ * This source code is licensed under the ISC license.
299
+ * See the LICENSE file in the root directory of this source tree.
300
+ */const Pn=se("Volume2",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]]);/**
301
+ * @license lucide-react v0.469.0 - ISC
302
+ *
303
+ * This source code is licensed under the ISC license.
304
+ * See the LICENSE file in the root directory of this source tree.
305
+ */const wd=se("VolumeX",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]]);/**
306
+ * @license lucide-react v0.469.0 - ISC
307
+ *
308
+ * This source code is licensed under the ISC license.
309
+ * See the LICENSE file in the root directory of this source tree.
310
+ */const Je=se("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/**
311
+ * @license lucide-react v0.469.0 - ISC
312
+ *
313
+ * This source code is licensed under the ISC license.
314
+ * See the LICENSE file in the root directory of this source tree.
315
+ */const vd=se("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);/**
316
+ * @license lucide-react v0.469.0 - ISC
317
+ *
318
+ * This source code is licensed under the ISC license.
319
+ * See the LICENSE file in the root directory of this source tree.
320
+ */const kd=se("ZoomIn",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);function Sd(t){const e=t.trim().split(`
321
+ `);if(e.length<2)return!1;const r=e[0].trim();if(!r.startsWith("|")||(r.match(/\|/g)||[]).length<2)return!1;const n=e[1].trim();if(!n.startsWith("|")||!/^[\s|:|-]+$/.test(n)||!n.includes("-"))return!1;for(let s=2;s<e.length;s++){const a=e[s].trim();if(a!==""&&!a.startsWith("|"))return!1}return!0}function jd(t){return t.replace(/(^|\n)(```|~~~)\s*\n([\s\S]*?)\n\2(\n|$)/g,(e,r,n,s,a)=>Sd(s)?`${r}
322
+ ${s.trim()}
323
+ ${a}`:e)}function Cd(t){const e={};let r=0;return t=t.replace(/\$\$([\s\S]*?)\$\$/g,(n,s)=>{const a=`__DISPLAY_MATH_${r++}__`;return e[a]=`$$${s}$$`,a}),t=t.replace(/\\\[([\s\S]*?)\\\]/g,(n,s)=>{const a=`__DISPLAY_MATH_${r++}__`;return e[a]=`$$${s}$$`,a}),t=t.replace(/\\\(([\s\S]*?)\\\)/g,(n,s)=>{const a=`__INLINE_MATH_${r++}__`;return e[a]=`$${s}$`,a}),t=t.replace(/(^|\n)(```|~~~)([^\n]*)\n([\s\S]*?)\n\2(\n|$)/g,(n,s,a,o,l,c)=>{const d=`__FENCED_CODE_${r++}__`;return e[d]=`${s}${a}${o}
324
+ ${l}
325
+ ${a}${c}`,d}),t=t.replace(/`([^`]+)`/g,n=>{const s=`__INLINE_CODE_${r++}__`;return e[s]=n,s}),{masked:t,masks:e}}function Ad(t){const e={};let r=0;return t=t.replace(new RegExp("(?<!\\$)\\$(?!\\$)([^$\\n]+?)(?<!\\$)\\$(?!\\$)","g"),(n,s)=>{const a=s.trim();if(/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?(?:\s?[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion)?$/.test(a))return n;const l=`__INLINE_MATH_${r++}__`;return e[l]=`$${s}$`,l}),{masked:t,masks:e}}const _a=/\\(?:iiint|iint|oint|int|sum|prod|lim|frac|sqrt|sin|cos|tan|sec|csc|cot|arcsin|arccos|arctan|ln|log|exp|Delta|nabla|partial)\b/;function Nd(t){const e=/(__INLINE_MATH_\d+__|__DISPLAY_MATH_\d+__|__CURRENCY_\d+__)/g,r=/^(__INLINE_MATH_\d+__|__DISPLAY_MATH_\d+__|__CURRENCY_\d+__)$/;return t.split(`
326
+ `).map(n=>_a.test(n)?n.split(e).map(s=>!s||r.test(s)||!_a.test(s)||s.includes("$")?s:s.replace(/\\(?:iiint|iint|oint|int|sum|prod|lim|frac|sqrt|sin|cos|tan|sec|csc|cot|arcsin|arccos|arctan|ln|log|exp|Delta|nabla|partial)\b[^\n]*/g,a=>{const o=a.trimEnd();return o?`$${o}$${a.slice(o.length)}`:a})).join(""):n).join(`
327
+ `)}function Id(t){return t.replace(/\$([^$\n]*?)\s*=\s*\$([^$\n]+)\$\s*([^$\n]*?)\$/g,(e,r,n,s)=>{const a=String(r).trimEnd(),o=String(n).trim(),l=String(s).trim(),c=[o,l].filter(Boolean).join(" ");return`$${a} = ${c}$`})}function Ld(t){const e=t.split(`
328
+ `);for(let n=0;n<e.length-1;n++){const s=e[n],a=e[n+1]??"";if(!s||!a)continue;const o=a.trim();if(!(o.startsWith("|")&&o.includes("-")))continue;const c=s.indexOf("|");if(c<=0)continue;const d=s.slice(0,c);if(!d||d.trim()==="")continue;const u=d.trim(),f=u.replace(/\s+/g,""),m=f!==""&&/^[>]+$/.test(f),g=/^[-*+]\s*$/.test(u),p=/^\d+\.\s*$/.test(u);if(m||g||p)continue;const x=s.slice(c);if((x.match(/\|/g)||[]).length<2)continue;const v=d.replace(/\s+$/,""),A=x.replace(/^\s+/,"");v&&(e.splice(n,1,v,A),n++)}const r=[];for(let n=0;n<e.length;n++){const s=e[n],a=s.trim(),l=(e[n+1]??"").trim();a.startsWith("|")&&(a.match(/\|/g)||[]).length>=2&&l.startsWith("|")&&/^[\s|:-]+$/.test(l)&&l.includes("-")&&r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push(s)}return r.join(`
329
+ `)}const Ta=["aligned","align","align*","array","cases","pmatrix","bmatrix","vmatrix","Vmatrix","matrix","smallmatrix","gather","gather*","multline","multline*","split","flalign","flalign*","eqnarray","equation","equation*"];function Ed(t,e){let r=0,n=`__${e}_${r}__`;for(;Object.prototype.hasOwnProperty.call(t,n);)r++,n=`__${e}_${r}__`;return n}function _d(t,e){if(!Ta.length)return t;const r=Ta.join("|"),n=new RegExp(String.raw`\\begin\{(${r})\}([\s\S]*?)\\end\{\1\}`,"g");return t.replace(n,(s,a,o,l,c)=>{const d=c.slice(0,l),u=c.slice(l+s.length),f=/(\$\$|\\\[)\s*$/.test(d),m=/^\s*(\$\$|\\\])/.test(u);if(f&&m)return s;const g=d.lastIndexOf("\\["),p=d.lastIndexOf("\\]");if(g>p&&g!==-1&&/\\]/.test(u))return s;const y=/\$\$/g;let v=0;for(;y.exec(d)!==null;)v++;if(v%2===1&&/\$\$/.test(u))return s;if((d.replace(/\$\$/g,"__DD__").replace(/\\\$/g,"__ES__").match(/\$/g)||[]).length%2===1){const k=u.replace(/\$\$/g,"__DD__").replace(/\\\$/g,"__ES__");if(/^[^$]*\$(?!\$)/.test(k))return s}const _=Ed(e,"LATEX_ENV"),b=s.trim();return e[_]=`
330
+ $$
331
+ ${b}
332
+ $$
333
+ `,_})}function Td(t,e){for(const[r,n]of Object.entries(e)){const s=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");t=t.replace(s,()=>n)}return t}const Md=t=>{if(!t||typeof t!="string")return"";try{let e=t.replace(/\r\n/g,`
334
+ `).replace(/\r/g,`
335
+ `);e=jd(e);const{masked:r,masks:n}=Cd(e);e=r,e=e.replace(/<br\s*\/?>/gi,`
336
+ `),e=e.replace(/\\(ne|neq)\$(?=\s*[-+0-9A-Za-z(])/g,"\\$1"),e=Id(e),e=Ld(e),e=_d(e,n);const s=new Map;let a=0;const o=String.raw`-?\$\(?\d{1,3}(?:,\d{3})*(?:\.\d+)?\)?(?:\s?(?:[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion))?|\$-?\d+(?:\.\d+)?(?:\s?(?:[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion))?`,l=new RegExp(String.raw`(${o})(\s?[–-]\s?)(${o})`,"g");e=e.replace(l,(m,g,p,x)=>{const y=`__CURRENCY_${a++}__`,v=`__CURRENCY_${a++}__`;return s.set(y,g),s.set(v,x),`${y}${p}${v}`});const c=new RegExp(String.raw`-?\$\(?\d{1,3}(?:,\d{3})*(?:\.\d+)?\)?(?:\s?(?:[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion))?(?!\w)|\$-?\d+(?:\.\d+)?(?:\s?(?:[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion))?(?!\w)`,"g");e=e.replace(c,(m,g,p)=>{if(p.substring(g+m.length).match(/^[a-zA-Z]/)&&!m.match(/[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion$/))return m;const y=`__CURRENCY_${a++}__`;return s.set(y,m),y});const{masked:d,masks:u}=Ad(e);return e=d,Object.assign(n,u),e=Nd(e),[/(?:^|\s)([a-zA-Z0-9]+\s*[\^_]\s*[a-zA-Z0-9{}]+(?:\s*[+\-*/]\s*[a-zA-Z0-9]+\s*[\^_]\s*[a-zA-Z0-9{}]+)*\s*=\s*[^$\n]+)(?:\s|$)/g,/(?:^|\s)(\\frac\{[^}]+\}\{[^}]+\})(?:\s|$)/g,/(?:^|\s)(\\(?:sqrt|int|sum|prod|lim|log|ln|sin|cos|tan|exp)\b[^$\n]{0,50})(?:\s|$)/g,/(?:^|\s)([A-Z][a-z]?(?:\d+)?(?:\([A-Z][a-z]?(?:\d+)?\))?(?:\d+)?(?:[+-]\d*)?)+(?:\s|$)/g].forEach(m=>{e=e.replace(m,(g,p)=>{if(g.includes("$")||g.includes("__INLINE_MATH_")||g.includes("__DISPLAY_MATH_")||g.includes("__CURRENCY_"))return g;const x=String(p??"").trim();if(/^[A-Za-z]$/.test(x))return g;const y=/[\\^_+=<>]|\\b(?:frac|sqrt|sum|int|lim|log|ln|sin|cos|tan|exp)\b/.test(x),v=/\d/.test(x),A=/[()]/.test(x),I=(x.match(/[A-Z]/g)||[]).length,C=(x.match(/[a-z]/g)||[]).length,S=I>=2,E=v||A||S&&C>0;return!y&&!E?g:g.replace(p,`$${p}$`)})}),e=e.replace(new RegExp("(?<!\\\\)\\$(?!\\$)([^$\\n]*?)(?<!\\\\)\\$(?!\\$)","g"),(m,g)=>{if(m.includes("__CURRENCY_")||m.includes("__INLINE_MATH_")||m.includes("__DISPLAY_MATH_")||g.trim()==="")return m;const p=/^\d+(?:,\d{3})*(?:\.\d{2})?$/.test(g.trim()),x=/\\/.test(g),y=/[+\-*/=<>^_{}()]/.test(g),v=/[a-zA-Z].*\d|\d.*[a-zA-Z]/.test(g),A=/\\(?:alpha|beta|gamma|delta|epsilon|theta|lambda|mu|pi|sigma|omega)/.test(g),I=/\\(?:frac|sqrt|sum|int|lim|log|ln|sin|cos|tan|exp)/.test(g),C=/^[A-Za-z]$/.test(g.trim());return!p&&(x||y||v||A||I||C||g.length>1)?m:`\\$${g}\\$`}),e=e.split(`
337
+ `).map(m=>{const g=m.indexOf("$$");return g===-1||m.trim()==="$$"||m.indexOf("$$",g+2)!==-1?m:m.replace("$$","\\$\\$")}).join(`
338
+ `),s.forEach((m,g)=>{const p=m.replace(/\$/g,"&#36;");e=e.replace(new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p)}),e=e.replace(/\\&#36;/g,"&#36;"),e=Td(e,n),e=e.trimEnd()+`
339
+ `,e}catch(e){return console.warn("Error preprocessing markdown:",e),t}},Fd=h.lazy(()=>Nt(()=>import("./MermaidRenderer-DABRS6vO.js").then(t=>t.au),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.MermaidRenderer}))),$d=h.lazy(()=>Nt(()=>import("./SVGRenderer-DjrOz9Zj.js"),__vite__mapDeps([6,1,3,5,7,8,9,2,10])).then(t=>({default:t.SVGRenderer}))),Rd=h.lazy(()=>Nt(()=>import("./ChartRenderer-Dl6Q8n8G.js"),__vite__mapDeps([11,1,5,4,12,13,14,15,16,17,7,8,9,2,10])).then(t=>({default:t.ChartRenderer}))),Pd=h.lazy(()=>Nt(()=>import("./MusicRenderer-DhhgLEOM.js"),__vite__mapDeps([18,2,1,5,7,8,9,10])).then(t=>({default:t.MusicRenderer}))),Dd=t=>{var n,s;if(!t)return typeof window<"u"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light";const e=t.closest(".markdown-content");if(e){if(e.classList.contains("dark"))return"dark";if(e.classList.contains("light"))return"light"}if(t.closest(".dark"))return"dark";if(t.closest(".light"))return"light";const r=t.closest("[data-theme]");if(r){const a=r.getAttribute("data-theme");if(a==="dark")return"dark";if(a==="light")return"light"}return typeof window<"u"&&((s=window.matchMedia)!=null&&s.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Ud=(t,e)=>{const[r,n]=h.useState("light"),s=h.useRef("light");return h.useEffect(()=>{var d,u,f;if(e||typeof window>"u"||typeof document>"u")return;const a=()=>{const m=Dd(t.current);m!==s.current&&(s.current=m,n(m))};a();const o=((d=window.matchMedia)==null?void 0:d.call(window,"(prefers-color-scheme: dark)"))??null,l=()=>a();o==null||o.addEventListener("change",l);const c=typeof MutationObserver<"u"?new MutationObserver(()=>a()):null;if(c){const m=((f=(u=t.current)==null?void 0:u.closest)==null?void 0:f.call(u,".markdown-content"))??null;m&&c.observe(m,{attributes:!0,attributeFilter:["class","data-theme"]}),document.body&&c.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]})}return()=>{o==null||o.removeEventListener("change",l),c==null||c.disconnect()}},[e,t]),e??r},Od={js:"javascript",jsx:"javascript",ts:"typescript",tsx:"tsx",sh:"bash",shell:"bash",shellsession:"bash",yml:"yaml",yaml:"yaml",py:"python",rb:"ruby",kt:"kotlin",md:"markdown",csharp:"csharp","c#":"csharp","c++":"cpp",tf:"hcl",terraform:"hcl",docker:"dockerfile",dotenv:"env",env:"env",plaintext:"text",text:"text"},zd=t=>{if(!t)return"";const e=t.match(/(?:^|\s)language-([^\s]+)/);if(!e)return"";const n=e[1].toLowerCase().split("{")[0].split("[")[0].split("<")[0].split(":")[0].trim().replace(/[^a-z0-9+#-]+$/g,"");return n?Od[n]??n:""},Bd=t=>gt.Children.toArray(t).map(e=>typeof e=="string"||typeof e=="number"?String(e):"").join("").replace(/\n$/,""),Ma=({code:t})=>{const{t:e}=Ie(),[r,n]=h.useState(!1),s=async()=>{try{await navigator.clipboard.writeText(t),n(!0),setTimeout(()=>n(!1),2e3)}catch{const a=document.createElement("textarea");a.value=t,a.style.position="fixed",a.style.opacity="0",document.body.appendChild(a),a.select();try{document.execCommand("copy"),n(!0),setTimeout(()=>n(!1),2e3)}catch(o){console.error("Failed to copy code:",o)}document.body.removeChild(a)}};return i.jsxs("button",{className:"code-copy-button",onClick:s,title:e(r?"markdown.codeBlock.copied":"markdown.codeBlock.copyTitle"),"aria-label":e(r?"markdown.codeBlock.copied":"markdown.codeBlock.copyAriaLabel"),children:[r?i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:i.jsx("path",{d:"M13.5 4.5L6 12L2.5 8.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):i.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M5.5 4.5H3.5C2.94772 4.5 2.5 4.94772 2.5 5.5V12.5C2.5 13.0523 2.94772 13.5 3.5 13.5H10.5C11.0523 13.5 11.5 13.0523 11.5 12.5V10.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),i.jsx("path",{d:"M6.5 2.5H12.5C13.0523 2.5 13.5 2.94772 13.5 3.5V9.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),i.jsx("path",{d:"M9.5 6.5L13.5 2.5L9.5 2.5V6.5Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),i.jsx("span",{className:"code-copy-button-text",children:e(r?"markdown.codeBlock.copied":"markdown.codeBlock.copyLabel")})]})},Hd=({inline:t,className:e="",children:r,enableGraphs:n=!0,enableMermaid:s=!0,enableSVG:a=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d})=>{const{t:u}=Ie(),f=h.useRef(null),m=Ud(f,d),g=i.jsx("div",{className:"markdown-code-block code-block-container",children:u("markdown.codeBlock.loadingRenderer")});if(t)return i.jsx("code",{className:e,children:r});const p=zd(e),x=Bd(r);if(o&&(p==="chart"||p==="chart-json"||p==="chart-table"))return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:g,children:i.jsx(Rd,{code:x,language:p})})});if(l&&(p==="abc"||p==="music"))return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:g,children:i.jsx(Pd,{code:x})})});if(n){if(p==="mermaid"&&s)return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:g,children:i.jsx(Fd,{code:x})})});if(p==="svg"&&a)return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:g,children:i.jsx($d,{code:x})})})}if(c&&p){const y=m==="light"?el:tl;return i.jsxs("div",{ref:f,className:"syntax-highlighted-wrapper code-block-container",children:[i.jsx(Ma,{code:x}),i.jsx(Jo,{language:p,style:y,customStyle:{margin:"12px 0",borderRadius:"6px",fontSize:"0.9em"},showLineNumbers:!1,children:x})]})}return i.jsxs("div",{ref:f,className:`markdown-code-block code-block-container ${e}`.trim(),children:[i.jsx(Ma,{code:x}),i.jsx("pre",{style:{margin:0,padding:0,background:"transparent",border:"none"},children:i.jsx("code",{children:x})})]})},Fa=new Set(["div","pre","blockquote","ul","ol","table","thead","tbody","tr","td","th","h1","h2","h3","h4","h5","h6","section","article","figure"]),$a=({children:t,href:e="",className:r="",standalone:n=!1,...s})=>{const a=gt.Children.toArray(t).map(f=>typeof f=="string"?f:"").join("").trim(),o=/^https?:\/\//i.test(e),l=!!(o&&a&&Ra(a)===Ra(e)),c=o?Vd(e):null,d=!!(n&&l&&c),u=["markdown-link",d?"markdown-link--card":"markdown-link--inline",r].filter(Boolean).join(" ");return i.jsxs("a",{...s,href:e,target:"_blank",rel:"noopener noreferrer",className:u,children:[i.jsx("span",{className:"markdown-link__content",children:d&&c?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"markdown-link__hostname",children:c.hostname}),c.path&&c.path!=="/"&&i.jsx("span",{className:"markdown-link__path",children:c.path})]}):t}),o&&i.jsx("span",{className:"markdown-link__icon","aria-hidden":"true",children:i.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:i.jsx("path",{d:"M8 16L16 8M16 8H9M16 8V15",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})})})]})};function Ra(t){return t.trim().replace(/\/$/,"")}function Vd(t){try{const e=new URL(t),r=e.hostname.replace(/^www\./i,""),n=`${e.pathname}${e.search}${e.hash}`||"/";return{hostname:r,path:n}}catch{return null}}const $t=({content:t,className:e="",disableMath:r=!1,enableGraphs:n=!0,enableMermaid:s=!0,enableSVG:a=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d="dark"})=>{const u=Md(t);if(!u)return null;const f=r?[oa]:[oa,[Qo,{singleDollarTextMath:!0}]],m=[];r||m.push([Zo,{throwOnError:!1,errorColor:"#cc0000",strict:!1,trust:!0,macros:{"\\RR":"\\mathbb{R}","\\NN":"\\mathbb{N}","\\ZZ":"\\mathbb{Z}","\\QQ":"\\mathbb{Q}","\\CC":"\\mathbb{C}","\\dx":"\\,dx","\\dy":"\\,dy","\\dt":"\\,dt","\\dz":"\\,dz"}}]);const g={table:({children:p,...x})=>i.jsx("div",{style:{overflowX:"auto",WebkitOverflowScrolling:"touch"},children:i.jsx("table",{...x,children:p})}),a:$a,code:p=>{const{className:x,children:y,...v}=p,A=x&&/language-/.test(x),I="inline"in p&&typeof p.inline=="boolean"&&p.inline||!A,C=A;return i.jsx(Hd,{inline:I,className:x,enableGraphs:n,enableMermaid:s,enableSVG:a,enableCharts:o,enableMusic:l,enableSyntaxHighlighting:c,syntaxTheme:d,"data-block-code":C?"true":void 0,...v,children:y})},p:({node:p,...x})=>{var C;const y=gt.Children.toArray(x.children).filter(S=>!(typeof S=="string"&&S.trim()==="")),v=y.some(S=>{if(!gt.isValidElement(S))return!1;const E=S.props;return(E==null?void 0:E["data-block-code"])==="true"?!0:typeof S.type=="string"?Fa.has(S.type):!1}),A=(C=p==null?void 0:p.children)==null?void 0:C.some(S=>{var E;if(S.type==="code")return!0;if(S.type==="element"){if(S.tagName&&Fa.has(S.tagName))return!0;if(S.tagName==="code"){const _=(E=S.properties)==null?void 0:E.className;return Array.isArray(_)?_.some(b=>typeof b=="string"&&b.startsWith("language-")):!0}}return!1});if(v||A)return i.jsx(i.Fragment,{children:x.children});if(y.length===1&&gt.isValidElement(y[0])&&y[0].type===$a){const S=y[0];return i.jsx("p",{...x,children:gt.cloneElement(S,{standalone:!0})})}return i.jsx("p",{...x})}};return i.jsx("div",{className:`markdown-content ${e}`,children:i.jsx(Yo,{remarkPlugins:f,rehypePlugins:m,components:g,children:u})})},Dn=()=>Q.debug.consoleDebug,D=(...t)=>{Dn()&&console.log(...t)},ge=(...t)=>{Dn()&&console.warn(...t)},xe=(...t)=>{Dn()&&console.error(...t)},ze=(...t)=>{console.error(...t)};function Pa(t){return t==="mp3"?"audio/mpeg":t==="wav"?"audio/wav":t==="ogg"?"audio/ogg":t==="opus"?"audio/opus":t==="webm"?"audio/webm":`audio/${t}`}function ns({audio:t,audioUrl:e,audioFormat:r="mp3",autoPlay:n=!1,maxSizeMB:s=10,downloadFilename:a}){const{t:o}=Ie(),{isDark:l}=tr(),c=h.useRef(null),[d,u]=h.useState(!1),[f,m]=h.useState(0),[g,p]=h.useState(0),[x,y]=h.useState(!0),[v,A]=h.useState(null),[I,C]=h.useState(null),[S,E]=h.useState(null);h.useEffect(()=>{if(!t)return;let L=null,O=!0;return(async()=>{try{y(!0),A(null),C(null);const G=t.length*3/4/(1024*1024);if(G>s)throw new Error(o("audio.player.audioFileTooLargePlaceholder",{sizeMB:G.toFixed(1),maxMB:s}));if(G>2&&(C(o("audio.player.largeAudioWarning",{sizeMB:G.toFixed(1)})),D("[AudioPlayer] Large audio file detected",{sizeMB:G.toFixed(2)})),!/^[A-Za-z0-9+/=]+$/.test(t.replace(/\s/g,"")))throw new Error(o("audio.player.invalidBase64Error"));const V=atob(t),J=new Uint8Array(V.length);for(let $=0;$<V.length;$++)J[$]=V.charCodeAt($);const ue=Pa(r),Ee=new Blob([J],{type:ue});if(L=URL.createObjectURL(Ee),!O){L&&URL.revokeObjectURL(L);return}E(L),y(!1),D("[AudioPlayer] Audio loaded successfully",{format:r,mimeType:ue,size:Ee.size})}catch(Y){xe("[AudioPlayer] Failed to load audio:",Y),O&&(A(o("audio.player.loadFailureError")),y(!1))}})(),()=>{O=!1,L&&URL.revokeObjectURL(L)}},[t,r,s,o]),h.useEffect(()=>{if(t||!e)return;let L=null,O=!1;return(async()=>{try{y(!0),A(null);const Y=typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null,G=await fetch(e,{headers:Y?{"X-Adapter-Name":Y}:{}});if(!G.ok)throw new Error(`Server returned ${G.status}`);if(O)return;const V=await G.arrayBuffer();if(O)return;const J=new Blob([V],{type:Pa(r)});L=URL.createObjectURL(J),E(L),y(!1)}catch(Y){xe("[AudioPlayer] Failed to fetch audio from",e,Y),O||(A(o("audio.player.loadFailureError")),y(!1))}})(),()=>{O=!0,L&&URL.revokeObjectURL(L)}},[t,e,r,o]),h.useEffect(()=>{n&&S&&c.current&&c.current.play().catch(L=>{xe("[AudioPlayer] Auto-play failed:",L)})},[n,S]);const _=()=>{c.current&&m(c.current.duration)},b=()=>{c.current&&p(c.current.currentTime)},F=()=>u(!0),k=()=>u(!1),N=()=>{u(!1),p(0)},U=()=>{c.current&&(d?c.current.pause():c.current.play().catch(L=>{xe("[AudioPlayer] Playback failed:",L),A(o("audio.player.playbackFailureError"))}))},T=L=>{if(!c.current)return;const O=parseFloat(L.target.value);c.current.currentTime=O,p(O)},H=()=>{if(!S)return;const L=document.createElement("a");L.href=S,L.download=a||`generated-audio.${r}`,L.click()},j=L=>{if(!isFinite(L))return"0:00";const O=Math.floor(L/60),M=Math.floor(L%60);return`${O}:${M.toString().padStart(2,"0")}`};return v?i.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-700 dark:bg-red-900/20 dark:text-red-400",children:[i.jsx(Pn,{className:"h-4 w-4"}),i.jsx("span",{children:v})]}):i.jsxs("div",{className:"mt-3 flex flex-col gap-1",children:[I&&i.jsxs("div",{className:"text-xs text-amber-600 dark:text-amber-400 px-1",children:["⚠️ ",I]}),i.jsxs("div",{className:"flex items-center gap-3 rounded-md border border-gray-200 bg-white/80 px-3 py-2 dark:border-[#3b3c49] dark:bg-white/5",children:[i.jsx("audio",{ref:c,src:S??void 0,onLoadedMetadata:_,onTimeUpdate:b,onPlay:F,onPause:k,onEnded:N}),i.jsx("button",{onClick:U,disabled:x,className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 disabled:opacity-50 dark:bg-[#4a4b54] dark:hover:bg-[#565869]",title:o(d?"audio.player.pauseTitle":"audio.player.playTitle"),"aria-label":o(d?"audio.player.pauseAriaLabel":"audio.player.playAriaLabel"),children:x?i.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-gray-400 border-t-transparent"}):d?i.jsx(ud,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"}):i.jsx(fd,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"})}),i.jsxs("div",{className:"flex flex-1 items-center gap-2",children:[i.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:j(g)}),i.jsx("input",{type:"range",min:"0",max:f||0,value:g,onChange:T,disabled:x||!f,className:"flex-1 cursor-pointer accent-gray-600 dark:accent-[#bfc2cd]",style:{background:(()=>{const L=l?"rgb(191 194 205)":"rgb(75 85 99)",O=l?"rgba(255 255 255 / 0.12)":"rgb(229 231 235)",M=f?g/f*100:0;return`linear-gradient(to right, ${L} 0%, ${L} ${M}%, ${O} ${M}%, ${O} 100%)`})()}}),i.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:j(f)})]}),a&&i.jsx("button",{onClick:H,disabled:x||!S,className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 disabled:opacity-50 dark:bg-[#4a4b54] dark:hover:bg-[#565869]",title:o("audio.player.downloadAudioTooltip"),children:i.jsx(_s,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"})})]})]})}function Da({image:t,imageUrl:e,imageFormat:r="png",revisedPrompt:n}){const{t:s}=Ie(),[a,o]=h.useState(!1),[l,c]=h.useState(!1),[d,u]=h.useState(null),f=h.useRef(null);h.useEffect(()=>{if(t||!e)return;let x=!1;return(async()=>{try{const y=typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null,v=await fetch(e,{headers:y?{"X-Adapter-Name":y}:{}});if(!v.ok){console.warn("[ImageDisplay] Server returned",v.status,"for",e);return}if(x)return;const A=await v.arrayBuffer();if(x)return;const I=new Blob([A],{type:`image/${r}`}),C=URL.createObjectURL(I);f.current=C,u(C)}catch(y){console.warn("[ImageDisplay] Failed to fetch image from",e,y)}})(),()=>{x=!0,f.current&&(URL.revokeObjectURL(f.current),f.current=null)}},[e,t,r]);const g=(t?`data:image/${r};base64,${t}`:null)??d;h.useEffect(()=>{if(!a)return;const x=y=>{y.key==="Escape"&&o(!1)};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[a]);const p=x=>{if(x.stopPropagation(),!g)return;const y=document.createElement("a");y.href=g,y.download=`generated-image.${r}`,y.click()};return g?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"generated-image-wrapper",style:{marginTop:"0.75rem"},children:[i.jsxs("div",{className:"generated-image-container",style:{position:"relative",display:"inline-block",cursor:"zoom-in",maxWidth:"100%"},onClick:()=>o(!0),title:n||s("imageDisplay.generatedImageTitle"),children:[i.jsx("img",{src:g,alt:n||s("imageDisplay.generatedImageAlt"),style:{maxWidth:"100%",maxHeight:"480px",borderRadius:"8px",display:"block",objectFit:"contain"}}),i.jsxs("div",{style:{position:"absolute",bottom:"8px",right:"8px",display:"flex",gap:"6px"},children:[i.jsx("button",{onClick:p,title:s("imageDisplay.downloadImageTooltip"),style:{background:"rgba(0,0,0,0.55)",border:"none",borderRadius:"6px",padding:"5px",cursor:"pointer",color:"#fff",display:"flex",alignItems:"center"},children:i.jsx(_s,{size:14})}),i.jsx("button",{onClick:x=>{x.stopPropagation(),o(!0)},title:s("imageDisplay.viewFullSizeTooltip"),style:{background:"rgba(0,0,0,0.55)",border:"none",borderRadius:"6px",padding:"5px",cursor:"pointer",color:"#fff",display:"flex",alignItems:"center"},children:i.jsx(kd,{size:14})})]})]}),n&&i.jsxs("div",{style:{marginTop:"8px",maxWidth:"480px"},children:[i.jsxs("button",{type:"button",onClick:()=>c(x=>!x),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:0,background:"transparent",border:"none",cursor:"pointer",fontSize:"0.75rem",fontWeight:500,opacity:.72},"aria-expanded":l,children:[l?i.jsx(bs,{size:14}):i.jsx(hr,{size:14}),s(l?"imageDisplay.hidePrompt":"imageDisplay.showPrompt")]}),l&&i.jsxs("div",{style:{marginTop:"8px",padding:"8px 10px",background:"rgba(128,128,128,0.08)",borderRadius:"6px"},children:[i.jsx("span",{style:{display:"block",fontSize:"0.65rem",fontWeight:600,opacity:.5,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"3px"},children:s("imageDisplay.promptLabel")}),i.jsx("span",{style:{fontSize:"0.8rem",lineHeight:1.45,opacity:.85},children:n})]})]})]}),a&&typeof document<"u"&&As.createPortal(i.jsxs("div",{onClick:()=>o(!1),style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.85)",zIndex:9999,overflow:"auto",padding:"56px 24px 24px"},children:[i.jsx("button",{onClick:x=>{x.stopPropagation(),o(!1)},style:{position:"fixed",top:"16px",right:"16px",background:"rgba(255,255,255,0.15)",border:"none",borderRadius:"50%",padding:"8px",cursor:"pointer",color:"#fff",display:"flex",alignItems:"center"},children:i.jsx(Je,{size:20})}),i.jsx("img",{src:g,alt:n||s("imageDisplay.generatedImageAlt"),style:{display:"block",width:"auto",height:"auto",maxWidth:"calc(100vw - 48px)",maxHeight:"calc(100vh - 80px)",objectFit:"contain",borderRadius:"8px",margin:"0 auto"},onClick:x=>x.stopPropagation()})]}),document.body)]}):null}const tn=[750,1500,3e3,5e3],qd=new Set([403,404,409,425,429,500,502,503,504]),Wd=t=>new Promise(e=>setTimeout(e,t));function Ua({video:t,videoUrl:e,videoFormat:r="mp4",revisedPrompt:n,adapterName:s}){const{t:a}=Ie(),[o,l]=h.useState(!1),[c,d]=h.useState(!1),[u,f]=h.useState(null),m=h.useRef(null);h.useEffect(()=>{if(t||!e)return;let y=!1;return(async()=>{try{const v=s||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null);let A=null;for(let E=0;E<=tn.length&&(A=await fetch(e,{headers:v?{"X-Adapter-Name":v}:{}}),!(A.ok||!qd.has(A.status)||E===tn.length));E+=1)if(await Wd(tn[E]),y)return;if(!A||!A.ok){console.warn("[VideoDisplay] Server returned",A==null?void 0:A.status,"for",e);return}if(y)return;const I=await A.arrayBuffer();if(y)return;const C=new Blob([I],{type:`video/${r}`}),S=URL.createObjectURL(C);m.current=S,f(S)}catch(v){console.warn("[VideoDisplay] Failed to fetch video from",e,v)}})(),()=>{y=!0,m.current&&(URL.revokeObjectURL(m.current),m.current=null)}},[e,t,r,s]);const p=(t?`data:video/${r};base64,${t}`:null)??u;h.useEffect(()=>{if(!o)return;const y=v=>{v.key==="Escape"&&l(!1)};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[o]);const x=y=>{if(y.stopPropagation(),!p)return;const v=document.createElement("a");v.href=p,v.download=`generated-video.${r}`,v.click()};return p?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"generated-video-wrapper",style:{marginTop:"0.75rem"},children:[i.jsxs("div",{style:{position:"relative",display:"inline-block",maxWidth:"100%"},children:[i.jsx("video",{src:p,controls:!0,style:{maxWidth:"100%",maxHeight:"480px",borderRadius:"8px",display:"block",backgroundColor:"#000"}}),i.jsxs("div",{style:{position:"absolute",bottom:"48px",right:"8px",display:"flex",gap:"6px"},children:[i.jsx("button",{onClick:x,title:a("videoDisplay.downloadVideoTooltip"),style:{background:"rgba(0,0,0,0.55)",border:"none",borderRadius:"6px",padding:"5px",cursor:"pointer",color:"#fff",display:"flex",alignItems:"center"},children:i.jsx(_s,{size:14})}),i.jsx("button",{onClick:y=>{y.stopPropagation(),l(!0)},title:a("videoDisplay.viewFullSizeTooltip"),style:{background:"rgba(0,0,0,0.55)",border:"none",borderRadius:"6px",padding:"5px",cursor:"pointer",color:"#fff",display:"flex",alignItems:"center"},children:i.jsx(td,{size:14})})]})]}),n&&i.jsxs("div",{style:{marginTop:"8px",maxWidth:"480px"},children:[i.jsxs("button",{type:"button",onClick:()=>d(y=>!y),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:0,background:"transparent",border:"none",cursor:"pointer",fontSize:"0.75rem",fontWeight:500,opacity:.72},"aria-expanded":c,children:[c?i.jsx(bs,{size:14}):i.jsx(hr,{size:14}),a(c?"videoDisplay.hidePrompt":"videoDisplay.showPrompt")]}),c&&i.jsxs("div",{style:{marginTop:"8px",padding:"8px 10px",background:"rgba(128,128,128,0.08)",borderRadius:"6px"},children:[i.jsx("span",{style:{display:"block",fontSize:"0.65rem",fontWeight:600,opacity:.5,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"3px"},children:a("videoDisplay.promptLabel")}),i.jsx("span",{style:{fontSize:"0.8rem",lineHeight:1.45,opacity:.85},children:n})]})]})]}),o&&i.jsxs("div",{onClick:()=>l(!1),style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.9)",zIndex:9999,display:"flex",alignItems:"center",justifyContent:"center"},children:[i.jsx("button",{onClick:y=>{y.stopPropagation(),l(!1)},style:{position:"fixed",top:"16px",right:"16px",background:"rgba(255,255,255,0.15)",border:"none",borderRadius:"50%",padding:"8px",cursor:"pointer",color:"#fff",display:"flex",alignItems:"center"},children:i.jsx(Je,{size:20})}),i.jsx("video",{src:p,controls:!0,autoPlay:!0,style:{maxWidth:"92vw",maxHeight:"92vh",borderRadius:"8px"},onClick:y=>y.stopPropagation()})]})]}):null}let ys=null;function Vi(t){ys=t}function Ts(){ys=null}async function Un(){if(!ys)return null;try{return await ys()}catch{return null}}let wn=!1,Pr=null;const vn=new Set;function qi(){vn.forEach(t=>t())}function vt(){return wn}function Kd(){return Pr}function Ms(t){wn!==t&&(wn=t,!t&&Pr!==null&&(Pr=null),qi())}function fr(t){const e=typeof t=="string"&&t.trim().length>0?t.trim():null;Pr!==e&&(Pr=e,qi())}function Gd(t){return vn.add(t),()=>{vn.delete(t)}}const Oa="orbitchat-guest-user-id";function as(t){if(typeof t!="string")return null;const e=t.trim();return e.length>0?e:null}function Xd(t){const e=t.split(".");if(e.length<2)return null;try{const r=e[1].replace(/-/g,"+").replace(/_/g,"/"),n=r.padEnd(Math.ceil(r.length/4)*4,"="),s=atob(n);return JSON.parse(s)}catch{return null}}function Yd(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return`guest:orbitchat:${t.randomUUID()}`;if(!t||typeof t.getRandomValues!="function")throw new Error("Secure random number generation is unavailable");const e=new Uint8Array(16);return t.getRandomValues(e),`guest:orbitchat:${Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}`}function Qd(){if(typeof window>"u")return"guest:orbitchat:server";const t=window.localStorage.getItem(Oa);if(t&&t.trim().length>0)return t;const e=Yd();return window.localStorage.setItem(Oa,e),e}async function Wi(){const t=Kd();if(t)return t;const e=await Un();if(e){const r=Xd(e),n=as(r==null?void 0:r.sub)||as(r==null?void 0:r.user_id)||as(r==null?void 0:r.preferred_username)||as(r==null?void 0:r.email);if(n)return n}return vt()?"authenticated:orbitchat:unknown":Qd()}const Zd={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",md:"text/markdown",csv:"text/csv"},za={pdf:"PDF",docx:"Word document",xlsx:"Excel workbook",pptx:"PowerPoint deck",md:"Markdown document",csv:"CSV file"},ms=/[\uE000-\uF8FF]|\\[eE][0-9a-fA-F]{2,3}|\\[fF][0-8][0-9a-fA-F]{2,3}/,Jd=/((?:p\.)?generated-docx-preview-num-\d+-\d+:before\s*\{[^}]*?)content\s*:\s*"([^"]*)"\s*;([^}]*?\})/g;function eu(t){var r;return ms.test(t)?`•${((r=t.match(/(?:\\9|\t|\u00A0| )+$/))==null?void 0:r[0])||"\\9"}`:null}function Ba(t){Array.from(t.querySelectorAll("style")).forEach(n=>{const s=n.textContent;!s||!ms.test(s)||(n.textContent=s.replace(Jd,(a,o,l,c)=>{const d=eu(l);if(!d)return a;const u=c.replace(/\s*font-family\s*:\s*[^;{}]+;?/gi,"");return`${o}content: "${d}";${u}`}))}),Array.from(t.querySelectorAll('span[style*="font-family"]')).forEach(n=>{if(!/\b(symbol|wingdings|webdings)\b/i.test(n.style.fontFamily))return;const s=n.textContent||"";ms.test(s)&&(n.textContent=s.replace(ms,"•"),n.style.fontFamily="")})}function tu(t){return(t||"pdf").toLowerCase().replace(/^\./,"")||"pdf"}function ru(t){const e=window.atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.charCodeAt(n);return r.buffer}function su(t){return t==="xlsx"||t==="csv"?i.jsx(Ri,{className:"h-5 w-5"}):t==="pptx"?i.jsx(Oi,{className:"h-5 w-5"}):t==="md"?i.jsx($i,{className:"h-5 w-5"}):i.jsx(yn,{className:"h-5 w-5"})}function Ha({document:t,documentUrl:e,documentFormat:r="pdf",revisedPrompt:n,adapterName:s}){const{t:a}=Ie(),o=tu(r),[l,c]=h.useState(t||e?"loading":"idle"),[d,u]=h.useState(null),[f,m]=h.useState(null),[g,p]=h.useState([]),[x,y]=h.useState(""),[v,A]=h.useState(null),[I,C]=h.useState([]),[S,E]=h.useState(0),[_,b]=h.useState(!1),[F,k]=h.useState(null),N=h.useRef(null),U=h.useRef(null),T=h.useRef(null),H=n||za[o]||a("documentDisplay.generatedDocument"),j=h.useMemo(()=>`generated-document.${o}`,[o]),L=Zd[o]||"application/octet-stream";h.useEffect(()=>{if(!t&&!e)return;let G=!1;return(async()=>{c("loading"),k(null),p([]),y(""),A(null),C([]),E(0);try{const J=t?ru(t):await(async()=>{const $=(s==null?void 0:s.trim())||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),re={"X-User-ID":await Wi()};$&&(re["X-Adapter-Name"]=$);const X=await Un();X&&(re.Authorization=`Bearer ${X}`);const K=await fetch(e,{headers:re});if(!K.ok)throw new Error(`Server returned ${K.status}`);return K.arrayBuffer()})();if(G)return;const ue=new Blob([J],{type:L}),Ee=URL.createObjectURL(ue);if(N.current&&URL.revokeObjectURL(N.current),N.current=Ee,u(Ee),m(J.slice(0)),o==="xlsx"){const{default:$}=await Nt(async()=>{const{default:K}=await import("./index-CZz_ECqk.js");return{default:K}},[]),X=(await $(ue))[0];y((X==null?void 0:X.sheet)||"First sheet"),p(((X==null?void 0:X.data)||[]).slice(0,100).map(K=>K.slice(0,30).map(le=>le==null?"":String(le))))}if(o==="md"&&A(new TextDecoder("utf-8").decode(J)),o==="csv"){const $=new TextDecoder("utf-8").decode(J),{default:re}=await Nt(async()=>{const{default:K}=await import("./papaparse.min-D13ujVVP.js").then(le=>le.p);return{default:K}},__vite__mapDeps([19,1])),X=re.parse($,{skipEmptyLines:!0});E(X.data.length),C(X.data.slice(0,25))}c("ready")}catch(J){if(G)return;console.warn("[DocumentDisplay] Failed to load document from",e,J),k(J instanceof Error?J.message:"Unable to load document"),c("error")}})(),()=>{G=!0,N.current&&(URL.revokeObjectURL(N.current),N.current=null)}},[s,t,e,o,L]),h.useEffect(()=>{if(l!=="ready"||o!=="docx"||!f||!U.current)return;const G=U.current;G.replaceChildren(),Nt(()=>import("./docx-preview-DehBmhog.js"),__vite__mapDeps([20,1])).then(async({renderAsync:V})=>{await V(f.slice(0),G,void 0,{className:"generated-docx-preview",inWrapper:!1,ignoreWidth:!0,ignoreHeight:!0}),Ba(G)}).catch(V=>{console.warn("[DocumentDisplay] Failed to render DOCX preview",V),k("Unable to render document preview")})},[f,o,l]),h.useEffect(()=>{if(!_||o!=="docx"||!f||!T.current)return;const G=T.current;G.replaceChildren(),Nt(()=>import("./docx-preview-DehBmhog.js"),__vite__mapDeps([20,1])).then(async({renderAsync:V})=>{await V(f.slice(0),G,void 0,{className:"generated-docx-preview",inWrapper:!1,ignoreWidth:!0,ignoreHeight:!0}),Ba(G)}).catch(V=>{console.warn("[DocumentDisplay] Failed to render modal DOCX preview",V)})},[f,o,_]),h.useEffect(()=>{if(!_)return;const G=V=>{V.key==="Escape"&&b(!1)};return window.document.addEventListener("keydown",G),()=>window.document.removeEventListener("keydown",G)},[_]);const O=G=>{if(G==null||G.stopPropagation(),!d)return;const V=window.document.createElement("a");V.href=d,V.download=j,V.click()},M=l==="ready"&&(o==="pdf"||o==="docx"||o==="xlsx"||o==="md"||o==="csv"),Y=M&&o!=="xlsx"&&o!=="csv";return l==="idle"?null:i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"mt-3 max-w-full overflow-hidden rounded-lg border border-gray-200 bg-white shadow-sm dark:border-[#3b3c49] dark:bg-[#202123]",children:[i.jsxs("div",{className:"flex items-center gap-3 border-b border-gray-100 px-3 py-2.5 dark:border-[#3b3c49]",children:[i.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-blue-50 text-blue-600 dark:bg-blue-500/10 dark:text-blue-300",children:su(o)}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"truncate text-sm font-medium text-[#353740] dark:text-[#ececf1]",children:H}),i.jsxs("p",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:[za[o]||`${o.toUpperCase()} document`,l==="loading"?` · ${a("documentDisplay.loadingPreview")}`:"",l==="error"?` · ${F||a("documentDisplay.previewUnavailableShort")}`:""]})]}),Y&&i.jsx("button",{type:"button",onClick:()=>b(!0),className:"rounded-md p-2 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-[#bfc2cd] dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",title:a("documentDisplay.openPreviewTooltip"),"aria-label":a("documentDisplay.openPreviewTooltip"),children:i.jsx(Wc,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:O,disabled:!d,className:"rounded-md p-2 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-50 dark:text-[#bfc2cd] dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",title:a("documentDisplay.downloadDocumentTooltip"),"aria-label":a("documentDisplay.downloadDocumentTooltip"),children:i.jsx(_s,{className:"h-4 w-4"})})]}),M&&i.jsxs("div",{className:"max-h-[460px] overflow-auto bg-gray-50 dark:bg-[#171717]",children:[o==="pdf"&&d&&i.jsx("iframe",{src:d,title:H,className:"block h-[460px] w-full border-0 bg-white"}),o==="docx"&&i.jsx("div",{ref:U,className:"min-h-[240px] bg-white p-5 text-sm text-[#111827] dark:bg-white dark:text-[#111827]"}),o==="xlsx"&&i.jsxs("div",{className:"p-3",children:[x&&i.jsx("p",{className:"mb-2 text-xs font-medium text-gray-500 dark:text-[#bfc2cd]",children:x}),i.jsx("div",{className:"overflow-auto rounded-md border border-gray-200 bg-white dark:border-[#3b3c49] dark:bg-[#202123]",children:i.jsx("table",{className:"min-w-full border-collapse text-left text-xs",children:i.jsx("tbody",{children:g.length>0?g.map((G,V)=>i.jsx("tr",{className:V===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:G.map((J,ue)=>i.jsx("td",{className:"max-w-[220px] truncate border-b border-r border-gray-100 px-2 py-1.5 text-[#353740] dark:border-[#3b3c49] dark:text-[#ececf1]",children:J},ue))},V)):i.jsx("tr",{children:i.jsx("td",{className:"px-3 py-4 text-sm text-gray-500 dark:text-[#bfc2cd]",children:a("documentDisplay.noSheetDataFound")})})})})})]}),o==="md"&&v!==null&&i.jsx("div",{className:"bg-white p-5 text-sm text-[#111827] dark:bg-[#171717] dark:text-[#ececf1]",children:i.jsx($t,{content:v,disableMath:!0})}),o==="csv"&&i.jsxs("div",{className:"p-3",children:[S>25&&i.jsx("p",{className:"mb-2 text-xs text-gray-500 dark:text-[#bfc2cd]",children:a("documentDisplay.csvRowsPreviewMessage",{count:S})}),i.jsx("div",{className:"overflow-auto rounded-md border border-gray-200 bg-white dark:border-[#3b3c49] dark:bg-[#202123]",children:i.jsx("table",{className:"min-w-full border-collapse text-left text-xs",children:i.jsx("tbody",{children:I.length>0?I.map((G,V)=>i.jsx("tr",{className:V===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:G.map((J,ue)=>i.jsx("td",{className:"max-w-[220px] truncate border-b border-r border-gray-100 px-2 py-1.5 text-[#353740] dark:border-[#3b3c49] dark:text-[#ececf1]",children:J},ue))},V)):i.jsx("tr",{children:i.jsx("td",{className:"px-3 py-4 text-sm text-gray-500 dark:text-[#bfc2cd]",children:a("documentDisplay.noDataFound")})})})})})]})]}),l==="ready"&&!M&&i.jsx("div",{className:"px-3 py-4 text-sm text-gray-600 dark:text-[#bfc2cd]",children:a("documentDisplay.previewUnavailable")})]}),_&&d&&i.jsxs("div",{onClick:()=>b(!1),className:"fixed inset-0 z-[9999] flex items-center justify-center bg-black/85 p-4",children:[i.jsx("button",{onClick:G=>{G.stopPropagation(),b(!1)},className:"fixed right-4 top-4 flex items-center rounded-full border-0 bg-white/15 p-2 text-white",title:a("common.close"),"aria-label":a("common.close"),children:i.jsx(Je,{className:"h-5 w-5"})}),i.jsxs("div",{onClick:G=>G.stopPropagation(),className:"h-[92vh] w-[92vw] overflow-auto rounded-lg bg-white",children:[o==="pdf"&&i.jsx("iframe",{src:d,title:H,className:"h-full w-full border-0"}),o==="docx"&&i.jsx("div",{ref:T,className:"min-h-full bg-white p-8 text-[#111827]"}),o==="md"&&v!==null&&i.jsx("div",{className:"min-h-full bg-white p-8 text-sm text-[#111827]",children:i.jsx($t,{content:v,disableMath:!0})})]})]})]})}const nu=["a[href]","area[href]",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])","button:not([disabled])","iframe","object","embed",'[contenteditable="true"]','[tabindex]:not([tabindex="-1"])'].join(",");function Dr(t,{enabled:e,onEscape:r}){h.useEffect(()=>{if(!e||!t.current)return;const n=t.current,s=document.activeElement,a=Array.from(n.querySelectorAll(nu)).filter(d=>d.tabIndex!==-1),o=a[0]||n,l=a[a.length-1]||n;o.focus({preventScroll:!0});const c=d=>{if(d.key==="Escape"){r==null||r();return}if(d.key!=="Tab")return;if(a.length===0){d.preventDefault(),n.focus({preventScroll:!0});return}const u=document.activeElement;if(d.shiftKey){(!u||u===o||!n.contains(u))&&(d.preventDefault(),l.focus({preventScroll:!0}));return}(!u||u===l||!n.contains(u))&&(d.preventDefault(),o.focus({preventScroll:!0}))};return document.addEventListener("keydown",c),()=>{var d;document.removeEventListener("keydown",c),(d=s==null?void 0:s.focus)==null||d.call(s,{preventScroll:!0})}},[e,r,t])}function ws({isOpen:t,onClose:e,onConfirm:r,title:n,message:s,confirmText:a,cancelText:o,type:l="danger",isLoading:c=!1}){const d=h.useRef(null);Dr(d,{enabled:t,onEscape:e});const{t:u}=Ie(),f=a??u("common.confirm"),m=o??u("common.cancel");if(!t)return null;const g=()=>{c||r()},x=(()=>{switch(l){case"danger":return{icon:"text-red-500",iconBg:"bg-red-100 dark:bg-red-900/20",confirmButton:"bg-red-600 hover:bg-red-700 focus:ring-red-500",border:"border-red-200 dark:border-red-800"};case"warning":return{icon:"text-amber-500",iconBg:"bg-amber-100 dark:bg-amber-900/20",confirmButton:"bg-amber-600 hover:bg-amber-700 focus:ring-amber-500",border:"border-amber-200 dark:border-amber-800"};default:return{icon:"text-blue-500",iconBg:"bg-blue-100 dark:bg-blue-900/20",confirmButton:"bg-blue-600 hover:bg-blue-700 focus:ring-blue-500",border:"border-blue-200 dark:border-blue-800"}}})(),y=i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center overflow-y-auto bg-black/60 p-4 backdrop-blur-sm animate-fadeIn",children:i.jsxs("div",{ref:d,role:"dialog","aria-modal":"true","aria-labelledby":"confirm-title",tabIndex:-1,className:"w-full max-w-md max-h-[calc(100vh-2rem)] overflow-y-auto rounded-2xl bg-white shadow-2xl transform animate-fadeIn dark:bg-[#1a1b1e]",children:[i.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-[#2d2f39]",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`w-10 h-10 rounded-full ${x.iconBg} flex items-center justify-center`,children:i.jsx(Rn,{className:`w-5 h-5 ${x.icon}`})}),i.jsx("h2",{id:"confirm-title",className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:n})]}),i.jsx("button",{type:"button",onClick:e,className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors","aria-label":u("common.close"),children:i.jsx(Je,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),i.jsx("div",{className:"p-6",children:i.jsx("p",{className:"text-gray-600 dark:text-gray-300 leading-relaxed",children:s})}),i.jsxs("div",{className:"flex items-center justify-end gap-3 p-6 border-t border-gray-200 dark:border-[#2d2f39] bg-gray-50 dark:bg-[#131416] rounded-b-2xl",children:[i.jsx("button",{type:"button",onClick:e,disabled:c,className:"px-4 py-3 md:py-2.5 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m}),i.jsx("button",{type:"button",onClick:g,disabled:c,className:`px-4 py-3 md:py-2.5 text-white rounded-lg transition-all font-medium shadow-sm hover:shadow-md transform hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-white dark:focus:ring-offset-gray-800 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none ${x.confirmButton}`,children:c?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"}),u("confirmationModal.loadingLabel")]}):f})]})]})});return typeof document>"u"?y:As.createPortal(y,document.body)}const au=["#","*","`","[","]","(",")","{","}","|","<",">"],Ki=t=>au.some(e=>t.includes(e));function Gi(t){if(!t||t.length<1e3)return!1;const e=/^[A-Za-z0-9+/=]+$/,r=t.replace(/\s+/g,"");if(r.length>1e4&&e.test(r)){const n=/\b(the|and|for|are|but|not|you|all|can|function|const|let|var|class|return|import|export|async|await|if|else|while|true|false|null|undefined|http|https|www|error|data|response|request|api|json|xml|html|css|js|py|java|cpp|def|print|console|log)\b/i.test(t),s=Ki(t),a=/[-.,;:!?'"()]/.test(t);if(!n&&!s&&!a)return!0}return!!(r.length>5e4&&e.test(r)&&t.replace(/[A-Za-z0-9+/=\s]/g,"").length<10)}const iu=/(?:\u202F|\u2009|\u200A|\u200B|\u200C|\u200D|\uFEFF)/g;function Ur(t){if(!t)return t;let e=t.replace(iu," ");if(Gi(e))return"";const r=/([A-Za-z0-9+/=]{10000,})/g;return e=e.replace(r,n=>{const s=n.replace(/\s+/g,"");if(s.length>1e4&&/^[A-Za-z0-9+/=]+$/.test(s)){const a=/\b(function|const|let|var|class|return|import|export|if|else|while|for|true|false|null|def|print)\b/i.test(n),o=Ki(n),l=/[-.,;:!?'"()]/.test(n);if(!a&&!o&&!l)return""}return n}),e}function kn(t,e=5e4){return!t||t.length<=e?t:Gi(t)?"":t.substring(0,e)+`
340
+
341
+ ... (content truncated due to length)`}const ou={maxFilesPerConversation:Q.limits.files.perConversation,maxFileSizeMB:Q.limits.files.maxSizeMB,maxTotalFiles:Q.limits.files.totalFiles,maxConversations:Q.limits.conversations.maxConversations,maxMessagesPerConversation:Q.limits.conversations.messagesPerConversation,maxMessagesPerThread:Q.limits.conversations.messagesPerThread,maxTotalMessages:Q.limits.conversations.totalMessages,maxMessageLength:Q.limits.messages.maxLength};function lu(t){const e=Q.guestLimits;switch(t){case"maxConversations":return e.conversations.maxConversations;case"maxMessagesPerConversation":return e.conversations.messagesPerConversation;case"maxMessagesPerThread":return e.conversations.messagesPerThread;case"maxTotalMessages":return e.conversations.totalMessages;case"maxFilesPerConversation":return e.files.perConversation;case"maxTotalFiles":return e.files.totalFiles;case"maxMessageLength":return e.messages.maxLength;case"maxFileSizeMB":return e.files.maxSizeMB;default:return}}const oe=new Proxy(ou,{get(t,e){if(rt()&&!vt()){const r=lu(e);if(r!==void 0)return r}return t[e]}});function mr(){return h.useSyncExternalStore(Gd,vt,vt)}class Xi extends Error{constructor(r,n){super(r);Ze(this,"status");Ze(this,"statusText");this.name="ApiRequestError",this.status=n.status,this.statusText=n.statusText}}async function Ue(t={}){const e={"X-User-ID":await Wi(),...t},r=await Un();return r&&(e.Authorization=`Bearer ${r}`),e}function Ct(t){return encodeURIComponent(t)}function cu(t){return!t||t.length===0?"":`?file_ids=${t.map(encodeURIComponent).join(",")}`}async function Lr(t){const e=`API request failed: ${t.status} ${t.statusText}`;try{if((t.headers.get("content-type")||"").includes("application/json")){const n=await t.json(),s=typeof n.detail=="string"&&n.detail.trim()||typeof n.error=="string"&&n.error.trim()||typeof n.message=="string"&&n.message.trim();if(s)return`${e}: ${s}`}else{const n=(await t.text()).trim();if(n)return`${e}: ${n}`}}catch{}return e}function Va(t){if(!t.startsWith("data: "))return null;try{const e=JSON.parse(t.substring(6));return e.request_id&&!e.response&&!e.done?{text:"",done:!1,request_id:e.request_id}:{text:e.text||e.content||e.message||e.response||"",done:e.done||!1,request_id:e.request_id,audio:e.audio,audioFormat:e.audio_format||e.audioFormat,audio_chunk:e.audio_chunk,chunk_index:e.chunk_index,image:e.image,image_format:e.image_format,image_revised_prompt:e.image_revised_prompt,image_url:e.image_url,video:e.video,video_format:e.video_format,video_revised_prompt:e.video_revised_prompt,video_url:e.video_url,document:e.document,document_format:e.document_format,document_revised_prompt:e.document_revised_prompt,document_url:e.document_url,generated_audio_url:e.generated_audio_url,generated_audio_format:e.generated_audio_format,generated_audio_revised_prompt:e.generated_audio_revised_prompt,model:e.model,assistant_message_id:e.assistant_message_id,threading:e.threading}}catch{return null}}let is=null;function du(){let t=null,e=null;const r=(s,a,o)=>{t=a||null,e=o||null},n=(s,a)=>({async*streamChat(o,l,c,d,u,f,m,g,p,x,y,v,A,I){var E,_;const C={messages:[{role:"user",content:o}],stream:l!==!1};c&&c.length>0&&(C.file_ids=c),d&&(C.thread_id=d),u&&(C.audio_input=u),f&&(C.audio_format=f),m&&(C.language=m),g!==void 0&&(C.return_audio=g),p&&(C.tts_voice=p),x&&(C.source_language=x),y&&(C.target_language=y),v&&(C.model=v),A&&(C.skill=A),I&&(C.regenerate_of_message_id=I);const S=await fetch("/api/v1/chat",{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":s,...a?{"X-Session-ID":a}:{}}),body:JSON.stringify(C)});if(!S.ok)throw new Error(await Lr(S));if((E=S.headers.get("content-type"))!=null&&E.includes("text/event-stream")){const b=(_=S.body)==null?void 0:_.getReader(),F=new TextDecoder;let k="";if(!b)throw new Error("Response body is not readable");for(;;){const{done:N,value:U}=await b.read();if(N)break;k+=F.decode(U,{stream:!0});const T=k.split(`
342
+ `);k=T.pop()||"";for(const H of T){const j=Va(H);j&&(yield j)}}if(k.trim())for(const N of k.split(`
343
+ `)){const U=Va(N);U&&(yield U)}}else{const b=await S.json();yield{text:b.message||b.response||"",done:!0,audio:b.audio,audioFormat:b.audio_format||b.audioFormat,image:b.image,image_format:b.image_format,image_revised_prompt:b.image_revised_prompt,image_url:b.image_url,video:b.video,video_format:b.video_format,video_revised_prompt:b.video_revised_prompt,video_url:b.video_url,document:b.document,document_format:b.document_format,document_revised_prompt:b.document_revised_prompt,document_url:b.document_url,generated_audio_url:b.generated_audio_url,generated_audio_format:b.generated_audio_format,generated_audio_revised_prompt:b.generated_audio_revised_prompt,model:b.model,assistant_message_id:b.assistant_message_id,threading:b.threading}}},async createThread(o,l){const c=await fetch("/api/threads",{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":s,"X-Session-ID":l}),body:JSON.stringify({message_id:o,session_id:l})});if(!c.ok)throw new Error(`Failed to create thread: ${c.statusText}`);return c.json()},async getThreadInfo(o){const l=await fetch(`/api/threads/${Ct(o)}`,{headers:await Ue({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to get thread info: ${l.statusText}`);return l.json()},async deleteThread(o){const l=await fetch(`/api/threads/${Ct(o)}`,{method:"DELETE",headers:await Ue({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to delete thread: ${l.statusText}`);return l.json()},async submitFeedback(o,l,c){const d=await fetch("/api/feedback",{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":s,"X-Session-ID":l}),body:JSON.stringify({message_id:o,session_id:l,feedback_type:c})});if(!d.ok)throw new Error(`Failed to submit feedback: ${d.statusText}`);return d.json()},async getSessionFeedback(o){const l=await fetch(`/api/feedback/${Ct(o)}`,{headers:await Ue({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to get feedback: ${l.statusText}`);return l.json()},async clearConversationHistory(o){const l=o||a;if(!l)throw new Error("No session ID available for clearing conversation history");const c=await fetch(`/api/admin/chat-history/${Ct(l)}`,{method:"DELETE",headers:await Ue({"X-Adapter-Name":s})});if(!c.ok)throw new Error(`Failed to clear history: ${c.statusText}`);return c.json()},async getConversationHistory(o,l){const c=o||a;if(!c)throw new Error("No session ID available for conversation history");const d=typeof l=="number"&&Number.isFinite(l)&&l>0?`?limit=${Math.floor(l)}`:"",u=await fetch(`/api/admin/chat-history/${Ct(c)}${d}`,{headers:await Ue({"X-Adapter-Name":s})});if(!u.ok)throw new Error(`Failed to load history: ${u.statusText}`);return u.json()},async deleteConversationWithFiles(o,l){const c=o||a;if(!c)throw new Error("No session ID available for deleting conversation");const d=cu(l),u=await fetch(`/api/admin/conversations/${Ct(c)}${d}`,{method:"DELETE",headers:await Ue({"X-Adapter-Name":s})});if(!u.ok)throw new Error(`Failed to delete conversation: ${u.statusText}`);return u.json()},getSessionId:()=>a,async uploadFile(o){const l=new FormData;l.append("file",o);const c=await fetch("/api/files/upload",{method:"POST",headers:await Ue({"X-Adapter-Name":s}),body:l});if(!c.ok)throw new Error(`Failed to upload file: ${c.statusText}`);return c.json()},async listFiles(){const o=await fetch("/api/files",{headers:await Ue({"X-Adapter-Name":s})});if(!o.ok)throw new Error(`Failed to list files: ${o.statusText}`);const l=await o.json();return Array.isArray(l)?l:l.files||[]},async getFileInfo(o){const l=await fetch(`/api/files/${Ct(o)}`,{headers:await Ue({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to get file info: ${l.statusText}`);return l.json()},async queryFile(o,l,c){const d=await fetch(`/api/files/${Ct(o)}/query`,{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":s}),body:JSON.stringify({query:l,max_results:c})});if(!d.ok)throw new Error(`Failed to query file: ${d.statusText}`);return d.json()},async deleteFile(o){const l=await fetch(`/api/files/${Ct(o)}`,{method:"DELETE",headers:await Ue({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to delete file: ${l.statusText}`);return l.json()},async validateApiKey(){const o=await fetch(`/api/admin/api-keys/${Ct(s)}/status`,{headers:await Ue({"X-Adapter-Name":s})});if(!o.ok)throw new Error(`Failed to validate API key: ${o.statusText}`);return o.json()},async getAdapterInfo(){const o="/api/admin/adapters/info",l=f=>{if(!f)return 0;const m=Number(f);if(Number.isFinite(m)&&m>0)return Math.min(m*1e3,3e4);const g=Date.parse(f);if(!Number.isNaN(g)){const p=g-Date.now();if(p>0)return Math.min(p,3e4)}return 0},c=f=>new Promise(m=>setTimeout(m,f)),d=async()=>fetch(o,{headers:await Ue({"X-Adapter-Name":s})});let u=await d();if(u.status===429){const f=l(u.headers.get("Retry-After"));f>0&&(await c(f),u=await d())}if(!u.ok){const f=await u.text(),m=`${u.status} ${u.statusText}`.trim(),g=u.status===401?`Adapter info request was unauthorized for '${s}'. Verify the adapter exists and you have access.`:`Failed to load adapter info (${m}) for '${s}'.`;throw console.warn("[ProxyApi] Adapter info request failed",{adapter:s,status:u.status,statusText:u.statusText,details:f||void 0}),new Xi(g,u)}return u.json()},async stopChat(o,l){const c=await fetch("/api/v1/chat/stop",{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":s}),body:JSON.stringify({session_id:o,request_id:l})});return c.ok?(await c.json()).status==="cancelled":(console.warn(`[ProxyApi] stopChat failed: ${c.status} ${c.statusText}`),!1)},async getAdapterModels(o){const l=await fetch(`/api/admin/adapters/${encodeURIComponent(o)}/models`,{headers:await Ue({"X-Adapter-Name":s})});if(!l.ok)throw new Error(await Lr(l));return l.json()},async getAllModels(){const o=await fetch("/api/admin/models",{headers:await Ue({"X-Adapter-Name":s})});if(!o.ok)throw new Error(await Lr(o));return o.json()},async getAdapterSkills(o){const l=await fetch(`/api/admin/adapters/${encodeURIComponent(o)}/skills`,{headers:await Ue({"X-Adapter-Name":s})});if(!l.ok)throw new Error(await Lr(l));return l.json()},async getAllSkills(){const o=await fetch("/api/admin/skills",{headers:await Ue({"X-Adapter-Name":s})});if(!o.ok)throw new Error(await Lr(o));return o.json()}});return{configureApi:r,streamChat:async function*(s,a,o,l,c,d,u,f,m,g,p,x,y,v){if(!e)throw new Error("Adapter name is required");yield*n(e,t).streamChat(s,a,o,l,c,d,u,f,m,g,p,x,y,v)},stopChat:async(s,a)=>{if(!e)throw new Error("Adapter name is required");return n(e,t).stopChat(s,a)},ApiClient:class{constructor(a){Ze(this,"client");const o=a.adapterName||null,l=a.sessionId||null;if(!o)throw new Error("Adapter name is required");this.client=n(o,l)}async*streamChat(...a){yield*this.client.streamChat(...a)}get createThread(){var a;return(a=this.client.createThread)==null?void 0:a.bind(this.client)}get getThreadInfo(){var a;return(a=this.client.getThreadInfo)==null?void 0:a.bind(this.client)}get deleteThread(){var a;return(a=this.client.deleteThread)==null?void 0:a.bind(this.client)}get submitFeedback(){var a;return(a=this.client.submitFeedback)==null?void 0:a.bind(this.client)}get getSessionFeedback(){var a;return(a=this.client.getSessionFeedback)==null?void 0:a.bind(this.client)}get clearConversationHistory(){var a;return(a=this.client.clearConversationHistory)==null?void 0:a.bind(this.client)}get getConversationHistory(){var a;return(a=this.client.getConversationHistory)==null?void 0:a.bind(this.client)}get deleteConversationWithFiles(){var a;return(a=this.client.deleteConversationWithFiles)==null?void 0:a.bind(this.client)}get getSessionId(){var a;return(a=this.client.getSessionId)==null?void 0:a.bind(this.client)}get uploadFile(){var a;return(a=this.client.uploadFile)==null?void 0:a.bind(this.client)}get listFiles(){var a;return(a=this.client.listFiles)==null?void 0:a.bind(this.client)}get getFileInfo(){var a;return(a=this.client.getFileInfo)==null?void 0:a.bind(this.client)}get queryFile(){var a;return(a=this.client.queryFile)==null?void 0:a.bind(this.client)}get deleteFile(){var a;return(a=this.client.deleteFile)==null?void 0:a.bind(this.client)}get validateApiKey(){var a;return(a=this.client.validateApiKey)==null?void 0:a.bind(this.client)}get getAdapterInfo(){var a;return(a=this.client.getAdapterInfo)==null?void 0:a.bind(this.client)}get stopChat(){var a;return(a=this.client.stopChat)==null?void 0:a.bind(this.client)}get getAdapterModels(){var a;return(a=this.client.getAdapterModels)==null?void 0:a.bind(this.client)}get getAllModels(){var a;return(a=this.client.getAllModels)==null?void 0:a.bind(this.client)}get getAdapterSkills(){var a;return(a=this.client.getAdapterSkills)==null?void 0:a.bind(this.client)}get getAllSkills(){var a;return(a=this.client.getAllSkills)==null?void 0:a.bind(this.client)}}}}async function uu(){return is||(D("Loading API via Express proxy"),is=du(),D("API loaded successfully"),is)}async function Fe(){return await uu()}class qa{static async getAdapterSkills(e,r){const n=await Fe(),s=new n.ApiClient({apiUrl:"",adapterName:r});return s.getAdapterSkills?(await s.getAdapterSkills(e)).available_skills:[]}static async getAllSkills(e){const r=await Fe(),n=new r.ApiClient({apiUrl:"",adapterName:e});return n.getAllSkills?(await n.getAllSkills()).skills:[]}}const fu=6e4;function Yi(t={}){const{adapterName:e,enabled:r=!0,selectionScopeKey:n,supportsThreading:s=!1}=t,a=r&&!!e&&!s,o=n??e??"__default__",[l,c]=h.useState([]),[d,u]=h.useState(!1),[f,m]=h.useState(null),[g,p]=h.useState({}),x=h.useRef(null),y=h.useRef(new Map),v=h.useCallback(async S=>{var b,F;const E=S,_=y.current.get(E);if(_&&_.expiresAt>Date.now()){c(_.skills),m(S);return}x.current&&x.current.abort(),x.current=new AbortController,u(!0);try{const[k,N]=await Promise.all([qa.getAdapterSkills(S,S),qa.getAllSkills(S)]);if((b=x.current)!=null&&b.signal.aborted)return;const U=N.filter(T=>k.includes(T.name)&&T.enabled);y.current.set(E,{skills:U,expiresAt:Date.now()+fu}),c(U),m(S),D("[useSkills] Loaded",U.length,"skills for adapter",S)}catch(k){if(k instanceof Error&&k.name==="AbortError")return;ge("[useSkills] Failed to load skills:",k instanceof Error?k.message:String(k)),c([]),m(S)}finally{(F=x.current)!=null&&F.signal.aborted||u(!1)}},[]);h.useEffect(()=>{if(!a||!e)return;const S=window.setTimeout(()=>{v(e)},0);return()=>{var E;window.clearTimeout(S),(E=x.current)==null||E.abort()}},[a,e,v]);const A=h.useCallback(S=>{p(E=>{const _=E[o]??null;if(_===S||(_==null?void 0:_.name)===(S==null?void 0:S.name))return E;const b={...E};return S?b[o]=S:delete b[o],b})},[o]),I=h.useCallback(()=>{p(S=>{if(!S[o])return S;const E={...S};return delete E[o],E})},[o]),C=a?g[o]??null:null;return{skills:a&&f===e?l:[],isLoading:a?d||f!==e:!1,selectedSkill:C,selectSkill:A,clearSkill:I}}const Wa=t=>{let e;const r=new Set,n=(d,u)=>{const f=typeof d=="function"?d(e):d;if(!Object.is(f,e)){const m=e;e=u??(typeof f!="object"||f===null)?f:Object.assign({},e,f),r.forEach(g=>g(e,m))}},s=()=>e,l={setState:n,getState:s,getInitialState:()=>c,subscribe:d=>(r.add(d),()=>r.delete(d))},c=e=t(n,s,l);return l},hu=(t=>t?Wa(t):Wa),mu=t=>t;function pu(t,e=mu){const r=gt.useSyncExternalStore(t.subscribe,gt.useCallback(()=>e(t.getState()),[t,e]),gt.useCallback(()=>e(t.getInitialState()),[t,e]));return gt.useDebugValue(r),r}const Ka=t=>{const e=hu(t),r=n=>pu(e,n);return Object.assign(r,e),r},Qi=(t=>t?Ka(t):Ka),st=Qi(t=>({showLoginPrompt:!1,promptMessage:"",openLoginPrompt:e=>t({showLoginPrompt:!0,promptMessage:e}),closeLoginPrompt:()=>t({showLoginPrompt:!1,promptMessage:""})})),os=t=>{const e=t==null?void 0:t.trim();return e||(typeof window<"u"&&window.localStorage?localStorage.getItem("chat-adapter-name"):null)};class Or{static async uploadFile(e,r,n,s,a){try{const o=oe.maxFileSizeMB*1024*1024;if(e.size>o)throw new Error(`File size exceeds maximum limit of ${oe.maxFileSizeMB}MB`);if(!(["application/pdf","text/plain","text/markdown","text/csv","application/json","text/html","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel","application/vnd.ms-excel.sheet.macroEnabled.12","text/x-python","text/x-python-script","text/x-java-source","text/x-java","text/x-sql","text/javascript","application/javascript","text/typescript","application/typescript","text/x-c++src","text/x-csrc","text/x-c","text/x-go","text/x-rust","text/x-ruby","text/x-php","text/x-shellscript","text/x-sh","text/yaml","text/x-yaml","text/xml","application/xml","text/css","text/x-scss","text/x-sass","text/x-less","image/png","image/jpeg","image/tiff","image/webp","audio/wav","audio/mpeg","audio/mp3","audio/mp4","audio/ogg","audio/flac","audio/webm","audio/x-m4a","audio/aac","text/vtt"].includes(e.type)||/\.(pdf|txt|md|csv|json|html|docx|pptx|xlsx|py|java|sql|js|mjs|ts|tsx|cpp|cxx|cc|c|h|hpp|go|rs|rb|php|sh|bash|zsh|yaml|yml|xml|css|scss|sass|less|png|jpe?g|tiff?|webp|wav|mp3|mp4|ogg|flac|webm|m4a|aac|vtt)$/i.test(e.name)||(e.type==="application/x-zip-compressed"||e.type==="application/zip")&&/\.xlsx$/i.test(e.name)))throw new Error(`File type not supported: ${e.type||"unknown"}`);r&&r({filename:e.name,progress:0,status:"uploading"});const d=await Fe(),u=(s==null?void 0:s.trim())||$e(),f=os(a);if(!f)throw new Error("Adapter not configured. Please select an adapter from the dropdown.");D(`Using adapter: ${f}`);const m=new d.ApiClient({apiUrl:u,sessionId:null,adapterName:f});if(!m.uploadFile)throw new Error("File upload is not available.");const g=await m.uploadFile(e);r&&r({filename:e.name,progress:75,status:"processing",fileId:g.file_id});let p;try{p=await this.pollFileStatus(g.file_id,30,2e3,void 0,u,f)}catch(x){const y=x instanceof Error?x.message:String(x);if(y.includes("was deleted"))throw new Error(`File ${g.file_id} was deleted during upload`);ge(`File status polling failed for ${g.file_id}:`,x);const v=y.includes("processing failed")||y.includes("timeout");p={file_id:g.file_id,filename:g.filename,mime_type:g.mime_type,file_size:g.file_size,processing_status:v?"failed":g.status||"processing",chunk_count:g.chunk_count,error_message:v?y:void 0}}return r&&r({filename:e.name,progress:100,status:p.processing_status==="completed"?"completed":"processing",fileId:g.file_id}),p}catch(o){let l=o instanceof Error?o.message:"Upload failed";throw l.includes("401")&&(l="Authentication failed. Please check your adapter configuration."),r&&r({filename:e.name,progress:0,status:"error",error:l}),new Error(l)}}static async uploadFiles(e,r){const s=[],a=[];for(let o=0;o<e.length;o+=3){const l=e.slice(o,o+3),c=await Promise.allSettled(l.map(async(d,u)=>{const f=o+u;return this.uploadFile(d,m=>{r&&r(f,m)})}));for(let d=0;d<c.length;d++){const u=c[d],f=o+d;u.status==="fulfilled"?s.push(u.value):(ze(`Failed to upload file ${e[f].name}:`,u.reason),a.push({index:f,file:e[f].name,error:u.reason}))}}if(s.length===0&&a.length>0){const o=a[0].error;throw o instanceof Error?o:new Error(`All ${a.length} file uploads failed`)}return a.length>0&&ge(`[FileUploadService] ${a.length} of ${e.length} files failed to upload:`,a.map(o=>o.file)),s}static async listFiles(e,r,n){try{const s=await Fe(),a=(r==null?void 0:r.trim())||$e(),o=os(n);if(!o)throw new Error("Adapter not configured");const l=new s.ApiClient({apiUrl:a,sessionId:null,adapterName:o});if(!l.listFiles)throw new Error("File listing is not available.");const c=await l.listFiles();return(Array.isArray(c)?c:Array.isArray(c.files)?c.files:[]).map(u=>({file_id:u.file_id,filename:u.filename,mime_type:u.mime_type,file_size:u.file_size,upload_timestamp:u.upload_timestamp,processing_status:u.processing_status,chunk_count:u.chunk_count,error_message:u.error_message}))}catch(s){ze("Failed to list files:",s);const a=s instanceof Error?s.message:"Failed to list files";throw new Error(a)}}static async getFileInfo(e,r,n,s){try{const a=await Fe(),o=(n==null?void 0:n.trim())||$e(),l=os(s);if(!l)throw new Error("Adapter not configured");const c=new a.ApiClient({apiUrl:o,sessionId:null,adapterName:l});if(!c.getFileInfo)throw new Error("File info retrieval is not available.");const d=await c.getFileInfo(e);return{file_id:d.file_id,filename:d.filename,mime_type:d.mime_type,file_size:d.file_size,upload_timestamp:d.upload_timestamp,processing_status:d.processing_status,chunk_count:d.chunk_count,error_message:d.error_message}}catch(a){if(a instanceof Error&&(a.message.includes("404")||a.message.includes("File not found")))throw new Error(`File ${e} was deleted`);ze(`Failed to get file info for ${e}:`,a);const o=a instanceof Error?a.message:`Failed to get file info: ${e}`;throw new Error(o)}}static async pollFileStatus(e,r=30,n=2e3,s,a,o){for(let l=0;l<r;l++)try{if(s&&!s())throw new Error("Polling cancelled - component unmounted");const c=await this.getFileInfo(e,void 0,a,o);if(c.processing_status==="completed")return c;if(c.processing_status==="error"||c.processing_status==="failed"){const d=c.error_message;throw new Error(d||`File processing failed for ${e}`)}l<r-1&&await new Promise(d=>setTimeout(d,n))}catch(c){const d=c instanceof Error?c.message:String(c);if(d.includes("404")||d.includes("File not found")||d.includes("was deleted"))throw new Error(`File ${e} was deleted during upload`);if(d.includes("component unmounted")||d.includes("processing failed")||d.includes("processing_status")||d.includes("401")||d.includes("403")||d.includes("500")||d.includes("502")||d.includes("503")||d.includes("Authentication")||d.includes("Adapter not configured"))throw c;if(l<r-1){await new Promise(u=>setTimeout(u,n));continue}throw c}throw new Error(`File processing timeout: ${e} did not complete within ${r*n/1e3} seconds`)}static async deleteFile(e,r,n,s){try{const a=await Fe(),o=(n==null?void 0:n.trim())||$e(),l=os(s);if(!l)throw new Error("Adapter not configured");const c=new a.ApiClient({apiUrl:o,sessionId:null,adapterName:l});if(!c.deleteFile)throw new Error("File deletion is not available.");return await c.deleteFile(e)}catch(a){if(a instanceof Error&&(a.message.includes("404")||a.message.includes("File not found")||a.message.includes("Not Found")))return D(`File ${e} was already deleted from server`),{message:"File already deleted",file_id:e};ze(`Failed to delete file ${e}:`,a);const o=a instanceof Error?a.message:`Failed to delete file: ${e}`;throw new Error(o)}}}class gu{constructor(){Ze(this,"audioQueue",[]);Ze(this,"isPlaying",!1);Ze(this,"currentAudio",null);Ze(this,"audioContext",null);Ze(this,"isEnabled",!1);Ze(this,"onPlaybackStart",null);Ze(this,"onPlaybackEnd",null);Ze(this,"mimeTypeCache",new Map);Ze(this,"onChunkPlayed",null);Ze(this,"blobUrls",[]);Ze(this,"suppressPlaybackErrors",!1)}async enableAudio(){var e,r;try{if(!this.audioContext){const a=typeof AudioContext<"u"?AudioContext:typeof window<"u"&&window.webkitAudioContext||null;a&&(this.audioContext=new a)}const n=((e=this.audioContext)==null?void 0:e.state)==="suspended"?this.audioContext.resume():Promise.resolve();let s=Promise.resolve();try{const a=this.createSilentWavBlob(),o=URL.createObjectURL(a),l=new Audio;l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),l.src=o,l.volume=0,s=l.play().then(()=>{l.pause()}).catch(()=>{D("[AudioStreamManager] HTMLAudioElement silent unlock failed (will retry on next gesture)")}).finally(()=>{URL.revokeObjectURL(o)})}catch{D("[AudioStreamManager] Could not create silent audio element")}if(await n,this.audioContext&&this.audioContext.state==="running"){const a=this.audioContext.createBuffer(1,1,22050),o=this.audioContext.createBufferSource();o.buffer=a,o.connect(this.audioContext.destination),o.start(0)}return await s,this.isEnabled=!0,D("[AudioStreamManager] Audio playback enabled",{audioContextState:(r=this.audioContext)==null?void 0:r.state}),!0}catch(n){return xe("[AudioStreamManager] Failed to enable audio:",n),!1}}createSilentWavBlob(){const o=new ArrayBuffer(844),l=new DataView(o),c=(d,u)=>{for(let f=0;f<u.length;f++)l.setUint8(d+f,u.charCodeAt(f))};return c(0,"RIFF"),l.setUint32(4,836,!0),c(8,"WAVE"),c(12,"fmt "),l.setUint32(16,16,!0),l.setUint16(20,1,!0),l.setUint16(22,1,!0),l.setUint32(24,8e3,!0),l.setUint32(28,8e3*2,!0),l.setUint16(32,2,!0),l.setUint16(34,16,!0),c(36,"data"),l.setUint32(40,800,!0),new Blob([o],{type:"audio/wav"})}disableAudio(){!this.isEnabled&&!this.isPlaying||(this.isEnabled=!1,this.stop(),D("[AudioStreamManager] Audio playback disabled"))}async ensureAudioContext(){var e;if(!this.audioContext){const r=typeof AudioContext<"u"?AudioContext:typeof window<"u"&&window.webkitAudioContext||null;if(r)try{this.audioContext=new r}catch(n){return xe("[AudioStreamManager] Failed to create AudioContext:",n),!1}}if(((e=this.audioContext)==null?void 0:e.state)==="suspended")try{await this.audioContext.resume()}catch(r){return D("[AudioStreamManager] AudioContext resume deferred",r),!1}return!0}resolveMimeType(e){const r=this.mimeTypeCache.get(e);if(r)return r;let n;switch(e){case"mp3":n="audio/mpeg";break;case"wav":n="audio/wav";break;case"webm":n="audio/webm";break;case"ogg":n="audio/ogg";break;case"opus":{const s=typeof document<"u"?document.createElement("audio"):null;s!=null&&s.canPlayType("audio/ogg; codecs=opus")?n="audio/ogg; codecs=opus":s!=null&&s.canPlayType("audio/webm; codecs=opus")?n="audio/webm; codecs=opus":n="audio/mp4";break}default:n=`audio/${e}`}return this.mimeTypeCache.set(e,n),D(`[AudioStreamManager] Resolved MIME type for "${e}": ${n}`),n}isAudioEnabled(){return this.isEnabled}setOnPlaybackStart(e){this.onPlaybackStart=e}setOnPlaybackEnd(e){this.onPlaybackEnd=e}setOnChunkPlayed(e){this.onChunkPlayed=e}async addChunk(e){if(!this.isEnabled){D(`[AudioStreamManager] Audio disabled, dropping chunk ${e.chunkIndex}`);return}D(`[AudioStreamManager] Adding chunk ${e.chunkIndex} to queue`),this.audioQueue.push(e),this.audioQueue.sort((r,n)=>r.chunkIndex-n.chunkIndex),this.isPlaying||this.playNextChunk().catch(r=>{xe("[AudioStreamManager] Playback chain error:",r)})}async playNextChunk(){var r,n;if(this.audioQueue.length===0){this.isPlaying=!1,D("[AudioStreamManager] Queue empty, playback complete"),this.onPlaybackEnd&&this.onPlaybackEnd();return}if(!this.isEnabled){D("[AudioStreamManager] Audio not enabled, skipping playback"),this.audioQueue=[],this.isPlaying=!1;return}this.suppressPlaybackErrors=!1,await this.ensureAudioContext(),this.isPlaying=!0;const e=this.audioQueue.shift();try{if(!this.isPlaying)return;if(this.onPlaybackStart&&e.chunkIndex===0&&this.onPlaybackStart(),D(`[AudioStreamManager] Playing chunk ${e.chunkIndex}`),!e.audio||e.audio.length===0)throw new Error(`Empty audio data for chunk ${e.chunkIndex}`);let s;try{s=atob(e.audio)}catch(f){throw new Error(`Failed to decode base64 audio for chunk ${e.chunkIndex}: ${f instanceof Error?f.message:String(f)}`)}if(s.length===0)throw new Error(`Decoded audio data is empty for chunk ${e.chunkIndex}`);const a=new Uint8Array(s.length);for(let f=0;f<s.length;f++)a[f]=s.charCodeAt(f);const o=this.resolveMimeType(e.audioFormat),l=new Blob([a],{type:o}),c=URL.createObjectURL(l);this.blobUrls.push(c);const d=()=>{if(this.currentAudio){try{this.currentAudio.pause()}catch{}this.currentAudio.removeAttribute("src"),this.currentAudio.load()}URL.revokeObjectURL(c),this.blobUrls=this.blobUrls.filter(f=>f!==c)};let u=!1;try{u=await this.playViaAudioElement(c,e,d)}catch{u=!1}if(!u&&!this.suppressPlaybackErrors&&this.audioContext){D(`[AudioStreamManager] HTMLAudioElement failed for chunk ${e.chunkIndex}, trying AudioContext fallback`);try{u=await this.playViaAudioContext(a.buffer,e.chunkIndex)}catch(f){xe(`[AudioStreamManager] AudioContext fallback also failed for chunk ${e.chunkIndex}:`,f)}d()}this.currentAudio=null,this.playNextChunk().catch(f=>{xe("[AudioStreamManager] Playback chain error:",f)})}catch(s){if(this.suppressPlaybackErrors){D("[AudioStreamManager] Playback stopped, suppressing audio error");return}const a=s instanceof Error?s.message:String(s);console.error(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,a,s,{audioFormat:e.audioFormat,chunkIndex:e.chunkIndex,audioLength:(r=e.audio)==null?void 0:r.length,audioContextState:(n=this.audioContext)==null?void 0:n.state,isEnabled:this.isEnabled}),xe(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,s),this.playNextChunk().catch(o=>{xe("[AudioStreamManager] Playback chain error after recovery:",o)})}}playViaAudioElement(e,r,n){return new Promise(s=>{const a=new Audio;a.setAttribute("playsinline",""),a.setAttribute("webkit-playsinline",""),a.src=e,this.currentAudio=a;let o=!1;const l=u=>{o||(o=!0,s(u))},c=()=>{if(this.suppressPlaybackErrors){n(),l(!0);return}const u=a.error;xe(`[AudioStreamManager] Media error on chunk ${r.chunkIndex}:`,u?{code:u.code,message:u.message,SRC_NOT_SUPPORTED:u.code===MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED}:"unknown"),n(),l(!1)};a.addEventListener("error",c,{once:!0});const d=async()=>{if(!o)try{a.addEventListener("ended",()=>{o||(D(`[AudioStreamManager] Chunk ${r.chunkIndex} finished`),this.onChunkPlayed&&this.onChunkPlayed(r.chunkIndex),n(),l(!0))},{once:!0}),await a.play()}catch(u){if(this.suppressPlaybackErrors){n(),l(!0);return}D(`[AudioStreamManager] audio.play() rejected for chunk ${r.chunkIndex}:`,u),n(),l(!1)}};a.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA?d():a.addEventListener("canplay",()=>d(),{once:!0})})}playViaAudioContext(e,r){return new Promise((n,s)=>{if(!this.audioContext){s(new Error("No AudioContext"));return}const a=e.slice(0);this.audioContext.decodeAudioData(a,o=>{if(!this.audioContext||this.suppressPlaybackErrors){n(!0);return}const l=this.audioContext.createBufferSource();l.buffer=o,l.connect(this.audioContext.destination),l.onended=()=>{D(`[AudioStreamManager] Chunk ${r} finished (AudioContext path)`),this.onChunkPlayed&&this.onChunkPlayed(r),n(!0)},l.start(0)},o=>{s(o)})})}stop(){D("[AudioStreamManager] Stopping playback"),this.suppressPlaybackErrors=!0,this.isPlaying=!1,this.audioQueue=[],this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.blobUrls.forEach(e=>URL.revokeObjectURL(e)),this.blobUrls=[]}reset(){this.stop(),D("[AudioStreamManager] Manager reset")}getQueueSize(){return this.audioQueue.length}isCurrentlyPlaying(){return this.isPlaying}}const qt=new gu,xu=[{extensions:["pdf"],Icon:yn,colorClass:"bg-red-500"},{extensions:["doc","docx"],Icon:yn,colorClass:"bg-blue-500"},{extensions:["xls","xlsx","csv"],Icon:Ri,colorClass:"bg-emerald-600"},{extensions:["ppt","pptx"],Icon:Oi,colorClass:"bg-orange-500"},{extensions:["png","jpg","jpeg","webp","tiff","gif"],Icon:Xc,colorClass:"bg-violet-500"},{extensions:["wav","mp3","ogg","flac","webm","m4a","aac"],Icon:Gc,colorClass:"bg-teal-600"},{extensions:["mp4","mov","avi","mkv"],Icon:Yc,colorClass:"bg-pink-600"},{extensions:["zip","rar","7z","tar","gz"],Icon:Kc,colorClass:"bg-amber-600"},{extensions:["js","mjs","ts","tsx","py","java","sql","cpp","cxx","cc","c","h","hpp","go","rs","rb","php","sh","bash","zsh","yaml","yml","xml","css","scss","sass","less","json","html","vtt"],Icon:$i,colorClass:"bg-slate-500"}],bu=new Set(["png","jpg","jpeg","webp","tiff","gif"]);function yu(t){const e=/\.([a-z0-9]+)$/i.exec(t.trim());return e?e[1].toLowerCase():""}function wu(t){const e=yu(t),r=xu.find(n=>n.extensions.includes(e));return{Icon:(r==null?void 0:r.Icon)??Qc,colorClass:(r==null?void 0:r.colorClass)??"bg-gray-400 dark:bg-gray-500",label:e?e.toUpperCase():"",isImage:bu.has(e)}}const zr=new Map;function Zi(t,e){const r=zr.get(t);r&&r!==e&&URL.revokeObjectURL(r),zr.set(t,e)}function vu(t){return zr.get(t)}function Sn(t){const e=zr.get(t);e&&(URL.revokeObjectURL(e),zr.delete(t))}const ku=xc()||rc(),Ji=()=>{if(Ls())return Ln()||void 0},Fr="",Su=["New Chat","New Conversation"],ju=t=>t&&!Su.includes(t)?t:Fr,$r=(t,e,r)=>({id:t,sessionId:e,title:Fr,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:r,adapterName:Ji(),adapterLoadError:null}),vs=()=>{const t=localStorage.getItem("chatbot-session-id");if(t)return t;const e=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return localStorage.setItem("chatbot-session-id",e),e},Cu=t=>{localStorage.setItem("chatbot-session-id",t)};let Au=0;const lr=t=>{const e=Date.now(),r=++Au,n=Math.random().toString(36).substr(2,9);return`msg_${e}_${r}_${n}_${t}`},Wt=()=>{const t=Date.now(),e=Math.random().toString(36).substr(2,9);return`session_${t}_${e}`},eo=t=>{const e=new Set;let r=!1;const n=t.map(s=>{if(!e.has(s.id))return e.add(s.id),s;r=!0;const a={...s,id:lr(s.role)};return e.add(a.id),ge(`[chatStore] Re-keyed duplicate message id ${s.id}`),a});return r?n:t},Ga=t=>t.filter(e=>!e.isThreadMessage&&!(e.role==="assistant"&&e.isStreaming)).length,Xa=t=>t.flatMap(r=>[r.imageUrl,r.videoUrl,r.documentUrl]).map(r=>{var n;return((n=r==null?void 0:r.match(/\/api\/files\/([^/]+)\/content/))==null?void 0:n[1])??null}).filter(r=>r!==null),Nu=(t,e)=>{if(t instanceof Date)return new Date(t);if(typeof t=="number"&&Number.isFinite(t)){const r=new Date(t);if(!Number.isNaN(r.getTime()))return r}if(typeof t=="string"){const r=new Date(t);if(!Number.isNaN(r.getTime()))return r}return e?new Date(e):new Date},Iu=(t,e)=>{const r=new Map;e.forEach((s,a)=>{s.databaseMessageId&&r.set(s.databaseMessageId,{message:s,index:a})});const n=new Set;return t.map((s,a)=>{var f;const o=s.role==="user"?"user":"assistant",l=typeof s.message_id=="string"&&s.message_id.length>0?s.message_id:void 0;let c;if(l&&r.has(l)){const m=r.get(l);c=m.message,n.add(m.index)}else{const m=a<e.length?a:0;if(!n.has(m)&&((f=e[m])==null?void 0:f.role)===o)c=e[m],n.add(m);else for(let g=1;g<e.length;g++){const p=(m+g)%e.length;if(!n.has(p)&&e[p].role===o){c=e[p],n.add(p);break}}}const d=s.timestamp?Nu(s.timestamp,c==null?void 0:c.timestamp):c!=null&&c.timestamp?new Date(c.timestamp):new Date,u=c?{...c,content:s.content??c.content,timestamp:d}:{id:l?`srv_${l}`:lr(o),content:s.content||"",role:o,timestamp:d};if(u.isStreaming=!1,l&&(u.databaseMessageId=l),!u.supportsThreading&&s.metadata&&typeof s.metadata=="object"){const m=s.metadata,g=m==null?void 0:m.retrieved_docs;Array.isArray(g)&&g.length>0&&(u.supportsThreading=!0)}return u})},Lu=(t,e)=>{if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){const n=t[r],s=e[r];if(n.role!==s.role||n.content!==s.content||(n.databaseMessageId||null)!==(s.databaseMessageId||null)||+n.timestamp!=+s.timestamp)return!1}return!0},to=t=>{var s,a,o,l,c,d;const e=((a=(s=t.adapterInfo)==null?void 0:s.adapter_name)==null?void 0:a.includes("voice"))||((l=(o=t.adapterInfo)==null?void 0:o.adapter_name)==null?void 0:l.includes("audio"))||((d=(c=t.adapterInfo)==null?void 0:c.adapter_name)==null?void 0:d.includes("multilingual"));let r=!1;try{const u=localStorage.getItem("chat-settings");u&&(r=JSON.parse(u).voiceEnabled===!0)}catch{ge("Failed to read global voice setting")}const n=t.audioSettings;return{returnAudio:(n==null?void 0:n.enabled)??r??!!e,ttsVoice:(n==null?void 0:n.ttsVoice)||void 0,language:(n==null?void 0:n.language)||"en-US",audioFormat:n==null?void 0:n.audioFormat}},Eu=300;let ls=null;const Ke=t=>{ls&&clearTimeout(ls),ls=setTimeout(()=>{ls=null;try{const e=t(),r=e.conversations.map(n=>({...n,messages:n.messages.map(s=>s.audio||s.image||s.video||s.document?Object.fromEntries(Object.entries(s).filter(([o])=>o!=="audio"&&o!=="image"&&o!=="video"&&o!=="document")):s)}));localStorage.setItem("chat-state",JSON.stringify({conversations:r,currentConversationId:e.currentConversationId}))}catch(e){e instanceof DOMException&&e.name==="QuotaExceededError"?ge("[chatStore] localStorage quota exceeded — skipping save"):ze("[chatStore] Failed to save state to localStorage:",e)}},Eu)},_u=32,cr=new Map;let Vt=null,ct=null,Ft=null,Jt=null;const jn=(t,e)=>{const r=cr.get(t);if(r){if(r.timeoutId&&(clearTimeout(r.timeoutId),r.timeoutId=null),r.content){const n=r.content,s=r.messageId;r.content="",e(a=>({conversations:a.conversations.map(o=>{if(o.id!==t)return o;const l=[...o.messages],c=s?l.findIndex(u=>u.id===s):l.length-1,d=c!==-1?l[c]:void 0;return d&&d.role==="assistant"&&d.isStreaming&&(l[c]={...d,content:d.content+n}),{...o,messages:l,updatedAt:new Date}})}))}cr.delete(t)}},pt=(t,e,r,n)=>({conversations:t.conversations.map(s=>{var l;if(s.id!==e)return s;const a=[...s.messages],o=n?a.findIndex(c=>c.id===n):a.length-1;return o!==-1&&((l=a[o])==null?void 0:l.role)==="assistant"&&(a[o]={...a[o],...r(a[o])}),{...s,messages:a,updatedAt:new Date}})});let ks=!1,Ss="";async function Er(){if(ks&&Ss)return!0;try{const t=await Fe(),e=localStorage.getItem("chat-api-url");e&&e===mn&&localStorage.removeItem("chat-api-url");const r=e&&e!==mn?e:$e(),n=vs(),s=localStorage.getItem("chat-adapter-name")||ku;return t.configureApi(r,n,s),Ss=r,ks=!0,!0}catch(t){return ze("Failed to configure API:",t),!1}}async function Ya(t,e,r,n,s,a,o,l,c){let d=!1;const u=new AbortController;Vt=u,Jt=n,ct=null;try{const f=t().conversations.find(y=>y.id===n);if(!f)throw new Error("Conversation not found");if(!f.adapterName)throw new Error("Adapter not configured for this conversation. Please select an adapter first.");Ft=f.sessionId,f.sessionId&&(await Fe()).configureApi(lt(f.apiUrl),f.sessionId,f.adapterName);const m=await Fe(),{returnAudio:g,ttsVoice:p,language:x}=to(f);for await(const y of m.streamChat(s,!0,a.length>0?a:void 0,void 0,void 0,void 0,x,g,p,void 0,void 0,o,void 0,c)){if(y.request_id&&!ct&&(ct=y.request_id,D(`[chatStore] >>> CAPTURED request_id for ${l} stop: ${y.request_id}`)),y.text){const v=Ur(y.text);v?(t().appendToLastMessage(v,n,r),d=!0):y.text.length>100&&ge("[chatStore] Filtered out potential base64 audio data from regenerated message content")}if(y.audio&&y.done&&e(v=>pt(v,n,()=>({audio:y.audio,audioFormat:y.audioFormat||"mp3"}),r)),y.image&&y.done&&(d=!0,e(v=>pt(v,n,()=>({image:y.image,imageFormat:y.image_format||"png",imageRevisedPrompt:y.image_revised_prompt,imageUrl:y.image_url}),r))),(y.video||y.video_url)&&y.done&&(d=!0,e(v=>pt(v,n,()=>({video:y.video,videoFormat:y.video_format||"mp4",videoRevisedPrompt:y.video_revised_prompt,videoUrl:y.video_url}),r))),(y.document||y.document_url)&&y.done&&(d=!0,e(v=>pt(v,n,()=>({document:y.document,documentFormat:y.document_format||"pdf",documentRevisedPrompt:y.document_revised_prompt,documentUrl:y.document_url}),r))),y.generated_audio_url&&y.done&&(d=!0,e(v=>pt(v,n,()=>({generatedAudioFormat:y.generated_audio_format||"mp3",generatedAudioRevisedPrompt:y.generated_audio_revised_prompt,generatedAudioUrl:y.generated_audio_url}),r))),y.done){const v=y.threading;v!=null&&v.supports_threading&&e(A=>({conversations:A.conversations.map(I=>I.id!==n?I:{...I,messages:I.messages.map(C=>C.id===r?{...C,supportsThreading:!0,databaseMessageId:v.message_id}:C),updatedAt:new Date})})),y.assistant_message_id&&e(A=>({conversations:A.conversations.map(I=>I.id!==n?I:{...I,messages:I.messages.map(C=>C.id===r&&!C.databaseMessageId?{...C,databaseMessageId:y.assistant_message_id}:C),updatedAt:new Date})})),y.model&&e(A=>pt(A,n,()=>({model:y.model}),r));break}}!d&&!u.signal.aborted&&t().appendToLastMessage("No response received from the server. Please try again later.",n,r)}catch(f){if(f instanceof Error&&(f.name==="AbortError"||f.message==="Stream cancelled by user"||f.message.includes("aborted")))D(`[chatStore] ${l==="edit-regenerate"?"Edit-regenerate":"Regeneration"} stream was cancelled by user`),d=!0;else{ze(`${l==="edit-regenerate"?"Edit-regenerate":"Regenerate"} API error:`,f);let g="Sorry, there was an error regenerating the response.";f instanceof Error&&(f.message.startsWith("Server error:")?g=f.message.substring(14):(f.message.includes("Could not connect")||f.message.includes("timed out"))&&(g=f.message)),t().appendToLastMessage(g,n,r)}}Vt=null,ct=null,Ft=null,Jt=null,jn(n,e),e(f=>{const m=f.conversations.map(p=>p.id===n?{...p,messages:p.messages.map(x=>x.id===r?{...x,isStreaming:!1}:x),updatedAt:new Date}:p),g=m.find(p=>p.id===f.currentConversationId);return{conversations:m,isLoading:g?g.messages.some(p=>p.role==="assistant"&&p.isStreaming):!1}})}const ye=Qi((t,e)=>({conversations:[],currentConversationId:null,isLoading:!1,error:null,sessionId:vs(),getSessionId:()=>e().sessionId,configureApiSettings:async(r,n,s)=>{const a=e(),o=a.conversations.find(c=>c.id===a.currentConversationId),l=(o==null?void 0:o.sessionId)||n||vs();n&&Cu(n),t({sessionId:l});try{const c=await Fe();if(!s||!s.trim())throw new Error("Adapter name is required");c.configureApi(r,l,s),Ss=r,ks=!0;let d;try{const u=new c.ApiClient({apiUrl:r,sessionId:null,adapterName:s});typeof u.getAdapterInfo=="function"&&(d=await u.getAdapterInfo(),D("Adapter info loaded:",d))}catch(u){ge("Failed to load adapter info:",u)}if(o)t(u=>({conversations:u.conversations.map(f=>f.id===o.id?{...f,adapterName:s,apiUrl:r,adapterInfo:d,adapterLoadError:null,updatedAt:new Date}:f)}));else if(s&&s.trim()){const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,f=Wt();t(m=>({conversations:[...m.conversations,{id:u,sessionId:f,title:Fr,messages:[],createdAt:new Date,updatedAt:new Date,adapterName:s,apiUrl:r,adapterInfo:d,adapterLoadError:null}],currentConversationId:u}))}}catch(c){throw xe("Failed to configure API:",c),t({isLoading:!1}),c instanceof Error?c:new Error("Failed to configure API settings")}s?localStorage.setItem("chat-adapter-name",s):localStorage.removeItem("chat-adapter-name"),t({isLoading:!1})},createConversation:()=>{var u;const r=e(),n=oe.maxConversations,s=r.conversations.length,a=r.currentConversationId?r.conversations.find(f=>f.id===r.currentConversationId):null;if(n!==null&&s>=n){if(rt()&&!vt()){const m=`You've reached the guest limit of ${n} conversation${n===1?"":"s"}. Sign in to unlock more conversations, or delete conversations to start over.`;throw t({error:m}),st.getState().openLoginPrompt(m),new Error("Guest conversation limit reached")}const f=`Maximum of ${n} conversations reached. Please delete an existing conversation before starting a new one.`;throw t({error:f}),new Error(f)}const o=!!a&&(a.messages.length>0||(((u=a.attachedFiles)==null?void 0:u.length)||0)>0);if(a&&!o){const f="Finish or delete the current conversation before starting a new one.";throw t({error:f}),new Error(f)}const l=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,c=Wt(),d={id:l,sessionId:c,title:Fr,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:$e(),adapterName:Ji(),adapterLoadError:null};return t(f=>({conversations:[d,...f.conversations],currentConversationId:l,sessionId:c,isLoading:!1})),Ke(e),l},selectConversation:async r=>{const n=e().conversations.find(s=>s.id===r);if(n){const s=n.messages.some(c=>c.role==="assistant"&&c.isStreaming);t({currentConversationId:r,sessionId:n.sessionId,isLoading:s});const a=n.apiUrl||$e(),o=n.adapterName;if(await Er()&&o){const c=await Fe();if(c.configureApi(a,n.sessionId,o),!n.adapterInfo)try{const d=new c.ApiClient({apiUrl:a,sessionId:null,adapterName:o});if(typeof d.getAdapterInfo=="function"){const u=await d.getAdapterInfo();D("Adapter info loaded for conversation:",u),t(f=>({conversations:f.conversations.map(m=>m.id===r?{...m,adapterInfo:u,adapterLoadError:null,updatedAt:new Date}:m)})),Ke(e)}}catch(d){ge("Failed to load adapter info for conversation:",d)}}e().loadFeedbackForConversation(n.sessionId).catch(()=>{})}Ke(e)},deleteConversation:async r=>{var a,o;const n=e(),s=n.conversations.find(l=>l.id===r);if(D(`🗑️ Deleting conversation ${r}:`,{conversationId:r,sessionId:s==null?void 0:s.sessionId,title:s==null?void 0:s.title,messageCount:s==null?void 0:s.messages.length,fileCount:((a=s==null?void 0:s.attachedFiles)==null?void 0:a.length)||0}),n.currentConversationId===r&&qt.stop(),s){const l=(s.attachedFiles||[]).map(d=>d.file_id),c=(s.messages||[]).flatMap(d=>(d.attachments||[]).map(u=>u.file_id));[...l,...c].forEach(Sn)}if(s!=null&&s.sessionId)try{if(!await Er())ze("Failed to configure API for conversation deletion");else{const c=s.apiUrl||$e(),d=s.adapterName;d?D(`Using conversation's adapter for deletion: ${d} (conversation: ${r})`):ge(`Skipping server deletion for conversation ${r}: adapter not configured`);const u=await Fe(),f=new u.ApiClient({apiUrl:c,sessionId:s.sessionId,adapterName:d}),m=((o=s.attachedFiles)==null?void 0:o.map(x=>x.file_id))||[],g=Xa(s.messages||[]),p=[...m,...g];if(D(`🔧 Calling deleteConversationWithFiles for session: ${s.sessionId}`),f.deleteConversationWithFiles){const x=await f.deleteConversationWithFiles(s.sessionId,p);D(`✅ Deleted conversation and files for session: ${s.sessionId}`,x),D(` - Deleted ${x.deleted_messages} messages`),D(` - Deleted ${x.deleted_files} files`),x.file_deletion_errors&&x.file_deletion_errors.length>0&&ge(` - Errors deleting files: ${x.file_deletion_errors.join(", ")}`)}else ge("⚠️ deleteConversationWithFiles method not available on API client")}}catch(l){ze("Failed to clear conversation history from server:",l)}else ge(`⚠️ No session ID found for conversation ${r}, skipping server-side deletion`);t(l=>{var u;const c=l.conversations.filter(f=>f.id!==r),d=l.currentConversationId===r?((u=c[0])==null?void 0:u.id)||null:l.currentConversationId;if(c.length===0){const f=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,m=Wt(),g=$r(f,m,$e());return Ke(e),{conversations:[g],currentConversationId:f,sessionId:m}}return Ke(e),{conversations:c,currentConversationId:d}})},deleteAllConversations:async()=>{const n=[...e().conversations];D(`🗑️ Deleting all conversations (${n.length} total)`),qt.stop();const s=n.map(async u=>{var f;if(u!=null&&u.sessionId)try{if(!await Er()){ze("Failed to configure API for conversation deletion");return}const g=u.adapterName;if(!g){D(`Skipping server deletion for conversation ${u.id}: adapter not configured`);return}const p=await Fe(),x=new p.ApiClient({apiUrl:lt(u.apiUrl),sessionId:u.sessionId,adapterName:g}),y=[...((f=u.attachedFiles)==null?void 0:f.map(v=>v.file_id))||[],...Xa(u.messages||[])];x.deleteConversationWithFiles?(await x.deleteConversationWithFiles(u.sessionId,y),D(`✅ Deleted conversation ${u.id} and files`)):ge(`deleteConversationWithFiles not available for conversation ${u.id}`)}catch(m){ze(`Failed to delete conversation ${u.id} from server:`,m)}}),o=(await Promise.allSettled(s)).filter(u=>u.status==="rejected");o.length>0&&ze(`Some conversations failed to delete from server: ${o.length}`,o);const l=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,c=Wt(),d=$r(l,c,$e());t({conversations:[d],currentConversationId:l,sessionId:c}),Ke(e)},deleteThread:async(r,n,s)=>{const a=e().conversations.find(f=>f.id===r);if(!a)throw new Error("Conversation not found");if(!a.adapterName)throw new Error("Adapter not configured for this conversation");const o=a.messages.find(f=>f.id===n);if(!(o!=null&&o.threadInfo)||o.threadInfo.thread_id!==s)throw new Error("Thread not found for this message");const l=lt(a.apiUrl||$e()),c=await Fe(),d=new c.ApiClient({apiUrl:l,sessionId:a.sessionId,adapterName:a.adapterName});await new(await Nt(async()=>{const{ThreadService:f}=await import("./threadService-B9Db3n0J.js");return{ThreadService:f}},[])).ThreadService(d).deleteThread(s),t(f=>({conversations:f.conversations.map(m=>{var x;if(m.id!==r)return m;const g=m.messages.filter(y=>y.isThreadMessage?!(y.threadId===s||y.parentMessageId===n):!0).map(y=>y.id!==n?y:{...y,threadInfo:void 0,supportsThreading:!0}),p=m.currentThreadId===s||m.currentThreadSessionId===((x=o.threadInfo)==null?void 0:x.thread_session_id);return{...m,messages:g,currentThreadId:p?void 0:m.currentThreadId,currentThreadSessionId:p?void 0:m.currentThreadSessionId,updatedAt:new Date}})})),Ke(e)},sendMessage:async(r,n,s,a,o)=>{var c;let l=null;try{if(e().isLoading){ge("Another request is already in progress");return}if(!await Er())throw new Error("API not properly configured. Please configure API settings first.");let u=e().currentConversationId;u||(u=e().createConversation());const f=e().conversations.find(b=>b.id===u);if(!f)throw new Error("Conversation not found");const m=oe.maxConversations;if(rt()&&!vt()&&m!==null&&e().conversations.length>m){st.getState().openLoginPrompt(`You've reached the guest limit of ${m} conversation${m===1?"":"s"}. Sign in to continue chatting.`),t({isLoading:!1});return}const g=n?n.map(b=>{var k;const F=(k=f==null?void 0:f.attachedFiles)==null?void 0:k.find(N=>N.file_id===b);return F||{file_id:b,filename:"",mime_type:"",file_size:0}}).filter(b=>b!==void 0):[];g.length>0&&g.forEach(b=>{e().addFileToConversation(u,b)});const p=s||null;let x,y=null;if(p){if(x=f.messages.find(b=>{var F;return((F=b.threadInfo)==null?void 0:F.thread_id)===p}),!x)throw new Error("Thread metadata not found. Please recreate the thread from this message.");if(y=((c=x.threadInfo)==null?void 0:c.thread_session_id)||null,!y)throw new Error("Thread session is missing. Please recreate the thread from this message.")}const v=Ga(f.messages),A=oe.maxMessagesPerConversation;if(A!==null&&v>=A){rt()&&!vt()&&st.getState().openLoginPrompt(`You've reached the guest limit of ${A} messages per conversation. Sign in to send more messages, or delete conversations to start over.`),ge(`[chatStore] Conversation ${u} reached the message limit (${A}).`),t({isLoading:!1});return}const I=oe.maxTotalMessages;if(I!==null&&e().conversations.reduce((F,k)=>F+Ga(k.messages),0)>=I){rt()&&!vt()&&st.getState().openLoginPrompt(`You've reached the guest limit of ${I} total messages. Sign in to continue chatting, or delete conversations to start over.`),ge(`[chatStore] Workspace reached the total message limit (${I}).`),t({isLoading:!1});return}const C={id:lr("user"),content:r,role:"user",timestamp:new Date,attachments:g.length>0?g:void 0},S=lr("assistant"),E={id:S,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:a};if(p&&x){C.isThreadMessage=!0,C.threadId=p,C.parentMessageId=x.id,E.isThreadMessage=!0,E.threadId=p,E.parentMessageId=x.id;const b=oe.maxMessagesPerThread;if(b!==null&&f.messages.filter(k=>k.isThreadMessage?(k.threadId===p||k.parentMessageId===x.id)&&!(k.role==="assistant"&&k.isStreaming):!1).length>=b){rt()&&!vt()&&st.getState().openLoginPrompt(`You've reached the guest limit of ${b} messages per thread. Sign in to continue this thread, or delete conversations to start over.`),ge(`[chatStore] Thread ${p} reached the message limit (${b}).`),t({isLoading:!1});return}}t(b=>{const F=b.conversations.find(N=>N.id===u),k=(F==null?void 0:F.messages.filter(N=>N.role==="assistant"&&N.isStreaming))||[];return k.length>0&&ge(`Cleaning up ${k.length} existing streaming messages`),{conversations:b.conversations.map(N=>{if(N.id!==u)return N;const U=N.messages.filter(T=>!(T.role==="assistant"&&T.isStreaming));return{...N,messages:[...U,C,E],updatedAt:new Date,title:N.messages.length===0?r.slice(0,50)+(r.length>50?"...":""):N.title}}),isLoading:!0,error:null}}),l=u;let _=!1;qt.reset();try{const b=e().conversations.find(M=>M.id===l);if(!b)throw new Error("Conversation not found");if(!b.adapterName)throw new Error("Adapter not configured for this conversation. Please select an adapter first.");const F=lt(b.apiUrl),k=b.adapterName,N=y||b.sessionId,U=await Fe();U.configureApi(F,N,k),p&&N!==b.sessionId&&D(`[chatStore] Thread mode: using thread session ${N} (original: ${b.sessionId})`);const{returnAudio:T,ttsVoice:H,language:j,audioFormat:L}=to(b);D("[chatStore] Audio settings:",{returnAudio:T,ttsVoice:H,language:j,audioFormat:L});const O=new AbortController;Vt=O,Ft=N,Jt=l,ct=null;for await(const M of U.streamChat(r,!0,n,p||void 0,void 0,void 0,j,T,H,void 0,void 0,a,o)){if(M.request_id&&!ct&&(ct=M.request_id,D(`[chatStore] >>> CAPTURED request_id for stop: ${M.request_id}`)),M.audio_chunk&&qt.addChunk({audio:M.audio_chunk,audioFormat:M.audioFormat||"opus",chunkIndex:M.chunk_index??0}),M.text){const Y=Ur(M.text);Y?(e().appendToLastMessage(Y,l,S),_=!0):M.text.length>100&&ge("[chatStore] Filtered out potential base64 audio data from message content")}if(M.audio&&M.done&&t(Y=>pt(Y,l,()=>({audio:M.audio,audioFormat:M.audioFormat||"mp3"}),S)),M.image&&M.done&&(_=!0,t(Y=>pt(Y,l,()=>({image:M.image,imageFormat:M.image_format||"png",imageRevisedPrompt:M.image_revised_prompt,imageUrl:M.image_url}),S))),(M.video||M.video_url)&&M.done&&(_=!0,t(Y=>pt(Y,l,()=>({video:M.video,videoFormat:M.video_format||"mp4",videoRevisedPrompt:M.video_revised_prompt,videoUrl:M.video_url}),S))),(M.document||M.document_url)&&M.done&&(_=!0,t(Y=>pt(Y,l,()=>({document:M.document,documentFormat:M.document_format||"pdf",documentRevisedPrompt:M.document_revised_prompt,documentUrl:M.document_url}),S))),M.generated_audio_url&&M.done&&(_=!0,t(Y=>pt(Y,l,()=>({generatedAudioFormat:M.generated_audio_format||"mp3",generatedAudioRevisedPrompt:M.generated_audio_revised_prompt,generatedAudioUrl:M.generated_audio_url}),S))),M.done){D("[chatStore] Stream completed, receivedAnyText:",_);const Y=M.threading;Y!=null&&Y.supports_threading&&t(G=>({conversations:G.conversations.map(V=>V.id!==l?V:{...V,messages:V.messages.map(J=>J.id===S?{...J,supportsThreading:!0,databaseMessageId:Y.message_id}:J),updatedAt:new Date})})),M.assistant_message_id&&t(G=>({conversations:G.conversations.map(V=>V.id!==l?V:{...V,messages:V.messages.map(J=>J.id===S&&!J.databaseMessageId?{...J,databaseMessageId:M.assistant_message_id}:J),updatedAt:new Date})})),M.model&&t(G=>pt(G,l,()=>({model:M.model}),S));break}}!_&&!O.signal.aborted&&e().appendToLastMessage("No response received from the server. Please try again later.",l,S)}catch(b){if(b instanceof Error&&(b.name==="AbortError"||b.message==="Stream cancelled by user"||b.message.includes("aborted")))D("[chatStore] Stream was cancelled by user"),_=!0;else{ze("Chat API error:",b);let k="Sorry, there was an error processing your request.";b instanceof Error&&(b.message.startsWith("Server error:")?k=b.message.substring(14):(b.message.includes("Could not connect")||b.message.includes("timed out"))&&(k=b.message)),e().appendToLastMessage(k,l,S)}}Vt=null,ct=null,Ft=null,Jt=null,jn(l,t),t(b=>{const F=b.conversations.map(N=>N.id===l?{...N,messages:N.messages.map(U=>U.id===S?{...U,isStreaming:!1}:U),updatedAt:new Date}:N),k=F.find(N=>N.id===b.currentConversationId);return{conversations:F,isLoading:k?k.messages.some(N=>N.role==="assistant"&&N.isStreaming):!1}}),Ke(e)}catch(d){ze("Chat store error:",d),t(u=>({isLoading:!1,...u.currentConversationId===l&&{error:`Failed to send message: ${d instanceof Error?d.message:"Unknown error"}`}}))}},createThread:async(r,n)=>{try{const s=e().conversations.find(m=>m.sessionId===n);if(!s)throw new Error("Conversation not found for session");if(!s.adapterName)throw new Error("Adapter not configured for this conversation");const a=s.messages.find(m=>m.id===r);if(!a)throw new Error("Message not found");const o=a.databaseMessageId||r,l=lt(s.apiUrl||$e()),c=await Fe(),d=new c.ApiClient({apiUrl:l,sessionId:n,adapterName:s.adapterName}),f=await new(await Nt(async()=>{const{ThreadService:m}=await import("./threadService-B9Db3n0J.js");return{ThreadService:m}},[])).ThreadService(d).createThread(o,n);t(m=>({conversations:m.conversations.map(g=>g.sessionId!==n?g:{...g,messages:g.messages.map(p=>p.id===r?{...p,threadInfo:f,supportsThreading:!0}:p),currentThreadId:void 0,currentThreadSessionId:void 0})})),D(`[chatStore] Created thread ${f.thread_id} for message ${r}`)}catch(s){throw ze("Failed to create thread:",s),s}},appendToLastMessage:(r,n,s)=>{const a=Ur(r);if(!a&&r){ge("[chatStore] Filtered out base64 audio data from message content");return}const o=kn(a),l=n||e().currentConversationId;if(!l)return;const c=l,d=cr.get(c);d?(d.content+=o,d.messageId=s,d.timeoutId&&clearTimeout(d.timeoutId)):cr.set(c,{content:o,timeoutId:null,messageId:s});const u=()=>{const m=cr.get(c);if(!m||!m.content)return;const g=m.content,p=m.messageId;m.content="",m.timeoutId=null,t(x=>({conversations:x.conversations.map(y=>{if(y.id!==l)return y;const v=[...y.messages],A=p?v.findIndex(C=>C.id===p):v.length-1,I=A!==-1?v[A]:void 0;return I&&I.role==="assistant"&&I.isStreaming&&(v[A]={...I,content:I.content+g}),{...y,messages:v,updatedAt:new Date}})}))},f=cr.get(c);f.timeoutId=setTimeout(u,_u)},regenerateResponse:async(r,n)=>{let s=null;try{if(e().isLoading){ge("Another request is already in progress");return}if(!await Er())throw new Error("API not properly configured");const o=e(),l=o.conversations.find(g=>g.id===o.currentConversationId);if(!l)return;const c=l.messages.findIndex(g=>g.id===r);if(c===-1)return;const d=l.messages[c];if(!d||d.role!=="assistant")return;const u=l.messages[c-1];if(!u||u.role!=="user")return;const f=(u.attachments||[]).map(g=>g.file_id).filter(g=>typeof g=="string"&&g.length>0),m=lr("assistant");if(t(g=>({conversations:g.conversations.map(p=>p.id===g.currentConversationId?{...p,messages:[...p.messages.slice(0,c),{id:m,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:n,supportsThreading:d.supportsThreading,databaseMessageId:d.databaseMessageId,threadInfo:d.threadInfo,threadId:d.threadId,parentMessageId:d.parentMessageId,isThreadMessage:d.isThreadMessage},...p.messages.slice(c+1)],updatedAt:new Date}:p),isLoading:!0,error:null})),s=o.currentConversationId,!s)throw new Error("No conversation selected");await Ya(e,t,m,s,u.content,f,n,"regenerate",d.databaseMessageId)}catch(a){ze("Regenerate error:",a),t(o=>({isLoading:!1,...o.currentConversationId===s&&{error:`Failed to regenerate response: ${a instanceof Error?a.message:"Unknown error"}`}}))}},editMessageAndRegenerate:async(r,n,s)=>{let a=null;try{if(e().isLoading){await e().stopStreaming();const x=e().currentConversationId;x&&jn(x,t)}const o=e(),l=o.conversations.find(x=>x.id===o.currentConversationId);if(!l)return;const c=l.messages.findIndex(x=>x.id===r);if(c===-1)return;const d=l.messages[c];if(d.role!=="user")return;const u=(d.attachments||[]).map(x=>x.file_id).filter(x=>typeof x=="string"&&x.length>0),f=lr("assistant"),m=l.messages[c+1],g=(m==null?void 0:m.role)==="assistant",p=g?c+2:c+1;if(t(x=>({conversations:x.conversations.map(y=>y.id===x.currentConversationId?{...y,messages:[...y.messages.slice(0,c),{...d,content:n,updatedAt:new Date},{id:f,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:s,supportsThreading:g?m.supportsThreading:void 0,databaseMessageId:g?m.databaseMessageId:void 0,threadInfo:g?m.threadInfo:void 0,threadId:g?m.threadId:void 0,parentMessageId:g?m.parentMessageId:void 0,isThreadMessage:g?m.isThreadMessage:void 0},...y.messages.slice(p)],updatedAt:new Date}:y),isLoading:!0,error:null})),a=o.currentConversationId,!a)throw new Error("No conversation selected");await Ya(e,t,f,a,n,u,s,"edit-regenerate",g?m.databaseMessageId:void 0),Ke(e)}catch(o){ze("Edit & regenerate error:",o),t(l=>({isLoading:!1,...l.currentConversationId===a&&{error:`Failed to regenerate response: ${o instanceof Error?o.message:"Unknown error"}`}}))}},updateConversationTitle:(r,n)=>{t(s=>({conversations:s.conversations.map(a=>a.id===r?{...a,title:n,updatedAt:new Date}:a)})),Ke(e)},clearError:()=>t({error:null}),cleanupStreamingMessages:()=>{const r=Jt;t(n=>{let s=!1;return{conversations:n.conversations.map(o=>o.id===r?(o.messages.some(c=>c.role==="assistant"&&c.isStreaming)&&(s=!0),o):o.messages.some(c=>c.role==="assistant"&&c.isStreaming)?{...o,messages:o.messages.filter(c=>!(c.role==="assistant"&&c.isStreaming)),updatedAt:new Date}:o),isLoading:s}})},canCreateNewConversation:()=>{var o;const r=e(),n=oe.maxConversations;if(!r.currentConversationId)return n===null||r.conversations.length<n;const s=r.conversations.find(l=>l.id===r.currentConversationId);return!!s&&(s.messages.length>0||(((o=s.attachedFiles)==null?void 0:o.length)||0)>0)?n===null||r.conversations.length<n:!1},getConversationCount:()=>e().conversations.length,addFileToConversation:(r,n)=>{D("[chatStore] addFileToConversation called",{conversationId:r,fileId:n.file_id,filename:n.filename}),t(s=>({conversations:s.conversations.map(a=>a.id===r?{...a,attachedFiles:[...(a.attachedFiles||[]).filter(o=>o.file_id!==n.file_id),n],updatedAt:new Date}:a)})),Ke(e)},removeFileFromConversation:async(r,n)=>{D("[chatStore] removeFileFromConversation called",{conversationId:r,fileId:n});try{const s=e().conversations.find(a=>a.id===r);if(!s)throw new Error("Conversation not found");if(!s.adapterName)throw new Error("Adapter not configured for this conversation. Cannot delete file.");await Or.deleteFile(n,void 0,lt(s.apiUrl),s.adapterName),D(`[chatStore] Successfully deleted file ${n} from server`)}catch(s){s instanceof Error&&(s.message.includes("404")||s.message.includes("File not found"))?D(`[chatStore] File ${n} was already deleted from server`):xe(`[chatStore] Failed to delete file ${n} from server:`,s)}Sn(n),t(s=>({conversations:s.conversations.map(a=>a.id===r?{...a,attachedFiles:(a.attachedFiles||[]).filter(o=>o.file_id!==n),updatedAt:new Date}:a)})),Ke(e)},loadConversationFiles:async r=>{try{const n=e().conversations.find(l=>l.id===r);if(!n)return;if(!n.adapterName){D(`Skipping file load for conversation ${r}: adapter not configured`);return}if(new Set((n.attachedFiles||[]).map(l=>l.file_id)).size===0){D(`No files to sync for conversation ${r}`);return}const a=await Or.listFiles(void 0,lt(n.apiUrl),n.adapterName),o=new Map(a.map(l=>[l.file_id,{file_id:l.file_id,filename:l.filename,mime_type:l.mime_type,file_size:l.file_size,upload_timestamp:l.upload_timestamp,processing_status:l.processing_status,chunk_count:l.chunk_count}]));t(l=>{const c=l.conversations.find(u=>u.id===r);if(!c)return l;const d=(c.attachedFiles||[]).map(u=>o.get(u.file_id)||u).filter(u=>o.has(u.file_id)||!u.processing_status||u.processing_status==="processing");return{conversations:l.conversations.map(u=>u.id===r?{...u,attachedFiles:d,updatedAt:new Date}:u)}}),Ke(e)}catch(n){ze(`Failed to load files for conversation ${r}:`,n)}},syncConversationFiles:async r=>{await e().loadConversationFiles(r)},syncConversationsWithBackend:async()=>{try{const r=e();if(r.conversations.length===0)return;const n=await Fe(),s=oe.maxMessagesPerConversation!==null&&oe.maxMessagesPerConversation||void 0;let a=!1;const l=(await Promise.all(r.conversations.map(async c=>{var d;if(!c.sessionId)return null;if(!c.adapterName)return ge(`[chatStore] Skipping backend sync for conversation ${c.id} - adapter not configured`),null;if(c.messages.length===0)return null;try{const u=new n.ApiClient({apiUrl:lt(c.apiUrl),sessionId:c.sessionId,adapterName:c.adapterName});if(typeof u.getConversationHistory!="function")return a||(a=!0,ge("[chatStore] Conversation history endpoint not supported by current API client")),null;const f=await u.getConversationHistory(c.sessionId,s),m=Array.isArray(f==null?void 0:f.messages)?f.messages:[];if(m.length===0)return c.messages.length===0?null:{id:c.id,sessionId:(f==null?void 0:f.session_id)||c.sessionId,messages:[],cleared:!0,updatedAt:new Date};const g=Iu(m,c.messages),p=c.messages.filter(y=>y.isThreadMessage),x=eo(p.length>0?[...g,...p]:g);return Lu(c.messages,x)?null:{id:c.id,sessionId:(f==null?void 0:f.session_id)||c.sessionId,messages:x,cleared:!1,updatedAt:((d=g[g.length-1])==null?void 0:d.timestamp)||new Date}}catch(u){return ge(`[chatStore] Failed to sync session ${c.sessionId}:`,u),null}}))).filter(c=>!!c);if(l.length===0)return;t(c=>{const d=new Map(l.map(u=>[u.id,u]));return{conversations:c.conversations.map(u=>{const f=d.get(u.id);return f?f.cleared?{...u,sessionId:f.sessionId||u.sessionId,messages:[],attachedFiles:[],title:Fr,updatedAt:f.updatedAt,adapterLoadError:null}:{...u,sessionId:f.sessionId||u.sessionId,messages:f.messages,updatedAt:f.updatedAt,adapterLoadError:null}:u}),currentConversationId:c.currentConversationId}}),Ke(e)}catch(r){ge("Failed to synchronize conversations with backend:",r)}},stopStreaming:async()=>{var n;if(!e().isLoading){D("[chatStore] stopStreaming called but not currently loading");return}if(D("[chatStore] Stopping stream...",{hasAbortController:!!Vt,requestId:ct,sessionId:Ft}),Vt&&Vt.abort(),ct&&Ft)try{const s=await Fe(),a=await((n=s.stopChat)==null?void 0:n.call(s,Ft,ct));D(`[chatStore] Server-side cancellation result: ${a}`)}catch(s){ge("[chatStore] Failed to cancel server-side stream:",s)}else ge(`[chatStore] Cannot call stopChat - missing IDs: requestId=${ct}, sessionId=${Ft}`);const r=Jt||e().currentConversationId;t(r?s=>({conversations:s.conversations.map(a=>a.id!==r?a:{...a,messages:a.messages.map(o=>o.isStreaming?{...o,isStreaming:!1}:o),updatedAt:new Date}),isLoading:!1}):{isLoading:!1}),Vt=null,ct=null,Ft=null,Jt=null,D("[chatStore] Stream stopped successfully")},clearCurrentConversationAdapter:()=>{const r=e().currentConversationId;r&&(t(n=>({conversations:n.conversations.map(s=>s.id===r?{...s,adapterName:void 0,adapterInfo:void 0,adapterLoadError:null}:s)})),Ke(e))},submitFeedback:async(r,n)=>{const s=e(),a=s.conversations.find(l=>l.id===s.currentConversationId);if(!a)return;const o=a.messages.find(l=>l.id===r);if(!(o!=null&&o.databaseMessageId)){ge("[chatStore] Cannot submit feedback: no databaseMessageId on message");return}if(a.adapterName)try{const l=await Fe(),u=(await new l.ApiClient({apiUrl:lt(a.apiUrl||$e()),sessionId:a.sessionId,adapterName:a.adapterName}).submitFeedback(o.databaseMessageId,a.sessionId,n)).feedback_type;t(f=>({conversations:f.conversations.map(m=>m.id!==s.currentConversationId?m:{...m,messages:m.messages.map(g=>g.id===r?{...g,feedback:u}:g),updatedAt:new Date})})),Ke(e)}catch(l){xe("[chatStore] Failed to submit feedback:",l)}},loadFeedbackForConversation:async r=>{var a;const s=e().conversations.find(o=>o.sessionId===r);if(s!=null&&s.adapterName)try{const o=await Fe(),l=new o.ApiClient({apiUrl:lt(s.apiUrl||$e()),sessionId:s.sessionId,adapterName:s.adapterName}),c=new Set([r]);for(const f of s.messages)(a=f.threadInfo)!=null&&a.thread_session_id&&c.add(f.threadInfo.thread_session_id);const d=await Promise.all(Array.from(c).map(f=>l.getSessionFeedback(f).catch(()=>({feedbacks:[]})))),u=new Map;for(const f of d)if(f!=null&&f.feedbacks)for(const m of f.feedbacks)u.set(m.message_id,m.feedback_type);if(u.size===0)return;t(f=>({conversations:f.conversations.map(m=>m.sessionId!==r?m:{...m,messages:m.messages.map(g=>g.databaseMessageId&&u.has(g.databaseMessageId)?{...g,feedback:u.get(g.databaseMessageId)}:g)})}))}catch(o){xe("[chatStore] Failed to load feedback:",o)}}})),Tu=async()=>{var c;const t=localStorage.getItem("chat-state"),e=$e(),r=!!localStorage.getItem("chat-api-url");let n=vs(),s=!1;if(t)try{const d=JSON.parse(t),u=g=>{if(g instanceof Date)return g;const p=g?new Date(g):new Date;return Number.isNaN(p.getTime())?new Date:p},m=(Array.isArray(d.conversations)?d.conversations:[]).map(g=>{const x=(Array.isArray(g.messages)?g.messages:[]).filter(I=>!(I.role==="assistant"&&I.isStreaming)).map(I=>({...I,timestamp:u(I.timestamp),isStreaming:!1})),y=eo(x),v={id:g.id,sessionId:g.sessionId||Wt(),title:ju(g.title),messages:y,createdAt:u(g.createdAt),updatedAt:u(g.updatedAt),attachedFiles:g.attachedFiles||[],adapterName:g.adapterName,apiUrl:g.apiUrl,adapterInfo:g.adapterInfo,adapterLoadError:g.adapterLoadError||null,audioSettings:g.audioSettings,currentThreadId:void 0,currentThreadSessionId:void 0},A=v.messages.length===0&&!v.adapterName;return{...v,apiUrl:A&&!r?e:lt(g.apiUrl)}});if(s=m.length>0,d.currentConversationId&&m.length>0){const g=m.find(p=>p.id===d.currentConversationId);g!=null&&g.sessionId&&(n=g.sessionId)}if(m.length===0){const g=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,p=Wt(),x=$r(g,p,$e());ye.setState({conversations:[x],currentConversationId:g,sessionId:p}),n=p}else ye.setState({conversations:m,currentConversationId:d.currentConversationId||((c=m[0])==null?void 0:c.id)||null,sessionId:n}),!d.currentConversationId&&m.length>0&&(ye.setState({currentConversationId:m[0].id,sessionId:m[0].sessionId||n}),n=m[0].sessionId||n);D("📋 Loaded conversations:",ye.getState().conversations.map(g=>{var p;return{id:g.id,title:g.title,sessionId:g.sessionId,messageCount:((p=g.messages)==null?void 0:p.length)||0}})),setTimeout(()=>ye.getState().cleanupStreamingMessages(),100)}catch(d){ze("Failed to load chat state:",d);const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,f=Wt(),m=$r(u,f,$e());ye.setState({conversations:[m],currentConversationId:u,sessionId:f}),n=f}else{const d=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,u=Wt(),f=$r(d,u,$e());ye.setState({conversations:[f],currentConversationId:d,sessionId:u}),n=u}localStorage.removeItem("chat-api-key");const a=ye.getState(),o=a.currentConversationId?a.conversations.find(d=>d.id===a.currentConversationId):null,l=s&&(o!=null&&o.apiUrl)?o.apiUrl:$e();try{const d=await Fe(),u=o==null?void 0:o.adapterName;if(!u)D("No adapter selected yet. Waiting for user selection before configuring API.");else if(d.configureApi(l,n,u),Ss=l,ks=!0,!(o!=null&&o.adapterInfo))try{const f=new d.ApiClient({apiUrl:l,sessionId:null,adapterName:u});if(typeof f.getAdapterInfo=="function"){const m=await f.getAdapterInfo();D("Adapter info loaded for existing adapter:",m);const g=ye.getState();g.currentConversationId&&(ye.setState({conversations:g.conversations.map(p=>p.id===g.currentConversationId?{...p,adapterInfo:m,adapterLoadError:null,updatedAt:new Date}:p)}),setTimeout(()=>{const p=ye.getState();localStorage.setItem("chat-state",JSON.stringify({conversations:p.conversations,currentConversationId:p.currentConversationId}))},0))}}catch(f){ge("Failed to load adapter info for existing adapter:",f)}}catch(d){ze("Failed to initialize API:",d)}try{await ye.getState().syncConversationsWithBackend()}catch(d){ge("Conversation history sync skipped:",d)}};typeof window<"u"&&Tu();function Mu(t){return t.includes("image")?i.jsx(Zc,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):t.includes("video")||t.includes("audio")?i.jsx(vd,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):i.jsx($n,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"})}function Fu(t){return t.replace(/-/g," ")}function ro({skills:t,isLoading:e,selectedSkill:r,activeSkillName:n,query:s="",onSelect:a,onActiveSkillChange:o}){const{t:l}=Ie(),c=gt.useRef(null),d=s.toLowerCase().replace(/-/g," "),u=d?t.filter(f=>f.name.replace(/-/g," ").toLowerCase().includes(d)||f.description.toLowerCase().includes(d)):t;return gt.useEffect(()=>{var m;const f=(m=c.current)==null?void 0:m.querySelector('[data-active="true"]');f==null||f.scrollIntoView({block:"nearest"})},[n,u.length]),!e&&t.length===0?i.jsx("div",{className:"w-full overflow-hidden rounded-xl border border-gray-200 bg-white shadow-lg shadow-black/5 dark:border-[#242424] dark:bg-[#101010] dark:shadow-black/30",children:i.jsx("p",{className:"px-4 py-3 text-sm text-gray-500 dark:text-[#bfc2cd]",children:l("skillPicker.noSkillsAvailable")})}):i.jsx("div",{className:"w-full overflow-hidden rounded-xl border border-gray-200 bg-white shadow-lg shadow-black/5 dark:border-[#242424] dark:bg-[#101010] dark:shadow-black/30",children:e?i.jsx("div",{className:"px-4 py-3.5",children:i.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-[#bfc2cd]",children:[i.jsx("div",{className:"h-3.5 w-3.5 rounded-full border-2 border-current border-t-transparent animate-spin","aria-hidden":"true"}),l("skillPicker.loadingLabel")]})}):u.length===0?i.jsx("div",{className:"px-4 py-3.5",children:i.jsx("p",{className:"text-sm text-gray-500 dark:text-[#bfc2cd]",children:d?l("skillPicker.noMatchingSkills",{query:s}):l("skillPicker.noMatchingSkillsGeneric")})}):i.jsx("div",{ref:c,role:"listbox","aria-label":l("skillPicker.listboxLabel"),className:"max-h-72 overflow-y-auto p-1.5",children:u.map((f,m)=>{const g=(r==null?void 0:r.name)===f.name,p=n===f.name||!n&&(g||!r&&m===0);return i.jsxs("button",{id:`skill-option-${f.name}`,type:"button",role:"option","aria-selected":p,"data-active":p?"true":void 0,onMouseEnter:()=>o==null?void 0:o(f),onClick:()=>a(f),className:`group flex w-full items-start gap-3 rounded-lg px-3 py-2.5 text-left transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 dark:focus-visible:ring-gray-600 ${p?"bg-gray-100 text-gray-950 dark:bg-[#242424] dark:text-white":"text-gray-900 hover:bg-gray-50 dark:text-gray-100 dark:hover:bg-[#1a1a1a]"}`,children:[i.jsx("div",{className:`mt-0.5 flex h-5 w-5 flex-shrink-0 items-center justify-center transition-colors ${p?"text-gray-900 dark:text-white":"text-gray-500 group-hover:text-gray-700 dark:text-[#bfc2cd] dark:group-hover:text-gray-200"}`,children:Mu(f.name)}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"flex min-w-0 items-center gap-2",children:i.jsx("span",{className:"truncate text-sm font-medium capitalize leading-5 text-current",children:Fu(f.name)})}),f.description&&i.jsx("p",{className:"mt-0.5 line-clamp-2 text-xs leading-5 text-gray-500 dark:text-[#bfc2cd]",children:f.description})]}),g&&i.jsx("span",{className:"mt-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-gray-900 text-white dark:bg-white dark:text-gray-900",children:i.jsx(ur,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]},f.name)})})})}function so({availableModels:t,defaultModel:e,selectedModel:r,onSelect:n,wrapperClassName:s="relative hidden md:block",maxWidthClass:a="max-w-[200px]",triggerTitle:o,listboxLabel:l,staticPaddingClass:c="px-3 py-1.5",triggerPaddingClass:d="px-3 py-1.5"}){const{t:u}=Ie(),f=o??u("modelPicker.selectModel"),m=l??u("modelPicker.selectModel"),[g,p]=h.useState(!1),[x,y]=h.useState(""),[v,A]=h.useState(null),I=h.useRef(null),C=h.useRef(null),S=h.useRef(null),E=h.useRef(null),_=r??e,b=x.trim()?t.filter(T=>T.name.toLowerCase().includes(x.trim().toLowerCase())):t,F=h.useCallback(()=>{if(!C.current)return;const T=C.current.getBoundingClientRect();A({bottom:window.innerHeight-T.top+8,right:window.innerWidth-T.right})},[]),k=h.useCallback(()=>{p(!1),y("")},[]),N=()=>{if(g){k();return}F(),p(!0)};if(h.useEffect(()=>{if(!g)return;const T=setTimeout(()=>{var O;return(O=S.current)==null?void 0:O.focus()},10),H=O=>{var V,J;const M=O.target,Y=((V=I.current)==null?void 0:V.contains(M))??!1,G=((J=E.current)==null?void 0:J.contains(M))??!1;!Y&&!G&&k()},j=O=>{var M;O.key==="Escape"&&(O.preventDefault(),k(),(M=C.current)==null||M.focus())},L=new ResizeObserver(F);return C.current&&L.observe(C.current),window.addEventListener("resize",F,{passive:!0}),document.addEventListener("scroll",F,{capture:!0,passive:!0}),document.addEventListener("pointerdown",H),document.addEventListener("keydown",j),()=>{clearTimeout(T),L.disconnect(),window.removeEventListener("resize",F),document.removeEventListener("scroll",F,{capture:!0}),document.removeEventListener("pointerdown",H),document.removeEventListener("keydown",j)}},[k,g,F]),!e&&t.length===0)return null;const U=g&&v&&typeof document<"u"?As.createPortal(i.jsxs("div",{ref:E,style:{position:"fixed",bottom:v.bottom,right:v.right,width:288,zIndex:9999},className:"rounded-xl border border-gray-200 bg-white shadow-xl dark:border-[#2f303d] dark:bg-[#111111]",children:[i.jsx("div",{className:"p-2 border-b border-gray-100 dark:border-[#222222]",children:i.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-gray-50 px-3 py-1.5 dark:bg-[#1a1a1a]",children:[i.jsx(Fn,{className:"h-3.5 w-3.5 flex-shrink-0 text-gray-400 dark:text-[#6b6f7a]","aria-hidden":"true"}),i.jsx("input",{ref:S,type:"text",value:x,onChange:T=>y(T.target.value),placeholder:u("modelPicker.searchPlaceholder"),className:"flex-1 bg-transparent pl-1 text-xs text-gray-700 placeholder-gray-400 focus:outline-none dark:text-[#ececf1] dark:placeholder-[#6b6f7a]","aria-label":u("modelPicker.searchAriaLabel")})]})}),i.jsx("div",{role:"listbox","aria-label":m,className:"max-h-60 overflow-y-auto py-1",children:b.length===0?i.jsx("div",{className:"px-3 py-5 text-center text-xs text-gray-400 dark:text-[#6b6f7a]",children:u("modelPicker.noModelsMatch",{query:x})}):b.map(T=>{const H=_===T.name;return i.jsxs("button",{role:"option","aria-selected":H,type:"button",onClick:()=>{var j;n(T.name),k(),(j=C.current)==null||j.focus()},className:`flex w-full items-center gap-2.5 px-3 py-2 text-left text-xs transition-colors ${H?"bg-gray-100 text-gray-900 dark:bg-[#1f1f1f] dark:text-[#ececf1]":"text-gray-700 hover:bg-gray-50 dark:text-[#bfc2cd] dark:hover:bg-[#1a1a1a]"}`,children:[i.jsx("span",{className:`flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center rounded-full border ${H?"border-blue-500 bg-blue-500 dark:border-blue-400 dark:bg-blue-400":"border-gray-300 dark:border-[#5a5b65]"}`,children:H&&i.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-white"})}),i.jsx("span",{className:"truncate font-medium normal-case tracking-normal",children:T.name})]},T.name)})}),t.length>8&&i.jsx("div",{className:"border-t border-gray-100 px-3 py-1.5 dark:border-[#222222]",children:i.jsx("span",{className:"text-[10px] text-gray-400 dark:text-[#6b6f7a]",children:u("modelPicker.modelCountHint",{filtered:b.length,total:t.length})})})]}),document.body):null;return i.jsx("div",{ref:I,className:s,children:t.length>1?i.jsxs(i.Fragment,{children:[i.jsxs("button",{ref:C,type:"button",onClick:N,className:`inline-flex min-w-[100px] ${a} items-center gap-1.5 rounded-full border border-gray-200 bg-gray-100 ${d} text-xs font-medium text-gray-700 transition-colors hover:bg-gray-200 dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#bfc2cd] dark:hover:bg-[#3a3b48]`,"aria-haspopup":"listbox","aria-expanded":g,title:f,children:[i.jsx("span",{className:"truncate flex-1",children:_}),i.jsx(hr,{className:`h-3.5 w-3.5 flex-shrink-0 text-gray-400 transition-transform duration-150 dark:text-[#6b6f7a] ${g?"rotate-180":""}`,"aria-hidden":"true"})]}),U]}):i.jsx("div",{className:`inline-flex min-w-[100px] ${a} items-center rounded-full border border-gray-200 bg-gray-100 ${c} text-xs text-gray-500 dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#bfc2cd]`,title:_??void 0,children:i.jsx("span",{className:"truncate",children:_})})})}function js({filename:t,fileId:e,status:r,statusText:n,errorMessage:s,onRemove:a,removeTitle:o,className:l=""}){const c=r==="uploading"||r==="processing",d=r==="error",u=wu(t),f=e?vu(e):void 0,m=u.Icon,g=d?s||n:n||u.label;return i.jsxs("div",{className:`group relative flex w-full min-w-[168px] max-w-[240px] items-center gap-2.5 rounded-xl border p-2 transition-colors ${d?"border-red-200 bg-red-50 dark:border-red-500/30 dark:bg-[#1a1010]":"border-gray-200 bg-gray-50 dark:border-[#242424] dark:bg-[#101010]"} ${l}`,children:[i.jsx("div",{className:`flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-lg text-white ${d?"bg-red-500":u.colorClass}`,children:f&&!d?i.jsx("img",{src:f,alt:"",className:"h-full w-full object-cover"}):c?i.jsx(Pi,{className:"h-[18px] w-[18px] animate-spin"}):d?i.jsx(bn,{className:"h-[18px] w-[18px]"}):i.jsx(m,{className:"h-[18px] w-[18px]"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:`truncate text-sm font-medium leading-tight ${d?"text-red-700 dark:text-red-300":"text-[#353740] dark:text-[#ececf1]"}`,title:t,children:t}),g&&i.jsx("p",{className:`truncate text-xs leading-tight mt-0.5 ${d?"text-red-500 dark:text-red-400":"text-gray-400 dark:text-[#8e8ea0]"}`,children:g})]}),a&&i.jsx("button",{type:"button",onClick:a,title:o,"aria-label":o,className:"absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full border border-gray-200 bg-white text-gray-500 shadow-sm transition-colors hover:text-red-600 dark:border-[#3c3f4a] dark:bg-[#2d2f39] dark:text-[#bfc2cd] dark:hover:text-red-400",children:i.jsx(Je,{className:"h-3 w-3"})})]})}const $u=[],Ru=(t="png")=>{const e=t.toLowerCase().replace(/^image\//,"");return e==="jpg"?"image/jpeg":`image/${e||"png"}`},Pu=(t,e)=>{const r=atob(t),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.charCodeAt(s);return new Blob([n],{type:e})},Du=async t=>{const e=URL.createObjectURL(t);try{const r=new Image;r.decoding="async";const n=new Promise((o,l)=>{r.onload=()=>o(r),r.onerror=()=>l(new Error("Failed to load generated image for clipboard copy"))});r.src=e,await n;const s=document.createElement("canvas");s.width=r.naturalWidth,s.height=r.naturalHeight;const a=s.getContext("2d");if(!a)throw new Error("Could not create canvas context for image clipboard copy");return a.drawImage(r,0,0),await new Promise((o,l)=>{s.toBlob(c=>{c?o(c):l(new Error("Could not encode generated image for clipboard copy"))},"image/png")})}finally{URL.revokeObjectURL(e)}},Uu=async(t,e)=>{const r=Ru(t.imageFormat);if(t.image)return Pu(t.image,r);if(!t.imageUrl)return null;const n=await fetch(t.imageUrl,{headers:e?{"X-Adapter-Name":e}:{}});if(!n.ok)throw new Error(`Could not fetch generated image for clipboard copy: ${n.status}`);const s=await n.blob();return s.type?s:new Blob([s],{type:r})},Ou=t=>t.imageUrl?new URL(t.imageUrl,window.location.origin).toString():t.imageRevisedPrompt||t.content;function Qa({size:t="md"}){const e=t==="sm"?"h-2 w-2":"h-2.5 w-2.5";return i.jsx("div",{className:"flex items-center gap-1.5 py-1",children:[0,150,300].map(r=>i.jsx("span",{className:`inline-block ${e} animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]`,style:{animationDelay:`${r}ms`}},r))})}function zu({reply:t}){const{t:e}=Ie(),[r,n]=h.useState(!1),[s,a]=h.useState(!1),o=h.useRef(null),l=ye(d=>d.submitFeedback);h.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]);const c=async d=>{if(!t.databaseMessageId||r)return;const u=t.feedback!==d;n(!0);try{await l(t.id,d),u?(a(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{a(!1),o.current=null},2e3)):a(!1)}catch(f){xe("Failed to submit thread reply feedback:",f)}finally{n(!1)}};return i.jsxs("div",{className:"mt-0.5 flex items-center gap-0.5 text-gray-400 dark:text-[#8e8ea0]",children:[i.jsx("button",{onClick:()=>c("up"),disabled:r,className:`rounded-md p-1.5 transition-colors ${r?"opacity-50 cursor-not-allowed":""} ${t.feedback==="up"?"text-green-600 dark:text-green-400":"hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]"}`,title:e("message.feedback.good"),"aria-label":e("message.feedback.good"),children:i.jsx(Bi,{className:"h-4 w-4"})}),i.jsx("button",{onClick:()=>c("down"),disabled:r,className:`rounded-md p-1.5 transition-colors ${r?"opacity-50 cursor-not-allowed":""} ${t.feedback==="down"?"text-red-600 dark:text-red-400":"hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]"}`,title:e("message.feedback.poor"),"aria-label":e("message.feedback.poor"),children:i.jsx(zi,{className:"h-4 w-4"})}),s&&i.jsxs("span",{className:"ml-1 inline-flex items-center gap-1.5 whitespace-nowrap rounded-lg bg-emerald-500 px-2.5 py-1 text-[11px] font-bold uppercase tracking-wider text-white shadow-sm animate-fadeIn dark:bg-emerald-600",children:[i.jsx(ur,{className:"h-3.5 w-3.5"}),e("message.feedback.thanks")]})]})}function Bu({message:t,onRegenerate:e,onEdit:r,onStartThread:n,onClearThread:s,onSendThreadMessage:a,threadMessages:o,sessionId:l,isThreadSendDisabled:c,availableModels:d=[],defaultModel:u=null,selectedModel:f=null}){var wt,yr,wr;const{t:m}=Ie(),[g,p]=h.useState(!1),[x,y]=h.useState(t.content||""),[v,A]=h.useState(!1),I=h.useRef(null),[C,S]=h.useState(!1),[E,_]=h.useState(!1),[b,F]=h.useState(!1),[k,N]=h.useState(""),[U,T]=h.useState(!1),[H,j]=h.useState(!1),[L,O]=h.useState(!1),[M,Y]=h.useState(0),[G,V]=h.useState(!1),[J,ue]=h.useState(!1),[Ee,$]=h.useState(()=>f??u),re=h.useRef(f),X=h.useRef(((wt=t.threadInfo)==null?void 0:wt.thread_id)||null),K=h.useRef(null),le=h.useRef(null),fe=h.useRef(null),z=h.useRef(!1),Z=h.useRef(0),ae=h.useRef(""),we=h.useRef(!1),ce=h.useRef(!0),te=h.useRef(!1),ee=h.useRef(null),_e=h.useRef(null),Ce=t.role==="assistant",Le=o??$u,De=Le.filter(R=>!(R.role==="assistant"&&R.isStreaming)).length,B=Le.some(R=>R.isStreaming),q=mr(),me=rt()&&!q,pe=ye(R=>R.conversations.find(ke=>ke.id===R.currentConversationId)),be=!!((t.image||t.imageUrl)&&Ce&&!t.isStreaming),Ye=!!((t.video||t.videoUrl)&&Ce&&!t.isStreaming),xt=m(be?"message.copyImageLabel":"message.copyLabel"),qe=mc(),kt=oe.maxMessageLength,Rt=oe.maxMessagesPerThread,St=Rt!==null&&De>=Rt,Pt=St?me?m("message.thread.limitReachedGuest",{count:Rt}):m("message.thread.limitReachedUser",{count:Rt}):null,{theme:Kt,isDark:nt}=tr(),Dt=m("message.thread.placeholder"),Ut=`thread-input-${t.id}`,{skills:je,isLoading:bt,selectedSkill:ie,selectSkill:ve,clearSkill:Te}=Yi({adapterName:pe==null?void 0:pe.adapterName,enabled:qe&&!!t.threadInfo,selectionScopeKey:((yr=t.threadInfo)==null?void 0:yr.thread_id)||t.id}),Me=k.startsWith("/")?k.slice(1):"",ne=Me.toLowerCase().replace(/-/g," "),Be=ne?je.filter(R=>R.name.replace(/-/g," ").toLowerCase().includes(ne)||R.description.toLowerCase().includes(ne)):je,Fs=Be.length>0?Math.min(M,Be.length-1):0,at=Be[Fs]??null,Gt=(at==null?void 0:at.name.replace(/-/g," "))??"",Br=L&&at&&k.startsWith("/")&&Gt.toLowerCase().startsWith(Me.toLowerCase())&&Gt.length>Me.length?Gt.slice(Me.length):null,rr=Kt.mode==="dark"?"dark":Kt.mode==="light"?"light":"",sr=nt?"dark":"light",dt=h.useMemo(()=>["message-markdown w-full min-w-0","prose prose-slate dark:prose-invert max-w-none",rr].filter(Boolean).join(" "),[rr]),Hr=h.useMemo(()=>["message-markdown w-full min-w-0","prose dark:prose-invert max-w-none",rr].filter(Boolean).join(" "),[rr]),pr=Ce?dt:Hr,gr=`${dt} text-sm leading-6`,Xt=`${Hr} text-sm leading-6`;h.useEffect(()=>{var R,ke;!X.current&&((R=t.threadInfo)!=null&&R.thread_id)&&T(!0),X.current=((ke=t.threadInfo)==null?void 0:ke.thread_id)||null},[(wr=t.threadInfo)==null?void 0:wr.thread_id]),h.useEffect(()=>{t.threadInfo||setTimeout(()=>{N(""),T(!1),j(!1),O(!1),Te()},0)},[t.threadInfo,Te]),h.useEffect(()=>{De>0&&setTimeout(()=>{T(!0)},0)},[De]),h.useEffect(()=>()=>{ee.current&&clearTimeout(ee.current),_e.current&&clearTimeout(_e.current)},[]),h.useEffect(()=>{if(!g||!I.current)return;const R=I.current;R.focus(),R.setSelectionRange(R.value.length,R.value.length)},[g]),h.useEffect(()=>{if(!g||!I.current)return;const R=I.current;R.style.height="auto",R.style.height=`${R.scrollHeight}px`},[g,x]);const xr=h.useCallback(()=>{const R=x.trim();if(!R||R===t.content){p(!1);return}r==null||r(t.id,R),p(!1)},[x,t.content,t.id,r]),it=h.useCallback(()=>{requestAnimationFrame(()=>{fe.current&&(fe.current.scrollTop=fe.current.scrollHeight)})},[]);h.useEffect(()=>{if(!U)return;const R=Le.length,ke=R>Z.current,W=Le[Le.length-1],Ne=(W==null?void 0:W.content)||"",et=Ne!==ae.current,We=(W==null?void 0:W.isStreaming)??!1,vr=we.current&&!We;ke||We&&et||vr?(it(),ce.current=!0):ce.current&&et&&it(),Z.current=R,ae.current=Ne,we.current=We},[U,Le,it]),h.useEffect(()=>{U&&(it(),ce.current=!0)},[U,it]);const nr=Ce?"message-bubble message-bubble-assistant min-w-0 break-words leading-relaxed text-[#353740] dark:text-[#ececf1]":"message-bubble message-bubble-user inline-block min-w-0 break-words leading-relaxed rounded-[1.75rem] border border-black/[0.06] bg-[#f4f4f4] px-4 py-3 text-[#111827] shadow-[0_1px_2px_rgba(16,24,40,0.06)] dark:border-white/[0.08] dark:bg-[#2a2a2a] dark:text-[#f5f5f5] dark:shadow-[0_1px_3px_rgba(0,0,0,0.3)]",jt=h.useCallback(()=>{S(!0),ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>{S(!1),ee.current=null},2e3)},[]),Vr=async()=>{try{if(be){if("ClipboardItem"in window&&navigator.clipboard.write)try{const ke=(pe==null?void 0:pe.adapterName)||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),W=await Uu(t,ke);if(W){const Ne=W.type==="image/png"?W:await Du(W);await navigator.clipboard.write([new ClipboardItem({[Ne.type||"image/png"]:Ne})]),jt();return}}catch(ke){xe("Failed to copy generated image, falling back to text:",ke)}const R=Ou(t);if(R){await navigator.clipboard.writeText(R),jt();return}return}await navigator.clipboard.writeText(t.content),jt()}catch(R){xe(be?"Failed to copy generated image:":"Failed to copy text:",R)}},$s=ye(R=>R.submitFeedback),Lt=async R=>{if(!t.databaseMessageId||E)return;const ke=t.feedback!==R;_(!0);try{await $s(t.id,R),ke?(F(!0),_e.current&&clearTimeout(_e.current),_e.current=setTimeout(()=>{F(!1),_e.current=null},2e3)):F(!1)}catch(W){xe("Failed to submit feedback:",W)}finally{_(!1)}},qr=async()=>{if(!a||!t.threadInfo||St)return;const R=k.trim();if(!R)return;const ke=k,W=ie,Ne=ie==null?void 0:ie.name;N(""),j(!0),O(!1),Ne&&Te();try{await a(t.threadInfo.thread_id,t.id,R,Ne,Ee??u??void 0),setTimeout(()=>{K.current&&K.current.focus()},100)}catch(et){xe("Failed to send thread message:",et),N(ke),W&&ve(W),setTimeout(()=>{K.current&&K.current.focus()},100)}finally{j(!1)}},He=h.useCallback(R=>{var ke;ve(R),O(!1),N(""),Y(0),(ke=K.current)==null||ke.focus()},[ve]),br=h.useCallback(()=>{var R;O(!1),N(""),Y(0),(R=K.current)==null||R.focus()},[]),ar=h.useCallback(()=>{var R;N("/"),O(!0),Y(0),(R=K.current)==null||R.focus()},[]),Rs=R=>{if(L){if(R.key==="ArrowDown"){R.preventDefault(),Y(ke=>Be.length===0?0:(ke+1)%Be.length);return}if(R.key==="ArrowUp"){R.preventDefault(),Y(ke=>Be.length===0?0:(ke-1+Be.length)%Be.length);return}if(R.key==="Home"){R.preventDefault(),Y(0);return}if(R.key==="End"){R.preventDefault(),Y(Math.max(Be.length-1,0));return}if((R.key==="Enter"&&!R.shiftKey||R.key==="Tab")&&at){R.preventDefault(),He(at);return}if(R.key==="Escape"){R.preventDefault(),br();return}}R.key==="Enter"&&!R.shiftKey&&(R.preventDefault(),qr())},ut=!t.threadInfo||!a||c||B||H||St,yt=!!t.threadInfo&&!!s&&De>0&&!B&&!H&&!c,Ps=async()=>{if(!(!t.threadInfo||!s)){ue(!0);try{await s(t.id,t.threadInfo.thread_id),V(!1),T(!1),N("")}catch(R){xe("Failed to clear thread:",R)}finally{ue(!1)}}};h.useEffect(()=>{re.current=f},[f]),h.useEffect(()=>{$(re.current??u)},[u]),h.useEffect(()=>{if(!U||ut){te.current=H;return}const R=K.current;if(!R){te.current=H;return}if(!(z.current||te.current)){te.current=H;return}const W=requestAnimationFrame(()=>{var et;z.current&&((et=le.current)==null||et.scrollIntoView({behavior:"auto",block:"nearest",inline:"nearest"})),R.focus();const Ne=R.value.length;R.setSelectionRange(Ne,Ne),z.current=!1,te.current=H});return()=>{cancelAnimationFrame(W),te.current=H}},[U,ut,H]),h.useEffect(()=>{if(K.current){const ke=K.current;ke.style.height="auto";const W=ke.scrollHeight;ke.style.height=`${Math.min(W,120)}px`,ke.style.overflowY=W>120?"auto":"hidden"}},[k]);const Ds=h.useMemo(()=>{if(t.isStreaming&&(!t.content||t.content==="…"))return i.jsx("div",{className:pr,children:i.jsx(Qa,{})});const R=t.isStreaming&&Ce?" streaming-cursor":"";return i.jsx("div",{className:R||void 0,children:i.jsx($t,{content:kn(Ur(t.content||"")),className:pr,syntaxTheme:sr})})},[pr,t.content,t.isStreaming,Ce,sr]),Us=h.useMemo(()=>{const R=W=>W instanceof Date?W.getTime():new Date(W).getTime();return[...Le].sort((W,Ne)=>R(W.timestamp)-R(Ne.timestamp)).map(W=>{const Ne=W.role==="assistant",et=Ne?gr:Xt,We=W.isStreaming&&Ne?" streaming-cursor":"",vr=W.isStreaming&&(!W.content||W.content==="…")?i.jsx("div",{className:et,children:i.jsx(Qa,{size:"sm"})}):i.jsx("div",{className:We||void 0,children:i.jsx($t,{content:kn(Ur(W.content||"")),className:et,syntaxTheme:sr})});return i.jsx("div",{className:`min-w-0 flex ${Ne?"justify-start":"justify-end"}`,children:i.jsxs("div",{className:Ne?"min-w-0 w-full max-w-full":"min-w-0 max-w-[85%]",children:[i.jsxs("div",{className:Ne?"thread-markdown-wrapper overflow-x-visible text-sm text-[#353740] dark:text-[#ececf1]":"thread-markdown-wrapper overflow-x-visible text-sm rounded-[1.75rem] bg-[#f4f4f4] px-4 py-3 text-[#111827] dark:bg-[#2a2a2a] dark:text-[#f5f5f5]",children:[vr,W.audio&&Ne&&!W.isStreaming&&i.jsx(ns,{audio:W.audio,audioFormat:W.audioFormat,autoPlay:!1}),(W.image||W.imageUrl)&&Ne&&!W.isStreaming&&i.jsx(Da,{image:W.image,imageUrl:W.imageUrl,imageFormat:W.imageFormat,revisedPrompt:W.imageRevisedPrompt}),(W.video||W.videoUrl)&&Ne&&!W.isStreaming&&i.jsx(Ua,{video:W.video,videoUrl:W.videoUrl,videoFormat:W.videoFormat,revisedPrompt:W.videoRevisedPrompt,adapterName:pe==null?void 0:pe.adapterName}),(W.document||W.documentUrl)&&Ne&&!W.isStreaming&&i.jsx(Ha,{document:W.document,documentUrl:W.documentUrl,documentFormat:W.documentFormat,revisedPrompt:W.documentRevisedPrompt,adapterName:pe==null?void 0:pe.adapterName}),W.generatedAudioUrl&&Ne&&!W.isStreaming&&i.jsx(ns,{audioUrl:W.generatedAudioUrl,audioFormat:W.generatedAudioFormat,downloadFilename:`generated-audio.${W.generatedAudioFormat||"mp3"}`,autoPlay:!1})]}),Ne&&!W.isStreaming&&W.model&&i.jsx("div",{className:"px-1 pt-0.5 text-[11px] text-gray-400 dark:text-[#9a9ab0]",children:m("message.generatedBy",{model:W.model})}),Ne&&!W.isStreaming&&Ca()&&i.jsx(zu,{reply:W})]})},W.id)})},[pe==null?void 0:pe.adapterName,sr,m,gr,Le,Xt]);return i.jsxs("div",{className:"group animate-fadeIn min-w-0 w-full px-0",children:[i.jsxs("div",{className:"min-w-0 space-y-1",children:[i.jsxs("div",{className:Ce?void 0:"flex flex-col items-end",children:[i.jsxs("div",{className:nr,children:[g?i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsx("textarea",{ref:I,className:"w-full resize-none overflow-hidden bg-transparent outline-none text-[#111827] dark:text-[#f5f5f5] leading-relaxed",value:x,onChange:R=>y(R.target.value),onCompositionStart:()=>A(!0),onCompositionEnd:()=>A(!1),onKeyDown:R=>{R.key==="Enter"&&!R.shiftKey&&!v&&(R.preventDefault(),R.stopPropagation(),xr()),R.key==="Escape"&&(R.stopPropagation(),p(!1),y(t.content||""))},maxLength:oe.maxMessageLength,rows:1,style:{minHeight:"24px"}}),i.jsxs("div",{className:"flex items-center justify-between gap-2 mt-1",children:[i.jsx("span",{className:"text-xs text-gray-400 dark:text-[#6e6e80]",children:m("message.edit.willRegenerateHint")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>{p(!1),y(t.content||"")},className:"px-3 py-1.5 text-xs font-medium rounded-full bg-gray-200 text-gray-700 hover:bg-gray-300 dark:bg-[#4a4b54] dark:text-gray-200 dark:hover:bg-[#565869] transition-colors",children:m("common.cancel")}),i.jsxs("button",{onClick:xr,className:"px-3 py-1.5 text-xs font-medium rounded-full bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-1.5",children:[i.jsx(xn,{className:"w-3.5 h-3.5"}),m("common.send")]})]})]})]}):Ds,t.attachments&&t.attachments.length>0&&i.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:t.attachments.map(R=>i.jsx(js,{filename:R.filename,fileId:R.file_id,status:"completed",statusText:`${(R.file_size/1024).toFixed(1)} KB`},R.file_id))}),t.audio&&Ce&&!t.isStreaming&&i.jsx(ns,{audio:t.audio,audioFormat:t.audioFormat,autoPlay:!1}),(t.image||t.imageUrl)&&Ce&&!t.isStreaming&&i.jsx(Da,{image:t.image,imageUrl:t.imageUrl,imageFormat:t.imageFormat,revisedPrompt:t.imageRevisedPrompt}),(t.video||t.videoUrl)&&Ce&&!t.isStreaming&&i.jsx(Ua,{video:t.video,videoUrl:t.videoUrl,videoFormat:t.videoFormat,revisedPrompt:t.videoRevisedPrompt,adapterName:pe==null?void 0:pe.adapterName}),(t.document||t.documentUrl)&&Ce&&!t.isStreaming&&i.jsx(Ha,{document:t.document,documentUrl:t.documentUrl,documentFormat:t.documentFormat,revisedPrompt:t.documentRevisedPrompt,adapterName:pe==null?void 0:pe.adapterName}),t.generatedAudioUrl&&Ce&&!t.isStreaming&&i.jsx(ns,{audioUrl:t.generatedAudioUrl,audioFormat:t.generatedAudioFormat,downloadFilename:`generated-audio.${t.generatedAudioFormat||"mp3"}`,autoPlay:!1})]}),!Ce&&!g&&i.jsxs("div",{className:"flex items-center gap-0.5 py-1 text-gray-400 dark:text-[#8e8ea0]",children:[i.jsx("button",{onClick:Vr,className:"rounded-md p-1.5 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",title:xt,"aria-label":xt,children:C?i.jsx(ur,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):i.jsx(Ia,{className:"h-4 w-4"})}),r&&i.jsx("button",{onClick:()=>{y(t.content||""),p(!0)},className:"rounded-md p-1.5 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",title:m("message.editAriaLabel"),"aria-label":m("message.editAriaLabel"),children:i.jsx(Ui,{className:"h-4 w-4"})})]})]}),Ce&&!t.isStreaming&&t.model&&i.jsx("div",{className:"px-1 pt-0.5 text-[11px] text-gray-400 dark:text-[#9a9ab0]",children:m("message.generatedBy",{model:t.model})}),Ce&&!t.isStreaming&&i.jsxs("div",{className:"py-1 flex flex-nowrap items-center gap-0.5 text-gray-400 dark:text-[#8e8ea0] transition-opacity",children:[!Ye&&i.jsx("button",{onClick:Vr,className:"rounded-md p-1.5 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",title:xt,"aria-label":xt,children:C?i.jsx(ur,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):i.jsx(Ia,{className:"h-4 w-4"})}),Ca()&&i.jsxs("div",{className:"relative flex items-center gap-0.5",children:[i.jsx("button",{onClick:()=>Lt("up"),disabled:E,className:`rounded-md p-1.5 transition-colors ${E?"opacity-50 cursor-not-allowed":""} ${t.feedback==="up"?"text-green-600 dark:text-green-400":"hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]"}`,title:m("message.feedback.good"),"aria-label":m("message.feedback.good"),children:i.jsx(Bi,{className:"h-4 w-4"})}),i.jsx("button",{onClick:()=>Lt("down"),disabled:E,className:`rounded-md p-1.5 transition-colors ${E?"opacity-50 cursor-not-allowed":""} ${t.feedback==="down"?"text-red-600 dark:text-red-400":"hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]"}`,title:m("message.feedback.poor"),"aria-label":m("message.feedback.poor"),children:i.jsx(zi,{className:"h-4 w-4"})}),b&&i.jsxs("div",{className:"absolute bottom-full left-1/2 mb-2 -translate-x-1/2 whitespace-nowrap rounded-lg bg-emerald-500 px-2.5 py-1 text-[11px] font-bold uppercase tracking-wider text-white shadow-sm animate-fadeIn dark:bg-emerald-600",children:[i.jsx("div",{className:"absolute left-1/2 top-full h-2.5 w-2.5 -translate-x-1/2 -translate-y-1/2 rotate-45 bg-emerald-500 dark:bg-emerald-600"}),i.jsxs("div",{className:"relative flex items-center gap-1.5",children:[i.jsx(ur,{className:"h-3.5 w-3.5"}),i.jsx("span",{children:m("message.feedback.thanks")})]})]})]}),e&&i.jsx("button",{onClick:()=>e(t.id),className:"rounded-md p-1.5 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",title:m("message.regenerateTitle"),"aria-label":m("message.regenerateAriaLabel"),children:i.jsx(pd,{className:"h-4 w-4"})}),qe&&t.supportsThreading&&!t.threadInfo&&n&&l&&i.jsxs("button",{type:"button",onClick:()=>{z.current=!0,T(!0),n(t.id,l)},className:"ml-1 inline-flex items-center gap-1.5 rounded-full border border-blue-200 bg-blue-50 px-2.5 py-1.5 text-xs text-blue-700 shadow-sm transition-all hover:border-blue-300 hover:bg-blue-100 hover:text-blue-800 hover:shadow-md dark:border-blue-500/30 dark:bg-blue-500/10 dark:text-blue-200 dark:hover:border-blue-400/50 dark:hover:bg-blue-500/20 dark:hover:text-blue-100 animate-follow-up-enter whitespace-nowrap",title:m("message.thread.continueDiscussionTitle"),"aria-label":m("message.thread.continueDiscussionAriaLabel"),children:[i.jsx(La,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{children:m("message.thread.continueLabel")})]}),qe&&t.threadInfo&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-px h-4 shrink-0 bg-gray-200 dark:bg-[#3c3f4a] mx-1"}),i.jsxs("button",{onClick:()=>T(R=>!R),className:"inline-flex min-w-0 items-center gap-1.5 rounded-md px-2 py-1.5 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1] transition-colors text-xs",children:[i.jsx(La,{className:"h-4 w-4"}),i.jsx("span",{className:"truncate",children:m("message.thread.replyCount",{count:De})}),U?i.jsx(bs,{className:"h-3 w-3"}):i.jsx(hr,{className:"h-3 w-3"})]}),yt&&i.jsx("button",{type:"button",onClick:()=>V(!0),className:"inline-flex items-center rounded-md px-2 py-1 text-xs font-medium text-red-600 transition-colors hover:bg-red-50 dark:text-red-300 dark:hover:bg-red-900/30",title:m("message.thread.clearTitle"),"aria-label":m("message.thread.clearAriaLabel"),children:m("common.clear")})]})]}),qe&&t.threadInfo&&U&&i.jsxs("div",{className:"thread-panel mt-3 md:mt-3 border-l-2 border-gray-200 pl-3 sm:pl-4 dark:border-[#3b3c49]",children:[i.jsx("div",{ref:fe,className:"thread-replies-scroll mt-2 space-y-2 pb-3",onScroll:()=>{if(!fe.current)return;const{scrollTop:R,scrollHeight:ke,clientHeight:W}=fe.current;ce.current=ke-R-W<100},children:De>0?Us:null}),Pt&&i.jsxs("div",{className:"mt-3 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900 dark:border-amber-500/30 dark:bg-[#2f2410] dark:text-amber-100",children:[Pt,me&&i.jsx("div",{className:"mt-2",children:i.jsx("button",{type:"button",onClick:()=>st.getState().openLoginPrompt(m("message.thread.signInPromptMessage")),className:"inline-flex items-center gap-1 rounded-md bg-blue-600 px-2.5 py-1 text-[11px] font-medium text-white hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600",children:m("message.thread.signInForHigherLimits")})})]}),i.jsxs("div",{ref:le,className:"mt-1 w-full max-w-[64rem] bg-transparent pt-1",children:[i.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-gray-200 bg-gray-50 px-3 py-2 dark:border-[#242424] dark:bg-[#101010]",children:[ie&&i.jsxs("div",{className:"flex h-8 shrink-0 items-center gap-1.5 self-center rounded-full border border-gray-300 bg-white px-2.5 text-xs text-gray-700 shadow-sm dark:border-[#3a3a3a] dark:bg-[#1a1a1a] dark:text-gray-200",children:[i.jsx($n,{className:"h-3.5 w-3.5 shrink-0 text-gray-500 dark:text-gray-400","aria-hidden":"true"}),i.jsx("span",{className:"min-w-0 truncate font-medium capitalize",children:ie.name.replace(/-/g," ")}),i.jsx("button",{type:"button",onClick:()=>Te(),className:"-mr-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-white/10 dark:hover:text-gray-100","aria-label":m("message.thread.removeSkillAriaLabel"),children:i.jsx(Je,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),!ie&&je.length>0&&k.length===0&&!ut&&i.jsxs("button",{type:"button",onClick:ar,className:"flex h-8 shrink-0 items-center gap-1.5 self-center rounded-full border border-gray-300 bg-white px-2.5 text-xs font-medium text-gray-600 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 dark:border-[#3a3a3a] dark:bg-[#1a1a1a] dark:text-gray-300 dark:hover:bg-white/10 dark:hover:text-gray-100 dark:focus-visible:ring-gray-600","aria-label":m("message.thread.skillsHintAriaLabel"),title:m("message.thread.skillsHint"),children:[i.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded bg-gray-200 font-mono text-[10px] leading-none text-gray-600 dark:bg-[#2a2a2a] dark:text-gray-300","aria-hidden":"true",children:"/"}),m("messageInput.skillsHint.text")]}),i.jsxs("div",{className:"relative flex min-h-8 flex-1 items-center min-w-0",children:[i.jsx("label",{htmlFor:Ut,className:"sr-only",children:m("message.thread.placeholder")}),Br&&i.jsxs("div",{className:"pointer-events-none absolute inset-0 whitespace-pre-wrap px-0 py-0 text-base leading-8 text-gray-400 dark:text-[#8e8ea0] sm:text-sm sm:leading-8","aria-hidden":"true",children:[i.jsx("span",{className:"invisible",children:k}),i.jsx("span",{children:Br})]}),i.jsx("textarea",{id:Ut,ref:K,className:"relative z-10 block h-8 w-full min-w-0 resize-none overflow-hidden bg-transparent px-0 py-0 text-base leading-8 text-[#353740] placeholder-slate-500 outline-none transition focus:outline-none disabled:opacity-60 dark:text-[#ececf1] dark:placeholder-[#70707c] sm:text-sm sm:leading-8",placeholder:Dt,"aria-label":m("message.thread.placeholder"),value:k,onChange:R=>{const ke=R.target.value;N(ke),ke.startsWith("/")&&Y(0),O(ke.startsWith("/"))},onKeyDown:Rs,disabled:ut,rows:1,maxLength:kt,style:{minHeight:"32px",maxHeight:"120px",outline:"none",boxShadow:"none",WebkitAppearance:"none",MozAppearance:"none",appearance:"none"}})]}),i.jsxs("div",{className:"flex items-center justify-between sm:justify-end gap-2",children:[i.jsx(so,{availableModels:d,defaultModel:u,selectedModel:Ee,onSelect:$,maxWidthClass:"max-w-[120px]",triggerPaddingClass:"px-2 py-1",staticPaddingClass:"px-2 py-1",triggerTitle:m("message.thread.selectModelTitle"),listboxLabel:m("message.thread.selectModelTitle")}),k.trim().length>0&&i.jsx("button",{type:"button",onClick:qr,disabled:ut||k.trim().length===0,className:"flex h-10 w-10 sm:h-8 sm:w-8 items-center justify-center rounded-full transition active:scale-95 bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-400 disabled:cursor-not-allowed",title:m("message.thread.sendMessageTitle"),children:i.jsx(xn,{className:"h-5 w-5 sm:h-4 sm:w-4"})})]})]}),L&&i.jsx("div",{className:"w-full pt-1",children:i.jsx(ro,{skills:je,isLoading:bt,selectedSkill:ie,activeSkillName:at==null?void 0:at.name,query:Me,onActiveSkillChange:R=>{const ke=Be.findIndex(W=>W.name===R.name);ke>=0&&Y(ke)},onSelect:He,onClose:br})})]}),De>0&&i.jsx("div",{className:"mt-2 flex justify-end",children:i.jsxs("button",{type:"button",onClick:()=>T(!1),className:"inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-[#bfc2cd] dark:hover:bg-[#2f313a] dark:hover:text-white","aria-label":m("message.thread.hideRepliesAriaLabel"),children:[i.jsx(bs,{className:"h-3 w-3"}),i.jsx("span",{children:m("message.thread.hideRepliesLabel")})]})})]})]}),i.jsx(ws,{isOpen:G,onClose:()=>{J||V(!1)},onConfirm:Ps,title:m("message.confirmation.clearRepliesTitle"),message:m("message.confirmation.clearRepliesMessage"),confirmText:m("common.clear"),cancelText:m("common.cancel"),type:"danger",isLoading:J})]})}let or=null;function Hu(){if(typeof window>"u")return null;const t=window.AudioContext??window.webkitAudioContext;return t?((!or||or.state==="closed")&&(or=new t),or.state==="suspended"&&or.resume(),or):(D("[SoundEffects] AudioContext not supported in this browser"),null)}function Vu(t){const e=Hu();if(!e)return;const r=e.currentTime;for(const n of t){const s=e.createOscillator(),a=e.createGain();s.connect(a),a.connect(e.destination),s.frequency.value=n.frequency,s.type=n.type;const o=r+n.startTime,l=o+n.duration;a.gain.setValueAtTime(.001,o),a.gain.linearRampToValueAtTime(n.gain,o+.008),a.gain.exponentialRampToValueAtTime(.001,l),s.start(o),s.stop(l+.01)}}const qu={messageSent:[{frequency:1046,startTime:0,duration:.08,gain:.15,type:"sine"},{frequency:1397,startTime:.07,duration:.11,gain:.18,type:"sine"}],messageReceived:[{frequency:988,startTime:0,duration:.12,gain:.16,type:"sine"},{frequency:1319,startTime:.13,duration:.12,gain:.18,type:"sine"},{frequency:1568,startTime:.26,duration:.18,gain:.14,type:"sine"}],success:[{frequency:784,startTime:0,duration:.1,gain:.14,type:"sine"},{frequency:1175,startTime:.11,duration:.18,gain:.18,type:"sine"}],error:[{frequency:330,startTime:0,duration:.15,gain:.16,type:"sine"},{frequency:262,startTime:.18,duration:.22,gain:.13,type:"sine"}],notification:[{frequency:880,startTime:0,duration:.1,gain:.14,type:"sine"},{frequency:1109,startTime:.12,duration:.16,gain:.17,type:"sine"}]};function _r(t,e){if(!e)return;const r=qu[t];if(!r){D(`[SoundEffects] Unknown sound effect type: ${t}`);return}try{Vu(r),D(`[SoundEffects] Playing ${t} sound effect`)}catch(n){D(`[SoundEffects] Failed to play ${t} sound effect:`,n)}}function Wu({messages:t,onRegenerate:e,onEditMessage:r,onStartThread:n,onClearThread:s,onSendThreadMessage:a,sessionId:o,isLoading:l,contentMaxWidthClass:c="max-w-[64rem]",availableModels:d,defaultModel:u,selectedModel:f}){const m=h.useRef(null),g=h.useRef(null),p=h.useRef(t.length),x=h.useRef(""),y=h.useRef(l),v=h.useRef(!0),{settings:A}=Ns(),{t:I}=Ie(),{topLevelMessages:C,threadLookup:S}=h.useMemo(()=>{const b=new Map,F=[];return t.forEach(k=>{if(k.isThreadMessage&&k.parentMessageId){const N=b.get(k.parentMessageId)||[];b.set(k.parentMessageId,[...N,k]);return}F.push(k)}),{topLevelMessages:F,threadLookup:b}},[t]),E=()=>{if(!g.current)return;const{scrollTop:b,scrollHeight:F,clientHeight:k}=g.current,U=F-b-k<200;v.current=U},_=h.useCallback(()=>{requestAnimationFrame(()=>{g.current&&(g.current.scrollTop=g.current.scrollHeight)})},[]);return h.useEffect(()=>{const b=t.length,F=p.current,k=b>F,N=t[t.length-1],U=(N==null?void 0:N.content)||"",T=U!==x.current,H=(N==null?void 0:N.isStreaming)??!1;k||H&&T?(_(),v.current=!0):v.current&&T&&_(),p.current=b,x.current=U},[t,_]),h.useEffect(()=>{l&&(_(),v.current=!0)},[l,_]),h.useEffect(()=>{if(y.current&&!l){const b=t[t.length-1];(b==null?void 0:b.role)==="assistant"&&b.content&&_r("messageReceived",A.soundEnabled)}y.current=l},[l,t,A.soundEnabled]),C.length===0?i.jsx("div",{className:"flex-1 flex items-center justify-center px-4 sm:px-6",children:i.jsxs("div",{className:"text-center text-lg text-gray-500 dark:text-[#bfc2cd]",children:[i.jsx("p",{className:"text-xl",children:I("messageList.emptyStateHeading")}),i.jsx("p",{className:"mt-1 text-lg",children:I("messageList.emptyStateSubheading")})]})}):i.jsx("div",{ref:g,className:"message-list flex-1 overflow-y-auto pb-8 pt-4 sm:pt-6",onScroll:E,children:i.jsx("div",{className:"mx-auto w-full max-w-[96rem] px-3 sm:px-5 md:px-6 lg:px-8 xl:px-10",children:i.jsxs("div",{className:`message-list__rail mx-auto w-full space-y-7 ${c}`,children:[C.map(b=>i.jsx("div",{className:`flex w-full ${b.role==="user"?"justify-end":"justify-start"}`,style:{contentVisibility:"auto",containIntrinsicSize:"420px"},children:i.jsx(Bu,{message:b,onRegenerate:e,onEdit:r,onStartThread:n,onClearThread:s,onSendThreadMessage:a,threadMessages:S.get(b.id),sessionId:o,isThreadSendDisabled:l,availableModels:d,defaultModel:u,selectedModel:f})},b.id)),i.jsx("div",{ref:m,className:"h-8"})]})})})}const Ku=4e3;function Gu(t,e,r={}){var F;const{t:n}=Ie(),[s,a]=h.useState(!1),[o,l]=h.useState(null),c=h.useRef(null),d=h.useRef(""),u=h.useRef(""),f=h.useRef(!1),m=h.useRef(null),g=typeof navigator<"u"?navigator.language:"en-US",p=Number.isFinite(r.silenceTimeoutMs)?Math.max(Math.floor(r.silenceTimeoutMs),1e3):Ku,x=((F=r.language)==null?void 0:F.trim())||g||"en-US",y=h.useCallback(k=>k.replace(/\s+/g," ").trim(),[]),v=h.useCallback(k=>{const N=y(k);N&&N!==u.current&&(u.current=N,t(N))},[y,t]),A=h.useCallback(()=>{if(!d.current)return;const k=d.current;d.current="",v(k)},[v]),I=typeof window<"u"&&("webkitSpeechRecognition"in window||"SpeechRecognition"in window),C=h.useCallback(()=>{!e||f.current||(f.current=!0,e())},[e]),S=h.useCallback(()=>{m.current!==null&&(clearTimeout(m.current),m.current=null)},[]),E=h.useCallback(()=>{S(),m.current=setTimeout(()=>{D("Speech recognition silence threshold reached, stopping recording"),c.current?c.current.stop():C()},p)},[S,C,p]),_=h.useCallback(()=>{if(!I){l(n("voice.browserNotSupported"));return}if(!c.current)try{f.current=!1;const k=window.SpeechRecognition||window.webkitSpeechRecognition,N=new k;N.continuous=!0,N.interimResults=!0,N.lang=x,N.maxAlternatives=1,N.onstart=()=>{a(!0),l(null),d.current="",u.current="",D("Speech recognition started"),E()},N.onresult=U=>{let T="",H="";for(let j=U.resultIndex;j<U.results.length;j++){const L=U.results[j][0].transcript;U.results[j].isFinal?T+=L:H+=L}H&&(d.current=y(H)),T&&(d.current="",v(T)),E()},N.onend=()=>{S(),A(),a(!1),c.current=null,D("Speech recognition ended"),C()},N.onerror=U=>{switch(S(),xe("Speech recognition error:",U.error),a(!1),c.current=null,d.current="",C(),U.error){case"no-speech":l(n("voice.error.noSpeech"));break;case"audio-capture":l(n("voice.error.audioCapture"));break;case"not-allowed":l(n("voice.error.notAllowed"));break;case"network":l(n("voice.error.network"));break;default:l(n("voice.error.generic",{error:U.error}))}},N.start(),c.current=N}catch(k){xe("Failed to start speech recognition:",k),l(n("voice.error.startFailed")),a(!1)}},[I,A,C,E,S,x,y,v,n]),b=h.useCallback(()=>{if(D("Stopping speech recognition..."),c.current){const k=c.current;k.onstart=null,k.onerror=null;try{k.stop()}catch(N){D("Recognition already stopped or error stopping:",N),S(),A(),k.onend=null,k.onresult=null,c.current=null,a(!1),C()}}S(),a(!1),l(null),D("Speech recognition stopped, isListening set to false")},[S,A,C]);return{isListening:s,isSupported:I,startListening:_,stopListening:b,error:o}}const Xu=300,Za=3,cs=5,Yu=6e4;function Ja(t){if(typeof t!="string")return null;const e=t.replace(/[\r\n\u2028\u2029]+/g," ").replace(/\s{2,}/g," ").trim();return e?{text:e}:null}function Qu(t,e={}){const{enabled:r=Ai(),adapterName:n,sessionId:s,adapterSupportsAutocomplete:a,skill:o,inputRef:l}=e,[c,d]=h.useState([]),[u,f]=h.useState(!1),[m,g]=h.useState(-1),p=h.useRef(null),x=h.useRef(null),y=h.useRef(null),v=h.useRef(null),A=h.useRef(null),I=h.useRef(0),C=h.useRef([]),S=h.useRef([]),E=h.useRef(new Map);h.useEffect(()=>{C.current=c},[c]);const _=h.useCallback(j=>{const L=E.current.get(j);return L?L<=Date.now()?(E.current.delete(j),!1):!0:!1},[]),b=h.useCallback((j,L=!0)=>{const O=j.toLowerCase().trim(),M=S.current.length>0?S.current:C.current;if(!O)return M.slice(0,cs);const Y=M.filter(G=>G.text.toLowerCase().includes(O));return Y.length>0?Y.slice(0,cs):L?M.slice(0,cs):[]},[]),F=h.useCallback(async j=>{if(!r||j.length<Za){d([]),S.current=[],x.current&&clearTimeout(x.current),y.current&&clearTimeout(y.current),f(!1);return}if(!n){d([]),S.current=[],x.current&&clearTimeout(x.current),f(!1);return}if(a===!1||_(n)){d([]),S.current=[],x.current&&clearTimeout(x.current),f(!1);return}v.current&&v.current.abort(),v.current=new AbortController;const L=I.current+1;I.current=L,x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{L===I.current&&f(!0)},150);try{const O={"X-Adapter-Name":n};s&&(O["X-Session-ID"]=s);const M=new URLSearchParams;M.set("q",j),M.set("limit",String(cs)),o&&M.set("skill",o);const Y=`/api/v1/autocomplete?${M.toString()}`,G=await fetch(Y,{method:"GET",headers:O,signal:v.current.signal});if(!G.ok){ge("[useAutocomplete] Request failed:",G.status),[404,405,501].includes(G.status)?(E.current.set(n,Date.now()+Yu),d([]),S.current=[]):d(b(j));return}const V=await G.json(),J=Array.isArray(V==null?void 0:V.suggestions)?V.suggestions.map(ue=>Ja(typeof ue=="string"?ue:ue==null?void 0:ue.text)).filter(ue=>ue!==null):[];if(L!==I.current)return;J.length===0?d(b(j,!1)):(d(J),S.current=J),g(-1),D("[useAutocomplete] Received",J.length,"suggestions")}catch(O){if(O instanceof Error&&O.name==="AbortError")return;ge("[useAutocomplete] Error:",O instanceof Error?O.message:String(O)),L===I.current&&d(b(j))}finally{L===I.current&&(x.current&&(clearTimeout(x.current),x.current=null),f(!1))}},[r,n,s,a,o,b,_]);h.useEffect(()=>{p.current&&clearTimeout(p.current);const j=()=>{v.current&&v.current.abort(),x.current&&clearTimeout(x.current),f(!1)},L=()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{y.current=null,d([]),j()},0)};if(!r||t.length<Za||a===!1||n&&_(n)){L();return}if(A.current){if(t===A.current){L();return}A.current=null}return p.current=setTimeout(()=>{F(t)},Xu),()=>{p.current&&clearTimeout(p.current),y.current&&(clearTimeout(y.current),y.current=null)}},[t,F,r,n,a,_]),h.useEffect(()=>()=>{v.current&&v.current.abort(),x.current&&clearTimeout(x.current)},[]);const k=h.useCallback(()=>{g(j=>{const L=C.current.length;return L===0?-1:j<L-1?j+1:0})},[]),N=h.useCallback(()=>{g(j=>{const L=C.current.length;return L===0?-1:j>0?j-1:L-1})},[]),U=h.useCallback(()=>{d([]),S.current=[],g(-1),v.current&&v.current.abort(),x.current&&clearTimeout(x.current),f(!1)},[]),T=h.useCallback(j=>{if(!(l!=null&&l.current))return;const L=()=>{const O=l.current;if(!O)return;const M=typeof j=="string"?j.length:O.value.length;O.focus({preventScroll:!0}),typeof O.setSelectionRange=="function"&&O.setSelectionRange(M,M)};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(L):setTimeout(L,0)},[l]),H=h.useCallback(j=>{A.current=j},[]);return{suggestions:c,isLoading:u,selectedIndex:m,setSelectedIndex:g,selectNext:k,selectPrevious:N,clearSuggestions:U,focusInputAfterSelection:T,suppressUntilQueryChange:H}}const Bt=new Map,Zu=new Map,Ju=new Map,ef=new Set,tf=()=>{if(typeof window>"u")return null;try{return localStorage.getItem("chat-adapter-name")}catch{return null}},no=t=>typeof t=="object"&&t!==null&&"message"in t,rf=t=>t instanceof Error?t.message:typeof t=="string"?t:no(t)?t.message??"Unknown error":"Unknown error";function sf({conversationId:t,onFilesSelected:e,onUploadError:r,onClose:n,onUploadingChange:s,onUploadSuccess:a,maxFiles:o=oe.maxFilesPerConversation,disabled:l=!1}){const{t:c}=Ie(),[d,u]=h.useState(!1),[f,m]=h.useState(0),g=h.useRef(null),p=h.useRef(Ju),x=h.useRef(ef),y=h.useRef(new Map),v=h.useRef(!0),A=h.useRef(Zu),I=h.useRef(t),C=ye($=>$.conversations),S=h.useMemo(()=>{if(!t)return new Map;const $=Bt.get(t);return $?new Map($):new Map},[t,f]),E=h.useMemo(()=>{var X;if(!t)return Array.from(S.entries());const $=C.find(K=>K.id===t),re=new Set(((X=$==null?void 0:$.attachedFiles)==null?void 0:X.map(K=>K.file_id))||[]);return Array.from(S.entries()).filter(([,K])=>!K.fileId||!re.has(K.fileId))},[t,C,S]),_=h.useCallback($=>{if(!$){s==null||s(null,!1),m(le=>le+1);return}const re=Bt.get($)||new Map,X=C.find(le=>le.id===$),K=new Map(re);if(X!=null&&X.attachedFiles){const le=new Set(X.attachedFiles.filter(fe=>fe.processing_status==="completed"||fe.processing_status==="failed"||fe.processing_status==="error").map(fe=>fe.file_id));K.forEach((fe,z)=>{fe.fileId&&le.has(fe.fileId)&&K.delete(z)})}K.size>0?(Bt.set($,K),s==null||s($,!0)):(Bt.delete($),s==null||s($,!1)),m(le=>le+1)},[C,s]);h.useEffect(()=>{I.current=t,setTimeout(()=>{_(t)},0)},[t,_]),h.useEffect(()=>{t&&setTimeout(()=>{_(t)},0)},[C,t,_]);const b=h.useCallback(($,re)=>{if(!$)return;const X=Bt.get($)||new Map,K=re(new Map(X));K.size>0?Bt.set($,K):Bt.delete($),s==null||s($,K.size>0),m(le=>le+1)},[s]),F=h.useCallback(($,re)=>{if(!$)return;const X=A.current.get($)||[],K=re([...X||[]]),le=new Set(X.map(fe=>fe.file_id));if(A.current.set($,K),e($,K),a){const fe=K.filter(z=>!le.has(z.file_id));fe.length>0&&a($,fe)}m(fe=>fe+1)},[e,a]),k=ye($=>$.removeFileFromConversation),N=ye($=>$.addFileToConversation);h.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);const U=h.useCallback(()=>{v.current=!1,new Map(y.current).forEach(re=>re.abort()),setTimeout(()=>{const re=ye.getState(),X=new Map(re.conversations.map(le=>[le.id,le])),K=[];p.current.forEach((le,fe)=>{var z;if(le){const Z=X.get(le);if(new Set(((z=Z==null?void 0:Z.attachedFiles)==null?void 0:z.map(we=>we.file_id))||[]).has(fe)){x.current.add(fe),p.current.delete(fe);return}}if(x.current.has(fe)){D(`[FileUpload] Skipping cleanup delete for ${fe}; file was previously attached and already handled`),p.current.delete(fe),x.current.delete(fe);return}K.push({fileId:fe,conversationId:le||null})}),K.length>0&&(n==null||n(),K.forEach(async({fileId:le,conversationId:fe})=>{try{if(fe)await k(fe,le);else{const z=tf();await Or.deleteFile(le,void 0,void 0,z??void 0),Sn(le)}}catch(z){if(no(z)){const Z=z.message??"";!Z.includes("404")&&!Z.includes("File not found")&&ge(`Failed to cleanup file ${le} during component unmount:`,z)}else ge(`Failed to cleanup file ${le} during component unmount`,z)}}))},300)},[n,k]);h.useEffect(()=>U,[U]);const T=h.useCallback(async $=>{if(!$||$.length===0)return;const re=Array.from($),X=ye.getState(),K=t||X.currentConversationId;if(!K){r==null||r(c("fileUpload.selectBeforeUpload"));return}const le=X.conversations.find(te=>te.id===K);if(!le){r==null||r(c("fileUpload.conversationNotFound"));return}const fe=le.attachedFiles||[],z=[],Z=re.filter(te=>fe.some(_e=>_e.filename===te.name&&_e.file_size===te.size)?(z.push(te.name),!1):!0);if(z.length>0&&(r==null||r(z.length===1?c("fileUpload.duplicateFileError",{filename:z[0]}):c("fileUpload.duplicateFilesError",{count:z.length}))),Z.length===0)return;if((A.current.get(K)||[]).length+Z.length>o){const te=c("fileUpload.maxFilesPerConversationError",{count:o});rt()&&!vt()&&st.getState().openLoginPrompt(c("fileUpload.maxFilesGuestLimitMessage",{count:o})),r==null||r(te);return}if(oe.maxTotalFiles!==null&&X.conversations.reduce((_e,Ce)=>{var Le;return _e+(((Le=Ce.attachedFiles)==null?void 0:Le.length)||0)},0)+Z.length>oe.maxTotalFiles){const _e=c("fileUpload.maxTotalFilesError",{count:oe.maxTotalFiles});rt()&&!vt()&&st.getState().openLoginPrompt(c("fileUpload.maxTotalFilesGuestLimitMessage",{count:oe.maxTotalFiles})),r==null||r(_e);return}if(!le.adapterName){r==null||r(c("fileUpload.adapterNotConfigured"));return}const we=le.adapterName,ce=lt(le.apiUrl);for(let te=0;te<Z.length;te++){const ee=Z[te],_e=new AbortController;y.current.set(ee.name,_e);const Ce=`${K}-${ee.name}-${Date.now()}-${te}`;let Le=null;const De=ee.type.startsWith("image/")?URL.createObjectURL(ee):null;try{const B=await Or.uploadFile(ee,q=>{if(b(K,me=>(me.set(Ce,q),me)),q.fileId&&!Le){Le=q.fileId,p.current.set(q.fileId,K),x.current.add(q.fileId),De&&Zi(q.fileId,De);const me={file_id:q.fileId,filename:ee.name,mime_type:ee.type||"application/octet-stream",file_size:ee.size,processing_status:q.status==="uploading"?"uploading":q.status==="processing"?"processing":q.status==="completed"?"completed":void 0};D(`[FileUpload] Adding file ${q.fileId} to conversation ${K} immediately (status: ${me.processing_status})`),N(K,me)}},void 0,ce,we).catch(q=>{if(q.message&&q.message.includes("was deleted")){Le&&p.current.delete(Le);const me=q.message.match(/File\s+([\w-]+)\s+was deleted/);return me&&me[1]&&p.current.delete(me[1]),D(`File ${ee.name} was deleted during upload`),null}throw q});B?(p.current.set(B.file_id,K),x.current.add(B.file_id),D(`[FileUpload] Updating file ${B.file_id} in conversation ${K} with final status`),N(K,B),B.processing_status==="completed"||B.processing_status==="failed"||B.processing_status==="error"?b(K,me=>(me.delete(Ce),me)):b(K,me=>{const pe=me.get(Ce);return pe&&me.set(Ce,{...pe,progress:90,status:"processing",fileId:B.file_id}),me}),F(K,me=>{if(new Set(me.map(Ye=>Ye.file_id)).has(B.file_id))return me;const be=[...me,B];return D(`[FileUpload] Updated uploadedFiles for ${K}: ${be.length} files`,be),be})):(ge(`Upload completed for ${ee.name} but uploadedAttachment is null`),b(K,q=>(q.delete(Ce),q)))}catch(B){const q=rf(B);if(B instanceof DOMException&&B.name==="AbortError"||_e.signal.aborted){D(`Upload cancelled for ${ee.name}`),Le?p.current.delete(Le):De&&URL.revokeObjectURL(De);continue}if(q.includes("was deleted")){D(`File ${ee.name} was deleted during upload`),Le&&p.current.delete(Le);const be=q.match(/File\s+([\w-]+)\s+was deleted/);be&&be[1]&&p.current.delete(be[1]);continue}v.current?(xe(`Failed to upload file ${ee.name}:`,B),xe(`File type: ${ee.type}, File name: ${ee.name}`),r==null||r(q||`Failed to upload ${ee.name}`)):ge(`Upload error for ${ee.name} (component unmounted):`,q),Le?p.current.delete(Le):De&&URL.revokeObjectURL(De);const me=Ce,pe=K;setTimeout(()=>{b(pe,be=>(be.delete(me),be))},5e3)}finally{y.current.delete(ee.name)}}},[N,t,o,r,c,F,b]),H=h.useCallback($=>{$.preventDefault(),$.stopPropagation(),l||u(!0)},[l]),j=h.useCallback($=>{$.preventDefault(),$.stopPropagation(),u(!1)},[]),L=h.useCallback($=>{if($.preventDefault(),$.stopPropagation(),u(!1),l)return;const re=$.dataTransfer.files;T(re)},[l,T]),O=h.useCallback($=>{const re=$.target.files;T(re),g.current&&(g.current.value="")},[T]),M=h.useCallback(()=>{!l&&g.current&&g.current.click()},[l]),Y=h.useCallback($=>{l||($.key==="Enter"||$.key===" ")&&($.preventDefault(),M())},[l,M]),G=E.length>0,V=h.useMemo(()=>{const $=new Map;return C.forEach(re=>{$.set(re.id,re.title||c("chatInterface.newChatTitle"))}),$},[C,c]),J=h.useMemo(()=>{const $=[];return Bt.forEach((re,X)=>{X!==t&&re.size>0&&$.push({conversationId:X,uploads:Array.from(re.entries()).map(([K,le])=>({key:K,progress:le}))})}),$},[t,f]),ue=($,re)=>{const X=$.status==="uploading"?c("fileUpload.uploadingStatus"):$.status==="processing"?c("fileUpload.processingStatus"):$.status==="completed"?c("fileUpload.completedStatus"):void 0;return i.jsx(js,{filename:$.filename,fileId:$.fileId,status:$.status,statusText:X,errorMessage:$.error||($.status==="error"?c("fileUpload.processingFailedMessage"):void 0)},re)},Ee=E.length>0?i.jsx("div",{className:"w-full max-w-full overflow-hidden flex flex-wrap gap-2",role:"status","aria-live":"polite",children:E.map(([$,re])=>ue(re,$))}):null;return i.jsxs("div",{className:"w-full max-w-full overflow-hidden space-y-2",children:[G&&Ee,!G&&i.jsxs("button",{type:"button",onClick:M,onKeyDown:Y,onDragOver:H,onDragLeave:j,onDrop:L,disabled:l,className:`
344
+ group relative w-full max-w-full rounded-lg border p-4 transition-all duration-200 text-left overflow-hidden
345
+ ${d?"border-blue-300 bg-blue-50 ring-2 ring-blue-400 ring-inset dark:border-blue-500/40 dark:bg-[#101010] dark:ring-blue-500":l?"border-gray-200 bg-gray-50 cursor-not-allowed opacity-50 dark:border-[#242424] dark:bg-[#101010]":"border-gray-200 bg-gray-50 hover:bg-gray-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 focus-visible:ring-inset dark:border-[#242424] dark:bg-[#101010] dark:hover:bg-[#1a1a1a]"}
346
+ `,"aria-label":c(l?"fileUpload.disabledAriaLabel":"fileUpload.enabledAriaLabel"),children:[i.jsx("input",{ref:g,type:"file",multiple:!0,onChange:O,className:"hidden",disabled:l,accept:".pdf,.doc,.docx,.txt,.md,.csv,.json,.html,.pptx,.xlsx,.py,.java,.sql,.js,.mjs,.ts,.tsx,.cpp,.cxx,.cc,.c,.h,.hpp,.go,.rs,.rb,.php,.sh,.bash,.zsh,.yaml,.yml,.xml,.css,.scss,.sass,.less,.png,.jpg,.jpeg,.tiff,.webp,.wav,.mp3,.mp4,.ogg,.flac,.webm,.m4a,.aac,.vtt"}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`flex h-10 w-10 shrink-0 items-center justify-center rounded-lg transition-colors duration-200 ${d?"bg-blue-100 dark:bg-blue-500/15":"bg-gray-200/70 dark:bg-[#1a1a1a] group-hover:bg-blue-100 dark:group-hover:bg-[#242424]"}`,children:i.jsx(yd,{className:`h-5 w-5 transition-colors duration-200 ${d?"text-blue-600 dark:text-blue-400":"text-gray-400 dark:text-[#8e8ea0] group-hover:text-blue-500 dark:group-hover:text-blue-400"}`})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:`text-sm font-medium transition-colors duration-200 ${d?"text-blue-700 dark:text-blue-300":"text-[#353740] dark:text-[#ececf1]"}`,children:c(l?"fileUpload.disabledAriaLabel":d?"fileUpload.draggingText":"fileUpload.dragDropText")}),i.jsx("p",{className:"text-xs text-gray-400 dark:text-[#8e8ea0] mt-0.5",children:c("fileUpload.fileTypesAndLimit",{count:o})})]})]})]}),J.length>0&&i.jsxs("div",{className:"w-full max-w-full space-y-2 rounded-lg border border-gray-200 bg-gray-50 p-2.5 dark:border-[#242424] dark:bg-[#101010]",children:[i.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-[#8e8ea0] px-1",children:c("fileUpload.otherConversationsLabel")}),J.map(({conversationId:$,uploads:re})=>i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("div",{className:"text-[11px] font-medium text-gray-400 dark:text-[#6b6f7a] px-1",children:V.get($)||"Conversation"}),i.jsx("div",{className:"flex flex-wrap gap-2",children:re.map(({key:X,progress:K})=>ue(K,X))})]},$))]})]})}const ei={"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/tiff":"tiff","image/tif":"tif","image/gif":"gif","image/webp":"webp","application/pdf":"pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/msword":"doc","text/plain":"txt","text/markdown":"md","application/json":"json"},rn=4,ds=3,nf=0,af=0,sn=2;function of(t){if(!t||typeof t!="object")return null;const e=t,r=["supportsAutocomplete","isAutocompleteSupported","autocompleteSupported"];for(const a of r)if(typeof e[a]=="boolean")return e[a];const n=["capabilities","features"],s=["autocomplete","supportsAutocomplete","autocomplete_supported"];for(const a of n){const o=e[a];if(!o||typeof o!="object")continue;const l=o;for(const c of s)if(typeof l[c]=="boolean")return l[c]}return null}function lf(t){if(!t)return"bin";if(ei[t])return ei[t];const e=t.split("/");return e.length===2&&e[1]?e[1]:"bin"}function cf(t){return t.replace(/[^a-zA-Z0-9._-]/g,"_").replace(/_+/g,"_")||"pasted-file"}function df(t){const e=t.lastIndexOf(".");return e===-1||e===t.length-1?null:t.slice(e+1).toLowerCase()}function uf(t){const e=t.lastIndexOf(".");return e===-1?t:t.slice(0,e)}function nn(t){return!t||t==="processing"||t==="uploading"}function ff(t,e){const r=Date.now(),n=t.name&&t.name.trim().length>0?t.name.trim():"pasted-file",s=cf(uf(n)),o=df(n)||lf(t.type),l=`${s}-${r}-${e}.${o}`;return new File([t],l,{type:t.type||"application/octet-stream"})}function ti({onSend:t,disabled:e=!1,placeholder:r=ji(),autoFocusEnabled:n=!0,suppressMobileAutoFocus:s=!1,desktopOnlyAutoFocus:a=!1,isCentered:o=!1,maxWidthClass:l="max-w-5xl",adapterNotes:c,skillState:d,availableModels:u=[],defaultModel:f=null,selectedModel:m=null,onSelectModel:g}){var na;const{t:p}=Ie(),[x,y]=h.useState(""),[v,A]=h.useState(!1),[I,C]=h.useState(!1),[S,E]=h.useState(!1),[_,b]=h.useState(!1),[F,k]=h.useState([]),[N,U]=h.useState({}),[T,H]=h.useState(new Map),[j,L]=h.useState(!1),[O,M]=h.useState(!1),[Y,G]=h.useState(null),[V,J]=h.useState(null),[ue,Ee]=h.useState(null),[$,re]=h.useState({isOpen:!1,fileId:"",filename:"",isDeleting:!1}),X=h.useRef(null),K=h.useRef(null),le=h.useRef(null),fe=h.useRef(null),z=h.useRef(null),Z=h.useRef(new Set),ae=h.useRef(""),we=h.useRef(!1),ce=h.useRef(0),te=h.useRef(null),{settings:ee,updateSettings:_e}=Ns(),{theme:Ce,isDark:Le}=tr(),De=Ce.mode==="dark"?"dark":Ce.mode==="light"?"light":"",B=Le?"dark":"light";Dr(K,{enabled:S,onEscape:()=>E(!1)});const q=h.useCallback((w,P)=>{w&&U(de=>{if(de[w]===P)return de;const Se={...de};return P?Se[w]=!0:delete Se[w],Se})},[]),[me,pe]=h.useState(0),[be,Ye]=h.useState(!1),[xt,qe]=h.useState(0),[kt,Rt]=h.useState(()=>({top:rn+ds,bottom:Math.max(rn-ds,0)})),[St,Pt]=h.useState(null),Kt=mr(),nt=rt()&&!Kt,Dt=st(w=>w.showLoginPrompt),{createConversation:Ut,currentConversationId:je,conversations:bt,isLoading:ie,syncConversationFiles:ve,stopStreaming:Te,removeFileFromConversation:Me}=ye(),ne=bt.find(w=>w.id===je),Be=ne?ne.messages.filter(w=>!(w.role==="assistant"&&w.isStreaming)).length:0,Fs=bt.reduce((w,P)=>w+P.messages.filter(de=>!(de.role==="assistant"&&de.isStreaming)).length,0),at=!!ne&&oe.maxMessagesPerConversation!==null&&Be>=oe.maxMessagesPerConversation,Gt=oe.maxTotalMessages!==null&&Fs>=oe.maxTotalMessages,Br=h.useCallback(()=>{pe(w=>w+1)},[]),rr=pc(),sr=gc(),{isListening:dt,isSupported:Hr,startListening:pr,stopListening:gr,error:Xt}=Gu(w=>{y(P=>{const de=P.length>0&&!/\s$/.test(P)?" ":"",Se=(P+de+w).slice(0,oe.maxMessageLength);return ae.current=Se,Se})},Br,{silenceTimeoutMs:rr,language:sr||void 0}),xr=fc(),it=hc(),nr=it&&Hr,jt=uc(),Vr=Ai(),$s=of(ne==null?void 0:ne.adapterInfo),{skills:Lt,isLoading:qr,selectedSkill:He,selectSkill:br,clearSkill:ar}=d,Rs=(ne==null?void 0:ne.adapterName)||null,{suggestions:ut,selectedIndex:yt,setSelectedIndex:Ps,selectNext:Ds,selectPrevious:Us,clearSuggestions:wt,focusInputAfterSelection:yr,suppressUntilQueryChange:wr}=Qu(x,{enabled:Vr&&!dt,apiUrl:ne==null?void 0:ne.apiUrl,adapterName:Rs,sessionId:ne==null?void 0:ne.sessionId,adapterSupportsAutocomplete:$s,skill:(He==null?void 0:He.name)||null,inputRef:X}),R=ut.length>0,ke=!dt,W=ke&&R&&!be,Ne=x.startsWith("/")?x.slice(1):"",et=Ne.toLowerCase().replace(/-/g," "),We=et?Lt.filter(w=>w.name.replace(/-/g," ").toLowerCase().includes(et)||w.description.toLowerCase().includes(et)):Lt,vr=We.length>0?Math.min(xt,We.length-1):0,Et=We[vr]??null,Os=(Et==null?void 0:Et.name.replace(/-/g," "))??"",go=be&&Et&&x.startsWith("/")&&Os.toLowerCase().startsWith(Ne.toLowerCase())&&Os.length>Ne.length?Os.slice(Ne.length):null,xo=yt>=0?yt:0,kr=R?ut[xo]:null,Hn=h.useMemo(()=>{if(!kr)return null;const w=kr.text||"";if(!x)return w;const P=x;return w.toLowerCase().startsWith(P.toLowerCase())&&w.length>P.length?w.slice(P.length):null},[kr,x]),zs=go??Hn,bo=x.trim().length===0&&!zs,yo=h.useCallback(w=>{if(!x)return i.jsx("span",{className:"line-clamp-1 text-current",children:w});if(!w.toLowerCase().startsWith(x.toLowerCase()))return i.jsx("span",{className:"line-clamp-1 text-current",children:w});const P=w.slice(0,x.length),de=w.slice(x.length);return i.jsxs("span",{className:"line-clamp-1",children:[i.jsx("span",{className:"text-gray-500 dark:text-[#8e8ea0]",children:P}),i.jsx("span",{className:"font-semibold text-[#353740] dark:text-[#ececf1]",children:de})]})},[x]),Vn=h.useCallback(w=>{var P;br(w),Ye(!1),y(""),wt(),qe(0),(P=X.current)==null||P.focus()},[wt,br]),wo=h.useCallback(()=>{var w;y("/"),Ye(!0),qe(0),(w=X.current)==null||w.focus()},[]),qn=h.useCallback(()=>{var w;Ye(!1),y(""),qe(0),(w=X.current)==null||w.focus()},[]),Ot=h.useCallback(()=>{const w=X.current;if(!w||typeof window>"u")return;const P=Ae=>{const Ve=Ae+ds,Pe=Math.max(Ae-ds,0);w.style.paddingTop=`${Ve}px`,w.style.paddingBottom=`${Pe}px`,Rt({top:Ve,bottom:Pe})},de=window.getComputedStyle(w),Se=parseFloat(de.lineHeight||"0");!Number.isNaN(Se)&&Se>0?Pt(Ae=>Ae===Se?Ae:Se):Pt(Ae=>Ae===null?Ae:null),P(rn)},[]),vo=()=>{const w=X.current;return w?w.selectionStart===w.selectionEnd&&w.selectionStart===x.length:!1},Wn=(ne==null?void 0:ne.attachedFiles)||[],ir=je?Wn:F,ko=bt.reduce((w,P)=>{var de;return w+(((de=P.attachedFiles)==null?void 0:de.length)||0)},0),Kn=oe.maxFilesPerConversation!==null&&oe.maxFilesPerConversation>0&&Wn.length>=oe.maxFilesPerConversation,Gn=oe.maxTotalFiles!==null&&ko>=oe.maxTotalFiles,Sr=((na=ne==null?void 0:ne.adapterInfo)==null?void 0:na.isFileSupported)??!1,Bs=ir.some(w=>w.processing_status?w.processing_status!=="completed"&&w.processing_status!=="error"&&w.processing_status!=="failed":!0),ft=je?!!N[je]:!1,Wr=Object.values(N).some(Boolean),Hs=x.trim().length>0,Vs=at||Gt,Oe=e||Bs||ft||Vs,Xn=jt&&Sr,Kr=Kn||Gn,jr=!Xn||e||ft||Vs||Kr,Yn=!_&&(ft||T.size>0),Qn=_||ft&&T.size===0;h.useLayoutEffect(()=>{if(X.current){const w=X.current,P=120;if(x.length===0){w.style.height="32px",w.style.overflowY="hidden",Ot();return}w.style.height="auto";const de=w.scrollHeight;w.style.height=`${Math.min(de,P)}px`,w.style.overflowY=de>P?"auto":"hidden",Ot()}},[x,Ot]),h.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const w=X.current;if(!w)return;const P=new ResizeObserver(()=>{Ot()});return P.observe(w),()=>{P.disconnect()}},[Ot]);const Zn=()=>{const w=document.activeElement;return w&&w.tagName==="TEXTAREA"},Gr=h.useCallback(()=>typeof window>"u"?!1:!!(a&&!window.matchMedia("(min-width: 1024px)").matches||s&&window.matchMedia("(max-width: 767px)").matches),[a,s]),Xr=h.useCallback(()=>{var w;(w=X.current)==null||w.focus({preventScroll:a})},[a]);h.useEffect(()=>{Gr()||n&&!Oe&&X.current&&!Zn()&&Xr()},[n,Oe,Gr,Xr]);const Jn=!!He||Lt.length>0&&x.length===0&&!Oe;h.useEffect(()=>{if(typeof window>"u"||!window.matchMedia("(max-width: 767px)").matches||!Jn||document.activeElement!==X.current)return;const w=window.requestAnimationFrame(()=>{const P=X.current;!P||document.activeElement!==P||(P.blur(),P.focus({preventScroll:!0}))});return()=>window.cancelAnimationFrame(w)},[Jn]);const qs=h.useRef(ie);h.useEffect(()=>{if(Gr()){qs.current=ie;return}n&&qs.current&&!ie&&!Oe&&X.current&&setTimeout(()=>{X.current&&!Zn()&&Xr()},100),qs.current=ie},[n,ie,Oe,Gr,Xr]),h.useEffect(()=>{if(!nr||(me>ce.current&&(we.current=!0,ce.current=me),!we.current||me===0))return;const w=ae.current.trim(),P=ye.getState();if(D("[MessageInput] Auto-send check after voice completion:",{hasMessage:!!w,isInputDisabled:Oe,isComposing:v,isLoading:P.isLoading}),we.current=!1,!w)return;if(Oe||v){D("[MessageInput] Auto-send skipped because input is currently disabled or composing");return}const de=P.conversations.find(Pe=>Pe.id===P.currentConversationId),Ae=((de==null?void 0:de.attachedFiles)||[]).map(Pe=>Pe.file_id),Ve=He==null?void 0:He.name;D("[MessageInput] Auto-sending voice message immediately:",w),t(w,Ae.length>0?Ae:void 0,void 0,Ve),Ve&&ar(),setTimeout(()=>{Ye(!1)},0),wt(),setTimeout(()=>{y("")},0),ae.current="",X.current&&(X.current.style.height="auto",X.current.style.overflowY="hidden",Ot())},[nr,me,Oe,v,t,He,ar,Ot,wt]),h.useEffect(()=>{ft&&_&&setTimeout(()=>{b(!1)},0)},[ft,_]);const Yr=h.useCallback((w,P)=>{setTimeout(()=>{let de=ye.getState(),Se=P||de.currentConversationId;if(Se||(Se=Ut(),de=ye.getState(),Se=de.currentConversationId||Se),!Se){xe("[MessageInput] Unable to sync files: conversation ID missing");return}const Ae=new Set(w.map(Pe=>Pe.file_id)),Ve=[];Z.current.forEach((Pe,Re)=>{const[,...Ge]=Re.split("-"),Qt=Ge.join("-");Ae.has(Qt)||Ve.push(Re)}),Ve.forEach(Pe=>Z.current.delete(Pe)),w.forEach(Pe=>{const Re=`${Se}-${Pe.file_id}`;Z.current.has(Re)||(Z.current.add(Re),D(`[MessageInput] Adding file ${Pe.file_id} to conversation ${Se}`),de.addFileToConversation(Se,Pe))})},0)},[Ut]);h.useEffect(()=>{if(je!==te.current)if(te.current=je||null,je&&ne){const w=ne.attachedFiles||[];setTimeout(()=>{k(w.map(P=>({...P})))},0)}else setTimeout(()=>{k([])},0)},[je,ne]),h.useEffect(()=>{if(je&&ne){const w=ne.attachedFiles||[];w.length>0?setTimeout(()=>{k(P=>{const de=new Set(P.map(Ae=>Ae.file_id)),Se=w.filter(Ae=>!de.has(Ae.file_id));return Se.length>0?(D(`[MessageInput] Syncing ${Se.length} missing files from conversation to UI`),[...P,...Se]):P})},0):w.length===0&&F.length>0&&setTimeout(()=>{k([])},0)}},[je,ne,bt,F.length]);const Ws=h.useRef(null),Ks=h.useRef(""),Qr=(ne==null?void 0:ne.attachedFiles)||[],Zr=Qr.length>0?`${Qr.length}:${Qr.map(w=>w.file_id).join("|")}`:"",ea=Qr.some(w=>nn(w.processing_status));h.useEffect(()=>{if(!je||!(ne!=null&&ne.adapterName))return;const w=Zr!=="";if(w&&(Ws.current!==je||Ks.current!==Zr)?(D(`[MessageInput] Syncing files for conversation ${je}...`),Ws.current=je,Ks.current=Zr,ve(je).catch(Se=>{xe("[MessageInput] Failed to sync conversation files:",Se)})):w||(Ws.current=je,Ks.current=""),!ea)return;D("[MessageInput] Files still processing, starting poll...");const de=setInterval(async()=>{const Ae=ye.getState().conversations.find(Re=>Re.id===je);if(!Ae){clearInterval(de);return}if((Ae.attachedFiles||[]).filter(Re=>nn(Re.processing_status)).length===0){D("[MessageInput] All files completed processing, stopping poll"),clearInterval(de);return}try{await ve(je)}catch(Re){xe("[MessageInput] Failed to poll file status:",Re)}},3e3);return()=>{clearInterval(de)}},[je,ne==null?void 0:ne.adapterName,Zr,ea,ve]),h.useEffect(()=>{setTimeout(()=>{U(w=>{const P=new Set(bt.map(Ae=>Ae.id));let de=!1;const Se={...w};return Object.keys(Se).forEach(Ae=>{P.has(Ae)||(delete Se[Ae],de=!0)}),de?Se:w})},0)},[bt]);const ta=w=>{if(w.preventDefault(),Hs&&!Oe&&!v){dt&&gr();const de=((ne==null?void 0:ne.attachedFiles)||[]).map(Ae=>Ae.file_id),Se=He==null?void 0:He.name;t(x.trim(),de.length>0?de:void 0,void 0,Se),Se&&ar(),Ye(!1),_r("messageSent",ee.soundEnabled),y(""),ae.current="",k([]),b(!1),X.current&&(X.current.style.height="auto",X.current.style.overflowY="hidden",Ot())}},Jr=h.useCallback(w=>{if(!w||w.length===0)return;const P=w.length===1?p("messageInput.uploadSuccess.single",{filename:w[0].filename}):p("messageInput.uploadSuccess.multiple",{count:w.length});_r("success",ee.soundEnabled),J(P),setTimeout(()=>{J(null)},6e3)},[ee.soundEnabled,p]),So=h.useCallback((w,P)=>{D(`[MessageInput] handleFilesSelected called with ${P.length} files for conversation ${w}:`,P),w&&(w===je&&k(P),Yr(P,w))},[je,Yr]),jo=h.useCallback((w,P)=>{w===je&&Jr(P)},[je,Jr]),Co=h.useCallback(w=>{re({isOpen:!0,fileId:w.file_id,filename:w.filename,isDeleting:!1})},[]),Ao=h.useCallback(()=>{re(w=>w.isDeleting?w:{isOpen:!1,fileId:"",filename:"",isDeleting:!1})},[]),No=h.useCallback(async()=>{if(!(!je||!$.fileId)){re(w=>({...w,isDeleting:!0}));try{await Me(je,$.fileId),k(w=>w.filter(P=>P.file_id!==$.fileId)),re({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}catch(w){const P=w instanceof Error?w.message:p("messageInput.fileRemoveFailed");xe("[MessageInput] Failed to remove file:",w),Ee(P),re({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}}},[je,$.fileId,Me,p]),ra=h.useCallback(w=>w.replace(/\s+/g," ").trim(),[]),es=h.useCallback(w=>{const P=ra(w);y(P),wt(),wr(P),yr(P)},[wt,yr,ra,wr]),Gs=h.useCallback(w=>{if(w<0)return;const P=ut[w]||ut[0];P&&es(P.text)},[ut,es]),Io=w=>{if(be){if(w.key==="ArrowDown"){w.preventDefault(),qe(P=>We.length===0?0:(P+1)%We.length);return}if(w.key==="ArrowUp"){w.preventDefault(),qe(P=>We.length===0?0:(P-1+We.length)%We.length);return}if(w.key==="Home"){w.preventDefault(),qe(0);return}if(w.key==="End"){w.preventDefault(),qe(Math.max(We.length-1,0));return}if((w.key==="Enter"&&!w.shiftKey||w.key==="Tab")&&Et){w.preventDefault(),Vn(Et);return}if(w.key==="Escape"){w.preventDefault(),qn();return}}if(R&&ke){if(w.key==="ArrowDown"){w.preventDefault(),Ds();return}if(w.key==="ArrowUp"){w.preventDefault(),Us();return}if(w.key==="Tab"){w.preventDefault();const P=yt>=0?yt:0;Gs(P);return}if(w.key==="ArrowRight"&&vo()){if(Hn&&kr){w.preventDefault(),es(kr.text);return}if(yt>=0){w.preventDefault(),Gs(yt);return}}if(w.key==="Enter"&&yt>=0){w.preventDefault(),Gs(yt);return}if(w.key==="Escape"){w.preventDefault(),wt();return}}w.key==="Enter"&&!w.shiftKey&&!v&&(w.preventDefault(),ta(w))},Lo=()=>{dt?gr():(wt(),pr())},Eo=()=>{const w=!ee.voiceEnabled;_e({voiceEnabled:w}),w&&qt.enableAudio()},_o=h.useCallback(async w=>{if(!jt||!I||!Sr||Oe)return;const P=w.clipboardData;if(!P||!P.items)return;const Se=Array.from(P.items).filter(Re=>Re.kind==="file");if(Se.length===0)return;const Ae=[];if(Se.forEach((Re,Ge)=>{const Qt=Re.getAsFile();Qt&&Ae.push(ff(Qt,Ge))}),Ae.length===0)return;w.preventDefault(),G(null),J(null),b(!1);let Ve=null;const Pe=new Set;try{const Re=ye.getState(),Ge=Re.conversations.find(ot=>ot.id===Re.currentConversationId);if(((Ge==null?void 0:Ge.attachedFiles)||[]).length+Ae.length>oe.maxFilesPerConversation)throw nt&&st.getState().openLoginPrompt(p("fileUpload.maxFilesGuestLimitMessage",{count:oe.maxFilesPerConversation})),new Error(p("fileUpload.maxFilesPerConversationError",{count:oe.maxFilesPerConversation}));if(oe.maxTotalFiles!==null&&Re.conversations.reduce((ht,Tt)=>{var Qe;return ht+(((Qe=Tt.attachedFiles)==null?void 0:Qe.length)||0)},0)+Ae.length>oe.maxTotalFiles)throw nt&&st.getState().openLoginPrompt(p("fileUpload.maxTotalFilesGuestLimitMessage",{count:oe.maxTotalFiles})),new Error(p("fileUpload.maxTotalFilesError",{count:oe.maxTotalFiles}));if(!Ge)throw new Error(p("messageInput.conversationNotFoundShort"));if(!Ge.adapterName)throw new Error(p("fileUpload.adapterNotConfigured"));const Fo=lt(Ge.apiUrl),$o=Ge.adapterName;Ve=Ge.id,q(Ve,!0);const Cr=[],aa=[];for(let ot=0;ot<Ae.length;ot++){const ht=Ae[ot],Tt=ht.name||`Clipboard file ${ot+1}`,Qe=`${Tt}-${Date.now()}-${ot}`,Ar=ht.type.startsWith("image/")?URL.createObjectURL(ht):null;Ar&&Pe.add(Ar);let ia=null;H(tt=>{const zt=new Map(tt);return zt.set(Qe,{filename:Tt,progress:0,status:"uploading"}),zt});const Ro=tt=>{tt.fileId&&!ia&&(ia=tt.fileId,Ar&&(Zi(tt.fileId,Ar),Pe.delete(Ar))),H(zt=>{const mt=new Map(zt),Nr=mt.get(Qe);return Nr&&mt.set(Qe,{...Nr,filename:Tt,progress:tt.progress,status:tt.status,fileId:tt.fileId}),mt})},Po=()=>new Promise(tt=>{H(zt=>{const mt=new Map(zt),Nr=mt.get(Qe);return Nr&&mt.set(Qe,{...Nr,progress:100,status:"completed"}),mt}),setTimeout(()=>{H(zt=>{const mt=new Map(zt);return mt.delete(Qe),mt}),tt()},2500)});D(`[MessageInput] Pasting file: ${ht.name}, type: ${ht.type||"unknown"}, size: ${ht.size}`);const Do=await Or.uploadFile(ht,tt=>{D(`[MessageInput] Paste upload progress for ${ht.name}: ${tt.progress}% - ${tt.status}`),Ro(tt)},void 0,Fo,$o);Cr.push(Do),aa.push(Po())}if(Cr.length>0){let ot=Cr;if(Ve&&Ve===je){const ht=new Set(F.map(Qe=>Qe.file_id)),Tt=Cr.filter(Qe=>!ht.has(Qe.file_id));Tt.length>0?(k(Qe=>[...Qe,...Tt]),ot=Tt):ot=[]}ot.length>0&&Yr(ot,Ve),await Promise.all(aa),Jr(Cr)}}catch(Re){const Ge=Re instanceof Error?Re.message:"Failed to paste file";xe("[MessageInput] Paste error:",Re),_r("error",ee.soundEnabled),G(Ge),Ge.toLowerCase().includes("maximum")&&Ee(Ge),setTimeout(()=>{G(null)},5e3),H(new Map),Pe.forEach(Qt=>URL.revokeObjectURL(Qt))}finally{q(Ve,!1)}},[F,je,I,Sr,nt,Oe,q,ee.soundEnabled,Jr,Yr,jt,p]),sa=ic(ne==null?void 0:ne.adapterName);let _t;Gt?_t=nt?p("messageInput.placeholder.guestLimitTotal",{count:oe.maxTotalMessages}):p("messageInput.placeholder.workspaceLimitTotal",{count:oe.maxTotalMessages}):at?_t=nt?p("messageInput.placeholder.guestLimitPerConversation",{count:oe.maxMessagesPerConversation}):p("messageInput.placeholder.conversationLimitReached",{count:oe.maxMessagesPerConversation}):Bs||ft?_t=p("messageInput.placeholder.filesUploading"):sa?_t=sa:Xn?_t=p("messageInput.placeholder.messageOrbit"):_t=r;const Yt=[];Gt&&oe.maxTotalMessages!==null&&(nt?Dt&&Yt.push(p("messageInput.limitWarning.guestTotalMessages",{count:oe.maxTotalMessages})):Yt.push(p("messageInput.limitWarning.workspaceTotalMessages",{count:oe.maxTotalMessages}))),at&&oe.maxMessagesPerConversation!==null&&(nt?Dt&&Yt.push(p("messageInput.limitWarning.guestPerConversation",{count:oe.maxMessagesPerConversation})):Yt.push(p("messageInput.limitWarning.conversationLimitReached",{count:oe.maxMessagesPerConversation}))),ue&&Yt.push(ue),h.useEffect(()=>{!it||!Xt||_r("error",ee.soundEnabled)},[it,ee.soundEnabled,Xt]),h.useEffect(()=>{if(!ue)return;const w=setTimeout(()=>Ee(null),5e3);return()=>clearTimeout(w)},[ue]),h.useEffect(()=>{if(!_)return;const w=P=>{P.key!=="Escape"||P.defaultPrevented||b(!1)};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[_]),h.useEffect(()=>{var w;(_||ft||T.size>0||Wr)&&((w=le.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[_,ft,T.size,Wr]),h.useEffect(()=>{var w;W&&((w=fe.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[W]),h.useEffect(()=>{var w;be&&((w=z.current)==null||w.scrollIntoView({behavior:"smooth",block:"end"}))},[be,We.length]);const To=l,Mo=o?"flex justify-center":"";return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:`bg-transparent px-2 py-1.5 md:bg-transparent md:px-0 md:pt-4 md:pb-2 md:dark:bg-transparent sm:px-4 ${Mo}`,children:i.jsxs("div",{className:`mx-auto w-full ${To}`,children:[Xt&&it&&i.jsxs("div",{role:"alert","aria-live":"assertive",className:"mb-2.5 w-full flex items-start gap-2.5 rounded-lg bg-red-50 dark:bg-red-950/40 px-3.5 py-2.5 animate-fadeIn",children:[i.jsx(bn,{className:"h-4 w-4 mt-0.5 flex-shrink-0 text-red-500 dark:text-red-400"}),i.jsx("span",{className:"text-sm text-red-700 dark:text-red-300",children:Xt})]}),Y&&i.jsxs("div",{role:"alert","aria-live":"assertive",className:"mb-2.5 w-full flex items-start gap-2.5 rounded-lg bg-red-50 dark:bg-red-950/40 px-3.5 py-2.5 animate-fadeIn",children:[i.jsx(bn,{className:"h-4 w-4 mt-0.5 flex-shrink-0 text-red-500 dark:text-red-400"}),i.jsx("span",{className:"text-sm text-red-700 dark:text-red-300",children:Y})]}),V&&i.jsxs("div",{role:"status","aria-live":"polite",className:"mb-2.5 w-full flex items-center gap-2.5 rounded-lg bg-gray-50 dark:bg-[#1f1f24] px-3.5 py-2.5 animate-fadeIn",children:[i.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-900/40",children:i.jsx(qc,{className:"h-3.5 w-3.5 text-emerald-600 dark:text-emerald-400"})}),i.jsx("span",{className:"text-sm text-[#353740] dark:text-[#ececf1]",children:V})]}),Yt.length>0&&i.jsxs("div",{role:"status","aria-live":"polite",className:"mb-2.5 w-full flex items-start gap-2.5 rounded-lg bg-amber-50 dark:bg-amber-950/30 px-3.5 py-2.5 animate-fadeIn",children:[i.jsx(Rn,{className:"h-4 w-4 mt-0.5 flex-shrink-0 text-amber-500 dark:text-amber-400"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("ul",{className:"list-none space-y-0.5",children:Yt.map((w,P)=>i.jsx("li",{className:"text-sm text-amber-800 dark:text-amber-200",children:w},`${w}-${P}`))}),nt&&(Vs||Kr)&&Dt&&i.jsx("button",{type:"button",onClick:()=>st.getState().openLoginPrompt(p("messageInput.signInPrompt.message")),className:"mt-2 inline-flex items-center gap-1.5 rounded-md bg-[#353740] px-3 py-1.5 text-xs font-medium text-white hover:bg-[#40414f] dark:bg-white dark:text-[#353740] dark:hover:bg-gray-200 transition-colors",children:p("messageInput.signInPrompt.button")})]})]}),i.jsxs("div",{className:"relative w-full",children:[i.jsxs("form",{onSubmit:ta,className:"flex w-full flex-col gap-2 md:gap-3",children:[i.jsxs("div",{className:`grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1.5 md:flex md:flex-row md:flex-nowrap md:gap-2 rounded-xl md:rounded-lg border px-2.5 py-1.5 md:px-4 md:py-3 shadow-sm transition-all ${I?"border-gray-400 shadow-md dark:border-[#3a3a3a] dark:shadow-lg":"border-gray-300 dark:border-[#242424]"} bg-gray-50 dark:bg-[#111111]`,children:[He&&i.jsx("div",{className:"col-span-2 flex w-full shrink-0 basis-full md:contents",children:i.jsxs("div",{className:"flex h-8 max-w-[45%] shrink-0 items-center gap-1.5 rounded-full border border-gray-300 bg-white px-2.5 text-xs text-gray-700 shadow-sm dark:border-[#3a3a3a] dark:bg-[#1a1a1a] dark:text-gray-200 sm:max-w-[38%] md:self-center md:max-w-[32%]",children:[i.jsx($n,{className:"h-3.5 w-3.5 shrink-0 text-gray-500 dark:text-gray-400","aria-hidden":"true"}),i.jsx("span",{className:"min-w-0 truncate font-medium capitalize",children:He.name.replace(/-/g," ")}),i.jsx("button",{type:"button",onClick:()=>{var w;ar(),(w=X.current)==null||w.focus()},className:"-mr-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 dark:text-gray-400 dark:hover:bg-white/10 dark:hover:text-gray-100 dark:focus-visible:ring-gray-600","aria-label":p("messageInput.selectedSkill.removeAriaLabel"),children:i.jsx(Je,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]})}),!He&&Lt.length>0&&x.length===0&&!Oe&&i.jsx("div",{className:"col-span-2 flex w-full shrink-0 basis-full md:contents",children:i.jsxs("button",{type:"button",onClick:wo,className:"flex h-8 shrink-0 items-center gap-1.5 rounded-full border border-gray-300 bg-white px-2.5 text-xs font-medium text-gray-600 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 dark:border-[#3a3a3a] dark:bg-[#1a1a1a] dark:text-gray-300 dark:hover:bg-white/10 dark:hover:text-gray-100 dark:focus-visible:ring-gray-600 md:self-center","aria-label":p("messageInput.skillsHint.ariaLabel"),title:p("messageInput.skillsHint.title"),children:[i.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded bg-gray-200 font-mono text-[10px] leading-none text-gray-600 dark:bg-[#2a2a2a] dark:text-gray-300","aria-hidden":"true",children:"/"}),p("messageInput.skillsHint.text")]})}),i.jsxs("div",{className:"relative flex-1 w-full min-w-0 md:translate-y-0.5",children:[bo&&_t&&i.jsx("div",{className:"pointer-events-none absolute inset-0 truncate whitespace-nowrap text-base md:text-sm text-gray-500 dark:text-[#8e8ea0]",style:{paddingTop:Math.max(kt.top-nf,0),paddingBottom:kt.bottom,paddingLeft:`${sn}px`,paddingRight:0,lineHeight:St?`${St}px`:void 0},"aria-hidden":"true",children:_t}),zs&&I&&i.jsxs("div",{className:"pointer-events-none absolute inset-0 whitespace-pre-wrap text-base md:text-sm text-gray-400 dark:text-[#8e8ea0]",style:{paddingTop:Math.max(kt.top-af,0),paddingBottom:kt.bottom,paddingLeft:`${sn}px`,paddingRight:0,lineHeight:St?`${St}px`:void 0},"aria-hidden":"true",children:[i.jsx("span",{className:"invisible",children:x}),i.jsx("span",{children:zs})]}),i.jsx("textarea",{ref:X,"aria-label":p("messageInput.textarea.ariaLabel"),value:x,onChange:w=>{const P=w.target.value;y(P),P.startsWith("/")&&qe(0),Ye(P.startsWith("/")&&Lt.length>0)},onKeyDown:Io,onPaste:_o,onCompositionStart:()=>A(!0),onCompositionEnd:()=>A(!1),onFocus:()=>C(!0),onBlur:()=>C(!1),placeholder:_t,disabled:Oe,rows:1,maxLength:oe.maxMessageLength,className:"relative z-10 flex-1 w-full min-w-0 resize-none bg-transparent py-0 text-base md:text-sm text-[#353740] placeholder-transparent focus:outline-none dark:text-[#ececf1] dark:placeholder-transparent",style:{minHeight:"24px",maxHeight:"120px",paddingTop:`${kt.top}px`,paddingBottom:`${kt.bottom}px`,paddingLeft:`${sn}px`,paddingRight:0,border:"none",outline:"none",boxShadow:"none",WebkitAppearance:"none",MozAppearance:"none",appearance:"none",caretColor:x.trim()||I?"inherit":"transparent"}})]}),i.jsxs("div",{className:"flex items-center justify-end gap-1 md:gap-2 flex-shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[o&&!jt&&i.jsx("div",{className:"hidden md:block h-8 w-8 shrink-0","aria-hidden":"true"}),jt&&i.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),jr||b(!_)},disabled:jr,onMouseEnter:()=>L(!0),onMouseLeave:()=>L(!1),className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${_||ir.length>0?"bg-gray-200 text-[#353740] dark:bg-[#565869] dark:text-[#ececf1]":jr?"cursor-not-allowed text-gray-300 dark:text-[#6b6f7a]":"text-gray-500 hover:bg-gray-200 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#565869]"}`,title:Sr?Kr&&Kn&&oe.maxFilesPerConversation!==null?p("messageInput.fileUpload.titleLimitPerConversation",{count:oe.maxFilesPerConversation}):Kr&&Gn&&oe.maxTotalFiles!==null?p("messageInput.fileUpload.titleLimitWorkspace",{count:oe.maxTotalFiles}):Oe?p("messageInput.fileUpload.titleUploading"):ir.length>0?p("messageInput.fileUpload.titleAttached",{count:ir.length}):p("messageInput.fileUpload.attachAriaLabel"):p("messageInput.fileUpload.titleNotSupported"),"aria-label":p("messageInput.fileUpload.attachAriaLabel"),children:jr&&j?i.jsx(Je,{className:"h-4 w-4"}):i.jsx(dd,{className:"h-4 w-4"})}),x.length>0&&i.jsx("div",{className:"hidden md:block px-2 text-xs text-gray-500 dark:text-[#bfc2cd] md:min-w-[72px] md:text-right",children:i.jsxs("span",{className:x.length>=oe.maxMessageLength?"text-red-600 font-semibold":"",children:[x.length,"/",oe.maxMessageLength]})})]}),i.jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[i.jsx(so,{availableModels:u,defaultModel:f,selectedModel:m,onSelect:w=>g==null?void 0:g(w)}),(xr||it)&&i.jsxs(i.Fragment,{children:[xr&&i.jsx("button",{type:"button",onClick:Eo,className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${ee.voiceEnabled?"bg-blue-100 text-blue-600 dark:bg-blue-900/40 dark:text-blue-300":"text-gray-500 hover:bg-gray-200 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#565869]"}`,title:ee.voiceEnabled?p("messageInput.voiceOutput.titleEnabled"):p("messageInput.voiceOutput.titleDisabled"),"aria-label":ee.voiceEnabled?p("messageInput.voiceOutput.ariaLabelEnabled"):p("messageInput.voiceOutput.ariaLabelDisabled"),children:ee.voiceEnabled?i.jsx(Pn,{className:"h-5 w-5"}):i.jsx(wd,{className:"h-5 w-5"})}),nr&&i.jsx("button",{type:"button",onClick:Lo,disabled:Oe,onMouseEnter:()=>M(!0),onMouseLeave:()=>M(!1),className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${dt?"!flex bg-red-100 text-red-600 dark:bg-red-900/40 dark:text-red-300":Oe?"cursor-not-allowed text-gray-300 dark:text-[#6b6f7a]":"text-gray-500 hover:bg-gray-200 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#565869]"}`,title:p(Oe?"messageInput.voiceInput.titleUploading":dt?"messageInput.voiceInput.titleListening":"messageInput.voiceInput.titleDisabled"),"aria-label":p(dt?"messageInput.voiceInput.ariaLabelListening":"messageInput.voiceInput.ariaLabelDisabled"),children:dt||Oe&&O?i.jsx(sd,{className:"h-5 w-5"}):i.jsx(nd,{className:"h-5 w-5"})})]}),c&&i.jsx("button",{type:"button",onClick:()=>E(!0),className:"hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 text-gray-500 hover:bg-gray-200 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#565869]",title:p("messageInput.agentInfo.title"),"aria-label":p("messageInput.agentInfo.ariaLabel"),children:i.jsx(Na,{className:"h-5 w-5"})}),(Bs||ft)&&i.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center",children:i.jsx(Pi,{className:"h-4 w-4 animate-spin text-gray-500 dark:text-[#bfc2cd]"})}),ie?i.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),Te()},className:"flex h-9 w-9 md:h-8 md:w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 bg-red-500 text-white hover:bg-red-600 dark:bg-red-600 dark:hover:bg-red-700",title:p("messageInput.stop.title"),"aria-label":p("messageInput.stop.ariaLabel"),children:i.jsx(gd,{className:"h-4 w-4 md:h-3 md:w-3 fill-current"})}):i.jsx("button",{type:"submit",disabled:!Hs||Oe||v,className:`flex h-9 w-9 md:h-8 md:w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${Hs&&!Oe&&!v?"bg-black text-white hover:bg-gray-800 dark:bg-white dark:text-black dark:hover:bg-gray-200":"bg-gray-300 text-gray-500 dark:bg-[#565869] dark:text-[#6b6f7a]"}`,title:p("messageInput.submit.title"),"aria-label":p("messageInput.submit.ariaLabel"),children:i.jsx(xn,{className:"h-4 w-4"})})]})]})]}),ir.length>0&&i.jsx("div",{className:"flex flex-wrap gap-2",children:ir.map(w=>{const P=nn(w.processing_status),de=w.processing_status==="failed"||w.processing_status==="error",Se=de?"error":P?w.processing_status==="uploading"?"uploading":"processing":"completed",Ae=P?w.processing_status==="uploading"?p("messageInput.attachedFile.uploadingStatus"):p("messageInput.attachedFile.processingStatus"):void 0;return i.jsx(js,{filename:w.filename,fileId:w.file_id,status:Se,statusText:Ae,errorMessage:de?w.error_message||p("messageInput.fileProcessingFailedTitle"):void 0,onRemove:()=>{de?(je&&Me(je,w.file_id),k(Ve=>Ve.filter(Pe=>Pe.file_id!==w.file_id))):Co(w)},removeTitle:p(de?"messageInput.attachedFile.removeTitleFailed":"messageInput.attachedFile.removeTitleNormal")},w.file_id)})}),jt&&(Sr||Wr)&&i.jsxs("div",{ref:le,className:`${Yn?"":"rounded-lg border border-gray-200/80 bg-white p-2.5 dark:border-[#3c3f4a] dark:bg-[#2a2b32]"} transition-all duration-200 ${!_&&!ft&&T.size===0&&!Wr?"hidden":""}`,children:[_&&i.jsxs("div",{className:"mb-2 flex items-center justify-between px-1",children:[i.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-[#8e8ea0] uppercase tracking-wider",children:p("messageInput.uploadPanel.headingAttach")}),i.jsx("button",{type:"button",onClick:()=>b(!1),className:"flex h-6 w-6 items-center justify-center rounded-md text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:text-[#6b6f7a] dark:hover:bg-[#3c3f4a] dark:hover:text-[#bfc2cd] transition-colors",title:p("messageInput.uploadPanel.closeTitle"),children:i.jsx(Je,{className:"h-3.5 w-3.5"})})]}),!Yn&&ft&&!_&&T.size===0&&i.jsx("div",{className:"mb-2 px-1",children:i.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-[#8e8ea0] uppercase tracking-wider",children:p("messageInput.uploadPanel.headingUploading")})}),T.size>0&&i.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:Array.from(T.entries()).map(([w,P])=>i.jsx(js,{filename:P.filename,fileId:P.fileId,status:P.status,statusText:P.status==="uploading"?p("messageInput.uploadProgress.statusUploading"):P.status==="processing"?p("messageInput.uploadProgress.statusProcessing"):P.status==="completed"?p("messageInput.uploadProgress.statusCompleted"):void 0,errorMessage:P.error},w))}),i.jsx("div",{className:`${Qn?"block max-h-[40vh] overflow-y-auto":"hidden"}`,"aria-hidden":!Qn,children:i.jsx(sf,{conversationId:je,onFilesSelected:So,onUploadError:w=>{xe("File upload error:",w),Ee(w)},onUploadingChange:q,onUploadSuccess:jo,maxFiles:oe.maxFilesPerConversation,disabled:jr})})]}),i.jsx("div",{className:"h-3 md:h-1",children:nr&&dt&&i.jsxs("span",{className:"flex items-center gap-2 text-sm md:text-xs text-gray-500 dark:text-[#bfc2cd]",children:[i.jsx("span",{className:"h-2.5 w-2.5 md:h-2 md:w-2 animate-pulse rounded-full bg-red-500"}),p("messageInput.listeningIndicator")]})})]}),be&&i.jsx("div",{ref:z,className:"w-full pt-1",children:i.jsx(ro,{skills:Lt,isLoading:qr,selectedSkill:He,activeSkillName:Et==null?void 0:Et.name,query:Ne,onActiveSkillChange:w=>{const P=We.findIndex(de=>de.name===w.name);P>=0&&qe(P)},onSelect:Vn,onClose:qn})}),W&&i.jsx("div",{ref:fe,role:"listbox","aria-label":p("messageInput.autocompletePanel.ariaLabel"),className:"w-full pt-1",children:ut.map((w,P)=>{const de=P===yt;return i.jsx("button",{type:"button",role:"option","aria-selected":de,className:`flex w-full items-center gap-3 px-3 py-3 md:py-2.5 text-left text-[15px] md:text-sm transition-colors ${de?"bg-gray-100 dark:bg-[#2d2f39]":"hover:bg-gray-50 dark:hover:bg-[#2d2f39]/60"}`,onClick:()=>es(w.text),onMouseEnter:()=>Ps(P),children:yo(w.text)},P)})}),i.jsx(ws,{isOpen:$.isOpen,onClose:Ao,onConfirm:No,title:p("messageInput.fileDelete.title"),message:p("messageInput.fileDelete.message",{filename:$.filename}),confirmText:p("messageInput.fileDelete.confirmText"),cancelText:p("common.cancel"),type:"danger",isLoading:$.isDeleting})]})]})}),S&&c&&typeof document<"u"&&As.createPortal(i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center overflow-y-auto bg-black/60 p-4 backdrop-blur-sm animate-fadeIn",children:i.jsxs("div",{ref:K,role:"dialog","aria-modal":"true","aria-labelledby":"agent-info-title",tabIndex:-1,className:"w-full max-w-2xl max-h-[calc(100vh-2rem)] overflow-y-auto rounded-2xl bg-white shadow-2xl transform animate-fadeIn dark:bg-[#1a1b1e]",children:[i.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-[#2d2f39]",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/20 flex items-center justify-center",children:i.jsx(Na,{className:"w-5 h-5 text-blue-500"})}),i.jsx("h2",{id:"agent-info-title",className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:p("messageInput.agentInfoModal.title")})]}),i.jsx("button",{type:"button",onClick:()=>E(!1),className:"p-2 hover:bg-gray-100 dark:hover:bg-[#25262f] rounded-lg transition-colors","aria-label":p("messageInput.agentInfoModal.closeAriaLabel"),children:i.jsx(Je,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),i.jsx("div",{className:"p-6",children:i.jsx($t,{content:c,className:`message-markdown w-full min-w-0 prose prose-slate dark:prose-invert max-w-none text-sm leading-relaxed text-[#434654] dark:text-[#d7dae3] [&>:first-child]:mt-0 [&>:last-child]:mb-0 ${De}`,syntaxTheme:B})}),i.jsx("div",{className:"flex items-center justify-end p-6 border-t border-gray-200 dark:border-[#2d2f39] bg-gray-50 dark:bg-[#111113] rounded-b-2xl",children:i.jsx("button",{type:"button",onClick:()=>E(!1),className:"px-4 py-3 md:py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors font-medium shadow-sm hover:shadow-md",children:p("messageInput.agentInfoModal.confirmButton")})})]})}),document.body)]})}function ri({adapter:t,onSelect:e}){var l;const{t:r}=Ie(),n=(l=t.description)==null?void 0:l.trim(),{isDark:s}=tr(),a=s?"dark":"light",o=()=>e(t);return i.jsxs("div",{tabIndex:0,role:"button","data-agent-card":"true",onClick:o,onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),o())},className:"group relative flex w-full cursor-pointer flex-col rounded-2xl border border-slate-200 bg-white px-4 py-3.5 text-left shadow-sm transition-colors duration-150 hover:border-slate-300 hover:bg-slate-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/30 dark:border-[#242424] dark:bg-[#080808] dark:hover:border-[#333333] dark:hover:bg-[#111111] dark:focus-visible:ring-sky-400/30 md:px-5 md:py-4",children:[i.jsx("div",{className:"relative",children:i.jsx("div",{className:"min-w-0",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"truncate text-[15px] font-semibold text-blue-700 dark:text-blue-300 md:text-base",children:t.name}),n?i.jsx("div",{className:"mt-1 text-sm leading-5 text-slate-600 dark:text-slate-300",children:i.jsx($t,{content:n,className:"prose prose-slate max-w-none text-inherit dark:prose-invert [&>*]:mb-0 [&>*]:mt-0 [&_p]:overflow-hidden [&_p]:text-ellipsis [&_p]:[display:-webkit-box] [&_p]:[-webkit-box-orient:vertical] [&_p]:[-webkit-line-clamp:4]",syntaxTheme:a})}):i.jsx("p",{className:"mt-1 text-sm leading-5 text-slate-500 dark:text-slate-400",children:r("agentCard.configureMessage")})]}),i.jsx("button",{type:"button",onClick:c=>{c.stopPropagation(),o()},className:"hidden h-8 w-8 flex-shrink-0 items-center justify-center self-start rounded-full text-slate-700 transition-all duration-150 hover:bg-slate-100 group-hover:translate-x-0.5 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/30 dark:text-slate-200 dark:hover:bg-white/10 dark:focus-visible:ring-sky-400/30 md:inline-flex","aria-label":r("agentCard.startConversationAriaLabel",{name:t.name}),children:i.jsx(Aa,{className:"h-4 w-4","aria-hidden":"true"})})]})})}),i.jsx("div",{className:"mt-3 flex items-center justify-end gap-3 border-t border-slate-200 pt-2.5 text-xs text-slate-500 dark:border-white/10 dark:text-slate-400 md:hidden",children:i.jsx("button",{type:"button",onClick:c=>{c.stopPropagation(),o()},className:"inline-flex h-8 w-8 items-center justify-center rounded-full text-slate-700 transition-all duration-150 hover:bg-slate-100 group-hover:translate-x-0.5 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/30 dark:text-slate-200 dark:hover:bg-white/10 dark:focus-visible:ring-sky-400/30","aria-label":r("agentCard.startConversationAriaLabel",{name:t.name}),children:i.jsx(Aa,{className:"h-4 w-4","aria-hidden":"true"})})})]})}const Zt=t=>{if(typeof t!="string")return;const e=t.trim();return e.length>0?e:void 0},hf=t=>{if(!t||typeof t!="object")return null;const e=t,r=Zt(e.name);if(!r)return null;const n=Zt(e.id);if(!n)return console.warn(`[middlewareConfig] Adapter "${r}" is missing a required 'id' field — skipping.`),null;const s=Zt(e.apiUrl),a=Zt(e.model),o=Zt(e.inputPlaceholder),l=typeof e.notes=="string"?e.notes.trim():void 0;let c=Zt(e.description)||Zt(e.summary);if(!c&&typeof l=="string"){const u=l.split(/\r?\n/).find(f=>f.trim().length>0);c=u?u.trim():void 0}const d={id:n,name:r};return s&&(d.apiUrl=s),c&&(d.description=c),l&&(d.notes=l),a&&(d.model=a),o&&(d.inputPlaceholder=o),d},ao=t=>Array.isArray(t)?t.map(hf).filter(e=>e!==null):[];let Ht=null,an=0;const mf=3e4;function pf(){if(typeof window<"u"){const t=window.ORBIT_CHAT_CONFIG;if(t!=null&&t.adapters&&Array.isArray(t.adapters)){D("Loading adapters from window.ORBIT_CHAT_CONFIG");const e=ao(t.adapters);if(e.length===0)return null;const r=`{
347
+ "simple-chat": "default-key",
348
+ "dialoga": "orbit_GOQzNNaC9uB0uNh5LrOCdlmPI0OHXnMz",
349
+ "web-search": "orbit_XfxmYoTZgnp7zoMTKsIBfMBuYwj6U21P",
350
+ "chat-with-files": "multimodal",
351
+ "hr-db-chatbot": "human-resources",
352
+ "intent-sql-sqlite-classified": "classified",
353
+ "ecomm-analytics": "analytical",
354
+ "intent-duckdb-ev-population": "electric-vehicle",
355
+ "intent-http-jsonplaceholder": "rest-json-api",
356
+ "intent-http-paris-opendata": "paris-opendata",
357
+ "intent-mongodb-mflix": "mongodb-mflix",
358
+ "intent-graphql-spacex": "graphql-spacex",
359
+ "intent-sql-postgres": "postgres-customer-orders",
360
+ "open-ai-real-time-voice-chat": "open-ai-real-time-voice-chat",
361
+ "composite-multi-source-explorer": "composite-multi-source-explorer",
362
+ "math-teacher-quadratic": "math-teacher-trig-identities",
363
+ "qa-sql": "orbit_g6QuN5sPUh3fI2v0njoOJroXbAh1ILGP",
364
+ "qa-vector-chroma": "orbit_Rxm90sh85f8l5bzOLJpqpMUP9HcoNAX3",
365
+ "image-generator": "orbit_bZQ0h6kvpTphfCr9QgrCP13dkVclAsKQ",
366
+ "video-generator": "orbit_9P1vnx1GNMvVNyNCKF71VvVvcYx9duuo",
367
+ "intent-elasticsearch-log": "orbit_Ghpo8Q9mRdvVIODdw97ht7lBPpYBAzb6",
368
+ "audio-transcription": "orbit_RTBIwFoB6DA2mBuuHfnKf0xabwE6XKs2",
369
+ "voice-chat": "orbit_WjrkTqVjHE7mBa2ri8sAjENEVnLT9wbO",
370
+ "real-time-voice-chat": "orbit_xkvziKTXpZ1ufHWKg76pUDPbMDBRSRqC",
371
+ "tender-notices": "tender-notices",
372
+ "award-notices": "award-notices",
373
+ "contract-history": "contract-history",
374
+ "standing-offers": "standing-offers"
375
+ }`;if(!r.trim())return[];try{const n=JSON.parse(r),s=new Set(Object.entries(n).filter(([,a])=>{if(typeof a=="string")return a.trim().length>0;if(a&&typeof a=="object"){const o=a;if(typeof o.apiKey=="string"&&o.apiKey.trim().length>0||typeof o.key=="string"&&o.key.trim().length>0)return!0}return!1}).map(([a])=>a));return e.filter(a=>s.has(a.id))}catch{return[]}}}return null}async function On(){if(Ht&&Date.now()-an<mf)return Ht;try{const e=await fetch("/api/adapters?refresh=1",{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(e.ok){const r=await e.json(),n=ao(r.adapters);if(n.length>0)return Ht=n,an=Date.now(),D("Fetched adapters from /api/adapters:",Ht),Ht;D("/api/adapters response did not contain valid adapters, trying fallback")}D(`/api/adapters returned ${e.status}, trying fallback`)}catch(e){D("Could not fetch from /api/adapters, trying fallback:",e)}const t=pf();if(t&&t.length>0)return Ht=t,an=Date.now(),D("Loaded adapters from config:",Ht),Ht;throw xe("No adapters available from API or config"),new Error("No adapters available. Define adapters in orbitchat.yaml and provide matching ids in VITE_ADAPTER_KEYS.")}const gf="h-[96px]";function xf({onAdapterSelect:t,className:e="",title:r="",subtitle:n="",eyebrow:s=""}){const{t:a}=Ie(),[o,l]=h.useState([]),[c,d]=h.useState(!0),[u,f]=h.useState(null),m=h.useRef(null),g=h.useRef(null),[p,x]=h.useState(""),[y,v]=h.useState(!1),A=h.useCallback(()=>{const j=m.current;if(!j){v(!1);return}v(j.scrollHeight-j.scrollTop-j.clientHeight>20)},[]),I=()=>typeof window<"u"&&window.matchMedia("(min-width: 768px)").matches,C=()=>{var j;return Array.from(((j=m.current)==null?void 0:j.querySelectorAll('[data-agent-card="true"]'))??[])},S=j=>{const O=C()[j]??null;O&&(O.focus(),O.scrollIntoView({block:"nearest"}))},E=()=>{S(0)},_=()=>{const j=C();j.length!==0&&S(j.length-1)},b=j=>{if(!c&&!u&&N.length>0&&I()){if(j.key==="Tab"&&!j.shiftKey){j.preventDefault(),E();return}if(j.key==="ArrowDown"){j.preventDefault(),E();return}j.key==="ArrowUp"&&(j.preventDefault(),_())}},F=j=>{var Y;if(!U||!I()||j.key!=="ArrowDown"&&j.key!=="ArrowUp")return;const L=document.activeElement;if(!(L instanceof HTMLElement)||L.dataset.agentCard!=="true")return;const O=C(),M=O.indexOf(L);if(M!==-1){if(j.preventDefault(),j.key==="ArrowDown"){S((M+1)%O.length);return}if(M===0){(Y=g.current)==null||Y.focus();return}S(M-1)}},k=p.trim().toLowerCase(),N=k?o.filter(j=>{var Y,G;const L=j.name.toLowerCase().includes(k),O=((Y=j.description)==null?void 0:Y.toLowerCase().includes(k))??!1,M=((G=j.model)==null?void 0:G.toLowerCase().includes(k))??!1;return L||O||M}):o,U=p.trim().length>0,T=U||N.length===1;h.useEffect(()=>{const j=m.current;if(j)return A(),j.addEventListener("scroll",A,{passive:!0}),()=>j.removeEventListener("scroll",A)},[A,N]),h.useEffect(()=>{let j=!0;return(async()=>{try{d(!0),f(null);const M=(await On()).slice().sort((Y,G)=>Y.name.localeCompare(G.name,void 0,{sensitivity:"base"}));j&&l(M)}catch(O){xe("[AgentSelectionList] Failed to load adapters",O),j&&f(a("agentSelectionList.unableToLoad"))}finally{j&&d(!1)}})(),()=>{j=!1}},[a]),h.useEffect(()=>{var j;c||u||o.length===0||(j=g.current)==null||j.focus()},[c,u,o.length]);const H=()=>c?i.jsx("div",{className:"grid gap-4",children:Array.from({length:3}).map((j,L)=>i.jsx("div",{className:`${gf} animate-pulse rounded-2xl border border-gray-200 bg-transparent dark:border-[#3b3c49]`},L))}):u?i.jsx("div",{className:"rounded-2xl border border-red-200 bg-transparent px-4 py-6 text-sm text-red-700 dark:border-red-900 dark:text-red-200",children:u}):o.length===0?i.jsx("div",{className:"rounded-2xl border border-gray-200 bg-transparent px-4 py-6 text-sm text-gray-600 dark:border-[#3b3c49] dark:text-gray-300",children:a("agentSelectionList.noAgentsAvailable")}):N.length===0?i.jsx("div",{className:"rounded-2xl border border-gray-200 bg-transparent px-4 py-6 text-sm text-gray-600 dark:border-[#3b3c49] dark:text-gray-300",children:a("agentSelectionList.noSearchResults")}):i.jsxs("div",{className:"relative flex flex-col h-full min-h-0",children:[i.jsx("div",{ref:m,onKeyDown:F,className:"agent-selection-scroll flex-1 min-h-0 overflow-y-auto pr-1 pb-2",children:T?i.jsx("div",{className:"mx-auto flex w-full max-w-xl flex-col gap-3 lg:max-w-2xl",children:N.map(j=>i.jsx(ri,{adapter:j,onSelect:L=>t(L.id)},j.id))}):i.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:N.map(j=>i.jsx(ri,{adapter:j,onSelect:L=>t(L.id)},j.id))})}),y&&i.jsx("div",{className:"pointer-events-none absolute bottom-0 left-0 right-0 h-12 md:hidden bg-gradient-to-t from-white dark:from-[#212121] to-transparent","aria-hidden":"true"})]});return i.jsxs("div",{className:`flex w-full flex-col gap-4 md:gap-6 ${e}`,children:[(s||r||n)&&i.jsxs("div",{className:"flex-shrink-0",children:[s&&i.jsx("p",{className:"text-sm font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-300",children:s}),r&&i.jsx("h2",{className:"mt-2 text-2xl font-bold text-gray-900 dark:text-white",children:r}),n&&i.jsx("p",{className:"mt-2 text-base text-gray-600 dark:text-gray-300",children:n})]}),i.jsx("div",{className:"flex w-full flex-shrink-0 justify-center",children:i.jsx("div",{className:"w-full max-w-xl lg:max-w-2xl",children:i.jsxs("div",{className:"relative overflow-hidden rounded-[1.75rem] border border-slate-300/90 bg-[linear-gradient(180deg,rgba(255,255,255,0.96),rgba(248,250,252,0.94))] shadow-[0_10px_28px_rgba(15,23,42,0.05)] dark:border-white/20 dark:bg-[linear-gradient(180deg,rgba(37,39,49,0.95),rgba(29,31,39,0.92))] dark:shadow-[0_12px_30px_rgba(0,0,0,0.2)]",children:[i.jsx("div",{className:"pointer-events-none absolute inset-0 rounded-[inherit] bg-[linear-gradient(180deg,rgba(255,255,255,0.45),rgba(255,255,255,0))] dark:bg-[linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))]"}),i.jsx(Fn,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400 dark:text-slate-500"}),i.jsx("input",{ref:g,type:"text",placeholder:a("agentSelectionList.searchPlaceholder"),value:p,maxLength:100,disabled:c||!!u||o.length===0,onChange:j=>x(j.target.value),onKeyDown:b,className:"relative z-10 w-full bg-transparent py-3 pl-11 pr-11 text-sm font-medium text-slate-700 placeholder:font-normal placeholder:text-slate-400 focus:outline-none focus:ring-0 focus-visible:ring-0 disabled:cursor-not-allowed disabled:opacity-60 dark:text-slate-100 dark:placeholder:text-slate-400"}),p&&i.jsx("button",{type:"button",onClick:()=>x(""),className:"absolute right-3 top-1/2 z-10 inline-flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-full border border-slate-200/80 bg-white/90 text-slate-400 transition-colors hover:border-slate-300 hover:text-slate-600 focus:outline-none focus:ring-2 focus:ring-sky-200 dark:border-white/10 dark:bg-white/5 dark:text-slate-500 dark:hover:border-white/20 dark:hover:text-slate-200 dark:focus:ring-sky-500/20","aria-label":a("agentSelectionList.clearSearchAriaLabel"),children:i.jsx(Je,{className:"h-3.5 w-3.5"})})]})})}),i.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:H()})]})}function Cn(){return Tn()?Es()==="entra"?i.jsx(yf,{}):i.jsx(bf,{}):null}function bf(){const{user:t,logout:e,loginWithRedirect:r}=In();if(!mr()||!t)return i.jsx(io,{onClick:()=>r()});const s=t.name||t.email||"User";return i.jsx(oo,{displayName:s,onClick:()=>e({logoutParams:{returnTo:window.location.origin}})})}function yf(){const{instance:t,accounts:e}=Nn();if(!mr()||e.length===0)return i.jsx(io,{onClick:()=>t.loginRedirect({scopes:Mn()}).catch(()=>{})});const n=e[0],s=n.name||n.username||"User";return i.jsx(oo,{displayName:s,onClick:()=>t.logoutRedirect({postLogoutRedirectUri:window.location.origin}).catch(()=>{})})}function io({onClick:t}){const{t:e}=Ie();return i.jsxs("button",{onClick:t,className:"inline-flex items-center justify-center gap-1.5 rounded-lg border border-blue-400/70 bg-blue-600 px-3 py-2 text-xs font-semibold text-white shadow-sm active:scale-[0.97] transition-all duration-150 hover:bg-blue-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:border-blue-500 dark:bg-blue-500 dark:hover:bg-blue-600",children:[i.jsx(Di,{className:"h-4 w-4"}),i.jsx("span",{children:e("common.signIn")})]})}function oo({displayName:t,onClick:e}){const{t:r}=Ie();return i.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-sm text-gray-600 dark:text-[#bfc2cd]",children:[i.jsx("span",{className:"hidden max-w-[170px] truncate font-medium md:block",title:t,children:t}),i.jsxs("button",{onClick:e,className:"inline-flex min-h-10 items-center justify-center gap-1.5 rounded-lg border border-slate-200 px-3 py-2 text-xs font-semibold text-slate-600 shadow-sm transition-colors hover:border-red-200 hover:bg-red-50 hover:text-red-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-400 dark:border-[#454755] dark:text-[#c4c8d4] dark:hover:border-red-900/40 dark:hover:bg-red-900/20 dark:hover:text-red-300 md:rounded-full md:text-sm md:font-medium",title:r("authStatus.signOutButton.title"),"aria-label":r("authStatus.signOutButton.ariaLabel"),children:[i.jsx(ed,{className:"h-4 w-4"}),i.jsx("span",{className:"hidden md:inline",children:r("common.logOut")})]})]})}function lo({placement:t="default",compact:e=!1}){const{t:r}=Ie();if(!Ei())return null;const n=Ec(),s=_c(),a=Tc(),o=Mc(),l=Fc(),c=$c(),d=Pc(),u=o?"border-t border-slate-200/80 dark:border-[#333645]":"",f=e?t==="sidebar"?"pt-4 pb-2":"pt-2 pb-2":c==="normal"?"pt-3 pb-3":"pt-5 pb-3",m=l==="inline"?"flex w-full flex-col gap-1 items-center justify-center text-center sm:flex-row sm:items-center sm:justify-center":"flex w-full flex-col items-center justify-center gap-1 text-center",g="justify-center",p=t==="sidebar"?"w-full px-2":"w-full px-3 sm:px-6",x=t==="sidebar"?"w-full":"mx-auto w-full max-w-7xl",y=e?"inline-flex min-h-8 items-center rounded px-1.5 text-xs font-medium transition-colors hover:bg-slate-100 hover:text-blue-700 hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:hover:bg-[#2b2d39] dark:hover:text-blue-300":"inline-flex min-h-10 items-center rounded-md px-2.5 text-sm font-medium transition-colors hover:bg-slate-100 hover:text-blue-700 hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:hover:bg-[#2b2d39] dark:hover:text-blue-300 sm:text-base";return i.jsx("footer",{className:`shrink-0 bg-white dark:bg-black text-sm ${f} ${u}`.trim(),style:{backgroundColor:s||void 0,color:a||void 0},children:i.jsx("div",{className:p,children:i.jsx("div",{className:x,children:i.jsxs("div",{className:m,children:[n&&i.jsx("p",{className:`${e?"text-xs leading-snug":"text-sm"} text-slate-700 dark:text-slate-200 ${t==="sidebar"?"pt-0.5":""}`.trim(),children:n}),d.length>0&&i.jsx("nav",{"aria-label":r("appFooter.navLinksAriaLabel"),children:i.jsx("ul",{className:`flex flex-wrap items-center ${g} ${e?"gap-1":"gap-1.5 sm:gap-2"}`,children:d.map((v,A)=>{const I=l==="inline"&&A>0;return i.jsxs("li",{className:"flex items-center",children:[I&&i.jsx("span",{className:"mr-1.5 text-slate-400 dark:text-slate-500","aria-hidden":"true",children:"·"}),i.jsx("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",className:y,style:{color:a||void 0},children:v.label})]},v.url)})})})]})})})})}const wf=60*1e3;let on=null,si=0;const ln=t=>{if(!t||t==="/")return"/";const e=t.trim();if(!e)return"/";const r=e.startsWith("/")?e:`/${e}`;return r==="/"?"/":r.endsWith("/")?r.slice(0,-1):r},co=()=>{if(typeof window>"u")return ln("/");const t=ln("/");if(typeof document>"u")return t;const e=document.querySelector("base[href]");if(!e)return t;try{const r=new URL(e.getAttribute("href")||"/",window.location.origin);return ln(r.pathname||t)}catch{return t}},Cs=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),vf=async()=>{const t=Date.now();if(on&&t-si<wf)return on;let e=[];try{e=await On()}catch(n){ge("[agentRouting] Unable to load adapters for slug resolution",n)}const r=new Map;return e.forEach(n=>{const s=Cs(n.name);s&&r.set(s,n.id);const a=Cs(n.id);a&&a!==s&&r.set(a,n.id)}),on=r,si=t,r},An=t=>{var a;const e=co(),r=t.startsWith("/")?t:`/${t}`;let n=r;if(e!=="/"){if(!r.startsWith(e))return null;n=r.slice(e.length)}const s=n.split("/").filter(Boolean);return s.length===0?null:((a=s[0])==null?void 0:a.toLowerCase())||null},uo=t=>{const e=co();if(!t)return e;const r=t.replace(/^\/+|\/+$/g,"");return e==="/"?r?`/${r}`:"/":`${e}/${r}`.replace(/\/{2,}/g,"/")},At=t=>{if(typeof window>"u")return;const e=uo(t),r=window.location.pathname;if(e===r)return;const n=window.location.search||"",s=window.location.hash||"";window.history.replaceState(window.history.state,"",`${e}${n}${s}`)},kf=()=>uo(null),Sf=async t=>{const e=t.trim().toLowerCase();return e&&(await vf()).get(e)||null};function jf({currentConversation:t,showEmptyState:e,createConversation:r,configureApiSettings:n,clearError:s,clearCurrentConversationAdapter:a}){var fe;const{t:o}=Ie(),l=o("agent.error.singleAdapterMissing"),[c,d]=h.useState(!1),[u,f]=h.useState(null),m=Ls(),g=Ln(),p=typeof window<"u"?An(window.location.pathname):null,[x,y]=h.useState(p),[v,A]=h.useState(()=>!m&&e&&!p),I=h.useRef(null),C=h.useRef(new Map),S=h.useRef(0),E=3e4,_=!!t,b=(t==null?void 0:t.messages.length)??0,F=((fe=t==null?void 0:t.attachedFiles)==null?void 0:fe.length)??0,k=h.useMemo(()=>_&&(b>0||F>0),[F,b,_]),N=h.useCallback(()=>{Ke(()=>ye.getState())},[]),U=h.useCallback((z,Z)=>{if(!z)return;const ae=Z||o("agent.error.configurationFailed");let we=!1;ye.setState(ce=>{const te=ce.conversations.find(ee=>ee.id===z);return!te||te.messages.length>0?ce:(we=!0,{conversations:ce.conversations.map(ee=>ee.id===z?{...ee,adapterLoadError:ae}:ee)})}),we&&N()},[N,o]),T=h.useCallback(z=>{if(!z)return;let Z=!1;ye.setState(ae=>{const we=ae.conversations.find(ce=>ce.id===z);return!we||!we.adapterLoadError?ae:(Z=!0,{conversations:ae.conversations.map(ce=>ce.id===z?{...ce,adapterLoadError:null}:ce)})}),Z&&N()},[N]),H=h.useCallback(z=>z instanceof Xi?z.status===401?o("agent.error.authenticationFailed"):z.status===404?o("agent.error.notFound"):z.message:z instanceof Error?z.message:o("agent.error.loadFailed"),[o]),j=h.useCallback(()=>{const z=ye.getState(),Z=z.currentConversationId?z.conversations.find(ae=>ae.id===z.currentConversationId):null;if(!Z||Z.messages.length>0)try{return r()}catch(ae){ge("Cannot create a new conversation for agent selection:",ae instanceof Error?ae.message:"Unknown error")}return(Z==null?void 0:Z.id)||null},[r]),L=h.useCallback(async z=>{if(!(z!=null&&z.adapterName))return{ok:!1};try{const Z=await Fe(),ae=new Z.ApiClient({apiUrl:z.apiUrl||$e(),sessionId:null,adapterName:z.adapterName});if(typeof ae.getAdapterInfo!="function")return{ok:!1};const we=await ae.getAdapterInfo();return ye.setState(ce=>({conversations:ce.conversations.map(te=>te.id===z.id?{...te,adapterInfo:we,adapterLoadError:null,updatedAt:new Date}:te)})),ye.getState().currentConversationId===z.id&&f(null),N(),{ok:!0}}catch(Z){const ae=H(Z),we=ye.getState();we.currentConversationId===z.id&&f({conversationId:z.id,message:ae});const ce=we.conversations.find(te=>te.id===z.id);return ce&&ce.messages.length===0&&U(z.id,ae),{ok:!1,error:Z}}},[H,U,N]),O=h.useCallback(async z=>{if(!z)return;const Z=ye.getState(),ae=Z.currentConversationId?Z.conversations.find(we=>we.id===Z.currentConversationId):null;if(ae){d(!0),f(null),T(ae.id);try{const we=ae.apiUrl||$e();await n(we,void 0,z),s();const ce=ye.getState(),te=ce.conversations.find(ee=>ee.id===ce.currentConversationId);if((te==null?void 0:te.adapterName)===z&&(!te.adapterInfo||te.adapterInfo.notes===void 0)){const ee=await L(te);!ee.ok&&ee.error&&xe("Failed to load adapter info after selecting adapter:",ee.error)}}catch(we){xe("Failed to configure adapter from empty state:",we);const ce=H(we);f({conversationId:ae.id,message:ce}),U(ae.id,ce)}finally{d(!1)}}},[T,s,n,L,H,U]),M=h.useCallback(z=>{m||(j(),A(!1),At(Cs(z)),O(z))},[j,O,m]),Y=h.useCallback(()=>{m||(a(),At(null),A(!0))},[a,m]),G=h.useCallback(()=>{var we,ce;if(m){const te=ye.getState(),ee=te.currentConversationId?te.conversations.find(Ce=>Ce.id===te.currentConversationId):null;if(!!ee&&(ee.messages.length>0||(((we=ee.attachedFiles)==null?void 0:we.length)||0)>0))try{r()}catch(Ce){ge("Cannot go home (new conversation):",Ce instanceof Error?Ce.message:"Unknown error")}At(null),A(!1);return}y(null);const z=ye.getState(),Z=z.currentConversationId?z.conversations.find(te=>te.id===z.currentConversationId):null;if(!!Z&&(Z.messages.length>0||(((ce=Z.attachedFiles)==null?void 0:ce.length)||0)>0))try{r()}catch(te){ge("Cannot go home (new conversation):",te instanceof Error?te.message:"Unknown error");return}else Z!=null&&Z.adapterName&&a();At(null),A(!0)},[a,r,m]),J=!m&&e&&!x&&!(t!=null&&t.adapterName)&&!k||!m&&e&&v&&!(t!=null&&t.adapterName)&&!k;h.useEffect(()=>{if(m){At(null);return}if(!x){if(J||!(t!=null&&t.adapterName)){At(null);return}At(Cs(t.adapterName))}},[t==null?void 0:t.adapterName,m,x,J]);const ue=h.useCallback(async()=>{if(typeof window>"u")return;const z=++S.current;if(m){At(null),y(null);return}const Z=An(window.location.pathname);if(!Z)return;const ae=await Sf(Z);if(z===S.current){if(!ae){j(),At(null),a(),A(!0),y(null);return}j(),A(!1),At(Z),await O(ae),y(null)}},[a,j,O,m]),Ee=h.useRef(ue);h.useEffect(()=>{Ee.current=ue},[ue]),h.useEffect(()=>{const z=window.setTimeout(()=>{Ee.current()},0),Z=()=>{Ee.current()};return window.addEventListener("popstate",Z),()=>{window.clearTimeout(z),S.current+=1,window.removeEventListener("popstate",Z)}},[]);const $=t==null?void 0:t.id,re=t==null?void 0:t.adapterName,X=t==null?void 0:t.apiUrl,K=!!(t!=null&&t.adapterInfo);h.useEffect(()=>{if(!m||!g||!e||!$||k||c)return;const z=(re==null?void 0:re.trim())||g,Z=(re==null?void 0:re.trim())!==z||!K;if(!z||!Z)return;let ae=!1;return(async()=>{d(!0),f(null),T($);try{const ce=X||$e();await n(ce,void 0,z),s()}catch(ce){if(!ae){const te=H(ce);f({conversationId:$,message:te}),U($,te)}}finally{ae||d(!1)}})(),()=>{ae=!0}},[T,s,n,k,H,c,m,U,e,re,X,K,$,g]),h.useEffect(()=>{(async()=>{const Z=t==null?void 0:t.adapterName,ae=t?`${t.id}:${Z}`:null;if(!(!ae||I.current===ae))if(Z){I.current=ae,D("[ChatInterface] Refreshing adapter info from the backend - adapterName:",Z);const we=await L(t);if(we.ok)D("[ChatInterface] Adapter info loaded successfully");else{const ce=we.error;xe("[ChatInterface] Failed to load adapter info:",ce);const te=ce instanceof Error?ce.message:String(ce);if((te.includes("429")||te.includes("Too Many Requests"))&&Z){const _e=C.current.get(ae);_e&&clearTimeout(_e);const Ce=setTimeout(()=>{I.current===ae&&(I.current=null),C.current.delete(ae)},E);C.current.set(ae,Ce),ge(`[ChatInterface] Adapter info request rate-limited; retrying in ${E/1e3}s`)}else I.current=null}}else D("[ChatInterface] Skipping adapter info refresh: no adapter selected")})()},[L,t]),h.useEffect(()=>{const z=C.current;return()=>{z.forEach(Z=>clearTimeout(Z)),z.clear()}},[]);const le=m&&!g?l:(t==null?void 0:t.adapterLoadError)??(u&&u.conversationId===(t==null?void 0:t.id)?u.message:null);return{adapterNotesError:le,handleAgentCardSelection:M,handleChangeAgent:Y,goToAgentSelectionHome:G,hasAdapterConfigurationError:!!le,isAgentSelectionVisible:v,isConfiguringAdapter:c,isSingleAdapterMode:m,setIsAgentSelectionVisible:A,shouldShowAgentSelectionList:J}}const fo=h.createContext(null),Cf={registerGoHome:()=>{},goHome:()=>{}};function ho(){return h.useContext(fo)??Cf}function Af({adapter:t,syntaxTheme:e,forcedThemeClass:r=""}){var s;const n=(s=t.notes)==null?void 0:s.trim();return n?i.jsxs("section",{"aria-labelledby":"agent-seo-content-title",className:"mx-auto w-full max-w-[56rem] px-1 text-left sm:px-0",children:[i.jsx("h2",{id:"agent-seo-content-title",className:"sr-only",children:t.name}),i.jsx("div",{children:i.jsx($t,{content:n,className:`message-markdown prose prose-slate dark:prose-invert max-w-none text-sm leading-relaxed text-[#434654] dark:text-[#d7dae3] [&>:first-child]:mt-0 [&>:last-child]:mb-0 ${r}`,syntaxTheme:e})})]}):null}const Nf='meta[name="description"]',If='meta[property="og:title"]',Lf='meta[property="og:description"]',Ef='meta[property="og:type"]',_f='link[rel="canonical"]';function ni(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Tf(t){return t.replace(/```[\s\S]*?```/g," ").replace(/`([^`]+)`/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/^>\s?/gm,"").replace(/[*_~]/g,"").replace(/\s+/g," ").trim()}function Mf(t,e){const r=t==null?void 0:t.trim();if(r)return r;if(!e)return _n();const n=Tf(e);return n.length>160?`${n.slice(0,157).trimEnd()}...`:n}function Ff(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $f(t){const e=t.trim();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Rf(t){const e=t.trim();if(!e)return null;const r=`^${Ff(e).replace(/\\\*/g,".*")}$`;try{return new RegExp(r,"i")}catch{return null}}function Pf(t){return[Ci(),...oc()].map($f).filter(r=>!!r).includes(t)?!0:lc().some(r=>{const n=Rf(r);return n?n.test(t):!1})}function Df(t){var n,s,a;const e=t==null?void 0:t.trim();if(!e)return null;const r=Q.adapters.find(o=>{var l;return((l=o==null?void 0:o.id)==null?void 0:l.trim())===e});return r?{id:r.id,name:((n=r.name)==null?void 0:n.trim())||r.id,description:((s=r.description)==null?void 0:s.trim())||void 0,notes:((a=r.notes)==null?void 0:a.trim())||void 0}:null}function Uf(t){var n,s,a;if(typeof window>"u")return null;const e=An(window.location.pathname);if(!e)return null;const r=Q.adapters.find(o=>{const l=ni(o.name||""),c=ni(o.id||"");return e===l||e===c});return r?{id:r.id,name:((n=r.name)==null?void 0:n.trim())||r.id,description:((s=r.description)==null?void 0:s.trim())||void 0,notes:((a=r.notes)==null?void 0:a.trim())||void 0}:null}function us(t,e,r){if(typeof document>"u")return null;const n=document.querySelector(t);if(n)return n;const s=document.createElement("meta");return s.setAttribute(e,r),document.head.appendChild(s),s}function Of(){if(typeof document>"u")return null;const t=document.querySelector(_f);if(t)return t;const e=document.createElement("link");return e.rel="canonical",document.head.appendChild(e),e}function mo(t){if(typeof document>"u")return;const e=En(),r=t?`${t.name} | ${e}`:e,n=t?Mf(t.description,t.notes):_n();document.title=r;const s=us(Nf,"name","description");s&&(s.content=n);const a=us(If,"property","og:title");a&&(a.content=r);const o=us(Lf,"property","og:description");o&&(o.content=n);const l=us(Ef,"property","og:type");l&&(l.content="website");const c=Of();if(c&&typeof window<"u"){const d=Ci(),u=window.location.origin,f=d?new URL(d.endsWith("/")?d:`${d}/`).origin:"",g=`${u&&Pf(u)?u:f||u}${window.location.pathname}`;c.href=g}}function zf(){return cc()}class zn{static async getAdapterModels(e,r){const n=await Fe(),s=new n.ApiClient({apiUrl:"",adapterName:r});if(!s.getAdapterModels)throw new Error("getAdapterModels is not available on this API client");return s.getAdapterModels(e)}static async getAllModels(e){const r=await Fe(),n=new r.ApiClient({apiUrl:"",adapterName:e});if(!n.getAllModels)throw new Error("getAllModels is not available on this API client");return n.getAllModels()}static async listAdapterModels(e,r){return(await zn.getAdapterModels(e,r)).models}}const Bf="rounded-t-[32px] border border-white/40 bg-transparent px-4 pb-4 pt-[max(env(safe-area-inset-top),1rem)] shadow-none backdrop-blur-0 dark:border-[#2f303d] dark:bg-transparent md:rounded-none md:border-0 md:bg-transparent md:px-0 md:pb-0 md:pt-3 md:shadow-none md:backdrop-blur-0 md:dark:bg-transparent md:dark:border-0",Hf="shrink-0 sticky bottom-[calc(var(--app-footer-height,0px)+0.25rem)] z-10 -mx-4 mt-auto overflow-visible bg-transparent pb-[max(env(safe-area-inset-bottom),0.5rem)] shadow-none backdrop-blur-0 transition-all duration-200 dark:bg-transparent md:bottom-[calc(var(--app-footer-height,0px)+0.5rem)] md:z-10 md:mx-0 md:mt-0 md:overflow-visible md:rounded-none md:border-0 md:bg-transparent md:pb-0 md:shadow-none md:backdrop-blur-0 md:dark:bg-transparent md:dark:border-0 [&>div]:bg-transparent md:[&>div]:rounded-none md:[&>div]:px-0",Vf="relative z-20 shrink-0 -mx-4 px-4 pt-2 pb-2 bg-transparent border-b border-transparent dark:border-transparent dark:bg-transparent md:static md:mx-0 md:px-0 md:pt-6 md:pb-6 md:bg-transparent md:border-gray-200 md:dark:border-[#4a4b54] md:dark:bg-transparent";function qf({onOpenSettings:t,onOpenSidebar:e}){var Pt,Kt,nt,Dt,Ut,je,bt;const{t:r}=Ie(),{conversations:n,currentConversationId:s,createConversation:a,canCreateNewConversation:o,sendMessage:l,regenerateResponse:c,editMessageAndRegenerate:d,isLoading:u,configureApiSettings:f,error:m,clearError:g,createThread:p,clearCurrentConversationAdapter:x}=ye(),{settings:y}=Ns(),v=mr(),A=rt()&&!v,{theme:I,isDark:C}=tr(),S=I.mode==="dark"?"dark":I.mode==="light"?"light":"",E=C?"dark":"light",_=["application-description agent-home-markdown prose prose-slate dark:prose-invert max-w-none text-sm md:text-base leading-relaxed","text-[#4a4c5a] dark:text-[#bfc2cd]","[&>:first-child]:mt-0 [&>:last-child]:mb-0",S].filter(Boolean).join(" "),b=n.find(ie=>ie.id===s),F=n.some(ie=>{var ve;return(ie.messages.length>0||(((ve=ie.attachedFiles)==null?void 0:ve.length)||0)>0)&&!ie.adapterLoadError}),k=!b||b.messages.length===0,N=((Pt=b==null?void 0:b.adapterInfo)==null?void 0:Pt.supportsThreading)===!0,U=!!(b!=null&&b.adapterName&&(b!=null&&b.adapterInfo))&&!N,T=Yi({adapterName:b==null?void 0:b.adapterName,enabled:U,selectionScopeKey:s,supportsThreading:N}),H=ji(),j=En(),L=_n().trim(),O=L.length>0,{registerGoHome:M}=ho(),[Y,G]=h.useState([]),[V,J]=h.useState(null);h.useEffect(()=>{const ie=b==null?void 0:b.adapterName;let ve=!1;async function Te(){if(J(null),!ie){G([]);return}try{const Me=await zn.listAdapterModels(ie,ie);if(ve)return;G(Me),J(Me.length>0?Me[0].name:null)}catch{ve||(G([]),J(null))}}return Te(),()=>{ve=!0}},[b==null?void 0:b.adapterName]);const{adapterNotesError:ue,handleAgentCardSelection:Ee,handleChangeAgent:$,goToAgentSelectionHome:re,hasAdapterConfigurationError:X,isAgentSelectionVisible:K,isConfiguringAdapter:le,isSingleAdapterMode:fe,shouldShowAgentSelectionList:z}=jf({currentConversation:b,showEmptyState:k,createConversation:a,configureApiSettings:f,clearError:g,clearCurrentConversationAdapter:x});h.useLayoutEffect(()=>(M(()=>re()),()=>M(null)),[M,re]);const Z="max-w-[96rem]",ae="max-w-[64rem]",we="max-w-[56rem]",ce=`mx-auto w-full ${Z}`,te=o(),ee=!!(b!=null&&b.adapterName)&&((b==null?void 0:b.messages.length)||0)===0,_e=r(te?"chatInterface.newConversation.tooltipCanStart":A?"chatInterface.newConversation.tooltipGuestLimited":"chatInterface.newConversation.tooltipCannotStart"),Ce=!!(b&&!z),Le=z?"border-transparent dark:border-transparent md:border-transparent md:dark:border-transparent":"",De=!gn()&&z?"pt-0 pb-0 md:pt-0 md:pb-1":"",q=`${Vf} ${Le} ${De}`.trim(),me=Ei(),pe=n.some(ie=>{var ve;return(ie.messages.length>0||(((ve=ie.attachedFiles)==null?void 0:ve.length)??0)>0)&&!ie.adapterLoadError}),be=me&&!pe,Ye=z?"pt-0 md:pt-0":"pt-4 md:pt-6",xt=h.useMemo(()=>{var Me,ne,Be;if(z)return null;const ie=Df(b==null?void 0:b.adapterName)||Uf();if(!ie&&!(b!=null&&b.adapterName))return null;const ve=(Me=b==null?void 0:b.adapterName)==null?void 0:Me.trim(),Te=(Be=(ne=b==null?void 0:b.adapterInfo)==null?void 0:ne.notes)==null?void 0:Be.trim();return ie?{...ie,notes:Te||ie.notes}:ve?{id:ve,name:ve,notes:Te||void 0}:null},[(Kt=b==null?void 0:b.adapterInfo)==null?void 0:Kt.notes,b==null?void 0:b.adapterName,z]);h.useEffect(()=>{mo(xt)},[xt]),h.useEffect(()=>{let ie=null;const ve=()=>{ie&&(ie(),ie=null)};if(y.voiceEnabled){if(qt.isAudioEnabled())return D("[ChatInterface] Audio streaming already enabled"),ve;const Te=()=>{ve();const Me=async()=>{ve(),await qt.enableAudio()?D("[ChatInterface] Audio streaming enabled after user gesture"):(ge("[ChatInterface] User gesture did not enable audio streaming"),Te())};document.addEventListener("pointerdown",Me,{once:!0}),document.addEventListener("keydown",Me,{once:!0}),ie=()=>{document.removeEventListener("pointerdown",Me),document.removeEventListener("keydown",Me)},D("[ChatInterface] Waiting for user gesture to enable audio streaming")};return Te(),ve}return ve(),qt.disableAudio(),D("[ChatInterface] Audio streaming disabled via settings"),ve},[y.voiceEnabled]);const qe=(ie,ve,Te,Me)=>{var ne;l(ie,ve,Te,V??((ne=b==null?void 0:b.adapterInfo)==null?void 0:ne.model)??void 0,Me)},kt=async(ie,ve,Te,Me,ne)=>{var Be;await l(Te,void 0,ie,ne??V??((Be=b==null?void 0:b.adapterInfo)==null?void 0:Be.model)??void 0,Me)},Rt=()=>{try{a()}catch(ie){ge("Cannot create new conversation:",ie instanceof Error?ie.message:"Unknown error")}},St=h.useCallback(async(ie,ve)=>{if(b)try{await ye.getState().deleteThread(b.id,ie,ve)}catch(Te){xe("Failed to clear thread:",Te)}},[b]);return i.jsx("main",{className:"flex-1 flex flex-col bg-transparent overflow-hidden","aria-label":r("chatInterface.workspace.ariaLabel"),children:i.jsx("div",{className:"flex h-full w-full flex-col overflow-hidden px-3 sm:px-5 lg:px-8",children:i.jsxs("div",{className:`mx-auto flex h-full w-full ${Z} flex-col overflow-hidden md:pb-4 ${Bf}`,children:[m&&i.jsx("div",{role:"alert",className:"mt-6 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700 dark:border-red-600/40 dark:bg-red-900/30 dark:text-red-200",children:i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsx("p",{children:m}),i.jsx("button",{onClick:g,className:"ml-4 rounded p-1 text-red-500 hover:bg-red-100 hover:text-red-700 dark:text-red-200 dark:hover:bg-red-800/40","aria-label":r("chatInterface.error.dismissAriaLabel"),children:"×"})]})}),i.jsxs("div",{className:q,children:[e&&i.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2 md:hidden",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("button",{onClick:e,disabled:!F,className:`inline-flex items-center justify-center gap-1.5 rounded-lg border px-3 py-2 text-xs font-semibold shadow-sm transition-all duration-150 ${F?"border-white/50 bg-white/80 text-gray-800 active:scale-[0.97] hover:bg-white dark:border-[#2f303d] dark:bg-[#232430] dark:text-[#ececf1]":"cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400 shadow-none dark:border-[#2f303d] dark:bg-[#181922] dark:text-[#6b6f7a]"}`,"aria-label":r("chatInterface.mobile.openChatsMenuAriaLabel"),children:[i.jsx(rd,{className:"h-4 w-4"}),r("chatInterface.mobile.chatsButton")]}),i.jsxs("button",{onClick:t,className:"inline-flex items-center justify-center gap-1.5 rounded-lg border border-white/50 bg-[#11121a]/90 px-3 py-2 text-xs font-semibold text-white shadow-sm active:scale-[0.97] transition-all duration-150 hover:bg-[#0c0d14] dark:border-[#3b3c49] dark:bg-[#565869] dark:hover:bg-[#6b6f7a]","aria-label":r("chatInterface.mobile.openSettingsAriaLabel"),children:[i.jsx(Ea,{className:"h-4 w-4"}),r("chatInterface.mobile.settingsButton")]})]}),i.jsx("div",{className:"ml-auto flex-shrink-0",children:i.jsx(Cn,{})})]}),i.jsxs("div",{className:"flex flex-col gap-2 md:gap-4 sm:flex-row sm:items-end sm:justify-between",children:[i.jsx("div",{className:"min-w-0 flex-1",children:Ce&&i.jsx("div",{className:"space-y-1.5 md:space-y-3",children:i.jsxs("div",{className:"md:space-y-1",children:[i.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[i.jsx("h1",{className:"min-w-0 truncate text-lg md:text-2xl font-semibold text-[#353740] dark:text-[#ececf1]",children:(b==null?void 0:b.title)||r("chatInterface.newChatTitle")}),b&&i.jsx("span",{className:"flex-shrink-0 text-xs md:hidden text-gray-500 dark:text-[#bfc2cd]",children:b.updatedAt.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),b&&i.jsx("div",{className:"hidden md:flex items-center text-sm text-gray-500 dark:text-[#bfc2cd]",children:i.jsx("span",{children:r("chatInterface.updatedAt",{time:b.updatedAt.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})})})]})})}),i.jsxs("div",{className:"flex w-full flex-wrap items-center gap-2 my-2 md:my-0 sm:w-auto md:justify-end md:gap-3",children:[i.jsx("div",{className:"hidden flex-shrink-0 items-center md:inline-flex",children:i.jsx("button",{onClick:t,className:"inline-flex h-[42px] w-[42px] items-center justify-center rounded-full border border-gray-200 text-gray-500 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:text-gray-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400/50 dark:border-[#3c3f4a] dark:text-[#9aa1bc] dark:hover:border-[#4d5166] dark:hover:bg-[#2d2f39] dark:hover:text-[#ececf1]","aria-label":r("chatInterface.settings.ariaLabel"),title:r("chatInterface.settings.title"),children:i.jsx(Ea,{className:"h-4 w-4"})})}),!fe&&!z&&!!(b!=null&&b.adapterName)&&i.jsx("button",{type:"button",onClick:()=>{ee&&$()},disabled:!ee,className:`order-2 sm:order-1 inline-flex h-8 md:h-[42px] w-[calc(50%-0.25rem)] min-w-[140px] md:w-[190px] items-center justify-center gap-1 md:gap-2 rounded-full border px-2.5 md:px-3.5 py-1.5 md:py-2.5 text-[11px] md:text-[13px] font-medium tracking-[0.01em] transition-colors focus-visible:outline-none focus-visible:ring-2 ${ee?"border-blue-300 text-blue-700 hover:bg-blue-50 hover:border-blue-400 focus-visible:ring-blue-500 dark:border-blue-500/40 dark:text-blue-300 dark:hover:bg-blue-900/20 dark:hover:border-blue-400/60 dark:focus-visible:ring-blue-400/60":"cursor-not-allowed border-gray-200 text-gray-400 bg-transparent dark:border-[#3c3f4a] dark:text-[#6b6f7a]"}`,title:r(ee?"chatInterface.changeAgent.titleEnabled":"chatInterface.changeAgent.titleDisabled"),children:r("chatInterface.changeAgent.button")}),!z&&i.jsxs("button",{onClick:Rt,disabled:!te,className:`order-3 sm:order-2 inline-flex h-8 md:h-[42px] w-[calc(50%-0.25rem)] min-w-[160px] md:w-[220px] md:min-w-[220px] items-center justify-center gap-1 md:gap-2 rounded-full border px-2.5 md:px-3.5 py-1.5 md:py-2.5 text-[11px] md:text-[13px] font-medium tracking-[0.01em] whitespace-nowrap ${te?"border-[#1f2937] bg-[#1f2937] text-white shadow-[0_2px_8px_rgba(15,23,42,0.12)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#1f2937]/40 dark:border-[#4b5568] dark:bg-[#2f3747] dark:text-[#e9edf8] dark:shadow-[0_2px_8px_rgba(0,0,0,0.25)] dark:focus-visible:ring-[#6f809f]/35":"cursor-not-allowed border-gray-200 text-gray-400 bg-white/40 dark:border-[#3c3f4a] dark:text-[#6b6f7a] dark:bg-transparent"}`,title:_e,children:[i.jsx(hd,{className:"h-3.5 w-3.5"}),r("chatInterface.newConversation.button")]}),!gn()&&i.jsx("div",{className:"order-4 hidden flex-shrink-0 items-center md:inline-flex",children:i.jsx(Cn,{})})]})]})]}),k?i.jsxs("div",{className:`flex flex-1 flex-col min-h-0 ${Ye} ${z?"overflow-hidden":""}`,children:[z?i.jsx("div",{className:"flex-1 flex flex-col md:justify-start min-h-0 overflow-hidden",children:i.jsx("div",{className:"w-full flex flex-col min-h-0 overflow-hidden flex-1",children:i.jsxs("div",{className:"flex flex-col min-h-0 flex-1 gap-3 overflow-hidden md:gap-6",children:[i.jsx("div",{className:`${ce} flex-shrink-0 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between`,children:i.jsxs("div",{className:"flex-1",children:[i.jsx($t,{content:j,className:"agent-home-markdown prose prose-slate dark:prose-invert max-w-none [&>:first-child]:mt-0 [&>:last-child]:mb-0 text-2xl font-semibold text-[#11111b] dark:text-white text-center md:text-left [&_p]:text-2xl [&_p]:font-semibold [&_p]:leading-tight [&_p]:m-0",syntaxTheme:E}),O&&i.jsx("div",{className:"mt-2",children:i.jsx($t,{content:L,className:_,syntaxTheme:E})})]})}),i.jsx(xf,{onAdapterSelect:Ee,className:`${ce} md:flex-1 md:min-h-0 md:overflow-hidden`})]})})}):i.jsx("div",{className:"flex flex-1 w-full min-h-0 flex-col overflow-y-auto pt-4 md:pt-6",children:i.jsxs("div",{className:`mx-auto flex w-full ${we} flex-col items-center gap-4 pb-8 md:gap-5 md:pb-12`,children:[ue?i.jsx("p",{className:"w-full text-center text-sm text-red-600 dark:text-red-400",children:ue}):b!=null&&b.adapterName?i.jsx("h2",{className:"w-full text-center text-xl font-semibold tracking-tight text-[#353740] dark:text-[#ececf1] md:text-2xl",style:{fontFamily:'-apple-system, "SF Pro Display", BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},children:ac(b.adapterName)||b.adapterName}):le?i.jsx("p",{className:"w-full text-center text-sm text-gray-500 dark:text-[#bfc2cd]",children:r("chatInterface.empty.configuringAgent")}):null,xt&&zf()&&i.jsx(Af,{adapter:xt,syntaxTheme:E,forcedThemeClass:S}),i.jsx("div",{className:"w-full min-w-0",children:i.jsx(ti,{onSend:qe,disabled:u||!b||!(b!=null&&b.adapterName)||X,autoFocusEnabled:!0,desktopOnlyAutoFocus:fe,placeholder:H,isCentered:!0,maxWidthClass:we,adapterNotes:(nt=b==null?void 0:b.adapterInfo)==null?void 0:nt.notes,skillState:T,availableModels:Y,defaultModel:((Dt=b==null?void 0:b.adapterInfo)==null?void 0:Dt.model)??null,selectedModel:V,onSelectModel:J})})]})}),be&&i.jsx("div",{className:"shrink-0 pt-5 md:pt-6",children:i.jsx(lo,{compact:!0})})]}):i.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[i.jsx(Wu,{messages:b.messages,onRegenerate:ie=>{var ve;return c(ie,V??((ve=b==null?void 0:b.adapterInfo)==null?void 0:ve.model)??void 0)},onEditMessage:(ie,ve)=>{var Te;return d(ie,ve,V??((Te=b==null?void 0:b.adapterInfo)==null?void 0:Te.model)??void 0)},onStartThread:async(ie,ve)=>{try{await p(ie,ve)}catch(Te){xe("Failed to create thread:",Te)}},onClearThread:St,onSendThreadMessage:kt,sessionId:b.sessionId,isLoading:u,contentMaxWidthClass:ae,availableModels:Y,defaultModel:((Ut=b==null?void 0:b.adapterInfo)==null?void 0:Ut.model)??null,selectedModel:V}),i.jsx("div",{className:Hf,children:i.jsx("div",{className:"mx-auto w-full max-w-[96rem] px-3 sm:px-5 md:px-6 lg:px-8 xl:px-10",children:i.jsx(ti,{onSend:qe,disabled:u||!b||!b.adapterName||K||X,autoFocusEnabled:!0,placeholder:r("chatInterface.docked.placeholder"),maxWidthClass:ae,isCentered:!1,adapterNotes:(je=b==null?void 0:b.adapterInfo)==null?void 0:je.notes,skillState:T,availableModels:Y,defaultModel:((bt=b==null?void 0:b.adapterInfo)==null?void 0:bt.model)??null,selectedModel:V,onSelectModel:J})})})]})]})})})}function Wf({selectedAdapter:t,onAdapterChange:e,disabled:r,showDescriptions:n=!1,variant:s="sidebar",label:a,showLabel:o}){const{t:l}=Ie(),[c,d]=h.useState([]),[u,f]=h.useState(!0),[m,g]=h.useState(null),[p,x]=h.useState(!1);h.useEffect(()=>{let F=!0;async function k(){try{f(!0),g(null);const N=await On();F&&d(N)}catch(N){xe("Failed to load adapters:",N),F&&g(l("adapterSelector.failedToLoad"))}finally{F&&f(!1)}}return k(),()=>{F=!1}},[l]);const y=c.find(F=>F.id===t),v=typeof o=="boolean"?o:s==="prominent",A=a||l(s==="prominent"?"adapterSelector.selectAnAgent":"adapterSelector.defaultLabel"),I=h.useMemo(()=>s==="prominent"?"relative w-full text-left":"relative w-full",[s]),C=h.useMemo(()=>{const F="w-full rounded-md border bg-white px-4 py-3 text-left text-sm text-[#353740] focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 dark:bg-[#343541] dark:text-[#ececf1]";return s==="prominent"?[F,"border-gray-300 shadow-sm transition-all duration-200 focus-visible:ring-blue-500 dark:border-[#4a4b54] dark:focus-visible:ring-blue-400"].join(" "):["w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-left text-sm text-[#353740] focus:border-gray-400 focus:outline-none dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#ececf1] dark:focus:border-[#6b6f7a]"].join(" ")},[s]),S=h.useMemo(()=>s==="prominent"?"absolute z-20 mt-2 w-full rounded-xl border border-gray-200 bg-white shadow-xl ring-1 ring-black/5 dark:border-[#4a4b54] dark:bg-[#1f2027]":"absolute z-20 mt-1 w-full rounded-md border border-gray-200 bg-white shadow-lg ring-1 ring-black/5 dark:border-[#4a4b54] dark:bg-[#1f2027]",[s]),b=v?`mb-2 block text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-[#bfc2cd] ${s==="prominent"?"!text-sm !font-semibold !text-gray-700 dark:!text-white":""}`:"sr-only";return i.jsxs("div",{className:I,children:[i.jsx("label",{className:b,children:A}),i.jsxs("div",{className:"relative",children:[i.jsx("button",{type:"button",onClick:()=>!r&&x(!p),disabled:r||u||c.length===0,className:`${C} disabled:opacity-50 disabled:cursor-not-allowed`,"aria-label":A,children:i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsxs("div",{className:"flex flex-col min-w-0",children:[i.jsx("span",{className:`truncate font-medium ${y?"text-[#11121a] dark:text-white":"text-gray-500 dark:text-gray-400"}`,children:u?l("adapterSelector.loadingAgents"):m?l("adapterSelector.errorLoadingAgents"):y?y.name:c.length===0?l("adapterSelector.noAgentsAvailable"):l("adapterSelector.selectAnAgent")}),s==="prominent"&&(y==null?void 0:y.description)&&i.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:y.description})]}),i.jsx(hr,{className:`h-4 w-4 flex-shrink-0 transition-transform text-gray-400 dark:text-gray-300 ${p?"rotate-180":""}`})]})}),p&&!r&&c.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>x(!1)}),i.jsx("div",{className:S,children:i.jsx("div",{className:"max-h-72 overflow-auto py-2",children:c.map(F=>{const k=F.id===t;return i.jsx("button",{type:"button",onClick:()=>{k||e(F.id),x(!1)},className:`w-full px-4 py-3 text-left text-sm transition-colors ${k?"bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-200":"text-[#353740] hover:bg-gray-50 dark:text-[#ececf1] dark:hover:bg-[#2a2d35]"}`,children:i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("span",{className:"font-medium truncate",children:F.name}),n&&F.description&&i.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",style:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:F.description})]})},F.id)})})})]})]}),m&&i.jsx("p",{className:"mt-1 text-xs text-red-600 dark:text-red-400",children:m})]})}const fs=100;function ai({onClick:t,label:e,hoverClassName:r,icon:n}){return i.jsx("button",{onClick:t,className:`rounded-lg p-1.5 text-slate-400 transition-colors dark:text-[#6b6f7a] ${r}`,"aria-label":e,children:n})}function Kf(t,e){const r=new Date(e.getFullYear(),e.getMonth(),e.getDate()),n=new Date(r);n.setDate(n.getDate()-1);const s=new Date(r);s.setDate(s.getDate()-r.getDay());const a=new Date(e.getFullYear(),e.getMonth(),1);return t>=r?"today":t>=n?"yesterday":t>=s?"thisWeek":t>=a?"thisMonth":"earlier"}function Gf(t){const e=new Date,r=["today","yesterday","thisWeek","thisMonth","earlier"],n=new Map;for(const s of t){const a=Kf(s.updatedAt,e),o=n.get(a);o?o.push(s):n.set(a,[s])}return r.filter(s=>n.has(s)).map(s=>({label:s,conversations:n.get(s)}))}function ii({onRequestClose:t,onToggleDesktopSidebar:e}){const{t:r}=Ie(),n=Ls(),{conversations:s,currentConversationId:a,selectConversation:o,deleteConversation:l,deleteAllConversations:c,updateConversationTitle:d,getConversationCount:u,configureApiSettings:f,clearError:m}=ye(),g=s.find(B=>B.id===a),[p,x]=h.useState(""),[y,v]=h.useState(null),[A,I]=h.useState(""),[C,S]=h.useState({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1}),[E,_]=h.useState({isOpen:!1,isDeleting:!1}),[b,F]=h.useState(!1),[k,N]=h.useState(null),[U,T]=h.useState(!1),[H,j]=h.useState(null),L=h.useRef(null),O=h.useRef(null),M=h.useRef(null),Y=!g||g.messages.length===0,G=(k==null?void 0:k.conversationId)===a?k.adapterName:(g==null?void 0:g.adapterName)??null,V=(H==null?void 0:H.conversationId)===a?H.message:null,J=h.useMemo(()=>s.filter(B=>{var q;return(B.messages.length>0||(((q=B.attachedFiles)==null?void 0:q.length)||0)>0)&&!B.adapterLoadError}),[s]),ue=h.useMemo(()=>{if(!p)return J;const B=p.toLowerCase();return J.filter(q=>(q.title||r("chatInterface.newChatTitle")).toLowerCase().includes(B)||q.messages.some(me=>me.content.toLowerCase().includes(B))||(q.attachedFiles||[]).some(me=>me.filename.toLowerCase().includes(B)))},[J,p,r]),Ee=h.useMemo(()=>Gf(ue),[ue]),$=u(),re=p.length>0,X=J.length>0;h.useEffect(()=>{if(!a||!O.current)return;const B=O.current.querySelector('[aria-current="true"]');B&&B.scrollIntoView({block:"nearest",behavior:"smooth"})},[a]);const K=h.useCallback(B=>{var Ye;if(B.key!=="ArrowDown"&&B.key!=="ArrowUp")return;B.preventDefault();const q=(Ye=O.current)==null?void 0:Ye.querySelectorAll('[role="option"]');if(!q||q.length===0)return;const me=document.activeElement,pe=Array.from(q).indexOf(me);let be;B.key==="ArrowDown"?be=pe<q.length-1?pe+1:0:be=pe>0?pe-1:q.length-1,q[be].focus()},[]),le=async B=>{if(!(!Y||!B)){N({conversationId:a??null,adapterName:B}),j(null),T(!0);try{const q=(g==null?void 0:g.apiUrl)||$e();await f(q,void 0,B),m(),F(!1)}catch(q){xe("Failed to configure adapter:",q),j({conversationId:a??null,message:q instanceof Error?q.message:r("sidebar.adapterConfigureFailed")})}finally{T(!1)}}},fe=async B=>{try{await o(B),t==null||t()}catch(q){xe("Failed to select conversation:",q)}},z=(B,q)=>{B.stopPropagation(),S({isOpen:!0,conversationId:q.id,conversationTitle:q.title||r("chatInterface.newChatTitle"),isDeleting:!1})},Z=async()=>{S(B=>({...B,isDeleting:!0}));try{await l(C.conversationId)}catch(B){xe("Failed to delete conversation:",B)}S({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},ae=()=>{S({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},we=(B,q)=>{B.stopPropagation(),v(q.id),I((q.title||r("chatInterface.newChatTitle")).slice(0,fs))},ce=B=>{const q=A.slice(0,fs).trim();q&&d(B,q),v(null),I("")},te=()=>{v(null),I("")},ee=()=>{_({isOpen:!0,isDeleting:!1})},_e=async()=>{_(B=>({...B,isDeleting:!0}));try{await c()}catch(B){xe("Failed to clear all conversations:",B)}_({isOpen:!1,isDeleting:!1})},Ce=()=>{_({isOpen:!1,isDeleting:!1})},Le=B=>{var q,me,pe;return(q=B.adapterName)!=null&&q.trim()?B.adapterName:(pe=(me=B.adapterInfo)==null?void 0:me.adapter_name)!=null&&pe.trim()?B.adapterInfo.adapter_name:null};Dr(L,{enabled:b,onEscape:()=>F(!1)});const De=B=>{const q=a===B.id,me=n?null:Le(B),pe=B.title||r("chatInterface.newChatTitle");return i.jsxs("div",{role:"option","aria-selected":q,tabIndex:0,onKeyDown:be=>{(be.key==="Enter"||be.key===" ")&&(be.preventDefault(),fe(B.id))},onClick:()=>fe(B.id),className:`group relative flex w-full cursor-pointer items-center overflow-hidden rounded-xl border px-3 py-2 text-left text-sm transition-all duration-150
376
+ ${q?"border-slate-200/70 bg-[linear-gradient(180deg,rgba(255,255,255,0.97),rgba(248,250,252,0.94))] shadow-[0_1px_2px_rgba(15,23,42,0.04),0_2px_10px_rgba(15,23,42,0.06)] dark:border-white/10 dark:bg-[linear-gradient(180deg,rgba(50,52,65,0.95),rgba(38,39,49,0.92))] dark:shadow-[0_2px_16px_rgba(0,0,0,0.32)]":"border-transparent hover:border-slate-200/60 hover:bg-slate-50 dark:hover:border-white/[0.05] dark:hover:bg-[#212228]"} focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/50 dark:focus-visible:ring-sky-400/40`,"aria-current":q?"true":void 0,"aria-label":r("sidebar.conversationCard.openAriaLabel",{title:pe}),children:[q&&i.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 bg-[linear-gradient(180deg,rgba(255,255,255,0.4),rgba(255,255,255,0))] dark:bg-[linear-gradient(180deg,rgba(255,255,255,0.045),rgba(255,255,255,0))]"}),i.jsx("span",{"aria-hidden":"true",className:`absolute inset-y-0 left-0 w-[3px] transition-opacity duration-150 ${q?"bg-sky-500 opacity-100 dark:bg-sky-400":"opacity-0"}`}),y===B.id?i.jsx("input",{type:"text",value:A,onChange:be=>I(be.target.value.slice(0,fs)),onKeyDown:be=>{be.key==="Enter"&&ce(B.id),be.key==="Escape"&&te(),be.stopPropagation()},onBlur:()=>ce(B.id),maxLength:fs,className:"relative z-10 flex-1 rounded-lg border border-sky-300 bg-white px-2 py-1 text-sm text-[#353740] focus:outline-none focus:ring-2 focus:ring-sky-400/50 dark:border-sky-500/40 dark:bg-[#1a1b1e] dark:text-[#ececf1]",autoFocus:!0,"aria-label":r("sidebar.conversationCard.editInputAriaLabel")}):i.jsxs("div",{className:"relative z-10 flex min-w-0 flex-1 flex-col gap-1",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[i.jsx("h3",{className:`flex-1 truncate text-sm leading-snug tracking-[-0.006em] ${q?"font-semibold text-slate-900 dark:text-[#ececf1]":"font-medium text-slate-700 dark:text-[#c5c8d6]"}`,children:pe}),i.jsxs("div",{className:"ml-1 flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity duration-100 group-hover:opacity-100 group-focus-within:opacity-100",children:[i.jsx(ai,{onClick:be=>we(be,B),label:r("sidebar.conversationCard.editAriaLabel",{title:pe}),hoverClassName:"hover:bg-slate-200/80 hover:text-slate-600 dark:hover:bg-[#3c3f4a] dark:hover:text-[#c5c8d6]",icon:i.jsx(Ui,{className:"h-3.5 w-3.5"})}),i.jsx(ai,{onClick:be=>z(be,B),label:r("sidebar.conversationCard.deleteAriaLabel",{title:pe}),hoverClassName:"hover:bg-red-100/80 hover:text-red-600 dark:hover:bg-red-900/30 dark:hover:text-red-400",icon:i.jsx(Hi,{className:"h-3.5 w-3.5"})})]})]}),me&&i.jsx("span",{className:"block max-w-full truncate text-left text-xs font-medium tracking-wide text-blue-700 dark:text-blue-300",children:me})]})]},B.id)};return i.jsxs(i.Fragment,{children:[!n&&b&&i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm px-4",children:i.jsxs("div",{ref:L,role:"dialog","aria-modal":"true","aria-labelledby":"select-agent-title",tabIndex:-1,className:"w-full max-w-md rounded-2xl border border-gray-200 bg-white p-6 shadow-2xl dark:border-[#3d4050] dark:bg-[#1a1b1e]",children:[i.jsx("h2",{id:"select-agent-title",className:"mb-4 text-lg font-semibold text-gray-900 dark:text-[#ececf1]",children:r("sidebar.selectAgent.title")}),i.jsxs("div",{className:"space-y-5",children:[i.jsx(Wf,{selectedAdapter:G,onAdapterChange:le,disabled:U,variant:"prominent",showDescriptions:!0,showLabel:!1}),V&&i.jsx("div",{role:"alert",className:"rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-600/40 dark:bg-red-900/30 dark:text-red-200",children:V}),i.jsx("div",{className:"flex justify-end gap-3 pt-2",children:i.jsx("button",{type:"button",onClick:()=>{j(null),F(!1)},className:"rounded-lg px-4 py-2 text-sm font-medium text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50 dark:text-[#d1d5db] dark:hover:bg-[#2d2f39]",disabled:U,children:r("common.cancel")})})]})]})}),i.jsxs("nav",{"aria-label":r("sidebar.navAriaLabel"),className:"flex h-full md:h-[calc(100%-2rem)] md:mt-4 w-full md:w-72 flex-col border-r border-b border-gray-200 md:border-l md:border-t md:rounded-2xl md:overflow-hidden bg-transparent dark:border-[#2d2f39]",children:[i.jsxs("div",{className:"bg-transparent px-4 pb-4 pt-4 dark:border-[#2d2f39]",children:[i.jsxs("div",{className:"flex items-center gap-2 pb-3",children:[s.length>0&&s.some(B=>B.messages.length>0)&&i.jsxs("button",{onClick:ee,className:"flex flex-1 items-center justify-center gap-2 rounded-lg border border-red-200 px-3 py-2 text-sm font-medium text-red-600 transition-all duration-150 hover:bg-red-50 hover:border-red-300 hover:shadow-sm dark:border-red-500/25 dark:text-red-400 dark:hover:bg-red-950/20 dark:hover:border-red-500/40",title:r("sidebar.deleteAllConversations.title"),children:[i.jsx(bd,{className:"h-4 w-4"}),r("sidebar.deleteAllConversations.button")]}),e&&i.jsx("button",{type:"button",onClick:e,className:"ml-auto hidden shrink-0 md:inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-200/80 bg-white text-slate-600 transition-colors hover:border-slate-300 hover:bg-slate-100 hover:text-slate-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:border-[#333645] dark:bg-[#161616] dark:text-[#d1d5db] dark:hover:border-[#43465a] dark:hover:bg-[#202020] dark:hover:text-white","aria-label":r("sidebar.collapse.ariaLabel"),title:r("sidebar.collapse.title"),children:i.jsx(ld,{className:"h-4 w-4"})})]}),V&&!b&&i.jsx("p",{role:"alert",className:"mt-2 text-xs text-red-600 dark:text-red-400",children:V}),X&&i.jsxs("div",{className:"border-t border-gray-200 pt-4 mt-4 dark:border-[#2d2f39]",children:[i.jsxs("div",{className:"relative overflow-hidden rounded-[1.75rem] border border-slate-200/85 bg-[linear-gradient(180deg,rgba(255,255,255,0.96),rgba(248,250,252,0.94))] shadow-[0_10px_28px_rgba(15,23,42,0.05)] transition-all duration-200 focus-within:border-sky-300/90 focus-within:shadow-[0_0_0_1px_rgba(125,211,252,0.55),0_10px_28px_rgba(15,23,42,0.05)] dark:border-white/10 dark:bg-[linear-gradient(180deg,rgba(37,39,49,0.95),rgba(29,31,39,0.92))] dark:shadow-[0_12px_30px_rgba(0,0,0,0.2)] dark:focus-within:border-sky-400/30 dark:focus-within:shadow-[0_0_0_1px_rgba(56,189,248,0.22),0_12px_30px_rgba(0,0,0,0.2)]",children:[i.jsx("div",{className:"pointer-events-none absolute inset-0 rounded-[inherit] bg-[linear-gradient(180deg,rgba(255,255,255,0.45),rgba(255,255,255,0))] dark:bg-[linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))]"}),i.jsx(Fn,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400 dark:text-slate-500"}),i.jsx("input",{ref:M,type:"text",role:"searchbox","aria-label":r("sidebar.search.ariaLabel"),placeholder:r("sidebar.search.placeholder"),value:p,onChange:B=>x(B.target.value),className:"relative z-10 w-full bg-transparent py-3 pl-11 pr-11 text-sm font-medium text-slate-700 placeholder:font-normal placeholder:text-slate-400 focus:outline-none dark:text-slate-100 dark:placeholder:text-slate-500"}),p&&i.jsx("button",{type:"button",onClick:()=>{var B;x(""),(B=M.current)==null||B.focus()},className:"absolute right-3 top-1/2 z-10 inline-flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-full border border-slate-200/80 bg-white/90 text-slate-400 transition-colors hover:border-slate-300 hover:text-slate-600 focus:outline-none focus:ring-2 focus:ring-sky-200 dark:border-white/10 dark:bg-white/5 dark:text-slate-500 dark:hover:border-white/20 dark:hover:text-slate-200 dark:focus:ring-sky-500/20","aria-label":r("sidebar.search.clearAriaLabel"),children:i.jsx(Je,{className:"h-3.5 w-3.5"})})]}),re&&i.jsx("p",{"aria-live":"polite",className:"mt-2 text-center text-[11px] tabular-nums text-gray-400 dark:text-[#6e7490]",children:ue.length===0?r("sidebar.resultsNone"):r("sidebar.results",{count:ue.length})})]})]}),i.jsx("div",{ref:O,role:"listbox","aria-label":r("sidebar.conversations.ariaLabel"),onKeyDown:K,className:"flex-1 overflow-y-auto bg-transparent px-3 py-2",children:ue.length===0?null:re?i.jsx("div",{className:"space-y-1.5",children:ue.map(De)}):i.jsx("div",{className:"space-y-4",children:Ee.map(B=>i.jsxs("section",{"aria-label":r(`sidebar.timeGroups.${B.label}`),children:[i.jsx("h4",{className:"sticky top-0 z-10 mb-1 bg-transparent px-1 pb-1 pt-0.5 text-[11px] font-semibold uppercase tracking-wider text-gray-400 backdrop-blur-sm dark:text-[#6e7490]",children:r(`sidebar.timeGroups.${B.label}`)}),i.jsx("div",{className:"space-y-1.5",children:B.conversations.map(De)})]},B.label))})}),(()=>{const B=Li();return B.length===0?null:i.jsx("div",{className:"shrink-0 border-t border-gray-200/80 px-4 py-3 md:hidden dark:border-[#2d2f39]",children:i.jsx("nav",{"aria-label":r("appHeader.navLinksAriaLabel"),children:i.jsx("ul",{className:"flex flex-wrap gap-2",children:B.map(q=>i.jsx("li",{children:i.jsx("a",{href:q.url,className:"inline-flex items-center rounded-md px-2.5 py-1.5 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-100 dark:text-[#d1d5db] dark:hover:bg-[#2b2d39]",children:q.label})},q.url))})})})})(),i.jsx("div",{className:"shrink-0 border-t border-gray-200/80 dark:border-[#2d2f39]",children:i.jsx(lo,{placement:"sidebar",compact:!0})})]}),i.jsx(ws,{isOpen:C.isOpen,onClose:ae,onConfirm:Z,title:r("sidebar.deleteConfirm.title"),message:r("sidebar.deleteConfirm.message",{title:C.conversationTitle}),confirmText:r("sidebar.deleteConfirm.confirmText"),cancelText:r("common.cancel"),type:"danger",isLoading:C.isDeleting}),i.jsx(ws,{isOpen:E.isOpen,onClose:Ce,onConfirm:_e,title:r("sidebar.clearAllConfirm.title"),message:r("sidebar.clearAllConfirm.message",{count:$}),confirmText:r("sidebar.clearAllConfirm.confirmText"),cancelText:r("common.cancel"),type:"danger",isLoading:E.isDeleting})]})}const Xf="3.11.11",Yf={version:Xf},Bn=Yf.version,Qf=["@@auth0spajs@@","a0.spajs","auth0","com.auth0"];function Zf(t){const e=t.toLowerCase();return Qf.some(r=>e.includes(r.toLowerCase()))}function Jf(t){const e=[];for(let r=0;r<t.length;r++){const n=t.key(r);n&&Zf(n)&&e.push(n)}e.forEach(r=>t.removeItem(r))}function oi(t){try{Jf(t),t.clear()}catch(e){console.warn("[Settings] Failed to clear browser storage during reset.",e)}}function eh(){if(typeof document>"u"||!document.cookie)return;const t=new Set([void 0]),e=window.location.hostname;e&&e!=="localhost"&&!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)&&(t.add(e),t.add(`.${e}`)),document.cookie.split(";").forEach(n=>{const s=n.indexOf("="),a=(s>-1?n.slice(0,s):n).trim();a&&t.forEach(o=>{const l=o?`;domain=${o}`:"";document.cookie=`${a}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${l}`})})}function th(){oi(localStorage),oi(sessionStorage),eh()}function rh({isOpen:t,onClose:e}){const{t:r}=Ie(),{theme:n,updateTheme:s}=tr(),{settings:a,updateSettings:o}=Ns(),{activeLanguages:l,currentLanguage:c,setLanguage:d}=zc(),[u,f]=h.useState(!1),[m,g]=h.useState(!1),p=h.useRef(null),x=h.useRef(null),y=h.useMemo(()=>[...l].sort((E,_)=>ss[E].localeCompare(ss[_])),[l]);h.useEffect(()=>{if(!m)return;const E=_=>{_.key==="Escape"&&(_.stopPropagation(),g(!1))};return document.addEventListener("keydown",E,{capture:!0}),()=>document.removeEventListener("keydown",E,{capture:!0})},[m]);const v=E=>{s({mode:E})},A=()=>{o({soundEnabled:!a.soundEnabled})},I=()=>{f(!0)},C=()=>{f(!1)},S=()=>{C(),Ts(),Ms(!1),fr(null),st.getState().closeLoginPrompt(),th(),window.location.reload()};return Dr(p,{enabled:t&&!u,onEscape:e}),Dr(x,{enabled:u,onEscape:C}),t?i.jsxs("div",{className:"fixed inset-0 z-50 flex items-end md:items-center justify-center overflow-y-auto bg-black/50 p-0 md:p-4",children:[i.jsx("button",{type:"button",onClick:e,"aria-label":r("settings.dialog.closeOverlayAriaLabel"),className:"absolute inset-0"}),i.jsxs("div",{onClick:E=>E.stopPropagation(),ref:p,role:"dialog","aria-modal":"true","aria-labelledby":"settings-title",tabIndex:-1,className:"relative flex h-[100dvh] w-full max-w-none flex-col overflow-hidden bg-white shadow-2xl dark:bg-[#1a1b1e] md:h-auto md:max-h-[90vh] md:max-w-md md:rounded-2xl",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between border-b border-gray-200 px-6 pb-4 pt-[max(env(safe-area-inset-top),1rem)] dark:border-[#2d2f39] md:p-6",children:[i.jsx("h2",{id:"settings-title",className:"text-xl font-semibold text-gray-900 dark:text-gray-100",children:r("settings.dialog.title")}),i.jsx("button",{onClick:e,className:"p-2 hover:bg-gray-100 dark:hover:bg-[#25262f] rounded-lg transition-colors","aria-label":r("settings.dialog.closeButtonAriaLabel"),children:i.jsx(Je,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),i.jsxs("div",{className:"flex-1 min-h-0 space-y-6 overflow-y-auto px-6 pb-[max(env(safe-area-inset-bottom),1.25rem)] pt-6 md:p-6",children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[i.jsx(od,{className:"w-5 h-5"}),r("settings.appearance.heading")]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:r("settings.appearance.themeLabel")}),i.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{value:"light",label:r("settings.appearance.themeLight"),icon:xd},{value:"dark",label:r("settings.appearance.themeDark"),icon:id},{value:"system",label:r("settings.appearance.themeSystem"),icon:ad}].map(({value:E,label:_,icon:b})=>i.jsxs("button",{onClick:()=>v(E),className:`flex flex-col items-center gap-2 p-3 rounded-lg border-2 transition-all duration-200 ${n.mode===E?"border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300":"border-gray-200 dark:border-[#2d2f39] hover:border-gray-300 dark:hover:border-[#43465a] text-gray-700 dark:text-gray-300"}`,children:[i.jsx(b,{className:"w-5 h-5"}),i.jsx("span",{className:"text-sm font-medium",children:_})]},E))})]}),l.length>1&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2",children:[i.jsx(Jc,{className:"w-4 h-4"}),r("settings.language.label")]}),i.jsxs("div",{className:"relative",children:[i.jsxs("button",{type:"button",onClick:()=>g(E=>!E),"aria-haspopup":"listbox","aria-expanded":m,className:`flex w-full items-center justify-between gap-2 rounded-lg border-2 px-3 py-2.5 text-left text-sm transition-colors duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 dark:focus-visible:ring-blue-400/40 ${m?"border-blue-500":"border-gray-200 dark:border-[#2d2f39] hover:border-gray-300 dark:hover:border-[#43465a]"}`,children:[i.jsx("span",{className:"font-medium text-gray-900 dark:text-gray-100",children:ss[c]}),i.jsx(hr,{className:`h-4 w-4 flex-shrink-0 text-gray-400 transition-transform duration-200 dark:text-gray-500 ${m?"rotate-180":""}`})]}),m&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),i.jsx("div",{role:"listbox","aria-label":r("settings.language.label"),className:"absolute z-20 mt-2 max-h-60 w-full overflow-y-auto rounded-lg border border-gray-200 bg-white p-1 shadow-lg ring-1 ring-black/5 dark:border-[#2d2f39] dark:bg-[#1a1b1e] dark:ring-white/5",children:y.map(E=>{const _=E===c;return i.jsxs("button",{type:"button",role:"option","aria-selected":_,onClick:()=>{d(E),g(!1)},className:`flex w-full items-center justify-between gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors ${_?"bg-blue-50 font-medium text-blue-700 dark:bg-blue-900/20 dark:text-blue-300":"text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-[#25262f]"}`,children:[i.jsx("span",{className:"truncate",children:ss[E]}),_&&i.jsx(ur,{className:"h-4 w-4 flex-shrink-0 text-blue-600 dark:text-blue-400"})]},E)})})]})]})]})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:r("settings.chat.heading")}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Pn,{className:"w-4 h-4 text-gray-600 dark:text-gray-400"}),i.jsxs("div",{children:[i.jsx("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:r("settings.soundEffects.label")}),i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:r("settings.soundEffects.description")})]})]}),i.jsx("button",{onClick:A,role:"switch","aria-checked":a.soundEnabled,"aria-label":r("settings.soundEffects.toggleAriaLabel"),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${a.soundEnabled?"bg-blue-600":"bg-gray-200 dark:bg-[#3c3f4a]"}`,children:i.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${a.soundEnabled?"translate-x-6":"translate-x-1"}`})})]})]}),i.jsxs("div",{className:"space-y-4 pt-4 border-t border-gray-200 dark:border-[#2d2f39]",children:[i.jsxs("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[i.jsx(Hi,{className:"w-5 h-5"}),r("settings.dataManagement.heading")]}),i.jsxs("div",{className:"space-y-3",children:[i.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:r("settings.dataManagement.description")}),i.jsx("button",{onClick:I,className:"w-full px-4 py-2 text-sm font-medium text-red-600 dark:text-red-400 border border-red-300 dark:border-red-700 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors",children:r("settings.reset.button")})]})]}),i.jsxs("p",{className:"pt-2 text-center text-xs text-gray-400 dark:text-[#858999]",children:["v",Bn]})]}),u&&i.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/70 p-4",children:i.jsxs("div",{ref:x,role:"dialog","aria-modal":"true","aria-labelledby":"reset-dialog-title",tabIndex:-1,className:"max-h-[calc(100dvh-2rem)] w-full max-w-sm overflow-y-auto rounded-2xl border border-red-100 bg-white p-6 shadow-2xl dark:border-red-800/60 dark:bg-[#111113]",children:[i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"mt-0.5 flex h-10 w-10 items-center justify-center rounded-full bg-red-100 dark:bg-red-900/40",children:i.jsx(Rn,{className:"w-5 h-5 text-red-600 dark:text-red-400"})}),i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("p",{id:"reset-dialog-title",className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:r("settings.reset.confirmTitle")}),i.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:r("settings.reset.confirmMessage")})]})]}),i.jsxs("div",{className:"mt-4 flex gap-2 pt-2",children:[i.jsx("button",{onClick:C,className:"flex-1 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-[#2d2f39] rounded-lg hover:bg-gray-50 dark:hover:bg-[#1a1b1e] transition-colors",children:r("common.cancel")}),i.jsx("button",{onClick:S,className:"flex-1 px-4 py-2 text-sm font-semibold rounded-lg transition-colors bg-red-600 text-white hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-600",children:r("settings.reset.confirmButton")})]})]})})]})]}):null}function sh({message:t}){const{t:e}=Ie(),r=En();return i.jsx("main",{className:"min-h-dvh bg-white px-4 py-6 text-slate-950 dark:bg-black dark:text-slate-100 sm:px-6 lg:px-8",children:i.jsxs("div",{className:"mx-auto flex min-h-[calc(100dvh-3rem)] w-full max-w-5xl flex-col",children:[i.jsxs("header",{className:"flex items-center justify-between gap-4",children:[i.jsx("p",{className:"min-w-0 truncate text-lg font-semibold tracking-tight sm:text-xl",children:r}),i.jsxs("span",{className:"shrink-0 text-xs font-medium text-slate-400 dark:text-[#858999]",children:["v",Bn]})]}),i.jsx("section",{className:"flex flex-1 items-center justify-center py-12",children:i.jsxs("div",{className:"w-full max-w-lg space-y-8",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("span",{className:"relative flex h-2.5 w-2.5 shrink-0",children:[i.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-amber-400 opacity-60 dark:bg-amber-500"}),i.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-amber-500 dark:bg-amber-400"})]}),i.jsx("span",{className:"text-xs font-semibold uppercase tracking-widest text-amber-700 dark:text-amber-400",children:e("outOfService.statusBadge")})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-slate-950 dark:text-white sm:text-4xl",children:e("outOfService.heading")}),i.jsx("p",{className:"max-w-md whitespace-pre-wrap text-base leading-relaxed text-slate-500 dark:text-slate-400",children:t})]}),i.jsx("div",{className:"border-t border-slate-200 dark:border-[#242424]"}),i.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[i.jsxs("button",{type:"button",onClick:()=>window.location.reload(),className:"inline-flex items-center justify-center gap-2 rounded-lg bg-slate-950 px-5 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-slate-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:bg-white dark:text-slate-950 dark:hover:bg-slate-200",children:[i.jsx(md,{className:"h-4 w-4","aria-hidden":"true"}),e("outOfService.retryButton")]}),i.jsx("span",{className:"hidden text-slate-300 dark:text-slate-700 sm:block","aria-hidden":"true",children:"·"})]})]})})]})})}function nh({children:t}){const{instance:e,accounts:r}=Nn(),n=rl();return h.useEffect(()=>{Ms(n)},[n]),h.useEffect(()=>{if(!n||r.length===0){fr(null);return}const s=r[0];fr(s.username||s.name||s.localAccountId||null)},[n,r]),h.useEffect(()=>{if(!n||r.length===0)return;const s=r[0],a=Mn();return Vi(async()=>(await e.acquireTokenSilent({scopes:a,account:s})).accessToken),()=>Ts()},[n,r,e]),i.jsx(i.Fragment,{children:t})}function ah({children:t}){return i.jsx(nh,{children:t})}function ih({children:t}){const{isLoading:e,isAuthenticated:r,getAccessTokenSilently:n,user:s}=In();return h.useEffect(()=>{Ms(r)},[r]),h.useEffect(()=>{if(!r){fr(null);return}const a=(s==null?void 0:s.sub)||(s==null?void 0:s.email)||(s==null?void 0:s.nickname)||(s==null?void 0:s.name)||null;fr(a)},[r,s]),h.useEffect(()=>(r&&Vi(()=>n()),()=>Ts()),[r,n]),e?i.jsx("div",{className:"flex items-center justify-center h-screen bg-white dark:bg-[#212121]",children:i.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 dark:border-gray-100"})}):i.jsx(i.Fragment,{children:t})}function oh({children:t}){return h.useEffect(()=>{Ms(!1),fr(null),Ts()},[]),i.jsx(i.Fragment,{children:t})}function lh({children:t}){return rt()?Es()==="entra"?i.jsx(ah,{children:t}):i.jsx(ih,{children:t}):i.jsx(oh,{children:t})}function ch(){const t=Tn(),e=rt(),r=mr(),{showLoginPrompt:n,promptMessage:s,closeLoginPrompt:a}=st();return h.useEffect(()=>{n&&(!t||!e||r)&&a()},[n,t,e,r,a]),!t||!e||r||!n?null:Es()==="entra"?i.jsx(uh,{message:s,onClose:a}):i.jsx(dh,{message:s,onClose:a})}function dh({message:t,onClose:e}){const{loginWithRedirect:r}=In();return i.jsx(po,{message:t,onClose:e,onLogin:()=>r()})}function uh({message:t,onClose:e}){const{instance:r}=Nn();return i.jsx(po,{message:t,onClose:e,onLogin:()=>r.loginRedirect({scopes:Mn()}).catch(()=>{})})}function po({message:t,onClose:e,onLogin:r}){const{t:n}=Ie();return i.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:e,"aria-hidden":"true"}),i.jsxs("div",{className:"relative z-10 mx-4 w-full max-w-md rounded-2xl border border-gray-200 bg-white p-6 shadow-2xl dark:border-[#4a4b54] dark:bg-[#2d2f39]",children:[i.jsx("button",{onClick:e,className:"absolute right-3 top-3 rounded-full p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]","aria-label":n("common.close"),children:i.jsx(Je,{className:"h-4 w-4"})}),i.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[i.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900/40",children:i.jsx(Di,{className:"h-5 w-5 text-blue-600 dark:text-blue-300"})}),i.jsx("h2",{className:"text-lg font-semibold text-gray-900 dark:text-[#ececf1]",children:n("loginPrompt.heading")})]}),i.jsx("p",{className:"mb-6 text-sm leading-relaxed text-gray-600 dark:text-[#bfc2cd]",children:t}),i.jsxs("div",{className:"flex gap-3",children:[i.jsx("button",{onClick:r,className:"flex-1 rounded-lg bg-blue-600 px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:bg-blue-500 dark:hover:bg-blue-600",children:n("common.signIn")}),i.jsx("button",{onClick:e,className:"flex-1 rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 dark:border-[#4a4b54] dark:bg-[#2d2f39] dark:text-[#bfc2cd] dark:hover:bg-[#3c3f4a]",children:n("common.cancel")})]})]})]})}function fh(){const{t}=Ie(),{goHome:e}=ho(),{isDark:r}=tr(),n=kf(),s=h.useRef(!1),a=kc(),o=Sc(),l=jc(),c=r?l:o,d=Cc(),u=Ac(),f=!!(d||u),m=Nc(),g=Ic(),p=Lc(),x=Li(),y=p?"border-b border-slate-200/80 dark:border-[#333645]":"",v="inline-flex min-h-10 items-center rounded-md px-2.5 text-sm font-medium transition-colors hover:bg-slate-100 hover:text-blue-700 hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:hover:bg-[#2b2d39] dark:hover:text-blue-300";return h.useEffect(()=>{s.current},[l,a,o]),gn()?i.jsx("header",{className:`relative z-30 shrink-0 bg-white px-3 pb-1 pt-2 dark:bg-black sm:px-5 sm:pb-2 sm:pt-3 lg:px-8 md:pt-5 ${y}`.trim(),style:{backgroundColor:m||void 0,color:g||void 0},children:i.jsxs("div",{className:"mx-auto flex w-full max-w-[96rem] items-center justify-between gap-3",children:[i.jsx("div",{className:"flex min-w-0 flex-1 items-center justify-center gap-2 md:justify-start md:gap-3",children:i.jsx("a",{href:n,"aria-label":t("appHeader.homeLinkAriaLabel"),onClick:A=>{A.preventDefault(),e()},className:"inline-flex items-center rounded-sm px-1 py-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 dark:focus-visible:ring-blue-300 dark:focus-visible:ring-offset-black md:-ml-1",children:i.jsx("img",{src:c,alt:t("appHeader.logoAlt"),draggable:!1,className:`block max-w-full flex-shrink-0 select-none ${f?"":"h-8 w-auto sm:h-10 md:h-11"}`.trim(),style:{WebkitUserDrag:"none",...d?{height:d}:{},...u?{width:u}:{}}})})}),i.jsxs("div",{className:"hidden min-w-0 flex-1 items-center justify-end gap-2 sm:gap-4 md:flex",children:[x.length>0&&i.jsx("nav",{"aria-label":t("appHeader.navLinksAriaLabel"),className:"hidden sm:block",children:i.jsx("ul",{className:"flex items-center gap-1.5 sm:gap-2",children:x.map(A=>i.jsx("li",{children:i.jsx("a",{href:A.url,target:"_blank",rel:"noopener noreferrer",className:v,style:{color:g||void 0},children:A.label})},A.url))})}),i.jsx(Cn,{})]})]})}):null}function hh({children:t}){const e=h.useRef(null),r=h.useCallback(s=>{e.current=s},[]),n=h.useCallback(()=>{var s;(s=e.current)==null||s.call(e)},[]);return i.jsx(fo.Provider,{value:{registerGoHome:r,goHome:n},children:t})}function mh(){const{t}=Ie(),[e,r]=h.useState(!1),[n,s]=h.useState(!1),[a,o]=h.useState(()=>localStorage.getItem("desktop-sidebar-collapsed")==="true"),l=ye(u=>u.conversations),c=bc();if(h.useEffect(()=>{localStorage.setItem("desktop-sidebar-collapsed",String(a))},[a]),c)return i.jsx(la,{children:i.jsx(sh,{message:c})});const d=l.some(u=>{var f;return(u.messages.length>0||(((f=u.attachedFiles)==null?void 0:f.length)??0)>0)&&!u.adapterLoadError});return i.jsx(la,{children:i.jsx(il,{children:i.jsx(Oc,{children:i.jsx(lh,{children:i.jsx(hh,{children:i.jsxs("div",{className:"h-dvh flex flex-col bg-white dark:bg-black text-slate-900 dark:text-slate-100",children:[i.jsxs("div",{className:"flex-1 flex flex-col md:flex-row md:pl-4 min-h-0",children:[d&&(a?i.jsx("div",{className:"hidden md:flex md:w-16 md:h-full shrink-0 items-start justify-center pt-8",children:i.jsx("button",{type:"button",onClick:()=>o(!1),className:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-200/80 bg-white text-slate-600 transition-colors hover:border-slate-300 hover:bg-slate-100 hover:text-slate-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:border-[#333645] dark:bg-[#161616] dark:text-[#d1d5db] dark:hover:border-[#43465a] dark:hover:bg-[#202020] dark:hover:text-white","aria-label":t("app.sidebar.openAriaLabel"),title:t("app.sidebar.openTitle"),children:i.jsx(cd,{className:"h-4 w-4"})})}):i.jsx("div",{className:"hidden md:h-full md:flex",children:i.jsx(ii,{onToggleDesktopSidebar:()=>o(!0)})})),i.jsxs("div",{className:"flex-1 flex flex-col w-full min-h-0",children:[i.jsx(fh,{}),i.jsx("div",{className:"flex-1 flex justify-center w-full min-h-0",children:i.jsx(qf,{onOpenSettings:()=>r(!0),onOpenSidebar:()=>s(!0)})})]})]}),i.jsx(ch,{}),i.jsx(rh,{isOpen:e,onClose:()=>r(!1)}),n&&i.jsxs("div",{className:"fixed inset-0 z-50 flex md:hidden",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:()=>s(!1),"aria-hidden":"true"}),i.jsxs("div",{className:"relative z-10 h-full w-[min(20rem,90vw)] animate-slideIn bg-white dark:bg-black",children:[i.jsx(ii,{onRequestClose:()=>s(!1)}),i.jsx("button",{onClick:()=>s(!1),className:"absolute -right-3 top-[max(env(safe-area-inset-top),0.75rem)] rounded-full bg-white/95 p-3 text-gray-600 shadow-lg active:scale-95 transition-transform dark:bg-[#2d2f39] dark:text-[#ececf1]","aria-label":t("app.menu.closeAriaLabel"),children:i.jsx(Je,{className:"h-5 w-5"})})]})]})]})})})})})})}const cn=new sl({auth:{clientId:Ni(),authority:`https://login.microsoftonline.com/${vc()}`,redirectUri:typeof window<"u"?window.location.origin:"/"},cache:{cacheLocation:"sessionStorage"}});function ph({children:t}){const[e,r]=h.useState(!1);return h.useEffect(()=>{cn.initialize().then(()=>cn.handleRedirectPromise()).catch(n=>{console.error("[EntraAuth] Redirect processing failed:",n)}).finally(()=>r(!0))},[]),e?i.jsx(nl,{instance:cn,children:t}):null}function gh({children:t}){if(!Tn()||!rt())return i.jsx(i.Fragment,{children:t});if(Es()==="entra")return i.jsx(ph,{children:t});const r=yc(),n=Ni(),s=wc();return!r||!n?i.jsx(i.Fragment,{children:t}):i.jsx(al,{domain:r,clientId:n,authorizationParams:{redirect_uri:window.location.origin,...s?{audience:s}:{}},cacheLocation:"memory",children:t})}mo(null);const li=dc(),ci=document.querySelector('link[rel="icon"]');if(ci)ci.href=li;else{const t=document.createElement("link");t.rel="icon",t.href=li,document.head.appendChild(t)}const xh=Rc();var di,ui,fi,hi,mi,pi;for(const t of xh){const e=((di=t.src)==null?void 0:di.trim())||"",r=((ui=t.content)==null?void 0:ui.trim())||"",n=((fi=t.id)==null?void 0:fi.trim())||"";if(!e&&!r||n&&document.querySelector(`script[data-orbitchat-startup-script-id="${n}"]`)||Array.from(document.querySelectorAll("script[data-orbitchat-startup-script]")).some(o=>{const l=e&&o.dataset.orbitchatStartupScriptSrc===e,c=r&&(o.textContent||"").trim()===r;return!!(l||c)}))continue;const a=document.createElement("script");e&&(a.src=e),r&&(a.text=r),a.async=t.async??!0,t.defer!==void 0&&(a.defer=t.defer),(hi=t.type)!=null&&hi.trim()&&(a.type=t.type.trim()),(mi=t.integrity)!=null&&mi.trim()&&(a.integrity=t.integrity.trim()),t.crossOrigin&&(a.crossOrigin=t.crossOrigin),(pi=t.referrerPolicy)!=null&&pi.trim()&&(a.referrerPolicy=t.referrerPolicy.trim()),a.dataset.orbitchatStartupScript="true",n&&(a.dataset.orbitchatStartupScriptId=n),e&&(a.dataset.orbitchatStartupScriptSrc=e),document.head.appendChild(a)}D("🚀 AI Chat Application started");D(`📱 App Version: v${Bn}`);Bo.createRoot(document.getElementById("root")).render(i.jsx(h.StrictMode,{children:i.jsx(gh,{children:i.jsx(mh,{})})}));export{zl as r,Ie as u};