orbitchat 3.11.6 → 3.11.7

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 (53) hide show
  1. package/dist/assets/{ChartRenderer-B9WgyQbh.js → ChartRenderer-BFQlovpe.js} +1 -1
  2. package/dist/assets/{MermaidRenderer-ZdYLQXe1.js → MermaidRenderer-DxunGWXF.js} +4 -4
  3. package/dist/assets/{MusicRenderer-CPc4ca0i.js → MusicRenderer-qpZbjlwR.js} +1 -1
  4. package/dist/assets/{SVGRenderer-BUZ2s3dH.js → SVGRenderer-DKegh4A9.js} +1 -1
  5. package/dist/assets/{architectureDiagram-3BPJPVTR-ywxEZC3c.js → architectureDiagram-3BPJPVTR-jYJI0p77.js} +1 -1
  6. package/dist/assets/{blockDiagram-GPEHLZMM-Bw-FXGjK.js → blockDiagram-GPEHLZMM-CbU7_hO5.js} +1 -1
  7. package/dist/assets/{c4Diagram-AAUBKEIU-CFRb30CH.js → c4Diagram-AAUBKEIU-Bcq1htcJ.js} +1 -1
  8. package/dist/assets/channel-BtuqB4HX.js +1 -0
  9. package/dist/assets/{chunk-2J33WTMH-q3h_OJ7U.js → chunk-2J33WTMH-BEZdJIj6.js} +1 -1
  10. package/dist/assets/{chunk-4BX2VUAB-BaoOm2YM.js → chunk-4BX2VUAB-DaeeAboq.js} +1 -1
  11. package/dist/assets/{chunk-55IACEB6-DNdZ3QZs.js → chunk-55IACEB6-hx4rlTxl.js} +1 -1
  12. package/dist/assets/{chunk-727SXJPM-Dm8KfhqO.js → chunk-727SXJPM-CSE1V8fn.js} +1 -1
  13. package/dist/assets/{chunk-AQP2D5EJ-CKZSB_XN.js → chunk-AQP2D5EJ-DQBM809-.js} +1 -1
  14. package/dist/assets/{chunk-FMBD7UC4-_49U0RVY.js → chunk-FMBD7UC4-BckzcK4u.js} +1 -1
  15. package/dist/assets/{chunk-ND2GUHAM-BnJM2pC7.js → chunk-ND2GUHAM-BMzK4wvX.js} +1 -1
  16. package/dist/assets/{chunk-QZHKN3VN-CY_Ss3eu.js → chunk-QZHKN3VN-DJ8uGwmx.js} +1 -1
  17. package/dist/assets/classDiagram-4FO5ZUOK-DkhrU_NZ.js +1 -0
  18. package/dist/assets/classDiagram-v2-Q7XG4LA2-DkhrU_NZ.js +1 -0
  19. package/dist/assets/{cose-bilkent-S5V4N54A-pnuSB6UR.js → cose-bilkent-S5V4N54A-Di1XL2vj.js} +1 -1
  20. package/dist/assets/{dagre-BM42HDAG-DXul9ync.js → dagre-BM42HDAG-DCQmHJFe.js} +1 -1
  21. package/dist/assets/{diagram-2AECGRRQ-CzdHeSR9.js → diagram-2AECGRRQ-CIoTDcBh.js} +1 -1
  22. package/dist/assets/{diagram-5GNKFQAL-C2kms3K5.js → diagram-5GNKFQAL-eXz-XBDZ.js} +1 -1
  23. package/dist/assets/{diagram-KO2AKTUF-Cu2TAUqA.js → diagram-KO2AKTUF-BhP7dgyb.js} +1 -1
  24. package/dist/assets/{diagram-LMA3HP47-6BXm36Xf.js → diagram-LMA3HP47-CvF4PpB2.js} +1 -1
  25. package/dist/assets/{diagram-OG6HWLK6-Dqz8Gut2.js → diagram-OG6HWLK6-C6s7GpY0.js} +1 -1
  26. package/dist/assets/{erDiagram-TEJ5UH35-CtlTK-SE.js → erDiagram-TEJ5UH35-Ck6BPVlP.js} +1 -1
  27. package/dist/assets/{flowDiagram-I6XJVG4X-D77QxS-7.js → flowDiagram-I6XJVG4X-C16g3xy-.js} +1 -1
  28. package/dist/assets/{ganttDiagram-6RSMTGT7-CL4vof27.js → ganttDiagram-6RSMTGT7-Dj8_f5WA.js} +1 -1
  29. package/dist/assets/{gitGraphDiagram-PVQCEYII-DamrJOZp.js → gitGraphDiagram-PVQCEYII-CW1EUE5V.js} +1 -1
  30. package/dist/assets/{index-ChQGVzAE.js → index-DS3jYAHC.js} +69 -69
  31. package/dist/assets/{infoDiagram-5YYISTIA-rfHV73X4.js → infoDiagram-5YYISTIA-tVvy_A0i.js} +1 -1
  32. package/dist/assets/{ishikawaDiagram-YF4QCWOH-CdPWxGJX.js → ishikawaDiagram-YF4QCWOH-CFlWu8EG.js} +1 -1
  33. package/dist/assets/{journeyDiagram-JHISSGLW-BOi5LZYz.js → journeyDiagram-JHISSGLW-U2atTlal.js} +1 -1
  34. package/dist/assets/{kanban-definition-UN3LZRKU-BkiNAsiv.js → kanban-definition-UN3LZRKU-BuHzHZFc.js} +1 -1
  35. package/dist/assets/locales-CcBtm6Ky.js +1 -0
  36. package/dist/assets/{mindmap-definition-RKZ34NQL-TgKEuoPJ.js → mindmap-definition-RKZ34NQL-DsfXQioK.js} +1 -1
  37. package/dist/assets/{pieDiagram-4H26LBE5-CXa8qPan.js → pieDiagram-4H26LBE5-DSMuyJx3.js} +1 -1
  38. package/dist/assets/{quadrantDiagram-W4KKPZXB-DUrm8cWn.js → quadrantDiagram-W4KKPZXB-zCfGSXvL.js} +1 -1
  39. package/dist/assets/{requirementDiagram-4Y6WPE33-CiGDx-T3.js → requirementDiagram-4Y6WPE33-R7qj84TH.js} +1 -1
  40. package/dist/assets/{sankeyDiagram-5OEKKPKP-BS2J3gW3.js → sankeyDiagram-5OEKKPKP-B7Hu_h-R.js} +1 -1
  41. package/dist/assets/{sequenceDiagram-3UESZ5HK-p_DBICST.js → sequenceDiagram-3UESZ5HK-ONL4cscH.js} +1 -1
  42. package/dist/assets/{stateDiagram-AJRCARHV-DCc2dFRi.js → stateDiagram-AJRCARHV-DzqLSEO8.js} +1 -1
  43. package/dist/assets/{stateDiagram-v2-BHNVJYJU-8yygPWnM.js → stateDiagram-v2-BHNVJYJU-Cz0T5vOV.js} +1 -1
  44. package/dist/assets/{timeline-definition-PNZ67QCA-CP_cwSHQ.js → timeline-definition-PNZ67QCA-hn6ijLp0.js} +1 -1
  45. package/dist/assets/{vennDiagram-CIIHVFJN-DTwc-s5g.js → vennDiagram-CIIHVFJN-BRpVUYgJ.js} +1 -1
  46. package/dist/assets/{wardleyDiagram-YWT4CUSO-C9dwjGZ6.js → wardleyDiagram-YWT4CUSO-D9dBXp0j.js} +1 -1
  47. package/dist/assets/{xychartDiagram-2RQKCTM6-CHZUHUxu.js → xychartDiagram-2RQKCTM6-CrHD1Lkr.js} +1 -1
  48. package/dist/index.html +2 -2
  49. package/package.json +1 -1
  50. package/dist/assets/channel-DLn-0I6t.js +0 -1
  51. package/dist/assets/classDiagram-4FO5ZUOK-DnhYadg0.js +0 -1
  52. package/dist/assets/classDiagram-v2-Q7XG4LA2-DnhYadg0.js +0 -1
  53. package/dist/assets/locales-DqtY0sVQ.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MermaidRenderer-ZdYLQXe1.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-BUZ2s3dH.js","assets/locales-DqtY0sVQ.js","assets/vendor-markdown-Cy_-N5ZX.js","assets/vendor-markdown-dRWncRqa.css","assets/vendor-auth-aD_bwYde.js","assets/ChartRenderer-B9WgyQbh.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-CPc4ca0i.js","assets/papaparse.min-D13ujVVP.js","assets/docx-preview-DehBmhog.js"])))=>i.map(i=>d[i]);
2
- var $o=Object.defineProperty;var Ro=(t,e,s)=>e in t?$o(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var Ze=(t,e,s)=>Ro(t,typeof e!="symbol"?e+"":e,s);import{r as h,j as i,a as Po,R as gt,b as Ir,d as Do}from"./vendor-react-BbEy7z12.js";import{z as Uo,p as Oo,j as zo,f as Bo,e as Ho,a as Vo,d as qo}from"./locales-DqtY0sVQ.js";import{M as Wo,r as rn,a as Ko,b as Go}from"./vendor-markdown-Cy_-N5ZX.js";import{_ as Ct,h as Xo,v as Yo,a as Qo}from"./vendor-syntax-INF7-xC_.js";import{u as Ca,a as Aa,b as Zo,P as Jo,M as el,A as tl}from"./vendor-auth-aD_bwYde.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))a(r);new MutationObserver(r=>{for(const n of r)if(n.type==="childList")for(const o of n.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&a(o)}).observe(document,{childList:!0,subtree:!0});function s(r){const n={};return r.integrity&&(n.integrity=r.integrity),r.referrerPolicy&&(n.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?n.credentials="include":r.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function a(r){if(r.ep)return;r.ep=!0;const n=s(r);fetch(r.href,n)}})();const hi=h.createContext(void 0);function an({children:t}){const[e,s]=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}}),[a,r]=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,r(l);const c=document.documentElement;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 n=o=>{s(l=>({...l,...o}))};return i.jsx(hi.Provider,{value:{theme:e,updateTheme:n,isDark:a},children:t})}function ts(){const t=h.useContext(hi);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}const pi=h.createContext(void 0),Xr={voiceEnabled:!1,soundEnabled:!1,autoSend:!1};function sl({children:t}){const[e,s]=h.useState(()=>{const r=localStorage.getItem("chat-settings");if(r)try{const n=JSON.parse(r);return{...Xr,...n,voiceEnabled:!1}}catch{return Xr}return Xr});h.useEffect(()=>{localStorage.setItem("chat-settings",JSON.stringify(e))},[e]);const a=r=>{s(n=>({...n,...r}))};return i.jsx(pi.Provider,{value:{settings:e,updateSettings:a},children:t})}function Lr(){const t=h.useContext(pi);if(!t)throw new Error("useSettings must be used within SettingsProvider");return t}const he=t=>typeof t=="string",Is=()=>{let t,e;const s=new Promise((a,r)=>{t=a,e=r});return s.resolve=t,s.reject=e,s},nn=t=>t==null?"":String(t),rl=(t,e,s)=>{t.forEach(a=>{e[a]&&(s[a]=e[a])})},al=/###/g,on=t=>t&&t.includes("###")?t.replace(al,"."):t,ln=t=>!t||he(t),Ts=(t,e,s)=>{const a=he(e)?e.split("."):e;let r=0;for(;r<a.length-1;){if(ln(t))return{};const n=on(a[r]);!t[n]&&s&&(t[n]=new s),Object.prototype.hasOwnProperty.call(t,n)?t=t[n]:t={},++r}return ln(t)?{}:{obj:t,k:on(a[r])}},cn=(t,e,s)=>{const{obj:a,k:r}=Ts(t,e,Object);if(a!==void 0||e.length===1){a[r]=s;return}let n=e[e.length-1],o=e.slice(0,e.length-1),l=Ts(t,o,Object);for(;l.obj===void 0&&o.length;)n=`${o[o.length-1]}.${n}`,o=o.slice(0,o.length-1),l=Ts(t,o,Object),l!=null&&l.obj&&typeof l.obj[`${l.k}.${n}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${n}`]=s},nl=(t,e,s,a)=>{const{obj:r,k:n}=Ts(t,e,Object);r[n]=r[n]||[],r[n].push(s)},xr=(t,e)=>{const{obj:s,k:a}=Ts(t,e);if(s&&Object.prototype.hasOwnProperty.call(s,a))return s[a]},il=(t,e,s)=>{const a=xr(t,s);return a!==void 0?a:xr(e,s)},mi=(t,e,s)=>{for(const a in e)a!=="__proto__"&&a!=="constructor"&&(Object.prototype.hasOwnProperty.call(t,a)?he(t[a])||t[a]instanceof String||he(e[a])||e[a]instanceof String?s&&(t[a]=e[a]):mi(t[a],e[a],s):t[a]=e[a]);return t},Lt=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),ol={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"},ll=t=>he(t)?t.replace(/[&<>"'\/]/g,e=>ol[e]):t;class cl{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const s=this.regExpMap.get(e);if(s!==void 0)return s;const a=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,a),this.regExpQueue.push(e),a}}const dl=[" ",",","?","!",";"],ul=new cl(20),fl=(t,e,s)=>{e=e||"",s=s||"";const a=dl.filter(o=>!e.includes(o)&&!s.includes(o));if(a.length===0)return!0;const r=ul.getRegExp(`(${a.map(o=>o==="?"?"\\?":o).join("|")})`);let n=!r.test(t);if(!n){const o=t.indexOf(s);o>0&&!r.test(t.substring(0,o))&&(n=!0)}return n},la=(t,e,s=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const a=e.split(s);let r=t;for(let n=0;n<a.length;){if(!r||typeof r!="object")return;let o,l="";for(let c=n;c<a.length;++c)if(c!==n&&(l+=s),l+=a[c],o=r[l],o!==void 0){if(["string","number","boolean"].includes(typeof o)&&c<a.length-1)continue;n+=c-n+1;break}r=o}return r},Rs=t=>t==null?void 0:t.replace(/_/g,"-"),hl={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){var s,a;(a=(s=console==null?void 0:console[t])==null?void 0:s.apply)==null||a.call(s,console,e)}};class br{constructor(e,s={}){this.init(e,s)}init(e,s={}){this.prefix=s.prefix||"i18next:",this.logger=e||hl,this.options=s,this.debug=s.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,s,a,r){return r&&!this.debug?null:(e=e.map(n=>he(n)?n.replace(/[\r\n\x00-\x1F\x7F]/g," "):n),he(e[0])&&(e[0]=`${a}${this.prefix} ${e[0]}`),this.logger[s](e))}create(e){return new br(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new br(this.logger,e)}}var At=new br;class Er{constructor(){this.observers={}}on(e,s){return e.split(" ").forEach(a=>{this.observers[a]||(this.observers[a]=new Map);const r=this.observers[a].get(s)||0;this.observers[a].set(s,r+1)}),this}off(e,s){if(this.observers[e]){if(!s){delete this.observers[e];return}this.observers[e].delete(s)}}once(e,s){const a=(...r)=>{s(...r),this.off(e,a)};return this.on(e,a),this}emit(e,...s){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([r,n])=>{for(let o=0;o<n;o++)r(...s)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([r,n])=>{for(let o=0;o<n;o++)r(e,...s)})}}class dn extends Er{constructor(e,s={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=s,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 s=this.options.ns.indexOf(e);s>-1&&this.options.ns.splice(s,1)}getResource(e,s,a,r={}){var d,u;const n=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator,o=r.ignoreJSONStructure!==void 0?r.ignoreJSONStructure:this.options.ignoreJSONStructure;let l;e.includes(".")?l=e.split("."):(l=[e,s],a&&(Array.isArray(a)?l.push(...a):he(a)&&n?l.push(...a.split(n)):l.push(a)));const c=xr(this.data,l);return!c&&!s&&!a&&e.includes(".")&&(e=l[0],s=l[1],a=l.slice(2).join(".")),c||!o||!he(a)?c:la((u=(d=this.data)==null?void 0:d[e])==null?void 0:u[s],a,n)}addResource(e,s,a,r,n={silent:!1}){const o=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let l=[e,s];a&&(l=l.concat(o?a.split(o):a)),e.includes(".")&&(l=e.split("."),r=s,s=l[1]),this.addNamespaces(s),cn(this.data,l,r),n.silent||this.emit("added",e,s,a,r)}addResources(e,s,a,r={silent:!1}){for(const n in a)(he(a[n])||Array.isArray(a[n]))&&this.addResource(e,s,n,a[n],{silent:!0});r.silent||this.emit("added",e,s,a)}addResourceBundle(e,s,a,r,n,o={silent:!1,skipCopy:!1}){let l=[e,s];e.includes(".")&&(l=e.split("."),r=a,a=s,s=l[1]),this.addNamespaces(s);let c=xr(this.data,l)||{};o.skipCopy||(a=JSON.parse(JSON.stringify(a))),r?mi(c,a,n):c={...c,...a},cn(this.data,l,c),o.silent||this.emit("added",e,s,a)}removeResourceBundle(e,s){this.hasResourceBundle(e,s)&&delete this.data[e][s],this.removeNamespaces(s),this.emit("removed",e,s)}hasResourceBundle(e,s){return this.getResource(e,s)!==void 0}getResourceBundle(e,s){return s||(s=this.options.defaultNS),this.getResource(e,s)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const s=this.getDataByLanguage(e);return!!(s&&Object.keys(s)||[]).find(r=>s[r]&&Object.keys(s[r]).length>0)}toJSON(){return this.data}}var gi={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,s,a,r){return t.forEach(n=>{var o;e=((o=this.processors[n])==null?void 0:o.process(e,s,a,r))??e}),e}};const xi=Symbol("i18next/PATH_KEY");function pl(){const t=[],e=Object.create(null);let s;return e.get=(a,r)=>{var n;return(n=s==null?void 0:s.revoke)==null||n.call(s),r===xi?t:(t.push(r),s=Proxy.revocable(a,e),s.proxy)},Proxy.revocable(Object.create(null),e).proxy}function cs(t,e){const{[xi]:s}=t(pl()),a=(e==null?void 0:e.keySeparator)??".",r=(e==null?void 0:e.nsSeparator)??":",n=(e==null?void 0:e.enableSelector)==="strict";if(s.length>1&&r){const o=e==null?void 0:e.ns,l=n?Array.isArray(o)?o:o?[o]:null:Array.isArray(o)?o:null;if(l&&(n?l:l.length>1?l.slice(1):[]).includes(s[0]))return`${s[0]}${r}${s.slice(1).join(a)}`}return s.join(a)}const Yr=t=>!he(t)&&typeof t!="boolean"&&typeof t!="number";class yr extends Er{constructor(e,s={}){super(),rl(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=s,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=At.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,s={interpolation:{}}){const a={...s};if(e==null)return!1;const r=this.resolve(e,a);if((r==null?void 0:r.res)===void 0)return!1;const n=Yr(r.res);return!(a.returnObjects===!1&&n)}extractFromKey(e,s){let a=s.nsSeparator!==void 0?s.nsSeparator:this.options.nsSeparator;a===void 0&&(a=":");const r=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let n=s.ns||this.options.defaultNS||[];const o=a&&e.includes(a),l=!this.options.userDefinedKeySeparator&&!s.keySeparator&&!this.options.userDefinedNsSeparator&&!s.nsSeparator&&!fl(e,a,r);if(o&&!l){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:he(n)?[n]:n};const d=e.split(a);(a!==r||a===r&&this.options.ns.includes(d[0]))&&(n=d.shift()),e=d.join(r)}return{key:e,namespaces:he(n)?[n]:n}}translate(e,s,a){let r=typeof s=="object"?{...s}:s;if(typeof r!="object"&&this.options.overloadTranslationOptionHandler&&(r=this.options.overloadTranslationOptionHandler(arguments)),typeof r=="object"&&(r={...r}),r||(r={}),e==null)return"";typeof e=="function"&&(e=cs(e,{...this.options,...r})),Array.isArray(e)||(e=[String(e)]),e=e.map(F=>typeof F=="function"?cs(F,{...this.options,...r}):String(F));const n=r.returnDetails!==void 0?r.returnDetails:this.options.returnDetails,o=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator,{key:l,namespaces:c}=this.extractFromKey(e[e.length-1],r),d=c[c.length-1];let u=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const f=r.lng||this.language,m=r.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if((f==null?void 0:f.toLowerCase())==="cimode")return m?n?{res:`${d}${u}${l}`,usedKey:l,exactUsedKey:l,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(r)}:`${d}${u}${l}`:n?{res:l,usedKey:l,exactUsedKey:l,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(r)}:l;const p=this.resolve(e,r);let g=p==null?void 0:p.res;const x=(p==null?void 0:p.usedKey)||l,y=(p==null?void 0:p.exactUsedKey)||l,k=["[object Number]","[object Function]","[object RegExp]"],A=r.joinArrays!==void 0?r.joinArrays:this.options.joinArrays,L=!this.i18nFormat||this.i18nFormat.handleAsObject,C=r.count!==void 0&&!he(r.count),v=yr.hasDefaultValue(r),N=C?this.pluralResolver.getSuffix(f,r.count,r):"",R=r.ordinal&&C?this.pluralResolver.getSuffix(f,r.count,{ordinal:!1}):"",b=C&&!r.ordinal&&r.count===0,_=b&&r[`defaultValue${this.options.pluralSeparator}zero`]||r[`defaultValue${N}`]||r[`defaultValue${R}`]||r.defaultValue;let S=g;L&&!g&&v&&(S=_);const I=Yr(S),M=Object.prototype.toString.apply(S);if(L&&S&&I&&!k.includes(M)&&!(he(A)&&Array.isArray(S))){if(!r.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const F=this.options.returnedObjectHandler?this.options.returnedObjectHandler(x,S,{...r,ns:c}):`key '${l} (${this.language})' returned an object instead of string.`;return n?(p.res=F,p.usedParams=this.getUsedParamsDetails(r),p):F}if(o){const F=Array.isArray(S),B=F?[]:{},j=F?y:x;for(const E in S)if(Object.prototype.hasOwnProperty.call(S,E)){const P=`${j}${o}${E}`;v&&!g?B[E]=this.translate(P,{...r,defaultValue:Yr(_)?_[E]:void 0,joinArrays:!1,ns:c}):B[E]=this.translate(P,{...r,joinArrays:!1,ns:c}),B[E]===P&&(B[E]=S[E])}g=B}}else if(L&&he(A)&&Array.isArray(g))g=g.join(A),g&&(g=this.extendTranslation(g,e,r,a));else{let F=!1,B=!1;!this.isValidLookup(g)&&v&&(F=!0,g=_),this.isValidLookup(g)||(B=!0,g=l);const E=(r.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&B?void 0:g,P=v&&_!==g&&this.options.updateMissing;if(B||F||P){if(this.logger.log(P?"updateKey":"missingKey",f,d,C&&!P?`${l}${this.pluralResolver.getSuffix(f,r.count,r)}`:l,P?_:g),o){const V=this.resolve(l,{...r,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 T=[];const K=this.languageUtils.getFallbackCodes(this.options.fallbackLng,r.lng||this.language);if(this.options.saveMissingTo==="fallback"&&K&&K[0])for(let V=0;V<K.length;V++)T.push(K[V]);else this.options.saveMissingTo==="all"?T=this.languageUtils.toResolveHierarchy(r.lng||this.language):T.push(r.lng||this.language);const G=(V,Z,ue)=>{var te;const O=v&&ue!==g?ue:E;this.options.missingKeyHandler?this.options.missingKeyHandler(V,d,Z,O,P,r):(te=this.backendConnector)!=null&&te.saveMissing&&this.backendConnector.saveMissing(V,d,Z,O,P,r),this.emit("missingKey",V,d,Z,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&C?T.forEach(V=>{const Z=this.pluralResolver.getSuffixes(V,r);b&&r[`defaultValue${this.options.pluralSeparator}zero`]&&!Z.includes(`${this.options.pluralSeparator}zero`)&&Z.push(`${this.options.pluralSeparator}zero`),Z.forEach(ue=>{G([V],l+ue,r[`defaultValue${ue}`]||_)})}):G(T,l,_))}g=this.extendTranslation(g,e,r,p,a),B&&g===l&&this.options.appendNamespaceToMissingKey&&(g=`${d}${u}${l}`),(B||F)&&this.options.parseMissingKeyHandler&&(g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${l}`:l,F?g:void 0,r))}return n?(p.res=g,p.usedParams=this.getUsedParamsDetails(r),p):g}extendTranslation(e,s,a,r,n){var c,d;if((c=this.i18nFormat)!=null&&c.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...a},a.lng||this.language||r.usedLng,r.usedNS,r.usedKey,{resolved:r});else if(!a.skipInterpolation){a.interpolation&&this.interpolator.init({...a,interpolation:{...this.options.interpolation,...a.interpolation}});const u=he(e)&&(((d=a==null?void 0:a.interpolation)==null?void 0:d.skipOnVariables)!==void 0?a.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let f;if(u){const p=e.match(this.interpolator.nestingRegexp);f=p&&p.length}let m=a.replace&&!he(a.replace)?a.replace:a;if(this.options.interpolation.defaultVariables&&(m={...this.options.interpolation.defaultVariables,...m}),e=this.interpolator.interpolate(e,m,a.lng||this.language||r.usedLng,a),u){const p=e.match(this.interpolator.nestingRegexp),g=p&&p.length;f<g&&(a.nest=!1)}!a.lng&&r&&r.res&&(a.lng=this.language||r.usedLng),a.nest!==!1&&(e=this.interpolator.nest(e,(...p)=>(n==null?void 0:n[0])===p[0]&&!a.context?(this.logger.warn(`It seems you are nesting recursively key: ${p[0]} in key: ${s[0]}`),null):this.translate(...p,s),a)),a.interpolation&&this.interpolator.reset()}const o=a.postProcess||this.options.postProcess,l=he(o)?[o]:o;return e!=null&&(l!=null&&l.length)&&a.applyPostProcessor!==!1&&(e=gi.handle(l,e,s,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...r,usedParams:this.getUsedParamsDetails(a)},...a}:a,this)),e}resolve(e,s={}){let a,r,n,o,l;return he(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(c=>typeof c=="function"?cs(c,{...this.options,...s}):c)),e.forEach(c=>{if(this.isValidLookup(a))return;const d=this.extractFromKey(c,s),u=d.key;r=u;let f=d.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const m=s.count!==void 0&&!he(s.count),p=m&&!s.ordinal&&s.count===0,g=s.context!==void 0&&(he(s.context)||typeof s.context=="number")&&s.context!=="",x=s.lngs?s.lngs:this.languageUtils.toResolveHierarchy(s.lng||this.language,s.fallbackLng);f.forEach(y=>{var k,A;this.isValidLookup(a)||(l=y,!this.checkedLoadedFor[`${x[0]}-${y}`]&&((k=this.utils)!=null&&k.hasLoadedNamespace)&&!((A=this.utils)!=null&&A.hasLoadedNamespace(l))&&(this.checkedLoadedFor[`${x[0]}-${y}`]=!0,this.logger.warn(`key "${r}" 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(L=>{var N;if(this.isValidLookup(a))return;o=L;const C=[u];if((N=this.i18nFormat)!=null&&N.addLookupKeys)this.i18nFormat.addLookupKeys(C,u,L,y,s);else{let R;m&&(R=this.pluralResolver.getSuffix(L,s.count,s));const b=`${this.options.pluralSeparator}zero`,_=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(m&&(s.ordinal&&R.startsWith(_)&&C.push(u+R.replace(_,this.options.pluralSeparator)),C.push(u+R),p&&C.push(u+b)),g){const S=`${u}${this.options.contextSeparator||"_"}${s.context}`;C.push(S),m&&(s.ordinal&&R.startsWith(_)&&C.push(S+R.replace(_,this.options.pluralSeparator)),C.push(S+R),p&&C.push(S+b))}}let v;for(;v=C.pop();)this.isValidLookup(a)||(n=v,a=this.getResource(L,y,v,s))}))})}),{res:a,usedKey:r,exactUsedKey:n,usedLng:o,usedNS:l}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,s,a,r={}){var n;return(n=this.i18nFormat)!=null&&n.getResource?this.i18nFormat.getResource(e,s,a,r):this.resourceStore.getResource(e,s,a,r)}getUsedParamsDetails(e={}){const s=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],a=e.replace&&!he(e.replace);let r=a?e.replace:e;if(a&&typeof e.count<"u"&&(r.count=e.count),this.options.interpolation.defaultVariables&&(r={...this.options.interpolation.defaultVariables,...r}),!a){r={...r};for(const n of s)delete r[n]}return r}static hasDefaultValue(e){const s="defaultValue";for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a)&&a.startsWith(s)&&e[a]!==void 0)return!0;return!1}}class un{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=At.create("languageUtils")}getScriptPartFromCode(e){if(e=Rs(e),!e||!e.includes("-"))return null;const s=e.split("-");return s.length===2||(s.pop(),s[s.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(s.join("-"))}getLanguagePartFromCode(e){if(e=Rs(e),!e||!e.includes("-"))return e;const s=e.split("-");return this.formatLanguageCode(s[0])}formatLanguageCode(e){if(he(e)&&e.includes("-")){let s;try{s=Intl.getCanonicalLocales(e)[0]}catch{}return s&&this.options.lowerCaseLng&&(s=s.toLowerCase()),s||(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 s;return e.forEach(a=>{if(s)return;const r=this.formatLanguageCode(a);(!this.options.supportedLngs||this.isSupportedCode(r))&&(s=r)}),!s&&this.options.supportedLngs&&e.forEach(a=>{if(s)return;const r=this.getScriptPartFromCode(a);if(this.isSupportedCode(r))return s=r;const n=this.getLanguagePartFromCode(a);if(this.isSupportedCode(n))return s=n;s=this.options.supportedLngs.find(o=>o===n?!0:!o.includes("-")&&!n.includes("-")?!1:!!(o.includes("-")&&!n.includes("-")&&o.slice(0,o.indexOf("-"))===n||o.startsWith(n)&&n.length>1))}),s||(s=this.getFallbackCodes(this.options.fallbackLng)[0]),s}getFallbackCodes(e,s){if(!e)return[];if(typeof e=="function"&&(e=e(s)),he(e)&&(e=[e]),Array.isArray(e))return e;if(!s)return e.default||[];let a=e[s];return a||(a=e[this.getScriptPartFromCode(s)]),a||(a=e[this.formatLanguageCode(s)]),a||(a=e[this.getLanguagePartFromCode(s)]),a||(a=e.default),a||[]}toResolveHierarchy(e,s){const a=this.getFallbackCodes((s===!1?[]:s)||this.options.fallbackLng||[],e),r=[],n=o=>{o&&(this.isSupportedCode(o)?r.push(o):this.logger.warn(`rejecting language code not found in supportedLngs: ${o}`))};return he(e)&&(e.includes("-")||e.includes("_"))?(this.options.load!=="languageOnly"&&n(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&n(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&n(this.getLanguagePartFromCode(e))):he(e)&&n(this.formatLanguageCode(e)),a.forEach(o=>{r.includes(o)||n(this.formatLanguageCode(o))}),r}}const fn={zero:0,one:1,two:2,few:3,many:4,other:5},hn={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class ml{constructor(e,s={}){this.languageUtils=e,this.options=s,this.logger=At.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,s={}){const a=Rs(e==="dev"?"en":e),r=s.ordinal?"ordinal":"cardinal",n=JSON.stringify({cleanedCode:a,type:r});if(n in this.pluralRulesCache)return this.pluralRulesCache[n];let o;try{o=new Intl.PluralRules(a,{type:r})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),hn;if(!e.match(/-|_/))return hn;const c=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(c,s)}return this.pluralRulesCache[n]=o,o}needsPlural(e,s={}){let a=this.getRule(e,s);return a||(a=this.getRule("dev",s)),(a==null?void 0:a.resolvedOptions().pluralCategories.length)>1}getPluralFormsOfKey(e,s,a={}){return this.getSuffixes(e,a).map(r=>`${s}${r}`)}getSuffixes(e,s={}){let a=this.getRule(e,s);return a||(a=this.getRule("dev",s)),a?a.resolvedOptions().pluralCategories.sort((r,n)=>fn[r]-fn[n]).map(r=>`${this.options.prepend}${s.ordinal?`ordinal${this.options.prepend}`:""}${r}`):[]}getSuffix(e,s,a={}){const r=this.getRule(e,a);return r?`${this.options.prepend}${a.ordinal?`ordinal${this.options.prepend}`:""}${r.select(s)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",s,a))}}const pn=(t,e,s,a=".",r=!0)=>{let n=il(t,e,s);return!n&&r&&he(s)&&(n=la(t,s,a),n===void 0&&(n=la(e,s,a))),n},Qr=t=>t.replace(/\$/g,"$$$$");class mn{constructor(e={}){var s;this.logger=At.create("interpolator"),this.options=e,this.format=((s=e==null?void 0:e.interpolation)==null?void 0:s.format)||(a=>a),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:s,escapeValue:a,useRawValueToEscape:r,prefix:n,prefixEscaped:o,suffix:l,suffixEscaped:c,formatSeparator:d,unescapeSuffix:u,unescapePrefix:f,nestingPrefix:m,nestingPrefixEscaped:p,nestingSuffix:g,nestingSuffixEscaped:x,nestingOptionsSeparator:y,maxReplaces:k,alwaysFormat:A}=e.interpolation;this.escape=s!==void 0?s:ll,this.escapeValue=a!==void 0?a:!0,this.useRawValueToEscape=r!==void 0?r:!1,this.prefix=n?Lt(n):o||"{{",this.suffix=l?Lt(l):c||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":f?Lt(f):"-",this.unescapeSuffix=this.unescapePrefix?"":u?Lt(u):"",this.nestingPrefix=m?Lt(m):p||Lt("$t("),this.nestingSuffix=g?Lt(g):x||Lt(")"),this.nestingOptionsSeparator=y||",",this.maxReplaces=k||1e3,this.alwaysFormat=A!==void 0?A:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(s,a)=>(s==null?void 0:s.source)===a?(s.lastIndex=0,s):new RegExp(a,"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,s,a,r){var p;let n,o,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=g=>{if(!g.includes(this.formatSeparator)){const A=pn(s,c,g,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(A,void 0,a,{...r,...s,interpolationkey:g}):A}const x=g.split(this.formatSeparator),y=x.shift().trim(),k=x.join(this.formatSeparator).trim();return this.format(pn(s,c,y,this.options.keySeparator,this.options.ignoreJSONStructure),k,a,{...r,...s,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=(r==null?void 0:r.missingInterpolationHandler)||this.options.missingInterpolationHandler,f=((p=r==null?void 0:r.interpolation)==null?void 0:p.skipOnVariables)!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:g=>Qr(g)},{regex:this.regexp,safeValue:g=>this.escapeValue?Qr(this.escape(g)):Qr(g)}].forEach(g=>{for(l=0;n=g.regex.exec(e);){const x=n[1].trim();if(o=d(x),o===void 0)if(typeof u=="function"){const k=u(e,n,r);o=he(k)?k:""}else if(r&&Object.prototype.hasOwnProperty.call(r,x))o="";else if(f){o=n[0];continue}else this.logger.warn(`missed to pass in variable ${x} for interpolating ${e}`),o="";else!he(o)&&!this.useRawValueToEscape&&(o=nn(o));const y=g.safeValue(o);if(e=e.replace(n[0],y),f?(g.regex.lastIndex+=o.length,g.regex.lastIndex-=n[0].length):g.regex.lastIndex=0,l++,l>=this.maxReplaces)break}}),e}nest(e,s,a={}){let r,n,o;const l=(c,d)=>{const u=this.nestingOptionsSeparator;if(!c.includes(u))return c;const f=c.split(new RegExp(`${Lt(u)}[ ]*{`));let m=`{${f[1]}`;c=f[0],m=this.interpolate(m,o);const p=m.match(/'/g),g=m.match(/"/g);(((p==null?void 0:p.length)??0)%2===0&&!g||((g==null?void 0:g.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(;r=this.nestingRegexp.exec(e);){let c=[];o={...a},o=o.replace&&!he(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const d=/{.*}/.test(r[1])?r[1].lastIndexOf("}")+1:r[1].indexOf(this.formatSeparator);if(d!==-1&&(c=r[1].slice(d).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),r[1]=r[1].slice(0,d)),n=s(l.call(this,r[1].trim(),o),o),n&&r[0]===e&&!he(n))return n;he(n)||(n=nn(n)),n||(this.logger.warn(`missed to resolve ${r[1]} for nesting ${e}`),n=""),c.length&&(n=c.reduce((u,f)=>this.format(u,f,a.lng,{...a,interpolationkey:r[1].trim()}),n.trim())),e=e.replace(r[0],n),this.regexp.lastIndex=0}return e}}const gl=t=>{let e=t.toLowerCase().trim();const s={};if(t.includes("(")){const a=t.split("(");e=a[0].toLowerCase().trim();const r=a[1].slice(0,-1);e==="currency"&&!r.includes(":")?s.currency||(s.currency=r.trim()):e==="relativetime"&&!r.includes(":")?s.range||(s.range=r.trim()):r.split(";").forEach(o=>{if(o){const[l,...c]=o.split(":"),d=c.join(":").trim().replace(/^'+|'+$/g,""),u=l.trim();s[u]||(s[u]=d),d==="false"&&(s[u]=!1),d==="true"&&(s[u]=!0),isNaN(d)||(s[u]=parseInt(d,10))}})}return{formatName:e,formatOptions:s}},gn=t=>{const e={};return(s,a,r)=>{let n=r;r&&r.interpolationkey&&r.formatParams&&r.formatParams[r.interpolationkey]&&r[r.interpolationkey]&&(n={...n,[r.interpolationkey]:void 0});const o=a+JSON.stringify(n);let l=e[o];return l||(l=t(Rs(a),r),e[o]=l),l(s)}},xl=t=>(e,s,a)=>t(Rs(s),a)(e);class bl{constructor(e={}){this.logger=At.create("formatter"),this.options=e,this.init(e)}init(e,s={interpolation:{}}){this.formatSeparator=s.interpolation.formatSeparator||",";const a=s.cacheInBuiltFormats?gn:xl;this.formats={number:a((r,n)=>{const o=new Intl.NumberFormat(r,{...n});return l=>o.format(l)}),currency:a((r,n)=>{const o=new Intl.NumberFormat(r,{...n,style:"currency"});return l=>o.format(l)}),datetime:a((r,n)=>{const o=new Intl.DateTimeFormat(r,{...n});return l=>o.format(l)}),relativetime:a((r,n)=>{const o=new Intl.RelativeTimeFormat(r,{...n});return l=>o.format(l,n.range||"day")}),list:a((r,n)=>{const o=new Intl.ListFormat(r,{...n});return l=>o.format(l)})}}add(e,s){this.formats[e.toLowerCase().trim()]=s}addCached(e,s){this.formats[e.toLowerCase().trim()]=gn(s)}format(e,s,a,r={}){if(!s||e==null)return e;const n=s.split(this.formatSeparator),o=[];for(let c=0;c<n.length;c++){let d=n[c];for(;d.indexOf("(")>-1&&!d.includes(")")&&c+1<n.length;)d=`${d}${this.formatSeparator}${n[++c]}`;o.push(d)}return o.reduce((c,d)=>{var m;const{formatName:u,formatOptions:f}=gl(d);if(this.formats[u]){let p=c;try{const g=((m=r==null?void 0:r.formatParams)==null?void 0:m[r.interpolationkey])||{},x=g.locale||g.lng||r.locale||r.lng||a;p=this.formats[u](c,x,{...f,...r,...g})}catch(g){this.logger.warn(g)}return p}else this.logger.warn(`there was no format function for ${u}`);return c},e)}}const yl=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class wl extends Er{constructor(e,s,a,r={}){var n,o;super(),this.backend=e,this.store=s,this.services=a,this.languageUtils=a.languageUtils,this.options=r,this.logger=At.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=r.maxParallelReads||10,this.readingCalls=0,this.maxRetries=r.maxRetries>=0?r.maxRetries:5,this.retryTimeout=r.retryTimeout>=1?r.retryTimeout:350,this.state={},this.queue=[],(o=(n=this.backend)==null?void 0:n.init)==null||o.call(n,a,r.backend,r)}queueLoad(e,s,a,r){const n={},o={},l={},c={};return e.forEach(d=>{let u=!0;s.forEach(f=>{const m=`${d}|${f}`;!a.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),n[m]===void 0&&(n[m]=!0),c[f]===void 0&&(c[f]=!0)))}),u||(l[d]=!0)}),(Object.keys(n).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:r}),{toLoad:Object.keys(n),pending:Object.keys(o),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(e,s,a){const r=e.split("|"),n=r[0],o=r[1];s&&this.emit("failedLoading",n,o,s),!s&&a&&this.store.addResourceBundle(n,o,a,void 0,void 0,{skipCopy:!0}),this.state[e]=s?-1:2,s&&a&&(this.state[e]=0);const l={};this.queue.forEach(c=>{nl(c.loaded,[n],o),yl(c,e),s&&c.errors.push(s),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,s,a,r=0,n=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:s,fcName:a,tried:r,wait:n,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&&r<this.maxRetries){setTimeout(()=>{this.read(e,s,a,r+1,n*2,o)},n);return}o(d,u)},c=this.backend[a].bind(this.backend);if(c.length===2){try{const d=c(e,s);d&&typeof d.then=="function"?d.then(u=>l(null,u)).catch(l):l(null,d)}catch(d){l(d)}return}return c(e,s,l)}prepareLoading(e,s,a={},r){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),r&&r();he(e)&&(e=this.languageUtils.toResolveHierarchy(e)),he(s)&&(s=[s]);const n=this.queueLoad(e,s,a,r);if(!n.toLoad.length)return n.pending.length||r(),null;n.toLoad.forEach(o=>{this.loadOne(o)})}load(e,s,a){this.prepareLoading(e,s,{},a)}reload(e,s,a){this.prepareLoading(e,s,{reload:!0},a)}loadOne(e,s=""){const a=e.split("|"),r=a[0],n=a[1];this.read(r,n,"read",void 0,void 0,(o,l)=>{o&&this.logger.warn(`${s}loading namespace ${n} for language ${r} failed`,o),!o&&l&&this.logger.log(`${s}loaded namespace ${n} for language ${r}`,l),this.loaded(e,o,l)})}saveMissing(e,s,a,r,n,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(s))){this.logger.warn(`did not save key "${a}" as the namespace "${s}" 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(!(a==null||a==="")){if((m=this.backend)!=null&&m.create){const p={...o,isUpdate:n},g=this.backend.create.bind(this.backend);if(g.length<6)try{let x;g.length===5?x=g(e,s,a,r,p):x=g(e,s,a,r),x&&typeof x.then=="function"?x.then(y=>l(null,y)).catch(l):l(null,x)}catch(x){l(x)}else g(e,s,a,r,l,p)}!e||!e[0]||this.store.addResource(e[0],s,a,r)}}}const Zr=()=>({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 s=t[3]||t[2];Object.keys(s).forEach(a=>{e[a]=s[a]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),xn=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),sr=()=>{},kl=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(s=>{typeof t[s]=="function"&&(t[s]=t[s].bind(t))})};class Ms extends Er{constructor(e={},s){if(super(),this.options=xn(e),this.services={},this.logger=At,this.modules={external:[]},kl(this),s&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,s),this;setTimeout(()=>{this.init(e,s)},0)}}init(e={},s){this.isInitializing=!0,typeof e=="function"&&(s=e,e={}),e.defaultNS==null&&e.ns&&(he(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const a=Zr();this.options={...a,...this.options,...xn(e)},this.options.interpolation={...a.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=a.overloadTranslationOptionHandler);const r=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?At.init(r(this.modules.logger),this.options):At.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=bl;const u=new un(this.options);this.store=new dn(this.options.resources,this.options);const f=this.services;f.logger=At,f.resourceStore=this.store,f.languageUtils=u,f.pluralResolver=new ml(u,{prepend:this.options.pluralSeparator}),d&&(f.formatter=r(d),f.formatter.init&&f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new mn(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new wl(r(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(m,...p)=>{this.emit(m,...p)}),this.modules.languageDetector&&(f.languageDetector=r(this.modules.languageDetector),f.languageDetector.init&&f.languageDetector.init(f,this.options.detection,this.options)),this.modules.i18nFormat&&(f.i18nFormat=r(this.modules.i18nFormat),f.i18nFormat.init&&f.i18nFormat.init(this)),this.translator=new yr(this.services,this.options),this.translator.on("*",(m,...p)=>{this.emit(m,...p)}),this.modules.external.forEach(m=>{m.init&&m.init(this)})}if(this.format=this.options.interpolation.format,s||(s=sr),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=Is(),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),s(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,s=sr){var n,o;let a=s;const r=he(e)?e:this.language;if(typeof e=="function"&&(a=e),!this.options.resources||this.options.partialBundledLanguages){if((r==null?void 0:r.toLowerCase())==="cimode"&&(!this.options.preload||this.options.preload.length===0))return a();const l=[],c=d=>{if(!d||d==="cimode")return;this.services.languageUtils.toResolveHierarchy(d).forEach(f=>{f!=="cimode"&&(l.includes(f)||l.push(f))})};r?c(r):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>c(u)),(o=(n=this.options.preload)==null?void 0:n.forEach)==null||o.call(n,d=>c(d)),this.services.backendConnector.load(l,this.options.ns,d=>{!d&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),a(d)})}else a(null)}reloadResources(e,s,a){const r=Is();return typeof e=="function"&&(a=e,e=void 0),typeof s=="function"&&(a=s,s=void 0),e||(e=this.languages),s||(s=this.options.ns),a||(a=sr),this.services.backendConnector.reload(e,s,n=>{r.resolve(),a(n)}),r}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"&&gi.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 s=0;s<this.languages.length;s++){const a=this.languages[s];if(!["cimode","dev"].includes(a)&&this.store.hasLanguageSomeTranslations(a)){this.resolvedLanguage=a;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,s){this.isLanguageChangingTo=e;const a=Is();this.emit("languageChanging",e);const r=l=>{this.language=l,this.languages=this.services.languageUtils.toResolveHierarchy(l),this.resolvedLanguage=void 0,this.setResolvedLanguage(l)},n=(l,c)=>{c?this.isLanguageChangingTo===e&&(r(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,a.resolve((...d)=>this.t(...d)),s&&s(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||r(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=>{n(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),a}getFixedT(e,s,a,r){const n=r==null?void 0:r.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||a||o.keyPrefix);const m={...this.options,...u};Array.isArray(n)&&!f&&(m.ns=n),typeof u.keyPrefix=="function"&&(u.keyPrefix=cs(u.keyPrefix,m));const p=this.options.keySeparator||".";let g;return u.keyPrefix&&Array.isArray(l)?g=l.map(x=>(typeof x=="function"&&(x=cs(x,m)),`${u.keyPrefix}${p}${x}`)):(typeof l=="function"&&(l=cs(l,m)),g=u.keyPrefix?`${u.keyPrefix}${p}${l}`:l),this.t(g,u)};return he(e)?o.lng=e:o.lngs=e,o.ns=s,o.keyPrefix=a,o}t(...e){var s;return(s=this.translator)==null?void 0:s.translate(...e)}exists(...e){var s;return(s=this.translator)==null?void 0:s.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,s={}){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 a=s.lng||this.resolvedLanguage||this.languages[0],r=this.options?this.options.fallbackLng:!1,n=this.languages[this.languages.length-1];if(a.toLowerCase()==="cimode")return!0;const o=(l,c)=>{const d=this.services.backendConnector.state[`${l}|${c}`];return d===-1||d===0||d===2};if(s.precheck){const l=s.precheck(this,o);if(l!==void 0)return l}return!!(this.hasResourceBundle(a,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(a,e)&&(!r||o(n,e)))}loadNamespaces(e,s){const a=Is();return this.options.ns?(he(e)&&(e=[e]),e.forEach(r=>{this.options.ns.includes(r)||this.options.ns.push(r)}),this.loadResources(r=>{a.resolve(),s&&s(r)}),a):(s&&s(),Promise.resolve())}loadLanguages(e,s){const a=Is();he(e)&&(e=[e]);const r=this.options.preload||[],n=e.filter(o=>!r.includes(o)&&this.services.languageUtils.isSupportedCode(o));return n.length?(this.options.preload=r.concat(n),this.loadResources(o=>{a.resolve(),s&&s(o)}),a):(s&&s(),Promise.resolve())}dir(e){var r,n;if(e||(e=this.resolvedLanguage||(((r=this.languages)==null?void 0:r.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 s=["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"],a=((n=this.services)==null?void 0:n.languageUtils)||new un(Zr());return e.toLowerCase().indexOf("-latn")>1?"ltr":s.includes(a.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},s){const a=new Ms(e,s);return a.createInstance=Ms.createInstance,a}cloneInstance(e={},s=sr){const a=e.forkResourceStore;a&&delete e.forkResourceStore;const r={...this.options,...e,isClone:!0},n=new Ms(r);if((e.debug!==void 0||e.prefix!==void 0)&&(n.logger=n.logger.clone(e)),["store","services","language"].forEach(l=>{n[l]=this[l]}),n.services={...this.services},n.services.utils={hasLoadedNamespace:n.hasLoadedNamespace.bind(n)},a){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),{});n.store=new dn(l,r),n.services.resourceStore=n.store}if(e.interpolation){const c={...Zr().interpolation,...this.options.interpolation,...e.interpolation},d={...r,interpolation:c};n.services.interpolator=new mn(d)}return n.translator=new yr(n.services,r),n.translator.on("*",(l,...c)=>{n.emit(l,...c)}),n.init(r,s),n.translator.options=r,n.translator.backendConnector.services.utils={hasLoadedNamespace:n.hasLoadedNamespace.bind(n)},n}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const Xe=Ms.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 vl=(t,e,s,a)=>{var n,o,l,c;const r=[s,{code:e,...a||{}}];if((o=(n=t==null?void 0:t.services)==null?void 0:n.logger)!=null&&o.forward)return t.services.logger.forward(r,"warn","react-i18next::",!0);es(r[0])&&(r[0]=`react-i18next:: ${r[0]}`),(c=(l=t==null?void 0:t.services)==null?void 0:l.logger)!=null&&c.warn?t.services.logger.warn(...r):console!=null&&console.warn&&console.warn(...r)},bn={},ca=(t,e,s,a)=>{es(s)&&bn[s]||(es(s)&&(bn[s]=new Date),vl(t,e,s,a))},bi=(t,e)=>()=>{if(t.isInitialized)e();else{const s=()=>{setTimeout(()=>{t.off("initialized",s)},0),e()};t.on("initialized",s)}},da=(t,e,s)=>{t.loadNamespaces(e,bi(t,s))},yn=(t,e,s,a)=>{if(es(s)&&(s=[s]),t.options.preload&&t.options.preload.indexOf(e)>-1)return da(t,s,a);s.forEach(r=>{t.options.ns.indexOf(r)<0&&t.options.ns.push(r)}),t.loadLanguages(e,bi(t,a))},Sl=(t,e,s={})=>!e.languages||!e.languages.length?(ca(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(t,{lng:s.lng,precheck:(a,r)=>{if(s.bindI18n&&s.bindI18n.indexOf("languageChanging")>-1&&a.services.backendConnector.backend&&a.isLanguageChangingTo&&!r(a.isLanguageChangingTo,t))return!1}}),es=t=>typeof t=="string",jl=t=>typeof t=="object"&&t!==null,Cl=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,Al={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},Nl=t=>Al[t],Il=t=>t.replace(Cl,Nl);let ua={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:Il,transDefaultProps:void 0};const Ll=(t={})=>{ua={...ua,...t}},El=()=>ua;let yi;const _l=t=>{yi=t},Tl=()=>yi,Ml={type:"3rdParty",init(t){Ll(t.options.react),_l(t)}},Fl=h.createContext();class $l{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(s=>{this.usedNamespaces[s]||(this.usedNamespaces[s]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var Jr={exports:{}},ea={};/**
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MermaidRenderer-DxunGWXF.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-DKegh4A9.js","assets/locales-CcBtm6Ky.js","assets/vendor-markdown-Cy_-N5ZX.js","assets/vendor-markdown-dRWncRqa.css","assets/vendor-auth-aD_bwYde.js","assets/ChartRenderer-BFQlovpe.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-qpZbjlwR.js","assets/papaparse.min-D13ujVVP.js","assets/docx-preview-DehBmhog.js"])))=>i.map(i=>d[i]);
2
+ var $o=Object.defineProperty;var Ro=(t,e,s)=>e in t?$o(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var Ze=(t,e,s)=>Ro(t,typeof e!="symbol"?e+"":e,s);import{r as h,j as i,a as Po,R as gt,b as Ir,d as Do}from"./vendor-react-BbEy7z12.js";import{z as Uo,p as Oo,j as zo,f as Bo,e as Ho,a as Vo,d as qo}from"./locales-CcBtm6Ky.js";import{M as Wo,r as rn,a as Ko,b as Go}from"./vendor-markdown-Cy_-N5ZX.js";import{_ as Ct,h as Xo,v as Yo,a as Qo}from"./vendor-syntax-INF7-xC_.js";import{u as Ca,a as Aa,b as Zo,P as Jo,M as el,A as tl}from"./vendor-auth-aD_bwYde.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))a(r);new MutationObserver(r=>{for(const n of r)if(n.type==="childList")for(const o of n.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&a(o)}).observe(document,{childList:!0,subtree:!0});function s(r){const n={};return r.integrity&&(n.integrity=r.integrity),r.referrerPolicy&&(n.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?n.credentials="include":r.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function a(r){if(r.ep)return;r.ep=!0;const n=s(r);fetch(r.href,n)}})();const hi=h.createContext(void 0);function an({children:t}){const[e,s]=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}}),[a,r]=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,r(l);const c=document.documentElement;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 n=o=>{s(l=>({...l,...o}))};return i.jsx(hi.Provider,{value:{theme:e,updateTheme:n,isDark:a},children:t})}function ts(){const t=h.useContext(hi);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}const pi=h.createContext(void 0),Xr={voiceEnabled:!1,soundEnabled:!1,autoSend:!1};function sl({children:t}){const[e,s]=h.useState(()=>{const r=localStorage.getItem("chat-settings");if(r)try{const n=JSON.parse(r);return{...Xr,...n,voiceEnabled:!1}}catch{return Xr}return Xr});h.useEffect(()=>{localStorage.setItem("chat-settings",JSON.stringify(e))},[e]);const a=r=>{s(n=>({...n,...r}))};return i.jsx(pi.Provider,{value:{settings:e,updateSettings:a},children:t})}function Lr(){const t=h.useContext(pi);if(!t)throw new Error("useSettings must be used within SettingsProvider");return t}const he=t=>typeof t=="string",Is=()=>{let t,e;const s=new Promise((a,r)=>{t=a,e=r});return s.resolve=t,s.reject=e,s},nn=t=>t==null?"":String(t),rl=(t,e,s)=>{t.forEach(a=>{e[a]&&(s[a]=e[a])})},al=/###/g,on=t=>t&&t.includes("###")?t.replace(al,"."):t,ln=t=>!t||he(t),Ts=(t,e,s)=>{const a=he(e)?e.split("."):e;let r=0;for(;r<a.length-1;){if(ln(t))return{};const n=on(a[r]);!t[n]&&s&&(t[n]=new s),Object.prototype.hasOwnProperty.call(t,n)?t=t[n]:t={},++r}return ln(t)?{}:{obj:t,k:on(a[r])}},cn=(t,e,s)=>{const{obj:a,k:r}=Ts(t,e,Object);if(a!==void 0||e.length===1){a[r]=s;return}let n=e[e.length-1],o=e.slice(0,e.length-1),l=Ts(t,o,Object);for(;l.obj===void 0&&o.length;)n=`${o[o.length-1]}.${n}`,o=o.slice(0,o.length-1),l=Ts(t,o,Object),l!=null&&l.obj&&typeof l.obj[`${l.k}.${n}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${n}`]=s},nl=(t,e,s,a)=>{const{obj:r,k:n}=Ts(t,e,Object);r[n]=r[n]||[],r[n].push(s)},xr=(t,e)=>{const{obj:s,k:a}=Ts(t,e);if(s&&Object.prototype.hasOwnProperty.call(s,a))return s[a]},il=(t,e,s)=>{const a=xr(t,s);return a!==void 0?a:xr(e,s)},mi=(t,e,s)=>{for(const a in e)a!=="__proto__"&&a!=="constructor"&&(Object.prototype.hasOwnProperty.call(t,a)?he(t[a])||t[a]instanceof String||he(e[a])||e[a]instanceof String?s&&(t[a]=e[a]):mi(t[a],e[a],s):t[a]=e[a]);return t},Lt=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),ol={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"},ll=t=>he(t)?t.replace(/[&<>"'\/]/g,e=>ol[e]):t;class cl{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const s=this.regExpMap.get(e);if(s!==void 0)return s;const a=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,a),this.regExpQueue.push(e),a}}const dl=[" ",",","?","!",";"],ul=new cl(20),fl=(t,e,s)=>{e=e||"",s=s||"";const a=dl.filter(o=>!e.includes(o)&&!s.includes(o));if(a.length===0)return!0;const r=ul.getRegExp(`(${a.map(o=>o==="?"?"\\?":o).join("|")})`);let n=!r.test(t);if(!n){const o=t.indexOf(s);o>0&&!r.test(t.substring(0,o))&&(n=!0)}return n},la=(t,e,s=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const a=e.split(s);let r=t;for(let n=0;n<a.length;){if(!r||typeof r!="object")return;let o,l="";for(let c=n;c<a.length;++c)if(c!==n&&(l+=s),l+=a[c],o=r[l],o!==void 0){if(["string","number","boolean"].includes(typeof o)&&c<a.length-1)continue;n+=c-n+1;break}r=o}return r},Rs=t=>t==null?void 0:t.replace(/_/g,"-"),hl={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){var s,a;(a=(s=console==null?void 0:console[t])==null?void 0:s.apply)==null||a.call(s,console,e)}};class br{constructor(e,s={}){this.init(e,s)}init(e,s={}){this.prefix=s.prefix||"i18next:",this.logger=e||hl,this.options=s,this.debug=s.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,s,a,r){return r&&!this.debug?null:(e=e.map(n=>he(n)?n.replace(/[\r\n\x00-\x1F\x7F]/g," "):n),he(e[0])&&(e[0]=`${a}${this.prefix} ${e[0]}`),this.logger[s](e))}create(e){return new br(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new br(this.logger,e)}}var At=new br;class Er{constructor(){this.observers={}}on(e,s){return e.split(" ").forEach(a=>{this.observers[a]||(this.observers[a]=new Map);const r=this.observers[a].get(s)||0;this.observers[a].set(s,r+1)}),this}off(e,s){if(this.observers[e]){if(!s){delete this.observers[e];return}this.observers[e].delete(s)}}once(e,s){const a=(...r)=>{s(...r),this.off(e,a)};return this.on(e,a),this}emit(e,...s){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([r,n])=>{for(let o=0;o<n;o++)r(...s)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([r,n])=>{for(let o=0;o<n;o++)r(e,...s)})}}class dn extends Er{constructor(e,s={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=s,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 s=this.options.ns.indexOf(e);s>-1&&this.options.ns.splice(s,1)}getResource(e,s,a,r={}){var d,u;const n=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator,o=r.ignoreJSONStructure!==void 0?r.ignoreJSONStructure:this.options.ignoreJSONStructure;let l;e.includes(".")?l=e.split("."):(l=[e,s],a&&(Array.isArray(a)?l.push(...a):he(a)&&n?l.push(...a.split(n)):l.push(a)));const c=xr(this.data,l);return!c&&!s&&!a&&e.includes(".")&&(e=l[0],s=l[1],a=l.slice(2).join(".")),c||!o||!he(a)?c:la((u=(d=this.data)==null?void 0:d[e])==null?void 0:u[s],a,n)}addResource(e,s,a,r,n={silent:!1}){const o=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let l=[e,s];a&&(l=l.concat(o?a.split(o):a)),e.includes(".")&&(l=e.split("."),r=s,s=l[1]),this.addNamespaces(s),cn(this.data,l,r),n.silent||this.emit("added",e,s,a,r)}addResources(e,s,a,r={silent:!1}){for(const n in a)(he(a[n])||Array.isArray(a[n]))&&this.addResource(e,s,n,a[n],{silent:!0});r.silent||this.emit("added",e,s,a)}addResourceBundle(e,s,a,r,n,o={silent:!1,skipCopy:!1}){let l=[e,s];e.includes(".")&&(l=e.split("."),r=a,a=s,s=l[1]),this.addNamespaces(s);let c=xr(this.data,l)||{};o.skipCopy||(a=JSON.parse(JSON.stringify(a))),r?mi(c,a,n):c={...c,...a},cn(this.data,l,c),o.silent||this.emit("added",e,s,a)}removeResourceBundle(e,s){this.hasResourceBundle(e,s)&&delete this.data[e][s],this.removeNamespaces(s),this.emit("removed",e,s)}hasResourceBundle(e,s){return this.getResource(e,s)!==void 0}getResourceBundle(e,s){return s||(s=this.options.defaultNS),this.getResource(e,s)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const s=this.getDataByLanguage(e);return!!(s&&Object.keys(s)||[]).find(r=>s[r]&&Object.keys(s[r]).length>0)}toJSON(){return this.data}}var gi={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,s,a,r){return t.forEach(n=>{var o;e=((o=this.processors[n])==null?void 0:o.process(e,s,a,r))??e}),e}};const xi=Symbol("i18next/PATH_KEY");function pl(){const t=[],e=Object.create(null);let s;return e.get=(a,r)=>{var n;return(n=s==null?void 0:s.revoke)==null||n.call(s),r===xi?t:(t.push(r),s=Proxy.revocable(a,e),s.proxy)},Proxy.revocable(Object.create(null),e).proxy}function cs(t,e){const{[xi]:s}=t(pl()),a=(e==null?void 0:e.keySeparator)??".",r=(e==null?void 0:e.nsSeparator)??":",n=(e==null?void 0:e.enableSelector)==="strict";if(s.length>1&&r){const o=e==null?void 0:e.ns,l=n?Array.isArray(o)?o:o?[o]:null:Array.isArray(o)?o:null;if(l&&(n?l:l.length>1?l.slice(1):[]).includes(s[0]))return`${s[0]}${r}${s.slice(1).join(a)}`}return s.join(a)}const Yr=t=>!he(t)&&typeof t!="boolean"&&typeof t!="number";class yr extends Er{constructor(e,s={}){super(),rl(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=s,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=At.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,s={interpolation:{}}){const a={...s};if(e==null)return!1;const r=this.resolve(e,a);if((r==null?void 0:r.res)===void 0)return!1;const n=Yr(r.res);return!(a.returnObjects===!1&&n)}extractFromKey(e,s){let a=s.nsSeparator!==void 0?s.nsSeparator:this.options.nsSeparator;a===void 0&&(a=":");const r=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let n=s.ns||this.options.defaultNS||[];const o=a&&e.includes(a),l=!this.options.userDefinedKeySeparator&&!s.keySeparator&&!this.options.userDefinedNsSeparator&&!s.nsSeparator&&!fl(e,a,r);if(o&&!l){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:he(n)?[n]:n};const d=e.split(a);(a!==r||a===r&&this.options.ns.includes(d[0]))&&(n=d.shift()),e=d.join(r)}return{key:e,namespaces:he(n)?[n]:n}}translate(e,s,a){let r=typeof s=="object"?{...s}:s;if(typeof r!="object"&&this.options.overloadTranslationOptionHandler&&(r=this.options.overloadTranslationOptionHandler(arguments)),typeof r=="object"&&(r={...r}),r||(r={}),e==null)return"";typeof e=="function"&&(e=cs(e,{...this.options,...r})),Array.isArray(e)||(e=[String(e)]),e=e.map(F=>typeof F=="function"?cs(F,{...this.options,...r}):String(F));const n=r.returnDetails!==void 0?r.returnDetails:this.options.returnDetails,o=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator,{key:l,namespaces:c}=this.extractFromKey(e[e.length-1],r),d=c[c.length-1];let u=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const f=r.lng||this.language,m=r.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if((f==null?void 0:f.toLowerCase())==="cimode")return m?n?{res:`${d}${u}${l}`,usedKey:l,exactUsedKey:l,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(r)}:`${d}${u}${l}`:n?{res:l,usedKey:l,exactUsedKey:l,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(r)}:l;const p=this.resolve(e,r);let g=p==null?void 0:p.res;const x=(p==null?void 0:p.usedKey)||l,y=(p==null?void 0:p.exactUsedKey)||l,k=["[object Number]","[object Function]","[object RegExp]"],A=r.joinArrays!==void 0?r.joinArrays:this.options.joinArrays,L=!this.i18nFormat||this.i18nFormat.handleAsObject,C=r.count!==void 0&&!he(r.count),v=yr.hasDefaultValue(r),N=C?this.pluralResolver.getSuffix(f,r.count,r):"",R=r.ordinal&&C?this.pluralResolver.getSuffix(f,r.count,{ordinal:!1}):"",b=C&&!r.ordinal&&r.count===0,_=b&&r[`defaultValue${this.options.pluralSeparator}zero`]||r[`defaultValue${N}`]||r[`defaultValue${R}`]||r.defaultValue;let S=g;L&&!g&&v&&(S=_);const I=Yr(S),M=Object.prototype.toString.apply(S);if(L&&S&&I&&!k.includes(M)&&!(he(A)&&Array.isArray(S))){if(!r.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const F=this.options.returnedObjectHandler?this.options.returnedObjectHandler(x,S,{...r,ns:c}):`key '${l} (${this.language})' returned an object instead of string.`;return n?(p.res=F,p.usedParams=this.getUsedParamsDetails(r),p):F}if(o){const F=Array.isArray(S),H=F?[]:{},j=F?y:x;for(const E in S)if(Object.prototype.hasOwnProperty.call(S,E)){const D=`${j}${o}${E}`;v&&!g?H[E]=this.translate(D,{...r,defaultValue:Yr(_)?_[E]:void 0,joinArrays:!1,ns:c}):H[E]=this.translate(D,{...r,joinArrays:!1,ns:c}),H[E]===D&&(H[E]=S[E])}g=H}}else if(L&&he(A)&&Array.isArray(g))g=g.join(A),g&&(g=this.extendTranslation(g,e,r,a));else{let F=!1,H=!1;!this.isValidLookup(g)&&v&&(F=!0,g=_),this.isValidLookup(g)||(H=!0,g=l);const E=(r.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&H?void 0:g,D=v&&_!==g&&this.options.updateMissing;if(H||F||D){if(this.logger.log(D?"updateKey":"missingKey",f,d,C&&!D?`${l}${this.pluralResolver.getSuffix(f,r.count,r)}`:l,D?_:g),o){const V=this.resolve(l,{...r,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 T=[];const G=this.languageUtils.getFallbackCodes(this.options.fallbackLng,r.lng||this.language);if(this.options.saveMissingTo==="fallback"&&G&&G[0])for(let V=0;V<G.length;V++)T.push(G[V]);else this.options.saveMissingTo==="all"?T=this.languageUtils.toResolveHierarchy(r.lng||this.language):T.push(r.lng||this.language);const X=(V,Z,fe)=>{var se;const z=v&&fe!==g?fe:E;this.options.missingKeyHandler?this.options.missingKeyHandler(V,d,Z,z,D,r):(se=this.backendConnector)!=null&&se.saveMissing&&this.backendConnector.saveMissing(V,d,Z,z,D,r),this.emit("missingKey",V,d,Z,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&C?T.forEach(V=>{const Z=this.pluralResolver.getSuffixes(V,r);b&&r[`defaultValue${this.options.pluralSeparator}zero`]&&!Z.includes(`${this.options.pluralSeparator}zero`)&&Z.push(`${this.options.pluralSeparator}zero`),Z.forEach(fe=>{X([V],l+fe,r[`defaultValue${fe}`]||_)})}):X(T,l,_))}g=this.extendTranslation(g,e,r,p,a),H&&g===l&&this.options.appendNamespaceToMissingKey&&(g=`${d}${u}${l}`),(H||F)&&this.options.parseMissingKeyHandler&&(g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${l}`:l,F?g:void 0,r))}return n?(p.res=g,p.usedParams=this.getUsedParamsDetails(r),p):g}extendTranslation(e,s,a,r,n){var c,d;if((c=this.i18nFormat)!=null&&c.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...a},a.lng||this.language||r.usedLng,r.usedNS,r.usedKey,{resolved:r});else if(!a.skipInterpolation){a.interpolation&&this.interpolator.init({...a,interpolation:{...this.options.interpolation,...a.interpolation}});const u=he(e)&&(((d=a==null?void 0:a.interpolation)==null?void 0:d.skipOnVariables)!==void 0?a.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let f;if(u){const p=e.match(this.interpolator.nestingRegexp);f=p&&p.length}let m=a.replace&&!he(a.replace)?a.replace:a;if(this.options.interpolation.defaultVariables&&(m={...this.options.interpolation.defaultVariables,...m}),e=this.interpolator.interpolate(e,m,a.lng||this.language||r.usedLng,a),u){const p=e.match(this.interpolator.nestingRegexp),g=p&&p.length;f<g&&(a.nest=!1)}!a.lng&&r&&r.res&&(a.lng=this.language||r.usedLng),a.nest!==!1&&(e=this.interpolator.nest(e,(...p)=>(n==null?void 0:n[0])===p[0]&&!a.context?(this.logger.warn(`It seems you are nesting recursively key: ${p[0]} in key: ${s[0]}`),null):this.translate(...p,s),a)),a.interpolation&&this.interpolator.reset()}const o=a.postProcess||this.options.postProcess,l=he(o)?[o]:o;return e!=null&&(l!=null&&l.length)&&a.applyPostProcessor!==!1&&(e=gi.handle(l,e,s,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...r,usedParams:this.getUsedParamsDetails(a)},...a}:a,this)),e}resolve(e,s={}){let a,r,n,o,l;return he(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(c=>typeof c=="function"?cs(c,{...this.options,...s}):c)),e.forEach(c=>{if(this.isValidLookup(a))return;const d=this.extractFromKey(c,s),u=d.key;r=u;let f=d.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const m=s.count!==void 0&&!he(s.count),p=m&&!s.ordinal&&s.count===0,g=s.context!==void 0&&(he(s.context)||typeof s.context=="number")&&s.context!=="",x=s.lngs?s.lngs:this.languageUtils.toResolveHierarchy(s.lng||this.language,s.fallbackLng);f.forEach(y=>{var k,A;this.isValidLookup(a)||(l=y,!this.checkedLoadedFor[`${x[0]}-${y}`]&&((k=this.utils)!=null&&k.hasLoadedNamespace)&&!((A=this.utils)!=null&&A.hasLoadedNamespace(l))&&(this.checkedLoadedFor[`${x[0]}-${y}`]=!0,this.logger.warn(`key "${r}" 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(L=>{var N;if(this.isValidLookup(a))return;o=L;const C=[u];if((N=this.i18nFormat)!=null&&N.addLookupKeys)this.i18nFormat.addLookupKeys(C,u,L,y,s);else{let R;m&&(R=this.pluralResolver.getSuffix(L,s.count,s));const b=`${this.options.pluralSeparator}zero`,_=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(m&&(s.ordinal&&R.startsWith(_)&&C.push(u+R.replace(_,this.options.pluralSeparator)),C.push(u+R),p&&C.push(u+b)),g){const S=`${u}${this.options.contextSeparator||"_"}${s.context}`;C.push(S),m&&(s.ordinal&&R.startsWith(_)&&C.push(S+R.replace(_,this.options.pluralSeparator)),C.push(S+R),p&&C.push(S+b))}}let v;for(;v=C.pop();)this.isValidLookup(a)||(n=v,a=this.getResource(L,y,v,s))}))})}),{res:a,usedKey:r,exactUsedKey:n,usedLng:o,usedNS:l}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,s,a,r={}){var n;return(n=this.i18nFormat)!=null&&n.getResource?this.i18nFormat.getResource(e,s,a,r):this.resourceStore.getResource(e,s,a,r)}getUsedParamsDetails(e={}){const s=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],a=e.replace&&!he(e.replace);let r=a?e.replace:e;if(a&&typeof e.count<"u"&&(r.count=e.count),this.options.interpolation.defaultVariables&&(r={...this.options.interpolation.defaultVariables,...r}),!a){r={...r};for(const n of s)delete r[n]}return r}static hasDefaultValue(e){const s="defaultValue";for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a)&&a.startsWith(s)&&e[a]!==void 0)return!0;return!1}}class un{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=At.create("languageUtils")}getScriptPartFromCode(e){if(e=Rs(e),!e||!e.includes("-"))return null;const s=e.split("-");return s.length===2||(s.pop(),s[s.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(s.join("-"))}getLanguagePartFromCode(e){if(e=Rs(e),!e||!e.includes("-"))return e;const s=e.split("-");return this.formatLanguageCode(s[0])}formatLanguageCode(e){if(he(e)&&e.includes("-")){let s;try{s=Intl.getCanonicalLocales(e)[0]}catch{}return s&&this.options.lowerCaseLng&&(s=s.toLowerCase()),s||(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 s;return e.forEach(a=>{if(s)return;const r=this.formatLanguageCode(a);(!this.options.supportedLngs||this.isSupportedCode(r))&&(s=r)}),!s&&this.options.supportedLngs&&e.forEach(a=>{if(s)return;const r=this.getScriptPartFromCode(a);if(this.isSupportedCode(r))return s=r;const n=this.getLanguagePartFromCode(a);if(this.isSupportedCode(n))return s=n;s=this.options.supportedLngs.find(o=>o===n?!0:!o.includes("-")&&!n.includes("-")?!1:!!(o.includes("-")&&!n.includes("-")&&o.slice(0,o.indexOf("-"))===n||o.startsWith(n)&&n.length>1))}),s||(s=this.getFallbackCodes(this.options.fallbackLng)[0]),s}getFallbackCodes(e,s){if(!e)return[];if(typeof e=="function"&&(e=e(s)),he(e)&&(e=[e]),Array.isArray(e))return e;if(!s)return e.default||[];let a=e[s];return a||(a=e[this.getScriptPartFromCode(s)]),a||(a=e[this.formatLanguageCode(s)]),a||(a=e[this.getLanguagePartFromCode(s)]),a||(a=e.default),a||[]}toResolveHierarchy(e,s){const a=this.getFallbackCodes((s===!1?[]:s)||this.options.fallbackLng||[],e),r=[],n=o=>{o&&(this.isSupportedCode(o)?r.push(o):this.logger.warn(`rejecting language code not found in supportedLngs: ${o}`))};return he(e)&&(e.includes("-")||e.includes("_"))?(this.options.load!=="languageOnly"&&n(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&n(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&n(this.getLanguagePartFromCode(e))):he(e)&&n(this.formatLanguageCode(e)),a.forEach(o=>{r.includes(o)||n(this.formatLanguageCode(o))}),r}}const fn={zero:0,one:1,two:2,few:3,many:4,other:5},hn={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class ml{constructor(e,s={}){this.languageUtils=e,this.options=s,this.logger=At.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,s={}){const a=Rs(e==="dev"?"en":e),r=s.ordinal?"ordinal":"cardinal",n=JSON.stringify({cleanedCode:a,type:r});if(n in this.pluralRulesCache)return this.pluralRulesCache[n];let o;try{o=new Intl.PluralRules(a,{type:r})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),hn;if(!e.match(/-|_/))return hn;const c=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(c,s)}return this.pluralRulesCache[n]=o,o}needsPlural(e,s={}){let a=this.getRule(e,s);return a||(a=this.getRule("dev",s)),(a==null?void 0:a.resolvedOptions().pluralCategories.length)>1}getPluralFormsOfKey(e,s,a={}){return this.getSuffixes(e,a).map(r=>`${s}${r}`)}getSuffixes(e,s={}){let a=this.getRule(e,s);return a||(a=this.getRule("dev",s)),a?a.resolvedOptions().pluralCategories.sort((r,n)=>fn[r]-fn[n]).map(r=>`${this.options.prepend}${s.ordinal?`ordinal${this.options.prepend}`:""}${r}`):[]}getSuffix(e,s,a={}){const r=this.getRule(e,a);return r?`${this.options.prepend}${a.ordinal?`ordinal${this.options.prepend}`:""}${r.select(s)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",s,a))}}const pn=(t,e,s,a=".",r=!0)=>{let n=il(t,e,s);return!n&&r&&he(s)&&(n=la(t,s,a),n===void 0&&(n=la(e,s,a))),n},Qr=t=>t.replace(/\$/g,"$$$$");class mn{constructor(e={}){var s;this.logger=At.create("interpolator"),this.options=e,this.format=((s=e==null?void 0:e.interpolation)==null?void 0:s.format)||(a=>a),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:s,escapeValue:a,useRawValueToEscape:r,prefix:n,prefixEscaped:o,suffix:l,suffixEscaped:c,formatSeparator:d,unescapeSuffix:u,unescapePrefix:f,nestingPrefix:m,nestingPrefixEscaped:p,nestingSuffix:g,nestingSuffixEscaped:x,nestingOptionsSeparator:y,maxReplaces:k,alwaysFormat:A}=e.interpolation;this.escape=s!==void 0?s:ll,this.escapeValue=a!==void 0?a:!0,this.useRawValueToEscape=r!==void 0?r:!1,this.prefix=n?Lt(n):o||"{{",this.suffix=l?Lt(l):c||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":f?Lt(f):"-",this.unescapeSuffix=this.unescapePrefix?"":u?Lt(u):"",this.nestingPrefix=m?Lt(m):p||Lt("$t("),this.nestingSuffix=g?Lt(g):x||Lt(")"),this.nestingOptionsSeparator=y||",",this.maxReplaces=k||1e3,this.alwaysFormat=A!==void 0?A:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(s,a)=>(s==null?void 0:s.source)===a?(s.lastIndex=0,s):new RegExp(a,"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,s,a,r){var p;let n,o,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=g=>{if(!g.includes(this.formatSeparator)){const A=pn(s,c,g,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(A,void 0,a,{...r,...s,interpolationkey:g}):A}const x=g.split(this.formatSeparator),y=x.shift().trim(),k=x.join(this.formatSeparator).trim();return this.format(pn(s,c,y,this.options.keySeparator,this.options.ignoreJSONStructure),k,a,{...r,...s,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=(r==null?void 0:r.missingInterpolationHandler)||this.options.missingInterpolationHandler,f=((p=r==null?void 0:r.interpolation)==null?void 0:p.skipOnVariables)!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:g=>Qr(g)},{regex:this.regexp,safeValue:g=>this.escapeValue?Qr(this.escape(g)):Qr(g)}].forEach(g=>{for(l=0;n=g.regex.exec(e);){const x=n[1].trim();if(o=d(x),o===void 0)if(typeof u=="function"){const k=u(e,n,r);o=he(k)?k:""}else if(r&&Object.prototype.hasOwnProperty.call(r,x))o="";else if(f){o=n[0];continue}else this.logger.warn(`missed to pass in variable ${x} for interpolating ${e}`),o="";else!he(o)&&!this.useRawValueToEscape&&(o=nn(o));const y=g.safeValue(o);if(e=e.replace(n[0],y),f?(g.regex.lastIndex+=o.length,g.regex.lastIndex-=n[0].length):g.regex.lastIndex=0,l++,l>=this.maxReplaces)break}}),e}nest(e,s,a={}){let r,n,o;const l=(c,d)=>{const u=this.nestingOptionsSeparator;if(!c.includes(u))return c;const f=c.split(new RegExp(`${Lt(u)}[ ]*{`));let m=`{${f[1]}`;c=f[0],m=this.interpolate(m,o);const p=m.match(/'/g),g=m.match(/"/g);(((p==null?void 0:p.length)??0)%2===0&&!g||((g==null?void 0:g.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(;r=this.nestingRegexp.exec(e);){let c=[];o={...a},o=o.replace&&!he(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const d=/{.*}/.test(r[1])?r[1].lastIndexOf("}")+1:r[1].indexOf(this.formatSeparator);if(d!==-1&&(c=r[1].slice(d).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),r[1]=r[1].slice(0,d)),n=s(l.call(this,r[1].trim(),o),o),n&&r[0]===e&&!he(n))return n;he(n)||(n=nn(n)),n||(this.logger.warn(`missed to resolve ${r[1]} for nesting ${e}`),n=""),c.length&&(n=c.reduce((u,f)=>this.format(u,f,a.lng,{...a,interpolationkey:r[1].trim()}),n.trim())),e=e.replace(r[0],n),this.regexp.lastIndex=0}return e}}const gl=t=>{let e=t.toLowerCase().trim();const s={};if(t.includes("(")){const a=t.split("(");e=a[0].toLowerCase().trim();const r=a[1].slice(0,-1);e==="currency"&&!r.includes(":")?s.currency||(s.currency=r.trim()):e==="relativetime"&&!r.includes(":")?s.range||(s.range=r.trim()):r.split(";").forEach(o=>{if(o){const[l,...c]=o.split(":"),d=c.join(":").trim().replace(/^'+|'+$/g,""),u=l.trim();s[u]||(s[u]=d),d==="false"&&(s[u]=!1),d==="true"&&(s[u]=!0),isNaN(d)||(s[u]=parseInt(d,10))}})}return{formatName:e,formatOptions:s}},gn=t=>{const e={};return(s,a,r)=>{let n=r;r&&r.interpolationkey&&r.formatParams&&r.formatParams[r.interpolationkey]&&r[r.interpolationkey]&&(n={...n,[r.interpolationkey]:void 0});const o=a+JSON.stringify(n);let l=e[o];return l||(l=t(Rs(a),r),e[o]=l),l(s)}},xl=t=>(e,s,a)=>t(Rs(s),a)(e);class bl{constructor(e={}){this.logger=At.create("formatter"),this.options=e,this.init(e)}init(e,s={interpolation:{}}){this.formatSeparator=s.interpolation.formatSeparator||",";const a=s.cacheInBuiltFormats?gn:xl;this.formats={number:a((r,n)=>{const o=new Intl.NumberFormat(r,{...n});return l=>o.format(l)}),currency:a((r,n)=>{const o=new Intl.NumberFormat(r,{...n,style:"currency"});return l=>o.format(l)}),datetime:a((r,n)=>{const o=new Intl.DateTimeFormat(r,{...n});return l=>o.format(l)}),relativetime:a((r,n)=>{const o=new Intl.RelativeTimeFormat(r,{...n});return l=>o.format(l,n.range||"day")}),list:a((r,n)=>{const o=new Intl.ListFormat(r,{...n});return l=>o.format(l)})}}add(e,s){this.formats[e.toLowerCase().trim()]=s}addCached(e,s){this.formats[e.toLowerCase().trim()]=gn(s)}format(e,s,a,r={}){if(!s||e==null)return e;const n=s.split(this.formatSeparator),o=[];for(let c=0;c<n.length;c++){let d=n[c];for(;d.indexOf("(")>-1&&!d.includes(")")&&c+1<n.length;)d=`${d}${this.formatSeparator}${n[++c]}`;o.push(d)}return o.reduce((c,d)=>{var m;const{formatName:u,formatOptions:f}=gl(d);if(this.formats[u]){let p=c;try{const g=((m=r==null?void 0:r.formatParams)==null?void 0:m[r.interpolationkey])||{},x=g.locale||g.lng||r.locale||r.lng||a;p=this.formats[u](c,x,{...f,...r,...g})}catch(g){this.logger.warn(g)}return p}else this.logger.warn(`there was no format function for ${u}`);return c},e)}}const yl=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class wl extends Er{constructor(e,s,a,r={}){var n,o;super(),this.backend=e,this.store=s,this.services=a,this.languageUtils=a.languageUtils,this.options=r,this.logger=At.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=r.maxParallelReads||10,this.readingCalls=0,this.maxRetries=r.maxRetries>=0?r.maxRetries:5,this.retryTimeout=r.retryTimeout>=1?r.retryTimeout:350,this.state={},this.queue=[],(o=(n=this.backend)==null?void 0:n.init)==null||o.call(n,a,r.backend,r)}queueLoad(e,s,a,r){const n={},o={},l={},c={};return e.forEach(d=>{let u=!0;s.forEach(f=>{const m=`${d}|${f}`;!a.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),n[m]===void 0&&(n[m]=!0),c[f]===void 0&&(c[f]=!0)))}),u||(l[d]=!0)}),(Object.keys(n).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:r}),{toLoad:Object.keys(n),pending:Object.keys(o),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(e,s,a){const r=e.split("|"),n=r[0],o=r[1];s&&this.emit("failedLoading",n,o,s),!s&&a&&this.store.addResourceBundle(n,o,a,void 0,void 0,{skipCopy:!0}),this.state[e]=s?-1:2,s&&a&&(this.state[e]=0);const l={};this.queue.forEach(c=>{nl(c.loaded,[n],o),yl(c,e),s&&c.errors.push(s),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,s,a,r=0,n=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:s,fcName:a,tried:r,wait:n,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&&r<this.maxRetries){setTimeout(()=>{this.read(e,s,a,r+1,n*2,o)},n);return}o(d,u)},c=this.backend[a].bind(this.backend);if(c.length===2){try{const d=c(e,s);d&&typeof d.then=="function"?d.then(u=>l(null,u)).catch(l):l(null,d)}catch(d){l(d)}return}return c(e,s,l)}prepareLoading(e,s,a={},r){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),r&&r();he(e)&&(e=this.languageUtils.toResolveHierarchy(e)),he(s)&&(s=[s]);const n=this.queueLoad(e,s,a,r);if(!n.toLoad.length)return n.pending.length||r(),null;n.toLoad.forEach(o=>{this.loadOne(o)})}load(e,s,a){this.prepareLoading(e,s,{},a)}reload(e,s,a){this.prepareLoading(e,s,{reload:!0},a)}loadOne(e,s=""){const a=e.split("|"),r=a[0],n=a[1];this.read(r,n,"read",void 0,void 0,(o,l)=>{o&&this.logger.warn(`${s}loading namespace ${n} for language ${r} failed`,o),!o&&l&&this.logger.log(`${s}loaded namespace ${n} for language ${r}`,l),this.loaded(e,o,l)})}saveMissing(e,s,a,r,n,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(s))){this.logger.warn(`did not save key "${a}" as the namespace "${s}" 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(!(a==null||a==="")){if((m=this.backend)!=null&&m.create){const p={...o,isUpdate:n},g=this.backend.create.bind(this.backend);if(g.length<6)try{let x;g.length===5?x=g(e,s,a,r,p):x=g(e,s,a,r),x&&typeof x.then=="function"?x.then(y=>l(null,y)).catch(l):l(null,x)}catch(x){l(x)}else g(e,s,a,r,l,p)}!e||!e[0]||this.store.addResource(e[0],s,a,r)}}}const Zr=()=>({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 s=t[3]||t[2];Object.keys(s).forEach(a=>{e[a]=s[a]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),xn=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),sr=()=>{},kl=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(s=>{typeof t[s]=="function"&&(t[s]=t[s].bind(t))})};class Ms extends Er{constructor(e={},s){if(super(),this.options=xn(e),this.services={},this.logger=At,this.modules={external:[]},kl(this),s&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,s),this;setTimeout(()=>{this.init(e,s)},0)}}init(e={},s){this.isInitializing=!0,typeof e=="function"&&(s=e,e={}),e.defaultNS==null&&e.ns&&(he(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const a=Zr();this.options={...a,...this.options,...xn(e)},this.options.interpolation={...a.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=a.overloadTranslationOptionHandler);const r=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?At.init(r(this.modules.logger),this.options):At.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=bl;const u=new un(this.options);this.store=new dn(this.options.resources,this.options);const f=this.services;f.logger=At,f.resourceStore=this.store,f.languageUtils=u,f.pluralResolver=new ml(u,{prepend:this.options.pluralSeparator}),d&&(f.formatter=r(d),f.formatter.init&&f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new mn(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new wl(r(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(m,...p)=>{this.emit(m,...p)}),this.modules.languageDetector&&(f.languageDetector=r(this.modules.languageDetector),f.languageDetector.init&&f.languageDetector.init(f,this.options.detection,this.options)),this.modules.i18nFormat&&(f.i18nFormat=r(this.modules.i18nFormat),f.i18nFormat.init&&f.i18nFormat.init(this)),this.translator=new yr(this.services,this.options),this.translator.on("*",(m,...p)=>{this.emit(m,...p)}),this.modules.external.forEach(m=>{m.init&&m.init(this)})}if(this.format=this.options.interpolation.format,s||(s=sr),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=Is(),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),s(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,s=sr){var n,o;let a=s;const r=he(e)?e:this.language;if(typeof e=="function"&&(a=e),!this.options.resources||this.options.partialBundledLanguages){if((r==null?void 0:r.toLowerCase())==="cimode"&&(!this.options.preload||this.options.preload.length===0))return a();const l=[],c=d=>{if(!d||d==="cimode")return;this.services.languageUtils.toResolveHierarchy(d).forEach(f=>{f!=="cimode"&&(l.includes(f)||l.push(f))})};r?c(r):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>c(u)),(o=(n=this.options.preload)==null?void 0:n.forEach)==null||o.call(n,d=>c(d)),this.services.backendConnector.load(l,this.options.ns,d=>{!d&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),a(d)})}else a(null)}reloadResources(e,s,a){const r=Is();return typeof e=="function"&&(a=e,e=void 0),typeof s=="function"&&(a=s,s=void 0),e||(e=this.languages),s||(s=this.options.ns),a||(a=sr),this.services.backendConnector.reload(e,s,n=>{r.resolve(),a(n)}),r}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"&&gi.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 s=0;s<this.languages.length;s++){const a=this.languages[s];if(!["cimode","dev"].includes(a)&&this.store.hasLanguageSomeTranslations(a)){this.resolvedLanguage=a;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,s){this.isLanguageChangingTo=e;const a=Is();this.emit("languageChanging",e);const r=l=>{this.language=l,this.languages=this.services.languageUtils.toResolveHierarchy(l),this.resolvedLanguage=void 0,this.setResolvedLanguage(l)},n=(l,c)=>{c?this.isLanguageChangingTo===e&&(r(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,a.resolve((...d)=>this.t(...d)),s&&s(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||r(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=>{n(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),a}getFixedT(e,s,a,r){const n=r==null?void 0:r.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||a||o.keyPrefix);const m={...this.options,...u};Array.isArray(n)&&!f&&(m.ns=n),typeof u.keyPrefix=="function"&&(u.keyPrefix=cs(u.keyPrefix,m));const p=this.options.keySeparator||".";let g;return u.keyPrefix&&Array.isArray(l)?g=l.map(x=>(typeof x=="function"&&(x=cs(x,m)),`${u.keyPrefix}${p}${x}`)):(typeof l=="function"&&(l=cs(l,m)),g=u.keyPrefix?`${u.keyPrefix}${p}${l}`:l),this.t(g,u)};return he(e)?o.lng=e:o.lngs=e,o.ns=s,o.keyPrefix=a,o}t(...e){var s;return(s=this.translator)==null?void 0:s.translate(...e)}exists(...e){var s;return(s=this.translator)==null?void 0:s.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,s={}){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 a=s.lng||this.resolvedLanguage||this.languages[0],r=this.options?this.options.fallbackLng:!1,n=this.languages[this.languages.length-1];if(a.toLowerCase()==="cimode")return!0;const o=(l,c)=>{const d=this.services.backendConnector.state[`${l}|${c}`];return d===-1||d===0||d===2};if(s.precheck){const l=s.precheck(this,o);if(l!==void 0)return l}return!!(this.hasResourceBundle(a,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(a,e)&&(!r||o(n,e)))}loadNamespaces(e,s){const a=Is();return this.options.ns?(he(e)&&(e=[e]),e.forEach(r=>{this.options.ns.includes(r)||this.options.ns.push(r)}),this.loadResources(r=>{a.resolve(),s&&s(r)}),a):(s&&s(),Promise.resolve())}loadLanguages(e,s){const a=Is();he(e)&&(e=[e]);const r=this.options.preload||[],n=e.filter(o=>!r.includes(o)&&this.services.languageUtils.isSupportedCode(o));return n.length?(this.options.preload=r.concat(n),this.loadResources(o=>{a.resolve(),s&&s(o)}),a):(s&&s(),Promise.resolve())}dir(e){var r,n;if(e||(e=this.resolvedLanguage||(((r=this.languages)==null?void 0:r.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 s=["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"],a=((n=this.services)==null?void 0:n.languageUtils)||new un(Zr());return e.toLowerCase().indexOf("-latn")>1?"ltr":s.includes(a.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},s){const a=new Ms(e,s);return a.createInstance=Ms.createInstance,a}cloneInstance(e={},s=sr){const a=e.forkResourceStore;a&&delete e.forkResourceStore;const r={...this.options,...e,isClone:!0},n=new Ms(r);if((e.debug!==void 0||e.prefix!==void 0)&&(n.logger=n.logger.clone(e)),["store","services","language"].forEach(l=>{n[l]=this[l]}),n.services={...this.services},n.services.utils={hasLoadedNamespace:n.hasLoadedNamespace.bind(n)},a){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),{});n.store=new dn(l,r),n.services.resourceStore=n.store}if(e.interpolation){const c={...Zr().interpolation,...this.options.interpolation,...e.interpolation},d={...r,interpolation:c};n.services.interpolator=new mn(d)}return n.translator=new yr(n.services,r),n.translator.on("*",(l,...c)=>{n.emit(l,...c)}),n.init(r,s),n.translator.options=r,n.translator.backendConnector.services.utils={hasLoadedNamespace:n.hasLoadedNamespace.bind(n)},n}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const Xe=Ms.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 vl=(t,e,s,a)=>{var n,o,l,c;const r=[s,{code:e,...a||{}}];if((o=(n=t==null?void 0:t.services)==null?void 0:n.logger)!=null&&o.forward)return t.services.logger.forward(r,"warn","react-i18next::",!0);es(r[0])&&(r[0]=`react-i18next:: ${r[0]}`),(c=(l=t==null?void 0:t.services)==null?void 0:l.logger)!=null&&c.warn?t.services.logger.warn(...r):console!=null&&console.warn&&console.warn(...r)},bn={},ca=(t,e,s,a)=>{es(s)&&bn[s]||(es(s)&&(bn[s]=new Date),vl(t,e,s,a))},bi=(t,e)=>()=>{if(t.isInitialized)e();else{const s=()=>{setTimeout(()=>{t.off("initialized",s)},0),e()};t.on("initialized",s)}},da=(t,e,s)=>{t.loadNamespaces(e,bi(t,s))},yn=(t,e,s,a)=>{if(es(s)&&(s=[s]),t.options.preload&&t.options.preload.indexOf(e)>-1)return da(t,s,a);s.forEach(r=>{t.options.ns.indexOf(r)<0&&t.options.ns.push(r)}),t.loadLanguages(e,bi(t,a))},Sl=(t,e,s={})=>!e.languages||!e.languages.length?(ca(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(t,{lng:s.lng,precheck:(a,r)=>{if(s.bindI18n&&s.bindI18n.indexOf("languageChanging")>-1&&a.services.backendConnector.backend&&a.isLanguageChangingTo&&!r(a.isLanguageChangingTo,t))return!1}}),es=t=>typeof t=="string",jl=t=>typeof t=="object"&&t!==null,Cl=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,Al={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},Nl=t=>Al[t],Il=t=>t.replace(Cl,Nl);let ua={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:Il,transDefaultProps:void 0};const Ll=(t={})=>{ua={...ua,...t}},El=()=>ua;let yi;const _l=t=>{yi=t},Tl=()=>yi,Ml={type:"3rdParty",init(t){Ll(t.options.react),_l(t)}},Fl=h.createContext();class $l{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(s=>{this.usedNamespaces[s]||(this.usedNamespaces[s]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var Jr={exports:{}},ea={};/**
3
3
  * @license React
4
4
  * use-sync-external-store-shim.production.js
5
5
  *
@@ -7,7 +7,7 @@ var $o=Object.defineProperty;var Ro=(t,e,s)=>e in t?$o(t,e,{enumerable:!0,config
7
7
  *
8
8
  * This source code is licensed under the MIT license found in the
9
9
  * LICENSE file in the root directory of this source tree.
10
- */var wn;function Rl(){if(wn)return ea;wn=1;var t=Po();function e(f,m){return f===m&&(f!==0||1/f===1/m)||f!==f&&m!==m}var s=typeof Object.is=="function"?Object.is:e,a=t.useState,r=t.useEffect,n=t.useLayoutEffect,o=t.useDebugValue;function l(f,m){var p=m(),g=a({inst:{value:p,getSnapshot:m}}),x=g[0].inst,y=g[1];return n(function(){x.value=p,x.getSnapshot=m,c(x)&&y({inst:x})},[f,p,m]),r(function(){return c(x)&&y({inst:x}),f(function(){c(x)&&y({inst:x})})},[f]),o(p),p}function c(f){var m=f.getSnapshot;f=f.value;try{var p=m();return!s(f,p)}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 ea.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:u,ea}var kn;function Pl(){return kn||(kn=1,Jr.exports=Rl()),Jr.exports}var Dl=Pl();const Ul=(t,e)=>{if(es(e))return e;if(jl(e)&&es(e.defaultValue))return e.defaultValue;if(typeof t=="function")return"";if(Array.isArray(t)){const s=t[t.length-1];return typeof s=="function"?"":s}return t},Ol={t:Ul,ready:!1},zl=()=>()=>{},Ee=(t,e={})=>{var _,S,I;const{i18n:s}=e,{i18n:a,defaultNS:r}=h.useContext(Fl)||{},n=s||a||Tl();n&&!n.reportNamespaces&&(n.reportNamespaces=new $l),n||ca(n,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=h.useMemo(()=>{var M;return{...El(),...(M=n==null?void 0:n.options)==null?void 0:M.react,...e}},[n,e]),{useSuspense:l,keyPrefix:c}=o,d=r||((_=n==null?void 0:n.options)==null?void 0:_.defaultNS),u=es(d)?[d]:d||["translation"],f=h.useMemo(()=>u,u);(I=(S=n==null?void 0:n.reportNamespaces)==null?void 0:S.addUsedNamespaces)==null||I.call(S,f);const m=h.useRef(0),p=h.useCallback(M=>{if(!n)return zl;const{bindI18n:F,bindI18nStore:B}=o,j=()=>{m.current+=1,M()};return F&&n.on(F,j),B&&n.store.on(B,j),()=>{F&&F.split(" ").forEach(E=>n.off(E,j)),B&&B.split(" ").forEach(E=>n.store.off(E,j))}},[n,o]),g=h.useRef(),x=h.useCallback(()=>{if(!n)return Ol;const M=!!(n.isInitialized||n.initializedStoreOnce)&&f.every(T=>Sl(T,n,o)),F=e.lng||n.language,B=m.current,j=g.current;if(j&&j.ready===M&&j.lng===F&&j.keyPrefix===c&&j.revision===B)return j;const P={t:n.getFixedT(F,o.nsMode==="fallback"?f:f[0],c,{scopeNs:f}),ready:M,lng:F,keyPrefix:c,revision:B};return g.current=P,P},[n,f,c,o,e.lng]),[y,k]=h.useState(0),{t:A,ready:L}=Dl.useSyncExternalStore(p,x,x);h.useEffect(()=>{if(n&&!L&&!l){const M=()=>k(F=>F+1);e.lng?yn(n,e.lng,f,M):da(n,f,M)}},[n,e.lng,f,L,l,y]);const C=n||{},v=h.useRef(null),N=h.useRef(),R=M=>{const F=Object.getOwnPropertyDescriptors(M);F.__original&&delete F.__original;const B=Object.create(Object.getPrototypeOf(M),F);if(!Object.prototype.hasOwnProperty.call(B,"__original"))try{Object.defineProperty(B,"__original",{value:M,writable:!1,enumerable:!1,configurable:!1})}catch{}return B},b=h.useMemo(()=>{const M=C,F=M==null?void 0:M.language;let B=M;M&&(v.current&&v.current.__original===M?N.current!==F?(B=R(M),v.current=B,N.current=F):B=v.current:(B=R(M),v.current=B,N.current=F));const j=!L&&!l?(...P)=>(ca(n,"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(...P)):A,E=[j,B,L];return E.t=j,E.i18n=B,E.ready=L,E},[A,C,L,C.resolvedLanguage,C.language,C.languages]);if(n&&l&&!L)throw new Promise(M=>{const F=()=>M();e.lng?yn(n,e.lng,f,F):da(n,f,F)});return b},Bl={de:{translation:qo},en:{translation:Vo},es:{translation:Ho},fr:{translation:Bo},ja:{translation:zo},pt:{translation:Oo},zh:{translation:Uo}};Xe.use(Ml).init({resources:Bl,lng:"en",fallbackLng:"en",interpolation:{escapeValue:!1},returnNull:!1});var Hl={agentMode:{mode:"single",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 fa="http://localhost:3000",Vl="/favicon.svg",ql="/orbit-logo-light.png",Wl="/orbit-logo-dark.png",Kl={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 rr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ha(t,e){if(!rr(t)||!rr(e))return e;const s={...t};return Object.keys(e).forEach(a=>{if(a==="__proto__"||a==="constructor"||a==="prototype")return;const r=s[a],n=e[a];rr(r)&&rr(n)?s[a]=ha(r,n):n!==void 0&&(s[a]=n)}),s}function Gl(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;const s=e.toLowerCase();return s==="false"||s==="0"||s==="off"||s==="disabled"?null:e}function Xl(t){return t==="single"?"single":"multi"}function Yl(t){const e=t.trim();if(e.startsWith("["))try{const s=JSON.parse(e);return Array.isArray(s)?s.filter(Boolean):[]}catch{return[]}return e.split(/\s+/).filter(Boolean)}function Ql(){const t=Hl||{},e=typeof window<"u"&&window.ORBIT_CHAT_CONFIG||{},s=!!(typeof window<"u"&&window.ORBIT_CHAT_CONFIG);let a=ha(Kl,t);return a=ha(a,e),(!s||!a.auth.domain)&&(a.auth.domain="dev-3c4dpzhecz4gundm.us.auth0.com"),(!s||!a.auth.clientId)&&(a.auth.clientId="9JSe5xtoi5mLXRuov2K7FHYU10ojCQLH"),!s||a.auth.audience,!s||a.auth.provider,!s||a.auth.tenantId,(!s||a.auth.scopes.length===0)&&(a.auth.scopes=Yl("openid profile email User.Read")),a.outOfServiceMessage=Gl(a.outOfServiceMessage),a.agentMode.mode=Xl(a.agentMode.mode),a.agentMode.defaultAdapterId=typeof a.agentMode.defaultAdapterId=="string"?a.agentMode.defaultAdapterId.trim():"",a}const Q=Ql();function Fe(){var e;const t=Q.adapters;if(Array.isArray(t)&&t.length>0){const s=(e=t[0].apiUrl)==null?void 0:e.trim();if(s)return s}return fa}function ut(t){const e=t==null?void 0:t.trim();return e&&e.length>0?e:Fe()}function Zl(){const t=Q.adapters;return Array.isArray(t)&&t.length>0?t[0].id:"default-key"}function Jl(){return Q.agentMode.mode}function _r(){return Jl()==="single"}function Na(){if(!_r())return null;const t=Q.agentMode.defaultAdapterId;return t&&Q.adapters.some(s=>{var a;return((a=s==null?void 0:s.id)==null?void 0:a.trim())===t})?t:null}function wi(){const t=Array.isArray(Q.i18n.activeLanguages)?Q.i18n.activeLanguages.filter(e=>typeof e=="string"):[];return t.length>0?t:["en"]}function ec(){var e;const t=(e=Q.i18n.defaultLanguage)==null?void 0:e.trim();return t&&wi().includes(t)?t:"en"}function Ia(){return Q.application.name}function La(){return Q.application.description}function ki(){return Q.application.inputPlaceholder}function tc(t){var r;const e=t==null?void 0:t.trim();if(!e)return null;const s=Q.adapters.find(n=>{var o;return((o=n==null?void 0:n.id)==null?void 0:o.trim())===e});return((r=s==null?void 0:s.name)==null?void 0:r.trim())||null}function sc(t){var r;const e=t==null?void 0:t.trim();if(!e)return null;const s=Q.adapters.find(n=>{var o;return((o=n==null?void 0:n.id)==null?void 0:o.trim())===e});return((r=s==null?void 0:s.inputPlaceholder)==null?void 0:r.trim())||null}function vi(){return Q.seo.siteUrl.trim()}function rc(){return Array.isArray(Q.seo.alternateSiteUrls)?Q.seo.alternateSiteUrls.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function ac(){return Array.isArray(Q.seo.hostPatterns)?Q.seo.hostPatterns.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function nc(){return Q.seo.exposeAgentNotes}function ic(){var e;return((e=Q.application.favicon)==null?void 0:e.trim())||Vl}function oc(){return Q.features.enableUpload}function lc(){return Q.features.enableAudioOutput}function cc(){return Q.features.enableAudioInput}function vn(){return Q.features.enableFeedbackButtons}function dc(){return Q.features.enableConversationThreads}function Si(){return Q.features.enableAutocomplete}function uc(){return Math.max(1e3,Q.voice.silenceTimeoutMs)}function fc(){return Q.voice.recognitionLanguage}function hc(){const t=Na();if(t)return t;const e=Q.adapters;if(Array.isArray(e)&&e.length>0)for(const s of e){const a=typeof(s==null?void 0:s.id)=="string"?s.id.trim():"";if(a)return a}return null}function pc(){return Q.outOfServiceMessage}function Ea(){return Q.auth.enabled}function it(){const{enabled:t,provider:e,domain:s,clientId:a,tenantId:r}=Q.auth;return!t||!a?!1:e==="entra"?!!r:!!s}function mc(){return Q.auth.domain}function ji(){return Q.auth.clientId}function gc(){return Q.auth.audience}function Tr(){return Q.auth.provider}function xc(){return Q.auth.tenantId}function _a(){const t=Q.auth.scopes;return t.length>0?t:["openid","profile","email"]}function pa(){return Q.header.enabled}function bc(){return Q.header.logoUrl}function yc(){var e;return((e=Q.header.logoUrlLight)==null?void 0:e.trim())||ql}function wc(){var e;return((e=Q.header.logoUrlDark)==null?void 0:e.trim())||Wl}function kc(){var t;return((t=Q.header.logoHeight)==null?void 0:t.trim())||""}function vc(){var t;return((t=Q.header.logoWidth)==null?void 0:t.trim())||""}function Sc(){return Q.header.bgColor}function jc(){return Q.header.textColor}function Cc(){return Q.header.showBorder}function Ci(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 Ai(){return Ci(Q.header.navLinks)}function Ni(){return Q.footer.enabled}function Ac(){return Q.footer.text}function Nc(){return Q.footer.bgColor}function Ic(){return Q.footer.textColor}function Lc(){return Q.footer.showBorder}function Ec(){return Q.footer.layout==="inline"?"inline":"stacked"}function _c(){return Q.footer.topPadding==="normal"?"normal":"large"}function Tc(){const t=Q.startupScripts;return Array.isArray(t)?t.filter(e=>!!(e&&typeof e=="object")).map(e=>{const s=typeof e.src=="string"?e.src.trim():"",a=typeof e.content=="string"?e.content.trim():"",r=typeof e.id=="string"?e.id.trim():"";return{...e,src:s||void 0,content:a||void 0,id:r||void 0}}).filter(e=>!!(e.src||e.content)):[]}function Mc(){return Ci(Q.footer.navLinks)}const Ii=["de","en","es","fr","ja","pt","zh"],ar={de:"Deutsch",en:"English",es:"Español",fr:"Français",ja:"日本語",pt:"Português",zh:"中文"};function mr(t){return Ii.includes(t)}const Li=h.createContext(void 0),Ei="orbit-chat-language";function Fc(){const t=wi().filter(mr);return t.length>0?t:["en"]}function $c(t){const e=localStorage.getItem(Ei);if(e&&mr(e)&&t.includes(e))return e;const s=[...navigator.languages||[],navigator.language].filter(Boolean);for(const r of s){const n=r.split("-")[0].toLowerCase();if(mr(n)&&t.includes(n))return n}const a=ec();return mr(a)&&t.includes(a)?a:t[0]??"en"}function Rc({children:t}){const[e]=h.useState(()=>Fc()),[s,a]=h.useState(()=>$c(e));h.useEffect(()=>{Xe.changeLanguage(s)},[s]),h.useEffect(()=>{localStorage.setItem(Ei,s)},[s]);const r=n=>{Ii.includes(n)&&a(n)};return i.jsx(Li.Provider,{value:{currentLanguage:s,activeLanguages:e,setLanguage:r},children:t})}function Pc(){const t=h.useContext(Li);if(!t)throw new Error("useLanguage must be used within LanguageProvider");return t}/**
10
+ */var wn;function Rl(){if(wn)return ea;wn=1;var t=Po();function e(f,m){return f===m&&(f!==0||1/f===1/m)||f!==f&&m!==m}var s=typeof Object.is=="function"?Object.is:e,a=t.useState,r=t.useEffect,n=t.useLayoutEffect,o=t.useDebugValue;function l(f,m){var p=m(),g=a({inst:{value:p,getSnapshot:m}}),x=g[0].inst,y=g[1];return n(function(){x.value=p,x.getSnapshot=m,c(x)&&y({inst:x})},[f,p,m]),r(function(){return c(x)&&y({inst:x}),f(function(){c(x)&&y({inst:x})})},[f]),o(p),p}function c(f){var m=f.getSnapshot;f=f.value;try{var p=m();return!s(f,p)}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 ea.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:u,ea}var kn;function Pl(){return kn||(kn=1,Jr.exports=Rl()),Jr.exports}var Dl=Pl();const Ul=(t,e)=>{if(es(e))return e;if(jl(e)&&es(e.defaultValue))return e.defaultValue;if(typeof t=="function")return"";if(Array.isArray(t)){const s=t[t.length-1];return typeof s=="function"?"":s}return t},Ol={t:Ul,ready:!1},zl=()=>()=>{},Le=(t,e={})=>{var _,S,I;const{i18n:s}=e,{i18n:a,defaultNS:r}=h.useContext(Fl)||{},n=s||a||Tl();n&&!n.reportNamespaces&&(n.reportNamespaces=new $l),n||ca(n,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=h.useMemo(()=>{var M;return{...El(),...(M=n==null?void 0:n.options)==null?void 0:M.react,...e}},[n,e]),{useSuspense:l,keyPrefix:c}=o,d=r||((_=n==null?void 0:n.options)==null?void 0:_.defaultNS),u=es(d)?[d]:d||["translation"],f=h.useMemo(()=>u,u);(I=(S=n==null?void 0:n.reportNamespaces)==null?void 0:S.addUsedNamespaces)==null||I.call(S,f);const m=h.useRef(0),p=h.useCallback(M=>{if(!n)return zl;const{bindI18n:F,bindI18nStore:H}=o,j=()=>{m.current+=1,M()};return F&&n.on(F,j),H&&n.store.on(H,j),()=>{F&&F.split(" ").forEach(E=>n.off(E,j)),H&&H.split(" ").forEach(E=>n.store.off(E,j))}},[n,o]),g=h.useRef(),x=h.useCallback(()=>{if(!n)return Ol;const M=!!(n.isInitialized||n.initializedStoreOnce)&&f.every(T=>Sl(T,n,o)),F=e.lng||n.language,H=m.current,j=g.current;if(j&&j.ready===M&&j.lng===F&&j.keyPrefix===c&&j.revision===H)return j;const D={t:n.getFixedT(F,o.nsMode==="fallback"?f:f[0],c,{scopeNs:f}),ready:M,lng:F,keyPrefix:c,revision:H};return g.current=D,D},[n,f,c,o,e.lng]),[y,k]=h.useState(0),{t:A,ready:L}=Dl.useSyncExternalStore(p,x,x);h.useEffect(()=>{if(n&&!L&&!l){const M=()=>k(F=>F+1);e.lng?yn(n,e.lng,f,M):da(n,f,M)}},[n,e.lng,f,L,l,y]);const C=n||{},v=h.useRef(null),N=h.useRef(),R=M=>{const F=Object.getOwnPropertyDescriptors(M);F.__original&&delete F.__original;const H=Object.create(Object.getPrototypeOf(M),F);if(!Object.prototype.hasOwnProperty.call(H,"__original"))try{Object.defineProperty(H,"__original",{value:M,writable:!1,enumerable:!1,configurable:!1})}catch{}return H},b=h.useMemo(()=>{const M=C,F=M==null?void 0:M.language;let H=M;M&&(v.current&&v.current.__original===M?N.current!==F?(H=R(M),v.current=H,N.current=F):H=v.current:(H=R(M),v.current=H,N.current=F));const j=!L&&!l?(...D)=>(ca(n,"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(...D)):A,E=[j,H,L];return E.t=j,E.i18n=H,E.ready=L,E},[A,C,L,C.resolvedLanguage,C.language,C.languages]);if(n&&l&&!L)throw new Promise(M=>{const F=()=>M();e.lng?yn(n,e.lng,f,F):da(n,f,F)});return b},Bl={de:{translation:qo},en:{translation:Vo},es:{translation:Ho},fr:{translation:Bo},ja:{translation:zo},pt:{translation:Oo},zh:{translation:Uo}};Xe.use(Ml).init({resources:Bl,lng:"en",fallbackLng:"en",interpolation:{escapeValue:!1},returnNull:!1});var Hl={agentMode:{mode:"single",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 fa="http://localhost:3000",Vl="/favicon.svg",ql="/orbit-logo-light.png",Wl="/orbit-logo-dark.png",Kl={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 rr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ha(t,e){if(!rr(t)||!rr(e))return e;const s={...t};return Object.keys(e).forEach(a=>{if(a==="__proto__"||a==="constructor"||a==="prototype")return;const r=s[a],n=e[a];rr(r)&&rr(n)?s[a]=ha(r,n):n!==void 0&&(s[a]=n)}),s}function Gl(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;const s=e.toLowerCase();return s==="false"||s==="0"||s==="off"||s==="disabled"?null:e}function Xl(t){return t==="single"?"single":"multi"}function Yl(t){const e=t.trim();if(e.startsWith("["))try{const s=JSON.parse(e);return Array.isArray(s)?s.filter(Boolean):[]}catch{return[]}return e.split(/\s+/).filter(Boolean)}function Ql(){const t=Hl||{},e=typeof window<"u"&&window.ORBIT_CHAT_CONFIG||{},s=!!(typeof window<"u"&&window.ORBIT_CHAT_CONFIG);let a=ha(Kl,t);return a=ha(a,e),(!s||!a.auth.domain)&&(a.auth.domain="dev-3c4dpzhecz4gundm.us.auth0.com"),(!s||!a.auth.clientId)&&(a.auth.clientId="9JSe5xtoi5mLXRuov2K7FHYU10ojCQLH"),!s||a.auth.audience,!s||a.auth.provider,!s||a.auth.tenantId,(!s||a.auth.scopes.length===0)&&(a.auth.scopes=Yl("openid profile email User.Read")),a.outOfServiceMessage=Gl(a.outOfServiceMessage),a.agentMode.mode=Xl(a.agentMode.mode),a.agentMode.defaultAdapterId=typeof a.agentMode.defaultAdapterId=="string"?a.agentMode.defaultAdapterId.trim():"",a}const Q=Ql();function Re(){var e;const t=Q.adapters;if(Array.isArray(t)&&t.length>0){const s=(e=t[0].apiUrl)==null?void 0:e.trim();if(s)return s}return fa}function ut(t){const e=t==null?void 0:t.trim();return e&&e.length>0?e:Re()}function Zl(){const t=Q.adapters;return Array.isArray(t)&&t.length>0?t[0].id:"default-key"}function Jl(){return Q.agentMode.mode}function _r(){return Jl()==="single"}function Na(){if(!_r())return null;const t=Q.agentMode.defaultAdapterId;return t&&Q.adapters.some(s=>{var a;return((a=s==null?void 0:s.id)==null?void 0:a.trim())===t})?t:null}function wi(){const t=Array.isArray(Q.i18n.activeLanguages)?Q.i18n.activeLanguages.filter(e=>typeof e=="string"):[];return t.length>0?t:["en"]}function ec(){var e;const t=(e=Q.i18n.defaultLanguage)==null?void 0:e.trim();return t&&wi().includes(t)?t:"en"}function Ia(){return Q.application.name}function La(){return Q.application.description}function ki(){return Q.application.inputPlaceholder}function tc(t){var r;const e=t==null?void 0:t.trim();if(!e)return null;const s=Q.adapters.find(n=>{var o;return((o=n==null?void 0:n.id)==null?void 0:o.trim())===e});return((r=s==null?void 0:s.name)==null?void 0:r.trim())||null}function sc(t){var r;const e=t==null?void 0:t.trim();if(!e)return null;const s=Q.adapters.find(n=>{var o;return((o=n==null?void 0:n.id)==null?void 0:o.trim())===e});return((r=s==null?void 0:s.inputPlaceholder)==null?void 0:r.trim())||null}function vi(){return Q.seo.siteUrl.trim()}function rc(){return Array.isArray(Q.seo.alternateSiteUrls)?Q.seo.alternateSiteUrls.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function ac(){return Array.isArray(Q.seo.hostPatterns)?Q.seo.hostPatterns.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function nc(){return Q.seo.exposeAgentNotes}function ic(){var e;return((e=Q.application.favicon)==null?void 0:e.trim())||Vl}function oc(){return Q.features.enableUpload}function lc(){return Q.features.enableAudioOutput}function cc(){return Q.features.enableAudioInput}function vn(){return Q.features.enableFeedbackButtons}function dc(){return Q.features.enableConversationThreads}function Si(){return Q.features.enableAutocomplete}function uc(){return Math.max(1e3,Q.voice.silenceTimeoutMs)}function fc(){return Q.voice.recognitionLanguage}function hc(){const t=Na();if(t)return t;const e=Q.adapters;if(Array.isArray(e)&&e.length>0)for(const s of e){const a=typeof(s==null?void 0:s.id)=="string"?s.id.trim():"";if(a)return a}return null}function pc(){return Q.outOfServiceMessage}function Ea(){return Q.auth.enabled}function it(){const{enabled:t,provider:e,domain:s,clientId:a,tenantId:r}=Q.auth;return!t||!a?!1:e==="entra"?!!r:!!s}function mc(){return Q.auth.domain}function ji(){return Q.auth.clientId}function gc(){return Q.auth.audience}function Tr(){return Q.auth.provider}function xc(){return Q.auth.tenantId}function _a(){const t=Q.auth.scopes;return t.length>0?t:["openid","profile","email"]}function pa(){return Q.header.enabled}function bc(){return Q.header.logoUrl}function yc(){var e;return((e=Q.header.logoUrlLight)==null?void 0:e.trim())||ql}function wc(){var e;return((e=Q.header.logoUrlDark)==null?void 0:e.trim())||Wl}function kc(){var t;return((t=Q.header.logoHeight)==null?void 0:t.trim())||""}function vc(){var t;return((t=Q.header.logoWidth)==null?void 0:t.trim())||""}function Sc(){return Q.header.bgColor}function jc(){return Q.header.textColor}function Cc(){return Q.header.showBorder}function Ci(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 Ai(){return Ci(Q.header.navLinks)}function Ni(){return Q.footer.enabled}function Ac(){return Q.footer.text}function Nc(){return Q.footer.bgColor}function Ic(){return Q.footer.textColor}function Lc(){return Q.footer.showBorder}function Ec(){return Q.footer.layout==="inline"?"inline":"stacked"}function _c(){return Q.footer.topPadding==="normal"?"normal":"large"}function Tc(){const t=Q.startupScripts;return Array.isArray(t)?t.filter(e=>!!(e&&typeof e=="object")).map(e=>{const s=typeof e.src=="string"?e.src.trim():"",a=typeof e.content=="string"?e.content.trim():"",r=typeof e.id=="string"?e.id.trim():"";return{...e,src:s||void 0,content:a||void 0,id:r||void 0}}).filter(e=>!!(e.src||e.content)):[]}function Mc(){return Ci(Q.footer.navLinks)}const Ii=["de","en","es","fr","ja","pt","zh"],ar={de:"Deutsch",en:"English",es:"Español",fr:"Français",ja:"日本語",pt:"Português",zh:"中文"};function mr(t){return Ii.includes(t)}const Li=h.createContext(void 0),Ei="orbit-chat-language";function Fc(){const t=wi().filter(mr);return t.length>0?t:["en"]}function $c(t){const e=localStorage.getItem(Ei);if(e&&mr(e)&&t.includes(e))return e;const s=[...navigator.languages||[],navigator.language].filter(Boolean);for(const r of s){const n=r.split("-")[0].toLowerCase();if(mr(n)&&t.includes(n))return n}const a=ec();return mr(a)&&t.includes(a)?a:t[0]??"en"}function Rc({children:t}){const[e]=h.useState(()=>Fc()),[s,a]=h.useState(()=>$c(e));h.useEffect(()=>{Xe.changeLanguage(s)},[s]),h.useEffect(()=>{localStorage.setItem(Ei,s)},[s]);const r=n=>{Ii.includes(n)&&a(n)};return i.jsx(Li.Provider,{value:{currentLanguage:s,activeLanguages:e,setLanguage:r},children:t})}function Pc(){const t=h.useContext(Li);if(!t)throw new Error("useLanguage must be used within LanguageProvider");return t}/**
11
11
  * @license lucide-react v0.469.0 - ISC
12
12
  *
13
13
  * This source code is licensed under the ISC license.
@@ -27,297 +27,297 @@ var $o=Object.defineProperty;var Ro=(t,e,s)=>e in t?$o(t,e,{enumerable:!0,config
27
27
  *
28
28
  * This source code is licensed under the ISC license.
29
29
  * See the LICENSE file in the root directory of this source tree.
30
- */const ae=(t,e)=>{const s=h.forwardRef(({className:a,...r},n)=>h.createElement(Oc,{ref:n,iconNode:e,className:_i(`lucide-${Dc(t)}`,a),...r}));return s.displayName=`${t}`,s};/**
30
+ */const ne=(t,e)=>{const s=h.forwardRef(({className:a,...r},n)=>h.createElement(Oc,{ref:n,iconNode:e,className:_i(`lucide-${Dc(t)}`,a),...r}));return s.displayName=`${t}`,s};/**
31
31
  * @license lucide-react v0.469.0 - ISC
32
32
  *
33
33
  * This source code is licensed under the ISC license.
34
34
  * See the LICENSE file in the root directory of this source tree.
35
- */const ma=ae("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/**
35
+ */const ma=ne("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/**
36
36
  * @license lucide-react v0.469.0 - ISC
37
37
  *
38
38
  * This source code is licensed under the ISC license.
39
39
  * See the LICENSE file in the root directory of this source tree.
40
- */const ds=ae("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
40
+ */const ds=ne("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
41
41
  * @license lucide-react v0.469.0 - ISC
42
42
  *
43
43
  * This source code is licensed under the ISC license.
44
44
  * See the LICENSE file in the root directory of this source tree.
45
- */const fs=ae("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/**
45
+ */const fs=ne("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/**
46
46
  * @license lucide-react v0.469.0 - ISC
47
47
  *
48
48
  * This source code is licensed under the ISC license.
49
49
  * See the LICENSE file in the root directory of this source tree.
50
- */const Sn=ae("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
50
+ */const Sn=ne("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
51
51
  * @license lucide-react v0.469.0 - ISC
52
52
  *
53
53
  * This source code is licensed under the ISC license.
54
54
  * See the LICENSE file in the root directory of this source tree.
55
- */const wr=ae("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/**
55
+ */const wr=ne("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/**
56
56
  * @license lucide-react v0.469.0 - ISC
57
57
  *
58
58
  * This source code is licensed under the ISC license.
59
59
  * See the LICENSE file in the root directory of this source tree.
60
- */const ga=ae("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"}]]);/**
60
+ */const ga=ne("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
61
  * @license lucide-react v0.469.0 - ISC
62
62
  *
63
63
  * This source code is licensed under the ISC license.
64
64
  * See the LICENSE file in the root directory of this source tree.
65
- */const zc=ae("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/**
65
+ */const zc=ne("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/**
66
66
  * @license lucide-react v0.469.0 - ISC
67
67
  *
68
68
  * This source code is licensed under the ISC license.
69
69
  * See the LICENSE file in the root directory of this source tree.
70
- */const jn=ae("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"}]]);/**
70
+ */const jn=ne("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
71
  * @license lucide-react v0.469.0 - ISC
72
72
  *
73
73
  * This source code is licensed under the ISC license.
74
74
  * See the LICENSE file in the root directory of this source tree.
75
- */const Cn=ae("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"}]]);/**
75
+ */const Cn=ne("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
76
  * @license lucide-react v0.469.0 - ISC
77
77
  *
78
78
  * This source code is licensed under the ISC license.
79
79
  * See the LICENSE file in the root directory of this source tree.
80
- */const Mr=ae("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"}]]);/**
80
+ */const Mr=ne("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
81
  * @license lucide-react v0.469.0 - ISC
82
82
  *
83
83
  * This source code is licensed under the ISC license.
84
84
  * See the LICENSE file in the root directory of this source tree.
85
- */const Bc=ae("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"}]]);/**
85
+ */const Bc=ne("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
86
  * @license lucide-react v0.469.0 - ISC
87
87
  *
88
88
  * This source code is licensed under the ISC license.
89
89
  * See the LICENSE file in the root directory of this source tree.
90
- */const Hc=ae("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"}]]);/**
90
+ */const Hc=ne("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
91
  * @license lucide-react v0.469.0 - ISC
92
92
  *
93
93
  * This source code is licensed under the ISC license.
94
94
  * See the LICENSE file in the root directory of this source tree.
95
- */const Vc=ae("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"}]]);/**
95
+ */const Vc=ne("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
96
  * @license lucide-react v0.469.0 - ISC
97
97
  *
98
98
  * This source code is licensed under the ISC license.
99
99
  * See the LICENSE file in the root directory of this source tree.
100
- */const Ti=ae("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"}]]);/**
100
+ */const Ti=ne("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
101
  * @license lucide-react v0.469.0 - ISC
102
102
  *
103
103
  * This source code is licensed under the ISC license.
104
104
  * See the LICENSE file in the root directory of this source tree.
105
- */const qc=ae("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"}]]);/**
105
+ */const qc=ne("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
106
  * @license lucide-react v0.469.0 - ISC
107
107
  *
108
108
  * This source code is licensed under the ISC license.
109
109
  * See the LICENSE file in the root directory of this source tree.
110
- */const Mi=ae("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"}]]);/**
110
+ */const Mi=ne("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
111
  * @license lucide-react v0.469.0 - ISC
112
112
  *
113
113
  * This source code is licensed under the ISC license.
114
114
  * See the LICENSE file in the root directory of this source tree.
115
- */const xa=ae("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"}]]);/**
115
+ */const xa=ne("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
116
  * @license lucide-react v0.469.0 - ISC
117
117
  *
118
118
  * This source code is licensed under the ISC license.
119
119
  * See the LICENSE file in the root directory of this source tree.
120
- */const Wc=ae("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"}]]);/**
120
+ */const Wc=ne("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
121
  * @license lucide-react v0.469.0 - ISC
122
122
  *
123
123
  * This source code is licensed under the ISC license.
124
124
  * See the LICENSE file in the root directory of this source tree.
125
- */const Kc=ae("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"}]]);/**
125
+ */const Kc=ne("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
126
  * @license lucide-react v0.469.0 - ISC
127
127
  *
128
128
  * This source code is licensed under the ISC license.
129
129
  * See the LICENSE file in the root directory of this source tree.
130
- */const Gc=ae("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"}]]);/**
130
+ */const Gc=ne("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
131
  * @license lucide-react v0.469.0 - ISC
132
132
  *
133
133
  * This source code is licensed under the ISC license.
134
134
  * See the LICENSE file in the root directory of this source tree.
135
- */const Xc=ae("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"}]]);/**
135
+ */const Xc=ne("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
136
  * @license lucide-react v0.469.0 - ISC
137
137
  *
138
138
  * This source code is licensed under the ISC license.
139
139
  * See the LICENSE file in the root directory of this source tree.
140
- */const Fi=ae("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
140
+ */const Fi=ne("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
141
141
  * @license lucide-react v0.469.0 - ISC
142
142
  *
143
143
  * This source code is licensed under the ISC license.
144
144
  * See the LICENSE file in the root directory of this source tree.
145
- */const $i=ae("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"}]]);/**
145
+ */const $i=ne("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
146
  * @license lucide-react v0.469.0 - ISC
147
147
  *
148
148
  * This source code is licensed under the ISC license.
149
149
  * See the LICENSE file in the root directory of this source tree.
150
- */const Yc=ae("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"}]]);/**
150
+ */const Yc=ne("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
151
  * @license lucide-react v0.469.0 - ISC
152
152
  *
153
153
  * This source code is licensed under the ISC license.
154
154
  * See the LICENSE file in the root directory of this source tree.
155
- */const Qc=ae("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"}]]);/**
155
+ */const Qc=ne("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
156
  * @license lucide-react v0.469.0 - ISC
157
157
  *
158
158
  * This source code is licensed under the ISC license.
159
159
  * See the LICENSE file in the root directory of this source tree.
160
- */const Zc=ae("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"}]]);/**
160
+ */const Zc=ne("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
161
  * @license lucide-react v0.469.0 - ISC
162
162
  *
163
163
  * This source code is licensed under the ISC license.
164
164
  * See the LICENSE file in the root directory of this source tree.
165
- */const An=ae("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"}]]);/**
165
+ */const An=ne("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
166
  * @license lucide-react v0.469.0 - ISC
167
167
  *
168
168
  * This source code is licensed under the ISC license.
169
169
  * See the LICENSE file in the root directory of this source tree.
170
- */const Jc=ae("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"}]]);/**
170
+ */const Jc=ne("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
171
  * @license lucide-react v0.469.0 - ISC
172
172
  *
173
173
  * This source code is licensed under the ISC license.
174
174
  * See the LICENSE file in the root directory of this source tree.
175
- */const ed=ae("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"}]]);/**
175
+ */const ed=ne("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
176
  * @license lucide-react v0.469.0 - ISC
177
177
  *
178
178
  * This source code is licensed under the ISC license.
179
179
  * See the LICENSE file in the root directory of this source tree.
180
- */const td=ae("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"}]]);/**
180
+ */const td=ne("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
181
  * @license lucide-react v0.469.0 - ISC
182
182
  *
183
183
  * This source code is licensed under the ISC license.
184
184
  * See the LICENSE file in the root directory of this source tree.
185
- */const sd=ae("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
185
+ */const sd=ne("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
186
186
  * @license lucide-react v0.469.0 - ISC
187
187
  *
188
188
  * This source code is licensed under the ISC license.
189
189
  * See the LICENSE file in the root directory of this source tree.
190
- */const rd=ae("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"}]]);/**
190
+ */const rd=ne("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
191
  * @license lucide-react v0.469.0 - ISC
192
192
  *
193
193
  * This source code is licensed under the ISC license.
194
194
  * See the LICENSE file in the root directory of this source tree.
195
- */const ad=ae("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"}]]);/**
195
+ */const ad=ne("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
196
  * @license lucide-react v0.469.0 - ISC
197
197
  *
198
198
  * This source code is licensed under the ISC license.
199
199
  * See the LICENSE file in the root directory of this source tree.
200
- */const nd=ae("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"}]]);/**
200
+ */const nd=ne("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
201
  * @license lucide-react v0.469.0 - ISC
202
202
  *
203
203
  * This source code is licensed under the ISC license.
204
204
  * See the LICENSE file in the root directory of this source tree.
205
- */const id=ae("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"}]]);/**
205
+ */const id=ne("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
206
  * @license lucide-react v0.469.0 - ISC
207
207
  *
208
208
  * This source code is licensed under the ISC license.
209
209
  * See the LICENSE file in the root directory of this source tree.
210
- */const od=ae("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"}]]);/**
210
+ */const od=ne("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
211
  * @license lucide-react v0.469.0 - ISC
212
212
  *
213
213
  * This source code is licensed under the ISC license.
214
214
  * See the LICENSE file in the root directory of this source tree.
215
- */const Ri=ae("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"}]]);/**
215
+ */const Ri=ne("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
216
  * @license lucide-react v0.469.0 - ISC
217
217
  *
218
218
  * This source code is licensed under the ISC license.
219
219
  * See the LICENSE file in the root directory of this source tree.
220
- */const ld=ae("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
220
+ */const ld=ne("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
221
221
  * @license lucide-react v0.469.0 - ISC
222
222
  *
223
223
  * This source code is licensed under the ISC license.
224
224
  * See the LICENSE file in the root directory of this source tree.
225
- */const cd=ae("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/**
225
+ */const cd=ne("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/**
226
226
  * @license lucide-react v0.469.0 - ISC
227
227
  *
228
228
  * This source code is licensed under the ISC license.
229
229
  * See the LICENSE file in the root directory of this source tree.
230
- */const Pi=ae("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"}]]);/**
230
+ */const Pi=ne("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
231
  * @license lucide-react v0.469.0 - ISC
232
232
  *
233
233
  * This source code is licensed under the ISC license.
234
234
  * See the LICENSE file in the root directory of this source tree.
235
- */const dd=ae("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"}]]);/**
235
+ */const dd=ne("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
236
  * @license lucide-react v0.469.0 - ISC
237
237
  *
238
238
  * This source code is licensed under the ISC license.
239
239
  * See the LICENSE file in the root directory of this source tree.
240
- */const ud=ae("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"}]]);/**
240
+ */const ud=ne("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
241
  * @license lucide-react v0.469.0 - ISC
242
242
  *
243
243
  * This source code is licensed under the ISC license.
244
244
  * See the LICENSE file in the root directory of this source tree.
245
- */const Ta=ae("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
245
+ */const Ta=ne("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
246
246
  * @license lucide-react v0.469.0 - ISC
247
247
  *
248
248
  * This source code is licensed under the ISC license.
249
249
  * See the LICENSE file in the root directory of this source tree.
250
- */const Nn=ae("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"}]]);/**
250
+ */const Nn=ne("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
251
  * @license lucide-react v0.469.0 - ISC
252
252
  *
253
253
  * This source code is licensed under the ISC license.
254
254
  * See the LICENSE file in the root directory of this source tree.
255
- */const Ma=ae("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"}]]);/**
255
+ */const Ma=ne("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
256
  * @license lucide-react v0.469.0 - ISC
257
257
  *
258
258
  * This source code is licensed under the ISC license.
259
259
  * See the LICENSE file in the root directory of this source tree.
260
- */const fd=ae("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
260
+ */const fd=ne("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
261
261
  * @license lucide-react v0.469.0 - ISC
262
262
  *
263
263
  * This source code is licensed under the ISC license.
264
264
  * See the LICENSE file in the root directory of this source tree.
265
- */const hd=ae("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"}]]);/**
265
+ */const hd=ne("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
266
  * @license lucide-react v0.469.0 - ISC
267
267
  *
268
268
  * This source code is licensed under the ISC license.
269
269
  * See the LICENSE file in the root directory of this source tree.
270
- */const Di=ae("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"}]]);/**
270
+ */const Di=ne("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
271
  * @license lucide-react v0.469.0 - ISC
272
272
  *
273
273
  * This source code is licensed under the ISC license.
274
274
  * See the LICENSE file in the root directory of this source tree.
275
- */const Ui=ae("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"}]]);/**
275
+ */const Ui=ne("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
276
  * @license lucide-react v0.469.0 - ISC
277
277
  *
278
278
  * This source code is licensed under the ISC license.
279
279
  * See the LICENSE file in the root directory of this source tree.
280
- */const Oi=ae("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"}]]);/**
280
+ */const Oi=ne("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
281
  * @license lucide-react v0.469.0 - ISC
282
282
  *
283
283
  * This source code is licensed under the ISC license.
284
284
  * See the LICENSE file in the root directory of this source tree.
285
- */const pd=ae("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"}]]);/**
285
+ */const pd=ne("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
286
  * @license lucide-react v0.469.0 - ISC
287
287
  *
288
288
  * This source code is licensed under the ISC license.
289
289
  * See the LICENSE file in the root directory of this source tree.
290
- */const Fa=ae("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"}]]);/**
290
+ */const Fa=ne("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
291
  * @license lucide-react v0.469.0 - ISC
292
292
  *
293
293
  * This source code is licensed under the ISC license.
294
294
  * See the LICENSE file in the root directory of this source tree.
295
- */const md=ae("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"}]]);/**
295
+ */const md=ne("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
296
  * @license lucide-react v0.469.0 - ISC
297
297
  *
298
298
  * This source code is licensed under the ISC license.
299
299
  * See the LICENSE file in the root directory of this source tree.
300
- */const $a=ae("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"}]]);/**
300
+ */const $a=ne("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
301
  * @license lucide-react v0.469.0 - ISC
302
302
  *
303
303
  * This source code is licensed under the ISC license.
304
304
  * See the LICENSE file in the root directory of this source tree.
305
- */const gd=ae("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"}]]);/**
305
+ */const gd=ne("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
306
  * @license lucide-react v0.469.0 - ISC
307
307
  *
308
308
  * This source code is licensed under the ISC license.
309
309
  * See the LICENSE file in the root directory of this source tree.
310
- */const Je=ae("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/**
310
+ */const Je=ne("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/**
311
311
  * @license lucide-react v0.469.0 - ISC
312
312
  *
313
313
  * This source code is licensed under the ISC license.
314
314
  * See the LICENSE file in the root directory of this source tree.
315
- */const xd=ae("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"}]]);/**
315
+ */const xd=ne("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
316
  * @license lucide-react v0.469.0 - ISC
317
317
  *
318
318
  * This source code is licensed under the ISC license.
319
319
  * See the LICENSE file in the root directory of this source tree.
320
- */const bd=ae("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 yd(t){const e=t.trim().split(`
320
+ */const bd=ne("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 yd(t){const e=t.trim().split(`
321
321
  `);if(e.length<2)return!1;const s=e[0].trim();if(!s.startsWith("|")||(s.match(/\|/g)||[]).length<2)return!1;const a=e[1].trim();if(!a.startsWith("|")||!/^[\s|:|-]+$/.test(a)||!a.includes("-"))return!1;for(let r=2;r<e.length;r++){const n=e[r].trim();if(n!==""&&!n.startsWith("|"))return!1}return!0}function wd(t){return t.replace(/(^|\n)(```|~~~)\s*\n([\s\S]*?)\n\2(\n|$)/g,(e,s,a,r,n)=>yd(r)?`${s}
322
322
  ${r.trim()}
323
323
  ${n}`:e)}function kd(t){const e={};let s=0;return t=t.replace(/\$\$([\s\S]*?)\$\$/g,(a,r)=>{const n=`__DISPLAY_MATH_${s++}__`;return e[n]=`$$${r}$$`,n}),t=t.replace(/\\\[([\s\S]*?)\\\]/g,(a,r)=>{const n=`__DISPLAY_MATH_${s++}__`;return e[n]=`$$${r}$$`,n}),t=t.replace(/\\\(([\s\S]*?)\\\)/g,(a,r)=>{const n=`__INLINE_MATH_${s++}__`;return e[n]=`$${r}$`,n}),t=t.replace(/(^|\n)(```|~~~)([^\n]*)\n([\s\S]*?)\n\2(\n|$)/g,(a,r,n,o,l,c)=>{const d=`__FENCED_CODE_${s++}__`;return e[d]=`${r}${n}${o}
@@ -336,14 +336,14 @@ $$
336
336
  `),e=e.replace(/\\(ne|neq)\$(?=\s*[-+0-9A-Za-z(])/g,"\\$1"),e=jd(e),e=Cd(e),e=Nd(e,a);const r=new Map;let n=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,p,g,x)=>{const y=`__CURRENCY_${n++}__`,k=`__CURRENCY_${n++}__`;return r.set(y,p),r.set(k,x),`${y}${g}${k}`});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,p,g)=>{if(g.substring(p+m.length).match(/^[a-zA-Z]/)&&!m.match(/[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion$/))return m;const y=`__CURRENCY_${n++}__`;return r.set(y,m),y});const{masked:d,masks:u}=vd(e);return e=d,Object.assign(a,u),e=Sd(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,(p,g)=>{if(p.includes("$")||p.includes("__INLINE_MATH_")||p.includes("__DISPLAY_MATH_")||p.includes("__CURRENCY_"))return p;const x=String(g??"").trim();if(/^[A-Za-z]$/.test(x))return p;const y=/[\\^_+=<>]|\\b(?:frac|sqrt|sum|int|lim|log|ln|sin|cos|tan|exp)\b/.test(x),k=/\d/.test(x),A=/[()]/.test(x),L=(x.match(/[A-Z]/g)||[]).length,C=(x.match(/[a-z]/g)||[]).length,v=L>=2,N=k||A||v&&C>0;return!y&&!N?p:p.replace(g,`$${g}$`)})}),e=e.replace(new RegExp("(?<!\\\\)\\$(?!\\$)([^$\\n]*?)(?<!\\\\)\\$(?!\\$)","g"),(m,p)=>{if(m.includes("__CURRENCY_")||m.includes("__INLINE_MATH_")||m.includes("__DISPLAY_MATH_")||p.trim()==="")return m;const g=/^\d+(?:,\d{3})*(?:\.\d{2})?$/.test(p.trim()),x=/\\/.test(p),y=/[+\-*/=<>^_{}()]/.test(p),k=/[a-zA-Z].*\d|\d.*[a-zA-Z]/.test(p),A=/\\(?:alpha|beta|gamma|delta|epsilon|theta|lambda|mu|pi|sigma|omega)/.test(p),L=/\\(?:frac|sqrt|sum|int|lim|log|ln|sin|cos|tan|exp)/.test(p),C=/^[A-Za-z]$/.test(p.trim());return!g&&(x||y||k||A||L||C||p.length>1)?m:`\\$${p}\\$`}),e=e.split(`
337
337
  `).map(m=>{const p=m.indexOf("$$");return p===-1||m.trim()==="$$"||m.indexOf("$$",p+2)!==-1?m:m.replace("$$","\\$\\$")}).join(`
338
338
  `),r.forEach((m,p)=>{const g=m.replace(/\$/g,"&#36;");e=e.replace(new RegExp(p.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),g)}),e=e.replace(/\\&#36;/g,"&#36;"),e=Id(e,a),e=e.trimEnd()+`
339
- `,e}catch(e){return console.warn("Error preprocessing markdown:",e),t}},Ed=h.lazy(()=>Ct(()=>import("./MermaidRenderer-ZdYLQXe1.js").then(t=>t.au),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.MermaidRenderer}))),_d=h.lazy(()=>Ct(()=>import("./SVGRenderer-BUZ2s3dH.js"),__vite__mapDeps([6,1,3,5,7,8,9,2,10])).then(t=>({default:t.SVGRenderer}))),Td=h.lazy(()=>Ct(()=>import("./ChartRenderer-B9WgyQbh.js"),__vite__mapDeps([11,1,5,4,12,13,14,15,16,17,7,8,9,2,10])).then(t=>({default:t.ChartRenderer}))),Md=h.lazy(()=>Ct(()=>import("./MusicRenderer-CPc4ca0i.js"),__vite__mapDeps([18,2,1,5,7,8,9,10])).then(t=>({default:t.MusicRenderer}))),Fd=t=>{var a,r;if(!t)return typeof window<"u"&&((a=window.matchMedia)!=null&&a.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 s=t.closest("[data-theme]");if(s){const n=s.getAttribute("data-theme");if(n==="dark")return"dark";if(n==="light")return"light"}return typeof window<"u"&&((r=window.matchMedia)!=null&&r.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},$d=(t,e)=>{const[s,a]=h.useState("light"),r=h.useRef("light");return h.useEffect(()=>{var d,u,f;if(e||typeof window>"u"||typeof document>"u")return;const n=()=>{const m=Fd(t.current);m!==r.current&&(r.current=m,a(m))};n();const o=((d=window.matchMedia)==null?void 0:d.call(window,"(prefers-color-scheme: dark)"))??null,l=()=>n();o==null||o.addEventListener("change",l);const c=typeof MutationObserver<"u"?new MutationObserver(()=>n()):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??s},Rd={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"},Pd=t=>{if(!t)return"";const e=t.match(/(?:^|\s)language-([^\s]+)/);if(!e)return"";const a=e[1].toLowerCase().split("{")[0].split("[")[0].split("<")[0].split(":")[0].trim().replace(/[^a-z0-9+#-]+$/g,"");return a?Rd[a]??a:""},Dd=t=>gt.Children.toArray(t).map(e=>typeof e=="string"||typeof e=="number"?String(e):"").join("").replace(/\n$/,""),En=({code:t})=>{const{t:e}=Ee(),[s,a]=h.useState(!1),r=async()=>{try{await navigator.clipboard.writeText(t),a(!0),setTimeout(()=>a(!1),2e3)}catch{const n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select();try{document.execCommand("copy"),a(!0),setTimeout(()=>a(!1),2e3)}catch(o){console.error("Failed to copy code:",o)}document.body.removeChild(n)}};return i.jsxs("button",{className:"code-copy-button",onClick:r,title:e(s?"markdown.codeBlock.copied":"markdown.codeBlock.copyTitle"),"aria-label":e(s?"markdown.codeBlock.copied":"markdown.codeBlock.copyAriaLabel"),children:[s?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(s?"markdown.codeBlock.copied":"markdown.codeBlock.copyLabel")})]})},Ud=({inline:t,className:e="",children:s,enableGraphs:a=!0,enableMermaid:r=!0,enableSVG:n=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d})=>{const{t:u}=Ee(),f=h.useRef(null),m=$d(f,d),p=i.jsx("div",{className:"markdown-code-block code-block-container",children:u("markdown.codeBlock.loadingRenderer")});if(t)return i.jsx("code",{className:e,children:s});const g=Pd(e),x=Dd(s);if(o&&(g==="chart"||g==="chart-json"||g==="chart-table"))return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:p,children:i.jsx(Td,{code:x,language:g})})});if(l&&(g==="abc"||g==="music"))return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:p,children:i.jsx(Md,{code:x})})});if(a){if(g==="mermaid"&&r)return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:p,children:i.jsx(Ed,{code:x})})});if(g==="svg"&&n)return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:p,children:i.jsx(_d,{code:x})})})}if(c&&g){const y=m==="light"?Yo:Qo;return i.jsxs("div",{ref:f,className:"syntax-highlighted-wrapper code-block-container",children:[i.jsx(En,{code:x}),i.jsx(Xo,{language:g,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(En,{code:x}),i.jsx("pre",{style:{margin:0,padding:0,background:"transparent",border:"none"},children:i.jsx("code",{children:x})})]})},_n=new Set(["div","pre","blockquote","ul","ol","table","thead","tbody","tr","td","th","h1","h2","h3","h4","h5","h6","section","article","figure"]),Tn=({children:t,href:e="",className:s="",standalone:a=!1,...r})=>{const n=gt.Children.toArray(t).map(f=>typeof f=="string"?f:"").join("").trim(),o=/^https?:\/\//i.test(e),l=!!(o&&n&&Mn(n)===Mn(e)),c=o?Od(e):null,d=!!(a&&l&&c),u=["markdown-link",d?"markdown-link--card":"markdown-link--inline",s].filter(Boolean).join(" ");return i.jsxs("a",{...r,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 Mn(t){return t.trim().replace(/\/$/,"")}function Od(t){try{const e=new URL(t),s=e.hostname.replace(/^www\./i,""),a=`${e.pathname}${e.search}${e.hash}`||"/";return{hostname:s,path:a}}catch{return null}}const _t=({content:t,className:e="",disableMath:s=!1,enableGraphs:a=!0,enableMermaid:r=!0,enableSVG:n=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d="dark"})=>{const u=Ld(t);if(!u)return null;const f=s?[rn]:[rn,[Ko,{singleDollarTextMath:!0}]],m=[];s||m.push([Go,{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 p={table:({children:g,...x})=>i.jsx("div",{style:{overflowX:"auto",WebkitOverflowScrolling:"touch"},children:i.jsx("table",{...x,children:g})}),a:Tn,code:g=>{const{className:x,children:y,...k}=g,A=x&&/language-/.test(x),L="inline"in g&&typeof g.inline=="boolean"&&g.inline||!A,C=A;return i.jsx(Ud,{inline:L,className:x,enableGraphs:a,enableMermaid:r,enableSVG:n,enableCharts:o,enableMusic:l,enableSyntaxHighlighting:c,syntaxTheme:d,"data-block-code":C?"true":void 0,...k,children:y})},p:({node:g,...x})=>{var C;const y=gt.Children.toArray(x.children).filter(v=>!(typeof v=="string"&&v.trim()==="")),k=y.some(v=>{if(!gt.isValidElement(v))return!1;const N=v.props;return(N==null?void 0:N["data-block-code"])==="true"?!0:typeof v.type=="string"?_n.has(v.type):!1}),A=(C=g==null?void 0:g.children)==null?void 0:C.some(v=>{var N;if(v.type==="code")return!0;if(v.type==="element"){if(v.tagName&&_n.has(v.tagName))return!0;if(v.tagName==="code"){const R=(N=v.properties)==null?void 0:N.className;return Array.isArray(R)?R.some(b=>typeof b=="string"&&b.startsWith("language-")):!0}}return!1});if(k||A)return i.jsx(i.Fragment,{children:x.children});if(y.length===1&&gt.isValidElement(y[0])&&y[0].type===Tn){const v=y[0];return i.jsx("p",{...x,children:gt.cloneElement(v,{standalone:!0})})}return i.jsx("p",{...x})}};return i.jsx("div",{className:`markdown-content ${e}`,children:i.jsx(Wo,{remarkPlugins:f,rehypePlugins:m,components:p,children:u})})},Ra=()=>Q.debug.consoleDebug,D=(...t)=>{Ra()&&console.log(...t)},me=(...t)=>{Ra()&&console.warn(...t)},ge=(...t)=>{Ra()&&console.error(...t)},Oe=(...t)=>{console.error(...t)};function Fn(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 nr({audio:t,audioUrl:e,audioFormat:s="mp3",autoPlay:a=!1,maxSizeMB:r=10,downloadFilename:n}){const{t:o}=Ee(),{isDark:l}=ts(),c=h.useRef(null),[d,u]=h.useState(!1),[f,m]=h.useState(0),[p,g]=h.useState(0),[x,y]=h.useState(!0),[k,A]=h.useState(null),[L,C]=h.useState(null),[v,N]=h.useState(null);h.useEffect(()=>{if(!t)return;let E=null,P=!0;return(async()=>{try{y(!0),A(null),C(null);const G=t.length*3/4/(1024*1024);if(G>r)throw new Error(o("audio.player.audioFileTooLargePlaceholder",{sizeMB:G.toFixed(1),maxMB:r}));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),Z=new Uint8Array(V.length);for(let te=0;te<V.length;te++)Z[te]=V.charCodeAt(te);const ue=Fn(s),O=new Blob([Z],{type:ue});if(E=URL.createObjectURL(O),!P){E&&URL.revokeObjectURL(E);return}N(E),y(!1),D("[AudioPlayer] Audio loaded successfully",{format:s,mimeType:ue,size:O.size})}catch(K){ge("[AudioPlayer] Failed to load audio:",K),P&&(A(o("audio.player.loadFailureError")),y(!1))}})(),()=>{P=!1,E&&URL.revokeObjectURL(E)}},[t,s,r,o]),h.useEffect(()=>{if(t||!e)return;let E=null,P=!1;return(async()=>{try{y(!0),A(null);const K=typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null,G=await fetch(e,{headers:K?{"X-Adapter-Name":K}:{}});if(!G.ok)throw new Error(`Server returned ${G.status}`);if(P)return;const V=await G.arrayBuffer();if(P)return;const Z=new Blob([V],{type:Fn(s)});E=URL.createObjectURL(Z),N(E),y(!1)}catch(K){ge("[AudioPlayer] Failed to fetch audio from",e,K),P||(A(o("audio.player.loadFailureError")),y(!1))}})(),()=>{P=!0,E&&URL.revokeObjectURL(E)}},[t,e,s,o]),h.useEffect(()=>{a&&v&&c.current&&c.current.play().catch(E=>{ge("[AudioPlayer] Auto-play failed:",E)})},[a,v]);const R=()=>{c.current&&m(c.current.duration)},b=()=>{c.current&&g(c.current.currentTime)},_=()=>u(!0),S=()=>u(!1),I=()=>{u(!1),g(0)},M=()=>{c.current&&(d?c.current.pause():c.current.play().catch(E=>{ge("[AudioPlayer] Playback failed:",E),A(o("audio.player.playbackFailureError"))}))},F=E=>{if(!c.current)return;const P=parseFloat(E.target.value);c.current.currentTime=P,g(P)},B=()=>{if(!v)return;const E=document.createElement("a");E.href=v,E.download=n||`generated-audio.${s}`,E.click()},j=E=>{if(!isFinite(E))return"0:00";const P=Math.floor(E/60),T=Math.floor(E%60);return`${P}:${T.toString().padStart(2,"0")}`};return k?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($a,{className:"h-4 w-4"}),i.jsx("span",{children:k})]}):i.jsxs("div",{className:"mt-3 flex flex-col gap-1",children:[L&&i.jsxs("div",{className:"text-xs text-amber-600 dark:text-amber-400 px-1",children:["⚠️ ",L]}),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:v??void 0,onLoadedMetadata:R,onTimeUpdate:b,onPlay:_,onPause:S,onEnded:I}),i.jsx("button",{onClick:M,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(od,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"}):i.jsx(ld,{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(p)}),i.jsx("input",{type:"range",min:"0",max:f||0,value:p,onChange:F,disabled:x||!f,className:"flex-1 cursor-pointer accent-gray-600 dark:accent-[#bfc2cd]",style:{background:(()=>{const E=l?"rgb(191 194 205)":"rgb(75 85 99)",P=l?"rgba(255 255 255 / 0.12)":"rgb(229 231 235)",T=f?p/f*100:0;return`linear-gradient(to right, ${E} 0%, ${E} ${T}%, ${P} ${T}%, ${P} 100%)`})()}}),i.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:j(f)})]}),n&&i.jsx("button",{onClick:B,disabled:x||!v,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(Mr,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"})})]})]})}function $n({image:t,imageUrl:e,imageFormat:s="png",revisedPrompt:a}){const{t:r}=Ee(),[n,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,k=await fetch(e,{headers:y?{"X-Adapter-Name":y}:{}});if(!k.ok){console.warn("[ImageDisplay] Server returned",k.status,"for",e);return}if(x)return;const A=await k.arrayBuffer();if(x)return;const L=new Blob([A],{type:`image/${s}`}),C=URL.createObjectURL(L);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,s]);const p=(t?`data:image/${s};base64,${t}`:null)??d;h.useEffect(()=>{if(!n)return;const x=y=>{y.key==="Escape"&&o(!1)};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[n]);const g=x=>{if(x.stopPropagation(),!p)return;const y=document.createElement("a");y.href=p,y.download=`generated-image.${s}`,y.click()};return p?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:a||r("imageDisplay.generatedImageTitle"),children:[i.jsx("img",{src:p,alt:a||r("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:g,title:r("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(Mr,{size:14})}),i.jsx("button",{onClick:x=>{x.stopPropagation(),o(!0)},title:r("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(bd,{size:14})})]})]}),a&&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(wr,{size:14}):i.jsx(fs,{size:14}),r(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:r("imageDisplay.promptLabel")}),i.jsx("span",{style:{fontSize:"0.8rem",lineHeight:1.45,opacity:.85},children:a})]})]})]}),n&&typeof document<"u"&&Ir.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:p,alt:a||r("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 ta=[750,1500,3e3,5e3],zd=new Set([403,404,409,425,429,500,502,503,504]),Bd=t=>new Promise(e=>setTimeout(e,t));function Rn({video:t,videoUrl:e,videoFormat:s="mp4",revisedPrompt:a,adapterName:r}){const{t:n}=Ee(),[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 k=r||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null);let A=null;for(let N=0;N<=ta.length&&(A=await fetch(e,{headers:k?{"X-Adapter-Name":k}:{}}),!(A.ok||!zd.has(A.status)||N===ta.length));N+=1)if(await Bd(ta[N]),y)return;if(!A||!A.ok){console.warn("[VideoDisplay] Server returned",A==null?void 0:A.status,"for",e);return}if(y)return;const L=await A.arrayBuffer();if(y)return;const C=new Blob([L],{type:`video/${s}`}),v=URL.createObjectURL(C);m.current=v,f(v)}catch(k){console.warn("[VideoDisplay] Failed to fetch video from",e,k)}})(),()=>{y=!0,m.current&&(URL.revokeObjectURL(m.current),m.current=null)}},[e,t,s,r]);const g=(t?`data:video/${s};base64,${t}`:null)??u;h.useEffect(()=>{if(!o)return;const y=k=>{k.key==="Escape"&&l(!1)};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[o]);const x=y=>{if(y.stopPropagation(),!g)return;const k=document.createElement("a");k.href=g,k.download=`generated-video.${s}`,k.click()};return g?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:g,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:n("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(Mr,{size:14})}),i.jsx("button",{onClick:y=>{y.stopPropagation(),l(!0)},title:n("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(Qc,{size:14})})]})]}),a&&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(wr,{size:14}):i.jsx(fs,{size:14}),n(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:n("videoDisplay.promptLabel")}),i.jsx("span",{style:{fontSize:"0.8rem",lineHeight:1.45,opacity:.85},children:a})]})]})]}),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:g,controls:!0,autoPlay:!0,style:{maxWidth:"92vw",maxHeight:"92vh",borderRadius:"8px"},onClick:y=>y.stopPropagation()})]})]}):null}let kr=null;function zi(t){kr=t}function Fr(){kr=null}async function Pa(){if(!kr)return null;try{return await kr()}catch{return null}}let ba=!1,Ps=null;const ya=new Set;function Bi(){ya.forEach(t=>t())}function wt(){return ba}function Hd(){return Ps}function $r(t){ba!==t&&(ba=t,!t&&Ps!==null&&(Ps=null),Bi())}function us(t){const e=typeof t=="string"&&t.trim().length>0?t.trim():null;Ps!==e&&(Ps=e,Bi())}function Vd(t){return ya.add(t),()=>{ya.delete(t)}}const Pn="orbitchat-guest-user-id";function ir(t){if(typeof t!="string")return null;const e=t.trim();return e.length>0?e:null}function qd(t){const e=t.split(".");if(e.length<2)return null;try{const s=e[1].replace(/-/g,"+").replace(/_/g,"/"),a=s.padEnd(Math.ceil(s.length/4)*4,"="),r=atob(a);return JSON.parse(r)}catch{return null}}function Wd(){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,a=>a.toString(16).padStart(2,"0")).join("")}`}function Kd(){if(typeof window>"u")return"guest:orbitchat:server";const t=window.localStorage.getItem(Pn);if(t&&t.trim().length>0)return t;const e=Wd();return window.localStorage.setItem(Pn,e),e}async function Hi(){const t=Hd();if(t)return t;const e=await Pa();if(e){const s=qd(e),a=ir(s==null?void 0:s.sub)||ir(s==null?void 0:s.user_id)||ir(s==null?void 0:s.preferred_username)||ir(s==null?void 0:s.email);if(a)return a}return wt()?"authenticated:orbitchat:unknown":Kd()}const Gd={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"},Dn={pdf:"PDF",docx:"Word document",xlsx:"Excel workbook",pptx:"PowerPoint deck",md:"Markdown document",csv:"CSV file"},gr=/[\uE000-\uF8FF]|\\[eE][0-9a-fA-F]{2,3}|\\[fF][0-8][0-9a-fA-F]{2,3}/,Xd=/((?:p\.)?generated-docx-preview-num-\d+-\d+:before\s*\{[^}]*?)content\s*:\s*"([^"]*)"\s*;([^}]*?\})/g;function Yd(t){var s;return gr.test(t)?`•${((s=t.match(/(?:\\9|\t|\u00A0| )+$/))==null?void 0:s[0])||"\\9"}`:null}function Un(t){Array.from(t.querySelectorAll("style")).forEach(a=>{const r=a.textContent;!r||!gr.test(r)||(a.textContent=r.replace(Xd,(n,o,l,c)=>{const d=Yd(l);if(!d)return n;const u=c.replace(/\s*font-family\s*:\s*[^;{}]+;?/gi,"");return`${o}content: "${d}";${u}`}))}),Array.from(t.querySelectorAll('span[style*="font-family"]')).forEach(a=>{if(!/\b(symbol|wingdings|webdings)\b/i.test(a.style.fontFamily))return;const r=a.textContent||"";gr.test(r)&&(a.textContent=r.replace(gr,"•"),a.style.fontFamily="")})}function Qd(t){return(t||"pdf").toLowerCase().replace(/^\./,"")||"pdf"}function Zd(t){const e=window.atob(t),s=new Uint8Array(e.length);for(let a=0;a<e.length;a+=1)s[a]=e.charCodeAt(a);return s.buffer}function Jd(t){return t==="xlsx"||t==="csv"?i.jsx(Mi,{className:"h-5 w-5"}):t==="pptx"?i.jsx(Pi,{className:"h-5 w-5"}):t==="md"?i.jsx(Ti,{className:"h-5 w-5"}):i.jsx(xa,{className:"h-5 w-5"})}function On({document:t,documentUrl:e,documentFormat:s="pdf",revisedPrompt:a,adapterName:r}){const{t:n}=Ee(),o=Qd(s),[l,c]=h.useState(t||e?"loading":"idle"),[d,u]=h.useState(null),[f,m]=h.useState(null),[p,g]=h.useState([]),[x,y]=h.useState(""),[k,A]=h.useState(null),[L,C]=h.useState([]),[v,N]=h.useState(0),[R,b]=h.useState(!1),[_,S]=h.useState(null),I=h.useRef(null),M=h.useRef(null),F=h.useRef(null),B=a||Dn[o]||n("documentDisplay.generatedDocument"),j=h.useMemo(()=>`generated-document.${o}`,[o]),E=Gd[o]||"application/octet-stream";h.useEffect(()=>{if(!t&&!e)return;let G=!1;return(async()=>{c("loading"),S(null),g([]),y(""),A(null),C([]),N(0);try{const Z=t?Zd(t):await(async()=>{const te=(r==null?void 0:r.trim())||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),Y={"X-User-ID":await Hi()};te&&(Y["X-Adapter-Name"]=te);const ee=await Pa();ee&&(Y.Authorization=`Bearer ${ee}`);const re=await fetch(e,{headers:Y});if(!re.ok)throw new Error(`Server returned ${re.status}`);return re.arrayBuffer()})();if(G)return;const ue=new Blob([Z],{type:E}),O=URL.createObjectURL(ue);if(I.current&&URL.revokeObjectURL(I.current),I.current=O,u(O),m(Z.slice(0)),o==="xlsx"){const{default:te}=await Ct(async()=>{const{default:re}=await import("./index-CZz_ECqk.js");return{default:re}},[]),ee=(await te(ue))[0];y((ee==null?void 0:ee.sheet)||"First sheet"),g(((ee==null?void 0:ee.data)||[]).slice(0,100).map(re=>re.slice(0,30).map(fe=>fe==null?"":String(fe))))}if(o==="md"&&A(new TextDecoder("utf-8").decode(Z)),o==="csv"){const te=new TextDecoder("utf-8").decode(Z),{default:Y}=await Ct(async()=>{const{default:re}=await import("./papaparse.min-D13ujVVP.js").then(fe=>fe.p);return{default:re}},__vite__mapDeps([19,1])),ee=Y.parse(te,{skipEmptyLines:!0});N(ee.data.length),C(ee.data.slice(0,25))}c("ready")}catch(Z){if(G)return;console.warn("[DocumentDisplay] Failed to load document from",e,Z),S(Z instanceof Error?Z.message:"Unable to load document"),c("error")}})(),()=>{G=!0,I.current&&(URL.revokeObjectURL(I.current),I.current=null)}},[r,t,e,o,E]),h.useEffect(()=>{if(l!=="ready"||o!=="docx"||!f||!M.current)return;const G=M.current;G.replaceChildren(),Ct(()=>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}),Un(G)}).catch(V=>{console.warn("[DocumentDisplay] Failed to render DOCX preview",V),S("Unable to render document preview")})},[f,o,l]),h.useEffect(()=>{if(!R||o!=="docx"||!f||!F.current)return;const G=F.current;G.replaceChildren(),Ct(()=>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}),Un(G)}).catch(V=>{console.warn("[DocumentDisplay] Failed to render modal DOCX preview",V)})},[f,o,R]),h.useEffect(()=>{if(!R)return;const G=V=>{V.key==="Escape"&&b(!1)};return window.document.addEventListener("keydown",G),()=>window.document.removeEventListener("keydown",G)},[R]);const P=G=>{if(G==null||G.stopPropagation(),!d)return;const V=window.document.createElement("a");V.href=d,V.download=j,V.click()},T=l==="ready"&&(o==="pdf"||o==="docx"||o==="xlsx"||o==="md"||o==="csv"),K=T&&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:Jd(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:B}),i.jsxs("p",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:[Dn[o]||`${o.toUpperCase()} document`,l==="loading"?` · ${n("documentDisplay.loadingPreview")}`:"",l==="error"?` · ${_||n("documentDisplay.previewUnavailableShort")}`:""]})]}),K&&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:n("documentDisplay.openPreviewTooltip"),"aria-label":n("documentDisplay.openPreviewTooltip"),children:i.jsx(Bc,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:P,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:n("documentDisplay.downloadDocumentTooltip"),"aria-label":n("documentDisplay.downloadDocumentTooltip"),children:i.jsx(Mr,{className:"h-4 w-4"})})]}),T&&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:B,className:"block h-[460px] w-full border-0 bg-white"}),o==="docx"&&i.jsx("div",{ref:M,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:p.length>0?p.map((G,V)=>i.jsx("tr",{className:V===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:G.map((Z,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:Z},ue))},V)):i.jsx("tr",{children:i.jsx("td",{className:"px-3 py-4 text-sm text-gray-500 dark:text-[#bfc2cd]",children:n("documentDisplay.noSheetDataFound")})})})})})]}),o==="md"&&k!==null&&i.jsx("div",{className:"bg-white p-5 text-sm text-[#111827] dark:bg-[#171717] dark:text-[#ececf1]",children:i.jsx(_t,{content:k,disableMath:!0})}),o==="csv"&&i.jsxs("div",{className:"p-3",children:[v>25&&i.jsx("p",{className:"mb-2 text-xs text-gray-500 dark:text-[#bfc2cd]",children:n("documentDisplay.csvRowsPreviewMessage",{count:v})}),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:L.length>0?L.map((G,V)=>i.jsx("tr",{className:V===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:G.map((Z,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:Z},ue))},V)):i.jsx("tr",{children:i.jsx("td",{className:"px-3 py-4 text-sm text-gray-500 dark:text-[#bfc2cd]",children:n("documentDisplay.noDataFound")})})})})})]})]}),l==="ready"&&!T&&i.jsx("div",{className:"px-3 py-4 text-sm text-gray-600 dark:text-[#bfc2cd]",children:n("documentDisplay.previewUnavailable")})]}),R&&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:n("common.close"),"aria-label":n("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:B,className:"h-full w-full border-0"}),o==="docx"&&i.jsx("div",{ref:F,className:"min-h-full bg-white p-8 text-[#111827]"}),o==="md"&&k!==null&&i.jsx("div",{className:"min-h-full bg-white p-8 text-sm text-[#111827]",children:i.jsx(_t,{content:k,disableMath:!0})})]})]})]})}const eu=["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 Ds(t,{enabled:e,onEscape:s}){h.useEffect(()=>{if(!e||!t.current)return;const a=t.current,r=document.activeElement,n=Array.from(a.querySelectorAll(eu)).filter(d=>d.tabIndex!==-1),o=n[0]||a,l=n[n.length-1]||a;o.focus({preventScroll:!0});const c=d=>{if(d.key==="Escape"){s==null||s();return}if(d.key!=="Tab")return;if(n.length===0){d.preventDefault(),a.focus({preventScroll:!0});return}const u=document.activeElement;if(d.shiftKey){(!u||u===o||!a.contains(u))&&(d.preventDefault(),l.focus({preventScroll:!0}));return}(!u||u===l||!a.contains(u))&&(d.preventDefault(),o.focus({preventScroll:!0}))};return document.addEventListener("keydown",c),()=>{var d;document.removeEventListener("keydown",c),(d=r==null?void 0:r.focus)==null||d.call(r,{preventScroll:!0})}},[e,s,t])}function vr({isOpen:t,onClose:e,onConfirm:s,title:a,message:r,confirmText:n,cancelText:o,type:l="danger",isLoading:c=!1}){const d=h.useRef(null);Ds(d,{enabled:t,onEscape:e});const{t:u}=Ee(),f=n??u("common.confirm"),m=o??u("common.cancel");if(!t)return null;const p=()=>{c||s()},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(Fa,{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:a})]}),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:r})}),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:p,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:Ir.createPortal(y,document.body)}const tu=["#","*","`","[","]","(",")","{","}","|","<",">"],Vi=t=>tu.some(e=>t.includes(e));function qi(t){if(!t||t.length<1e3)return!1;const e=/^[A-Za-z0-9+/=]+$/,s=t.replace(/\s+/g,"");if(s.length>1e4&&e.test(s)){const a=/\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),r=Vi(t),n=/[-.,;:!?'"()]/.test(t);if(!a&&!r&&!n)return!0}return!!(s.length>5e4&&e.test(s)&&t.replace(/[A-Za-z0-9+/=\s]/g,"").length<10)}const su=/(?:\u202F|\u2009|\u200A|\u200B|\u200C|\u200D|\uFEFF)/g;function Us(t){if(!t)return t;let e=t.replace(su," ");if(qi(e))return"";const s=/([A-Za-z0-9+/=]{10000,})/g;return e=e.replace(s,a=>{const r=a.replace(/\s+/g,"");if(r.length>1e4&&/^[A-Za-z0-9+/=]+$/.test(r)){const n=/\b(function|const|let|var|class|return|import|export|if|else|while|for|true|false|null|def|print)\b/i.test(a),o=Vi(a),l=/[-.,;:!?'"()]/.test(a);if(!n&&!o&&!l)return""}return a}),e}function wa(t,e=5e4){return!t||t.length<=e?t:qi(t)?"":t.substring(0,e)+`
339
+ `,e}catch(e){return console.warn("Error preprocessing markdown:",e),t}},Ed=h.lazy(()=>Ct(()=>import("./MermaidRenderer-DxunGWXF.js").then(t=>t.au),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.MermaidRenderer}))),_d=h.lazy(()=>Ct(()=>import("./SVGRenderer-DKegh4A9.js"),__vite__mapDeps([6,1,3,5,7,8,9,2,10])).then(t=>({default:t.SVGRenderer}))),Td=h.lazy(()=>Ct(()=>import("./ChartRenderer-BFQlovpe.js"),__vite__mapDeps([11,1,5,4,12,13,14,15,16,17,7,8,9,2,10])).then(t=>({default:t.ChartRenderer}))),Md=h.lazy(()=>Ct(()=>import("./MusicRenderer-qpZbjlwR.js"),__vite__mapDeps([18,2,1,5,7,8,9,10])).then(t=>({default:t.MusicRenderer}))),Fd=t=>{var a,r;if(!t)return typeof window<"u"&&((a=window.matchMedia)!=null&&a.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 s=t.closest("[data-theme]");if(s){const n=s.getAttribute("data-theme");if(n==="dark")return"dark";if(n==="light")return"light"}return typeof window<"u"&&((r=window.matchMedia)!=null&&r.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},$d=(t,e)=>{const[s,a]=h.useState("light"),r=h.useRef("light");return h.useEffect(()=>{var d,u,f;if(e||typeof window>"u"||typeof document>"u")return;const n=()=>{const m=Fd(t.current);m!==r.current&&(r.current=m,a(m))};n();const o=((d=window.matchMedia)==null?void 0:d.call(window,"(prefers-color-scheme: dark)"))??null,l=()=>n();o==null||o.addEventListener("change",l);const c=typeof MutationObserver<"u"?new MutationObserver(()=>n()):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??s},Rd={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"},Pd=t=>{if(!t)return"";const e=t.match(/(?:^|\s)language-([^\s]+)/);if(!e)return"";const a=e[1].toLowerCase().split("{")[0].split("[")[0].split("<")[0].split(":")[0].trim().replace(/[^a-z0-9+#-]+$/g,"");return a?Rd[a]??a:""},Dd=t=>gt.Children.toArray(t).map(e=>typeof e=="string"||typeof e=="number"?String(e):"").join("").replace(/\n$/,""),En=({code:t})=>{const{t:e}=Le(),[s,a]=h.useState(!1),r=async()=>{try{await navigator.clipboard.writeText(t),a(!0),setTimeout(()=>a(!1),2e3)}catch{const n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select();try{document.execCommand("copy"),a(!0),setTimeout(()=>a(!1),2e3)}catch(o){console.error("Failed to copy code:",o)}document.body.removeChild(n)}};return i.jsxs("button",{className:"code-copy-button",onClick:r,title:e(s?"markdown.codeBlock.copied":"markdown.codeBlock.copyTitle"),"aria-label":e(s?"markdown.codeBlock.copied":"markdown.codeBlock.copyAriaLabel"),children:[s?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(s?"markdown.codeBlock.copied":"markdown.codeBlock.copyLabel")})]})},Ud=({inline:t,className:e="",children:s,enableGraphs:a=!0,enableMermaid:r=!0,enableSVG:n=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d})=>{const{t:u}=Le(),f=h.useRef(null),m=$d(f,d),p=i.jsx("div",{className:"markdown-code-block code-block-container",children:u("markdown.codeBlock.loadingRenderer")});if(t)return i.jsx("code",{className:e,children:s});const g=Pd(e),x=Dd(s);if(o&&(g==="chart"||g==="chart-json"||g==="chart-table"))return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:p,children:i.jsx(Td,{code:x,language:g})})});if(l&&(g==="abc"||g==="music"))return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:p,children:i.jsx(Md,{code:x})})});if(a){if(g==="mermaid"&&r)return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:p,children:i.jsx(Ed,{code:x})})});if(g==="svg"&&n)return i.jsx("div",{ref:f,children:i.jsx(h.Suspense,{fallback:p,children:i.jsx(_d,{code:x})})})}if(c&&g){const y=m==="light"?Yo:Qo;return i.jsxs("div",{ref:f,className:"syntax-highlighted-wrapper code-block-container",children:[i.jsx(En,{code:x}),i.jsx(Xo,{language:g,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(En,{code:x}),i.jsx("pre",{style:{margin:0,padding:0,background:"transparent",border:"none"},children:i.jsx("code",{children:x})})]})},_n=new Set(["div","pre","blockquote","ul","ol","table","thead","tbody","tr","td","th","h1","h2","h3","h4","h5","h6","section","article","figure"]),Tn=({children:t,href:e="",className:s="",standalone:a=!1,...r})=>{const n=gt.Children.toArray(t).map(f=>typeof f=="string"?f:"").join("").trim(),o=/^https?:\/\//i.test(e),l=!!(o&&n&&Mn(n)===Mn(e)),c=o?Od(e):null,d=!!(a&&l&&c),u=["markdown-link",d?"markdown-link--card":"markdown-link--inline",s].filter(Boolean).join(" ");return i.jsxs("a",{...r,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 Mn(t){return t.trim().replace(/\/$/,"")}function Od(t){try{const e=new URL(t),s=e.hostname.replace(/^www\./i,""),a=`${e.pathname}${e.search}${e.hash}`||"/";return{hostname:s,path:a}}catch{return null}}const _t=({content:t,className:e="",disableMath:s=!1,enableGraphs:a=!0,enableMermaid:r=!0,enableSVG:n=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d="dark"})=>{const u=Ld(t);if(!u)return null;const f=s?[rn]:[rn,[Ko,{singleDollarTextMath:!0}]],m=[];s||m.push([Go,{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 p={table:({children:g,...x})=>i.jsx("div",{style:{overflowX:"auto",WebkitOverflowScrolling:"touch"},children:i.jsx("table",{...x,children:g})}),a:Tn,code:g=>{const{className:x,children:y,...k}=g,A=x&&/language-/.test(x),L="inline"in g&&typeof g.inline=="boolean"&&g.inline||!A,C=A;return i.jsx(Ud,{inline:L,className:x,enableGraphs:a,enableMermaid:r,enableSVG:n,enableCharts:o,enableMusic:l,enableSyntaxHighlighting:c,syntaxTheme:d,"data-block-code":C?"true":void 0,...k,children:y})},p:({node:g,...x})=>{var C;const y=gt.Children.toArray(x.children).filter(v=>!(typeof v=="string"&&v.trim()==="")),k=y.some(v=>{if(!gt.isValidElement(v))return!1;const N=v.props;return(N==null?void 0:N["data-block-code"])==="true"?!0:typeof v.type=="string"?_n.has(v.type):!1}),A=(C=g==null?void 0:g.children)==null?void 0:C.some(v=>{var N;if(v.type==="code")return!0;if(v.type==="element"){if(v.tagName&&_n.has(v.tagName))return!0;if(v.tagName==="code"){const R=(N=v.properties)==null?void 0:N.className;return Array.isArray(R)?R.some(b=>typeof b=="string"&&b.startsWith("language-")):!0}}return!1});if(k||A)return i.jsx(i.Fragment,{children:x.children});if(y.length===1&&gt.isValidElement(y[0])&&y[0].type===Tn){const v=y[0];return i.jsx("p",{...x,children:gt.cloneElement(v,{standalone:!0})})}return i.jsx("p",{...x})}};return i.jsx("div",{className:`markdown-content ${e}`,children:i.jsx(Wo,{remarkPlugins:f,rehypePlugins:m,components:p,children:u})})},Ra=()=>Q.debug.consoleDebug,U=(...t)=>{Ra()&&console.log(...t)},ge=(...t)=>{Ra()&&console.warn(...t)},xe=(...t)=>{Ra()&&console.error(...t)},ze=(...t)=>{console.error(...t)};function Fn(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 nr({audio:t,audioUrl:e,audioFormat:s="mp3",autoPlay:a=!1,maxSizeMB:r=10,downloadFilename:n}){const{t:o}=Le(),{isDark:l}=ts(),c=h.useRef(null),[d,u]=h.useState(!1),[f,m]=h.useState(0),[p,g]=h.useState(0),[x,y]=h.useState(!0),[k,A]=h.useState(null),[L,C]=h.useState(null),[v,N]=h.useState(null);h.useEffect(()=>{if(!t)return;let E=null,D=!0;return(async()=>{try{y(!0),A(null),C(null);const X=t.length*3/4/(1024*1024);if(X>r)throw new Error(o("audio.player.audioFileTooLargePlaceholder",{sizeMB:X.toFixed(1),maxMB:r}));if(X>2&&(C(o("audio.player.largeAudioWarning",{sizeMB:X.toFixed(1)})),U("[AudioPlayer] Large audio file detected",{sizeMB:X.toFixed(2)})),!/^[A-Za-z0-9+/=]+$/.test(t.replace(/\s/g,"")))throw new Error(o("audio.player.invalidBase64Error"));const V=atob(t),Z=new Uint8Array(V.length);for(let se=0;se<V.length;se++)Z[se]=V.charCodeAt(se);const fe=Fn(s),z=new Blob([Z],{type:fe});if(E=URL.createObjectURL(z),!D){E&&URL.revokeObjectURL(E);return}N(E),y(!1),U("[AudioPlayer] Audio loaded successfully",{format:s,mimeType:fe,size:z.size})}catch(G){xe("[AudioPlayer] Failed to load audio:",G),D&&(A(o("audio.player.loadFailureError")),y(!1))}})(),()=>{D=!1,E&&URL.revokeObjectURL(E)}},[t,s,r,o]),h.useEffect(()=>{if(t||!e)return;let E=null,D=!1;return(async()=>{try{y(!0),A(null);const G=typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null,X=await fetch(e,{headers:G?{"X-Adapter-Name":G}:{}});if(!X.ok)throw new Error(`Server returned ${X.status}`);if(D)return;const V=await X.arrayBuffer();if(D)return;const Z=new Blob([V],{type:Fn(s)});E=URL.createObjectURL(Z),N(E),y(!1)}catch(G){xe("[AudioPlayer] Failed to fetch audio from",e,G),D||(A(o("audio.player.loadFailureError")),y(!1))}})(),()=>{D=!0,E&&URL.revokeObjectURL(E)}},[t,e,s,o]),h.useEffect(()=>{a&&v&&c.current&&c.current.play().catch(E=>{xe("[AudioPlayer] Auto-play failed:",E)})},[a,v]);const R=()=>{c.current&&m(c.current.duration)},b=()=>{c.current&&g(c.current.currentTime)},_=()=>u(!0),S=()=>u(!1),I=()=>{u(!1),g(0)},M=()=>{c.current&&(d?c.current.pause():c.current.play().catch(E=>{xe("[AudioPlayer] Playback failed:",E),A(o("audio.player.playbackFailureError"))}))},F=E=>{if(!c.current)return;const D=parseFloat(E.target.value);c.current.currentTime=D,g(D)},H=()=>{if(!v)return;const E=document.createElement("a");E.href=v,E.download=n||`generated-audio.${s}`,E.click()},j=E=>{if(!isFinite(E))return"0:00";const D=Math.floor(E/60),T=Math.floor(E%60);return`${D}:${T.toString().padStart(2,"0")}`};return k?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($a,{className:"h-4 w-4"}),i.jsx("span",{children:k})]}):i.jsxs("div",{className:"mt-3 flex flex-col gap-1",children:[L&&i.jsxs("div",{className:"text-xs text-amber-600 dark:text-amber-400 px-1",children:["⚠️ ",L]}),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:v??void 0,onLoadedMetadata:R,onTimeUpdate:b,onPlay:_,onPause:S,onEnded:I}),i.jsx("button",{onClick:M,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(od,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"}):i.jsx(ld,{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(p)}),i.jsx("input",{type:"range",min:"0",max:f||0,value:p,onChange:F,disabled:x||!f,className:"flex-1 cursor-pointer accent-gray-600 dark:accent-[#bfc2cd]",style:{background:(()=>{const E=l?"rgb(191 194 205)":"rgb(75 85 99)",D=l?"rgba(255 255 255 / 0.12)":"rgb(229 231 235)",T=f?p/f*100:0;return`linear-gradient(to right, ${E} 0%, ${E} ${T}%, ${D} ${T}%, ${D} 100%)`})()}}),i.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:j(f)})]}),n&&i.jsx("button",{onClick:H,disabled:x||!v,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(Mr,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"})})]})]})}function $n({image:t,imageUrl:e,imageFormat:s="png",revisedPrompt:a}){const{t:r}=Le(),[n,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,k=await fetch(e,{headers:y?{"X-Adapter-Name":y}:{}});if(!k.ok){console.warn("[ImageDisplay] Server returned",k.status,"for",e);return}if(x)return;const A=await k.arrayBuffer();if(x)return;const L=new Blob([A],{type:`image/${s}`}),C=URL.createObjectURL(L);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,s]);const p=(t?`data:image/${s};base64,${t}`:null)??d;h.useEffect(()=>{if(!n)return;const x=y=>{y.key==="Escape"&&o(!1)};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[n]);const g=x=>{if(x.stopPropagation(),!p)return;const y=document.createElement("a");y.href=p,y.download=`generated-image.${s}`,y.click()};return p?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:a||r("imageDisplay.generatedImageTitle"),children:[i.jsx("img",{src:p,alt:a||r("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:g,title:r("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(Mr,{size:14})}),i.jsx("button",{onClick:x=>{x.stopPropagation(),o(!0)},title:r("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(bd,{size:14})})]})]}),a&&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(wr,{size:14}):i.jsx(fs,{size:14}),r(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:r("imageDisplay.promptLabel")}),i.jsx("span",{style:{fontSize:"0.8rem",lineHeight:1.45,opacity:.85},children:a})]})]})]}),n&&typeof document<"u"&&Ir.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:p,alt:a||r("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 ta=[750,1500,3e3,5e3],zd=new Set([403,404,409,425,429,500,502,503,504]),Bd=t=>new Promise(e=>setTimeout(e,t));function Rn({video:t,videoUrl:e,videoFormat:s="mp4",revisedPrompt:a,adapterName:r}){const{t:n}=Le(),[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 k=r||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null);let A=null;for(let N=0;N<=ta.length&&(A=await fetch(e,{headers:k?{"X-Adapter-Name":k}:{}}),!(A.ok||!zd.has(A.status)||N===ta.length));N+=1)if(await Bd(ta[N]),y)return;if(!A||!A.ok){console.warn("[VideoDisplay] Server returned",A==null?void 0:A.status,"for",e);return}if(y)return;const L=await A.arrayBuffer();if(y)return;const C=new Blob([L],{type:`video/${s}`}),v=URL.createObjectURL(C);m.current=v,f(v)}catch(k){console.warn("[VideoDisplay] Failed to fetch video from",e,k)}})(),()=>{y=!0,m.current&&(URL.revokeObjectURL(m.current),m.current=null)}},[e,t,s,r]);const g=(t?`data:video/${s};base64,${t}`:null)??u;h.useEffect(()=>{if(!o)return;const y=k=>{k.key==="Escape"&&l(!1)};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[o]);const x=y=>{if(y.stopPropagation(),!g)return;const k=document.createElement("a");k.href=g,k.download=`generated-video.${s}`,k.click()};return g?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:g,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:n("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(Mr,{size:14})}),i.jsx("button",{onClick:y=>{y.stopPropagation(),l(!0)},title:n("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(Qc,{size:14})})]})]}),a&&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(wr,{size:14}):i.jsx(fs,{size:14}),n(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:n("videoDisplay.promptLabel")}),i.jsx("span",{style:{fontSize:"0.8rem",lineHeight:1.45,opacity:.85},children:a})]})]})]}),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:g,controls:!0,autoPlay:!0,style:{maxWidth:"92vw",maxHeight:"92vh",borderRadius:"8px"},onClick:y=>y.stopPropagation()})]})]}):null}let kr=null;function zi(t){kr=t}function Fr(){kr=null}async function Pa(){if(!kr)return null;try{return await kr()}catch{return null}}let ba=!1,Ps=null;const ya=new Set;function Bi(){ya.forEach(t=>t())}function wt(){return ba}function Hd(){return Ps}function $r(t){ba!==t&&(ba=t,!t&&Ps!==null&&(Ps=null),Bi())}function us(t){const e=typeof t=="string"&&t.trim().length>0?t.trim():null;Ps!==e&&(Ps=e,Bi())}function Vd(t){return ya.add(t),()=>{ya.delete(t)}}const Pn="orbitchat-guest-user-id";function ir(t){if(typeof t!="string")return null;const e=t.trim();return e.length>0?e:null}function qd(t){const e=t.split(".");if(e.length<2)return null;try{const s=e[1].replace(/-/g,"+").replace(/_/g,"/"),a=s.padEnd(Math.ceil(s.length/4)*4,"="),r=atob(a);return JSON.parse(r)}catch{return null}}function Wd(){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,a=>a.toString(16).padStart(2,"0")).join("")}`}function Kd(){if(typeof window>"u")return"guest:orbitchat:server";const t=window.localStorage.getItem(Pn);if(t&&t.trim().length>0)return t;const e=Wd();return window.localStorage.setItem(Pn,e),e}async function Hi(){const t=Hd();if(t)return t;const e=await Pa();if(e){const s=qd(e),a=ir(s==null?void 0:s.sub)||ir(s==null?void 0:s.user_id)||ir(s==null?void 0:s.preferred_username)||ir(s==null?void 0:s.email);if(a)return a}return wt()?"authenticated:orbitchat:unknown":Kd()}const Gd={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"},Dn={pdf:"PDF",docx:"Word document",xlsx:"Excel workbook",pptx:"PowerPoint deck",md:"Markdown document",csv:"CSV file"},gr=/[\uE000-\uF8FF]|\\[eE][0-9a-fA-F]{2,3}|\\[fF][0-8][0-9a-fA-F]{2,3}/,Xd=/((?:p\.)?generated-docx-preview-num-\d+-\d+:before\s*\{[^}]*?)content\s*:\s*"([^"]*)"\s*;([^}]*?\})/g;function Yd(t){var s;return gr.test(t)?`•${((s=t.match(/(?:\\9|\t|\u00A0| )+$/))==null?void 0:s[0])||"\\9"}`:null}function Un(t){Array.from(t.querySelectorAll("style")).forEach(a=>{const r=a.textContent;!r||!gr.test(r)||(a.textContent=r.replace(Xd,(n,o,l,c)=>{const d=Yd(l);if(!d)return n;const u=c.replace(/\s*font-family\s*:\s*[^;{}]+;?/gi,"");return`${o}content: "${d}";${u}`}))}),Array.from(t.querySelectorAll('span[style*="font-family"]')).forEach(a=>{if(!/\b(symbol|wingdings|webdings)\b/i.test(a.style.fontFamily))return;const r=a.textContent||"";gr.test(r)&&(a.textContent=r.replace(gr,"•"),a.style.fontFamily="")})}function Qd(t){return(t||"pdf").toLowerCase().replace(/^\./,"")||"pdf"}function Zd(t){const e=window.atob(t),s=new Uint8Array(e.length);for(let a=0;a<e.length;a+=1)s[a]=e.charCodeAt(a);return s.buffer}function Jd(t){return t==="xlsx"||t==="csv"?i.jsx(Mi,{className:"h-5 w-5"}):t==="pptx"?i.jsx(Pi,{className:"h-5 w-5"}):t==="md"?i.jsx(Ti,{className:"h-5 w-5"}):i.jsx(xa,{className:"h-5 w-5"})}function On({document:t,documentUrl:e,documentFormat:s="pdf",revisedPrompt:a,adapterName:r}){const{t:n}=Le(),o=Qd(s),[l,c]=h.useState(t||e?"loading":"idle"),[d,u]=h.useState(null),[f,m]=h.useState(null),[p,g]=h.useState([]),[x,y]=h.useState(""),[k,A]=h.useState(null),[L,C]=h.useState([]),[v,N]=h.useState(0),[R,b]=h.useState(!1),[_,S]=h.useState(null),I=h.useRef(null),M=h.useRef(null),F=h.useRef(null),H=a||Dn[o]||n("documentDisplay.generatedDocument"),j=h.useMemo(()=>`generated-document.${o}`,[o]),E=Gd[o]||"application/octet-stream";h.useEffect(()=>{if(!t&&!e)return;let X=!1;return(async()=>{c("loading"),S(null),g([]),y(""),A(null),C([]),N(0);try{const Z=t?Zd(t):await(async()=>{const se=(r==null?void 0:r.trim())||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),Y={"X-User-ID":await Hi()};se&&(Y["X-Adapter-Name"]=se);const J=await Pa();J&&(Y.Authorization=`Bearer ${J}`);const ee=await fetch(e,{headers:Y});if(!ee.ok)throw new Error(`Server returned ${ee.status}`);return ee.arrayBuffer()})();if(X)return;const fe=new Blob([Z],{type:E}),z=URL.createObjectURL(fe);if(I.current&&URL.revokeObjectURL(I.current),I.current=z,u(z),m(Z.slice(0)),o==="xlsx"){const{default:se}=await Ct(async()=>{const{default:ee}=await import("./index-CZz_ECqk.js");return{default:ee}},[]),J=(await se(fe))[0];y((J==null?void 0:J.sheet)||"First sheet"),g(((J==null?void 0:J.data)||[]).slice(0,100).map(ee=>ee.slice(0,30).map(ue=>ue==null?"":String(ue))))}if(o==="md"&&A(new TextDecoder("utf-8").decode(Z)),o==="csv"){const se=new TextDecoder("utf-8").decode(Z),{default:Y}=await Ct(async()=>{const{default:ee}=await import("./papaparse.min-D13ujVVP.js").then(ue=>ue.p);return{default:ee}},__vite__mapDeps([19,1])),J=Y.parse(se,{skipEmptyLines:!0});N(J.data.length),C(J.data.slice(0,25))}c("ready")}catch(Z){if(X)return;console.warn("[DocumentDisplay] Failed to load document from",e,Z),S(Z instanceof Error?Z.message:"Unable to load document"),c("error")}})(),()=>{X=!0,I.current&&(URL.revokeObjectURL(I.current),I.current=null)}},[r,t,e,o,E]),h.useEffect(()=>{if(l!=="ready"||o!=="docx"||!f||!M.current)return;const X=M.current;X.replaceChildren(),Ct(()=>import("./docx-preview-DehBmhog.js"),__vite__mapDeps([20,1])).then(async({renderAsync:V})=>{await V(f.slice(0),X,void 0,{className:"generated-docx-preview",inWrapper:!1,ignoreWidth:!0,ignoreHeight:!0}),Un(X)}).catch(V=>{console.warn("[DocumentDisplay] Failed to render DOCX preview",V),S("Unable to render document preview")})},[f,o,l]),h.useEffect(()=>{if(!R||o!=="docx"||!f||!F.current)return;const X=F.current;X.replaceChildren(),Ct(()=>import("./docx-preview-DehBmhog.js"),__vite__mapDeps([20,1])).then(async({renderAsync:V})=>{await V(f.slice(0),X,void 0,{className:"generated-docx-preview",inWrapper:!1,ignoreWidth:!0,ignoreHeight:!0}),Un(X)}).catch(V=>{console.warn("[DocumentDisplay] Failed to render modal DOCX preview",V)})},[f,o,R]),h.useEffect(()=>{if(!R)return;const X=V=>{V.key==="Escape"&&b(!1)};return window.document.addEventListener("keydown",X),()=>window.document.removeEventListener("keydown",X)},[R]);const D=X=>{if(X==null||X.stopPropagation(),!d)return;const V=window.document.createElement("a");V.href=d,V.download=j,V.click()},T=l==="ready"&&(o==="pdf"||o==="docx"||o==="xlsx"||o==="md"||o==="csv"),G=T&&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:Jd(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:[Dn[o]||`${o.toUpperCase()} document`,l==="loading"?` · ${n("documentDisplay.loadingPreview")}`:"",l==="error"?` · ${_||n("documentDisplay.previewUnavailableShort")}`:""]})]}),G&&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:n("documentDisplay.openPreviewTooltip"),"aria-label":n("documentDisplay.openPreviewTooltip"),children:i.jsx(Bc,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:D,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:n("documentDisplay.downloadDocumentTooltip"),"aria-label":n("documentDisplay.downloadDocumentTooltip"),children:i.jsx(Mr,{className:"h-4 w-4"})})]}),T&&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:M,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:p.length>0?p.map((X,V)=>i.jsx("tr",{className:V===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:X.map((Z,fe)=>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:Z},fe))},V)):i.jsx("tr",{children:i.jsx("td",{className:"px-3 py-4 text-sm text-gray-500 dark:text-[#bfc2cd]",children:n("documentDisplay.noSheetDataFound")})})})})})]}),o==="md"&&k!==null&&i.jsx("div",{className:"bg-white p-5 text-sm text-[#111827] dark:bg-[#171717] dark:text-[#ececf1]",children:i.jsx(_t,{content:k,disableMath:!0})}),o==="csv"&&i.jsxs("div",{className:"p-3",children:[v>25&&i.jsx("p",{className:"mb-2 text-xs text-gray-500 dark:text-[#bfc2cd]",children:n("documentDisplay.csvRowsPreviewMessage",{count:v})}),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:L.length>0?L.map((X,V)=>i.jsx("tr",{className:V===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:X.map((Z,fe)=>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:Z},fe))},V)):i.jsx("tr",{children:i.jsx("td",{className:"px-3 py-4 text-sm text-gray-500 dark:text-[#bfc2cd]",children:n("documentDisplay.noDataFound")})})})})})]})]}),l==="ready"&&!T&&i.jsx("div",{className:"px-3 py-4 text-sm text-gray-600 dark:text-[#bfc2cd]",children:n("documentDisplay.previewUnavailable")})]}),R&&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:X=>{X.stopPropagation(),b(!1)},className:"fixed right-4 top-4 flex items-center rounded-full border-0 bg-white/15 p-2 text-white",title:n("common.close"),"aria-label":n("common.close"),children:i.jsx(Je,{className:"h-5 w-5"})}),i.jsxs("div",{onClick:X=>X.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:F,className:"min-h-full bg-white p-8 text-[#111827]"}),o==="md"&&k!==null&&i.jsx("div",{className:"min-h-full bg-white p-8 text-sm text-[#111827]",children:i.jsx(_t,{content:k,disableMath:!0})})]})]})]})}const eu=["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 Ds(t,{enabled:e,onEscape:s}){h.useEffect(()=>{if(!e||!t.current)return;const a=t.current,r=document.activeElement,n=Array.from(a.querySelectorAll(eu)).filter(d=>d.tabIndex!==-1),o=n[0]||a,l=n[n.length-1]||a;o.focus({preventScroll:!0});const c=d=>{if(d.key==="Escape"){s==null||s();return}if(d.key!=="Tab")return;if(n.length===0){d.preventDefault(),a.focus({preventScroll:!0});return}const u=document.activeElement;if(d.shiftKey){(!u||u===o||!a.contains(u))&&(d.preventDefault(),l.focus({preventScroll:!0}));return}(!u||u===l||!a.contains(u))&&(d.preventDefault(),o.focus({preventScroll:!0}))};return document.addEventListener("keydown",c),()=>{var d;document.removeEventListener("keydown",c),(d=r==null?void 0:r.focus)==null||d.call(r,{preventScroll:!0})}},[e,s,t])}function vr({isOpen:t,onClose:e,onConfirm:s,title:a,message:r,confirmText:n,cancelText:o,type:l="danger",isLoading:c=!1}){const d=h.useRef(null);Ds(d,{enabled:t,onEscape:e});const{t:u}=Le(),f=n??u("common.confirm"),m=o??u("common.cancel");if(!t)return null;const p=()=>{c||s()},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(Fa,{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:a})]}),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:r})}),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:p,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:Ir.createPortal(y,document.body)}const tu=["#","*","`","[","]","(",")","{","}","|","<",">"],Vi=t=>tu.some(e=>t.includes(e));function qi(t){if(!t||t.length<1e3)return!1;const e=/^[A-Za-z0-9+/=]+$/,s=t.replace(/\s+/g,"");if(s.length>1e4&&e.test(s)){const a=/\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),r=Vi(t),n=/[-.,;:!?'"()]/.test(t);if(!a&&!r&&!n)return!0}return!!(s.length>5e4&&e.test(s)&&t.replace(/[A-Za-z0-9+/=\s]/g,"").length<10)}const su=/(?:\u202F|\u2009|\u200A|\u200B|\u200C|\u200D|\uFEFF)/g;function Us(t){if(!t)return t;let e=t.replace(su," ");if(qi(e))return"";const s=/([A-Za-z0-9+/=]{10000,})/g;return e=e.replace(s,a=>{const r=a.replace(/\s+/g,"");if(r.length>1e4&&/^[A-Za-z0-9+/=]+$/.test(r)){const n=/\b(function|const|let|var|class|return|import|export|if|else|while|for|true|false|null|def|print)\b/i.test(a),o=Vi(a),l=/[-.,;:!?'"()]/.test(a);if(!n&&!o&&!l)return""}return a}),e}function wa(t,e=5e4){return!t||t.length<=e?t:qi(t)?"":t.substring(0,e)+`
340
340
 
341
- ... (content truncated due to length)`}const ru={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 au(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 le=new Proxy(ru,{get(t,e){if(it()&&!wt()){const s=au(e);if(s!==void 0)return s}return t[e]}});function hs(){return h.useSyncExternalStore(Vd,wt,wt)}class Wi extends Error{constructor(s,a){super(s);Ze(this,"status");Ze(this,"statusText");this.name="ApiRequestError",this.status=a.status,this.statusText=a.statusText}}async function Pe(t={}){const e={"X-User-ID":await Hi(),...t},s=await Pa();return s&&(e.Authorization=`Bearer ${s}`),e}function vt(t){return encodeURIComponent(t)}function nu(t){return!t||t.length===0?"":`?file_ids=${t.map(encodeURIComponent).join(",")}`}async function Ls(t){const e=`API request failed: ${t.status} ${t.statusText}`;try{if((t.headers.get("content-type")||"").includes("application/json")){const a=await t.json(),r=typeof a.detail=="string"&&a.detail.trim()||typeof a.error=="string"&&a.error.trim()||typeof a.message=="string"&&a.message.trim();if(r)return`${e}: ${r}`}else{const a=(await t.text()).trim();if(a)return`${e}: ${a}`}}catch{}return e}function zn(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,assistant_message_id:e.assistant_message_id,threading:e.threading}}catch{return null}}let or=null;function iu(){let t=null,e=null;const s=(r,n,o)=>{t=n||null,e=o||null},a=(r,n)=>({async*streamChat(o,l,c,d,u,f,m,p,g,x,y,k,A,L){var N,R;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),p!==void 0&&(C.return_audio=p),g&&(C.tts_voice=g),x&&(C.source_language=x),y&&(C.target_language=y),k&&(C.model=k),A&&(C.skill=A),L&&(C.regenerate_of_message_id=L);const v=await fetch("/api/v1/chat",{method:"POST",headers:await Pe({"Content-Type":"application/json","X-Adapter-Name":r,...n?{"X-Session-ID":n}:{}}),body:JSON.stringify(C)});if(!v.ok)throw new Error(await Ls(v));if((N=v.headers.get("content-type"))!=null&&N.includes("text/event-stream")){const b=(R=v.body)==null?void 0:R.getReader(),_=new TextDecoder;let S="";if(!b)throw new Error("Response body is not readable");for(;;){const{done:I,value:M}=await b.read();if(I)break;S+=_.decode(M,{stream:!0});const F=S.split(`
342
- `);S=F.pop()||"";for(const B of F){const j=zn(B);j&&(yield j)}}if(S.trim())for(const I of S.split(`
343
- `)){const M=zn(I);M&&(yield M)}}else{const b=await v.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,assistant_message_id:b.assistant_message_id,threading:b.threading}}},async createThread(o,l){const c=await fetch("/api/threads",{method:"POST",headers:await Pe({"Content-Type":"application/json","X-Adapter-Name":r,"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/${vt(o)}`,{headers:await Pe({"X-Adapter-Name":r})});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/${vt(o)}`,{method:"DELETE",headers:await Pe({"X-Adapter-Name":r})});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 Pe({"Content-Type":"application/json","X-Adapter-Name":r,"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/${vt(o)}`,{headers:await Pe({"X-Adapter-Name":r})});if(!l.ok)throw new Error(`Failed to get feedback: ${l.statusText}`);return l.json()},async clearConversationHistory(o){const l=o||n;if(!l)throw new Error("No session ID available for clearing conversation history");const c=await fetch(`/api/admin/chat-history/${vt(l)}`,{method:"DELETE",headers:await Pe({"X-Adapter-Name":r})});if(!c.ok)throw new Error(`Failed to clear history: ${c.statusText}`);return c.json()},async getConversationHistory(o,l){const c=o||n;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/${vt(c)}${d}`,{headers:await Pe({"X-Adapter-Name":r})});if(!u.ok)throw new Error(`Failed to load history: ${u.statusText}`);return u.json()},async deleteConversationWithFiles(o,l){const c=o||n;if(!c)throw new Error("No session ID available for deleting conversation");const d=nu(l),u=await fetch(`/api/admin/conversations/${vt(c)}${d}`,{method:"DELETE",headers:await Pe({"X-Adapter-Name":r})});if(!u.ok)throw new Error(`Failed to delete conversation: ${u.statusText}`);return u.json()},getSessionId:()=>n,async uploadFile(o){const l=new FormData;l.append("file",o);const c=await fetch("/api/files/upload",{method:"POST",headers:await Pe({"X-Adapter-Name":r}),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 Pe({"X-Adapter-Name":r})});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/${vt(o)}`,{headers:await Pe({"X-Adapter-Name":r})});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/${vt(o)}/query`,{method:"POST",headers:await Pe({"Content-Type":"application/json","X-Adapter-Name":r}),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/${vt(o)}`,{method:"DELETE",headers:await Pe({"X-Adapter-Name":r})});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/${vt(r)}/status`,{headers:await Pe({"X-Adapter-Name":r})});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 p=Date.parse(f);if(!Number.isNaN(p)){const g=p-Date.now();if(g>0)return Math.min(g,3e4)}return 0},c=f=>new Promise(m=>setTimeout(m,f)),d=async()=>fetch(o,{headers:await Pe({"X-Adapter-Name":r})});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(),p=u.status===401?`Adapter info request was unauthorized for '${r}'. Verify the adapter exists and you have access.`:`Failed to load adapter info (${m}) for '${r}'.`;throw console.warn("[ProxyApi] Adapter info request failed",{adapter:r,status:u.status,statusText:u.statusText,details:f||void 0}),new Wi(p,u)}return u.json()},async stopChat(o,l){const c=await fetch("/api/v1/chat/stop",{method:"POST",headers:await Pe({"Content-Type":"application/json","X-Adapter-Name":r}),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 Pe({"X-Adapter-Name":r})});if(!l.ok)throw new Error(await Ls(l));return l.json()},async getAllModels(){const o=await fetch("/api/admin/models",{headers:await Pe({"X-Adapter-Name":r})});if(!o.ok)throw new Error(await Ls(o));return o.json()},async getAdapterSkills(o){const l=await fetch(`/api/admin/adapters/${encodeURIComponent(o)}/skills`,{headers:await Pe({"X-Adapter-Name":r})});if(!l.ok)throw new Error(await Ls(l));return l.json()},async getAllSkills(){const o=await fetch("/api/admin/skills",{headers:await Pe({"X-Adapter-Name":r})});if(!o.ok)throw new Error(await Ls(o));return o.json()}});return{configureApi:s,streamChat:async function*(r,n,o,l,c,d,u,f,m,p,g,x,y,k){if(!e)throw new Error("Adapter name is required");yield*a(e,t).streamChat(r,n,o,l,c,d,u,f,m,p,g,x,y,k)},stopChat:async(r,n)=>{if(!e)throw new Error("Adapter name is required");return a(e,t).stopChat(r,n)},ApiClient:class{constructor(n){Ze(this,"client");const o=n.adapterName||null,l=n.sessionId||null;if(!o)throw new Error("Adapter name is required");this.client=a(o,l)}async*streamChat(...n){yield*this.client.streamChat(...n)}get createThread(){var n;return(n=this.client.createThread)==null?void 0:n.bind(this.client)}get getThreadInfo(){var n;return(n=this.client.getThreadInfo)==null?void 0:n.bind(this.client)}get deleteThread(){var n;return(n=this.client.deleteThread)==null?void 0:n.bind(this.client)}get submitFeedback(){var n;return(n=this.client.submitFeedback)==null?void 0:n.bind(this.client)}get getSessionFeedback(){var n;return(n=this.client.getSessionFeedback)==null?void 0:n.bind(this.client)}get clearConversationHistory(){var n;return(n=this.client.clearConversationHistory)==null?void 0:n.bind(this.client)}get getConversationHistory(){var n;return(n=this.client.getConversationHistory)==null?void 0:n.bind(this.client)}get deleteConversationWithFiles(){var n;return(n=this.client.deleteConversationWithFiles)==null?void 0:n.bind(this.client)}get getSessionId(){var n;return(n=this.client.getSessionId)==null?void 0:n.bind(this.client)}get uploadFile(){var n;return(n=this.client.uploadFile)==null?void 0:n.bind(this.client)}get listFiles(){var n;return(n=this.client.listFiles)==null?void 0:n.bind(this.client)}get getFileInfo(){var n;return(n=this.client.getFileInfo)==null?void 0:n.bind(this.client)}get queryFile(){var n;return(n=this.client.queryFile)==null?void 0:n.bind(this.client)}get deleteFile(){var n;return(n=this.client.deleteFile)==null?void 0:n.bind(this.client)}get validateApiKey(){var n;return(n=this.client.validateApiKey)==null?void 0:n.bind(this.client)}get getAdapterInfo(){var n;return(n=this.client.getAdapterInfo)==null?void 0:n.bind(this.client)}get stopChat(){var n;return(n=this.client.stopChat)==null?void 0:n.bind(this.client)}get getAdapterModels(){var n;return(n=this.client.getAdapterModels)==null?void 0:n.bind(this.client)}get getAllModels(){var n;return(n=this.client.getAllModels)==null?void 0:n.bind(this.client)}get getAdapterSkills(){var n;return(n=this.client.getAdapterSkills)==null?void 0:n.bind(this.client)}get getAllSkills(){var n;return(n=this.client.getAllSkills)==null?void 0:n.bind(this.client)}}}}async function ou(){return or||(D("Loading API via Express proxy"),or=iu(),D("API loaded successfully"),or)}async function Me(){return await ou()}class Bn{static async getAdapterSkills(e,s){const a=await Me(),r=new a.ApiClient({apiUrl:"",adapterName:s});return r.getAdapterSkills?(await r.getAdapterSkills(e)).available_skills:[]}static async getAllSkills(e){const s=await Me(),a=new s.ApiClient({apiUrl:"",adapterName:e});return a.getAllSkills?(await a.getAllSkills()).skills:[]}}const lu=6e4;function Ki(t={}){const{adapterName:e,enabled:s=!0,selectionScopeKey:a,supportsThreading:r=!1}=t,n=s&&!!e&&!r,o=a??e??"__default__",[l,c]=h.useState([]),[d,u]=h.useState(!1),[f,m]=h.useState(null),[p,g]=h.useState({}),x=h.useRef(null),y=h.useRef(new Map),k=h.useCallback(async v=>{var b,_;const N=v,R=y.current.get(N);if(R&&R.expiresAt>Date.now()){c(R.skills),m(v);return}x.current&&x.current.abort(),x.current=new AbortController,u(!0);try{const[S,I]=await Promise.all([Bn.getAdapterSkills(v,v),Bn.getAllSkills(v)]);if((b=x.current)!=null&&b.signal.aborted)return;const M=I.filter(F=>S.includes(F.name)&&F.enabled);y.current.set(N,{skills:M,expiresAt:Date.now()+lu}),c(M),m(v),D("[useSkills] Loaded",M.length,"skills for adapter",v)}catch(S){if(S instanceof Error&&S.name==="AbortError")return;me("[useSkills] Failed to load skills:",S instanceof Error?S.message:String(S)),c([]),m(v)}finally{(_=x.current)!=null&&_.signal.aborted||u(!1)}},[]);h.useEffect(()=>{if(!n||!e)return;const v=window.setTimeout(()=>{k(e)},0);return()=>{var N;window.clearTimeout(v),(N=x.current)==null||N.abort()}},[n,e,k]);const A=h.useCallback(v=>{g(N=>{const R=N[o]??null;if(R===v||(R==null?void 0:R.name)===(v==null?void 0:v.name))return N;const b={...N};return v?b[o]=v:delete b[o],b})},[o]),L=h.useCallback(()=>{g(v=>{if(!v[o])return v;const N={...v};return delete N[o],N})},[o]),C=n?p[o]??null:null;return{skills:n&&f===e?l:[],isLoading:n?d||f!==e:!1,selectedSkill:C,selectSkill:A,clearSkill:L}}const Hn=t=>{let e;const s=new Set,a=(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),s.forEach(p=>p(e,m))}},r=()=>e,l={setState:a,getState:r,getInitialState:()=>c,subscribe:d=>(s.add(d),()=>s.delete(d))},c=e=t(a,r,l);return l},cu=(t=>t?Hn(t):Hn),du=t=>t;function uu(t,e=du){const s=gt.useSyncExternalStore(t.subscribe,gt.useCallback(()=>e(t.getState()),[t,e]),gt.useCallback(()=>e(t.getInitialState()),[t,e]));return gt.useDebugValue(s),s}const Vn=t=>{const e=cu(t),s=a=>uu(e,a);return Object.assign(s,e),s},Gi=(t=>t?Vn(t):Vn),ot=Gi(t=>({showLoginPrompt:!1,promptMessage:"",openLoginPrompt:e=>t({showLoginPrompt:!0,promptMessage:e}),closeLoginPrompt:()=>t({showLoginPrompt:!1,promptMessage:""})})),lr=t=>{const e=t==null?void 0:t.trim();return e||(typeof window<"u"&&window.localStorage?localStorage.getItem("chat-adapter-name"):null)};class Os{static async uploadFile(e,s,a,r,n){try{const o=le.maxFileSizeMB*1024*1024;if(e.size>o)throw new Error(`File size exceeds maximum limit of ${le.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"}`);s&&s({filename:e.name,progress:0,status:"uploading"});const d=await Me(),u=(r==null?void 0:r.trim())||Fe(),f=lr(n);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 p=await m.uploadFile(e);s&&s({filename:e.name,progress:75,status:"processing",fileId:p.file_id});let g;try{g=await this.pollFileStatus(p.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 ${p.file_id} was deleted during upload`);me(`File status polling failed for ${p.file_id}:`,x);const k=y.includes("processing failed")||y.includes("timeout");g={file_id:p.file_id,filename:p.filename,mime_type:p.mime_type,file_size:p.file_size,processing_status:k?"failed":p.status||"processing",chunk_count:p.chunk_count,error_message:k?y:void 0}}return s&&s({filename:e.name,progress:100,status:g.processing_status==="completed"?"completed":"processing",fileId:p.file_id}),g}catch(o){let l=o instanceof Error?o.message:"Upload failed";throw l.includes("401")&&(l="Authentication failed. Please check your adapter configuration."),s&&s({filename:e.name,progress:0,status:"error",error:l}),new Error(l)}}static async uploadFiles(e,s){const r=[],n=[];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=>{s&&s(f,m)})}));for(let d=0;d<c.length;d++){const u=c[d],f=o+d;u.status==="fulfilled"?r.push(u.value):(Oe(`Failed to upload file ${e[f].name}:`,u.reason),n.push({index:f,file:e[f].name,error:u.reason}))}}if(r.length===0&&n.length>0){const o=n[0].error;throw o instanceof Error?o:new Error(`All ${n.length} file uploads failed`)}return n.length>0&&me(`[FileUploadService] ${n.length} of ${e.length} files failed to upload:`,n.map(o=>o.file)),r}static async listFiles(e,s,a){try{const r=await Me(),n=(s==null?void 0:s.trim())||Fe(),o=lr(a);if(!o)throw new Error("Adapter not configured");const l=new r.ApiClient({apiUrl:n,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(r){Oe("Failed to list files:",r);const n=r instanceof Error?r.message:"Failed to list files";throw new Error(n)}}static async getFileInfo(e,s,a,r){try{const n=await Me(),o=(a==null?void 0:a.trim())||Fe(),l=lr(r);if(!l)throw new Error("Adapter not configured");const c=new n.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(n){if(n instanceof Error&&(n.message.includes("404")||n.message.includes("File not found")))throw new Error(`File ${e} was deleted`);Oe(`Failed to get file info for ${e}:`,n);const o=n instanceof Error?n.message:`Failed to get file info: ${e}`;throw new Error(o)}}static async pollFileStatus(e,s=30,a=2e3,r,n,o){for(let l=0;l<s;l++)try{if(r&&!r())throw new Error("Polling cancelled - component unmounted");const c=await this.getFileInfo(e,void 0,n,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<s-1&&await new Promise(d=>setTimeout(d,a))}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<s-1){await new Promise(u=>setTimeout(u,a));continue}throw c}throw new Error(`File processing timeout: ${e} did not complete within ${s*a/1e3} seconds`)}static async deleteFile(e,s,a,r){try{const n=await Me(),o=(a==null?void 0:a.trim())||Fe(),l=lr(r);if(!l)throw new Error("Adapter not configured");const c=new n.ApiClient({apiUrl:o,sessionId:null,adapterName:l});if(!c.deleteFile)throw new Error("File deletion is not available.");return await c.deleteFile(e)}catch(n){if(n instanceof Error&&(n.message.includes("404")||n.message.includes("File not found")||n.message.includes("Not Found")))return D(`File ${e} was already deleted from server`),{message:"File already deleted",file_id:e};Oe(`Failed to delete file ${e}:`,n);const o=n instanceof Error?n.message:`Failed to delete file: ${e}`;throw new Error(o)}}}class fu{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,s;try{if(!this.audioContext){const n=typeof AudioContext<"u"?AudioContext:typeof window<"u"&&window.webkitAudioContext||null;n&&(this.audioContext=new n)}const a=((e=this.audioContext)==null?void 0:e.state)==="suspended"?this.audioContext.resume():Promise.resolve();let r=Promise.resolve();try{const n=this.createSilentWavBlob(),o=URL.createObjectURL(n),l=new Audio;l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),l.src=o,l.volume=0,r=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 a,this.audioContext&&this.audioContext.state==="running"){const n=this.audioContext.createBuffer(1,1,22050),o=this.audioContext.createBufferSource();o.buffer=n,o.connect(this.audioContext.destination),o.start(0)}return await r,this.isEnabled=!0,D("[AudioStreamManager] Audio playback enabled",{audioContextState:(s=this.audioContext)==null?void 0:s.state}),!0}catch(a){return ge("[AudioStreamManager] Failed to enable audio:",a),!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 s=typeof AudioContext<"u"?AudioContext:typeof window<"u"&&window.webkitAudioContext||null;if(s)try{this.audioContext=new s}catch(a){return ge("[AudioStreamManager] Failed to create AudioContext:",a),!1}}if(((e=this.audioContext)==null?void 0:e.state)==="suspended")try{await this.audioContext.resume()}catch(s){return D("[AudioStreamManager] AudioContext resume deferred",s),!1}return!0}resolveMimeType(e){const s=this.mimeTypeCache.get(e);if(s)return s;let a;switch(e){case"mp3":a="audio/mpeg";break;case"wav":a="audio/wav";break;case"webm":a="audio/webm";break;case"ogg":a="audio/ogg";break;case"opus":{const r=typeof document<"u"?document.createElement("audio"):null;r!=null&&r.canPlayType("audio/ogg; codecs=opus")?a="audio/ogg; codecs=opus":r!=null&&r.canPlayType("audio/webm; codecs=opus")?a="audio/webm; codecs=opus":a="audio/mp4";break}default:a=`audio/${e}`}return this.mimeTypeCache.set(e,a),D(`[AudioStreamManager] Resolved MIME type for "${e}": ${a}`),a}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((s,a)=>s.chunkIndex-a.chunkIndex),this.isPlaying||this.playNextChunk().catch(s=>{ge("[AudioStreamManager] Playback chain error:",s)})}async playNextChunk(){var s,a;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 r;try{r=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(r.length===0)throw new Error(`Decoded audio data is empty for chunk ${e.chunkIndex}`);const n=new Uint8Array(r.length);for(let f=0;f<r.length;f++)n[f]=r.charCodeAt(f);const o=this.resolveMimeType(e.audioFormat),l=new Blob([n],{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(n.buffer,e.chunkIndex)}catch(f){ge(`[AudioStreamManager] AudioContext fallback also failed for chunk ${e.chunkIndex}:`,f)}d()}this.currentAudio=null,this.playNextChunk().catch(f=>{ge("[AudioStreamManager] Playback chain error:",f)})}catch(r){if(this.suppressPlaybackErrors){D("[AudioStreamManager] Playback stopped, suppressing audio error");return}const n=r instanceof Error?r.message:String(r);console.error(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,n,r,{audioFormat:e.audioFormat,chunkIndex:e.chunkIndex,audioLength:(s=e.audio)==null?void 0:s.length,audioContextState:(a=this.audioContext)==null?void 0:a.state,isEnabled:this.isEnabled}),ge(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,r),this.playNextChunk().catch(o=>{ge("[AudioStreamManager] Playback chain error after recovery:",o)})}}playViaAudioElement(e,s,a){return new Promise(r=>{const n=new Audio;n.setAttribute("playsinline",""),n.setAttribute("webkit-playsinline",""),n.src=e,this.currentAudio=n;let o=!1;const l=u=>{o||(o=!0,r(u))},c=()=>{if(this.suppressPlaybackErrors){a(),l(!0);return}const u=n.error;ge(`[AudioStreamManager] Media error on chunk ${s.chunkIndex}:`,u?{code:u.code,message:u.message,SRC_NOT_SUPPORTED:u.code===MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED}:"unknown"),a(),l(!1)};n.addEventListener("error",c,{once:!0});const d=async()=>{if(!o)try{n.addEventListener("ended",()=>{o||(D(`[AudioStreamManager] Chunk ${s.chunkIndex} finished`),this.onChunkPlayed&&this.onChunkPlayed(s.chunkIndex),a(),l(!0))},{once:!0}),await n.play()}catch(u){if(this.suppressPlaybackErrors){a(),l(!0);return}D(`[AudioStreamManager] audio.play() rejected for chunk ${s.chunkIndex}:`,u),a(),l(!1)}};n.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA?d():n.addEventListener("canplay",()=>d(),{once:!0})})}playViaAudioContext(e,s){return new Promise((a,r)=>{if(!this.audioContext){r(new Error("No AudioContext"));return}const n=e.slice(0);this.audioContext.decodeAudioData(n,o=>{if(!this.audioContext||this.suppressPlaybackErrors){a(!0);return}const l=this.audioContext.createBufferSource();l.buffer=o,l.connect(this.audioContext.destination),l.onended=()=>{D(`[AudioStreamManager] Chunk ${s} finished (AudioContext path)`),this.onChunkPlayed&&this.onChunkPlayed(s),a(!0)},l.start(0)},o=>{r(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 Bt=new fu,hu=[{extensions:["pdf"],Icon:xa,colorClass:"bg-red-500"},{extensions:["doc","docx"],Icon:xa,colorClass:"bg-blue-500"},{extensions:["xls","xlsx","csv"],Icon:Mi,colorClass:"bg-emerald-600"},{extensions:["ppt","pptx"],Icon:Pi,colorClass:"bg-orange-500"},{extensions:["png","jpg","jpeg","webp","tiff","gif"],Icon:qc,colorClass:"bg-violet-500"},{extensions:["wav","mp3","ogg","flac","webm","m4a","aac"],Icon:Vc,colorClass:"bg-teal-600"},{extensions:["mp4","mov","avi","mkv"],Icon:Wc,colorClass:"bg-pink-600"},{extensions:["zip","rar","7z","tar","gz"],Icon:Hc,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:Ti,colorClass:"bg-slate-500"}],pu=new Set(["png","jpg","jpeg","webp","tiff","gif"]);function mu(t){const e=/\.([a-z0-9]+)$/i.exec(t.trim());return e?e[1].toLowerCase():""}function gu(t){const e=mu(t),s=hu.find(a=>a.extensions.includes(e));return{Icon:(s==null?void 0:s.Icon)??Kc,colorClass:(s==null?void 0:s.colorClass)??"bg-gray-400 dark:bg-gray-500",label:e?e.toUpperCase():"",isImage:pu.has(e)}}const zs=new Map;function Xi(t,e){const s=zs.get(t);s&&s!==e&&URL.revokeObjectURL(s),zs.set(t,e)}function xu(t){return zs.get(t)}function ka(t){const e=zs.get(t);e&&(URL.revokeObjectURL(e),zs.delete(t))}const bu=hc()||Zl(),Yi=()=>{if(_r())return Na()||void 0},Fs="",yu=["New Chat","New Conversation"],wu=t=>t&&!yu.includes(t)?t:Fs,$s=(t,e,s)=>({id:t,sessionId:e,title:Fs,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:s,adapterName:Yi(),adapterLoadError:null}),Sr=()=>{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},ku=t=>{localStorage.setItem("chatbot-session-id",t)};let vu=0;const os=t=>{const e=Date.now(),s=++vu,a=Math.random().toString(36).substr(2,9);return`msg_${e}_${s}_${a}_${t}`},Ht=()=>{const t=Date.now(),e=Math.random().toString(36).substr(2,9);return`session_${t}_${e}`},Qi=t=>{const e=new Set;let s=!1;const a=t.map(r=>{if(!e.has(r.id))return e.add(r.id),r;s=!0;const n={...r,id:os(r.role)};return e.add(n.id),me(`[chatStore] Re-keyed duplicate message id ${r.id}`),n});return s?a:t},qn=t=>t.filter(e=>!e.isThreadMessage&&!(e.role==="assistant"&&e.isStreaming)).length,Wn=t=>t.flatMap(s=>[s.imageUrl,s.videoUrl,s.documentUrl]).map(s=>{var a;return((a=s==null?void 0:s.match(/\/api\/files\/([^/]+)\/content/))==null?void 0:a[1])??null}).filter(s=>s!==null),Su=(t,e)=>{if(t instanceof Date)return new Date(t);if(typeof t=="number"&&Number.isFinite(t)){const s=new Date(t);if(!Number.isNaN(s.getTime()))return s}if(typeof t=="string"){const s=new Date(t);if(!Number.isNaN(s.getTime()))return s}return e?new Date(e):new Date},ju=(t,e)=>{const s=new Map;e.forEach((r,n)=>{r.databaseMessageId&&s.set(r.databaseMessageId,{message:r,index:n})});const a=new Set;return t.map((r,n)=>{var f;const o=r.role==="user"?"user":"assistant",l=typeof r.message_id=="string"&&r.message_id.length>0?r.message_id:void 0;let c;if(l&&s.has(l)){const m=s.get(l);c=m.message,a.add(m.index)}else{const m=n<e.length?n:0;if(!a.has(m)&&((f=e[m])==null?void 0:f.role)===o)c=e[m],a.add(m);else for(let p=1;p<e.length;p++){const g=(m+p)%e.length;if(!a.has(g)&&e[g].role===o){c=e[g],a.add(g);break}}}const d=r.timestamp?Su(r.timestamp,c==null?void 0:c.timestamp):c!=null&&c.timestamp?new Date(c.timestamp):new Date,u=c?{...c,content:r.content??c.content,timestamp:d}:{id:l?`srv_${l}`:os(o),content:r.content||"",role:o,timestamp:d};if(u.isStreaming=!1,l&&(u.databaseMessageId=l),!u.supportsThreading&&r.metadata&&typeof r.metadata=="object"){const m=r.metadata,p=m==null?void 0:m.retrieved_docs;Array.isArray(p)&&p.length>0&&(u.supportsThreading=!0)}return u})},Cu=(t,e)=>{if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++){const a=t[s],r=e[s];if(a.role!==r.role||a.content!==r.content||(a.databaseMessageId||null)!==(r.databaseMessageId||null)||+a.timestamp!=+r.timestamp)return!1}return!0},Zi=t=>{var r,n,o,l,c,d;const e=((n=(r=t.adapterInfo)==null?void 0:r.adapter_name)==null?void 0:n.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 s=!1;try{const u=localStorage.getItem("chat-settings");u&&(s=JSON.parse(u).voiceEnabled===!0)}catch{me("Failed to read global voice setting")}const a=t.audioSettings;return{returnAudio:(a==null?void 0:a.enabled)??s??!!e,ttsVoice:(a==null?void 0:a.ttsVoice)||void 0,language:(a==null?void 0:a.language)||"en-US",audioFormat:a==null?void 0:a.audioFormat}},Au=300;let cr=null;const Ke=t=>{cr&&clearTimeout(cr),cr=setTimeout(()=>{cr=null;try{const e=t(),s=e.conversations.map(a=>({...a,messages:a.messages.map(r=>r.audio||r.image||r.video||r.document?Object.fromEntries(Object.entries(r).filter(([o])=>o!=="audio"&&o!=="image"&&o!=="video"&&o!=="document")):r)}));localStorage.setItem("chat-state",JSON.stringify({conversations:s,currentConversationId:e.currentConversationId}))}catch(e){e instanceof DOMException&&e.name==="QuotaExceededError"?me("[chatStore] localStorage quota exceeded — skipping save"):Oe("[chatStore] Failed to save state to localStorage:",e)}},Au)},Nu=32,ls=new Map;let zt=null,ft=null,Et=null,Jt=null;const va=(t,e)=>{const s=ls.get(t);if(s){if(s.timeoutId&&(clearTimeout(s.timeoutId),s.timeoutId=null),s.content){const a=s.content,r=s.messageId;s.content="",e(n=>({conversations:n.conversations.map(o=>{if(o.id!==t)return o;const l=[...o.messages],c=r?l.findIndex(u=>u.id===r):l.length-1,d=c!==-1?l[c]:void 0;return d&&d.role==="assistant"&&d.isStreaming&&(l[c]={...d,content:d.content+a}),{...o,messages:l,updatedAt:new Date}})}))}ls.delete(t)}},jt=(t,e,s,a)=>({conversations:t.conversations.map(r=>{var l;if(r.id!==e)return r;const n=[...r.messages],o=a?n.findIndex(c=>c.id===a):n.length-1;return o!==-1&&((l=n[o])==null?void 0:l.role)==="assistant"&&(n[o]={...n[o],...s(n[o])}),{...r,messages:n,updatedAt:new Date}})});let jr=!1,Cr="";async function Es(){if(jr&&Cr)return!0;try{const t=await Me(),e=localStorage.getItem("chat-api-url");e&&e===fa&&localStorage.removeItem("chat-api-url");const s=e&&e!==fa?e:Fe(),a=Sr(),r=localStorage.getItem("chat-adapter-name")||bu;return t.configureApi(s,a,r),Cr=s,jr=!0,!0}catch(t){return Oe("Failed to configure API:",t),!1}}async function Kn(t,e,s,a,r,n,o,l,c){let d=!1;const u=new AbortController;zt=u,Jt=a,ft=null;try{const f=t().conversations.find(y=>y.id===a);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.");Et=f.sessionId,f.sessionId&&(await Me()).configureApi(ut(f.apiUrl),f.sessionId,f.adapterName);const m=await Me(),{returnAudio:p,ttsVoice:g,language:x}=Zi(f);for await(const y of m.streamChat(r,!0,n.length>0?n:void 0,void 0,void 0,void 0,x,p,g,void 0,void 0,o,void 0,c)){if(y.request_id&&!ft&&(ft=y.request_id,D(`[chatStore] >>> CAPTURED request_id for ${l} stop: ${y.request_id}`)),y.text){const k=Us(y.text);k?(t().appendToLastMessage(k,a,s),d=!0):y.text.length>100&&me("[chatStore] Filtered out potential base64 audio data from regenerated message content")}if(y.audio&&y.done&&e(k=>jt(k,a,()=>({audio:y.audio,audioFormat:y.audioFormat||"mp3"}),s)),y.image&&y.done&&(d=!0,e(k=>jt(k,a,()=>({image:y.image,imageFormat:y.image_format||"png",imageRevisedPrompt:y.image_revised_prompt,imageUrl:y.image_url}),s))),(y.video||y.video_url)&&y.done&&(d=!0,e(k=>jt(k,a,()=>({video:y.video,videoFormat:y.video_format||"mp4",videoRevisedPrompt:y.video_revised_prompt,videoUrl:y.video_url}),s))),(y.document||y.document_url)&&y.done&&(d=!0,e(k=>jt(k,a,()=>({document:y.document,documentFormat:y.document_format||"pdf",documentRevisedPrompt:y.document_revised_prompt,documentUrl:y.document_url}),s))),y.generated_audio_url&&y.done&&(d=!0,e(k=>jt(k,a,()=>({generatedAudioFormat:y.generated_audio_format||"mp3",generatedAudioRevisedPrompt:y.generated_audio_revised_prompt,generatedAudioUrl:y.generated_audio_url}),s))),y.done){const k=y.threading;k!=null&&k.supports_threading&&e(A=>({conversations:A.conversations.map(L=>L.id!==a?L:{...L,messages:L.messages.map(C=>C.id===s?{...C,supportsThreading:!0,databaseMessageId:k.message_id}:C),updatedAt:new Date})})),y.assistant_message_id&&e(A=>({conversations:A.conversations.map(L=>L.id!==a?L:{...L,messages:L.messages.map(C=>C.id===s&&!C.databaseMessageId?{...C,databaseMessageId:y.assistant_message_id}:C),updatedAt:new Date})}));break}}!d&&!u.signal.aborted&&t().appendToLastMessage("No response received from the server. Please try again later.",a,s)}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{Oe(`${l==="edit-regenerate"?"Edit-regenerate":"Regenerate"} API error:`,f);let p="Sorry, there was an error regenerating the response.";f instanceof Error&&(f.message.startsWith("Server error:")?p=f.message.substring(14):(f.message.includes("Could not connect")||f.message.includes("timed out"))&&(p=f.message)),t().appendToLastMessage(p,a,s)}}zt=null,ft=null,Et=null,Jt=null,va(a,e),e(f=>{const m=f.conversations.map(g=>g.id===a?{...g,messages:g.messages.map(x=>x.id===s?{...x,isStreaming:!1}:x),updatedAt:new Date}:g),p=m.find(g=>g.id===f.currentConversationId);return{conversations:m,isLoading:p?p.messages.some(g=>g.role==="assistant"&&g.isStreaming):!1}})}const ke=Gi((t,e)=>({conversations:[],currentConversationId:null,isLoading:!1,error:null,sessionId:Sr(),getSessionId:()=>e().sessionId,configureApiSettings:async(s,a,r)=>{const n=e(),o=n.conversations.find(c=>c.id===n.currentConversationId),l=(o==null?void 0:o.sessionId)||a||Sr();a&&ku(a),t({sessionId:l});try{const c=await Me();if(!r||!r.trim())throw new Error("Adapter name is required");c.configureApi(s,l,r),Cr=s,jr=!0;let d;try{const u=new c.ApiClient({apiUrl:s,sessionId:null,adapterName:r});typeof u.getAdapterInfo=="function"&&(d=await u.getAdapterInfo(),D("Adapter info loaded:",d))}catch(u){me("Failed to load adapter info:",u)}if(o)t(u=>({conversations:u.conversations.map(f=>f.id===o.id?{...f,adapterName:r,apiUrl:s,adapterInfo:d,adapterLoadError:null,updatedAt:new Date}:f)}));else if(r&&r.trim()){const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,f=Ht();t(m=>({conversations:[...m.conversations,{id:u,sessionId:f,title:Fs,messages:[],createdAt:new Date,updatedAt:new Date,adapterName:r,apiUrl:s,adapterInfo:d,adapterLoadError:null}],currentConversationId:u}))}}catch(c){throw ge("Failed to configure API:",c),t({isLoading:!1}),c instanceof Error?c:new Error("Failed to configure API settings")}r?localStorage.setItem("chat-adapter-name",r):localStorage.removeItem("chat-adapter-name"),t({isLoading:!1})},createConversation:()=>{var u;const s=e(),a=le.maxConversations,r=s.conversations.length,n=s.currentConversationId?s.conversations.find(f=>f.id===s.currentConversationId):null;if(a!==null&&r>=a){if(it()&&!wt()){const m=`You've reached the guest limit of ${a} conversation${a===1?"":"s"}. Sign in to unlock more conversations, or delete conversations to start over.`;throw t({error:m}),ot.getState().openLoginPrompt(m),new Error("Guest conversation limit reached")}const f=`Maximum of ${a} conversations reached. Please delete an existing conversation before starting a new one.`;throw t({error:f}),new Error(f)}const o=!!n&&(n.messages.length>0||(((u=n.attachedFiles)==null?void 0:u.length)||0)>0);if(n&&!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=Ht(),d={id:l,sessionId:c,title:Fs,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:Fe(),adapterName:Yi(),adapterLoadError:null};return t(f=>({conversations:[d,...f.conversations],currentConversationId:l,sessionId:c,isLoading:!1})),Ke(e),l},selectConversation:async s=>{const a=e().conversations.find(r=>r.id===s);if(a){const r=a.messages.some(c=>c.role==="assistant"&&c.isStreaming);t({currentConversationId:s,sessionId:a.sessionId,isLoading:r});const n=a.apiUrl||Fe(),o=a.adapterName;if(await Es()&&o){const c=await Me();if(c.configureApi(n,a.sessionId,o),!a.adapterInfo)try{const d=new c.ApiClient({apiUrl:n,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===s?{...m,adapterInfo:u,adapterLoadError:null,updatedAt:new Date}:m)})),Ke(e)}}catch(d){me("Failed to load adapter info for conversation:",d)}}e().loadFeedbackForConversation(a.sessionId).catch(()=>{})}Ke(e)},deleteConversation:async s=>{var n,o;const a=e(),r=a.conversations.find(l=>l.id===s);if(D(`🗑️ Deleting conversation ${s}:`,{conversationId:s,sessionId:r==null?void 0:r.sessionId,title:r==null?void 0:r.title,messageCount:r==null?void 0:r.messages.length,fileCount:((n=r==null?void 0:r.attachedFiles)==null?void 0:n.length)||0}),a.currentConversationId===s&&Bt.stop(),r){const l=(r.attachedFiles||[]).map(d=>d.file_id),c=(r.messages||[]).flatMap(d=>(d.attachments||[]).map(u=>u.file_id));[...l,...c].forEach(ka)}if(r!=null&&r.sessionId)try{if(!await Es())Oe("Failed to configure API for conversation deletion");else{const c=r.apiUrl||Fe(),d=r.adapterName;d?D(`Using conversation's adapter for deletion: ${d} (conversation: ${s})`):me(`Skipping server deletion for conversation ${s}: adapter not configured`);const u=await Me(),f=new u.ApiClient({apiUrl:c,sessionId:r.sessionId,adapterName:d}),m=((o=r.attachedFiles)==null?void 0:o.map(x=>x.file_id))||[],p=Wn(r.messages||[]),g=[...m,...p];if(D(`🔧 Calling deleteConversationWithFiles for session: ${r.sessionId}`),f.deleteConversationWithFiles){const x=await f.deleteConversationWithFiles(r.sessionId,g);D(`✅ Deleted conversation and files for session: ${r.sessionId}`,x),D(` - Deleted ${x.deleted_messages} messages`),D(` - Deleted ${x.deleted_files} files`),x.file_deletion_errors&&x.file_deletion_errors.length>0&&me(` - Errors deleting files: ${x.file_deletion_errors.join(", ")}`)}else me("⚠️ deleteConversationWithFiles method not available on API client")}}catch(l){Oe("Failed to clear conversation history from server:",l)}else me(`⚠️ No session ID found for conversation ${s}, skipping server-side deletion`);t(l=>{var u;const c=l.conversations.filter(f=>f.id!==s),d=l.currentConversationId===s?((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=Ht(),p=$s(f,m,Fe());return Ke(e),{conversations:[p],currentConversationId:f,sessionId:m}}return Ke(e),{conversations:c,currentConversationId:d}})},deleteAllConversations:async()=>{const a=[...e().conversations];D(`🗑️ Deleting all conversations (${a.length} total)`),Bt.stop();const r=a.map(async u=>{var f;if(u!=null&&u.sessionId)try{if(!await Es()){Oe("Failed to configure API for conversation deletion");return}const p=u.adapterName;if(!p){D(`Skipping server deletion for conversation ${u.id}: adapter not configured`);return}const g=await Me(),x=new g.ApiClient({apiUrl:ut(u.apiUrl),sessionId:u.sessionId,adapterName:p}),y=[...((f=u.attachedFiles)==null?void 0:f.map(k=>k.file_id))||[],...Wn(u.messages||[])];x.deleteConversationWithFiles?(await x.deleteConversationWithFiles(u.sessionId,y),D(`✅ Deleted conversation ${u.id} and files`)):me(`deleteConversationWithFiles not available for conversation ${u.id}`)}catch(m){Oe(`Failed to delete conversation ${u.id} from server:`,m)}}),o=(await Promise.allSettled(r)).filter(u=>u.status==="rejected");o.length>0&&Oe(`Some conversations failed to delete from server: ${o.length}`,o);const l=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,c=Ht(),d=$s(l,c,Fe());t({conversations:[d],currentConversationId:l,sessionId:c}),Ke(e)},deleteThread:async(s,a,r)=>{const n=e().conversations.find(f=>f.id===s);if(!n)throw new Error("Conversation not found");if(!n.adapterName)throw new Error("Adapter not configured for this conversation");const o=n.messages.find(f=>f.id===a);if(!(o!=null&&o.threadInfo)||o.threadInfo.thread_id!==r)throw new Error("Thread not found for this message");const l=ut(n.apiUrl||Fe()),c=await Me(),d=new c.ApiClient({apiUrl:l,sessionId:n.sessionId,adapterName:n.adapterName});await new(await Ct(async()=>{const{ThreadService:f}=await import("./threadService-B9Db3n0J.js");return{ThreadService:f}},[])).ThreadService(d).deleteThread(r),t(f=>({conversations:f.conversations.map(m=>{var x;if(m.id!==s)return m;const p=m.messages.filter(y=>y.isThreadMessage?!(y.threadId===r||y.parentMessageId===a):!0).map(y=>y.id!==a?y:{...y,threadInfo:void 0,supportsThreading:!0}),g=m.currentThreadId===r||m.currentThreadSessionId===((x=o.threadInfo)==null?void 0:x.thread_session_id);return{...m,messages:p,currentThreadId:g?void 0:m.currentThreadId,currentThreadSessionId:g?void 0:m.currentThreadSessionId,updatedAt:new Date}})})),Ke(e)},sendMessage:async(s,a,r,n,o)=>{var c;let l=null;try{if(e().isLoading){me("Another request is already in progress");return}if(!await Es())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=le.maxConversations;if(it()&&!wt()&&m!==null&&e().conversations.length>m){ot.getState().openLoginPrompt(`You've reached the guest limit of ${m} conversation${m===1?"":"s"}. Sign in to continue chatting.`),t({isLoading:!1});return}const p=a?a.map(b=>{var S;const _=(S=f==null?void 0:f.attachedFiles)==null?void 0:S.find(I=>I.file_id===b);return _||{file_id:b,filename:"",mime_type:"",file_size:0}}).filter(b=>b!==void 0):[];p.length>0&&p.forEach(b=>{e().addFileToConversation(u,b)});const g=r||null;let x,y=null;if(g){if(x=f.messages.find(b=>{var _;return((_=b.threadInfo)==null?void 0:_.thread_id)===g}),!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 k=qn(f.messages),A=le.maxMessagesPerConversation;if(A!==null&&k>=A){it()&&!wt()&&ot.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.`),me(`[chatStore] Conversation ${u} reached the message limit (${A}).`),t({isLoading:!1});return}const L=le.maxTotalMessages;if(L!==null&&e().conversations.reduce((_,S)=>_+qn(S.messages),0)>=L){it()&&!wt()&&ot.getState().openLoginPrompt(`You've reached the guest limit of ${L} total messages. Sign in to continue chatting, or delete conversations to start over.`),me(`[chatStore] Workspace reached the total message limit (${L}).`),t({isLoading:!1});return}const C={id:os("user"),content:s,role:"user",timestamp:new Date,attachments:p.length>0?p:void 0},v=os("assistant"),N={id:v,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:n};if(g&&x){C.isThreadMessage=!0,C.threadId=g,C.parentMessageId=x.id,N.isThreadMessage=!0,N.threadId=g,N.parentMessageId=x.id;const b=le.maxMessagesPerThread;if(b!==null&&f.messages.filter(S=>S.isThreadMessage?(S.threadId===g||S.parentMessageId===x.id)&&!(S.role==="assistant"&&S.isStreaming):!1).length>=b){it()&&!wt()&&ot.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.`),me(`[chatStore] Thread ${g} reached the message limit (${b}).`),t({isLoading:!1});return}}t(b=>{const _=b.conversations.find(I=>I.id===u),S=(_==null?void 0:_.messages.filter(I=>I.role==="assistant"&&I.isStreaming))||[];return S.length>0&&me(`Cleaning up ${S.length} existing streaming messages`),{conversations:b.conversations.map(I=>{if(I.id!==u)return I;const M=I.messages.filter(F=>!(F.role==="assistant"&&F.isStreaming));return{...I,messages:[...M,C,N],updatedAt:new Date,title:I.messages.length===0?s.slice(0,50)+(s.length>50?"...":""):I.title}}),isLoading:!0,error:null}}),l=u;let R=!1;Bt.reset();try{const b=e().conversations.find(T=>T.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 _=ut(b.apiUrl),S=b.adapterName,I=y||b.sessionId,M=await Me();M.configureApi(_,I,S),g&&I!==b.sessionId&&D(`[chatStore] Thread mode: using thread session ${I} (original: ${b.sessionId})`);const{returnAudio:F,ttsVoice:B,language:j,audioFormat:E}=Zi(b);D("[chatStore] Audio settings:",{returnAudio:F,ttsVoice:B,language:j,audioFormat:E});const P=new AbortController;zt=P,Et=I,Jt=l,ft=null;for await(const T of M.streamChat(s,!0,a,g||void 0,void 0,void 0,j,F,B,void 0,void 0,n,o)){if(T.request_id&&!ft&&(ft=T.request_id,D(`[chatStore] >>> CAPTURED request_id for stop: ${T.request_id}`)),T.audio_chunk&&Bt.addChunk({audio:T.audio_chunk,audioFormat:T.audioFormat||"opus",chunkIndex:T.chunk_index??0}),T.text){const K=Us(T.text);K?(e().appendToLastMessage(K,l,v),R=!0):T.text.length>100&&me("[chatStore] Filtered out potential base64 audio data from message content")}if(T.audio&&T.done&&t(K=>jt(K,l,()=>({audio:T.audio,audioFormat:T.audioFormat||"mp3"}),v)),T.image&&T.done&&(R=!0,t(K=>jt(K,l,()=>({image:T.image,imageFormat:T.image_format||"png",imageRevisedPrompt:T.image_revised_prompt,imageUrl:T.image_url}),v))),(T.video||T.video_url)&&T.done&&(R=!0,t(K=>jt(K,l,()=>({video:T.video,videoFormat:T.video_format||"mp4",videoRevisedPrompt:T.video_revised_prompt,videoUrl:T.video_url}),v))),(T.document||T.document_url)&&T.done&&(R=!0,t(K=>jt(K,l,()=>({document:T.document,documentFormat:T.document_format||"pdf",documentRevisedPrompt:T.document_revised_prompt,documentUrl:T.document_url}),v))),T.generated_audio_url&&T.done&&(R=!0,t(K=>jt(K,l,()=>({generatedAudioFormat:T.generated_audio_format||"mp3",generatedAudioRevisedPrompt:T.generated_audio_revised_prompt,generatedAudioUrl:T.generated_audio_url}),v))),T.done){D("[chatStore] Stream completed, receivedAnyText:",R);const K=T.threading;K!=null&&K.supports_threading&&t(G=>({conversations:G.conversations.map(V=>V.id!==l?V:{...V,messages:V.messages.map(Z=>Z.id===v?{...Z,supportsThreading:!0,databaseMessageId:K.message_id}:Z),updatedAt:new Date})})),T.assistant_message_id&&t(G=>({conversations:G.conversations.map(V=>V.id!==l?V:{...V,messages:V.messages.map(Z=>Z.id===v&&!Z.databaseMessageId?{...Z,databaseMessageId:T.assistant_message_id}:Z),updatedAt:new Date})}));break}}!R&&!P.signal.aborted&&e().appendToLastMessage("No response received from the server. Please try again later.",l,v)}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"),R=!0;else{Oe("Chat API error:",b);let S="Sorry, there was an error processing your request.";b instanceof Error&&(b.message.startsWith("Server error:")?S=b.message.substring(14):(b.message.includes("Could not connect")||b.message.includes("timed out"))&&(S=b.message)),e().appendToLastMessage(S,l,v)}}zt=null,ft=null,Et=null,Jt=null,va(l,t),t(b=>{const _=b.conversations.map(I=>I.id===l?{...I,messages:I.messages.map(M=>M.id===v?{...M,isStreaming:!1}:M),updatedAt:new Date}:I),S=_.find(I=>I.id===b.currentConversationId);return{conversations:_,isLoading:S?S.messages.some(I=>I.role==="assistant"&&I.isStreaming):!1}}),Ke(e)}catch(d){Oe("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(s,a)=>{try{const r=e().conversations.find(m=>m.sessionId===a);if(!r)throw new Error("Conversation not found for session");if(!r.adapterName)throw new Error("Adapter not configured for this conversation");const n=r.messages.find(m=>m.id===s);if(!n)throw new Error("Message not found");const o=n.databaseMessageId||s,l=ut(r.apiUrl||Fe()),c=await Me(),d=new c.ApiClient({apiUrl:l,sessionId:a,adapterName:r.adapterName}),f=await new(await Ct(async()=>{const{ThreadService:m}=await import("./threadService-B9Db3n0J.js");return{ThreadService:m}},[])).ThreadService(d).createThread(o,a);t(m=>({conversations:m.conversations.map(p=>p.sessionId!==a?p:{...p,messages:p.messages.map(g=>g.id===s?{...g,threadInfo:f,supportsThreading:!0}:g),currentThreadId:void 0,currentThreadSessionId:void 0})})),D(`[chatStore] Created thread ${f.thread_id} for message ${s}`)}catch(r){throw Oe("Failed to create thread:",r),r}},appendToLastMessage:(s,a,r)=>{const n=Us(s);if(!n&&s){me("[chatStore] Filtered out base64 audio data from message content");return}const o=wa(n),l=a||e().currentConversationId;if(!l)return;const c=l,d=ls.get(c);d?(d.content+=o,d.messageId=r,d.timeoutId&&clearTimeout(d.timeoutId)):ls.set(c,{content:o,timeoutId:null,messageId:r});const u=()=>{const m=ls.get(c);if(!m||!m.content)return;const p=m.content,g=m.messageId;m.content="",m.timeoutId=null,t(x=>({conversations:x.conversations.map(y=>{if(y.id!==l)return y;const k=[...y.messages],A=g?k.findIndex(C=>C.id===g):k.length-1,L=A!==-1?k[A]:void 0;return L&&L.role==="assistant"&&L.isStreaming&&(k[A]={...L,content:L.content+p}),{...y,messages:k,updatedAt:new Date}})}))},f=ls.get(c);f.timeoutId=setTimeout(u,Nu)},regenerateResponse:async(s,a)=>{let r=null;try{if(e().isLoading){me("Another request is already in progress");return}if(!await Es())throw new Error("API not properly configured");const o=e(),l=o.conversations.find(p=>p.id===o.currentConversationId);if(!l)return;const c=l.messages.findIndex(p=>p.id===s);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(p=>p.file_id).filter(p=>typeof p=="string"&&p.length>0),m=os("assistant");if(t(p=>({conversations:p.conversations.map(g=>g.id===p.currentConversationId?{...g,messages:[...g.messages.slice(0,c),{id:m,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:a,supportsThreading:d.supportsThreading,databaseMessageId:d.databaseMessageId,threadInfo:d.threadInfo,threadId:d.threadId,parentMessageId:d.parentMessageId,isThreadMessage:d.isThreadMessage},...g.messages.slice(c+1)],updatedAt:new Date}:g),isLoading:!0,error:null})),r=o.currentConversationId,!r)throw new Error("No conversation selected");await Kn(e,t,m,r,u.content,f,a,"regenerate",d.databaseMessageId)}catch(n){Oe("Regenerate error:",n),t(o=>({isLoading:!1,...o.currentConversationId===r&&{error:`Failed to regenerate response: ${n instanceof Error?n.message:"Unknown error"}`}}))}},editMessageAndRegenerate:async(s,a,r)=>{let n=null;try{if(e().isLoading){await e().stopStreaming();const x=e().currentConversationId;x&&va(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===s);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=os("assistant"),m=l.messages[c+1],p=(m==null?void 0:m.role)==="assistant",g=p?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:a,updatedAt:new Date},{id:f,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:r,supportsThreading:p?m.supportsThreading:void 0,databaseMessageId:p?m.databaseMessageId:void 0,threadInfo:p?m.threadInfo:void 0,threadId:p?m.threadId:void 0,parentMessageId:p?m.parentMessageId:void 0,isThreadMessage:p?m.isThreadMessage:void 0},...y.messages.slice(g)],updatedAt:new Date}:y),isLoading:!0,error:null})),n=o.currentConversationId,!n)throw new Error("No conversation selected");await Kn(e,t,f,n,a,u,r,"edit-regenerate",p?m.databaseMessageId:void 0),Ke(e)}catch(o){Oe("Edit & regenerate error:",o),t(l=>({isLoading:!1,...l.currentConversationId===n&&{error:`Failed to regenerate response: ${o instanceof Error?o.message:"Unknown error"}`}}))}},updateConversationTitle:(s,a)=>{t(r=>({conversations:r.conversations.map(n=>n.id===s?{...n,title:a,updatedAt:new Date}:n)})),Ke(e)},clearError:()=>t({error:null}),cleanupStreamingMessages:()=>{const s=Jt;t(a=>{let r=!1;return{conversations:a.conversations.map(o=>o.id===s?(o.messages.some(c=>c.role==="assistant"&&c.isStreaming)&&(r=!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:r}})},canCreateNewConversation:()=>{var o;const s=e(),a=le.maxConversations;if(!s.currentConversationId)return a===null||s.conversations.length<a;const r=s.conversations.find(l=>l.id===s.currentConversationId);return!!r&&(r.messages.length>0||(((o=r.attachedFiles)==null?void 0:o.length)||0)>0)?a===null||s.conversations.length<a:!1},getConversationCount:()=>e().conversations.length,addFileToConversation:(s,a)=>{D("[chatStore] addFileToConversation called",{conversationId:s,fileId:a.file_id,filename:a.filename}),t(r=>({conversations:r.conversations.map(n=>n.id===s?{...n,attachedFiles:[...(n.attachedFiles||[]).filter(o=>o.file_id!==a.file_id),a],updatedAt:new Date}:n)})),Ke(e)},removeFileFromConversation:async(s,a)=>{D("[chatStore] removeFileFromConversation called",{conversationId:s,fileId:a});try{const r=e().conversations.find(n=>n.id===s);if(!r)throw new Error("Conversation not found");if(!r.adapterName)throw new Error("Adapter not configured for this conversation. Cannot delete file.");await Os.deleteFile(a,void 0,ut(r.apiUrl),r.adapterName),D(`[chatStore] Successfully deleted file ${a} from server`)}catch(r){r instanceof Error&&(r.message.includes("404")||r.message.includes("File not found"))?D(`[chatStore] File ${a} was already deleted from server`):ge(`[chatStore] Failed to delete file ${a} from server:`,r)}ka(a),t(r=>({conversations:r.conversations.map(n=>n.id===s?{...n,attachedFiles:(n.attachedFiles||[]).filter(o=>o.file_id!==a),updatedAt:new Date}:n)})),Ke(e)},loadConversationFiles:async s=>{try{const a=e().conversations.find(l=>l.id===s);if(!a)return;if(!a.adapterName){D(`Skipping file load for conversation ${s}: adapter not configured`);return}if(new Set((a.attachedFiles||[]).map(l=>l.file_id)).size===0){D(`No files to sync for conversation ${s}`);return}const n=await Os.listFiles(void 0,ut(a.apiUrl),a.adapterName),o=new Map(n.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===s);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===s?{...u,attachedFiles:d,updatedAt:new Date}:u)}}),Ke(e)}catch(a){Oe(`Failed to load files for conversation ${s}:`,a)}},syncConversationFiles:async s=>{await e().loadConversationFiles(s)},syncConversationsWithBackend:async()=>{try{const s=e();if(s.conversations.length===0)return;const a=await Me(),r=le.maxMessagesPerConversation!==null&&le.maxMessagesPerConversation||void 0;let n=!1;const l=(await Promise.all(s.conversations.map(async c=>{var d;if(!c.sessionId)return null;if(!c.adapterName)return me(`[chatStore] Skipping backend sync for conversation ${c.id} - adapter not configured`),null;if(c.messages.length===0)return null;try{const u=new a.ApiClient({apiUrl:ut(c.apiUrl),sessionId:c.sessionId,adapterName:c.adapterName});if(typeof u.getConversationHistory!="function")return n||(n=!0,me("[chatStore] Conversation history endpoint not supported by current API client")),null;const f=await u.getConversationHistory(c.sessionId,r),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 p=ju(m,c.messages),g=c.messages.filter(y=>y.isThreadMessage),x=Qi(g.length>0?[...p,...g]:p);return Cu(c.messages,x)?null:{id:c.id,sessionId:(f==null?void 0:f.session_id)||c.sessionId,messages:x,cleared:!1,updatedAt:((d=p[p.length-1])==null?void 0:d.timestamp)||new Date}}catch(u){return me(`[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:Fs,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(s){me("Failed to synchronize conversations with backend:",s)}},stopStreaming:async()=>{var a;if(!e().isLoading){D("[chatStore] stopStreaming called but not currently loading");return}if(D("[chatStore] Stopping stream...",{hasAbortController:!!zt,requestId:ft,sessionId:Et}),zt&&zt.abort(),ft&&Et)try{const r=await Me(),n=await((a=r.stopChat)==null?void 0:a.call(r,Et,ft));D(`[chatStore] Server-side cancellation result: ${n}`)}catch(r){me("[chatStore] Failed to cancel server-side stream:",r)}else me(`[chatStore] Cannot call stopChat - missing IDs: requestId=${ft}, sessionId=${Et}`);const s=Jt||e().currentConversationId;t(s?r=>({conversations:r.conversations.map(n=>n.id!==s?n:{...n,messages:n.messages.map(o=>o.isStreaming?{...o,isStreaming:!1}:o),updatedAt:new Date}),isLoading:!1}):{isLoading:!1}),zt=null,ft=null,Et=null,Jt=null,D("[chatStore] Stream stopped successfully")},clearCurrentConversationAdapter:()=>{const s=e().currentConversationId;s&&(t(a=>({conversations:a.conversations.map(r=>r.id===s?{...r,adapterName:void 0,adapterInfo:void 0,adapterLoadError:null}:r)})),Ke(e))},submitFeedback:async(s,a)=>{const r=e(),n=r.conversations.find(l=>l.id===r.currentConversationId);if(!n)return;const o=n.messages.find(l=>l.id===s);if(!(o!=null&&o.databaseMessageId)){me("[chatStore] Cannot submit feedback: no databaseMessageId on message");return}if(n.adapterName)try{const l=await Me(),u=(await new l.ApiClient({apiUrl:ut(n.apiUrl||Fe()),sessionId:n.sessionId,adapterName:n.adapterName}).submitFeedback(o.databaseMessageId,n.sessionId,a)).feedback_type;t(f=>({conversations:f.conversations.map(m=>m.id!==r.currentConversationId?m:{...m,messages:m.messages.map(p=>p.id===s?{...p,feedback:u}:p),updatedAt:new Date})})),Ke(e)}catch(l){ge("[chatStore] Failed to submit feedback:",l)}},loadFeedbackForConversation:async s=>{var n;const r=e().conversations.find(o=>o.sessionId===s);if(r!=null&&r.adapterName)try{const o=await Me(),l=new o.ApiClient({apiUrl:ut(r.apiUrl||Fe()),sessionId:r.sessionId,adapterName:r.adapterName}),c=new Set([s]);for(const f of r.messages)(n=f.threadInfo)!=null&&n.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!==s?m:{...m,messages:m.messages.map(p=>p.databaseMessageId&&u.has(p.databaseMessageId)?{...p,feedback:u.get(p.databaseMessageId)}:p)})}))}catch(o){ge("[chatStore] Failed to load feedback:",o)}}})),Iu=async()=>{var c;const t=localStorage.getItem("chat-state"),e=Fe(),s=!!localStorage.getItem("chat-api-url");let a=Sr(),r=!1;if(t)try{const d=JSON.parse(t),u=p=>{if(p instanceof Date)return p;const g=p?new Date(p):new Date;return Number.isNaN(g.getTime())?new Date:g},m=(Array.isArray(d.conversations)?d.conversations:[]).map(p=>{const x=(Array.isArray(p.messages)?p.messages:[]).filter(L=>!(L.role==="assistant"&&L.isStreaming)).map(L=>({...L,timestamp:u(L.timestamp),isStreaming:!1})),y=Qi(x),k={id:p.id,sessionId:p.sessionId||Ht(),title:wu(p.title),messages:y,createdAt:u(p.createdAt),updatedAt:u(p.updatedAt),attachedFiles:p.attachedFiles||[],adapterName:p.adapterName,apiUrl:p.apiUrl,adapterInfo:p.adapterInfo,adapterLoadError:p.adapterLoadError||null,audioSettings:p.audioSettings,currentThreadId:void 0,currentThreadSessionId:void 0},A=k.messages.length===0&&!k.adapterName;return{...k,apiUrl:A&&!s?e:ut(p.apiUrl)}});if(r=m.length>0,d.currentConversationId&&m.length>0){const p=m.find(g=>g.id===d.currentConversationId);p!=null&&p.sessionId&&(a=p.sessionId)}if(m.length===0){const p=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,g=Ht(),x=$s(p,g,Fe());ke.setState({conversations:[x],currentConversationId:p,sessionId:g}),a=g}else ke.setState({conversations:m,currentConversationId:d.currentConversationId||((c=m[0])==null?void 0:c.id)||null,sessionId:a}),!d.currentConversationId&&m.length>0&&(ke.setState({currentConversationId:m[0].id,sessionId:m[0].sessionId||a}),a=m[0].sessionId||a);D("📋 Loaded conversations:",ke.getState().conversations.map(p=>{var g;return{id:p.id,title:p.title,sessionId:p.sessionId,messageCount:((g=p.messages)==null?void 0:g.length)||0}})),setTimeout(()=>ke.getState().cleanupStreamingMessages(),100)}catch(d){Oe("Failed to load chat state:",d);const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,f=Ht(),m=$s(u,f,Fe());ke.setState({conversations:[m],currentConversationId:u,sessionId:f}),a=f}else{const d=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,u=Ht(),f=$s(d,u,Fe());ke.setState({conversations:[f],currentConversationId:d,sessionId:u}),a=u}localStorage.removeItem("chat-api-key");const n=ke.getState(),o=n.currentConversationId?n.conversations.find(d=>d.id===n.currentConversationId):null,l=r&&(o!=null&&o.apiUrl)?o.apiUrl:Fe();try{const d=await Me(),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,a,u),Cr=l,jr=!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 p=ke.getState();p.currentConversationId&&(ke.setState({conversations:p.conversations.map(g=>g.id===p.currentConversationId?{...g,adapterInfo:m,adapterLoadError:null,updatedAt:new Date}:g)}),setTimeout(()=>{const g=ke.getState();localStorage.setItem("chat-state",JSON.stringify({conversations:g.conversations,currentConversationId:g.currentConversationId}))},0))}}catch(f){me("Failed to load adapter info for existing adapter:",f)}}catch(d){Oe("Failed to initialize API:",d)}try{await ke.getState().syncConversationsWithBackend()}catch(d){me("Conversation history sync skipped:",d)}};typeof window<"u"&&Iu();function Lu(t){return t.includes("image")?i.jsx(Gc,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):t.includes("video")||t.includes("audio")?i.jsx(xd,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):i.jsx(Ma,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"})}function Eu(t){return t.replace(/-/g," ")}function Ji({skills:t,isLoading:e,selectedSkill:s,activeSkillName:a,query:r="",onSelect:n,onActiveSkillChange:o}){const{t:l}=Ee(),c=gt.useRef(null),d=r.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"})},[a,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:r}):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 p=(s==null?void 0:s.name)===f.name,g=a===f.name||!a&&(p||!s&&m===0);return i.jsxs("button",{id:`skill-option-${f.name}`,type:"button",role:"option","aria-selected":g,"data-active":g?"true":void 0,onMouseEnter:()=>o==null?void 0:o(f),onClick:()=>n(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 ${g?"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 ${g?"text-gray-900 dark:text-white":"text-gray-500 group-hover:text-gray-700 dark:text-[#bfc2cd] dark:group-hover:text-gray-200"}`,children:Lu(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:Eu(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})]}),p&&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(ds,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]},f.name)})})})}function eo({availableModels:t,defaultModel:e,selectedModel:s,onSelect:a,wrapperClassName:r="relative hidden md:block",maxWidthClass:n="max-w-[200px]",triggerTitle:o,listboxLabel:l,staticPaddingClass:c="px-3 py-1.5",triggerPaddingClass:d="px-3 py-1.5"}){const{t:u}=Ee(),f=o??u("modelPicker.selectModel"),m=l??u("modelPicker.selectModel"),[p,g]=h.useState(!1),[x,y]=h.useState(""),[k,A]=h.useState(null),L=h.useRef(null),C=h.useRef(null),v=h.useRef(null),N=h.useRef(null),R=s??e,b=x.trim()?t.filter(F=>F.name.toLowerCase().includes(x.trim().toLowerCase())):t,_=h.useCallback(()=>{if(!C.current)return;const F=C.current.getBoundingClientRect();A({bottom:window.innerHeight-F.top+8,right:window.innerWidth-F.right})},[]),S=h.useCallback(()=>{g(!1),y("")},[]),I=()=>{if(p){S();return}_(),g(!0)};if(h.useEffect(()=>{if(!p)return;const F=setTimeout(()=>{var P;return(P=v.current)==null?void 0:P.focus()},10),B=P=>{var V,Z;const T=P.target,K=((V=L.current)==null?void 0:V.contains(T))??!1,G=((Z=N.current)==null?void 0:Z.contains(T))??!1;!K&&!G&&S()},j=P=>{var T;P.key==="Escape"&&(P.preventDefault(),S(),(T=C.current)==null||T.focus())},E=new ResizeObserver(_);return C.current&&E.observe(C.current),window.addEventListener("resize",_,{passive:!0}),document.addEventListener("scroll",_,{capture:!0,passive:!0}),document.addEventListener("pointerdown",B),document.addEventListener("keydown",j),()=>{clearTimeout(F),E.disconnect(),window.removeEventListener("resize",_),document.removeEventListener("scroll",_,{capture:!0}),document.removeEventListener("pointerdown",B),document.removeEventListener("keydown",j)}},[S,p,_]),!e&&t.length===0)return null;const M=p&&k&&typeof document<"u"?Ir.createPortal(i.jsxs("div",{ref:N,style:{position:"fixed",bottom:k.bottom,right:k.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(Ta,{className:"h-3.5 w-3.5 flex-shrink-0 text-gray-400 dark:text-[#6b6f7a]","aria-hidden":"true"}),i.jsx("input",{ref:v,type:"text",value:x,onChange:F=>y(F.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(F=>{const B=R===F.name;return i.jsxs("button",{role:"option","aria-selected":B,type:"button",onClick:()=>{var j;a(F.name),S(),(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 ${B?"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 ${B?"border-blue-500 bg-blue-500 dark:border-blue-400 dark:bg-blue-400":"border-gray-300 dark:border-[#5a5b65]"}`,children:B&&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:F.name})]},F.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:L,className:r,children:t.length>1?i.jsxs(i.Fragment,{children:[i.jsxs("button",{ref:C,type:"button",onClick:I,className:`inline-flex min-w-[100px] ${n} 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":p,title:f,children:[i.jsx("span",{className:"truncate flex-1",children:R}),i.jsx(fs,{className:`h-3.5 w-3.5 flex-shrink-0 text-gray-400 transition-transform duration-150 dark:text-[#6b6f7a] ${p?"rotate-180":""}`,"aria-hidden":"true"})]}),M]}):i.jsx("div",{className:`inline-flex min-w-[100px] ${n} 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:R??void 0,children:i.jsx("span",{className:"truncate",children:R})})})}function Ar({filename:t,fileId:e,status:s,statusText:a,errorMessage:r,onRemove:n,removeTitle:o,className:l=""}){const c=s==="uploading"||s==="processing",d=s==="error",u=gu(t),f=e?xu(e):void 0,m=u.Icon,p=d?r||a:a||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(Fi,{className:"h-[18px] w-[18px] animate-spin"}):d?i.jsx(ga,{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}),p&&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:p})]}),n&&i.jsx("button",{type:"button",onClick:n,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=[],Tu=(t="png")=>{const e=t.toLowerCase().replace(/^image\//,"");return e==="jpg"?"image/jpeg":`image/${e||"png"}`},Mu=(t,e)=>{const s=atob(t),a=new Uint8Array(s.length);for(let r=0;r<s.length;r+=1)a[r]=s.charCodeAt(r);return new Blob([a],{type:e})},Fu=async t=>{const e=URL.createObjectURL(t);try{const s=new Image;s.decoding="async";const a=new Promise((o,l)=>{s.onload=()=>o(s),s.onerror=()=>l(new Error("Failed to load generated image for clipboard copy"))});s.src=e,await a;const r=document.createElement("canvas");r.width=s.naturalWidth,r.height=s.naturalHeight;const n=r.getContext("2d");if(!n)throw new Error("Could not create canvas context for image clipboard copy");return n.drawImage(s,0,0),await new Promise((o,l)=>{r.toBlob(c=>{c?o(c):l(new Error("Could not encode generated image for clipboard copy"))},"image/png")})}finally{URL.revokeObjectURL(e)}},$u=async(t,e)=>{const s=Tu(t.imageFormat);if(t.image)return Mu(t.image,s);if(!t.imageUrl)return null;const a=await fetch(t.imageUrl,{headers:e?{"X-Adapter-Name":e}:{}});if(!a.ok)throw new Error(`Could not fetch generated image for clipboard copy: ${a.status}`);const r=await a.blob();return r.type?r:new Blob([r],{type:s})},Ru=t=>t.imageUrl?new URL(t.imageUrl,window.location.origin).toString():t.imageRevisedPrompt||t.content;function Gn({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(s=>i.jsx("span",{className:`inline-block ${e} animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]`,style:{animationDelay:`${s}ms`}},s))})}function Pu({reply:t}){const{t:e}=Ee(),[s,a]=h.useState(!1),[r,n]=h.useState(!1),o=h.useRef(null),l=ke(d=>d.submitFeedback);h.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]);const c=async d=>{if(!t.databaseMessageId||s)return;const u=t.feedback!==d;a(!0);try{await l(t.id,d),u?(n(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{n(!1),o.current=null},2e3)):n(!1)}catch(f){ge("Failed to submit thread reply feedback:",f)}finally{a(!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:s,className:`rounded-md p-1.5 transition-colors ${s?"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(Ui,{className:"h-4 w-4"})}),i.jsx("button",{onClick:()=>c("down"),disabled:s,className:`rounded-md p-1.5 transition-colors ${s?"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(Di,{className:"h-4 w-4"})}),r&&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(ds,{className:"h-3.5 w-3.5"}),e("message.feedback.thanks")]})]})}function Du({message:t,onRegenerate:e,onEdit:s,onStartThread:a,onClearThread:r,onSendThreadMessage:n,threadMessages:o,sessionId:l,isThreadSendDisabled:c,availableModels:d=[],defaultModel:u=null,selectedModel:f=null}){var ws,ks,as;const{t:m}=Ee(),[p,g]=h.useState(!1),[x,y]=h.useState(t.content||""),[k,A]=h.useState(!1),L=h.useRef(null),[C,v]=h.useState(!1),[N,R]=h.useState(!1),[b,_]=h.useState(!1),[S,I]=h.useState(""),[M,F]=h.useState(!1),[B,j]=h.useState(!1),[E,P]=h.useState(!1),[T,K]=h.useState(0),[G,V]=h.useState(!1),[Z,ue]=h.useState(!1),[O,te]=h.useState(()=>f??u),Y=h.useRef(f),ee=h.useRef(((ws=t.threadInfo)==null?void 0:ws.thread_id)||null),re=h.useRef(null),fe=h.useRef(null),Ae=h.useRef(null),H=h.useRef(!1),J=h.useRef(0),W=h.useRef(""),ye=h.useRef(!1),ne=h.useRef(!0),X=h.useRef(!1),xe=h.useRef(null),Ce=h.useRef(null),oe=t.role==="assistant",ve=o??_u,$e=ve.filter($=>!($.role==="assistant"&&$.isStreaming)).length,z=ve.some($=>$.isStreaming),ie=hs(),Be=it()&&!ie,be=ke($=>$.conversations.find(we=>we.id===$.currentConversationId)),Ne=!!((t.image||t.imageUrl)&&oe&&!t.isStreaming),Tt=!!((t.video||t.videoUrl)&&oe&&!t.isStreaming),ze=m(Ne?"message.copyImageLabel":"message.copyLabel"),et=dc(),ps=le.maxMessageLength,xt=le.maxMessagesPerThread,Mt=xt!==null&&$e>=xt,Vt=Mt?Be?m("message.thread.limitReachedGuest",{count:xt}):m("message.thread.limitReachedUser",{count:xt}):null,{theme:tt,isDark:Ft}=ts(),qt=m("message.thread.placeholder"),je=`thread-input-${t.id}`,{skills:st,isLoading:bt,selectedSkill:ce,selectSkill:Se,clearSkill:_e}=Ki({adapterName:be==null?void 0:be.adapterName,enabled:et&&!!t.threadInfo,selectionScopeKey:((ks=t.threadInfo)==null?void 0:ks.thread_id)||t.id}),se=S.startsWith("/")?S.slice(1):"",rt=se.toLowerCase().replace(/-/g," "),He=rt?st.filter($=>$.name.replace(/-/g," ").toLowerCase().includes(rt)||$.description.toLowerCase().includes(rt)):st,ms=He.length>0?Math.min(T,He.length-1):0,lt=He[ms]??null,gs=(lt==null?void 0:lt.name.replace(/-/g," "))??"",Bs=E&&lt&&S.startsWith("/")&&gs.toLowerCase().startsWith(se.toLowerCase())&&gs.length>se.length?gs.slice(se.length):null,ss=tt.mode==="dark"?"dark":tt.mode==="light"?"light":"",at=Ft?"dark":"light",Hs=h.useMemo(()=>["message-markdown w-full min-w-0","prose prose-slate dark:prose-invert max-w-none",ss].filter(Boolean).join(" "),[ss]),Vs=h.useMemo(()=>["message-markdown w-full min-w-0","prose dark:prose-invert max-w-none",ss].filter(Boolean).join(" "),[ss]),rs=oe?Hs:Vs,Wt=`${Hs} text-sm leading-6`,xs=`${Vs} text-sm leading-6`;h.useEffect(()=>{var $,we;!ee.current&&(($=t.threadInfo)!=null&&$.thread_id)&&F(!0),ee.current=((we=t.threadInfo)==null?void 0:we.thread_id)||null},[(as=t.threadInfo)==null?void 0:as.thread_id]),h.useEffect(()=>{t.threadInfo||setTimeout(()=>{I(""),F(!1),j(!1),P(!1),_e()},0)},[t.threadInfo,_e]),h.useEffect(()=>{$e>0&&setTimeout(()=>{F(!0)},0)},[$e]),h.useEffect(()=>()=>{xe.current&&clearTimeout(xe.current),Ce.current&&clearTimeout(Ce.current)},[]),h.useEffect(()=>{if(!p||!L.current)return;const $=L.current;$.focus(),$.setSelectionRange($.value.length,$.value.length)},[p]),h.useEffect(()=>{if(!p||!L.current)return;const $=L.current;$.style.height="auto",$.style.height=`${$.scrollHeight}px`},[p,x]);const $t=h.useCallback(()=>{const $=x.trim();if(!$||$===t.content){g(!1);return}s==null||s(t.id,$),g(!1)},[x,t.content,t.id,s]),ht=h.useCallback(()=>{requestAnimationFrame(()=>{Ae.current&&(Ae.current.scrollTop=Ae.current.scrollHeight)})},[]);h.useEffect(()=>{if(!M)return;const $=ve.length,we=$>J.current,q=ve[ve.length-1],Ie=(q==null?void 0:q.content)||"",Re=Ie!==W.current,Xt=(q==null?void 0:q.isStreaming)??!1,ct=ye.current&&!Xt;we||Xt&&Re||ct?(ht(),ne.current=!0):ne.current&&Re&&ht(),J.current=$,W.current=Ie,ye.current=Xt},[M,ve,ht]),h.useEffect(()=>{M&&(ht(),ne.current=!0)},[M,ht]);const Rt=oe?"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)]",bs=h.useCallback(()=>{v(!0),xe.current&&clearTimeout(xe.current),xe.current=setTimeout(()=>{v(!1),xe.current=null},2e3)},[]),qs=async()=>{try{if(Ne){if("ClipboardItem"in window&&navigator.clipboard.write)try{const we=(be==null?void 0:be.adapterName)||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),q=await $u(t,we);if(q){const Ie=q.type==="image/png"?q:await Fu(q);await navigator.clipboard.write([new ClipboardItem({[Ie.type||"image/png"]:Ie})]),bs();return}}catch(we){ge("Failed to copy generated image, falling back to text:",we)}const $=Ru(t);if($){await navigator.clipboard.writeText($),bs();return}return}await navigator.clipboard.writeText(t.content),bs()}catch($){ge(Ne?"Failed to copy generated image:":"Failed to copy text:",$)}},Kt=ke($=>$.submitFeedback),Ws=async $=>{if(!t.databaseMessageId||N)return;const we=t.feedback!==$;R(!0);try{await Kt(t.id,$),we?(_(!0),Ce.current&&clearTimeout(Ce.current),Ce.current=setTimeout(()=>{_(!1),Ce.current=null},2e3)):_(!1)}catch(q){ge("Failed to submit feedback:",q)}finally{R(!1)}},qe=async()=>{if(!n||!t.threadInfo||Mt)return;const $=S.trim();if(!$)return;const we=S,q=ce,Ie=ce==null?void 0:ce.name;I(""),j(!0),P(!1),Ie&&_e();try{await n(t.threadInfo.thread_id,t.id,$,Ie,O??u??void 0),setTimeout(()=>{re.current&&re.current.focus()},100)}catch(Re){ge("Failed to send thread message:",Re),I(we),q&&Se(q),setTimeout(()=>{re.current&&re.current.focus()},100)}finally{j(!1)}},ys=h.useCallback($=>{var we;Se($),P(!1),I(""),K(0),(we=re.current)==null||we.focus()},[Se]),Gt=h.useCallback(()=>{var $;P(!1),I(""),K(0),($=re.current)==null||$.focus()},[]),Rr=h.useCallback(()=>{var $;I("/"),P(!0),K(0),($=re.current)==null||$.focus()},[]),Pt=$=>{if(E){if($.key==="ArrowDown"){$.preventDefault(),K(we=>He.length===0?0:(we+1)%He.length);return}if($.key==="ArrowUp"){$.preventDefault(),K(we=>He.length===0?0:(we-1+He.length)%He.length);return}if($.key==="Home"){$.preventDefault(),K(0);return}if($.key==="End"){$.preventDefault(),K(Math.max(He.length-1,0));return}if(($.key==="Enter"&&!$.shiftKey||$.key==="Tab")&&lt){$.preventDefault(),ys(lt);return}if($.key==="Escape"){$.preventDefault(),Gt();return}}$.key==="Enter"&&!$.shiftKey&&($.preventDefault(),qe())},Ye=!t.threadInfo||!n||c||z||B||Mt,Pr=!!t.threadInfo&&!!r&&$e>0&&!z&&!B&&!c,Dr=async()=>{if(!(!t.threadInfo||!r)){ue(!0);try{await r(t.id,t.threadInfo.thread_id),V(!1),F(!1),I("")}catch($){ge("Failed to clear thread:",$)}finally{ue(!1)}}};h.useEffect(()=>{Y.current=f},[f]),h.useEffect(()=>{te(Y.current??u)},[u]),h.useEffect(()=>{if(!M||Ye){X.current=B;return}const $=re.current;if(!$){X.current=B;return}if(!(H.current||X.current)){X.current=B;return}const q=requestAnimationFrame(()=>{var Re;H.current&&((Re=fe.current)==null||Re.scrollIntoView({behavior:"auto",block:"nearest",inline:"nearest"})),$.focus();const Ie=$.value.length;$.setSelectionRange(Ie,Ie),H.current=!1,X.current=B});return()=>{cancelAnimationFrame(q),X.current=B}},[M,Ye,B]),h.useEffect(()=>{if(re.current){const we=re.current;we.style.height="auto";const q=we.scrollHeight;we.style.height=`${Math.min(q,120)}px`,we.style.overflowY=q>120?"auto":"hidden"}},[S]);const Ur=h.useMemo(()=>{if(t.isStreaming&&(!t.content||t.content==="…"))return i.jsx("div",{className:rs,children:i.jsx(Gn,{})});const $=t.isStreaming&&oe?" streaming-cursor":"";return i.jsx("div",{className:$||void 0,children:i.jsx(_t,{content:wa(Us(t.content||"")),className:rs,syntaxTheme:at})})},[rs,t.content,t.isStreaming,oe,at]),kt=h.useMemo(()=>{const $=q=>q instanceof Date?q.getTime():new Date(q).getTime();return[...ve].sort((q,Ie)=>$(q.timestamp)-$(Ie.timestamp)).map(q=>{const Ie=q.role==="assistant",Re=Ie?Wt:xs,Xt=q.isStreaming&&Ie?" streaming-cursor":"",ct=q.isStreaming&&(!q.content||q.content==="…")?i.jsx("div",{className:Re,children:i.jsx(Gn,{size:"sm"})}):i.jsx("div",{className:Xt||void 0,children:i.jsx(_t,{content:wa(Us(q.content||"")),className:Re,syntaxTheme:at})});return i.jsx("div",{className:`min-w-0 flex ${Ie?"justify-start":"justify-end"}`,children:i.jsxs("div",{className:Ie?"min-w-0 w-full max-w-full":"min-w-0 max-w-[85%]",children:[i.jsxs("div",{className:Ie?"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:[ct,q.audio&&Ie&&!q.isStreaming&&i.jsx(nr,{audio:q.audio,audioFormat:q.audioFormat,autoPlay:!1}),(q.image||q.imageUrl)&&Ie&&!q.isStreaming&&i.jsx($n,{image:q.image,imageUrl:q.imageUrl,imageFormat:q.imageFormat,revisedPrompt:q.imageRevisedPrompt}),(q.video||q.videoUrl)&&Ie&&!q.isStreaming&&i.jsx(Rn,{video:q.video,videoUrl:q.videoUrl,videoFormat:q.videoFormat,revisedPrompt:q.videoRevisedPrompt,adapterName:be==null?void 0:be.adapterName}),(q.document||q.documentUrl)&&Ie&&!q.isStreaming&&i.jsx(On,{document:q.document,documentUrl:q.documentUrl,documentFormat:q.documentFormat,revisedPrompt:q.documentRevisedPrompt,adapterName:be==null?void 0:be.adapterName}),q.generatedAudioUrl&&Ie&&!q.isStreaming&&i.jsx(nr,{audioUrl:q.generatedAudioUrl,audioFormat:q.generatedAudioFormat,downloadFilename:`generated-audio.${q.generatedAudioFormat||"mp3"}`,autoPlay:!1})]}),Ie&&!q.isStreaming&&q.model&&i.jsx("div",{className:"px-1 pt-0.5 text-[11px] text-gray-400 dark:text-[#9a9ab0]",children:m("message.generatedBy",{model:q.model})}),Ie&&!q.isStreaming&&vn()&&i.jsx(Pu,{reply:q})]})},q.id)})},[be==null?void 0:be.adapterName,at,m,Wt,ve,xs]);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:oe?void 0:"flex flex-col items-end",children:[i.jsxs("div",{className:Rt,children:[p?i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsx("textarea",{ref:L,className:"w-full resize-none overflow-hidden bg-transparent outline-none text-[#111827] dark:text-[#f5f5f5] leading-relaxed",value:x,onChange:$=>y($.target.value),onCompositionStart:()=>A(!0),onCompositionEnd:()=>A(!1),onKeyDown:$=>{$.key==="Enter"&&!$.shiftKey&&!k&&($.preventDefault(),$.stopPropagation(),$t()),$.key==="Escape"&&($.stopPropagation(),g(!1),y(t.content||""))},maxLength:le.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:()=>{g(!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:$t,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(ma,{className:"w-3.5 h-3.5"}),m("common.send")]})]})]})]}):Ur,t.attachments&&t.attachments.length>0&&i.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:t.attachments.map($=>i.jsx(Ar,{filename:$.filename,fileId:$.file_id,status:"completed",statusText:`${($.file_size/1024).toFixed(1)} KB`},$.file_id))}),t.audio&&oe&&!t.isStreaming&&i.jsx(nr,{audio:t.audio,audioFormat:t.audioFormat,autoPlay:!1}),(t.image||t.imageUrl)&&oe&&!t.isStreaming&&i.jsx($n,{image:t.image,imageUrl:t.imageUrl,imageFormat:t.imageFormat,revisedPrompt:t.imageRevisedPrompt}),(t.video||t.videoUrl)&&oe&&!t.isStreaming&&i.jsx(Rn,{video:t.video,videoUrl:t.videoUrl,videoFormat:t.videoFormat,revisedPrompt:t.videoRevisedPrompt,adapterName:be==null?void 0:be.adapterName}),(t.document||t.documentUrl)&&oe&&!t.isStreaming&&i.jsx(On,{document:t.document,documentUrl:t.documentUrl,documentFormat:t.documentFormat,revisedPrompt:t.documentRevisedPrompt,adapterName:be==null?void 0:be.adapterName}),t.generatedAudioUrl&&oe&&!t.isStreaming&&i.jsx(nr,{audioUrl:t.generatedAudioUrl,audioFormat:t.generatedAudioFormat,downloadFilename:`generated-audio.${t.generatedAudioFormat||"mp3"}`,autoPlay:!1})]}),!oe&&!p&&i.jsxs("div",{className:"flex items-center gap-0.5 py-1 text-gray-400 dark:text-[#8e8ea0]",children:[i.jsx("button",{onClick:qs,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:ze,"aria-label":ze,children:C?i.jsx(ds,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):i.jsx(Cn,{className:"h-4 w-4"})}),s&&i.jsx("button",{onClick:()=>{y(t.content||""),g(!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(Ri,{className:"h-4 w-4"})})]})]}),oe&&!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})}),oe&&!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:[!Tt&&i.jsx("button",{onClick:qs,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:ze,"aria-label":ze,children:C?i.jsx(ds,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):i.jsx(Cn,{className:"h-4 w-4"})}),vn()&&i.jsxs("div",{className:"relative flex items-center gap-0.5",children:[i.jsx("button",{onClick:()=>Ws("up"),disabled:N,className:`rounded-md p-1.5 transition-colors ${N?"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(Ui,{className:"h-4 w-4"})}),i.jsx("button",{onClick:()=>Ws("down"),disabled:N,className:`rounded-md p-1.5 transition-colors ${N?"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(Di,{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(ds,{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(ud,{className:"h-4 w-4"})}),et&&t.supportsThreading&&!t.threadInfo&&a&&l&&i.jsxs("button",{type:"button",onClick:()=>{H.current=!0,F(!0),a(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(An,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{children:m("message.thread.continueLabel")})]}),et&&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:()=>F($=>!$),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(An,{className:"h-4 w-4"}),i.jsx("span",{className:"truncate",children:m("message.thread.replyCount",{count:$e})}),M?i.jsx(wr,{className:"h-3 w-3"}):i.jsx(fs,{className:"h-3 w-3"})]}),Pr&&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")})]})]}),et&&t.threadInfo&&M&&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:Ae,className:"thread-replies-scroll mt-2 space-y-2 pb-3",onScroll:()=>{if(!Ae.current)return;const{scrollTop:$,scrollHeight:we,clientHeight:q}=Ae.current;ne.current=we-$-q<100},children:$e>0?kt:null}),Vt&&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:[Vt,Be&&i.jsx("div",{className:"mt-2",children:i.jsx("button",{type:"button",onClick:()=>ot.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:fe,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:[ce&&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(Ma,{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:ce.name.replace(/-/g," ")}),i.jsx("button",{type:"button",onClick:()=>_e(),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"})})]}),!ce&&st.length>0&&S.length===0&&!Ye&&i.jsxs("button",{type:"button",onClick:Rr,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:je,className:"sr-only",children:m("message.thread.placeholder")}),Bs&&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:S}),i.jsx("span",{children:Bs})]}),i.jsx("textarea",{id:je,ref:re,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:qt,"aria-label":m("message.thread.placeholder"),value:S,onChange:$=>{const we=$.target.value;I(we),we.startsWith("/")&&K(0),P(we.startsWith("/"))},onKeyDown:Pt,disabled:Ye,rows:1,maxLength:ps,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(eo,{availableModels:d,defaultModel:u,selectedModel:O,onSelect:te,maxWidthClass:"max-w-[120px]",triggerPaddingClass:"px-2 py-1",staticPaddingClass:"px-2 py-1",triggerTitle:m("message.thread.selectModelTitle"),listboxLabel:m("message.thread.selectModelTitle")}),S.trim().length>0&&i.jsx("button",{type:"button",onClick:qe,disabled:Ye||S.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(ma,{className:"h-5 w-5 sm:h-4 sm:w-4"})})]})]}),E&&i.jsx("div",{className:"w-full pt-1",children:i.jsx(Ji,{skills:st,isLoading:bt,selectedSkill:ce,activeSkillName:lt==null?void 0:lt.name,query:se,onActiveSkillChange:$=>{const we=He.findIndex(q=>q.name===$.name);we>=0&&K(we)},onSelect:ys,onClose:Gt})})]}),$e>0&&i.jsx("div",{className:"mt-2 flex justify-end",children:i.jsxs("button",{type:"button",onClick:()=>F(!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(wr,{className:"h-3 w-3"}),i.jsx("span",{children:m("message.thread.hideRepliesLabel")})]})})]})]}),i.jsx(vr,{isOpen:G,onClose:()=>{Z||V(!1)},onConfirm:Dr,title:m("message.confirmation.clearRepliesTitle"),message:m("message.confirmation.clearRepliesMessage"),confirmText:m("common.clear"),cancelText:m("common.cancel"),type:"danger",isLoading:Z})]})}let is=null;function Uu(){if(typeof window>"u")return null;const t=window.AudioContext??window.webkitAudioContext;return t?((!is||is.state==="closed")&&(is=new t),is.state==="suspended"&&is.resume(),is):(D("[SoundEffects] AudioContext not supported in this browser"),null)}function Ou(t){const e=Uu();if(!e)return;const s=e.currentTime;for(const a of t){const r=e.createOscillator(),n=e.createGain();r.connect(n),n.connect(e.destination),r.frequency.value=a.frequency,r.type=a.type;const o=s+a.startTime,l=o+a.duration;n.gain.setValueAtTime(.001,o),n.gain.linearRampToValueAtTime(a.gain,o+.008),n.gain.exponentialRampToValueAtTime(.001,l),r.start(o),r.stop(l+.01)}}const zu={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 _s(t,e){if(!e)return;const s=zu[t];if(!s){D(`[SoundEffects] Unknown sound effect type: ${t}`);return}try{Ou(s),D(`[SoundEffects] Playing ${t} sound effect`)}catch(a){D(`[SoundEffects] Failed to play ${t} sound effect:`,a)}}function Bu({messages:t,onRegenerate:e,onEditMessage:s,onStartThread:a,onClearThread:r,onSendThreadMessage:n,sessionId:o,isLoading:l,contentMaxWidthClass:c="max-w-[64rem]",availableModels:d,defaultModel:u,selectedModel:f}){const m=h.useRef(null),p=h.useRef(null),g=h.useRef(t.length),x=h.useRef(""),y=h.useRef(l),k=h.useRef(!0),{settings:A}=Lr(),{t:L}=Ee(),{topLevelMessages:C,threadLookup:v}=h.useMemo(()=>{const b=new Map,_=[];return t.forEach(S=>{if(S.isThreadMessage&&S.parentMessageId){const I=b.get(S.parentMessageId)||[];b.set(S.parentMessageId,[...I,S]);return}_.push(S)}),{topLevelMessages:_,threadLookup:b}},[t]),N=()=>{if(!p.current)return;const{scrollTop:b,scrollHeight:_,clientHeight:S}=p.current,M=_-b-S<200;k.current=M},R=h.useCallback(()=>{requestAnimationFrame(()=>{p.current&&(p.current.scrollTop=p.current.scrollHeight)})},[]);return h.useEffect(()=>{const b=t.length,_=g.current,S=b>_,I=t[t.length-1],M=(I==null?void 0:I.content)||"",F=M!==x.current,B=(I==null?void 0:I.isStreaming)??!1;S||B&&F?(R(),k.current=!0):k.current&&F&&R(),g.current=b,x.current=M},[t,R]),h.useEffect(()=>{l&&(R(),k.current=!0)},[l,R]),h.useEffect(()=>{if(y.current&&!l){const b=t[t.length-1];(b==null?void 0:b.role)==="assistant"&&b.content&&_s("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:L("messageList.emptyStateHeading")}),i.jsx("p",{className:"mt-1 text-lg",children:L("messageList.emptyStateSubheading")})]})}):i.jsx("div",{ref:p,className:"message-list flex-1 overflow-y-auto pb-8 pt-4 sm:pt-6",onScroll:N,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(Du,{message:b,onRegenerate:e,onEdit:s,onStartThread:a,onClearThread:r,onSendThreadMessage:n,threadMessages:v.get(b.id),sessionId:o,isThreadSendDisabled:l,availableModels:d,defaultModel:u,selectedModel:f})},b.id)),i.jsx("div",{ref:m,className:"h-8"})]})})})}const Hu=4e3;function Vu(t,e,s={}){var _;const{t:a}=Ee(),[r,n]=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),p=typeof navigator<"u"?navigator.language:"en-US",g=Number.isFinite(s.silenceTimeoutMs)?Math.max(Math.floor(s.silenceTimeoutMs),1e3):Hu,x=((_=s.language)==null?void 0:_.trim())||p||"en-US",y=h.useCallback(S=>S.replace(/\s+/g," ").trim(),[]),k=h.useCallback(S=>{const I=y(S);I&&I!==u.current&&(u.current=I,t(I))},[y,t]),A=h.useCallback(()=>{if(!d.current)return;const S=d.current;d.current="",k(S)},[k]),L=typeof window<"u"&&("webkitSpeechRecognition"in window||"SpeechRecognition"in window),C=h.useCallback(()=>{!e||f.current||(f.current=!0,e())},[e]),v=h.useCallback(()=>{m.current!==null&&(clearTimeout(m.current),m.current=null)},[]),N=h.useCallback(()=>{v(),m.current=setTimeout(()=>{D("Speech recognition silence threshold reached, stopping recording"),c.current?c.current.stop():C()},g)},[v,C,g]),R=h.useCallback(()=>{if(!L){l(a("voice.browserNotSupported"));return}if(!c.current)try{f.current=!1;const S=window.SpeechRecognition||window.webkitSpeechRecognition,I=new S;I.continuous=!0,I.interimResults=!0,I.lang=x,I.maxAlternatives=1,I.onstart=()=>{n(!0),l(null),d.current="",u.current="",D("Speech recognition started"),N()},I.onresult=M=>{let F="",B="";for(let j=M.resultIndex;j<M.results.length;j++){const E=M.results[j][0].transcript;M.results[j].isFinal?F+=E:B+=E}B&&(d.current=y(B)),F&&(d.current="",k(F)),N()},I.onend=()=>{v(),A(),n(!1),c.current=null,D("Speech recognition ended"),C()},I.onerror=M=>{switch(v(),ge("Speech recognition error:",M.error),n(!1),c.current=null,d.current="",C(),M.error){case"no-speech":l(a("voice.error.noSpeech"));break;case"audio-capture":l(a("voice.error.audioCapture"));break;case"not-allowed":l(a("voice.error.notAllowed"));break;case"network":l(a("voice.error.network"));break;default:l(a("voice.error.generic",{error:M.error}))}},I.start(),c.current=I}catch(S){ge("Failed to start speech recognition:",S),l(a("voice.error.startFailed")),n(!1)}},[L,A,C,N,v,x,y,k,a]),b=h.useCallback(()=>{if(D("Stopping speech recognition..."),c.current){const S=c.current;S.onstart=null,S.onerror=null;try{S.stop()}catch(I){D("Recognition already stopped or error stopping:",I),v(),A(),S.onend=null,S.onresult=null,c.current=null,n(!1),C()}}v(),n(!1),l(null),D("Speech recognition stopped, isListening set to false")},[v,A,C]);return{isListening:r,isSupported:L,startListening:R,stopListening:b,error:o}}const qu=300,Xn=3,dr=5,Wu=6e4;function Yn(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 Ku(t,e={}){const{enabled:s=Si(),adapterName:a,sessionId:r,adapterSupportsAutocomplete:n,skill:o,inputRef:l}=e,[c,d]=h.useState([]),[u,f]=h.useState(!1),[m,p]=h.useState(-1),g=h.useRef(null),x=h.useRef(null),y=h.useRef(null),k=h.useRef(null),A=h.useRef(null),L=h.useRef(0),C=h.useRef([]),v=h.useRef([]),N=h.useRef(new Map);h.useEffect(()=>{C.current=c},[c]);const R=h.useCallback(j=>{const E=N.current.get(j);return E?E<=Date.now()?(N.current.delete(j),!1):!0:!1},[]),b=h.useCallback((j,E=!0)=>{const P=j.toLowerCase().trim(),T=v.current.length>0?v.current:C.current;if(!P)return T.slice(0,dr);const K=T.filter(G=>G.text.toLowerCase().includes(P));return K.length>0?K.slice(0,dr):E?T.slice(0,dr):[]},[]),_=h.useCallback(async j=>{if(!s||j.length<Xn){d([]),v.current=[],x.current&&clearTimeout(x.current),y.current&&clearTimeout(y.current),f(!1);return}if(!a){d([]),v.current=[],x.current&&clearTimeout(x.current),f(!1);return}if(n===!1||R(a)){d([]),v.current=[],x.current&&clearTimeout(x.current),f(!1);return}k.current&&k.current.abort(),k.current=new AbortController;const E=L.current+1;L.current=E,x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{E===L.current&&f(!0)},150);try{const P={"X-Adapter-Name":a};r&&(P["X-Session-ID"]=r);const T=new URLSearchParams;T.set("q",j),T.set("limit",String(dr)),o&&T.set("skill",o);const K=`/api/v1/autocomplete?${T.toString()}`,G=await fetch(K,{method:"GET",headers:P,signal:k.current.signal});if(!G.ok){me("[useAutocomplete] Request failed:",G.status),[404,405,501].includes(G.status)?(N.current.set(a,Date.now()+Wu),d([]),v.current=[]):d(b(j));return}const V=await G.json(),Z=Array.isArray(V==null?void 0:V.suggestions)?V.suggestions.map(ue=>Yn(typeof ue=="string"?ue:ue==null?void 0:ue.text)).filter(ue=>ue!==null):[];if(E!==L.current)return;Z.length===0?d(b(j,!1)):(d(Z),v.current=Z),p(-1),D("[useAutocomplete] Received",Z.length,"suggestions")}catch(P){if(P instanceof Error&&P.name==="AbortError")return;me("[useAutocomplete] Error:",P instanceof Error?P.message:String(P)),E===L.current&&d(b(j))}finally{E===L.current&&(x.current&&(clearTimeout(x.current),x.current=null),f(!1))}},[s,a,r,n,o,b,R]);h.useEffect(()=>{g.current&&clearTimeout(g.current);const j=()=>{k.current&&k.current.abort(),x.current&&clearTimeout(x.current),f(!1)},E=()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{y.current=null,d([]),j()},0)};if(!s||t.length<Xn||n===!1||a&&R(a)){E();return}if(A.current){if(t===A.current){E();return}A.current=null}return g.current=setTimeout(()=>{_(t)},qu),()=>{g.current&&clearTimeout(g.current),y.current&&(clearTimeout(y.current),y.current=null)}},[t,_,s,a,n,R]),h.useEffect(()=>()=>{k.current&&k.current.abort(),x.current&&clearTimeout(x.current)},[]);const S=h.useCallback(()=>{p(j=>{const E=C.current.length;return E===0?-1:j<E-1?j+1:0})},[]),I=h.useCallback(()=>{p(j=>{const E=C.current.length;return E===0?-1:j>0?j-1:E-1})},[]),M=h.useCallback(()=>{d([]),v.current=[],p(-1),k.current&&k.current.abort(),x.current&&clearTimeout(x.current),f(!1)},[]),F=h.useCallback(j=>{if(!(l!=null&&l.current))return;const E=()=>{const P=l.current;if(!P)return;const T=typeof j=="string"?j.length:P.value.length;P.focus({preventScroll:!0}),typeof P.setSelectionRange=="function"&&P.setSelectionRange(T,T)};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(E):setTimeout(E,0)},[l]),B=h.useCallback(j=>{A.current=j},[]);return{suggestions:c,isLoading:u,selectedIndex:m,setSelectedIndex:p,selectNext:S,selectPrevious:I,clearSuggestions:M,focusInputAfterSelection:F,suppressUntilQueryChange:B}}const Ut=new Map,Gu=new Map,Xu=new Map,Yu=new Set,Qu=()=>{if(typeof window>"u")return null;try{return localStorage.getItem("chat-adapter-name")}catch{return null}},to=t=>typeof t=="object"&&t!==null&&"message"in t,Zu=t=>t instanceof Error?t.message:typeof t=="string"?t:to(t)?t.message??"Unknown error":"Unknown error";function Ju({conversationId:t,onFilesSelected:e,onUploadError:s,onClose:a,onUploadingChange:r,onUploadSuccess:n,maxFiles:o=le.maxFilesPerConversation,disabled:l=!1}){const{t:c}=Ee(),[d,u]=h.useState(!1),[f,m]=h.useState(0),p=h.useRef(null),g=h.useRef(Xu),x=h.useRef(Yu),y=h.useRef(new Map),k=h.useRef(!0),A=h.useRef(Gu),L=h.useRef(t),C=ke(O=>O.conversations),v=h.useMemo(()=>{if(!t)return new Map;const O=Ut.get(t);return O?new Map(O):new Map},[t,f]),N=h.useCallback(O=>{if(!O){r==null||r(null,!1),m(re=>re+1);return}const te=Ut.get(O)||new Map,Y=C.find(re=>re.id===O),ee=new Map(te);if(Y!=null&&Y.attachedFiles){const re=new Set(Y.attachedFiles.filter(fe=>fe.processing_status==="completed"||fe.processing_status==="failed"||fe.processing_status==="error").map(fe=>fe.file_id));ee.forEach((fe,Ae)=>{fe.fileId&&re.has(fe.fileId)&&ee.delete(Ae)})}ee.size>0?(Ut.set(O,ee),r==null||r(O,!0)):(Ut.delete(O),r==null||r(O,!1)),m(re=>re+1)},[C,r]);h.useEffect(()=>{L.current=t,setTimeout(()=>{N(t)},0)},[t,N]),h.useEffect(()=>{t&&setTimeout(()=>{N(t)},0)},[C,t,N]);const R=h.useCallback((O,te)=>{if(!O)return;const Y=Ut.get(O)||new Map,ee=te(new Map(Y));ee.size>0?Ut.set(O,ee):Ut.delete(O),r==null||r(O,ee.size>0),m(re=>re+1)},[r]),b=h.useCallback((O,te)=>{if(!O)return;const Y=A.current.get(O)||[],ee=te([...Y||[]]),re=new Set(Y.map(fe=>fe.file_id));if(A.current.set(O,ee),e(O,ee),n){const fe=ee.filter(Ae=>!re.has(Ae.file_id));fe.length>0&&n(O,fe)}m(fe=>fe+1)},[e,n]),_=ke(O=>O.removeFileFromConversation),S=ke(O=>O.addFileToConversation);h.useEffect(()=>(k.current=!0,()=>{k.current=!1}),[]);const I=h.useCallback(()=>{k.current=!1,new Map(y.current).forEach(te=>te.abort()),setTimeout(()=>{const te=ke.getState(),Y=new Map(te.conversations.map(re=>[re.id,re])),ee=[];g.current.forEach((re,fe)=>{var Ae;if(re){const H=Y.get(re);if(new Set(((Ae=H==null?void 0:H.attachedFiles)==null?void 0:Ae.map(W=>W.file_id))||[]).has(fe)){x.current.add(fe),g.current.delete(fe);return}}if(x.current.has(fe)){D(`[FileUpload] Skipping cleanup delete for ${fe}; file was previously attached and already handled`),g.current.delete(fe),x.current.delete(fe);return}ee.push({fileId:fe,conversationId:re||null})}),ee.length>0&&(a==null||a(),ee.forEach(async({fileId:re,conversationId:fe})=>{try{if(fe)await _(fe,re);else{const Ae=Qu();await Os.deleteFile(re,void 0,void 0,Ae??void 0),ka(re)}}catch(Ae){if(to(Ae)){const H=Ae.message??"";!H.includes("404")&&!H.includes("File not found")&&me(`Failed to cleanup file ${re} during component unmount:`,Ae)}else me(`Failed to cleanup file ${re} during component unmount`,Ae)}}))},300)},[a,_]);h.useEffect(()=>I,[I]);const M=h.useCallback(async O=>{if(!O||O.length===0)return;const te=Array.from(O),Y=ke.getState(),ee=t||Y.currentConversationId;if(!ee){s==null||s(c("fileUpload.selectBeforeUpload"));return}const re=Y.conversations.find(J=>J.id===ee);if(!re){s==null||s(c("fileUpload.conversationNotFound"));return}if((A.current.get(ee)||[]).length+te.length>o){const J=c("fileUpload.maxFilesPerConversationError",{count:o});it()&&!wt()&&ot.getState().openLoginPrompt(c("fileUpload.maxFilesGuestLimitMessage",{count:o})),s==null||s(J);return}if(le.maxTotalFiles!==null&&Y.conversations.reduce((ye,ne)=>{var X;return ye+(((X=ne.attachedFiles)==null?void 0:X.length)||0)},0)+te.length>le.maxTotalFiles){const ye=c("fileUpload.maxTotalFilesError",{count:le.maxTotalFiles});it()&&!wt()&&ot.getState().openLoginPrompt(c("fileUpload.maxTotalFilesGuestLimitMessage",{count:le.maxTotalFiles})),s==null||s(ye);return}if(!re.adapterName){s==null||s(c("fileUpload.adapterNotConfigured"));return}const Ae=re.adapterName,H=ut(re.apiUrl);for(let J=0;J<te.length;J++){const W=te[J],ye=new AbortController;y.current.set(W.name,ye);const ne=`${ee}-${W.name}-${Date.now()}-${J}`;let X=null;const xe=W.type.startsWith("image/")?URL.createObjectURL(W):null;try{const Ce=await Os.uploadFile(W,oe=>{if(R(ee,ve=>(ve.set(ne,oe),ve)),oe.fileId&&!X){X=oe.fileId,g.current.set(oe.fileId,ee),x.current.add(oe.fileId),xe&&Xi(oe.fileId,xe);const ve={file_id:oe.fileId,filename:W.name,mime_type:W.type||"application/octet-stream",file_size:W.size,processing_status:oe.status==="uploading"?"uploading":oe.status==="processing"?"processing":oe.status==="completed"?"completed":void 0};D(`[FileUpload] Adding file ${oe.fileId} to conversation ${ee} immediately (status: ${ve.processing_status})`),S(ee,ve)}},void 0,H,Ae).catch(oe=>{if(oe.message&&oe.message.includes("was deleted")){X&&g.current.delete(X);const ve=oe.message.match(/File\s+([\w-]+)\s+was deleted/);return ve&&ve[1]&&g.current.delete(ve[1]),D(`File ${W.name} was deleted during upload`),null}throw oe});Ce?(g.current.set(Ce.file_id,ee),x.current.add(Ce.file_id),D(`[FileUpload] Updating file ${Ce.file_id} in conversation ${ee} with final status`),S(ee,Ce),Ce.processing_status==="completed"||Ce.processing_status==="failed"||Ce.processing_status==="error"?R(ee,ve=>(ve.delete(ne),ve)):R(ee,ve=>{const $e=ve.get(ne);return $e&&ve.set(ne,{...$e,progress:90,status:"processing",fileId:Ce.file_id}),ve}),b(ee,ve=>{if(new Set(ve.map(ie=>ie.file_id)).has(Ce.file_id))return ve;const z=[...ve,Ce];return D(`[FileUpload] Updated uploadedFiles for ${ee}: ${z.length} files`,z),z})):(me(`Upload completed for ${W.name} but uploadedAttachment is null`),R(ee,oe=>(oe.delete(ne),oe)))}catch(Ce){const oe=Zu(Ce);if(Ce instanceof DOMException&&Ce.name==="AbortError"||ye.signal.aborted){D(`Upload cancelled for ${W.name}`),X?g.current.delete(X):xe&&URL.revokeObjectURL(xe);continue}if(oe.includes("was deleted")){D(`File ${W.name} was deleted during upload`),X&&g.current.delete(X);const z=oe.match(/File\s+([\w-]+)\s+was deleted/);z&&z[1]&&g.current.delete(z[1]);continue}k.current?(ge(`Failed to upload file ${W.name}:`,Ce),ge(`File type: ${W.type}, File name: ${W.name}`),s==null||s(oe||`Failed to upload ${W.name}`)):me(`Upload error for ${W.name} (component unmounted):`,oe),X?g.current.delete(X):xe&&URL.revokeObjectURL(xe);const ve=ne,$e=ee;setTimeout(()=>{R($e,z=>(z.delete(ve),z))},5e3)}finally{y.current.delete(W.name)}}},[S,t,o,s,c,b,R]),F=h.useCallback(O=>{O.preventDefault(),O.stopPropagation(),l||u(!0)},[l]),B=h.useCallback(O=>{O.preventDefault(),O.stopPropagation(),u(!1)},[]),j=h.useCallback(O=>{if(O.preventDefault(),O.stopPropagation(),u(!1),l)return;const te=O.dataTransfer.files;M(te)},[l,M]),E=h.useCallback(O=>{const te=O.target.files;M(te),p.current&&(p.current.value="")},[M]),P=h.useCallback(()=>{!l&&p.current&&p.current.click()},[l]),T=h.useCallback(O=>{l||(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),P())},[l,P]),K=v.size>0,G=h.useMemo(()=>{const O=new Map;return C.forEach(te=>{O.set(te.id,te.title||c("chatInterface.newChatTitle"))}),O},[C,c]),V=h.useMemo(()=>{const O=[];return Ut.forEach((te,Y)=>{Y!==t&&te.size>0&&O.push({conversationId:Y,uploads:Array.from(te.entries()).map(([ee,re])=>({key:ee,progress:re}))})}),O},[t,f]),Z=(O,te)=>{const Y=O.status==="uploading"?c("fileUpload.uploadingStatus"):O.status==="processing"?c("fileUpload.processingStatus"):O.status==="completed"?c("fileUpload.completedStatus"):void 0;return i.jsx(Ar,{filename:O.filename,fileId:O.fileId,status:O.status,statusText:Y,errorMessage:O.error||(O.status==="error"?c("fileUpload.processingFailedMessage"):void 0)},te)},ue=i.jsx("div",{className:"w-full max-w-full overflow-hidden flex flex-wrap gap-2",role:"status","aria-live":"polite",children:Array.from(v.entries()).map(([O,te])=>Z(te,O))});return i.jsxs("div",{className:"w-full max-w-full overflow-hidden space-y-2",children:[K&&ue,!K&&i.jsxs("button",{type:"button",onClick:P,onKeyDown:T,onDragOver:F,onDragLeave:B,onDrop:j,disabled:l,className:`
341
+ ... (content truncated due to length)`}const ru={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 au(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 le=new Proxy(ru,{get(t,e){if(it()&&!wt()){const s=au(e);if(s!==void 0)return s}return t[e]}});function hs(){return h.useSyncExternalStore(Vd,wt,wt)}class Wi extends Error{constructor(s,a){super(s);Ze(this,"status");Ze(this,"statusText");this.name="ApiRequestError",this.status=a.status,this.statusText=a.statusText}}async function De(t={}){const e={"X-User-ID":await Hi(),...t},s=await Pa();return s&&(e.Authorization=`Bearer ${s}`),e}function vt(t){return encodeURIComponent(t)}function nu(t){return!t||t.length===0?"":`?file_ids=${t.map(encodeURIComponent).join(",")}`}async function Ls(t){const e=`API request failed: ${t.status} ${t.statusText}`;try{if((t.headers.get("content-type")||"").includes("application/json")){const a=await t.json(),r=typeof a.detail=="string"&&a.detail.trim()||typeof a.error=="string"&&a.error.trim()||typeof a.message=="string"&&a.message.trim();if(r)return`${e}: ${r}`}else{const a=(await t.text()).trim();if(a)return`${e}: ${a}`}}catch{}return e}function zn(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,assistant_message_id:e.assistant_message_id,threading:e.threading}}catch{return null}}let or=null;function iu(){let t=null,e=null;const s=(r,n,o)=>{t=n||null,e=o||null},a=(r,n)=>({async*streamChat(o,l,c,d,u,f,m,p,g,x,y,k,A,L){var N,R;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),p!==void 0&&(C.return_audio=p),g&&(C.tts_voice=g),x&&(C.source_language=x),y&&(C.target_language=y),k&&(C.model=k),A&&(C.skill=A),L&&(C.regenerate_of_message_id=L);const v=await fetch("/api/v1/chat",{method:"POST",headers:await De({"Content-Type":"application/json","X-Adapter-Name":r,...n?{"X-Session-ID":n}:{}}),body:JSON.stringify(C)});if(!v.ok)throw new Error(await Ls(v));if((N=v.headers.get("content-type"))!=null&&N.includes("text/event-stream")){const b=(R=v.body)==null?void 0:R.getReader(),_=new TextDecoder;let S="";if(!b)throw new Error("Response body is not readable");for(;;){const{done:I,value:M}=await b.read();if(I)break;S+=_.decode(M,{stream:!0});const F=S.split(`
342
+ `);S=F.pop()||"";for(const H of F){const j=zn(H);j&&(yield j)}}if(S.trim())for(const I of S.split(`
343
+ `)){const M=zn(I);M&&(yield M)}}else{const b=await v.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,assistant_message_id:b.assistant_message_id,threading:b.threading}}},async createThread(o,l){const c=await fetch("/api/threads",{method:"POST",headers:await De({"Content-Type":"application/json","X-Adapter-Name":r,"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/${vt(o)}`,{headers:await De({"X-Adapter-Name":r})});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/${vt(o)}`,{method:"DELETE",headers:await De({"X-Adapter-Name":r})});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 De({"Content-Type":"application/json","X-Adapter-Name":r,"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/${vt(o)}`,{headers:await De({"X-Adapter-Name":r})});if(!l.ok)throw new Error(`Failed to get feedback: ${l.statusText}`);return l.json()},async clearConversationHistory(o){const l=o||n;if(!l)throw new Error("No session ID available for clearing conversation history");const c=await fetch(`/api/admin/chat-history/${vt(l)}`,{method:"DELETE",headers:await De({"X-Adapter-Name":r})});if(!c.ok)throw new Error(`Failed to clear history: ${c.statusText}`);return c.json()},async getConversationHistory(o,l){const c=o||n;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/${vt(c)}${d}`,{headers:await De({"X-Adapter-Name":r})});if(!u.ok)throw new Error(`Failed to load history: ${u.statusText}`);return u.json()},async deleteConversationWithFiles(o,l){const c=o||n;if(!c)throw new Error("No session ID available for deleting conversation");const d=nu(l),u=await fetch(`/api/admin/conversations/${vt(c)}${d}`,{method:"DELETE",headers:await De({"X-Adapter-Name":r})});if(!u.ok)throw new Error(`Failed to delete conversation: ${u.statusText}`);return u.json()},getSessionId:()=>n,async uploadFile(o){const l=new FormData;l.append("file",o);const c=await fetch("/api/files/upload",{method:"POST",headers:await De({"X-Adapter-Name":r}),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 De({"X-Adapter-Name":r})});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/${vt(o)}`,{headers:await De({"X-Adapter-Name":r})});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/${vt(o)}/query`,{method:"POST",headers:await De({"Content-Type":"application/json","X-Adapter-Name":r}),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/${vt(o)}`,{method:"DELETE",headers:await De({"X-Adapter-Name":r})});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/${vt(r)}/status`,{headers:await De({"X-Adapter-Name":r})});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 p=Date.parse(f);if(!Number.isNaN(p)){const g=p-Date.now();if(g>0)return Math.min(g,3e4)}return 0},c=f=>new Promise(m=>setTimeout(m,f)),d=async()=>fetch(o,{headers:await De({"X-Adapter-Name":r})});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(),p=u.status===401?`Adapter info request was unauthorized for '${r}'. Verify the adapter exists and you have access.`:`Failed to load adapter info (${m}) for '${r}'.`;throw console.warn("[ProxyApi] Adapter info request failed",{adapter:r,status:u.status,statusText:u.statusText,details:f||void 0}),new Wi(p,u)}return u.json()},async stopChat(o,l){const c=await fetch("/api/v1/chat/stop",{method:"POST",headers:await De({"Content-Type":"application/json","X-Adapter-Name":r}),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 De({"X-Adapter-Name":r})});if(!l.ok)throw new Error(await Ls(l));return l.json()},async getAllModels(){const o=await fetch("/api/admin/models",{headers:await De({"X-Adapter-Name":r})});if(!o.ok)throw new Error(await Ls(o));return o.json()},async getAdapterSkills(o){const l=await fetch(`/api/admin/adapters/${encodeURIComponent(o)}/skills`,{headers:await De({"X-Adapter-Name":r})});if(!l.ok)throw new Error(await Ls(l));return l.json()},async getAllSkills(){const o=await fetch("/api/admin/skills",{headers:await De({"X-Adapter-Name":r})});if(!o.ok)throw new Error(await Ls(o));return o.json()}});return{configureApi:s,streamChat:async function*(r,n,o,l,c,d,u,f,m,p,g,x,y,k){if(!e)throw new Error("Adapter name is required");yield*a(e,t).streamChat(r,n,o,l,c,d,u,f,m,p,g,x,y,k)},stopChat:async(r,n)=>{if(!e)throw new Error("Adapter name is required");return a(e,t).stopChat(r,n)},ApiClient:class{constructor(n){Ze(this,"client");const o=n.adapterName||null,l=n.sessionId||null;if(!o)throw new Error("Adapter name is required");this.client=a(o,l)}async*streamChat(...n){yield*this.client.streamChat(...n)}get createThread(){var n;return(n=this.client.createThread)==null?void 0:n.bind(this.client)}get getThreadInfo(){var n;return(n=this.client.getThreadInfo)==null?void 0:n.bind(this.client)}get deleteThread(){var n;return(n=this.client.deleteThread)==null?void 0:n.bind(this.client)}get submitFeedback(){var n;return(n=this.client.submitFeedback)==null?void 0:n.bind(this.client)}get getSessionFeedback(){var n;return(n=this.client.getSessionFeedback)==null?void 0:n.bind(this.client)}get clearConversationHistory(){var n;return(n=this.client.clearConversationHistory)==null?void 0:n.bind(this.client)}get getConversationHistory(){var n;return(n=this.client.getConversationHistory)==null?void 0:n.bind(this.client)}get deleteConversationWithFiles(){var n;return(n=this.client.deleteConversationWithFiles)==null?void 0:n.bind(this.client)}get getSessionId(){var n;return(n=this.client.getSessionId)==null?void 0:n.bind(this.client)}get uploadFile(){var n;return(n=this.client.uploadFile)==null?void 0:n.bind(this.client)}get listFiles(){var n;return(n=this.client.listFiles)==null?void 0:n.bind(this.client)}get getFileInfo(){var n;return(n=this.client.getFileInfo)==null?void 0:n.bind(this.client)}get queryFile(){var n;return(n=this.client.queryFile)==null?void 0:n.bind(this.client)}get deleteFile(){var n;return(n=this.client.deleteFile)==null?void 0:n.bind(this.client)}get validateApiKey(){var n;return(n=this.client.validateApiKey)==null?void 0:n.bind(this.client)}get getAdapterInfo(){var n;return(n=this.client.getAdapterInfo)==null?void 0:n.bind(this.client)}get stopChat(){var n;return(n=this.client.stopChat)==null?void 0:n.bind(this.client)}get getAdapterModels(){var n;return(n=this.client.getAdapterModels)==null?void 0:n.bind(this.client)}get getAllModels(){var n;return(n=this.client.getAllModels)==null?void 0:n.bind(this.client)}get getAdapterSkills(){var n;return(n=this.client.getAdapterSkills)==null?void 0:n.bind(this.client)}get getAllSkills(){var n;return(n=this.client.getAllSkills)==null?void 0:n.bind(this.client)}}}}async function ou(){return or||(U("Loading API via Express proxy"),or=iu(),U("API loaded successfully"),or)}async function $e(){return await ou()}class Bn{static async getAdapterSkills(e,s){const a=await $e(),r=new a.ApiClient({apiUrl:"",adapterName:s});return r.getAdapterSkills?(await r.getAdapterSkills(e)).available_skills:[]}static async getAllSkills(e){const s=await $e(),a=new s.ApiClient({apiUrl:"",adapterName:e});return a.getAllSkills?(await a.getAllSkills()).skills:[]}}const lu=6e4;function Ki(t={}){const{adapterName:e,enabled:s=!0,selectionScopeKey:a,supportsThreading:r=!1}=t,n=s&&!!e&&!r,o=a??e??"__default__",[l,c]=h.useState([]),[d,u]=h.useState(!1),[f,m]=h.useState(null),[p,g]=h.useState({}),x=h.useRef(null),y=h.useRef(new Map),k=h.useCallback(async v=>{var b,_;const N=v,R=y.current.get(N);if(R&&R.expiresAt>Date.now()){c(R.skills),m(v);return}x.current&&x.current.abort(),x.current=new AbortController,u(!0);try{const[S,I]=await Promise.all([Bn.getAdapterSkills(v,v),Bn.getAllSkills(v)]);if((b=x.current)!=null&&b.signal.aborted)return;const M=I.filter(F=>S.includes(F.name)&&F.enabled);y.current.set(N,{skills:M,expiresAt:Date.now()+lu}),c(M),m(v),U("[useSkills] Loaded",M.length,"skills for adapter",v)}catch(S){if(S instanceof Error&&S.name==="AbortError")return;ge("[useSkills] Failed to load skills:",S instanceof Error?S.message:String(S)),c([]),m(v)}finally{(_=x.current)!=null&&_.signal.aborted||u(!1)}},[]);h.useEffect(()=>{if(!n||!e)return;const v=window.setTimeout(()=>{k(e)},0);return()=>{var N;window.clearTimeout(v),(N=x.current)==null||N.abort()}},[n,e,k]);const A=h.useCallback(v=>{g(N=>{const R=N[o]??null;if(R===v||(R==null?void 0:R.name)===(v==null?void 0:v.name))return N;const b={...N};return v?b[o]=v:delete b[o],b})},[o]),L=h.useCallback(()=>{g(v=>{if(!v[o])return v;const N={...v};return delete N[o],N})},[o]),C=n?p[o]??null:null;return{skills:n&&f===e?l:[],isLoading:n?d||f!==e:!1,selectedSkill:C,selectSkill:A,clearSkill:L}}const Hn=t=>{let e;const s=new Set,a=(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),s.forEach(p=>p(e,m))}},r=()=>e,l={setState:a,getState:r,getInitialState:()=>c,subscribe:d=>(s.add(d),()=>s.delete(d))},c=e=t(a,r,l);return l},cu=(t=>t?Hn(t):Hn),du=t=>t;function uu(t,e=du){const s=gt.useSyncExternalStore(t.subscribe,gt.useCallback(()=>e(t.getState()),[t,e]),gt.useCallback(()=>e(t.getInitialState()),[t,e]));return gt.useDebugValue(s),s}const Vn=t=>{const e=cu(t),s=a=>uu(e,a);return Object.assign(s,e),s},Gi=(t=>t?Vn(t):Vn),ot=Gi(t=>({showLoginPrompt:!1,promptMessage:"",openLoginPrompt:e=>t({showLoginPrompt:!0,promptMessage:e}),closeLoginPrompt:()=>t({showLoginPrompt:!1,promptMessage:""})})),lr=t=>{const e=t==null?void 0:t.trim();return e||(typeof window<"u"&&window.localStorage?localStorage.getItem("chat-adapter-name"):null)};class Os{static async uploadFile(e,s,a,r,n){try{const o=le.maxFileSizeMB*1024*1024;if(e.size>o)throw new Error(`File size exceeds maximum limit of ${le.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"}`);s&&s({filename:e.name,progress:0,status:"uploading"});const d=await $e(),u=(r==null?void 0:r.trim())||Re(),f=lr(n);if(!f)throw new Error("Adapter not configured. Please select an adapter from the dropdown.");U(`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 p=await m.uploadFile(e);s&&s({filename:e.name,progress:75,status:"processing",fileId:p.file_id});let g;try{g=await this.pollFileStatus(p.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 ${p.file_id} was deleted during upload`);ge(`File status polling failed for ${p.file_id}:`,x);const k=y.includes("processing failed")||y.includes("timeout");g={file_id:p.file_id,filename:p.filename,mime_type:p.mime_type,file_size:p.file_size,processing_status:k?"failed":p.status||"processing",chunk_count:p.chunk_count,error_message:k?y:void 0}}return s&&s({filename:e.name,progress:100,status:g.processing_status==="completed"?"completed":"processing",fileId:p.file_id}),g}catch(o){let l=o instanceof Error?o.message:"Upload failed";throw l.includes("401")&&(l="Authentication failed. Please check your adapter configuration."),s&&s({filename:e.name,progress:0,status:"error",error:l}),new Error(l)}}static async uploadFiles(e,s){const r=[],n=[];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=>{s&&s(f,m)})}));for(let d=0;d<c.length;d++){const u=c[d],f=o+d;u.status==="fulfilled"?r.push(u.value):(ze(`Failed to upload file ${e[f].name}:`,u.reason),n.push({index:f,file:e[f].name,error:u.reason}))}}if(r.length===0&&n.length>0){const o=n[0].error;throw o instanceof Error?o:new Error(`All ${n.length} file uploads failed`)}return n.length>0&&ge(`[FileUploadService] ${n.length} of ${e.length} files failed to upload:`,n.map(o=>o.file)),r}static async listFiles(e,s,a){try{const r=await $e(),n=(s==null?void 0:s.trim())||Re(),o=lr(a);if(!o)throw new Error("Adapter not configured");const l=new r.ApiClient({apiUrl:n,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(r){ze("Failed to list files:",r);const n=r instanceof Error?r.message:"Failed to list files";throw new Error(n)}}static async getFileInfo(e,s,a,r){try{const n=await $e(),o=(a==null?void 0:a.trim())||Re(),l=lr(r);if(!l)throw new Error("Adapter not configured");const c=new n.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(n){if(n instanceof Error&&(n.message.includes("404")||n.message.includes("File not found")))throw new Error(`File ${e} was deleted`);ze(`Failed to get file info for ${e}:`,n);const o=n instanceof Error?n.message:`Failed to get file info: ${e}`;throw new Error(o)}}static async pollFileStatus(e,s=30,a=2e3,r,n,o){for(let l=0;l<s;l++)try{if(r&&!r())throw new Error("Polling cancelled - component unmounted");const c=await this.getFileInfo(e,void 0,n,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<s-1&&await new Promise(d=>setTimeout(d,a))}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<s-1){await new Promise(u=>setTimeout(u,a));continue}throw c}throw new Error(`File processing timeout: ${e} did not complete within ${s*a/1e3} seconds`)}static async deleteFile(e,s,a,r){try{const n=await $e(),o=(a==null?void 0:a.trim())||Re(),l=lr(r);if(!l)throw new Error("Adapter not configured");const c=new n.ApiClient({apiUrl:o,sessionId:null,adapterName:l});if(!c.deleteFile)throw new Error("File deletion is not available.");return await c.deleteFile(e)}catch(n){if(n instanceof Error&&(n.message.includes("404")||n.message.includes("File not found")||n.message.includes("Not Found")))return U(`File ${e} was already deleted from server`),{message:"File already deleted",file_id:e};ze(`Failed to delete file ${e}:`,n);const o=n instanceof Error?n.message:`Failed to delete file: ${e}`;throw new Error(o)}}}class fu{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,s;try{if(!this.audioContext){const n=typeof AudioContext<"u"?AudioContext:typeof window<"u"&&window.webkitAudioContext||null;n&&(this.audioContext=new n)}const a=((e=this.audioContext)==null?void 0:e.state)==="suspended"?this.audioContext.resume():Promise.resolve();let r=Promise.resolve();try{const n=this.createSilentWavBlob(),o=URL.createObjectURL(n),l=new Audio;l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),l.src=o,l.volume=0,r=l.play().then(()=>{l.pause()}).catch(()=>{U("[AudioStreamManager] HTMLAudioElement silent unlock failed (will retry on next gesture)")}).finally(()=>{URL.revokeObjectURL(o)})}catch{U("[AudioStreamManager] Could not create silent audio element")}if(await a,this.audioContext&&this.audioContext.state==="running"){const n=this.audioContext.createBuffer(1,1,22050),o=this.audioContext.createBufferSource();o.buffer=n,o.connect(this.audioContext.destination),o.start(0)}return await r,this.isEnabled=!0,U("[AudioStreamManager] Audio playback enabled",{audioContextState:(s=this.audioContext)==null?void 0:s.state}),!0}catch(a){return xe("[AudioStreamManager] Failed to enable audio:",a),!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(),U("[AudioStreamManager] Audio playback disabled"))}async ensureAudioContext(){var e;if(!this.audioContext){const s=typeof AudioContext<"u"?AudioContext:typeof window<"u"&&window.webkitAudioContext||null;if(s)try{this.audioContext=new s}catch(a){return xe("[AudioStreamManager] Failed to create AudioContext:",a),!1}}if(((e=this.audioContext)==null?void 0:e.state)==="suspended")try{await this.audioContext.resume()}catch(s){return U("[AudioStreamManager] AudioContext resume deferred",s),!1}return!0}resolveMimeType(e){const s=this.mimeTypeCache.get(e);if(s)return s;let a;switch(e){case"mp3":a="audio/mpeg";break;case"wav":a="audio/wav";break;case"webm":a="audio/webm";break;case"ogg":a="audio/ogg";break;case"opus":{const r=typeof document<"u"?document.createElement("audio"):null;r!=null&&r.canPlayType("audio/ogg; codecs=opus")?a="audio/ogg; codecs=opus":r!=null&&r.canPlayType("audio/webm; codecs=opus")?a="audio/webm; codecs=opus":a="audio/mp4";break}default:a=`audio/${e}`}return this.mimeTypeCache.set(e,a),U(`[AudioStreamManager] Resolved MIME type for "${e}": ${a}`),a}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){U(`[AudioStreamManager] Audio disabled, dropping chunk ${e.chunkIndex}`);return}U(`[AudioStreamManager] Adding chunk ${e.chunkIndex} to queue`),this.audioQueue.push(e),this.audioQueue.sort((s,a)=>s.chunkIndex-a.chunkIndex),this.isPlaying||this.playNextChunk().catch(s=>{xe("[AudioStreamManager] Playback chain error:",s)})}async playNextChunk(){var s,a;if(this.audioQueue.length===0){this.isPlaying=!1,U("[AudioStreamManager] Queue empty, playback complete"),this.onPlaybackEnd&&this.onPlaybackEnd();return}if(!this.isEnabled){U("[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(),U(`[AudioStreamManager] Playing chunk ${e.chunkIndex}`),!e.audio||e.audio.length===0)throw new Error(`Empty audio data for chunk ${e.chunkIndex}`);let r;try{r=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(r.length===0)throw new Error(`Decoded audio data is empty for chunk ${e.chunkIndex}`);const n=new Uint8Array(r.length);for(let f=0;f<r.length;f++)n[f]=r.charCodeAt(f);const o=this.resolveMimeType(e.audioFormat),l=new Blob([n],{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){U(`[AudioStreamManager] HTMLAudioElement failed for chunk ${e.chunkIndex}, trying AudioContext fallback`);try{u=await this.playViaAudioContext(n.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(r){if(this.suppressPlaybackErrors){U("[AudioStreamManager] Playback stopped, suppressing audio error");return}const n=r instanceof Error?r.message:String(r);console.error(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,n,r,{audioFormat:e.audioFormat,chunkIndex:e.chunkIndex,audioLength:(s=e.audio)==null?void 0:s.length,audioContextState:(a=this.audioContext)==null?void 0:a.state,isEnabled:this.isEnabled}),xe(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,r),this.playNextChunk().catch(o=>{xe("[AudioStreamManager] Playback chain error after recovery:",o)})}}playViaAudioElement(e,s,a){return new Promise(r=>{const n=new Audio;n.setAttribute("playsinline",""),n.setAttribute("webkit-playsinline",""),n.src=e,this.currentAudio=n;let o=!1;const l=u=>{o||(o=!0,r(u))},c=()=>{if(this.suppressPlaybackErrors){a(),l(!0);return}const u=n.error;xe(`[AudioStreamManager] Media error on chunk ${s.chunkIndex}:`,u?{code:u.code,message:u.message,SRC_NOT_SUPPORTED:u.code===MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED}:"unknown"),a(),l(!1)};n.addEventListener("error",c,{once:!0});const d=async()=>{if(!o)try{n.addEventListener("ended",()=>{o||(U(`[AudioStreamManager] Chunk ${s.chunkIndex} finished`),this.onChunkPlayed&&this.onChunkPlayed(s.chunkIndex),a(),l(!0))},{once:!0}),await n.play()}catch(u){if(this.suppressPlaybackErrors){a(),l(!0);return}U(`[AudioStreamManager] audio.play() rejected for chunk ${s.chunkIndex}:`,u),a(),l(!1)}};n.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA?d():n.addEventListener("canplay",()=>d(),{once:!0})})}playViaAudioContext(e,s){return new Promise((a,r)=>{if(!this.audioContext){r(new Error("No AudioContext"));return}const n=e.slice(0);this.audioContext.decodeAudioData(n,o=>{if(!this.audioContext||this.suppressPlaybackErrors){a(!0);return}const l=this.audioContext.createBufferSource();l.buffer=o,l.connect(this.audioContext.destination),l.onended=()=>{U(`[AudioStreamManager] Chunk ${s} finished (AudioContext path)`),this.onChunkPlayed&&this.onChunkPlayed(s),a(!0)},l.start(0)},o=>{r(o)})})}stop(){U("[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(),U("[AudioStreamManager] Manager reset")}getQueueSize(){return this.audioQueue.length}isCurrentlyPlaying(){return this.isPlaying}}const Bt=new fu,hu=[{extensions:["pdf"],Icon:xa,colorClass:"bg-red-500"},{extensions:["doc","docx"],Icon:xa,colorClass:"bg-blue-500"},{extensions:["xls","xlsx","csv"],Icon:Mi,colorClass:"bg-emerald-600"},{extensions:["ppt","pptx"],Icon:Pi,colorClass:"bg-orange-500"},{extensions:["png","jpg","jpeg","webp","tiff","gif"],Icon:qc,colorClass:"bg-violet-500"},{extensions:["wav","mp3","ogg","flac","webm","m4a","aac"],Icon:Vc,colorClass:"bg-teal-600"},{extensions:["mp4","mov","avi","mkv"],Icon:Wc,colorClass:"bg-pink-600"},{extensions:["zip","rar","7z","tar","gz"],Icon:Hc,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:Ti,colorClass:"bg-slate-500"}],pu=new Set(["png","jpg","jpeg","webp","tiff","gif"]);function mu(t){const e=/\.([a-z0-9]+)$/i.exec(t.trim());return e?e[1].toLowerCase():""}function gu(t){const e=mu(t),s=hu.find(a=>a.extensions.includes(e));return{Icon:(s==null?void 0:s.Icon)??Kc,colorClass:(s==null?void 0:s.colorClass)??"bg-gray-400 dark:bg-gray-500",label:e?e.toUpperCase():"",isImage:pu.has(e)}}const zs=new Map;function Xi(t,e){const s=zs.get(t);s&&s!==e&&URL.revokeObjectURL(s),zs.set(t,e)}function xu(t){return zs.get(t)}function ka(t){const e=zs.get(t);e&&(URL.revokeObjectURL(e),zs.delete(t))}const bu=hc()||Zl(),Yi=()=>{if(_r())return Na()||void 0},Fs="",yu=["New Chat","New Conversation"],wu=t=>t&&!yu.includes(t)?t:Fs,$s=(t,e,s)=>({id:t,sessionId:e,title:Fs,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:s,adapterName:Yi(),adapterLoadError:null}),Sr=()=>{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},ku=t=>{localStorage.setItem("chatbot-session-id",t)};let vu=0;const os=t=>{const e=Date.now(),s=++vu,a=Math.random().toString(36).substr(2,9);return`msg_${e}_${s}_${a}_${t}`},Ht=()=>{const t=Date.now(),e=Math.random().toString(36).substr(2,9);return`session_${t}_${e}`},Qi=t=>{const e=new Set;let s=!1;const a=t.map(r=>{if(!e.has(r.id))return e.add(r.id),r;s=!0;const n={...r,id:os(r.role)};return e.add(n.id),ge(`[chatStore] Re-keyed duplicate message id ${r.id}`),n});return s?a:t},qn=t=>t.filter(e=>!e.isThreadMessage&&!(e.role==="assistant"&&e.isStreaming)).length,Wn=t=>t.flatMap(s=>[s.imageUrl,s.videoUrl,s.documentUrl]).map(s=>{var a;return((a=s==null?void 0:s.match(/\/api\/files\/([^/]+)\/content/))==null?void 0:a[1])??null}).filter(s=>s!==null),Su=(t,e)=>{if(t instanceof Date)return new Date(t);if(typeof t=="number"&&Number.isFinite(t)){const s=new Date(t);if(!Number.isNaN(s.getTime()))return s}if(typeof t=="string"){const s=new Date(t);if(!Number.isNaN(s.getTime()))return s}return e?new Date(e):new Date},ju=(t,e)=>{const s=new Map;e.forEach((r,n)=>{r.databaseMessageId&&s.set(r.databaseMessageId,{message:r,index:n})});const a=new Set;return t.map((r,n)=>{var f;const o=r.role==="user"?"user":"assistant",l=typeof r.message_id=="string"&&r.message_id.length>0?r.message_id:void 0;let c;if(l&&s.has(l)){const m=s.get(l);c=m.message,a.add(m.index)}else{const m=n<e.length?n:0;if(!a.has(m)&&((f=e[m])==null?void 0:f.role)===o)c=e[m],a.add(m);else for(let p=1;p<e.length;p++){const g=(m+p)%e.length;if(!a.has(g)&&e[g].role===o){c=e[g],a.add(g);break}}}const d=r.timestamp?Su(r.timestamp,c==null?void 0:c.timestamp):c!=null&&c.timestamp?new Date(c.timestamp):new Date,u=c?{...c,content:r.content??c.content,timestamp:d}:{id:l?`srv_${l}`:os(o),content:r.content||"",role:o,timestamp:d};if(u.isStreaming=!1,l&&(u.databaseMessageId=l),!u.supportsThreading&&r.metadata&&typeof r.metadata=="object"){const m=r.metadata,p=m==null?void 0:m.retrieved_docs;Array.isArray(p)&&p.length>0&&(u.supportsThreading=!0)}return u})},Cu=(t,e)=>{if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++){const a=t[s],r=e[s];if(a.role!==r.role||a.content!==r.content||(a.databaseMessageId||null)!==(r.databaseMessageId||null)||+a.timestamp!=+r.timestamp)return!1}return!0},Zi=t=>{var r,n,o,l,c,d;const e=((n=(r=t.adapterInfo)==null?void 0:r.adapter_name)==null?void 0:n.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 s=!1;try{const u=localStorage.getItem("chat-settings");u&&(s=JSON.parse(u).voiceEnabled===!0)}catch{ge("Failed to read global voice setting")}const a=t.audioSettings;return{returnAudio:(a==null?void 0:a.enabled)??s??!!e,ttsVoice:(a==null?void 0:a.ttsVoice)||void 0,language:(a==null?void 0:a.language)||"en-US",audioFormat:a==null?void 0:a.audioFormat}},Au=300;let cr=null;const Ke=t=>{cr&&clearTimeout(cr),cr=setTimeout(()=>{cr=null;try{const e=t(),s=e.conversations.map(a=>({...a,messages:a.messages.map(r=>r.audio||r.image||r.video||r.document?Object.fromEntries(Object.entries(r).filter(([o])=>o!=="audio"&&o!=="image"&&o!=="video"&&o!=="document")):r)}));localStorage.setItem("chat-state",JSON.stringify({conversations:s,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)}},Au)},Nu=32,ls=new Map;let zt=null,ft=null,Et=null,Jt=null;const va=(t,e)=>{const s=ls.get(t);if(s){if(s.timeoutId&&(clearTimeout(s.timeoutId),s.timeoutId=null),s.content){const a=s.content,r=s.messageId;s.content="",e(n=>({conversations:n.conversations.map(o=>{if(o.id!==t)return o;const l=[...o.messages],c=r?l.findIndex(u=>u.id===r):l.length-1,d=c!==-1?l[c]:void 0;return d&&d.role==="assistant"&&d.isStreaming&&(l[c]={...d,content:d.content+a}),{...o,messages:l,updatedAt:new Date}})}))}ls.delete(t)}},jt=(t,e,s,a)=>({conversations:t.conversations.map(r=>{var l;if(r.id!==e)return r;const n=[...r.messages],o=a?n.findIndex(c=>c.id===a):n.length-1;return o!==-1&&((l=n[o])==null?void 0:l.role)==="assistant"&&(n[o]={...n[o],...s(n[o])}),{...r,messages:n,updatedAt:new Date}})});let jr=!1,Cr="";async function Es(){if(jr&&Cr)return!0;try{const t=await $e(),e=localStorage.getItem("chat-api-url");e&&e===fa&&localStorage.removeItem("chat-api-url");const s=e&&e!==fa?e:Re(),a=Sr(),r=localStorage.getItem("chat-adapter-name")||bu;return t.configureApi(s,a,r),Cr=s,jr=!0,!0}catch(t){return ze("Failed to configure API:",t),!1}}async function Kn(t,e,s,a,r,n,o,l,c){let d=!1;const u=new AbortController;zt=u,Jt=a,ft=null;try{const f=t().conversations.find(y=>y.id===a);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.");Et=f.sessionId,f.sessionId&&(await $e()).configureApi(ut(f.apiUrl),f.sessionId,f.adapterName);const m=await $e(),{returnAudio:p,ttsVoice:g,language:x}=Zi(f);for await(const y of m.streamChat(r,!0,n.length>0?n:void 0,void 0,void 0,void 0,x,p,g,void 0,void 0,o,void 0,c)){if(y.request_id&&!ft&&(ft=y.request_id,U(`[chatStore] >>> CAPTURED request_id for ${l} stop: ${y.request_id}`)),y.text){const k=Us(y.text);k?(t().appendToLastMessage(k,a,s),d=!0):y.text.length>100&&ge("[chatStore] Filtered out potential base64 audio data from regenerated message content")}if(y.audio&&y.done&&e(k=>jt(k,a,()=>({audio:y.audio,audioFormat:y.audioFormat||"mp3"}),s)),y.image&&y.done&&(d=!0,e(k=>jt(k,a,()=>({image:y.image,imageFormat:y.image_format||"png",imageRevisedPrompt:y.image_revised_prompt,imageUrl:y.image_url}),s))),(y.video||y.video_url)&&y.done&&(d=!0,e(k=>jt(k,a,()=>({video:y.video,videoFormat:y.video_format||"mp4",videoRevisedPrompt:y.video_revised_prompt,videoUrl:y.video_url}),s))),(y.document||y.document_url)&&y.done&&(d=!0,e(k=>jt(k,a,()=>({document:y.document,documentFormat:y.document_format||"pdf",documentRevisedPrompt:y.document_revised_prompt,documentUrl:y.document_url}),s))),y.generated_audio_url&&y.done&&(d=!0,e(k=>jt(k,a,()=>({generatedAudioFormat:y.generated_audio_format||"mp3",generatedAudioRevisedPrompt:y.generated_audio_revised_prompt,generatedAudioUrl:y.generated_audio_url}),s))),y.done){const k=y.threading;k!=null&&k.supports_threading&&e(A=>({conversations:A.conversations.map(L=>L.id!==a?L:{...L,messages:L.messages.map(C=>C.id===s?{...C,supportsThreading:!0,databaseMessageId:k.message_id}:C),updatedAt:new Date})})),y.assistant_message_id&&e(A=>({conversations:A.conversations.map(L=>L.id!==a?L:{...L,messages:L.messages.map(C=>C.id===s&&!C.databaseMessageId?{...C,databaseMessageId:y.assistant_message_id}:C),updatedAt:new Date})}));break}}!d&&!u.signal.aborted&&t().appendToLastMessage("No response received from the server. Please try again later.",a,s)}catch(f){if(f instanceof Error&&(f.name==="AbortError"||f.message==="Stream cancelled by user"||f.message.includes("aborted")))U(`[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 p="Sorry, there was an error regenerating the response.";f instanceof Error&&(f.message.startsWith("Server error:")?p=f.message.substring(14):(f.message.includes("Could not connect")||f.message.includes("timed out"))&&(p=f.message)),t().appendToLastMessage(p,a,s)}}zt=null,ft=null,Et=null,Jt=null,va(a,e),e(f=>{const m=f.conversations.map(g=>g.id===a?{...g,messages:g.messages.map(x=>x.id===s?{...x,isStreaming:!1}:x),updatedAt:new Date}:g),p=m.find(g=>g.id===f.currentConversationId);return{conversations:m,isLoading:p?p.messages.some(g=>g.role==="assistant"&&g.isStreaming):!1}})}const we=Gi((t,e)=>({conversations:[],currentConversationId:null,isLoading:!1,error:null,sessionId:Sr(),getSessionId:()=>e().sessionId,configureApiSettings:async(s,a,r)=>{const n=e(),o=n.conversations.find(c=>c.id===n.currentConversationId),l=(o==null?void 0:o.sessionId)||a||Sr();a&&ku(a),t({sessionId:l});try{const c=await $e();if(!r||!r.trim())throw new Error("Adapter name is required");c.configureApi(s,l,r),Cr=s,jr=!0;let d;try{const u=new c.ApiClient({apiUrl:s,sessionId:null,adapterName:r});typeof u.getAdapterInfo=="function"&&(d=await u.getAdapterInfo(),U("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:r,apiUrl:s,adapterInfo:d,adapterLoadError:null,updatedAt:new Date}:f)}));else if(r&&r.trim()){const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,f=Ht();t(m=>({conversations:[...m.conversations,{id:u,sessionId:f,title:Fs,messages:[],createdAt:new Date,updatedAt:new Date,adapterName:r,apiUrl:s,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")}r?localStorage.setItem("chat-adapter-name",r):localStorage.removeItem("chat-adapter-name"),t({isLoading:!1})},createConversation:()=>{var u;const s=e(),a=le.maxConversations,r=s.conversations.length,n=s.currentConversationId?s.conversations.find(f=>f.id===s.currentConversationId):null;if(a!==null&&r>=a){if(it()&&!wt()){const m=`You've reached the guest limit of ${a} conversation${a===1?"":"s"}. Sign in to unlock more conversations, or delete conversations to start over.`;throw t({error:m}),ot.getState().openLoginPrompt(m),new Error("Guest conversation limit reached")}const f=`Maximum of ${a} conversations reached. Please delete an existing conversation before starting a new one.`;throw t({error:f}),new Error(f)}const o=!!n&&(n.messages.length>0||(((u=n.attachedFiles)==null?void 0:u.length)||0)>0);if(n&&!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=Ht(),d={id:l,sessionId:c,title:Fs,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:Re(),adapterName:Yi(),adapterLoadError:null};return t(f=>({conversations:[d,...f.conversations],currentConversationId:l,sessionId:c,isLoading:!1})),Ke(e),l},selectConversation:async s=>{const a=e().conversations.find(r=>r.id===s);if(a){const r=a.messages.some(c=>c.role==="assistant"&&c.isStreaming);t({currentConversationId:s,sessionId:a.sessionId,isLoading:r});const n=a.apiUrl||Re(),o=a.adapterName;if(await Es()&&o){const c=await $e();if(c.configureApi(n,a.sessionId,o),!a.adapterInfo)try{const d=new c.ApiClient({apiUrl:n,sessionId:null,adapterName:o});if(typeof d.getAdapterInfo=="function"){const u=await d.getAdapterInfo();U("Adapter info loaded for conversation:",u),t(f=>({conversations:f.conversations.map(m=>m.id===s?{...m,adapterInfo:u,adapterLoadError:null,updatedAt:new Date}:m)})),Ke(e)}}catch(d){ge("Failed to load adapter info for conversation:",d)}}e().loadFeedbackForConversation(a.sessionId).catch(()=>{})}Ke(e)},deleteConversation:async s=>{var n,o;const a=e(),r=a.conversations.find(l=>l.id===s);if(U(`🗑️ Deleting conversation ${s}:`,{conversationId:s,sessionId:r==null?void 0:r.sessionId,title:r==null?void 0:r.title,messageCount:r==null?void 0:r.messages.length,fileCount:((n=r==null?void 0:r.attachedFiles)==null?void 0:n.length)||0}),a.currentConversationId===s&&Bt.stop(),r){const l=(r.attachedFiles||[]).map(d=>d.file_id),c=(r.messages||[]).flatMap(d=>(d.attachments||[]).map(u=>u.file_id));[...l,...c].forEach(ka)}if(r!=null&&r.sessionId)try{if(!await Es())ze("Failed to configure API for conversation deletion");else{const c=r.apiUrl||Re(),d=r.adapterName;d?U(`Using conversation's adapter for deletion: ${d} (conversation: ${s})`):ge(`Skipping server deletion for conversation ${s}: adapter not configured`);const u=await $e(),f=new u.ApiClient({apiUrl:c,sessionId:r.sessionId,adapterName:d}),m=((o=r.attachedFiles)==null?void 0:o.map(x=>x.file_id))||[],p=Wn(r.messages||[]),g=[...m,...p];if(U(`🔧 Calling deleteConversationWithFiles for session: ${r.sessionId}`),f.deleteConversationWithFiles){const x=await f.deleteConversationWithFiles(r.sessionId,g);U(`✅ Deleted conversation and files for session: ${r.sessionId}`,x),U(` - Deleted ${x.deleted_messages} messages`),U(` - 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 ${s}, skipping server-side deletion`);t(l=>{var u;const c=l.conversations.filter(f=>f.id!==s),d=l.currentConversationId===s?((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=Ht(),p=$s(f,m,Re());return Ke(e),{conversations:[p],currentConversationId:f,sessionId:m}}return Ke(e),{conversations:c,currentConversationId:d}})},deleteAllConversations:async()=>{const a=[...e().conversations];U(`🗑️ Deleting all conversations (${a.length} total)`),Bt.stop();const r=a.map(async u=>{var f;if(u!=null&&u.sessionId)try{if(!await Es()){ze("Failed to configure API for conversation deletion");return}const p=u.adapterName;if(!p){U(`Skipping server deletion for conversation ${u.id}: adapter not configured`);return}const g=await $e(),x=new g.ApiClient({apiUrl:ut(u.apiUrl),sessionId:u.sessionId,adapterName:p}),y=[...((f=u.attachedFiles)==null?void 0:f.map(k=>k.file_id))||[],...Wn(u.messages||[])];x.deleteConversationWithFiles?(await x.deleteConversationWithFiles(u.sessionId,y),U(`✅ 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(r)).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=Ht(),d=$s(l,c,Re());t({conversations:[d],currentConversationId:l,sessionId:c}),Ke(e)},deleteThread:async(s,a,r)=>{const n=e().conversations.find(f=>f.id===s);if(!n)throw new Error("Conversation not found");if(!n.adapterName)throw new Error("Adapter not configured for this conversation");const o=n.messages.find(f=>f.id===a);if(!(o!=null&&o.threadInfo)||o.threadInfo.thread_id!==r)throw new Error("Thread not found for this message");const l=ut(n.apiUrl||Re()),c=await $e(),d=new c.ApiClient({apiUrl:l,sessionId:n.sessionId,adapterName:n.adapterName});await new(await Ct(async()=>{const{ThreadService:f}=await import("./threadService-B9Db3n0J.js");return{ThreadService:f}},[])).ThreadService(d).deleteThread(r),t(f=>({conversations:f.conversations.map(m=>{var x;if(m.id!==s)return m;const p=m.messages.filter(y=>y.isThreadMessage?!(y.threadId===r||y.parentMessageId===a):!0).map(y=>y.id!==a?y:{...y,threadInfo:void 0,supportsThreading:!0}),g=m.currentThreadId===r||m.currentThreadSessionId===((x=o.threadInfo)==null?void 0:x.thread_session_id);return{...m,messages:p,currentThreadId:g?void 0:m.currentThreadId,currentThreadSessionId:g?void 0:m.currentThreadSessionId,updatedAt:new Date}})})),Ke(e)},sendMessage:async(s,a,r,n,o)=>{var c;let l=null;try{if(e().isLoading){ge("Another request is already in progress");return}if(!await Es())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=le.maxConversations;if(it()&&!wt()&&m!==null&&e().conversations.length>m){ot.getState().openLoginPrompt(`You've reached the guest limit of ${m} conversation${m===1?"":"s"}. Sign in to continue chatting.`),t({isLoading:!1});return}const p=a?a.map(b=>{var S;const _=(S=f==null?void 0:f.attachedFiles)==null?void 0:S.find(I=>I.file_id===b);return _||{file_id:b,filename:"",mime_type:"",file_size:0}}).filter(b=>b!==void 0):[];p.length>0&&p.forEach(b=>{e().addFileToConversation(u,b)});const g=r||null;let x,y=null;if(g){if(x=f.messages.find(b=>{var _;return((_=b.threadInfo)==null?void 0:_.thread_id)===g}),!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 k=qn(f.messages),A=le.maxMessagesPerConversation;if(A!==null&&k>=A){it()&&!wt()&&ot.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 L=le.maxTotalMessages;if(L!==null&&e().conversations.reduce((_,S)=>_+qn(S.messages),0)>=L){it()&&!wt()&&ot.getState().openLoginPrompt(`You've reached the guest limit of ${L} total messages. Sign in to continue chatting, or delete conversations to start over.`),ge(`[chatStore] Workspace reached the total message limit (${L}).`),t({isLoading:!1});return}const C={id:os("user"),content:s,role:"user",timestamp:new Date,attachments:p.length>0?p:void 0},v=os("assistant"),N={id:v,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:n};if(g&&x){C.isThreadMessage=!0,C.threadId=g,C.parentMessageId=x.id,N.isThreadMessage=!0,N.threadId=g,N.parentMessageId=x.id;const b=le.maxMessagesPerThread;if(b!==null&&f.messages.filter(S=>S.isThreadMessage?(S.threadId===g||S.parentMessageId===x.id)&&!(S.role==="assistant"&&S.isStreaming):!1).length>=b){it()&&!wt()&&ot.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 ${g} reached the message limit (${b}).`),t({isLoading:!1});return}}t(b=>{const _=b.conversations.find(I=>I.id===u),S=(_==null?void 0:_.messages.filter(I=>I.role==="assistant"&&I.isStreaming))||[];return S.length>0&&ge(`Cleaning up ${S.length} existing streaming messages`),{conversations:b.conversations.map(I=>{if(I.id!==u)return I;const M=I.messages.filter(F=>!(F.role==="assistant"&&F.isStreaming));return{...I,messages:[...M,C,N],updatedAt:new Date,title:I.messages.length===0?s.slice(0,50)+(s.length>50?"...":""):I.title}}),isLoading:!0,error:null}}),l=u;let R=!1;Bt.reset();try{const b=e().conversations.find(T=>T.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 _=ut(b.apiUrl),S=b.adapterName,I=y||b.sessionId,M=await $e();M.configureApi(_,I,S),g&&I!==b.sessionId&&U(`[chatStore] Thread mode: using thread session ${I} (original: ${b.sessionId})`);const{returnAudio:F,ttsVoice:H,language:j,audioFormat:E}=Zi(b);U("[chatStore] Audio settings:",{returnAudio:F,ttsVoice:H,language:j,audioFormat:E});const D=new AbortController;zt=D,Et=I,Jt=l,ft=null;for await(const T of M.streamChat(s,!0,a,g||void 0,void 0,void 0,j,F,H,void 0,void 0,n,o)){if(T.request_id&&!ft&&(ft=T.request_id,U(`[chatStore] >>> CAPTURED request_id for stop: ${T.request_id}`)),T.audio_chunk&&Bt.addChunk({audio:T.audio_chunk,audioFormat:T.audioFormat||"opus",chunkIndex:T.chunk_index??0}),T.text){const G=Us(T.text);G?(e().appendToLastMessage(G,l,v),R=!0):T.text.length>100&&ge("[chatStore] Filtered out potential base64 audio data from message content")}if(T.audio&&T.done&&t(G=>jt(G,l,()=>({audio:T.audio,audioFormat:T.audioFormat||"mp3"}),v)),T.image&&T.done&&(R=!0,t(G=>jt(G,l,()=>({image:T.image,imageFormat:T.image_format||"png",imageRevisedPrompt:T.image_revised_prompt,imageUrl:T.image_url}),v))),(T.video||T.video_url)&&T.done&&(R=!0,t(G=>jt(G,l,()=>({video:T.video,videoFormat:T.video_format||"mp4",videoRevisedPrompt:T.video_revised_prompt,videoUrl:T.video_url}),v))),(T.document||T.document_url)&&T.done&&(R=!0,t(G=>jt(G,l,()=>({document:T.document,documentFormat:T.document_format||"pdf",documentRevisedPrompt:T.document_revised_prompt,documentUrl:T.document_url}),v))),T.generated_audio_url&&T.done&&(R=!0,t(G=>jt(G,l,()=>({generatedAudioFormat:T.generated_audio_format||"mp3",generatedAudioRevisedPrompt:T.generated_audio_revised_prompt,generatedAudioUrl:T.generated_audio_url}),v))),T.done){U("[chatStore] Stream completed, receivedAnyText:",R);const G=T.threading;G!=null&&G.supports_threading&&t(X=>({conversations:X.conversations.map(V=>V.id!==l?V:{...V,messages:V.messages.map(Z=>Z.id===v?{...Z,supportsThreading:!0,databaseMessageId:G.message_id}:Z),updatedAt:new Date})})),T.assistant_message_id&&t(X=>({conversations:X.conversations.map(V=>V.id!==l?V:{...V,messages:V.messages.map(Z=>Z.id===v&&!Z.databaseMessageId?{...Z,databaseMessageId:T.assistant_message_id}:Z),updatedAt:new Date})}));break}}!R&&!D.signal.aborted&&e().appendToLastMessage("No response received from the server. Please try again later.",l,v)}catch(b){if(b instanceof Error&&(b.name==="AbortError"||b.message==="Stream cancelled by user"||b.message.includes("aborted")))U("[chatStore] Stream was cancelled by user"),R=!0;else{ze("Chat API error:",b);let S="Sorry, there was an error processing your request.";b instanceof Error&&(b.message.startsWith("Server error:")?S=b.message.substring(14):(b.message.includes("Could not connect")||b.message.includes("timed out"))&&(S=b.message)),e().appendToLastMessage(S,l,v)}}zt=null,ft=null,Et=null,Jt=null,va(l,t),t(b=>{const _=b.conversations.map(I=>I.id===l?{...I,messages:I.messages.map(M=>M.id===v?{...M,isStreaming:!1}:M),updatedAt:new Date}:I),S=_.find(I=>I.id===b.currentConversationId);return{conversations:_,isLoading:S?S.messages.some(I=>I.role==="assistant"&&I.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(s,a)=>{try{const r=e().conversations.find(m=>m.sessionId===a);if(!r)throw new Error("Conversation not found for session");if(!r.adapterName)throw new Error("Adapter not configured for this conversation");const n=r.messages.find(m=>m.id===s);if(!n)throw new Error("Message not found");const o=n.databaseMessageId||s,l=ut(r.apiUrl||Re()),c=await $e(),d=new c.ApiClient({apiUrl:l,sessionId:a,adapterName:r.adapterName}),f=await new(await Ct(async()=>{const{ThreadService:m}=await import("./threadService-B9Db3n0J.js");return{ThreadService:m}},[])).ThreadService(d).createThread(o,a);t(m=>({conversations:m.conversations.map(p=>p.sessionId!==a?p:{...p,messages:p.messages.map(g=>g.id===s?{...g,threadInfo:f,supportsThreading:!0}:g),currentThreadId:void 0,currentThreadSessionId:void 0})})),U(`[chatStore] Created thread ${f.thread_id} for message ${s}`)}catch(r){throw ze("Failed to create thread:",r),r}},appendToLastMessage:(s,a,r)=>{const n=Us(s);if(!n&&s){ge("[chatStore] Filtered out base64 audio data from message content");return}const o=wa(n),l=a||e().currentConversationId;if(!l)return;const c=l,d=ls.get(c);d?(d.content+=o,d.messageId=r,d.timeoutId&&clearTimeout(d.timeoutId)):ls.set(c,{content:o,timeoutId:null,messageId:r});const u=()=>{const m=ls.get(c);if(!m||!m.content)return;const p=m.content,g=m.messageId;m.content="",m.timeoutId=null,t(x=>({conversations:x.conversations.map(y=>{if(y.id!==l)return y;const k=[...y.messages],A=g?k.findIndex(C=>C.id===g):k.length-1,L=A!==-1?k[A]:void 0;return L&&L.role==="assistant"&&L.isStreaming&&(k[A]={...L,content:L.content+p}),{...y,messages:k,updatedAt:new Date}})}))},f=ls.get(c);f.timeoutId=setTimeout(u,Nu)},regenerateResponse:async(s,a)=>{let r=null;try{if(e().isLoading){ge("Another request is already in progress");return}if(!await Es())throw new Error("API not properly configured");const o=e(),l=o.conversations.find(p=>p.id===o.currentConversationId);if(!l)return;const c=l.messages.findIndex(p=>p.id===s);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(p=>p.file_id).filter(p=>typeof p=="string"&&p.length>0),m=os("assistant");if(t(p=>({conversations:p.conversations.map(g=>g.id===p.currentConversationId?{...g,messages:[...g.messages.slice(0,c),{id:m,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:a,supportsThreading:d.supportsThreading,databaseMessageId:d.databaseMessageId,threadInfo:d.threadInfo,threadId:d.threadId,parentMessageId:d.parentMessageId,isThreadMessage:d.isThreadMessage},...g.messages.slice(c+1)],updatedAt:new Date}:g),isLoading:!0,error:null})),r=o.currentConversationId,!r)throw new Error("No conversation selected");await Kn(e,t,m,r,u.content,f,a,"regenerate",d.databaseMessageId)}catch(n){ze("Regenerate error:",n),t(o=>({isLoading:!1,...o.currentConversationId===r&&{error:`Failed to regenerate response: ${n instanceof Error?n.message:"Unknown error"}`}}))}},editMessageAndRegenerate:async(s,a,r)=>{let n=null;try{if(e().isLoading){await e().stopStreaming();const x=e().currentConversationId;x&&va(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===s);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=os("assistant"),m=l.messages[c+1],p=(m==null?void 0:m.role)==="assistant",g=p?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:a,updatedAt:new Date},{id:f,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:r,supportsThreading:p?m.supportsThreading:void 0,databaseMessageId:p?m.databaseMessageId:void 0,threadInfo:p?m.threadInfo:void 0,threadId:p?m.threadId:void 0,parentMessageId:p?m.parentMessageId:void 0,isThreadMessage:p?m.isThreadMessage:void 0},...y.messages.slice(g)],updatedAt:new Date}:y),isLoading:!0,error:null})),n=o.currentConversationId,!n)throw new Error("No conversation selected");await Kn(e,t,f,n,a,u,r,"edit-regenerate",p?m.databaseMessageId:void 0),Ke(e)}catch(o){ze("Edit & regenerate error:",o),t(l=>({isLoading:!1,...l.currentConversationId===n&&{error:`Failed to regenerate response: ${o instanceof Error?o.message:"Unknown error"}`}}))}},updateConversationTitle:(s,a)=>{t(r=>({conversations:r.conversations.map(n=>n.id===s?{...n,title:a,updatedAt:new Date}:n)})),Ke(e)},clearError:()=>t({error:null}),cleanupStreamingMessages:()=>{const s=Jt;t(a=>{let r=!1;return{conversations:a.conversations.map(o=>o.id===s?(o.messages.some(c=>c.role==="assistant"&&c.isStreaming)&&(r=!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:r}})},canCreateNewConversation:()=>{var o;const s=e(),a=le.maxConversations;if(!s.currentConversationId)return a===null||s.conversations.length<a;const r=s.conversations.find(l=>l.id===s.currentConversationId);return!!r&&(r.messages.length>0||(((o=r.attachedFiles)==null?void 0:o.length)||0)>0)?a===null||s.conversations.length<a:!1},getConversationCount:()=>e().conversations.length,addFileToConversation:(s,a)=>{U("[chatStore] addFileToConversation called",{conversationId:s,fileId:a.file_id,filename:a.filename}),t(r=>({conversations:r.conversations.map(n=>n.id===s?{...n,attachedFiles:[...(n.attachedFiles||[]).filter(o=>o.file_id!==a.file_id),a],updatedAt:new Date}:n)})),Ke(e)},removeFileFromConversation:async(s,a)=>{U("[chatStore] removeFileFromConversation called",{conversationId:s,fileId:a});try{const r=e().conversations.find(n=>n.id===s);if(!r)throw new Error("Conversation not found");if(!r.adapterName)throw new Error("Adapter not configured for this conversation. Cannot delete file.");await Os.deleteFile(a,void 0,ut(r.apiUrl),r.adapterName),U(`[chatStore] Successfully deleted file ${a} from server`)}catch(r){r instanceof Error&&(r.message.includes("404")||r.message.includes("File not found"))?U(`[chatStore] File ${a} was already deleted from server`):xe(`[chatStore] Failed to delete file ${a} from server:`,r)}ka(a),t(r=>({conversations:r.conversations.map(n=>n.id===s?{...n,attachedFiles:(n.attachedFiles||[]).filter(o=>o.file_id!==a),updatedAt:new Date}:n)})),Ke(e)},loadConversationFiles:async s=>{try{const a=e().conversations.find(l=>l.id===s);if(!a)return;if(!a.adapterName){U(`Skipping file load for conversation ${s}: adapter not configured`);return}if(new Set((a.attachedFiles||[]).map(l=>l.file_id)).size===0){U(`No files to sync for conversation ${s}`);return}const n=await Os.listFiles(void 0,ut(a.apiUrl),a.adapterName),o=new Map(n.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===s);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===s?{...u,attachedFiles:d,updatedAt:new Date}:u)}}),Ke(e)}catch(a){ze(`Failed to load files for conversation ${s}:`,a)}},syncConversationFiles:async s=>{await e().loadConversationFiles(s)},syncConversationsWithBackend:async()=>{try{const s=e();if(s.conversations.length===0)return;const a=await $e(),r=le.maxMessagesPerConversation!==null&&le.maxMessagesPerConversation||void 0;let n=!1;const l=(await Promise.all(s.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 a.ApiClient({apiUrl:ut(c.apiUrl),sessionId:c.sessionId,adapterName:c.adapterName});if(typeof u.getConversationHistory!="function")return n||(n=!0,ge("[chatStore] Conversation history endpoint not supported by current API client")),null;const f=await u.getConversationHistory(c.sessionId,r),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 p=ju(m,c.messages),g=c.messages.filter(y=>y.isThreadMessage),x=Qi(g.length>0?[...p,...g]:p);return Cu(c.messages,x)?null:{id:c.id,sessionId:(f==null?void 0:f.session_id)||c.sessionId,messages:x,cleared:!1,updatedAt:((d=p[p.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:Fs,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(s){ge("Failed to synchronize conversations with backend:",s)}},stopStreaming:async()=>{var a;if(!e().isLoading){U("[chatStore] stopStreaming called but not currently loading");return}if(U("[chatStore] Stopping stream...",{hasAbortController:!!zt,requestId:ft,sessionId:Et}),zt&&zt.abort(),ft&&Et)try{const r=await $e(),n=await((a=r.stopChat)==null?void 0:a.call(r,Et,ft));U(`[chatStore] Server-side cancellation result: ${n}`)}catch(r){ge("[chatStore] Failed to cancel server-side stream:",r)}else ge(`[chatStore] Cannot call stopChat - missing IDs: requestId=${ft}, sessionId=${Et}`);const s=Jt||e().currentConversationId;t(s?r=>({conversations:r.conversations.map(n=>n.id!==s?n:{...n,messages:n.messages.map(o=>o.isStreaming?{...o,isStreaming:!1}:o),updatedAt:new Date}),isLoading:!1}):{isLoading:!1}),zt=null,ft=null,Et=null,Jt=null,U("[chatStore] Stream stopped successfully")},clearCurrentConversationAdapter:()=>{const s=e().currentConversationId;s&&(t(a=>({conversations:a.conversations.map(r=>r.id===s?{...r,adapterName:void 0,adapterInfo:void 0,adapterLoadError:null}:r)})),Ke(e))},submitFeedback:async(s,a)=>{const r=e(),n=r.conversations.find(l=>l.id===r.currentConversationId);if(!n)return;const o=n.messages.find(l=>l.id===s);if(!(o!=null&&o.databaseMessageId)){ge("[chatStore] Cannot submit feedback: no databaseMessageId on message");return}if(n.adapterName)try{const l=await $e(),u=(await new l.ApiClient({apiUrl:ut(n.apiUrl||Re()),sessionId:n.sessionId,adapterName:n.adapterName}).submitFeedback(o.databaseMessageId,n.sessionId,a)).feedback_type;t(f=>({conversations:f.conversations.map(m=>m.id!==r.currentConversationId?m:{...m,messages:m.messages.map(p=>p.id===s?{...p,feedback:u}:p),updatedAt:new Date})})),Ke(e)}catch(l){xe("[chatStore] Failed to submit feedback:",l)}},loadFeedbackForConversation:async s=>{var n;const r=e().conversations.find(o=>o.sessionId===s);if(r!=null&&r.adapterName)try{const o=await $e(),l=new o.ApiClient({apiUrl:ut(r.apiUrl||Re()),sessionId:r.sessionId,adapterName:r.adapterName}),c=new Set([s]);for(const f of r.messages)(n=f.threadInfo)!=null&&n.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!==s?m:{...m,messages:m.messages.map(p=>p.databaseMessageId&&u.has(p.databaseMessageId)?{...p,feedback:u.get(p.databaseMessageId)}:p)})}))}catch(o){xe("[chatStore] Failed to load feedback:",o)}}})),Iu=async()=>{var c;const t=localStorage.getItem("chat-state"),e=Re(),s=!!localStorage.getItem("chat-api-url");let a=Sr(),r=!1;if(t)try{const d=JSON.parse(t),u=p=>{if(p instanceof Date)return p;const g=p?new Date(p):new Date;return Number.isNaN(g.getTime())?new Date:g},m=(Array.isArray(d.conversations)?d.conversations:[]).map(p=>{const x=(Array.isArray(p.messages)?p.messages:[]).filter(L=>!(L.role==="assistant"&&L.isStreaming)).map(L=>({...L,timestamp:u(L.timestamp),isStreaming:!1})),y=Qi(x),k={id:p.id,sessionId:p.sessionId||Ht(),title:wu(p.title),messages:y,createdAt:u(p.createdAt),updatedAt:u(p.updatedAt),attachedFiles:p.attachedFiles||[],adapterName:p.adapterName,apiUrl:p.apiUrl,adapterInfo:p.adapterInfo,adapterLoadError:p.adapterLoadError||null,audioSettings:p.audioSettings,currentThreadId:void 0,currentThreadSessionId:void 0},A=k.messages.length===0&&!k.adapterName;return{...k,apiUrl:A&&!s?e:ut(p.apiUrl)}});if(r=m.length>0,d.currentConversationId&&m.length>0){const p=m.find(g=>g.id===d.currentConversationId);p!=null&&p.sessionId&&(a=p.sessionId)}if(m.length===0){const p=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,g=Ht(),x=$s(p,g,Re());we.setState({conversations:[x],currentConversationId:p,sessionId:g}),a=g}else we.setState({conversations:m,currentConversationId:d.currentConversationId||((c=m[0])==null?void 0:c.id)||null,sessionId:a}),!d.currentConversationId&&m.length>0&&(we.setState({currentConversationId:m[0].id,sessionId:m[0].sessionId||a}),a=m[0].sessionId||a);U("📋 Loaded conversations:",we.getState().conversations.map(p=>{var g;return{id:p.id,title:p.title,sessionId:p.sessionId,messageCount:((g=p.messages)==null?void 0:g.length)||0}})),setTimeout(()=>we.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=Ht(),m=$s(u,f,Re());we.setState({conversations:[m],currentConversationId:u,sessionId:f}),a=f}else{const d=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,u=Ht(),f=$s(d,u,Re());we.setState({conversations:[f],currentConversationId:d,sessionId:u}),a=u}localStorage.removeItem("chat-api-key");const n=we.getState(),o=n.currentConversationId?n.conversations.find(d=>d.id===n.currentConversationId):null,l=r&&(o!=null&&o.apiUrl)?o.apiUrl:Re();try{const d=await $e(),u=o==null?void 0:o.adapterName;if(!u)U("No adapter selected yet. Waiting for user selection before configuring API.");else if(d.configureApi(l,a,u),Cr=l,jr=!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();U("Adapter info loaded for existing adapter:",m);const p=we.getState();p.currentConversationId&&(we.setState({conversations:p.conversations.map(g=>g.id===p.currentConversationId?{...g,adapterInfo:m,adapterLoadError:null,updatedAt:new Date}:g)}),setTimeout(()=>{const g=we.getState();localStorage.setItem("chat-state",JSON.stringify({conversations:g.conversations,currentConversationId:g.currentConversationId}))},0))}}catch(f){ge("Failed to load adapter info for existing adapter:",f)}}catch(d){ze("Failed to initialize API:",d)}try{await we.getState().syncConversationsWithBackend()}catch(d){ge("Conversation history sync skipped:",d)}};typeof window<"u"&&Iu();function Lu(t){return t.includes("image")?i.jsx(Gc,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):t.includes("video")||t.includes("audio")?i.jsx(xd,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):i.jsx(Ma,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"})}function Eu(t){return t.replace(/-/g," ")}function Ji({skills:t,isLoading:e,selectedSkill:s,activeSkillName:a,query:r="",onSelect:n,onActiveSkillChange:o}){const{t:l}=Le(),c=gt.useRef(null),d=r.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"})},[a,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:r}):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 p=(s==null?void 0:s.name)===f.name,g=a===f.name||!a&&(p||!s&&m===0);return i.jsxs("button",{id:`skill-option-${f.name}`,type:"button",role:"option","aria-selected":g,"data-active":g?"true":void 0,onMouseEnter:()=>o==null?void 0:o(f),onClick:()=>n(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 ${g?"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 ${g?"text-gray-900 dark:text-white":"text-gray-500 group-hover:text-gray-700 dark:text-[#bfc2cd] dark:group-hover:text-gray-200"}`,children:Lu(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:Eu(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})]}),p&&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(ds,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]},f.name)})})})}function eo({availableModels:t,defaultModel:e,selectedModel:s,onSelect:a,wrapperClassName:r="relative hidden md:block",maxWidthClass:n="max-w-[200px]",triggerTitle:o,listboxLabel:l,staticPaddingClass:c="px-3 py-1.5",triggerPaddingClass:d="px-3 py-1.5"}){const{t:u}=Le(),f=o??u("modelPicker.selectModel"),m=l??u("modelPicker.selectModel"),[p,g]=h.useState(!1),[x,y]=h.useState(""),[k,A]=h.useState(null),L=h.useRef(null),C=h.useRef(null),v=h.useRef(null),N=h.useRef(null),R=s??e,b=x.trim()?t.filter(F=>F.name.toLowerCase().includes(x.trim().toLowerCase())):t,_=h.useCallback(()=>{if(!C.current)return;const F=C.current.getBoundingClientRect();A({bottom:window.innerHeight-F.top+8,right:window.innerWidth-F.right})},[]),S=h.useCallback(()=>{g(!1),y("")},[]),I=()=>{if(p){S();return}_(),g(!0)};if(h.useEffect(()=>{if(!p)return;const F=setTimeout(()=>{var D;return(D=v.current)==null?void 0:D.focus()},10),H=D=>{var V,Z;const T=D.target,G=((V=L.current)==null?void 0:V.contains(T))??!1,X=((Z=N.current)==null?void 0:Z.contains(T))??!1;!G&&!X&&S()},j=D=>{var T;D.key==="Escape"&&(D.preventDefault(),S(),(T=C.current)==null||T.focus())},E=new ResizeObserver(_);return C.current&&E.observe(C.current),window.addEventListener("resize",_,{passive:!0}),document.addEventListener("scroll",_,{capture:!0,passive:!0}),document.addEventListener("pointerdown",H),document.addEventListener("keydown",j),()=>{clearTimeout(F),E.disconnect(),window.removeEventListener("resize",_),document.removeEventListener("scroll",_,{capture:!0}),document.removeEventListener("pointerdown",H),document.removeEventListener("keydown",j)}},[S,p,_]),!e&&t.length===0)return null;const M=p&&k&&typeof document<"u"?Ir.createPortal(i.jsxs("div",{ref:N,style:{position:"fixed",bottom:k.bottom,right:k.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(Ta,{className:"h-3.5 w-3.5 flex-shrink-0 text-gray-400 dark:text-[#6b6f7a]","aria-hidden":"true"}),i.jsx("input",{ref:v,type:"text",value:x,onChange:F=>y(F.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(F=>{const H=R===F.name;return i.jsxs("button",{role:"option","aria-selected":H,type:"button",onClick:()=>{var j;a(F.name),S(),(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:F.name})]},F.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:L,className:r,children:t.length>1?i.jsxs(i.Fragment,{children:[i.jsxs("button",{ref:C,type:"button",onClick:I,className:`inline-flex min-w-[100px] ${n} 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":p,title:f,children:[i.jsx("span",{className:"truncate flex-1",children:R}),i.jsx(fs,{className:`h-3.5 w-3.5 flex-shrink-0 text-gray-400 transition-transform duration-150 dark:text-[#6b6f7a] ${p?"rotate-180":""}`,"aria-hidden":"true"})]}),M]}):i.jsx("div",{className:`inline-flex min-w-[100px] ${n} 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:R??void 0,children:i.jsx("span",{className:"truncate",children:R})})})}function Ar({filename:t,fileId:e,status:s,statusText:a,errorMessage:r,onRemove:n,removeTitle:o,className:l=""}){const c=s==="uploading"||s==="processing",d=s==="error",u=gu(t),f=e?xu(e):void 0,m=u.Icon,p=d?r||a:a||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(Fi,{className:"h-[18px] w-[18px] animate-spin"}):d?i.jsx(ga,{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}),p&&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:p})]}),n&&i.jsx("button",{type:"button",onClick:n,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=[],Tu=(t="png")=>{const e=t.toLowerCase().replace(/^image\//,"");return e==="jpg"?"image/jpeg":`image/${e||"png"}`},Mu=(t,e)=>{const s=atob(t),a=new Uint8Array(s.length);for(let r=0;r<s.length;r+=1)a[r]=s.charCodeAt(r);return new Blob([a],{type:e})},Fu=async t=>{const e=URL.createObjectURL(t);try{const s=new Image;s.decoding="async";const a=new Promise((o,l)=>{s.onload=()=>o(s),s.onerror=()=>l(new Error("Failed to load generated image for clipboard copy"))});s.src=e,await a;const r=document.createElement("canvas");r.width=s.naturalWidth,r.height=s.naturalHeight;const n=r.getContext("2d");if(!n)throw new Error("Could not create canvas context for image clipboard copy");return n.drawImage(s,0,0),await new Promise((o,l)=>{r.toBlob(c=>{c?o(c):l(new Error("Could not encode generated image for clipboard copy"))},"image/png")})}finally{URL.revokeObjectURL(e)}},$u=async(t,e)=>{const s=Tu(t.imageFormat);if(t.image)return Mu(t.image,s);if(!t.imageUrl)return null;const a=await fetch(t.imageUrl,{headers:e?{"X-Adapter-Name":e}:{}});if(!a.ok)throw new Error(`Could not fetch generated image for clipboard copy: ${a.status}`);const r=await a.blob();return r.type?r:new Blob([r],{type:s})},Ru=t=>t.imageUrl?new URL(t.imageUrl,window.location.origin).toString():t.imageRevisedPrompt||t.content;function Gn({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(s=>i.jsx("span",{className:`inline-block ${e} animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]`,style:{animationDelay:`${s}ms`}},s))})}function Pu({reply:t}){const{t:e}=Le(),[s,a]=h.useState(!1),[r,n]=h.useState(!1),o=h.useRef(null),l=we(d=>d.submitFeedback);h.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]);const c=async d=>{if(!t.databaseMessageId||s)return;const u=t.feedback!==d;a(!0);try{await l(t.id,d),u?(n(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{n(!1),o.current=null},2e3)):n(!1)}catch(f){xe("Failed to submit thread reply feedback:",f)}finally{a(!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:s,className:`rounded-md p-1.5 transition-colors ${s?"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(Ui,{className:"h-4 w-4"})}),i.jsx("button",{onClick:()=>c("down"),disabled:s,className:`rounded-md p-1.5 transition-colors ${s?"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(Di,{className:"h-4 w-4"})}),r&&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(ds,{className:"h-3.5 w-3.5"}),e("message.feedback.thanks")]})]})}function Du({message:t,onRegenerate:e,onEdit:s,onStartThread:a,onClearThread:r,onSendThreadMessage:n,threadMessages:o,sessionId:l,isThreadSendDisabled:c,availableModels:d=[],defaultModel:u=null,selectedModel:f=null}){var ws,ks,as;const{t:m}=Le(),[p,g]=h.useState(!1),[x,y]=h.useState(t.content||""),[k,A]=h.useState(!1),L=h.useRef(null),[C,v]=h.useState(!1),[N,R]=h.useState(!1),[b,_]=h.useState(!1),[S,I]=h.useState(""),[M,F]=h.useState(!1),[H,j]=h.useState(!1),[E,D]=h.useState(!1),[T,G]=h.useState(0),[X,V]=h.useState(!1),[Z,fe]=h.useState(!1),[z,se]=h.useState(()=>f??u),Y=h.useRef(f),J=h.useRef(((ws=t.threadInfo)==null?void 0:ws.thread_id)||null),ee=h.useRef(null),ue=h.useRef(null),ve=h.useRef(null),B=h.useRef(!1),ae=h.useRef(0),ie=h.useRef(""),je=h.useRef(!1),re=h.useRef(!0),W=h.useRef(!1),pe=h.useRef(null),_e=h.useRef(null),be=t.role==="assistant",Me=o??_u,Ce=Me.filter($=>!($.role==="assistant"&&$.isStreaming)).length,P=Me.some($=>$.isStreaming),K=hs(),Fe=it()&&!K,oe=we($=>$.conversations.find(ye=>ye.id===$.currentConversationId)),Ae=!!((t.image||t.imageUrl)&&be&&!t.isStreaming),Tt=!!((t.video||t.videoUrl)&&be&&!t.isStreaming),Be=m(Ae?"message.copyImageLabel":"message.copyLabel"),et=dc(),ps=le.maxMessageLength,xt=le.maxMessagesPerThread,Mt=xt!==null&&Ce>=xt,Vt=Mt?Fe?m("message.thread.limitReachedGuest",{count:xt}):m("message.thread.limitReachedUser",{count:xt}):null,{theme:tt,isDark:Ft}=ts(),qt=m("message.thread.placeholder"),Se=`thread-input-${t.id}`,{skills:st,isLoading:bt,selectedSkill:ce,selectSkill:ke,clearSkill:Ee}=Ki({adapterName:oe==null?void 0:oe.adapterName,enabled:et&&!!t.threadInfo,selectionScopeKey:((ks=t.threadInfo)==null?void 0:ks.thread_id)||t.id}),te=S.startsWith("/")?S.slice(1):"",rt=te.toLowerCase().replace(/-/g," "),He=rt?st.filter($=>$.name.replace(/-/g," ").toLowerCase().includes(rt)||$.description.toLowerCase().includes(rt)):st,ms=He.length>0?Math.min(T,He.length-1):0,lt=He[ms]??null,gs=(lt==null?void 0:lt.name.replace(/-/g," "))??"",Bs=E&&lt&&S.startsWith("/")&&gs.toLowerCase().startsWith(te.toLowerCase())&&gs.length>te.length?gs.slice(te.length):null,ss=tt.mode==="dark"?"dark":tt.mode==="light"?"light":"",at=Ft?"dark":"light",Hs=h.useMemo(()=>["message-markdown w-full min-w-0","prose prose-slate dark:prose-invert max-w-none",ss].filter(Boolean).join(" "),[ss]),Vs=h.useMemo(()=>["message-markdown w-full min-w-0","prose dark:prose-invert max-w-none",ss].filter(Boolean).join(" "),[ss]),rs=be?Hs:Vs,Wt=`${Hs} text-sm leading-6`,xs=`${Vs} text-sm leading-6`;h.useEffect(()=>{var $,ye;!J.current&&(($=t.threadInfo)!=null&&$.thread_id)&&F(!0),J.current=((ye=t.threadInfo)==null?void 0:ye.thread_id)||null},[(as=t.threadInfo)==null?void 0:as.thread_id]),h.useEffect(()=>{t.threadInfo||setTimeout(()=>{I(""),F(!1),j(!1),D(!1),Ee()},0)},[t.threadInfo,Ee]),h.useEffect(()=>{Ce>0&&setTimeout(()=>{F(!0)},0)},[Ce]),h.useEffect(()=>()=>{pe.current&&clearTimeout(pe.current),_e.current&&clearTimeout(_e.current)},[]),h.useEffect(()=>{if(!p||!L.current)return;const $=L.current;$.focus(),$.setSelectionRange($.value.length,$.value.length)},[p]),h.useEffect(()=>{if(!p||!L.current)return;const $=L.current;$.style.height="auto",$.style.height=`${$.scrollHeight}px`},[p,x]);const $t=h.useCallback(()=>{const $=x.trim();if(!$||$===t.content){g(!1);return}s==null||s(t.id,$),g(!1)},[x,t.content,t.id,s]),ht=h.useCallback(()=>{requestAnimationFrame(()=>{ve.current&&(ve.current.scrollTop=ve.current.scrollHeight)})},[]);h.useEffect(()=>{if(!M)return;const $=Me.length,ye=$>ae.current,q=Me[Me.length-1],Ne=(q==null?void 0:q.content)||"",Pe=Ne!==ie.current,Xt=(q==null?void 0:q.isStreaming)??!1,ct=je.current&&!Xt;ye||Xt&&Pe||ct?(ht(),re.current=!0):re.current&&Pe&&ht(),ae.current=$,ie.current=Ne,je.current=Xt},[M,Me,ht]),h.useEffect(()=>{M&&(ht(),re.current=!0)},[M,ht]);const Rt=be?"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)]",bs=h.useCallback(()=>{v(!0),pe.current&&clearTimeout(pe.current),pe.current=setTimeout(()=>{v(!1),pe.current=null},2e3)},[]),qs=async()=>{try{if(Ae){if("ClipboardItem"in window&&navigator.clipboard.write)try{const ye=(oe==null?void 0:oe.adapterName)||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),q=await $u(t,ye);if(q){const Ne=q.type==="image/png"?q:await Fu(q);await navigator.clipboard.write([new ClipboardItem({[Ne.type||"image/png"]:Ne})]),bs();return}}catch(ye){xe("Failed to copy generated image, falling back to text:",ye)}const $=Ru(t);if($){await navigator.clipboard.writeText($),bs();return}return}await navigator.clipboard.writeText(t.content),bs()}catch($){xe(Ae?"Failed to copy generated image:":"Failed to copy text:",$)}},Kt=we($=>$.submitFeedback),Ws=async $=>{if(!t.databaseMessageId||N)return;const ye=t.feedback!==$;R(!0);try{await Kt(t.id,$),ye?(_(!0),_e.current&&clearTimeout(_e.current),_e.current=setTimeout(()=>{_(!1),_e.current=null},2e3)):_(!1)}catch(q){xe("Failed to submit feedback:",q)}finally{R(!1)}},qe=async()=>{if(!n||!t.threadInfo||Mt)return;const $=S.trim();if(!$)return;const ye=S,q=ce,Ne=ce==null?void 0:ce.name;I(""),j(!0),D(!1),Ne&&Ee();try{await n(t.threadInfo.thread_id,t.id,$,Ne,z??u??void 0),setTimeout(()=>{ee.current&&ee.current.focus()},100)}catch(Pe){xe("Failed to send thread message:",Pe),I(ye),q&&ke(q),setTimeout(()=>{ee.current&&ee.current.focus()},100)}finally{j(!1)}},ys=h.useCallback($=>{var ye;ke($),D(!1),I(""),G(0),(ye=ee.current)==null||ye.focus()},[ke]),Gt=h.useCallback(()=>{var $;D(!1),I(""),G(0),($=ee.current)==null||$.focus()},[]),Rr=h.useCallback(()=>{var $;I("/"),D(!0),G(0),($=ee.current)==null||$.focus()},[]),Pt=$=>{if(E){if($.key==="ArrowDown"){$.preventDefault(),G(ye=>He.length===0?0:(ye+1)%He.length);return}if($.key==="ArrowUp"){$.preventDefault(),G(ye=>He.length===0?0:(ye-1+He.length)%He.length);return}if($.key==="Home"){$.preventDefault(),G(0);return}if($.key==="End"){$.preventDefault(),G(Math.max(He.length-1,0));return}if(($.key==="Enter"&&!$.shiftKey||$.key==="Tab")&&lt){$.preventDefault(),ys(lt);return}if($.key==="Escape"){$.preventDefault(),Gt();return}}$.key==="Enter"&&!$.shiftKey&&($.preventDefault(),qe())},Ye=!t.threadInfo||!n||c||P||H||Mt,Pr=!!t.threadInfo&&!!r&&Ce>0&&!P&&!H&&!c,Dr=async()=>{if(!(!t.threadInfo||!r)){fe(!0);try{await r(t.id,t.threadInfo.thread_id),V(!1),F(!1),I("")}catch($){xe("Failed to clear thread:",$)}finally{fe(!1)}}};h.useEffect(()=>{Y.current=f},[f]),h.useEffect(()=>{se(Y.current??u)},[u]),h.useEffect(()=>{if(!M||Ye){W.current=H;return}const $=ee.current;if(!$){W.current=H;return}if(!(B.current||W.current)){W.current=H;return}const q=requestAnimationFrame(()=>{var Pe;B.current&&((Pe=ue.current)==null||Pe.scrollIntoView({behavior:"auto",block:"nearest",inline:"nearest"})),$.focus();const Ne=$.value.length;$.setSelectionRange(Ne,Ne),B.current=!1,W.current=H});return()=>{cancelAnimationFrame(q),W.current=H}},[M,Ye,H]),h.useEffect(()=>{if(ee.current){const ye=ee.current;ye.style.height="auto";const q=ye.scrollHeight;ye.style.height=`${Math.min(q,120)}px`,ye.style.overflowY=q>120?"auto":"hidden"}},[S]);const Ur=h.useMemo(()=>{if(t.isStreaming&&(!t.content||t.content==="…"))return i.jsx("div",{className:rs,children:i.jsx(Gn,{})});const $=t.isStreaming&&be?" streaming-cursor":"";return i.jsx("div",{className:$||void 0,children:i.jsx(_t,{content:wa(Us(t.content||"")),className:rs,syntaxTheme:at})})},[rs,t.content,t.isStreaming,be,at]),kt=h.useMemo(()=>{const $=q=>q instanceof Date?q.getTime():new Date(q).getTime();return[...Me].sort((q,Ne)=>$(q.timestamp)-$(Ne.timestamp)).map(q=>{const Ne=q.role==="assistant",Pe=Ne?Wt:xs,Xt=q.isStreaming&&Ne?" streaming-cursor":"",ct=q.isStreaming&&(!q.content||q.content==="…")?i.jsx("div",{className:Pe,children:i.jsx(Gn,{size:"sm"})}):i.jsx("div",{className:Xt||void 0,children:i.jsx(_t,{content:wa(Us(q.content||"")),className:Pe,syntaxTheme:at})});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:[ct,q.audio&&Ne&&!q.isStreaming&&i.jsx(nr,{audio:q.audio,audioFormat:q.audioFormat,autoPlay:!1}),(q.image||q.imageUrl)&&Ne&&!q.isStreaming&&i.jsx($n,{image:q.image,imageUrl:q.imageUrl,imageFormat:q.imageFormat,revisedPrompt:q.imageRevisedPrompt}),(q.video||q.videoUrl)&&Ne&&!q.isStreaming&&i.jsx(Rn,{video:q.video,videoUrl:q.videoUrl,videoFormat:q.videoFormat,revisedPrompt:q.videoRevisedPrompt,adapterName:oe==null?void 0:oe.adapterName}),(q.document||q.documentUrl)&&Ne&&!q.isStreaming&&i.jsx(On,{document:q.document,documentUrl:q.documentUrl,documentFormat:q.documentFormat,revisedPrompt:q.documentRevisedPrompt,adapterName:oe==null?void 0:oe.adapterName}),q.generatedAudioUrl&&Ne&&!q.isStreaming&&i.jsx(nr,{audioUrl:q.generatedAudioUrl,audioFormat:q.generatedAudioFormat,downloadFilename:`generated-audio.${q.generatedAudioFormat||"mp3"}`,autoPlay:!1})]}),Ne&&!q.isStreaming&&q.model&&i.jsx("div",{className:"px-1 pt-0.5 text-[11px] text-gray-400 dark:text-[#9a9ab0]",children:m("message.generatedBy",{model:q.model})}),Ne&&!q.isStreaming&&vn()&&i.jsx(Pu,{reply:q})]})},q.id)})},[oe==null?void 0:oe.adapterName,at,m,Wt,Me,xs]);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:be?void 0:"flex flex-col items-end",children:[i.jsxs("div",{className:Rt,children:[p?i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsx("textarea",{ref:L,className:"w-full resize-none overflow-hidden bg-transparent outline-none text-[#111827] dark:text-[#f5f5f5] leading-relaxed",value:x,onChange:$=>y($.target.value),onCompositionStart:()=>A(!0),onCompositionEnd:()=>A(!1),onKeyDown:$=>{$.key==="Enter"&&!$.shiftKey&&!k&&($.preventDefault(),$.stopPropagation(),$t()),$.key==="Escape"&&($.stopPropagation(),g(!1),y(t.content||""))},maxLength:le.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:()=>{g(!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:$t,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(ma,{className:"w-3.5 h-3.5"}),m("common.send")]})]})]})]}):Ur,t.attachments&&t.attachments.length>0&&i.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:t.attachments.map($=>i.jsx(Ar,{filename:$.filename,fileId:$.file_id,status:"completed",statusText:`${($.file_size/1024).toFixed(1)} KB`},$.file_id))}),t.audio&&be&&!t.isStreaming&&i.jsx(nr,{audio:t.audio,audioFormat:t.audioFormat,autoPlay:!1}),(t.image||t.imageUrl)&&be&&!t.isStreaming&&i.jsx($n,{image:t.image,imageUrl:t.imageUrl,imageFormat:t.imageFormat,revisedPrompt:t.imageRevisedPrompt}),(t.video||t.videoUrl)&&be&&!t.isStreaming&&i.jsx(Rn,{video:t.video,videoUrl:t.videoUrl,videoFormat:t.videoFormat,revisedPrompt:t.videoRevisedPrompt,adapterName:oe==null?void 0:oe.adapterName}),(t.document||t.documentUrl)&&be&&!t.isStreaming&&i.jsx(On,{document:t.document,documentUrl:t.documentUrl,documentFormat:t.documentFormat,revisedPrompt:t.documentRevisedPrompt,adapterName:oe==null?void 0:oe.adapterName}),t.generatedAudioUrl&&be&&!t.isStreaming&&i.jsx(nr,{audioUrl:t.generatedAudioUrl,audioFormat:t.generatedAudioFormat,downloadFilename:`generated-audio.${t.generatedAudioFormat||"mp3"}`,autoPlay:!1})]}),!be&&!p&&i.jsxs("div",{className:"flex items-center gap-0.5 py-1 text-gray-400 dark:text-[#8e8ea0]",children:[i.jsx("button",{onClick:qs,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:Be,"aria-label":Be,children:C?i.jsx(ds,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):i.jsx(Cn,{className:"h-4 w-4"})}),s&&i.jsx("button",{onClick:()=>{y(t.content||""),g(!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(Ri,{className:"h-4 w-4"})})]})]}),be&&!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})}),be&&!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:[!Tt&&i.jsx("button",{onClick:qs,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:Be,"aria-label":Be,children:C?i.jsx(ds,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):i.jsx(Cn,{className:"h-4 w-4"})}),vn()&&i.jsxs("div",{className:"relative flex items-center gap-0.5",children:[i.jsx("button",{onClick:()=>Ws("up"),disabled:N,className:`rounded-md p-1.5 transition-colors ${N?"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(Ui,{className:"h-4 w-4"})}),i.jsx("button",{onClick:()=>Ws("down"),disabled:N,className:`rounded-md p-1.5 transition-colors ${N?"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(Di,{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(ds,{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(ud,{className:"h-4 w-4"})}),et&&t.supportsThreading&&!t.threadInfo&&a&&l&&i.jsxs("button",{type:"button",onClick:()=>{B.current=!0,F(!0),a(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(An,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{children:m("message.thread.continueLabel")})]}),et&&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:()=>F($=>!$),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(An,{className:"h-4 w-4"}),i.jsx("span",{className:"truncate",children:m("message.thread.replyCount",{count:Ce})}),M?i.jsx(wr,{className:"h-3 w-3"}):i.jsx(fs,{className:"h-3 w-3"})]}),Pr&&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")})]})]}),et&&t.threadInfo&&M&&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:ve,className:"thread-replies-scroll mt-2 space-y-2 pb-3",onScroll:()=>{if(!ve.current)return;const{scrollTop:$,scrollHeight:ye,clientHeight:q}=ve.current;re.current=ye-$-q<100},children:Ce>0?kt:null}),Vt&&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:[Vt,Fe&&i.jsx("div",{className:"mt-2",children:i.jsx("button",{type:"button",onClick:()=>ot.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:ue,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:[ce&&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(Ma,{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:ce.name.replace(/-/g," ")}),i.jsx("button",{type:"button",onClick:()=>Ee(),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"})})]}),!ce&&st.length>0&&S.length===0&&!Ye&&i.jsxs("button",{type:"button",onClick:Rr,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:Se,className:"sr-only",children:m("message.thread.placeholder")}),Bs&&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:S}),i.jsx("span",{children:Bs})]}),i.jsx("textarea",{id:Se,ref:ee,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:qt,"aria-label":m("message.thread.placeholder"),value:S,onChange:$=>{const ye=$.target.value;I(ye),ye.startsWith("/")&&G(0),D(ye.startsWith("/"))},onKeyDown:Pt,disabled:Ye,rows:1,maxLength:ps,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(eo,{availableModels:d,defaultModel:u,selectedModel:z,onSelect:se,maxWidthClass:"max-w-[120px]",triggerPaddingClass:"px-2 py-1",staticPaddingClass:"px-2 py-1",triggerTitle:m("message.thread.selectModelTitle"),listboxLabel:m("message.thread.selectModelTitle")}),S.trim().length>0&&i.jsx("button",{type:"button",onClick:qe,disabled:Ye||S.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(ma,{className:"h-5 w-5 sm:h-4 sm:w-4"})})]})]}),E&&i.jsx("div",{className:"w-full pt-1",children:i.jsx(Ji,{skills:st,isLoading:bt,selectedSkill:ce,activeSkillName:lt==null?void 0:lt.name,query:te,onActiveSkillChange:$=>{const ye=He.findIndex(q=>q.name===$.name);ye>=0&&G(ye)},onSelect:ys,onClose:Gt})})]}),Ce>0&&i.jsx("div",{className:"mt-2 flex justify-end",children:i.jsxs("button",{type:"button",onClick:()=>F(!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(wr,{className:"h-3 w-3"}),i.jsx("span",{children:m("message.thread.hideRepliesLabel")})]})})]})]}),i.jsx(vr,{isOpen:X,onClose:()=>{Z||V(!1)},onConfirm:Dr,title:m("message.confirmation.clearRepliesTitle"),message:m("message.confirmation.clearRepliesMessage"),confirmText:m("common.clear"),cancelText:m("common.cancel"),type:"danger",isLoading:Z})]})}let is=null;function Uu(){if(typeof window>"u")return null;const t=window.AudioContext??window.webkitAudioContext;return t?((!is||is.state==="closed")&&(is=new t),is.state==="suspended"&&is.resume(),is):(U("[SoundEffects] AudioContext not supported in this browser"),null)}function Ou(t){const e=Uu();if(!e)return;const s=e.currentTime;for(const a of t){const r=e.createOscillator(),n=e.createGain();r.connect(n),n.connect(e.destination),r.frequency.value=a.frequency,r.type=a.type;const o=s+a.startTime,l=o+a.duration;n.gain.setValueAtTime(.001,o),n.gain.linearRampToValueAtTime(a.gain,o+.008),n.gain.exponentialRampToValueAtTime(.001,l),r.start(o),r.stop(l+.01)}}const zu={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 _s(t,e){if(!e)return;const s=zu[t];if(!s){U(`[SoundEffects] Unknown sound effect type: ${t}`);return}try{Ou(s),U(`[SoundEffects] Playing ${t} sound effect`)}catch(a){U(`[SoundEffects] Failed to play ${t} sound effect:`,a)}}function Bu({messages:t,onRegenerate:e,onEditMessage:s,onStartThread:a,onClearThread:r,onSendThreadMessage:n,sessionId:o,isLoading:l,contentMaxWidthClass:c="max-w-[64rem]",availableModels:d,defaultModel:u,selectedModel:f}){const m=h.useRef(null),p=h.useRef(null),g=h.useRef(t.length),x=h.useRef(""),y=h.useRef(l),k=h.useRef(!0),{settings:A}=Lr(),{t:L}=Le(),{topLevelMessages:C,threadLookup:v}=h.useMemo(()=>{const b=new Map,_=[];return t.forEach(S=>{if(S.isThreadMessage&&S.parentMessageId){const I=b.get(S.parentMessageId)||[];b.set(S.parentMessageId,[...I,S]);return}_.push(S)}),{topLevelMessages:_,threadLookup:b}},[t]),N=()=>{if(!p.current)return;const{scrollTop:b,scrollHeight:_,clientHeight:S}=p.current,M=_-b-S<200;k.current=M},R=h.useCallback(()=>{requestAnimationFrame(()=>{p.current&&(p.current.scrollTop=p.current.scrollHeight)})},[]);return h.useEffect(()=>{const b=t.length,_=g.current,S=b>_,I=t[t.length-1],M=(I==null?void 0:I.content)||"",F=M!==x.current,H=(I==null?void 0:I.isStreaming)??!1;S||H&&F?(R(),k.current=!0):k.current&&F&&R(),g.current=b,x.current=M},[t,R]),h.useEffect(()=>{l&&(R(),k.current=!0)},[l,R]),h.useEffect(()=>{if(y.current&&!l){const b=t[t.length-1];(b==null?void 0:b.role)==="assistant"&&b.content&&_s("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:L("messageList.emptyStateHeading")}),i.jsx("p",{className:"mt-1 text-lg",children:L("messageList.emptyStateSubheading")})]})}):i.jsx("div",{ref:p,className:"message-list flex-1 overflow-y-auto pb-8 pt-4 sm:pt-6",onScroll:N,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(Du,{message:b,onRegenerate:e,onEdit:s,onStartThread:a,onClearThread:r,onSendThreadMessage:n,threadMessages:v.get(b.id),sessionId:o,isThreadSendDisabled:l,availableModels:d,defaultModel:u,selectedModel:f})},b.id)),i.jsx("div",{ref:m,className:"h-8"})]})})})}const Hu=4e3;function Vu(t,e,s={}){var _;const{t:a}=Le(),[r,n]=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),p=typeof navigator<"u"?navigator.language:"en-US",g=Number.isFinite(s.silenceTimeoutMs)?Math.max(Math.floor(s.silenceTimeoutMs),1e3):Hu,x=((_=s.language)==null?void 0:_.trim())||p||"en-US",y=h.useCallback(S=>S.replace(/\s+/g," ").trim(),[]),k=h.useCallback(S=>{const I=y(S);I&&I!==u.current&&(u.current=I,t(I))},[y,t]),A=h.useCallback(()=>{if(!d.current)return;const S=d.current;d.current="",k(S)},[k]),L=typeof window<"u"&&("webkitSpeechRecognition"in window||"SpeechRecognition"in window),C=h.useCallback(()=>{!e||f.current||(f.current=!0,e())},[e]),v=h.useCallback(()=>{m.current!==null&&(clearTimeout(m.current),m.current=null)},[]),N=h.useCallback(()=>{v(),m.current=setTimeout(()=>{U("Speech recognition silence threshold reached, stopping recording"),c.current?c.current.stop():C()},g)},[v,C,g]),R=h.useCallback(()=>{if(!L){l(a("voice.browserNotSupported"));return}if(!c.current)try{f.current=!1;const S=window.SpeechRecognition||window.webkitSpeechRecognition,I=new S;I.continuous=!0,I.interimResults=!0,I.lang=x,I.maxAlternatives=1,I.onstart=()=>{n(!0),l(null),d.current="",u.current="",U("Speech recognition started"),N()},I.onresult=M=>{let F="",H="";for(let j=M.resultIndex;j<M.results.length;j++){const E=M.results[j][0].transcript;M.results[j].isFinal?F+=E:H+=E}H&&(d.current=y(H)),F&&(d.current="",k(F)),N()},I.onend=()=>{v(),A(),n(!1),c.current=null,U("Speech recognition ended"),C()},I.onerror=M=>{switch(v(),xe("Speech recognition error:",M.error),n(!1),c.current=null,d.current="",C(),M.error){case"no-speech":l(a("voice.error.noSpeech"));break;case"audio-capture":l(a("voice.error.audioCapture"));break;case"not-allowed":l(a("voice.error.notAllowed"));break;case"network":l(a("voice.error.network"));break;default:l(a("voice.error.generic",{error:M.error}))}},I.start(),c.current=I}catch(S){xe("Failed to start speech recognition:",S),l(a("voice.error.startFailed")),n(!1)}},[L,A,C,N,v,x,y,k,a]),b=h.useCallback(()=>{if(U("Stopping speech recognition..."),c.current){const S=c.current;S.onstart=null,S.onerror=null;try{S.stop()}catch(I){U("Recognition already stopped or error stopping:",I),v(),A(),S.onend=null,S.onresult=null,c.current=null,n(!1),C()}}v(),n(!1),l(null),U("Speech recognition stopped, isListening set to false")},[v,A,C]);return{isListening:r,isSupported:L,startListening:R,stopListening:b,error:o}}const qu=300,Xn=3,dr=5,Wu=6e4;function Yn(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 Ku(t,e={}){const{enabled:s=Si(),adapterName:a,sessionId:r,adapterSupportsAutocomplete:n,skill:o,inputRef:l}=e,[c,d]=h.useState([]),[u,f]=h.useState(!1),[m,p]=h.useState(-1),g=h.useRef(null),x=h.useRef(null),y=h.useRef(null),k=h.useRef(null),A=h.useRef(null),L=h.useRef(0),C=h.useRef([]),v=h.useRef([]),N=h.useRef(new Map);h.useEffect(()=>{C.current=c},[c]);const R=h.useCallback(j=>{const E=N.current.get(j);return E?E<=Date.now()?(N.current.delete(j),!1):!0:!1},[]),b=h.useCallback((j,E=!0)=>{const D=j.toLowerCase().trim(),T=v.current.length>0?v.current:C.current;if(!D)return T.slice(0,dr);const G=T.filter(X=>X.text.toLowerCase().includes(D));return G.length>0?G.slice(0,dr):E?T.slice(0,dr):[]},[]),_=h.useCallback(async j=>{if(!s||j.length<Xn){d([]),v.current=[],x.current&&clearTimeout(x.current),y.current&&clearTimeout(y.current),f(!1);return}if(!a){d([]),v.current=[],x.current&&clearTimeout(x.current),f(!1);return}if(n===!1||R(a)){d([]),v.current=[],x.current&&clearTimeout(x.current),f(!1);return}k.current&&k.current.abort(),k.current=new AbortController;const E=L.current+1;L.current=E,x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{E===L.current&&f(!0)},150);try{const D={"X-Adapter-Name":a};r&&(D["X-Session-ID"]=r);const T=new URLSearchParams;T.set("q",j),T.set("limit",String(dr)),o&&T.set("skill",o);const G=`/api/v1/autocomplete?${T.toString()}`,X=await fetch(G,{method:"GET",headers:D,signal:k.current.signal});if(!X.ok){ge("[useAutocomplete] Request failed:",X.status),[404,405,501].includes(X.status)?(N.current.set(a,Date.now()+Wu),d([]),v.current=[]):d(b(j));return}const V=await X.json(),Z=Array.isArray(V==null?void 0:V.suggestions)?V.suggestions.map(fe=>Yn(typeof fe=="string"?fe:fe==null?void 0:fe.text)).filter(fe=>fe!==null):[];if(E!==L.current)return;Z.length===0?d(b(j,!1)):(d(Z),v.current=Z),p(-1),U("[useAutocomplete] Received",Z.length,"suggestions")}catch(D){if(D instanceof Error&&D.name==="AbortError")return;ge("[useAutocomplete] Error:",D instanceof Error?D.message:String(D)),E===L.current&&d(b(j))}finally{E===L.current&&(x.current&&(clearTimeout(x.current),x.current=null),f(!1))}},[s,a,r,n,o,b,R]);h.useEffect(()=>{g.current&&clearTimeout(g.current);const j=()=>{k.current&&k.current.abort(),x.current&&clearTimeout(x.current),f(!1)},E=()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{y.current=null,d([]),j()},0)};if(!s||t.length<Xn||n===!1||a&&R(a)){E();return}if(A.current){if(t===A.current){E();return}A.current=null}return g.current=setTimeout(()=>{_(t)},qu),()=>{g.current&&clearTimeout(g.current),y.current&&(clearTimeout(y.current),y.current=null)}},[t,_,s,a,n,R]),h.useEffect(()=>()=>{k.current&&k.current.abort(),x.current&&clearTimeout(x.current)},[]);const S=h.useCallback(()=>{p(j=>{const E=C.current.length;return E===0?-1:j<E-1?j+1:0})},[]),I=h.useCallback(()=>{p(j=>{const E=C.current.length;return E===0?-1:j>0?j-1:E-1})},[]),M=h.useCallback(()=>{d([]),v.current=[],p(-1),k.current&&k.current.abort(),x.current&&clearTimeout(x.current),f(!1)},[]),F=h.useCallback(j=>{if(!(l!=null&&l.current))return;const E=()=>{const D=l.current;if(!D)return;const T=typeof j=="string"?j.length:D.value.length;D.focus({preventScroll:!0}),typeof D.setSelectionRange=="function"&&D.setSelectionRange(T,T)};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(E):setTimeout(E,0)},[l]),H=h.useCallback(j=>{A.current=j},[]);return{suggestions:c,isLoading:u,selectedIndex:m,setSelectedIndex:p,selectNext:S,selectPrevious:I,clearSuggestions:M,focusInputAfterSelection:F,suppressUntilQueryChange:H}}const Ut=new Map,Gu=new Map,Xu=new Map,Yu=new Set,Qu=()=>{if(typeof window>"u")return null;try{return localStorage.getItem("chat-adapter-name")}catch{return null}},to=t=>typeof t=="object"&&t!==null&&"message"in t,Zu=t=>t instanceof Error?t.message:typeof t=="string"?t:to(t)?t.message??"Unknown error":"Unknown error";function Ju({conversationId:t,onFilesSelected:e,onUploadError:s,onClose:a,onUploadingChange:r,onUploadSuccess:n,maxFiles:o=le.maxFilesPerConversation,disabled:l=!1}){const{t:c}=Le(),[d,u]=h.useState(!1),[f,m]=h.useState(0),p=h.useRef(null),g=h.useRef(Xu),x=h.useRef(Yu),y=h.useRef(new Map),k=h.useRef(!0),A=h.useRef(Gu),L=h.useRef(t),C=we(z=>z.conversations),v=h.useMemo(()=>{if(!t)return new Map;const z=Ut.get(t);return z?new Map(z):new Map},[t,f]),N=h.useCallback(z=>{if(!z){r==null||r(null,!1),m(ee=>ee+1);return}const se=Ut.get(z)||new Map,Y=C.find(ee=>ee.id===z),J=new Map(se);if(Y!=null&&Y.attachedFiles){const ee=new Set(Y.attachedFiles.filter(ue=>ue.processing_status==="completed"||ue.processing_status==="failed"||ue.processing_status==="error").map(ue=>ue.file_id));J.forEach((ue,ve)=>{ue.fileId&&ee.has(ue.fileId)&&J.delete(ve)})}J.size>0?(Ut.set(z,J),r==null||r(z,!0)):(Ut.delete(z),r==null||r(z,!1)),m(ee=>ee+1)},[C,r]);h.useEffect(()=>{L.current=t,setTimeout(()=>{N(t)},0)},[t,N]),h.useEffect(()=>{t&&setTimeout(()=>{N(t)},0)},[C,t,N]);const R=h.useCallback((z,se)=>{if(!z)return;const Y=Ut.get(z)||new Map,J=se(new Map(Y));J.size>0?Ut.set(z,J):Ut.delete(z),r==null||r(z,J.size>0),m(ee=>ee+1)},[r]),b=h.useCallback((z,se)=>{if(!z)return;const Y=A.current.get(z)||[],J=se([...Y||[]]),ee=new Set(Y.map(ue=>ue.file_id));if(A.current.set(z,J),e(z,J),n){const ue=J.filter(ve=>!ee.has(ve.file_id));ue.length>0&&n(z,ue)}m(ue=>ue+1)},[e,n]),_=we(z=>z.removeFileFromConversation),S=we(z=>z.addFileToConversation);h.useEffect(()=>(k.current=!0,()=>{k.current=!1}),[]);const I=h.useCallback(()=>{k.current=!1,new Map(y.current).forEach(se=>se.abort()),setTimeout(()=>{const se=we.getState(),Y=new Map(se.conversations.map(ee=>[ee.id,ee])),J=[];g.current.forEach((ee,ue)=>{var ve;if(ee){const B=Y.get(ee);if(new Set(((ve=B==null?void 0:B.attachedFiles)==null?void 0:ve.map(ie=>ie.file_id))||[]).has(ue)){x.current.add(ue),g.current.delete(ue);return}}if(x.current.has(ue)){U(`[FileUpload] Skipping cleanup delete for ${ue}; file was previously attached and already handled`),g.current.delete(ue),x.current.delete(ue);return}J.push({fileId:ue,conversationId:ee||null})}),J.length>0&&(a==null||a(),J.forEach(async({fileId:ee,conversationId:ue})=>{try{if(ue)await _(ue,ee);else{const ve=Qu();await Os.deleteFile(ee,void 0,void 0,ve??void 0),ka(ee)}}catch(ve){if(to(ve)){const B=ve.message??"";!B.includes("404")&&!B.includes("File not found")&&ge(`Failed to cleanup file ${ee} during component unmount:`,ve)}else ge(`Failed to cleanup file ${ee} during component unmount`,ve)}}))},300)},[a,_]);h.useEffect(()=>I,[I]);const M=h.useCallback(async z=>{if(!z||z.length===0)return;const se=Array.from(z),Y=we.getState(),J=t||Y.currentConversationId;if(!J){s==null||s(c("fileUpload.selectBeforeUpload"));return}const ee=Y.conversations.find(re=>re.id===J);if(!ee){s==null||s(c("fileUpload.conversationNotFound"));return}const ue=ee.attachedFiles||[],ve=[],B=se.filter(re=>ue.some(pe=>pe.filename===re.name&&pe.file_size===re.size)?(ve.push(re.name),!1):!0);if(ve.length>0&&(s==null||s(ve.length===1?c("fileUpload.duplicateFileError",{filename:ve[0]}):c("fileUpload.duplicateFilesError",{count:ve.length}))),B.length===0)return;if((A.current.get(J)||[]).length+B.length>o){const re=c("fileUpload.maxFilesPerConversationError",{count:o});it()&&!wt()&&ot.getState().openLoginPrompt(c("fileUpload.maxFilesGuestLimitMessage",{count:o})),s==null||s(re);return}if(le.maxTotalFiles!==null&&Y.conversations.reduce((pe,_e)=>{var be;return pe+(((be=_e.attachedFiles)==null?void 0:be.length)||0)},0)+B.length>le.maxTotalFiles){const pe=c("fileUpload.maxTotalFilesError",{count:le.maxTotalFiles});it()&&!wt()&&ot.getState().openLoginPrompt(c("fileUpload.maxTotalFilesGuestLimitMessage",{count:le.maxTotalFiles})),s==null||s(pe);return}if(!ee.adapterName){s==null||s(c("fileUpload.adapterNotConfigured"));return}const ie=ee.adapterName,je=ut(ee.apiUrl);for(let re=0;re<B.length;re++){const W=B[re],pe=new AbortController;y.current.set(W.name,pe);const _e=`${J}-${W.name}-${Date.now()}-${re}`;let be=null;const Me=W.type.startsWith("image/")?URL.createObjectURL(W):null;try{const Ce=await Os.uploadFile(W,P=>{if(R(J,K=>(K.set(_e,P),K)),P.fileId&&!be){be=P.fileId,g.current.set(P.fileId,J),x.current.add(P.fileId),Me&&Xi(P.fileId,Me);const K={file_id:P.fileId,filename:W.name,mime_type:W.type||"application/octet-stream",file_size:W.size,processing_status:P.status==="uploading"?"uploading":P.status==="processing"?"processing":P.status==="completed"?"completed":void 0};U(`[FileUpload] Adding file ${P.fileId} to conversation ${J} immediately (status: ${K.processing_status})`),S(J,K)}},void 0,je,ie).catch(P=>{if(P.message&&P.message.includes("was deleted")){be&&g.current.delete(be);const K=P.message.match(/File\s+([\w-]+)\s+was deleted/);return K&&K[1]&&g.current.delete(K[1]),U(`File ${W.name} was deleted during upload`),null}throw P});Ce?(g.current.set(Ce.file_id,J),x.current.add(Ce.file_id),U(`[FileUpload] Updating file ${Ce.file_id} in conversation ${J} with final status`),S(J,Ce),Ce.processing_status==="completed"||Ce.processing_status==="failed"||Ce.processing_status==="error"?R(J,K=>(K.delete(_e),K)):R(J,K=>{const Fe=K.get(_e);return Fe&&K.set(_e,{...Fe,progress:90,status:"processing",fileId:Ce.file_id}),K}),b(J,K=>{if(new Set(K.map(Ae=>Ae.file_id)).has(Ce.file_id))return K;const oe=[...K,Ce];return U(`[FileUpload] Updated uploadedFiles for ${J}: ${oe.length} files`,oe),oe})):(ge(`Upload completed for ${W.name} but uploadedAttachment is null`),R(J,P=>(P.delete(_e),P)))}catch(Ce){const P=Zu(Ce);if(Ce instanceof DOMException&&Ce.name==="AbortError"||pe.signal.aborted){U(`Upload cancelled for ${W.name}`),be?g.current.delete(be):Me&&URL.revokeObjectURL(Me);continue}if(P.includes("was deleted")){U(`File ${W.name} was deleted during upload`),be&&g.current.delete(be);const oe=P.match(/File\s+([\w-]+)\s+was deleted/);oe&&oe[1]&&g.current.delete(oe[1]);continue}k.current?(xe(`Failed to upload file ${W.name}:`,Ce),xe(`File type: ${W.type}, File name: ${W.name}`),s==null||s(P||`Failed to upload ${W.name}`)):ge(`Upload error for ${W.name} (component unmounted):`,P),be?g.current.delete(be):Me&&URL.revokeObjectURL(Me);const K=_e,Fe=J;setTimeout(()=>{R(Fe,oe=>(oe.delete(K),oe))},5e3)}finally{y.current.delete(W.name)}}},[S,t,o,s,c,b,R]),F=h.useCallback(z=>{z.preventDefault(),z.stopPropagation(),l||u(!0)},[l]),H=h.useCallback(z=>{z.preventDefault(),z.stopPropagation(),u(!1)},[]),j=h.useCallback(z=>{if(z.preventDefault(),z.stopPropagation(),u(!1),l)return;const se=z.dataTransfer.files;M(se)},[l,M]),E=h.useCallback(z=>{const se=z.target.files;M(se),p.current&&(p.current.value="")},[M]),D=h.useCallback(()=>{!l&&p.current&&p.current.click()},[l]),T=h.useCallback(z=>{l||(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),D())},[l,D]),G=v.size>0,X=h.useMemo(()=>{const z=new Map;return C.forEach(se=>{z.set(se.id,se.title||c("chatInterface.newChatTitle"))}),z},[C,c]),V=h.useMemo(()=>{const z=[];return Ut.forEach((se,Y)=>{Y!==t&&se.size>0&&z.push({conversationId:Y,uploads:Array.from(se.entries()).map(([J,ee])=>({key:J,progress:ee}))})}),z},[t,f]),Z=(z,se)=>{const Y=z.status==="uploading"?c("fileUpload.uploadingStatus"):z.status==="processing"?c("fileUpload.processingStatus"):z.status==="completed"?c("fileUpload.completedStatus"):void 0;return i.jsx(Ar,{filename:z.filename,fileId:z.fileId,status:z.status,statusText:Y,errorMessage:z.error||(z.status==="error"?c("fileUpload.processingFailedMessage"):void 0)},se)},fe=i.jsx("div",{className:"w-full max-w-full overflow-hidden flex flex-wrap gap-2",role:"status","aria-live":"polite",children:Array.from(v.entries()).map(([z,se])=>Z(se,z))});return i.jsxs("div",{className:"w-full max-w-full overflow-hidden space-y-2",children:[G&&fe,!G&&i.jsxs("button",{type:"button",onClick:D,onKeyDown:T,onDragOver:F,onDragLeave:H,onDrop:j,disabled:l,className:`
344
344
  group relative w-full max-w-full rounded-lg border p-4 transition-all duration-200 text-left overflow-hidden
345
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:p,type:"file",multiple:!0,onChange:E,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(md,{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})})]})]})]}),V.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")}),V.map(({conversationId:O,uploads:te})=>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:G.get(O)||"Conversation"}),i.jsx("div",{className:"flex flex-wrap gap-2",children:te.map(({key:Y,progress:ee})=>Z(ee,Y))})]},O))]})]})}const Qn={"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"},ur=4,fr=3,ef=0,tf=0,sa=2;function sf(t){if(!t||typeof t!="object")return null;const e=t,s=["supportsAutocomplete","isAutocompleteSupported","autocompleteSupported"];for(const n of s)if(typeof e[n]=="boolean")return e[n];const a=["capabilities","features"],r=["autocomplete","supportsAutocomplete","autocomplete_supported"];for(const n of a){const o=e[n];if(!o||typeof o!="object")continue;const l=o;for(const c of r)if(typeof l[c]=="boolean")return l[c]}return null}function rf(t){if(!t)return"bin";if(Qn[t])return Qn[t];const e=t.split("/");return e.length===2&&e[1]?e[1]:"bin"}function af(t){return t.replace(/[^a-zA-Z0-9._-]/g,"_").replace(/_+/g,"_")||"pasted-file"}function nf(t){const e=t.lastIndexOf(".");return e===-1||e===t.length-1?null:t.slice(e+1).toLowerCase()}function of(t){const e=t.lastIndexOf(".");return e===-1?t:t.slice(0,e)}function ra(t){return!t||t==="processing"||t==="uploading"}function lf(t,e){const s=Date.now(),a=t.name&&t.name.trim().length>0?t.name.trim():"pasted-file",r=af(of(a)),o=nf(a)||rf(t.type),l=`${r}-${s}-${e}.${o}`;return new File([t],l,{type:t.type||"application/octet-stream"})}function Zn({onSend:t,disabled:e=!1,placeholder:s=ki(),autoFocusEnabled:a=!0,suppressMobileAutoFocus:r=!1,isCentered:n=!1,maxWidthClass:o="max-w-5xl",adapterNotes:l,skillState:c,availableModels:d=[],defaultModel:u=null,selectedModel:f=null,onSelectModel:m}){var en;const{t:p}=Ee(),[g,x]=h.useState(""),[y,k]=h.useState(!1),[A,L]=h.useState(!1),[C,v]=h.useState(!1),[N,R]=h.useState(!1),[b,_]=h.useState([]),[S,I]=h.useState({}),[M,F]=h.useState(new Map),[B,j]=h.useState(!1),[E,P]=h.useState(!1),[T,K]=h.useState(null),[G,V]=h.useState(null),[Z,ue]=h.useState(null),[O,te]=h.useState({isOpen:!1,fileId:"",filename:"",isDeleting:!1}),Y=h.useRef(null),ee=h.useRef(null),re=h.useRef(null),fe=h.useRef(null),Ae=h.useRef(null),H=h.useRef(new Set),J=h.useRef(""),W=h.useRef(!1),ye=h.useRef(0),ne=h.useRef(null),{settings:X,updateSettings:xe}=Lr(),{theme:Ce,isDark:oe}=ts(),ve=Ce.mode==="dark"?"dark":Ce.mode==="light"?"light":"",$e=oe?"dark":"light";Ds(ee,{enabled:C,onEscape:()=>v(!1)});const z=h.useCallback((w,U)=>{w&&I(de=>{if(de[w]===U)return de;const pe={...de};return U?pe[w]=!0:delete pe[w],pe})},[]),[ie,Be]=h.useState(0),[be,Ne]=h.useState(!1),[Tt,ze]=h.useState(0),[et,ps]=h.useState(()=>({top:ur+fr,bottom:Math.max(ur-fr,0)})),[xt,Mt]=h.useState(null),Vt=hs(),tt=it()&&!Vt,Ft=ot(w=>w.showLoginPrompt),{createConversation:qt,currentConversationId:je,conversations:st,isLoading:bt,syncConversationFiles:ce,stopStreaming:Se,removeFileFromConversation:_e}=ke(),se=st.find(w=>w.id===je),rt=se?se.messages.filter(w=>!(w.role==="assistant"&&w.isStreaming)).length:0,He=st.reduce((w,U)=>w+U.messages.filter(de=>!(de.role==="assistant"&&de.isStreaming)).length,0),ms=!!se&&le.maxMessagesPerConversation!==null&&rt>=le.maxMessagesPerConversation,lt=le.maxTotalMessages!==null&&He>=le.maxTotalMessages,gs=h.useCallback(()=>{Be(w=>w+1)},[]),Bs=uc(),ss=fc(),{isListening:at,isSupported:Hs,startListening:Vs,stopListening:rs,error:Wt}=Vu(w=>{x(U=>{const de=U.length>0&&!/\s$/.test(U)?" ":"",pe=(U+de+w).slice(0,le.maxMessageLength);return J.current=pe,pe})},gs,{silenceTimeoutMs:Bs,language:ss||void 0}),xs=lc(),$t=cc(),ht=$t&&Hs,Rt=oc(),bs=Si(),qs=sf(se==null?void 0:se.adapterInfo),{skills:Kt,isLoading:Ws,selectedSkill:qe,selectSkill:ys,clearSkill:Gt}=c,Rr=(se==null?void 0:se.adapterName)||null,{suggestions:Pt,selectedIndex:Ye,setSelectedIndex:Pr,selectNext:Dr,selectPrevious:Ur,clearSuggestions:kt,focusInputAfterSelection:ws,suppressUntilQueryChange:ks}=Ku(g,{enabled:bs&&!at,apiUrl:se==null?void 0:se.apiUrl,adapterName:Rr,sessionId:se==null?void 0:se.sessionId,adapterSupportsAutocomplete:qs,skill:(qe==null?void 0:qe.name)||null,inputRef:Y}),as=Pt.length>0,$=!at,we=$&&as&&!be,q=g.startsWith("/")?g.slice(1):"",Ie=q.toLowerCase().replace(/-/g," "),Re=Ie?Kt.filter(w=>w.name.replace(/-/g," ").toLowerCase().includes(Ie)||w.description.toLowerCase().includes(Ie)):Kt,Xt=Re.length>0?Math.min(Tt,Re.length-1):0,ct=Re[Xt]??null,Or=(ct==null?void 0:ct.name.replace(/-/g," "))??"",ho=be&&ct&&g.startsWith("/")&&Or.toLowerCase().startsWith(q.toLowerCase())&&Or.length>q.length?Or.slice(q.length):null,po=Ye>=0?Ye:0,vs=as?Pt[po]:null,za=h.useMemo(()=>{if(!vs)return null;const w=vs.text||"";if(!g)return w;const U=g;return w.toLowerCase().startsWith(U.toLowerCase())&&w.length>U.length?w.slice(U.length):null},[vs,g]),zr=ho??za,mo=g.trim().length===0&&!zr,go=h.useCallback(w=>{if(!g)return i.jsx("span",{className:"line-clamp-1 text-current",children:w});if(!w.toLowerCase().startsWith(g.toLowerCase()))return i.jsx("span",{className:"line-clamp-1 text-current",children:w});const U=w.slice(0,g.length),de=w.slice(g.length);return i.jsxs("span",{className:"line-clamp-1",children:[i.jsx("span",{className:"text-gray-500 dark:text-[#8e8ea0]",children:U}),i.jsx("span",{className:"font-semibold text-[#353740] dark:text-[#ececf1]",children:de})]})},[g]),Ba=h.useCallback(w=>{var U;ys(w),Ne(!1),x(""),kt(),ze(0),(U=Y.current)==null||U.focus()},[kt,ys]),xo=h.useCallback(()=>{var w;x("/"),Ne(!0),ze(0),(w=Y.current)==null||w.focus()},[]),Ha=h.useCallback(()=>{var w;Ne(!1),x(""),ze(0),(w=Y.current)==null||w.focus()},[]),Yt=h.useCallback(()=>{const w=Y.current;if(!w||typeof window>"u")return;const U=Ge=>{const Gr=Ge+fr,tr=Math.max(Ge-fr,0);w.style.paddingTop=`${Gr}px`,w.style.paddingBottom=`${tr}px`,ps({top:Gr,bottom:tr})},de=window.getComputedStyle(w),pe=parseFloat(de.lineHeight||"0");if(!Number.isNaN(pe)&&pe>0?Mt(Ge=>Ge===pe?Ge:pe):Mt(Ge=>Ge===null?Ge:null),!pe||Number.isNaN(pe)){U(ur);return}const Le=w.scrollHeight,We=w.clientHeight;if(Le>pe+2){U(ur);return}const Te=Math.max(We-pe,0),Ve=Math.max(Te/2,0);U(Ve)},[]),bo=()=>{const w=Y.current;return w?w.selectionStart===w.selectionEnd&&w.selectionStart===g.length:!1},Va=(se==null?void 0:se.attachedFiles)||[],ns=je?Va:b,yo=st.reduce((w,U)=>{var de;return w+(((de=U.attachedFiles)==null?void 0:de.length)||0)},0),qa=le.maxFilesPerConversation!==null&&le.maxFilesPerConversation>0&&Va.length>=le.maxFilesPerConversation,Wa=le.maxTotalFiles!==null&&yo>=le.maxTotalFiles,Ss=((en=se==null?void 0:se.adapterInfo)==null?void 0:en.isFileSupported)??!1,Br=ns.some(w=>w.processing_status?w.processing_status!=="completed"&&w.processing_status!=="error"&&w.processing_status!=="failed":!0),yt=je?!!S[je]:!1,Ks=Object.values(S).some(Boolean),Hr=g.trim().length>0,Ka=ms||lt,De=e||Br||yt||Ka,Ga=Rt&&Ss,Gs=qa||Wa,js=!Ga||De||Gs;h.useLayoutEffect(()=>{if(Y.current){const w=Y.current,U=120;w.style.height="auto";const de=w.scrollHeight;w.style.height=`${Math.min(de,U)}px`,w.style.overflowY=de>U?"auto":"hidden",Yt()}},[g,Yt]),h.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const w=Y.current;if(!w)return;const U=new ResizeObserver(()=>{Yt()});return U.observe(w),()=>{U.disconnect()}},[Yt]);const Xa=()=>{const w=document.activeElement;return w&&w.tagName==="TEXTAREA"},Xs=h.useCallback(()=>!r||typeof window>"u"?!1:window.matchMedia("(max-width: 767px)").matches,[r]);h.useEffect(()=>{Xs()||a&&!De&&Y.current&&!Xa()&&Y.current.focus()},[a,De,r,Xs]);const Vr=h.useRef(bt);h.useEffect(()=>{if(Xs()){Vr.current=bt;return}a&&Vr.current&&!bt&&!De&&Y.current&&setTimeout(()=>{Y.current&&!Xa()&&Y.current.focus()},100),Vr.current=bt},[a,bt,De,r,Xs]),h.useEffect(()=>{if(!ht||(ie>ye.current&&(W.current=!0,ye.current=ie),!W.current||ie===0))return;const w=J.current.trim(),U=ke.getState();if(D("[MessageInput] Auto-send check after voice completion:",{hasMessage:!!w,isInputDisabled:De,isComposing:y,isLoading:U.isLoading}),W.current=!1,!w)return;if(De||y){D("[MessageInput] Auto-send skipped because input is currently disabled or composing");return}const de=U.conversations.find(Ue=>Ue.id===U.currentConversationId),Le=((de==null?void 0:de.attachedFiles)||[]).map(Ue=>Ue.file_id),We=qe==null?void 0:qe.name;D("[MessageInput] Auto-sending voice message immediately:",w),t(w,Le.length>0?Le:void 0,void 0,We),We&&Gt(),setTimeout(()=>{Ne(!1)},0),kt(),setTimeout(()=>{x("")},0),J.current="",Y.current&&(Y.current.style.height="auto",Y.current.style.overflowY="hidden",Yt())},[ht,ie,De,y,t,qe,Gt,Yt,kt]),h.useEffect(()=>{yt&&N&&setTimeout(()=>{R(!1)},0)},[yt,N]);const Ys=h.useCallback((w,U)=>{setTimeout(()=>{let de=ke.getState(),pe=U||de.currentConversationId;if(pe||(pe=qt(),de=ke.getState(),pe=de.currentConversationId||pe),!pe){ge("[MessageInput] Unable to sync files: conversation ID missing");return}const Le=new Set(w.map(Ue=>Ue.file_id)),We=[];H.current.forEach((Ue,Te)=>{const[,...Ve]=Te.split("-"),Ge=Ve.join("-");Le.has(Ge)||We.push(Te)}),We.forEach(Ue=>H.current.delete(Ue)),w.forEach(Ue=>{const Te=`${pe}-${Ue.file_id}`;H.current.has(Te)||(H.current.add(Te),D(`[MessageInput] Adding file ${Ue.file_id} to conversation ${pe}`),de.addFileToConversation(pe,Ue))})},0)},[qt]);h.useEffect(()=>{if(je!==ne.current)if(ne.current=je||null,je&&se){const w=se.attachedFiles||[];setTimeout(()=>{_(w.map(U=>({...U})))},0)}else setTimeout(()=>{_([])},0)},[je,se]),h.useEffect(()=>{if(je&&se){const w=se.attachedFiles||[];w.length>0?setTimeout(()=>{_(U=>{const de=new Set(U.map(Le=>Le.file_id)),pe=w.filter(Le=>!de.has(Le.file_id));return pe.length>0?(D(`[MessageInput] Syncing ${pe.length} missing files from conversation to UI`),[...U,...pe]):U})},0):w.length===0&&b.length>0&&setTimeout(()=>{_([])},0)}},[je,se,st,b.length]);const qr=h.useRef(null),Wr=h.useRef(""),Qs=(se==null?void 0:se.attachedFiles)||[],Zs=Qs.length>0?`${Qs.length}:${Qs.map(w=>w.file_id).join("|")}`:"",Ya=Qs.some(w=>ra(w.processing_status));h.useEffect(()=>{if(!je||!(se!=null&&se.adapterName))return;const w=Zs!=="";if(w&&(qr.current!==je||Wr.current!==Zs)?(D(`[MessageInput] Syncing files for conversation ${je}...`),qr.current=je,Wr.current=Zs,ce(je).catch(pe=>{ge("[MessageInput] Failed to sync conversation files:",pe)})):w||(qr.current=je,Wr.current=""),!Ya)return;D("[MessageInput] Files still processing, starting poll...");const de=setInterval(async()=>{const Le=ke.getState().conversations.find(Te=>Te.id===je);if(!Le){clearInterval(de);return}if((Le.attachedFiles||[]).filter(Te=>ra(Te.processing_status)).length===0){D("[MessageInput] All files completed processing, stopping poll"),clearInterval(de);return}try{await ce(je)}catch(Te){ge("[MessageInput] Failed to poll file status:",Te)}},3e3);return()=>{clearInterval(de)}},[je,se==null?void 0:se.adapterName,Zs,Ya,ce]),h.useEffect(()=>{setTimeout(()=>{I(w=>{const U=new Set(st.map(Le=>Le.id));let de=!1;const pe={...w};return Object.keys(pe).forEach(Le=>{U.has(Le)||(delete pe[Le],de=!0)}),de?pe:w})},0)},[st]);const Qa=w=>{if(w.preventDefault(),Hr&&!De&&!y){at&&rs();const de=((se==null?void 0:se.attachedFiles)||[]).map(Le=>Le.file_id),pe=qe==null?void 0:qe.name;t(g.trim(),de.length>0?de:void 0,void 0,pe),pe&&Gt(),Ne(!1),_s("messageSent",X.soundEnabled),x(""),J.current="",_([]),R(!1),Y.current&&(Y.current.style.height="auto",Y.current.style.overflowY="hidden",Yt())}},Js=h.useCallback(w=>{if(!w||w.length===0)return;const U=w.length===1?p("messageInput.uploadSuccess.single",{filename:w[0].filename}):p("messageInput.uploadSuccess.multiple",{count:w.length});_s("success",X.soundEnabled),V(U),setTimeout(()=>{V(null)},6e3)},[X.soundEnabled,p]),wo=h.useCallback((w,U)=>{D(`[MessageInput] handleFilesSelected called with ${U.length} files for conversation ${w}:`,U),w&&(w===je&&_(U),Ys(U,w))},[je,Ys]),ko=h.useCallback((w,U)=>{w===je&&Js(U)},[je,Js]),vo=h.useCallback(w=>{te({isOpen:!0,fileId:w.file_id,filename:w.filename,isDeleting:!1})},[]),So=h.useCallback(()=>{te(w=>w.isDeleting?w:{isOpen:!1,fileId:"",filename:"",isDeleting:!1})},[]),jo=h.useCallback(async()=>{if(!(!je||!O.fileId)){te(w=>({...w,isDeleting:!0}));try{await _e(je,O.fileId),_(w=>w.filter(U=>U.file_id!==O.fileId)),te({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}catch(w){const U=w instanceof Error?w.message:p("messageInput.fileRemoveFailed");ge("[MessageInput] Failed to remove file:",w),ue(U),te({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}}},[je,O.fileId,_e,p]),Za=h.useCallback(w=>w.replace(/\s+/g," ").trim(),[]),er=h.useCallback(w=>{const U=Za(w);x(U),kt(),ks(U),ws(U)},[kt,ws,Za,ks]),Kr=h.useCallback(w=>{if(w<0)return;const U=Pt[w]||Pt[0];U&&er(U.text)},[Pt,er]),Co=w=>{if(be){if(w.key==="ArrowDown"){w.preventDefault(),ze(U=>Re.length===0?0:(U+1)%Re.length);return}if(w.key==="ArrowUp"){w.preventDefault(),ze(U=>Re.length===0?0:(U-1+Re.length)%Re.length);return}if(w.key==="Home"){w.preventDefault(),ze(0);return}if(w.key==="End"){w.preventDefault(),ze(Math.max(Re.length-1,0));return}if((w.key==="Enter"&&!w.shiftKey||w.key==="Tab")&&ct){w.preventDefault(),Ba(ct);return}if(w.key==="Escape"){w.preventDefault(),Ha();return}}if(as&&$){if(w.key==="ArrowDown"){w.preventDefault(),Dr();return}if(w.key==="ArrowUp"){w.preventDefault(),Ur();return}if(w.key==="Tab"){w.preventDefault();const U=Ye>=0?Ye:0;Kr(U);return}if(w.key==="ArrowRight"&&bo()){if(za&&vs){w.preventDefault(),er(vs.text);return}if(Ye>=0){w.preventDefault(),Kr(Ye);return}}if(w.key==="Enter"&&Ye>=0){w.preventDefault(),Kr(Ye);return}if(w.key==="Escape"){w.preventDefault(),kt();return}}w.key==="Enter"&&!w.shiftKey&&!y&&(w.preventDefault(),Qa(w))},Ao=()=>{at?rs():(kt(),Vs())},No=()=>{const w=!X.voiceEnabled;xe({voiceEnabled:w}),w&&Bt.enableAudio()},Io=h.useCallback(async w=>{if(!Rt||!A||!Ss||De)return;const U=w.clipboardData;if(!U||!U.items)return;const pe=Array.from(U.items).filter(Te=>Te.kind==="file");if(pe.length===0)return;const Le=[];if(pe.forEach((Te,Ve)=>{const Ge=Te.getAsFile();Ge&&Le.push(lf(Ge,Ve))}),Le.length===0)return;w.preventDefault(),K(null),V(null);let We=null;const Ue=new Set;try{const Te=ke.getState(),Ve=Te.conversations.find(dt=>dt.id===Te.currentConversationId);if(((Ve==null?void 0:Ve.attachedFiles)||[]).length+Le.length>le.maxFilesPerConversation)throw tt&&ot.getState().openLoginPrompt(p("fileUpload.maxFilesGuestLimitMessage",{count:le.maxFilesPerConversation})),new Error(p("fileUpload.maxFilesPerConversationError",{count:le.maxFilesPerConversation}));if(le.maxTotalFiles!==null&&Te.conversations.reduce((pt,It)=>{var Qe;return pt+(((Qe=It.attachedFiles)==null?void 0:Qe.length)||0)},0)+Le.length>le.maxTotalFiles)throw tt&&ot.getState().openLoginPrompt(p("fileUpload.maxTotalFilesGuestLimitMessage",{count:le.maxTotalFiles})),new Error(p("fileUpload.maxTotalFilesError",{count:le.maxTotalFiles}));if(!Ve)throw new Error(p("messageInput.conversationNotFoundShort"));if(!Ve.adapterName)throw new Error(p("fileUpload.adapterNotConfigured"));const tr=ut(Ve.apiUrl),_o=Ve.adapterName;We=Ve.id,z(We,!0);const Cs=[],tn=[];for(let dt=0;dt<Le.length;dt++){const pt=Le[dt],It=pt.name||`Clipboard file ${dt+1}`,Qe=`${It}-${Date.now()}-${dt}`,As=pt.type.startsWith("image/")?URL.createObjectURL(pt):null;As&&Ue.add(As);let sn=null;F(nt=>{const Dt=new Map(nt);return Dt.set(Qe,{filename:It,progress:0,status:"uploading"}),Dt});const To=nt=>{nt.fileId&&!sn&&(sn=nt.fileId,As&&(Xi(nt.fileId,As),Ue.delete(As))),F(Dt=>{const mt=new Map(Dt),Ns=mt.get(Qe);return Ns&&mt.set(Qe,{...Ns,filename:It,progress:nt.progress,status:nt.status,fileId:nt.fileId}),mt})},Mo=()=>new Promise(nt=>{F(Dt=>{const mt=new Map(Dt),Ns=mt.get(Qe);return Ns&&mt.set(Qe,{...Ns,progress:100,status:"completed"}),mt}),setTimeout(()=>{F(Dt=>{const mt=new Map(Dt);return mt.delete(Qe),mt}),nt()},2500)});D(`[MessageInput] Pasting file: ${pt.name}, type: ${pt.type||"unknown"}, size: ${pt.size}`);const Fo=await Os.uploadFile(pt,nt=>{D(`[MessageInput] Paste upload progress for ${pt.name}: ${nt.progress}% - ${nt.status}`),To(nt)},void 0,tr,_o);Cs.push(Fo),tn.push(Mo())}if(Cs.length>0){let dt=Cs;if(We&&We===je){const pt=new Set(b.map(Qe=>Qe.file_id)),It=Cs.filter(Qe=>!pt.has(Qe.file_id));It.length>0?(_(Qe=>[...Qe,...It]),dt=It):dt=[]}dt.length>0&&Ys(dt,We),await Promise.all(tn),Js(Cs)}}catch(Te){const Ve=Te instanceof Error?Te.message:"Failed to paste file";ge("[MessageInput] Paste error:",Te),_s("error",X.soundEnabled),K(Ve),Ve.toLowerCase().includes("maximum")&&ue(Ve),setTimeout(()=>{K(null)},5e3),F(new Map),Ue.forEach(Ge=>URL.revokeObjectURL(Ge))}finally{z(We,!1)}},[b,je,A,Ss,tt,De,z,X.soundEnabled,Js,Ys,Rt,p]),Ja=sc(se==null?void 0:se.adapterName);let Nt;lt?Nt=tt?p("messageInput.placeholder.guestLimitTotal",{count:le.maxTotalMessages}):p("messageInput.placeholder.workspaceLimitTotal",{count:le.maxTotalMessages}):ms?Nt=tt?p("messageInput.placeholder.guestLimitPerConversation",{count:le.maxMessagesPerConversation}):p("messageInput.placeholder.conversationLimitReached",{count:le.maxMessagesPerConversation}):Br||yt?Nt=p("messageInput.placeholder.filesUploading"):Ja?Nt=Ja:Ga?Nt=p("messageInput.placeholder.messageOrbit"):Nt=s;const Qt=[];lt&&le.maxTotalMessages!==null&&(tt?Ft&&Qt.push(p("messageInput.limitWarning.guestTotalMessages",{count:le.maxTotalMessages})):Qt.push(p("messageInput.limitWarning.workspaceTotalMessages",{count:le.maxTotalMessages}))),ms&&le.maxMessagesPerConversation!==null&&(tt?Ft&&Qt.push(p("messageInput.limitWarning.guestPerConversation",{count:le.maxMessagesPerConversation})):Qt.push(p("messageInput.limitWarning.conversationLimitReached",{count:le.maxMessagesPerConversation}))),Z&&Qt.push(Z),h.useEffect(()=>{!$t||!Wt||_s("error",X.soundEnabled)},[$t,X.soundEnabled,Wt]),h.useEffect(()=>{if(!Z)return;const w=setTimeout(()=>ue(null),5e3);return()=>clearTimeout(w)},[Z]),h.useEffect(()=>{var w;(N||yt||M.size>0||Ks)&&((w=re.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[N,yt,M.size,Ks]),h.useEffect(()=>{var w;we&&((w=fe.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[we]),h.useEffect(()=>{var w;be&&((w=Ae.current)==null||w.scrollIntoView({behavior:"smooth",block:"end"}))},[be,Re.length]);const Lo=o,Eo=n?"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 ${Eo}`,children:i.jsxs("div",{className:`mx-auto w-full ${Lo}`,children:[Wt&&$t&&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(ga,{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:Wt})]}),T&&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(ga,{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:T})]}),G&&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(zc,{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:G})]}),Qt.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(Fa,{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:Qt.map((w,U)=>i.jsx("li",{className:"text-sm text-amber-800 dark:text-amber-200",children:w},`${w}-${U}`))}),tt&&(Ka||Gs)&&Ft&&i.jsx("button",{type:"button",onClick:()=>ot.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:Qa,className:"flex w-full flex-col gap-2 md:gap-3",children:[i.jsxs("div",{className:`flex flex-row items-center gap-1.5 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 ${A?"border-gray-400 shadow-md dark:border-[#3a3a3a] dark:shadow-lg":"border-gray-300 dark:border-[#242424]"} bg-gray-50 dark:bg-[#111111]`,children:[qe&&i.jsxs("div",{className:"flex h-8 max-w-[45%] 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 sm:max-w-[38%] md:max-w-[32%]",children:[i.jsx(Ma,{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:qe.name.replace(/-/g," ")}),i.jsx("button",{type:"button",onClick:()=>{var w;Gt(),(w=Y.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"})})]}),!qe&&Kt.length>0&&g.length===0&&!De&&i.jsxs("button",{type:"button",onClick:xo,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":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",children:[mo&&Nt&&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(et.top-ef,0),paddingBottom:et.bottom,paddingLeft:`${sa}px`,paddingRight:0,lineHeight:xt?`${xt}px`:void 0},"aria-hidden":"true",children:Nt}),zr&&A&&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(et.top-tf,0),paddingBottom:et.bottom,paddingLeft:`${sa}px`,paddingRight:0,lineHeight:xt?`${xt}px`:void 0},"aria-hidden":"true",children:[i.jsx("span",{className:"invisible",children:g}),i.jsx("span",{children:zr})]}),i.jsx("textarea",{ref:Y,"aria-label":p("messageInput.textarea.ariaLabel"),value:g,onChange:w=>{const U=w.target.value;x(U),U.startsWith("/")&&ze(0),Ne(U.startsWith("/")&&Kt.length>0)},onKeyDown:Co,onPaste:Io,onCompositionStart:()=>k(!0),onCompositionEnd:()=>k(!1),onFocus:()=>L(!0),onBlur:()=>L(!1),placeholder:Nt,disabled:De,rows:1,maxLength:le.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:`${et.top}px`,paddingBottom:`${et.bottom}px`,paddingLeft:`${sa}px`,paddingRight:0,border:"none",outline:"none",boxShadow:"none",WebkitAppearance:"none",MozAppearance:"none",appearance:"none",caretColor:g.trim()||A?"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:[n&&!Rt&&i.jsx("div",{className:"hidden md:block h-8 w-8 shrink-0","aria-hidden":"true"}),Rt&&i.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),js||R(!N)},disabled:js,onMouseEnter:()=>j(!0),onMouseLeave:()=>j(!1),className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${N||ns.length>0?"bg-gray-200 text-[#353740] dark:bg-[#565869] dark:text-[#ececf1]":js?"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:Ss?Gs&&qa&&le.maxFilesPerConversation!==null?p("messageInput.fileUpload.titleLimitPerConversation",{count:le.maxFilesPerConversation}):Gs&&Wa&&le.maxTotalFiles!==null?p("messageInput.fileUpload.titleLimitWorkspace",{count:le.maxTotalFiles}):De?p("messageInput.fileUpload.titleUploading"):ns.length>0?p("messageInput.fileUpload.titleAttached",{count:ns.length}):p("messageInput.fileUpload.attachAriaLabel"):p("messageInput.fileUpload.titleNotSupported"),"aria-label":p("messageInput.fileUpload.attachAriaLabel"),children:js&&B?i.jsx(Je,{className:"h-4 w-4"}):i.jsx(id,{className:"h-4 w-4"})}),g.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:g.length>=le.maxMessageLength?"text-red-600 font-semibold":"",children:[g.length,"/",le.maxMessageLength]})})]}),i.jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[i.jsx(eo,{availableModels:d,defaultModel:u,selectedModel:f,onSelect:w=>m==null?void 0:m(w)}),(xs||$t)&&i.jsxs(i.Fragment,{children:[xs&&i.jsx("button",{type:"button",onClick:No,className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${X.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:X.voiceEnabled?p("messageInput.voiceOutput.titleEnabled"):p("messageInput.voiceOutput.titleDisabled"),"aria-label":X.voiceEnabled?p("messageInput.voiceOutput.ariaLabelEnabled"):p("messageInput.voiceOutput.ariaLabelDisabled"),children:X.voiceEnabled?i.jsx($a,{className:"h-5 w-5"}):i.jsx(gd,{className:"h-5 w-5"})}),ht&&i.jsx("button",{type:"button",onClick:Ao,disabled:De,onMouseEnter:()=>P(!0),onMouseLeave:()=>P(!1),className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${at?"!flex bg-red-100 text-red-600 dark:bg-red-900/40 dark:text-red-300":De?"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(De?"messageInput.voiceInput.titleUploading":at?"messageInput.voiceInput.titleListening":"messageInput.voiceInput.titleDisabled"),"aria-label":p(at?"messageInput.voiceInput.ariaLabelListening":"messageInput.voiceInput.ariaLabelDisabled"),children:at||De&&E?i.jsx(Jc,{className:"h-5 w-5"}):i.jsx(ed,{className:"h-5 w-5"})})]}),l&&i.jsx("button",{type:"button",onClick:()=>v(!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(jn,{className:"h-5 w-5"})}),(Br||yt)&&i.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center",children:i.jsx(Fi,{className:"h-4 w-4 animate-spin text-gray-500 dark:text-[#bfc2cd]"})}),bt?i.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),Se()},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(fd,{className:"h-4 w-4 md:h-3 md:w-3 fill-current"})}):i.jsx("button",{type:"submit",disabled:!Hr||De||y,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 ${Hr&&!De&&!y?"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(ma,{className:"h-4 w-4"})})]})]})]}),ns.length>0&&i.jsx("div",{className:"flex flex-wrap gap-2",children:ns.map(w=>{const U=ra(w.processing_status),de=w.processing_status==="failed"||w.processing_status==="error",pe=de?"error":U?w.processing_status==="uploading"?"uploading":"processing":"completed",Le=U?w.processing_status==="uploading"?p("messageInput.attachedFile.uploadingStatus"):p("messageInput.attachedFile.processingStatus"):void 0;return i.jsx(Ar,{filename:w.filename,fileId:w.file_id,status:pe,statusText:Le,errorMessage:de?w.error_message||p("messageInput.fileProcessingFailedTitle"):void 0,onRemove:()=>{de?(je&&_e(je,w.file_id),_(We=>We.filter(Ue=>Ue.file_id!==w.file_id))):vo(w)},removeTitle:p(de?"messageInput.attachedFile.removeTitleFailed":"messageInput.attachedFile.removeTitleNormal")},w.file_id)})}),Rt&&(Ss||Ks)&&i.jsxs("div",{ref:re,className:`rounded-lg border border-gray-200/80 bg-white p-2.5 dark:border-[#3c3f4a] dark:bg-[#2a2b32] transition-all duration-200 ${!N&&!yt&&M.size===0&&!Ks?"hidden":""}`,children:[N&&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:()=>R(!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"})})]}),(yt||M.size>0)&&!N&&M.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")})}),M.size>0&&i.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:Array.from(M.entries()).map(([w,U])=>i.jsx(Ar,{filename:U.filename,fileId:U.fileId,status:U.status,statusText:U.status==="uploading"?p("messageInput.uploadProgress.statusUploading"):U.status==="processing"?p("messageInput.uploadProgress.statusProcessing"):U.status==="completed"?p("messageInput.uploadProgress.statusCompleted"):void 0,errorMessage:U.error},w))}),i.jsx("div",{className:`${N||yt?"block max-h-[40vh] overflow-y-auto":"hidden"}`,"aria-hidden":!(N||yt),children:i.jsx(Ju,{conversationId:je,onFilesSelected:wo,onUploadError:w=>{ge("File upload error:",w),ue(w)},onUploadingChange:z,onUploadSuccess:ko,maxFiles:le.maxFilesPerConversation,disabled:js})})]}),i.jsx("div",{className:"h-3 md:h-1",children:ht&&at&&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:Ae,className:"w-full pt-1",children:i.jsx(Ji,{skills:Kt,isLoading:Ws,selectedSkill:qe,activeSkillName:ct==null?void 0:ct.name,query:q,onActiveSkillChange:w=>{const U=Re.findIndex(de=>de.name===w.name);U>=0&&ze(U)},onSelect:Ba,onClose:Ha})}),we&&i.jsx("div",{ref:fe,role:"listbox","aria-label":p("messageInput.autocompletePanel.ariaLabel"),className:"w-full pt-1",children:Pt.map((w,U)=>{const de=U===Ye;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:()=>er(w.text),onMouseEnter:()=>Pr(U),children:go(w.text)},U)})}),i.jsx(vr,{isOpen:O.isOpen,onClose:So,onConfirm:jo,title:p("messageInput.fileDelete.title"),message:p("messageInput.fileDelete.message",{filename:O.filename}),confirmText:p("messageInput.fileDelete.confirmText"),cancelText:p("common.cancel"),type:"danger",isLoading:O.isDeleting})]})]})}),C&&l&&typeof document<"u"&&Ir.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:ee,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(jn,{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:()=>v(!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:l,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 ${ve}`,syntaxTheme:$e})}),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:()=>v(!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 Jn({adapter:t,onSelect:e}){var l;const{t:s}=Ee(),a=(l=t.description)==null?void 0:l.trim(),{isDark:r}=ts(),n=r?"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}),a?i.jsx("div",{className:"mt-1 text-sm leading-5 text-slate-600 dark:text-slate-300",children:i.jsx(_t,{content:a,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:n})}):i.jsx("p",{className:"mt-1 text-sm leading-5 text-slate-500 dark:text-slate-400",children:s("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":s("agentCard.startConversationAriaLabel",{name:t.name}),children:i.jsx(Sn,{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":s("agentCard.startConversationAriaLabel",{name:t.name}),children:i.jsx(Sn,{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},cf=t=>{if(!t||typeof t!="object")return null;const e=t,s=Zt(e.name);if(!s)return null;const a=Zt(e.id);if(!a)return console.warn(`[middlewareConfig] Adapter "${s}" is missing a required 'id' field — skipping.`),null;const r=Zt(e.apiUrl),n=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:a,name:s};return r&&(d.apiUrl=r),c&&(d.description=c),l&&(d.notes=l),n&&(d.model=n),o&&(d.inputPlaceholder=o),d},so=t=>Array.isArray(t)?t.map(cf).filter(e=>e!==null):[];let Ot=null,aa=0;const df=3e4;function uf(){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=so(t.adapters);if(e.length===0)return null;const s=`{
346
+ `,"aria-label":c(l?"fileUpload.disabledAriaLabel":"fileUpload.enabledAriaLabel"),children:[i.jsx("input",{ref:p,type:"file",multiple:!0,onChange:E,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(md,{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})})]})]})]}),V.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")}),V.map(({conversationId:z,uploads:se})=>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:X.get(z)||"Conversation"}),i.jsx("div",{className:"flex flex-wrap gap-2",children:se.map(({key:Y,progress:J})=>Z(J,Y))})]},z))]})]})}const Qn={"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"},ur=4,fr=3,ef=0,tf=0,sa=2;function sf(t){if(!t||typeof t!="object")return null;const e=t,s=["supportsAutocomplete","isAutocompleteSupported","autocompleteSupported"];for(const n of s)if(typeof e[n]=="boolean")return e[n];const a=["capabilities","features"],r=["autocomplete","supportsAutocomplete","autocomplete_supported"];for(const n of a){const o=e[n];if(!o||typeof o!="object")continue;const l=o;for(const c of r)if(typeof l[c]=="boolean")return l[c]}return null}function rf(t){if(!t)return"bin";if(Qn[t])return Qn[t];const e=t.split("/");return e.length===2&&e[1]?e[1]:"bin"}function af(t){return t.replace(/[^a-zA-Z0-9._-]/g,"_").replace(/_+/g,"_")||"pasted-file"}function nf(t){const e=t.lastIndexOf(".");return e===-1||e===t.length-1?null:t.slice(e+1).toLowerCase()}function of(t){const e=t.lastIndexOf(".");return e===-1?t:t.slice(0,e)}function ra(t){return!t||t==="processing"||t==="uploading"}function lf(t,e){const s=Date.now(),a=t.name&&t.name.trim().length>0?t.name.trim():"pasted-file",r=af(of(a)),o=nf(a)||rf(t.type),l=`${r}-${s}-${e}.${o}`;return new File([t],l,{type:t.type||"application/octet-stream"})}function Zn({onSend:t,disabled:e=!1,placeholder:s=ki(),autoFocusEnabled:a=!0,suppressMobileAutoFocus:r=!1,isCentered:n=!1,maxWidthClass:o="max-w-5xl",adapterNotes:l,skillState:c,availableModels:d=[],defaultModel:u=null,selectedModel:f=null,onSelectModel:m}){var en;const{t:p}=Le(),[g,x]=h.useState(""),[y,k]=h.useState(!1),[A,L]=h.useState(!1),[C,v]=h.useState(!1),[N,R]=h.useState(!1),[b,_]=h.useState([]),[S,I]=h.useState({}),[M,F]=h.useState(new Map),[H,j]=h.useState(!1),[E,D]=h.useState(!1),[T,G]=h.useState(null),[X,V]=h.useState(null),[Z,fe]=h.useState(null),[z,se]=h.useState({isOpen:!1,fileId:"",filename:"",isDeleting:!1}),Y=h.useRef(null),J=h.useRef(null),ee=h.useRef(null),ue=h.useRef(null),ve=h.useRef(null),B=h.useRef(new Set),ae=h.useRef(""),ie=h.useRef(!1),je=h.useRef(0),re=h.useRef(null),{settings:W,updateSettings:pe}=Lr(),{theme:_e,isDark:be}=ts(),Me=_e.mode==="dark"?"dark":_e.mode==="light"?"light":"",Ce=be?"dark":"light";Ds(J,{enabled:C,onEscape:()=>v(!1)});const P=h.useCallback((w,O)=>{w&&I(de=>{if(de[w]===O)return de;const me={...de};return O?me[w]=!0:delete me[w],me})},[]),[K,Fe]=h.useState(0),[oe,Ae]=h.useState(!1),[Tt,Be]=h.useState(0),[et,ps]=h.useState(()=>({top:ur+fr,bottom:Math.max(ur-fr,0)})),[xt,Mt]=h.useState(null),Vt=hs(),tt=it()&&!Vt,Ft=ot(w=>w.showLoginPrompt),{createConversation:qt,currentConversationId:Se,conversations:st,isLoading:bt,syncConversationFiles:ce,stopStreaming:ke,removeFileFromConversation:Ee}=we(),te=st.find(w=>w.id===Se),rt=te?te.messages.filter(w=>!(w.role==="assistant"&&w.isStreaming)).length:0,He=st.reduce((w,O)=>w+O.messages.filter(de=>!(de.role==="assistant"&&de.isStreaming)).length,0),ms=!!te&&le.maxMessagesPerConversation!==null&&rt>=le.maxMessagesPerConversation,lt=le.maxTotalMessages!==null&&He>=le.maxTotalMessages,gs=h.useCallback(()=>{Fe(w=>w+1)},[]),Bs=uc(),ss=fc(),{isListening:at,isSupported:Hs,startListening:Vs,stopListening:rs,error:Wt}=Vu(w=>{x(O=>{const de=O.length>0&&!/\s$/.test(O)?" ":"",me=(O+de+w).slice(0,le.maxMessageLength);return ae.current=me,me})},gs,{silenceTimeoutMs:Bs,language:ss||void 0}),xs=lc(),$t=cc(),ht=$t&&Hs,Rt=oc(),bs=Si(),qs=sf(te==null?void 0:te.adapterInfo),{skills:Kt,isLoading:Ws,selectedSkill:qe,selectSkill:ys,clearSkill:Gt}=c,Rr=(te==null?void 0:te.adapterName)||null,{suggestions:Pt,selectedIndex:Ye,setSelectedIndex:Pr,selectNext:Dr,selectPrevious:Ur,clearSuggestions:kt,focusInputAfterSelection:ws,suppressUntilQueryChange:ks}=Ku(g,{enabled:bs&&!at,apiUrl:te==null?void 0:te.apiUrl,adapterName:Rr,sessionId:te==null?void 0:te.sessionId,adapterSupportsAutocomplete:qs,skill:(qe==null?void 0:qe.name)||null,inputRef:Y}),as=Pt.length>0,$=!at,ye=$&&as&&!oe,q=g.startsWith("/")?g.slice(1):"",Ne=q.toLowerCase().replace(/-/g," "),Pe=Ne?Kt.filter(w=>w.name.replace(/-/g," ").toLowerCase().includes(Ne)||w.description.toLowerCase().includes(Ne)):Kt,Xt=Pe.length>0?Math.min(Tt,Pe.length-1):0,ct=Pe[Xt]??null,Or=(ct==null?void 0:ct.name.replace(/-/g," "))??"",ho=oe&&ct&&g.startsWith("/")&&Or.toLowerCase().startsWith(q.toLowerCase())&&Or.length>q.length?Or.slice(q.length):null,po=Ye>=0?Ye:0,vs=as?Pt[po]:null,za=h.useMemo(()=>{if(!vs)return null;const w=vs.text||"";if(!g)return w;const O=g;return w.toLowerCase().startsWith(O.toLowerCase())&&w.length>O.length?w.slice(O.length):null},[vs,g]),zr=ho??za,mo=g.trim().length===0&&!zr,go=h.useCallback(w=>{if(!g)return i.jsx("span",{className:"line-clamp-1 text-current",children:w});if(!w.toLowerCase().startsWith(g.toLowerCase()))return i.jsx("span",{className:"line-clamp-1 text-current",children:w});const O=w.slice(0,g.length),de=w.slice(g.length);return i.jsxs("span",{className:"line-clamp-1",children:[i.jsx("span",{className:"text-gray-500 dark:text-[#8e8ea0]",children:O}),i.jsx("span",{className:"font-semibold text-[#353740] dark:text-[#ececf1]",children:de})]})},[g]),Ba=h.useCallback(w=>{var O;ys(w),Ae(!1),x(""),kt(),Be(0),(O=Y.current)==null||O.focus()},[kt,ys]),xo=h.useCallback(()=>{var w;x("/"),Ae(!0),Be(0),(w=Y.current)==null||w.focus()},[]),Ha=h.useCallback(()=>{var w;Ae(!1),x(""),Be(0),(w=Y.current)==null||w.focus()},[]),Yt=h.useCallback(()=>{const w=Y.current;if(!w||typeof window>"u")return;const O=Ge=>{const Gr=Ge+fr,tr=Math.max(Ge-fr,0);w.style.paddingTop=`${Gr}px`,w.style.paddingBottom=`${tr}px`,ps({top:Gr,bottom:tr})},de=window.getComputedStyle(w),me=parseFloat(de.lineHeight||"0");if(!Number.isNaN(me)&&me>0?Mt(Ge=>Ge===me?Ge:me):Mt(Ge=>Ge===null?Ge:null),!me||Number.isNaN(me)){O(ur);return}const Ie=w.scrollHeight,We=w.clientHeight;if(Ie>me+2){O(ur);return}const Te=Math.max(We-me,0),Ve=Math.max(Te/2,0);O(Ve)},[]),bo=()=>{const w=Y.current;return w?w.selectionStart===w.selectionEnd&&w.selectionStart===g.length:!1},Va=(te==null?void 0:te.attachedFiles)||[],ns=Se?Va:b,yo=st.reduce((w,O)=>{var de;return w+(((de=O.attachedFiles)==null?void 0:de.length)||0)},0),qa=le.maxFilesPerConversation!==null&&le.maxFilesPerConversation>0&&Va.length>=le.maxFilesPerConversation,Wa=le.maxTotalFiles!==null&&yo>=le.maxTotalFiles,Ss=((en=te==null?void 0:te.adapterInfo)==null?void 0:en.isFileSupported)??!1,Br=ns.some(w=>w.processing_status?w.processing_status!=="completed"&&w.processing_status!=="error"&&w.processing_status!=="failed":!0),yt=Se?!!S[Se]:!1,Ks=Object.values(S).some(Boolean),Hr=g.trim().length>0,Ka=ms||lt,Ue=e||Br||yt||Ka,Ga=Rt&&Ss,Gs=qa||Wa,js=!Ga||Ue||Gs;h.useLayoutEffect(()=>{if(Y.current){const w=Y.current,O=120;w.style.height="auto";const de=w.scrollHeight;w.style.height=`${Math.min(de,O)}px`,w.style.overflowY=de>O?"auto":"hidden",Yt()}},[g,Yt]),h.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const w=Y.current;if(!w)return;const O=new ResizeObserver(()=>{Yt()});return O.observe(w),()=>{O.disconnect()}},[Yt]);const Xa=()=>{const w=document.activeElement;return w&&w.tagName==="TEXTAREA"},Xs=h.useCallback(()=>!r||typeof window>"u"?!1:window.matchMedia("(max-width: 767px)").matches,[r]);h.useEffect(()=>{Xs()||a&&!Ue&&Y.current&&!Xa()&&Y.current.focus()},[a,Ue,r,Xs]);const Vr=h.useRef(bt);h.useEffect(()=>{if(Xs()){Vr.current=bt;return}a&&Vr.current&&!bt&&!Ue&&Y.current&&setTimeout(()=>{Y.current&&!Xa()&&Y.current.focus()},100),Vr.current=bt},[a,bt,Ue,r,Xs]),h.useEffect(()=>{if(!ht||(K>je.current&&(ie.current=!0,je.current=K),!ie.current||K===0))return;const w=ae.current.trim(),O=we.getState();if(U("[MessageInput] Auto-send check after voice completion:",{hasMessage:!!w,isInputDisabled:Ue,isComposing:y,isLoading:O.isLoading}),ie.current=!1,!w)return;if(Ue||y){U("[MessageInput] Auto-send skipped because input is currently disabled or composing");return}const de=O.conversations.find(Oe=>Oe.id===O.currentConversationId),Ie=((de==null?void 0:de.attachedFiles)||[]).map(Oe=>Oe.file_id),We=qe==null?void 0:qe.name;U("[MessageInput] Auto-sending voice message immediately:",w),t(w,Ie.length>0?Ie:void 0,void 0,We),We&&Gt(),setTimeout(()=>{Ae(!1)},0),kt(),setTimeout(()=>{x("")},0),ae.current="",Y.current&&(Y.current.style.height="auto",Y.current.style.overflowY="hidden",Yt())},[ht,K,Ue,y,t,qe,Gt,Yt,kt]),h.useEffect(()=>{yt&&N&&setTimeout(()=>{R(!1)},0)},[yt,N]);const Ys=h.useCallback((w,O)=>{setTimeout(()=>{let de=we.getState(),me=O||de.currentConversationId;if(me||(me=qt(),de=we.getState(),me=de.currentConversationId||me),!me){xe("[MessageInput] Unable to sync files: conversation ID missing");return}const Ie=new Set(w.map(Oe=>Oe.file_id)),We=[];B.current.forEach((Oe,Te)=>{const[,...Ve]=Te.split("-"),Ge=Ve.join("-");Ie.has(Ge)||We.push(Te)}),We.forEach(Oe=>B.current.delete(Oe)),w.forEach(Oe=>{const Te=`${me}-${Oe.file_id}`;B.current.has(Te)||(B.current.add(Te),U(`[MessageInput] Adding file ${Oe.file_id} to conversation ${me}`),de.addFileToConversation(me,Oe))})},0)},[qt]);h.useEffect(()=>{if(Se!==re.current)if(re.current=Se||null,Se&&te){const w=te.attachedFiles||[];setTimeout(()=>{_(w.map(O=>({...O})))},0)}else setTimeout(()=>{_([])},0)},[Se,te]),h.useEffect(()=>{if(Se&&te){const w=te.attachedFiles||[];w.length>0?setTimeout(()=>{_(O=>{const de=new Set(O.map(Ie=>Ie.file_id)),me=w.filter(Ie=>!de.has(Ie.file_id));return me.length>0?(U(`[MessageInput] Syncing ${me.length} missing files from conversation to UI`),[...O,...me]):O})},0):w.length===0&&b.length>0&&setTimeout(()=>{_([])},0)}},[Se,te,st,b.length]);const qr=h.useRef(null),Wr=h.useRef(""),Qs=(te==null?void 0:te.attachedFiles)||[],Zs=Qs.length>0?`${Qs.length}:${Qs.map(w=>w.file_id).join("|")}`:"",Ya=Qs.some(w=>ra(w.processing_status));h.useEffect(()=>{if(!Se||!(te!=null&&te.adapterName))return;const w=Zs!=="";if(w&&(qr.current!==Se||Wr.current!==Zs)?(U(`[MessageInput] Syncing files for conversation ${Se}...`),qr.current=Se,Wr.current=Zs,ce(Se).catch(me=>{xe("[MessageInput] Failed to sync conversation files:",me)})):w||(qr.current=Se,Wr.current=""),!Ya)return;U("[MessageInput] Files still processing, starting poll...");const de=setInterval(async()=>{const Ie=we.getState().conversations.find(Te=>Te.id===Se);if(!Ie){clearInterval(de);return}if((Ie.attachedFiles||[]).filter(Te=>ra(Te.processing_status)).length===0){U("[MessageInput] All files completed processing, stopping poll"),clearInterval(de);return}try{await ce(Se)}catch(Te){xe("[MessageInput] Failed to poll file status:",Te)}},3e3);return()=>{clearInterval(de)}},[Se,te==null?void 0:te.adapterName,Zs,Ya,ce]),h.useEffect(()=>{setTimeout(()=>{I(w=>{const O=new Set(st.map(Ie=>Ie.id));let de=!1;const me={...w};return Object.keys(me).forEach(Ie=>{O.has(Ie)||(delete me[Ie],de=!0)}),de?me:w})},0)},[st]);const Qa=w=>{if(w.preventDefault(),Hr&&!Ue&&!y){at&&rs();const de=((te==null?void 0:te.attachedFiles)||[]).map(Ie=>Ie.file_id),me=qe==null?void 0:qe.name;t(g.trim(),de.length>0?de:void 0,void 0,me),me&&Gt(),Ae(!1),_s("messageSent",W.soundEnabled),x(""),ae.current="",_([]),R(!1),Y.current&&(Y.current.style.height="auto",Y.current.style.overflowY="hidden",Yt())}},Js=h.useCallback(w=>{if(!w||w.length===0)return;const O=w.length===1?p("messageInput.uploadSuccess.single",{filename:w[0].filename}):p("messageInput.uploadSuccess.multiple",{count:w.length});_s("success",W.soundEnabled),V(O),setTimeout(()=>{V(null)},6e3)},[W.soundEnabled,p]),wo=h.useCallback((w,O)=>{U(`[MessageInput] handleFilesSelected called with ${O.length} files for conversation ${w}:`,O),w&&(w===Se&&_(O),Ys(O,w))},[Se,Ys]),ko=h.useCallback((w,O)=>{w===Se&&Js(O)},[Se,Js]),vo=h.useCallback(w=>{se({isOpen:!0,fileId:w.file_id,filename:w.filename,isDeleting:!1})},[]),So=h.useCallback(()=>{se(w=>w.isDeleting?w:{isOpen:!1,fileId:"",filename:"",isDeleting:!1})},[]),jo=h.useCallback(async()=>{if(!(!Se||!z.fileId)){se(w=>({...w,isDeleting:!0}));try{await Ee(Se,z.fileId),_(w=>w.filter(O=>O.file_id!==z.fileId)),se({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}catch(w){const O=w instanceof Error?w.message:p("messageInput.fileRemoveFailed");xe("[MessageInput] Failed to remove file:",w),fe(O),se({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}}},[Se,z.fileId,Ee,p]),Za=h.useCallback(w=>w.replace(/\s+/g," ").trim(),[]),er=h.useCallback(w=>{const O=Za(w);x(O),kt(),ks(O),ws(O)},[kt,ws,Za,ks]),Kr=h.useCallback(w=>{if(w<0)return;const O=Pt[w]||Pt[0];O&&er(O.text)},[Pt,er]),Co=w=>{if(oe){if(w.key==="ArrowDown"){w.preventDefault(),Be(O=>Pe.length===0?0:(O+1)%Pe.length);return}if(w.key==="ArrowUp"){w.preventDefault(),Be(O=>Pe.length===0?0:(O-1+Pe.length)%Pe.length);return}if(w.key==="Home"){w.preventDefault(),Be(0);return}if(w.key==="End"){w.preventDefault(),Be(Math.max(Pe.length-1,0));return}if((w.key==="Enter"&&!w.shiftKey||w.key==="Tab")&&ct){w.preventDefault(),Ba(ct);return}if(w.key==="Escape"){w.preventDefault(),Ha();return}}if(as&&$){if(w.key==="ArrowDown"){w.preventDefault(),Dr();return}if(w.key==="ArrowUp"){w.preventDefault(),Ur();return}if(w.key==="Tab"){w.preventDefault();const O=Ye>=0?Ye:0;Kr(O);return}if(w.key==="ArrowRight"&&bo()){if(za&&vs){w.preventDefault(),er(vs.text);return}if(Ye>=0){w.preventDefault(),Kr(Ye);return}}if(w.key==="Enter"&&Ye>=0){w.preventDefault(),Kr(Ye);return}if(w.key==="Escape"){w.preventDefault(),kt();return}}w.key==="Enter"&&!w.shiftKey&&!y&&(w.preventDefault(),Qa(w))},Ao=()=>{at?rs():(kt(),Vs())},No=()=>{const w=!W.voiceEnabled;pe({voiceEnabled:w}),w&&Bt.enableAudio()},Io=h.useCallback(async w=>{if(!Rt||!A||!Ss||Ue)return;const O=w.clipboardData;if(!O||!O.items)return;const me=Array.from(O.items).filter(Te=>Te.kind==="file");if(me.length===0)return;const Ie=[];if(me.forEach((Te,Ve)=>{const Ge=Te.getAsFile();Ge&&Ie.push(lf(Ge,Ve))}),Ie.length===0)return;w.preventDefault(),G(null),V(null);let We=null;const Oe=new Set;try{const Te=we.getState(),Ve=Te.conversations.find(dt=>dt.id===Te.currentConversationId);if(((Ve==null?void 0:Ve.attachedFiles)||[]).length+Ie.length>le.maxFilesPerConversation)throw tt&&ot.getState().openLoginPrompt(p("fileUpload.maxFilesGuestLimitMessage",{count:le.maxFilesPerConversation})),new Error(p("fileUpload.maxFilesPerConversationError",{count:le.maxFilesPerConversation}));if(le.maxTotalFiles!==null&&Te.conversations.reduce((pt,It)=>{var Qe;return pt+(((Qe=It.attachedFiles)==null?void 0:Qe.length)||0)},0)+Ie.length>le.maxTotalFiles)throw tt&&ot.getState().openLoginPrompt(p("fileUpload.maxTotalFilesGuestLimitMessage",{count:le.maxTotalFiles})),new Error(p("fileUpload.maxTotalFilesError",{count:le.maxTotalFiles}));if(!Ve)throw new Error(p("messageInput.conversationNotFoundShort"));if(!Ve.adapterName)throw new Error(p("fileUpload.adapterNotConfigured"));const tr=ut(Ve.apiUrl),_o=Ve.adapterName;We=Ve.id,P(We,!0);const Cs=[],tn=[];for(let dt=0;dt<Ie.length;dt++){const pt=Ie[dt],It=pt.name||`Clipboard file ${dt+1}`,Qe=`${It}-${Date.now()}-${dt}`,As=pt.type.startsWith("image/")?URL.createObjectURL(pt):null;As&&Oe.add(As);let sn=null;F(nt=>{const Dt=new Map(nt);return Dt.set(Qe,{filename:It,progress:0,status:"uploading"}),Dt});const To=nt=>{nt.fileId&&!sn&&(sn=nt.fileId,As&&(Xi(nt.fileId,As),Oe.delete(As))),F(Dt=>{const mt=new Map(Dt),Ns=mt.get(Qe);return Ns&&mt.set(Qe,{...Ns,filename:It,progress:nt.progress,status:nt.status,fileId:nt.fileId}),mt})},Mo=()=>new Promise(nt=>{F(Dt=>{const mt=new Map(Dt),Ns=mt.get(Qe);return Ns&&mt.set(Qe,{...Ns,progress:100,status:"completed"}),mt}),setTimeout(()=>{F(Dt=>{const mt=new Map(Dt);return mt.delete(Qe),mt}),nt()},2500)});U(`[MessageInput] Pasting file: ${pt.name}, type: ${pt.type||"unknown"}, size: ${pt.size}`);const Fo=await Os.uploadFile(pt,nt=>{U(`[MessageInput] Paste upload progress for ${pt.name}: ${nt.progress}% - ${nt.status}`),To(nt)},void 0,tr,_o);Cs.push(Fo),tn.push(Mo())}if(Cs.length>0){let dt=Cs;if(We&&We===Se){const pt=new Set(b.map(Qe=>Qe.file_id)),It=Cs.filter(Qe=>!pt.has(Qe.file_id));It.length>0?(_(Qe=>[...Qe,...It]),dt=It):dt=[]}dt.length>0&&Ys(dt,We),await Promise.all(tn),Js(Cs)}}catch(Te){const Ve=Te instanceof Error?Te.message:"Failed to paste file";xe("[MessageInput] Paste error:",Te),_s("error",W.soundEnabled),G(Ve),Ve.toLowerCase().includes("maximum")&&fe(Ve),setTimeout(()=>{G(null)},5e3),F(new Map),Oe.forEach(Ge=>URL.revokeObjectURL(Ge))}finally{P(We,!1)}},[b,Se,A,Ss,tt,Ue,P,W.soundEnabled,Js,Ys,Rt,p]),Ja=sc(te==null?void 0:te.adapterName);let Nt;lt?Nt=tt?p("messageInput.placeholder.guestLimitTotal",{count:le.maxTotalMessages}):p("messageInput.placeholder.workspaceLimitTotal",{count:le.maxTotalMessages}):ms?Nt=tt?p("messageInput.placeholder.guestLimitPerConversation",{count:le.maxMessagesPerConversation}):p("messageInput.placeholder.conversationLimitReached",{count:le.maxMessagesPerConversation}):Br||yt?Nt=p("messageInput.placeholder.filesUploading"):Ja?Nt=Ja:Ga?Nt=p("messageInput.placeholder.messageOrbit"):Nt=s;const Qt=[];lt&&le.maxTotalMessages!==null&&(tt?Ft&&Qt.push(p("messageInput.limitWarning.guestTotalMessages",{count:le.maxTotalMessages})):Qt.push(p("messageInput.limitWarning.workspaceTotalMessages",{count:le.maxTotalMessages}))),ms&&le.maxMessagesPerConversation!==null&&(tt?Ft&&Qt.push(p("messageInput.limitWarning.guestPerConversation",{count:le.maxMessagesPerConversation})):Qt.push(p("messageInput.limitWarning.conversationLimitReached",{count:le.maxMessagesPerConversation}))),Z&&Qt.push(Z),h.useEffect(()=>{!$t||!Wt||_s("error",W.soundEnabled)},[$t,W.soundEnabled,Wt]),h.useEffect(()=>{if(!Z)return;const w=setTimeout(()=>fe(null),5e3);return()=>clearTimeout(w)},[Z]),h.useEffect(()=>{var w;(N||yt||M.size>0||Ks)&&((w=ee.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[N,yt,M.size,Ks]),h.useEffect(()=>{var w;ye&&((w=ue.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[ye]),h.useEffect(()=>{var w;oe&&((w=ve.current)==null||w.scrollIntoView({behavior:"smooth",block:"end"}))},[oe,Pe.length]);const Lo=o,Eo=n?"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 ${Eo}`,children:i.jsxs("div",{className:`mx-auto w-full ${Lo}`,children:[Wt&&$t&&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(ga,{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:Wt})]}),T&&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(ga,{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:T})]}),X&&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(zc,{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:X})]}),Qt.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(Fa,{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:Qt.map((w,O)=>i.jsx("li",{className:"text-sm text-amber-800 dark:text-amber-200",children:w},`${w}-${O}`))}),tt&&(Ka||Gs)&&Ft&&i.jsx("button",{type:"button",onClick:()=>ot.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:Qa,className:"flex w-full flex-col gap-2 md:gap-3",children:[i.jsxs("div",{className:`flex flex-row items-center gap-1.5 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 ${A?"border-gray-400 shadow-md dark:border-[#3a3a3a] dark:shadow-lg":"border-gray-300 dark:border-[#242424]"} bg-gray-50 dark:bg-[#111111]`,children:[qe&&i.jsxs("div",{className:"flex h-8 max-w-[45%] 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 sm:max-w-[38%] md:max-w-[32%]",children:[i.jsx(Ma,{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:qe.name.replace(/-/g," ")}),i.jsx("button",{type:"button",onClick:()=>{var w;Gt(),(w=Y.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"})})]}),!qe&&Kt.length>0&&g.length===0&&!Ue&&i.jsxs("button",{type:"button",onClick:xo,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":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",children:[mo&&Nt&&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(et.top-ef,0),paddingBottom:et.bottom,paddingLeft:`${sa}px`,paddingRight:0,lineHeight:xt?`${xt}px`:void 0},"aria-hidden":"true",children:Nt}),zr&&A&&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(et.top-tf,0),paddingBottom:et.bottom,paddingLeft:`${sa}px`,paddingRight:0,lineHeight:xt?`${xt}px`:void 0},"aria-hidden":"true",children:[i.jsx("span",{className:"invisible",children:g}),i.jsx("span",{children:zr})]}),i.jsx("textarea",{ref:Y,"aria-label":p("messageInput.textarea.ariaLabel"),value:g,onChange:w=>{const O=w.target.value;x(O),O.startsWith("/")&&Be(0),Ae(O.startsWith("/")&&Kt.length>0)},onKeyDown:Co,onPaste:Io,onCompositionStart:()=>k(!0),onCompositionEnd:()=>k(!1),onFocus:()=>L(!0),onBlur:()=>L(!1),placeholder:Nt,disabled:Ue,rows:1,maxLength:le.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:`${et.top}px`,paddingBottom:`${et.bottom}px`,paddingLeft:`${sa}px`,paddingRight:0,border:"none",outline:"none",boxShadow:"none",WebkitAppearance:"none",MozAppearance:"none",appearance:"none",caretColor:g.trim()||A?"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:[n&&!Rt&&i.jsx("div",{className:"hidden md:block h-8 w-8 shrink-0","aria-hidden":"true"}),Rt&&i.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),js||R(!N)},disabled:js,onMouseEnter:()=>j(!0),onMouseLeave:()=>j(!1),className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${N||ns.length>0?"bg-gray-200 text-[#353740] dark:bg-[#565869] dark:text-[#ececf1]":js?"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:Ss?Gs&&qa&&le.maxFilesPerConversation!==null?p("messageInput.fileUpload.titleLimitPerConversation",{count:le.maxFilesPerConversation}):Gs&&Wa&&le.maxTotalFiles!==null?p("messageInput.fileUpload.titleLimitWorkspace",{count:le.maxTotalFiles}):Ue?p("messageInput.fileUpload.titleUploading"):ns.length>0?p("messageInput.fileUpload.titleAttached",{count:ns.length}):p("messageInput.fileUpload.attachAriaLabel"):p("messageInput.fileUpload.titleNotSupported"),"aria-label":p("messageInput.fileUpload.attachAriaLabel"),children:js&&H?i.jsx(Je,{className:"h-4 w-4"}):i.jsx(id,{className:"h-4 w-4"})}),g.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:g.length>=le.maxMessageLength?"text-red-600 font-semibold":"",children:[g.length,"/",le.maxMessageLength]})})]}),i.jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[i.jsx(eo,{availableModels:d,defaultModel:u,selectedModel:f,onSelect:w=>m==null?void 0:m(w)}),(xs||$t)&&i.jsxs(i.Fragment,{children:[xs&&i.jsx("button",{type:"button",onClick:No,className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${W.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:W.voiceEnabled?p("messageInput.voiceOutput.titleEnabled"):p("messageInput.voiceOutput.titleDisabled"),"aria-label":W.voiceEnabled?p("messageInput.voiceOutput.ariaLabelEnabled"):p("messageInput.voiceOutput.ariaLabelDisabled"),children:W.voiceEnabled?i.jsx($a,{className:"h-5 w-5"}):i.jsx(gd,{className:"h-5 w-5"})}),ht&&i.jsx("button",{type:"button",onClick:Ao,disabled:Ue,onMouseEnter:()=>D(!0),onMouseLeave:()=>D(!1),className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${at?"!flex bg-red-100 text-red-600 dark:bg-red-900/40 dark:text-red-300":Ue?"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(Ue?"messageInput.voiceInput.titleUploading":at?"messageInput.voiceInput.titleListening":"messageInput.voiceInput.titleDisabled"),"aria-label":p(at?"messageInput.voiceInput.ariaLabelListening":"messageInput.voiceInput.ariaLabelDisabled"),children:at||Ue&&E?i.jsx(Jc,{className:"h-5 w-5"}):i.jsx(ed,{className:"h-5 w-5"})})]}),l&&i.jsx("button",{type:"button",onClick:()=>v(!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(jn,{className:"h-5 w-5"})}),(Br||yt)&&i.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center",children:i.jsx(Fi,{className:"h-4 w-4 animate-spin text-gray-500 dark:text-[#bfc2cd]"})}),bt?i.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),ke()},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(fd,{className:"h-4 w-4 md:h-3 md:w-3 fill-current"})}):i.jsx("button",{type:"submit",disabled:!Hr||Ue||y,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 ${Hr&&!Ue&&!y?"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(ma,{className:"h-4 w-4"})})]})]})]}),ns.length>0&&i.jsx("div",{className:"flex flex-wrap gap-2",children:ns.map(w=>{const O=ra(w.processing_status),de=w.processing_status==="failed"||w.processing_status==="error",me=de?"error":O?w.processing_status==="uploading"?"uploading":"processing":"completed",Ie=O?w.processing_status==="uploading"?p("messageInput.attachedFile.uploadingStatus"):p("messageInput.attachedFile.processingStatus"):void 0;return i.jsx(Ar,{filename:w.filename,fileId:w.file_id,status:me,statusText:Ie,errorMessage:de?w.error_message||p("messageInput.fileProcessingFailedTitle"):void 0,onRemove:()=>{de?(Se&&Ee(Se,w.file_id),_(We=>We.filter(Oe=>Oe.file_id!==w.file_id))):vo(w)},removeTitle:p(de?"messageInput.attachedFile.removeTitleFailed":"messageInput.attachedFile.removeTitleNormal")},w.file_id)})}),Rt&&(Ss||Ks)&&i.jsxs("div",{ref:ee,className:`rounded-lg border border-gray-200/80 bg-white p-2.5 dark:border-[#3c3f4a] dark:bg-[#2a2b32] transition-all duration-200 ${!N&&!yt&&M.size===0&&!Ks?"hidden":""}`,children:[N&&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:()=>R(!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"})})]}),(yt||M.size>0)&&!N&&M.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")})}),M.size>0&&i.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:Array.from(M.entries()).map(([w,O])=>i.jsx(Ar,{filename:O.filename,fileId:O.fileId,status:O.status,statusText:O.status==="uploading"?p("messageInput.uploadProgress.statusUploading"):O.status==="processing"?p("messageInput.uploadProgress.statusProcessing"):O.status==="completed"?p("messageInput.uploadProgress.statusCompleted"):void 0,errorMessage:O.error},w))}),i.jsx("div",{className:`${N||yt?"block max-h-[40vh] overflow-y-auto":"hidden"}`,"aria-hidden":!(N||yt),children:i.jsx(Ju,{conversationId:Se,onFilesSelected:wo,onUploadError:w=>{xe("File upload error:",w),fe(w)},onUploadingChange:P,onUploadSuccess:ko,maxFiles:le.maxFilesPerConversation,disabled:js})})]}),i.jsx("div",{className:"h-3 md:h-1",children:ht&&at&&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")]})})]}),oe&&i.jsx("div",{ref:ve,className:"w-full pt-1",children:i.jsx(Ji,{skills:Kt,isLoading:Ws,selectedSkill:qe,activeSkillName:ct==null?void 0:ct.name,query:q,onActiveSkillChange:w=>{const O=Pe.findIndex(de=>de.name===w.name);O>=0&&Be(O)},onSelect:Ba,onClose:Ha})}),ye&&i.jsx("div",{ref:ue,role:"listbox","aria-label":p("messageInput.autocompletePanel.ariaLabel"),className:"w-full pt-1",children:Pt.map((w,O)=>{const de=O===Ye;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:()=>er(w.text),onMouseEnter:()=>Pr(O),children:go(w.text)},O)})}),i.jsx(vr,{isOpen:z.isOpen,onClose:So,onConfirm:jo,title:p("messageInput.fileDelete.title"),message:p("messageInput.fileDelete.message",{filename:z.filename}),confirmText:p("messageInput.fileDelete.confirmText"),cancelText:p("common.cancel"),type:"danger",isLoading:z.isDeleting})]})]})}),C&&l&&typeof document<"u"&&Ir.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:J,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(jn,{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:()=>v(!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:l,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 ${Me}`,syntaxTheme:Ce})}),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:()=>v(!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 Jn({adapter:t,onSelect:e}){var l;const{t:s}=Le(),a=(l=t.description)==null?void 0:l.trim(),{isDark:r}=ts(),n=r?"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}),a?i.jsx("div",{className:"mt-1 text-sm leading-5 text-slate-600 dark:text-slate-300",children:i.jsx(_t,{content:a,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:n})}):i.jsx("p",{className:"mt-1 text-sm leading-5 text-slate-500 dark:text-slate-400",children:s("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":s("agentCard.startConversationAriaLabel",{name:t.name}),children:i.jsx(Sn,{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":s("agentCard.startConversationAriaLabel",{name:t.name}),children:i.jsx(Sn,{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},cf=t=>{if(!t||typeof t!="object")return null;const e=t,s=Zt(e.name);if(!s)return null;const a=Zt(e.id);if(!a)return console.warn(`[middlewareConfig] Adapter "${s}" is missing a required 'id' field — skipping.`),null;const r=Zt(e.apiUrl),n=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:a,name:s};return r&&(d.apiUrl=r),c&&(d.description=c),l&&(d.notes=l),n&&(d.model=n),o&&(d.inputPlaceholder=o),d},so=t=>Array.isArray(t)?t.map(cf).filter(e=>e!==null):[];let Ot=null,aa=0;const df=3e4;function uf(){if(typeof window<"u"){const t=window.ORBIT_CHAT_CONFIG;if(t!=null&&t.adapters&&Array.isArray(t.adapters)){U("Loading adapters from window.ORBIT_CHAT_CONFIG");const e=so(t.adapters);if(e.length===0)return null;const s=`{
347
347
  "simple-chat": "default-key",
348
348
  "dialoga": "orbit_GOQzNNaC9uB0uNh5LrOCdlmPI0OHXnMz",
349
349
  "web-search": "orbit_XfxmYoTZgnp7zoMTKsIBfMBuYwj6U21P",
@@ -372,5 +372,5 @@ $$
372
372
  "award-notices": "award-notices",
373
373
  "contract-history": "contract-history",
374
374
  "standing-offers": "standing-offers"
375
- }`;if(!s.trim())return[];try{const a=JSON.parse(s),r=new Set(Object.entries(a).filter(([,n])=>{if(typeof n=="string")return n.trim().length>0;if(n&&typeof n=="object"){const o=n;if(typeof o.apiKey=="string"&&o.apiKey.trim().length>0||typeof o.key=="string"&&o.key.trim().length>0)return!0}return!1}).map(([n])=>n));return e.filter(n=>r.has(n.id))}catch{return[]}}}return null}async function Da(){if(Ot&&Date.now()-aa<df)return Ot;try{const e=await fetch("/api/adapters?refresh=1",{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(e.ok){const s=await e.json(),a=so(s.adapters);if(a.length>0)return Ot=a,aa=Date.now(),D("Fetched adapters from /api/adapters:",Ot),Ot;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=uf();if(t&&t.length>0)return Ot=t,aa=Date.now(),D("Loaded adapters from config:",Ot),Ot;throw ge("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 ff="h-[96px]";function hf({onAdapterSelect:t,className:e="",title:s="",subtitle:a="",eyebrow:r=""}){const{t:n}=Ee(),[o,l]=h.useState([]),[c,d]=h.useState(!0),[u,f]=h.useState(null),m=h.useRef(null),p=h.useRef(null),[g,x]=h.useState(""),[y,k]=h.useState(!1),A=h.useCallback(()=>{const j=m.current;if(!j){k(!1);return}k(j.scrollHeight-j.scrollTop-j.clientHeight>20)},[]),L=()=>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"]'))??[])},v=j=>{const P=C()[j]??null;P&&(P.focus(),P.scrollIntoView({block:"nearest"}))},N=()=>{v(0)},R=()=>{const j=C();j.length!==0&&v(j.length-1)},b=j=>{if(!c&&!u&&I.length>0&&L()){if(j.key==="Tab"&&!j.shiftKey){j.preventDefault(),N();return}if(j.key==="ArrowDown"){j.preventDefault(),N();return}j.key==="ArrowUp"&&(j.preventDefault(),R())}},_=j=>{var K;if(!M||!L()||j.key!=="ArrowDown"&&j.key!=="ArrowUp")return;const E=document.activeElement;if(!(E instanceof HTMLElement)||E.dataset.agentCard!=="true")return;const P=C(),T=P.indexOf(E);if(T!==-1){if(j.preventDefault(),j.key==="ArrowDown"){v((T+1)%P.length);return}if(T===0){(K=p.current)==null||K.focus();return}v(T-1)}},S=g.trim().toLowerCase(),I=S?o.filter(j=>{var K,G;const E=j.name.toLowerCase().includes(S),P=((K=j.description)==null?void 0:K.toLowerCase().includes(S))??!1,T=((G=j.model)==null?void 0:G.toLowerCase().includes(S))??!1;return E||P||T}):o,M=g.trim().length>0,F=M||I.length===1;h.useEffect(()=>{const j=m.current;if(j)return A(),j.addEventListener("scroll",A,{passive:!0}),()=>j.removeEventListener("scroll",A)},[A,I]),h.useEffect(()=>{let j=!0;return(async()=>{try{d(!0),f(null);const T=(await Da()).slice().sort((K,G)=>K.name.localeCompare(G.name,void 0,{sensitivity:"base"}));j&&l(T)}catch(P){ge("[AgentSelectionList] Failed to load adapters",P),j&&f(n("agentSelectionList.unableToLoad"))}finally{j&&d(!1)}})(),()=>{j=!1}},[n]),h.useEffect(()=>{var j;c||u||o.length===0||(j=p.current)==null||j.focus()},[c,u,o.length]);const B=()=>c?i.jsx("div",{className:"grid gap-4",children:Array.from({length:3}).map((j,E)=>i.jsx("div",{className:`${ff} animate-pulse rounded-2xl border border-gray-200 bg-transparent dark:border-[#3b3c49]`},E))}):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:n("agentSelectionList.noAgentsAvailable")}):I.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:n("agentSelectionList.noSearchResults")}):i.jsxs("div",{className:"relative flex flex-col h-full min-h-0",children:[i.jsx("div",{ref:m,onKeyDown:_,className:"agent-selection-scroll flex-1 min-h-0 overflow-y-auto pr-1 pb-2",children:F?i.jsx("div",{className:"mx-auto flex w-full max-w-xl flex-col gap-3 lg:max-w-2xl",children:I.map(j=>i.jsx(Jn,{adapter:j,onSelect:E=>t(E.id)},j.id))}):i.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:I.map(j=>i.jsx(Jn,{adapter:j,onSelect:E=>t(E.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:[(r||s||a)&&i.jsxs("div",{className:"flex-shrink-0",children:[r&&i.jsx("p",{className:"text-sm font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-300",children:r}),s&&i.jsx("h2",{className:"mt-2 text-2xl font-bold text-gray-900 dark:text-white",children:s}),a&&i.jsx("p",{className:"mt-2 text-base text-gray-600 dark:text-gray-300",children:a})]}),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(Ta,{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:p,type:"text",placeholder:n("agentSelectionList.searchPlaceholder"),value:g,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"}),g&&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":n("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:B()})]})}function Sa(){return Ea()?Tr()==="entra"?i.jsx(mf,{}):i.jsx(pf,{}):null}function pf(){const{user:t,logout:e,loginWithRedirect:s}=Aa();if(!hs()||!t)return i.jsx(ro,{onClick:()=>s()});const r=t.name||t.email||"User";return i.jsx(ao,{displayName:r,onClick:()=>e({logoutParams:{returnTo:window.location.origin}})})}function mf(){const{instance:t,accounts:e}=Ca();if(!hs()||e.length===0)return i.jsx(ro,{onClick:()=>t.loginRedirect({scopes:_a()}).catch(()=>{})});const a=e[0],r=a.name||a.username||"User";return i.jsx(ao,{displayName:r,onClick:()=>t.logoutRedirect({postLogoutRedirectUri:window.location.origin}).catch(()=>{})})}function ro({onClick:t}){const{t:e}=Ee();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($i,{className:"h-4 w-4"}),i.jsx("span",{children:e("common.signIn")})]})}function ao({displayName:t,onClick:e}){const{t:s}=Ee();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:s("authStatus.signOutButton.title"),"aria-label":s("authStatus.signOutButton.ariaLabel"),children:[i.jsx(Yc,{className:"h-4 w-4"}),i.jsx("span",{className:"hidden md:inline",children:s("common.logOut")})]})]})}function no({placement:t="default",compact:e=!1}){const{t:s}=Ee();if(!Ni())return null;const a=Ac(),r=Nc(),n=Ic(),o=Lc(),l=Ec(),c=_c(),d=Mc(),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",p="justify-center",g=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:r||void 0,color:n||void 0},children:i.jsx("div",{className:g,children:i.jsx("div",{className:x,children:i.jsxs("div",{className:m,children:[a&&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:a}),d.length>0&&i.jsx("nav",{"aria-label":s("appFooter.navLinksAriaLabel"),children:i.jsx("ul",{className:`flex flex-wrap items-center ${p} ${e?"gap-1":"gap-1.5 sm:gap-2"}`,children:d.map((k,A)=>{const L=l==="inline"&&A>0;return i.jsxs("li",{className:"flex items-center",children:[L&&i.jsx("span",{className:"mr-1.5 text-slate-400 dark:text-slate-500","aria-hidden":"true",children:"·"}),i.jsx("a",{href:k.url,target:"_blank",rel:"noopener noreferrer",className:y,style:{color:n||void 0},children:k.label})]},k.url)})})})]})})})})}const gf=60*1e3;let na=null,ei=0;const ia=t=>{if(!t||t==="/")return"/";const e=t.trim();if(!e)return"/";const s=e.startsWith("/")?e:`/${e}`;return s==="/"?"/":s.endsWith("/")?s.slice(0,-1):s},io=()=>{if(typeof window>"u")return ia("/");const t=ia("/");if(typeof document>"u")return t;const e=document.querySelector("base[href]");if(!e)return t;try{const s=new URL(e.getAttribute("href")||"/",window.location.origin);return ia(s.pathname||t)}catch{return t}},Nr=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),xf=async()=>{const t=Date.now();if(na&&t-ei<gf)return na;let e=[];try{e=await Da()}catch(a){me("[agentRouting] Unable to load adapters for slug resolution",a)}const s=new Map;return e.forEach(a=>{const r=Nr(a.name);r&&s.set(r,a.id);const n=Nr(a.id);n&&n!==r&&s.set(n,a.id)}),na=s,ei=t,s},ja=t=>{var n;const e=io(),s=t.startsWith("/")?t:`/${t}`;let a=s;if(e!=="/"){if(!s.startsWith(e))return null;a=s.slice(e.length)}const r=a.split("/").filter(Boolean);return r.length===0?null:((n=r[0])==null?void 0:n.toLowerCase())||null},oo=t=>{const e=io();if(!t)return e;const s=t.replace(/^\/+|\/+$/g,"");return e==="/"?s?`/${s}`:"/":`${e}/${s}`.replace(/\/{2,}/g,"/")},St=t=>{if(typeof window>"u")return;const e=oo(t),s=window.location.pathname;if(e===s)return;const a=window.location.search||"",r=window.location.hash||"";window.history.replaceState(window.history.state,"",`${e}${a}${r}`)},bf=()=>oo(null),yf=async t=>{const e=t.trim().toLowerCase();return e&&(await xf()).get(e)||null};function wf({currentConversation:t,showEmptyState:e,createConversation:s,configureApiSettings:a,clearError:r,clearCurrentConversationAdapter:n}){var Ae;const{t:o}=Ee(),l=o("agent.error.singleAdapterMissing"),[c,d]=h.useState(!1),[u,f]=h.useState(null),m=_r(),p=Na(),g=typeof window<"u"?ja(window.location.pathname):null,[x,y]=h.useState(g),[k,A]=h.useState(()=>!m&&e&&!g),L=h.useRef(null),C=h.useRef(new Map),v=h.useRef(0),N=3e4,R=!!t,b=(t==null?void 0:t.messages.length)??0,_=((Ae=t==null?void 0:t.attachedFiles)==null?void 0:Ae.length)??0,S=h.useMemo(()=>R&&(b>0||_>0),[_,b,R]),I=h.useCallback(()=>{Ke(()=>ke.getState())},[]),M=h.useCallback((H,J)=>{if(!H)return;const W=J||o("agent.error.configurationFailed");let ye=!1;ke.setState(ne=>{const X=ne.conversations.find(xe=>xe.id===H);return!X||X.messages.length>0?ne:(ye=!0,{conversations:ne.conversations.map(xe=>xe.id===H?{...xe,adapterLoadError:W}:xe)})}),ye&&I()},[I,o]),F=h.useCallback(H=>{if(!H)return;let J=!1;ke.setState(W=>{const ye=W.conversations.find(ne=>ne.id===H);return!ye||!ye.adapterLoadError?W:(J=!0,{conversations:W.conversations.map(ne=>ne.id===H?{...ne,adapterLoadError:null}:ne)})}),J&&I()},[I]),B=h.useCallback(H=>H instanceof Wi?H.status===401?o("agent.error.authenticationFailed"):H.status===404?o("agent.error.notFound"):H.message:H instanceof Error?H.message:o("agent.error.loadFailed"),[o]),j=h.useCallback(()=>{const H=ke.getState(),J=H.currentConversationId?H.conversations.find(W=>W.id===H.currentConversationId):null;if(!J||J.messages.length>0)try{return s()}catch(W){me("Cannot create a new conversation for agent selection:",W instanceof Error?W.message:"Unknown error")}return(J==null?void 0:J.id)||null},[s]),E=h.useCallback(async H=>{if(!(H!=null&&H.adapterName))return{ok:!1};try{const J=await Me(),W=new J.ApiClient({apiUrl:H.apiUrl||Fe(),sessionId:null,adapterName:H.adapterName});if(typeof W.getAdapterInfo!="function")return{ok:!1};const ye=await W.getAdapterInfo();return ke.setState(ne=>({conversations:ne.conversations.map(X=>X.id===H.id?{...X,adapterInfo:ye,adapterLoadError:null,updatedAt:new Date}:X)})),ke.getState().currentConversationId===H.id&&f(null),I(),{ok:!0}}catch(J){const W=B(J),ye=ke.getState();ye.currentConversationId===H.id&&f({conversationId:H.id,message:W});const ne=ye.conversations.find(X=>X.id===H.id);return ne&&ne.messages.length===0&&M(H.id,W),{ok:!1,error:J}}},[B,M,I]),P=h.useCallback(async H=>{if(!H)return;const J=ke.getState(),W=J.currentConversationId?J.conversations.find(ye=>ye.id===J.currentConversationId):null;if(W){d(!0),f(null),F(W.id);try{const ye=W.apiUrl||Fe();await a(ye,void 0,H),r();const ne=ke.getState(),X=ne.conversations.find(xe=>xe.id===ne.currentConversationId);if((X==null?void 0:X.adapterName)===H&&(!X.adapterInfo||X.adapterInfo.notes===void 0)){const xe=await E(X);!xe.ok&&xe.error&&ge("Failed to load adapter info after selecting adapter:",xe.error)}}catch(ye){ge("Failed to configure adapter from empty state:",ye);const ne=B(ye);f({conversationId:W.id,message:ne}),M(W.id,ne)}finally{d(!1)}}},[F,r,a,E,B,M]),T=h.useCallback(H=>{m||(j(),A(!1),St(Nr(H)),P(H))},[j,P,m]),K=h.useCallback(()=>{m||(n(),St(null),A(!0))},[n,m]),G=h.useCallback(()=>{var ye,ne;if(m){const X=ke.getState(),xe=X.currentConversationId?X.conversations.find(oe=>oe.id===X.currentConversationId):null;if(!!xe&&(xe.messages.length>0||(((ye=xe.attachedFiles)==null?void 0:ye.length)||0)>0))try{s()}catch(oe){me("Cannot go home (new conversation):",oe instanceof Error?oe.message:"Unknown error")}St(null),A(!1);return}y(null);const H=ke.getState(),J=H.currentConversationId?H.conversations.find(X=>X.id===H.currentConversationId):null;if(!!J&&(J.messages.length>0||(((ne=J.attachedFiles)==null?void 0:ne.length)||0)>0))try{s()}catch(X){me("Cannot go home (new conversation):",X instanceof Error?X.message:"Unknown error");return}else J!=null&&J.adapterName&&n();St(null),A(!0)},[n,s,m]),Z=!m&&e&&!x&&!(t!=null&&t.adapterName)&&!S||!m&&e&&k&&!(t!=null&&t.adapterName)&&!S;h.useEffect(()=>{if(m){St(null);return}if(!x){if(Z||!(t!=null&&t.adapterName)){St(null);return}St(Nr(t.adapterName))}},[t==null?void 0:t.adapterName,m,x,Z]);const ue=h.useCallback(async()=>{if(typeof window>"u")return;const H=++v.current;if(m){St(null),y(null);return}const J=ja(window.location.pathname);if(!J)return;const W=await yf(J);if(H===v.current){if(!W){j(),St(null),n(),A(!0),y(null);return}j(),A(!1),St(J),await P(W),y(null)}},[n,j,P,m]),O=h.useRef(ue);h.useEffect(()=>{O.current=ue},[ue]),h.useEffect(()=>{const H=window.setTimeout(()=>{O.current()},0),J=()=>{O.current()};return window.addEventListener("popstate",J),()=>{window.clearTimeout(H),v.current+=1,window.removeEventListener("popstate",J)}},[]);const te=t==null?void 0:t.id,Y=t==null?void 0:t.adapterName,ee=t==null?void 0:t.apiUrl,re=!!(t!=null&&t.adapterInfo);h.useEffect(()=>{if(!m||!p||!e||!te||S||c)return;const H=(Y==null?void 0:Y.trim())||p,J=(Y==null?void 0:Y.trim())!==H||!re;if(!H||!J)return;let W=!1;return(async()=>{d(!0),f(null),F(te);try{const ne=ee||Fe();await a(ne,void 0,H),r()}catch(ne){if(!W){const X=B(ne);f({conversationId:te,message:X}),M(te,X)}}finally{W||d(!1)}})(),()=>{W=!0}},[F,r,a,S,B,c,m,M,e,Y,ee,re,te,p]),h.useEffect(()=>{(async()=>{var ne;const J=t==null?void 0:t.adapterName,W=t?`${t.id}:${J}`:null;if(!W||L.current===W)return;const ye=!(t!=null&&t.adapterInfo)||(t==null?void 0:t.adapterInfo)&&t.adapterInfo.notes===void 0;if(J&&ye){L.current=W,D("[ChatInterface] Loading adapter info - adapterName:",J,"reason:",t!=null&&t.adapterInfo?"notes undefined":"missing");const X=await E(t);if(X.ok)D("[ChatInterface] Adapter info loaded successfully");else{const xe=X.error;ge("[ChatInterface] Failed to load adapter info:",xe);const Ce=xe instanceof Error?xe.message:String(xe);if((Ce.includes("429")||Ce.includes("Too Many Requests"))&&J){const ve=C.current.get(W);ve&&clearTimeout(ve);const $e=setTimeout(()=>{L.current===W&&(L.current=null),C.current.delete(W)},N);C.current.set(W,$e),me(`[ChatInterface] Adapter info request rate-limited; retrying in ${N/1e3}s`)}else L.current=null}}else D("[ChatInterface] Skipping adapter info load:",{adapterName:J,hasAdapterInfo:!!(t!=null&&t.adapterInfo),hasNotes:((ne=t==null?void 0:t.adapterInfo)==null?void 0:ne.notes)!==void 0,refValue:L.current})})()},[E,t]),h.useEffect(()=>{const H=C.current;return()=>{H.forEach(J=>clearTimeout(J)),H.clear()}},[]);const fe=m&&!p?l:(t==null?void 0:t.adapterLoadError)??(u&&u.conversationId===(t==null?void 0:t.id)?u.message:null);return{adapterNotesError:fe,handleAgentCardSelection:T,handleChangeAgent:K,goToAgentSelectionHome:G,hasAdapterConfigurationError:!!fe,isAgentSelectionVisible:k,isConfiguringAdapter:c,isSingleAdapterMode:m,setIsAgentSelectionVisible:A,shouldShowAgentSelectionList:Z}}const lo=h.createContext(null),kf={registerGoHome:()=>{},goHome:()=>{}};function co(){return h.useContext(lo)??kf}function vf({adapter:t,syntaxTheme:e,forcedThemeClass:s=""}){var r;const a=(r=t.notes)==null?void 0:r.trim();return a?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:a,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 ${s}`,syntaxTheme:e})})]}):null}const Sf='meta[name="description"]',jf='meta[property="og:title"]',Cf='meta[property="og:description"]',Af='meta[property="og:type"]',Nf='link[rel="canonical"]';function ti(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function If(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 Lf(t,e){const s=t==null?void 0:t.trim();if(s)return s;if(!e)return La();const a=If(e);return a.length>160?`${a.slice(0,157).trimEnd()}...`:a}function Ef(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 Tf(t){const e=t.trim();if(!e)return null;const s=`^${Ef(e).replace(/\\\*/g,".*")}$`;try{return new RegExp(s,"i")}catch{return null}}function Mf(t){return[vi(),...rc()].map(_f).filter(s=>!!s).includes(t)?!0:ac().some(s=>{const a=Tf(s);return a?a.test(t):!1})}function Ff(t){var a,r,n;const e=t==null?void 0:t.trim();if(!e)return null;const s=Q.adapters.find(o=>{var l;return((l=o==null?void 0:o.id)==null?void 0:l.trim())===e});return s?{id:s.id,name:((a=s.name)==null?void 0:a.trim())||s.id,description:((r=s.description)==null?void 0:r.trim())||void 0,notes:((n=s.notes)==null?void 0:n.trim())||void 0}:null}function $f(t){var a,r,n;if(typeof window>"u")return null;const e=ja(window.location.pathname);if(!e)return null;const s=Q.adapters.find(o=>{const l=ti(o.name||""),c=ti(o.id||"");return e===l||e===c});return s?{id:s.id,name:((a=s.name)==null?void 0:a.trim())||s.id,description:((r=s.description)==null?void 0:r.trim())||void 0,notes:((n=s.notes)==null?void 0:n.trim())||void 0}:null}function hr(t,e,s){if(typeof document>"u")return null;const a=document.querySelector(t);if(a)return a;const r=document.createElement("meta");return r.setAttribute(e,s),document.head.appendChild(r),r}function Rf(){if(typeof document>"u")return null;const t=document.querySelector(Nf);if(t)return t;const e=document.createElement("link");return e.rel="canonical",document.head.appendChild(e),e}function uo(t){if(typeof document>"u")return;const e=Ia(),s=t?`${t.name} | ${e}`:e,a=t?Lf(t.description,t.notes):La();document.title=s;const r=hr(Sf,"name","description");r&&(r.content=a);const n=hr(jf,"property","og:title");n&&(n.content=s);const o=hr(Cf,"property","og:description");o&&(o.content=a);const l=hr(Af,"property","og:type");l&&(l.content="website");const c=Rf();if(c&&typeof window<"u"){const d=vi(),u=window.location.origin,f=d?new URL(d.endsWith("/")?d:`${d}/`).origin:"",p=`${u&&Mf(u)?u:f||u}${window.location.pathname}`;c.href=p}}function Pf(){return nc()}class Ua{static async getAdapterModels(e,s){const a=await Me(),r=new a.ApiClient({apiUrl:"",adapterName:s});if(!r.getAdapterModels)throw new Error("getAdapterModels is not available on this API client");return r.getAdapterModels(e)}static async getAllModels(e){const s=await Me(),a=new s.ApiClient({apiUrl:"",adapterName:e});if(!a.getAllModels)throw new Error("getAllModels is not available on this API client");return a.getAllModels()}static async listAdapterModels(e,s){return(await Ua.getAdapterModels(e,s)).models}}const Df="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",Uf="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",Of="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 zf({onOpenSettings:t,onOpenSidebar:e}){var Vt,tt,Ft,qt,je,st,bt;const{t:s}=Ee(),{conversations:a,currentConversationId:r,createConversation:n,canCreateNewConversation:o,sendMessage:l,regenerateResponse:c,editMessageAndRegenerate:d,isLoading:u,configureApiSettings:f,error:m,clearError:p,createThread:g,clearCurrentConversationAdapter:x}=ke(),{settings:y}=Lr(),k=hs(),A=it()&&!k,{theme:L,isDark:C}=ts(),v=L.mode==="dark"?"dark":L.mode==="light"?"light":"",N=C?"dark":"light",R=["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",v].filter(Boolean).join(" "),b=a.find(ce=>ce.id===r),_=a.some(ce=>{var Se;return(ce.messages.length>0||(((Se=ce.attachedFiles)==null?void 0:Se.length)||0)>0)&&!ce.adapterLoadError}),S=!b||b.messages.length===0,I=((Vt=b==null?void 0:b.adapterInfo)==null?void 0:Vt.supportsThreading)===!0,M=!!(b!=null&&b.adapterName&&(b!=null&&b.adapterInfo))&&!I,F=Ki({adapterName:b==null?void 0:b.adapterName,enabled:M,selectionScopeKey:r,supportsThreading:I}),B=ki(),j=Ia(),E=La().trim(),P=E.length>0,{registerGoHome:T}=co(),[K,G]=h.useState([]),[V,Z]=h.useState(null);h.useEffect(()=>{const ce=b==null?void 0:b.adapterName;let Se=!1;async function _e(){if(Z(null),!ce){G([]);return}try{const se=await Ua.listAdapterModels(ce,ce);if(Se)return;G(se),Z(se.length>0?se[0].name:null)}catch{Se||(G([]),Z(null))}}return _e(),()=>{Se=!0}},[b==null?void 0:b.adapterName]);const{adapterNotesError:ue,handleAgentCardSelection:O,handleChangeAgent:te,goToAgentSelectionHome:Y,hasAdapterConfigurationError:ee,isAgentSelectionVisible:re,isConfiguringAdapter:fe,isSingleAdapterMode:Ae,shouldShowAgentSelectionList:H}=wf({currentConversation:b,showEmptyState:S,createConversation:n,configureApiSettings:f,clearError:p,clearCurrentConversationAdapter:x});h.useLayoutEffect(()=>(T(()=>Y()),()=>T(null)),[T,Y]);const J="max-w-[96rem]",W="max-w-[64rem]",ye="max-w-[56rem]",ne=`mx-auto w-full ${J}`,X=o(),xe=!!(b!=null&&b.adapterName)&&((b==null?void 0:b.messages.length)||0)===0,Ce=s(X?"chatInterface.newConversation.tooltipCanStart":A?"chatInterface.newConversation.tooltipGuestLimited":"chatInterface.newConversation.tooltipCannotStart"),oe=!!(b&&!H),ve=H?"border-transparent dark:border-transparent md:border-transparent md:dark:border-transparent":"",$e=!pa()&&H?"pt-0 pb-0 md:pt-0 md:pb-1":"",ie=`${Of} ${ve} ${$e}`.trim(),Be=Ni(),be=a.some(ce=>{var Se;return(ce.messages.length>0||(((Se=ce.attachedFiles)==null?void 0:Se.length)??0)>0)&&!ce.adapterLoadError}),Ne=Be&&!be,Tt=H?"pt-0 md:pt-0":"pt-4 md:pt-6",ze=h.useMemo(()=>{var se,rt,He;if(H)return null;const ce=Ff(b==null?void 0:b.adapterName)||$f();if(!ce&&!(b!=null&&b.adapterName))return null;const Se=(se=b==null?void 0:b.adapterName)==null?void 0:se.trim(),_e=(He=(rt=b==null?void 0:b.adapterInfo)==null?void 0:rt.notes)==null?void 0:He.trim();return ce?{...ce,notes:_e||ce.notes}:Se?{id:Se,name:Se,notes:_e||void 0}:null},[(tt=b==null?void 0:b.adapterInfo)==null?void 0:tt.notes,b==null?void 0:b.adapterName,H]);h.useEffect(()=>{uo(ze)},[ze]),h.useEffect(()=>{let ce=null;const Se=()=>{ce&&(ce(),ce=null)};if(y.voiceEnabled){if(Bt.isAudioEnabled())return D("[ChatInterface] Audio streaming already enabled"),Se;const _e=()=>{Se();const se=async()=>{Se(),await Bt.enableAudio()?D("[ChatInterface] Audio streaming enabled after user gesture"):(me("[ChatInterface] User gesture did not enable audio streaming"),_e())};document.addEventListener("pointerdown",se,{once:!0}),document.addEventListener("keydown",se,{once:!0}),ce=()=>{document.removeEventListener("pointerdown",se),document.removeEventListener("keydown",se)},D("[ChatInterface] Waiting for user gesture to enable audio streaming")};return _e(),Se}return Se(),Bt.disableAudio(),D("[ChatInterface] Audio streaming disabled via settings"),Se},[y.voiceEnabled]);const et=(ce,Se,_e,se)=>{var rt;l(ce,Se,_e,V??((rt=b==null?void 0:b.adapterInfo)==null?void 0:rt.model)??void 0,se)},ps=async(ce,Se,_e,se,rt)=>{var He;await l(_e,void 0,ce,rt??V??((He=b==null?void 0:b.adapterInfo)==null?void 0:He.model)??void 0,se)},xt=()=>{try{n()}catch(ce){me("Cannot create new conversation:",ce instanceof Error?ce.message:"Unknown error")}},Mt=h.useCallback(async(ce,Se)=>{if(b)try{await ke.getState().deleteThread(b.id,ce,Se)}catch(_e){ge("Failed to clear thread:",_e)}},[b]);return i.jsx("main",{className:"flex-1 flex flex-col bg-transparent overflow-hidden","aria-label":s("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 ${J} flex-col overflow-hidden md:pb-4 ${Df}`,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:p,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":s("chatInterface.error.dismissAriaLabel"),children:"×"})]})}),i.jsxs("div",{className:ie,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:!_,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 ${_?"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":s("chatInterface.mobile.openChatsMenuAriaLabel"),children:[i.jsx(Zc,{className:"h-4 w-4"}),s("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":s("chatInterface.mobile.openSettingsAriaLabel"),children:[i.jsx(Nn,{className:"h-4 w-4"}),s("chatInterface.mobile.settingsButton")]})]}),i.jsx("div",{className:"ml-auto flex-shrink-0",children:i.jsx(Sa,{})})]}),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:oe&&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)||s("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:s("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":s("chatInterface.settings.ariaLabel"),title:s("chatInterface.settings.title"),children:i.jsx(Nn,{className:"h-4 w-4"})})}),!Ae&&!H&&!!(b!=null&&b.adapterName)&&i.jsx("button",{type:"button",onClick:()=>{xe&&te()},disabled:!xe,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 ${xe?"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:s(xe?"chatInterface.changeAgent.titleEnabled":"chatInterface.changeAgent.titleDisabled"),children:s("chatInterface.changeAgent.button")}),!H&&i.jsxs("button",{onClick:xt,disabled:!X,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 ${X?"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:Ce,children:[i.jsx(cd,{className:"h-3.5 w-3.5"}),s("chatInterface.newConversation.button")]}),!pa()&&i.jsx("div",{className:"order-4 hidden flex-shrink-0 items-center md:inline-flex",children:i.jsx(Sa,{})})]})]})]}),S?i.jsxs("div",{className:`flex flex-1 flex-col min-h-0 ${Tt} ${H?"overflow-hidden":""}`,children:[H?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:`${ne} 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:N}),P&&i.jsx("div",{className:"mt-2",children:i.jsx(_t,{content:E,className:R,syntaxTheme:N})})]})}),i.jsx(hf,{onAdapterSelect:O,className:`${ne} 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 ${ye} 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:tc(b.adapterName)||b.adapterName}):fe?i.jsx("p",{className:"w-full text-center text-sm text-gray-500 dark:text-[#bfc2cd]",children:s("chatInterface.empty.configuringAgent")}):null,ze&&Pf()&&i.jsx(vf,{adapter:ze,syntaxTheme:N,forcedThemeClass:v}),i.jsx("div",{className:"w-full min-w-0",children:i.jsx(Zn,{onSend:et,disabled:u||!b||!(b!=null&&b.adapterName)||ee,autoFocusEnabled:!0,placeholder:B,isCentered:!0,maxWidthClass:ye,adapterNotes:(Ft=b==null?void 0:b.adapterInfo)==null?void 0:Ft.notes,skillState:F,availableModels:K,defaultModel:((qt=b==null?void 0:b.adapterInfo)==null?void 0:qt.model)??null,selectedModel:V,onSelectModel:Z})})]})}),Ne&&i.jsx("div",{className:"shrink-0 pt-5 md:pt-6",children:i.jsx(no,{compact:!0})})]}):i.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[i.jsx(Bu,{messages:b.messages,onRegenerate:ce=>{var Se;return c(ce,V??((Se=b==null?void 0:b.adapterInfo)==null?void 0:Se.model)??void 0)},onEditMessage:(ce,Se)=>{var _e;return d(ce,Se,V??((_e=b==null?void 0:b.adapterInfo)==null?void 0:_e.model)??void 0)},onStartThread:async(ce,Se)=>{try{await g(ce,Se)}catch(_e){ge("Failed to create thread:",_e)}},onClearThread:Mt,onSendThreadMessage:ps,sessionId:b.sessionId,isLoading:u,contentMaxWidthClass:W,availableModels:K,defaultModel:((je=b==null?void 0:b.adapterInfo)==null?void 0:je.model)??null,selectedModel:V}),i.jsx("div",{className:Uf,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(Zn,{onSend:et,disabled:u||!b||!b.adapterName||re||ee,autoFocusEnabled:!0,placeholder:s("chatInterface.docked.placeholder"),maxWidthClass:W,isCentered:!1,adapterNotes:(st=b==null?void 0:b.adapterInfo)==null?void 0:st.notes,skillState:F,availableModels:K,defaultModel:((bt=b==null?void 0:b.adapterInfo)==null?void 0:bt.model)??null,selectedModel:V,onSelectModel:Z})})})]})]})})})}function Bf({selectedAdapter:t,onAdapterChange:e,disabled:s,showDescriptions:a=!1,variant:r="sidebar",label:n,showLabel:o}){const{t:l}=Ee(),[c,d]=h.useState([]),[u,f]=h.useState(!0),[m,p]=h.useState(null),[g,x]=h.useState(!1);h.useEffect(()=>{let _=!0;async function S(){try{f(!0),p(null);const I=await Da();_&&d(I)}catch(I){ge("Failed to load adapters:",I),_&&p(l("adapterSelector.failedToLoad"))}finally{_&&f(!1)}}return S(),()=>{_=!1}},[l]);const y=c.find(_=>_.id===t),k=typeof o=="boolean"?o:r==="prominent",A=n||l(r==="prominent"?"adapterSelector.selectAnAgent":"adapterSelector.defaultLabel"),L=h.useMemo(()=>r==="prominent"?"relative w-full text-left":"relative w-full",[r]),C=h.useMemo(()=>{const _="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 r==="prominent"?[_,"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(" ")},[r]),v=h.useMemo(()=>r==="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]",[r]),b=k?`mb-2 block text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-[#bfc2cd] ${r==="prominent"?"!text-sm !font-semibold !text-gray-700 dark:!text-white":""}`:"sr-only";return i.jsxs("div",{className:L,children:[i.jsx("label",{className:b,children:A}),i.jsxs("div",{className:"relative",children:[i.jsx("button",{type:"button",onClick:()=>!s&&x(!g),disabled:s||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")}),r==="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(fs,{className:`h-4 w-4 flex-shrink-0 transition-transform text-gray-400 dark:text-gray-300 ${g?"rotate-180":""}`})]})}),g&&!s&&c.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>x(!1)}),i.jsx("div",{className:v,children:i.jsx("div",{className:"max-h-72 overflow-auto py-2",children:c.map(_=>{const S=_.id===t;return i.jsx("button",{type:"button",onClick:()=>{S||e(_.id),x(!1)},className:`w-full px-4 py-3 text-left text-sm transition-colors ${S?"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:_.name}),a&&_.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:_.description})]})},_.id)})})})]})]}),m&&i.jsx("p",{className:"mt-1 text-xs text-red-600 dark:text-red-400",children:m})]})}const pr=100;function si({onClick:t,label:e,hoverClassName:s,icon:a}){return i.jsx("button",{onClick:t,className:`rounded-lg p-1.5 text-slate-400 transition-colors dark:text-[#6b6f7a] ${s}`,"aria-label":e,children:a})}function Hf(t,e){const s=new Date(e.getFullYear(),e.getMonth(),e.getDate()),a=new Date(s);a.setDate(a.getDate()-1);const r=new Date(s);r.setDate(r.getDate()-s.getDay());const n=new Date(e.getFullYear(),e.getMonth(),1);return t>=s?"today":t>=a?"yesterday":t>=r?"thisWeek":t>=n?"thisMonth":"earlier"}function Vf(t){const e=new Date,s=["today","yesterday","thisWeek","thisMonth","earlier"],a=new Map;for(const r of t){const n=Hf(r.updatedAt,e),o=a.get(n);o?o.push(r):a.set(n,[r])}return s.filter(r=>a.has(r)).map(r=>({label:r,conversations:a.get(r)}))}function ri({onRequestClose:t,onToggleDesktopSidebar:e}){const{t:s}=Ee(),a=_r(),{conversations:r,currentConversationId:n,selectConversation:o,deleteConversation:l,deleteAllConversations:c,updateConversationTitle:d,getConversationCount:u,configureApiSettings:f,clearError:m}=ke(),p=r.find(z=>z.id===n),[g,x]=h.useState(""),[y,k]=h.useState(null),[A,L]=h.useState(""),[C,v]=h.useState({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1}),[N,R]=h.useState({isOpen:!1,isDeleting:!1}),[b,_]=h.useState(!1),[S,I]=h.useState(null),[M,F]=h.useState(!1),[B,j]=h.useState(null),E=h.useRef(null),P=h.useRef(null),T=h.useRef(null),K=!p||p.messages.length===0,G=(S==null?void 0:S.conversationId)===n?S.adapterName:(p==null?void 0:p.adapterName)??null,V=(B==null?void 0:B.conversationId)===n?B.message:null,Z=h.useMemo(()=>r.filter(z=>{var ie;return(z.messages.length>0||(((ie=z.attachedFiles)==null?void 0:ie.length)||0)>0)&&!z.adapterLoadError}),[r]),ue=h.useMemo(()=>{if(!g)return Z;const z=g.toLowerCase();return Z.filter(ie=>(ie.title||s("chatInterface.newChatTitle")).toLowerCase().includes(z)||ie.messages.some(Be=>Be.content.toLowerCase().includes(z))||(ie.attachedFiles||[]).some(Be=>Be.filename.toLowerCase().includes(z)))},[Z,g,s]),O=h.useMemo(()=>Vf(ue),[ue]),te=u(),Y=g.length>0,ee=Z.length>0;h.useEffect(()=>{if(!n||!P.current)return;const z=P.current.querySelector('[aria-current="true"]');z&&z.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const re=h.useCallback(z=>{var Tt;if(z.key!=="ArrowDown"&&z.key!=="ArrowUp")return;z.preventDefault();const ie=(Tt=P.current)==null?void 0:Tt.querySelectorAll('[role="option"]');if(!ie||ie.length===0)return;const Be=document.activeElement,be=Array.from(ie).indexOf(Be);let Ne;z.key==="ArrowDown"?Ne=be<ie.length-1?be+1:0:Ne=be>0?be-1:ie.length-1,ie[Ne].focus()},[]),fe=async z=>{if(!(!K||!z)){I({conversationId:n??null,adapterName:z}),j(null),F(!0);try{const ie=(p==null?void 0:p.apiUrl)||Fe();await f(ie,void 0,z),m(),_(!1)}catch(ie){ge("Failed to configure adapter:",ie),j({conversationId:n??null,message:ie instanceof Error?ie.message:s("sidebar.adapterConfigureFailed")})}finally{F(!1)}}},Ae=async z=>{try{await o(z),t==null||t()}catch(ie){ge("Failed to select conversation:",ie)}},H=(z,ie)=>{z.stopPropagation(),v({isOpen:!0,conversationId:ie.id,conversationTitle:ie.title||s("chatInterface.newChatTitle"),isDeleting:!1})},J=async()=>{v(z=>({...z,isDeleting:!0}));try{await l(C.conversationId)}catch(z){ge("Failed to delete conversation:",z)}v({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},W=()=>{v({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},ye=(z,ie)=>{z.stopPropagation(),k(ie.id),L((ie.title||s("chatInterface.newChatTitle")).slice(0,pr))},ne=z=>{const ie=A.slice(0,pr).trim();ie&&d(z,ie),k(null),L("")},X=()=>{k(null),L("")},xe=()=>{R({isOpen:!0,isDeleting:!1})},Ce=async()=>{R(z=>({...z,isDeleting:!0}));try{await c()}catch(z){ge("Failed to clear all conversations:",z)}R({isOpen:!1,isDeleting:!1})},oe=()=>{R({isOpen:!1,isDeleting:!1})},ve=z=>{var ie,Be,be;return(ie=z.adapterName)!=null&&ie.trim()?z.adapterName:(be=(Be=z.adapterInfo)==null?void 0:Be.adapter_name)!=null&&be.trim()?z.adapterInfo.adapter_name:null};Ds(E,{enabled:b,onEscape:()=>_(!1)});const $e=z=>{const ie=n===z.id,Be=a?null:ve(z),be=z.title||s("chatInterface.newChatTitle");return i.jsxs("div",{role:"option","aria-selected":ie,tabIndex:0,onKeyDown:Ne=>{(Ne.key==="Enter"||Ne.key===" ")&&(Ne.preventDefault(),Ae(z.id))},onClick:()=>Ae(z.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
- ${ie?"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":ie?"true":void 0,"aria-label":s("sidebar.conversationCard.openAriaLabel",{title:be}),children:[ie&&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 ${ie?"bg-sky-500 opacity-100 dark:bg-sky-400":"opacity-0"}`}),y===z.id?i.jsx("input",{type:"text",value:A,onChange:Ne=>L(Ne.target.value.slice(0,pr)),onKeyDown:Ne=>{Ne.key==="Enter"&&ne(z.id),Ne.key==="Escape"&&X(),Ne.stopPropagation()},onBlur:()=>ne(z.id),maxLength:pr,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":s("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] ${ie?"font-semibold text-slate-900 dark:text-[#ececf1]":"font-medium text-slate-700 dark:text-[#c5c8d6]"}`,children:be}),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(si,{onClick:Ne=>ye(Ne,z),label:s("sidebar.conversationCard.editAriaLabel",{title:be}),hoverClassName:"hover:bg-slate-200/80 hover:text-slate-600 dark:hover:bg-[#3c3f4a] dark:hover:text-[#c5c8d6]",icon:i.jsx(Ri,{className:"h-3.5 w-3.5"})}),i.jsx(si,{onClick:Ne=>H(Ne,z),label:s("sidebar.conversationCard.deleteAriaLabel",{title:be}),hoverClassName:"hover:bg-red-100/80 hover:text-red-600 dark:hover:bg-red-900/30 dark:hover:text-red-400",icon:i.jsx(Oi,{className:"h-3.5 w-3.5"})})]})]}),Be&&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:Be})]})]},z.id)};return i.jsxs(i.Fragment,{children:[!a&&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:E,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:s("sidebar.selectAgent.title")}),i.jsxs("div",{className:"space-y-5",children:[i.jsx(Bf,{selectedAdapter:G,onAdapterChange:fe,disabled:M,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),_(!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:M,children:s("common.cancel")})})]})]})}),i.jsxs("nav",{"aria-label":s("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:[r.length>0&&r.some(z=>z.messages.length>0)&&i.jsxs("button",{onClick:xe,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:s("sidebar.deleteAllConversations.title"),children:[i.jsx(pd,{className:"h-4 w-4"}),s("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":s("sidebar.collapse.ariaLabel"),title:s("sidebar.collapse.title"),children:i.jsx(ad,{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}),ee&&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(Ta,{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:T,type:"text",role:"searchbox","aria-label":s("sidebar.search.ariaLabel"),placeholder:s("sidebar.search.placeholder"),value:g,onChange:z=>x(z.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"}),g&&i.jsx("button",{type:"button",onClick:()=>{var z;x(""),(z=T.current)==null||z.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":s("sidebar.search.clearAriaLabel"),children:i.jsx(Je,{className:"h-3.5 w-3.5"})})]}),Y&&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?s("sidebar.resultsNone"):s("sidebar.results",{count:ue.length})})]})]}),i.jsx("div",{ref:P,role:"listbox","aria-label":s("sidebar.conversations.ariaLabel"),onKeyDown:re,className:"flex-1 overflow-y-auto bg-transparent px-3 py-2",children:ue.length===0?null:Y?i.jsx("div",{className:"space-y-1.5",children:ue.map($e)}):i.jsx("div",{className:"space-y-4",children:O.map(z=>i.jsxs("section",{"aria-label":s(`sidebar.timeGroups.${z.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:s(`sidebar.timeGroups.${z.label}`)}),i.jsx("div",{className:"space-y-1.5",children:z.conversations.map($e)})]},z.label))})}),(()=>{const z=Ai();return z.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":s("appHeader.navLinksAriaLabel"),children:i.jsx("ul",{className:"flex flex-wrap gap-2",children:z.map(ie=>i.jsx("li",{children:i.jsx("a",{href:ie.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:ie.label})},ie.url))})})})})(),i.jsx("div",{className:"shrink-0 border-t border-gray-200/80 dark:border-[#2d2f39]",children:i.jsx(no,{placement:"sidebar",compact:!0})})]}),i.jsx(vr,{isOpen:C.isOpen,onClose:W,onConfirm:J,title:s("sidebar.deleteConfirm.title"),message:s("sidebar.deleteConfirm.message",{title:C.conversationTitle}),confirmText:s("sidebar.deleteConfirm.confirmText"),cancelText:s("common.cancel"),type:"danger",isLoading:C.isDeleting}),i.jsx(vr,{isOpen:N.isOpen,onClose:oe,onConfirm:Ce,title:s("sidebar.clearAllConfirm.title"),message:s("sidebar.clearAllConfirm.message",{count:te}),confirmText:s("sidebar.clearAllConfirm.confirmText"),cancelText:s("common.cancel"),type:"danger",isLoading:N.isDeleting})]})}const qf="3.11.6",Wf={version:qf},Oa=Wf.version,Kf=["@@auth0spajs@@","a0.spajs","auth0","com.auth0"];function Gf(t){const e=t.toLowerCase();return Kf.some(s=>e.includes(s.toLowerCase()))}function Xf(t){const e=[];for(let s=0;s<t.length;s++){const a=t.key(s);a&&Gf(a)&&e.push(a)}e.forEach(s=>t.removeItem(s))}function ai(t){try{Xf(t),t.clear()}catch(e){console.warn("[Settings] Failed to clear browser storage during reset.",e)}}function Yf(){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(a=>{const r=a.indexOf("="),n=(r>-1?a.slice(0,r):a).trim();n&&t.forEach(o=>{const l=o?`;domain=${o}`:"";document.cookie=`${n}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${l}`})})}function Qf(){ai(localStorage),ai(sessionStorage),Yf()}function Zf({isOpen:t,onClose:e}){const{t:s}=Ee(),{theme:a,updateTheme:r}=ts(),{settings:n,updateSettings:o}=Lr(),{activeLanguages:l,currentLanguage:c,setLanguage:d}=Pc(),[u,f]=h.useState(!1),[m,p]=h.useState(!1),g=h.useRef(null),x=h.useRef(null),y=h.useMemo(()=>[...l].sort((N,R)=>ar[N].localeCompare(ar[R])),[l]);h.useEffect(()=>{if(!m)return;const N=R=>{R.key==="Escape"&&(R.stopPropagation(),p(!1))};return document.addEventListener("keydown",N,{capture:!0}),()=>document.removeEventListener("keydown",N,{capture:!0})},[m]);const k=N=>{r({mode:N})},A=()=>{o({soundEnabled:!n.soundEnabled})},L=()=>{f(!0)},C=()=>{f(!1)},v=()=>{C(),Fr(),$r(!1),us(null),ot.getState().closeLoginPrompt(),Qf(),window.location.reload()};return Ds(g,{enabled:t&&!u,onEscape:e}),Ds(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":s("settings.dialog.closeOverlayAriaLabel"),className:"absolute inset-0"}),i.jsxs("div",{onClick:N=>N.stopPropagation(),ref:g,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:s("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":s("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(rd,{className:"w-5 h-5"}),s("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:s("settings.appearance.themeLabel")}),i.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{value:"light",label:s("settings.appearance.themeLight"),icon:hd},{value:"dark",label:s("settings.appearance.themeDark"),icon:sd},{value:"system",label:s("settings.appearance.themeSystem"),icon:td}].map(({value:N,label:R,icon:b})=>i.jsxs("button",{onClick:()=>k(N),className:`flex flex-col items-center gap-2 p-3 rounded-lg border-2 transition-all duration-200 ${a.mode===N?"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:R})]},N))})]}),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(Xc,{className:"w-4 h-4"}),s("settings.language.label")]}),i.jsxs("div",{className:"relative",children:[i.jsxs("button",{type:"button",onClick:()=>p(N=>!N),"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:ar[c]}),i.jsx(fs,{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:()=>p(!1)}),i.jsx("div",{role:"listbox","aria-label":s("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(N=>{const R=N===c;return i.jsxs("button",{type:"button",role:"option","aria-selected":R,onClick:()=>{d(N),p(!1)},className:`flex w-full items-center justify-between gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors ${R?"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:ar[N]}),R&&i.jsx(ds,{className:"h-4 w-4 flex-shrink-0 text-blue-600 dark:text-blue-400"})]},N)})})]})]})]})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:s("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($a,{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:s("settings.soundEffects.label")}),i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s("settings.soundEffects.description")})]})]}),i.jsx("button",{onClick:A,role:"switch","aria-checked":n.soundEnabled,"aria-label":s("settings.soundEffects.toggleAriaLabel"),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${n.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 ${n.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(Oi,{className:"w-5 h-5"}),s("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:s("settings.dataManagement.description")}),i.jsx("button",{onClick:L,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:s("settings.reset.button")})]})]}),i.jsxs("p",{className:"pt-2 text-center text-xs text-gray-400 dark:text-[#858999]",children:["v",Oa]})]}),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(Fa,{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:s("settings.reset.confirmTitle")}),i.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:s("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:s("common.cancel")}),i.jsx("button",{onClick:v,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:s("settings.reset.confirmButton")})]})]})})]})]}):null}function Jf({message:t}){const{t:e}=Ee(),s=Ia();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:s}),i.jsxs("span",{className:"shrink-0 text-xs font-medium text-slate-400 dark:text-[#858999]",children:["v",Oa]})]}),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(dd,{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 eh({children:t}){const{instance:e,accounts:s}=Ca(),a=Zo();return h.useEffect(()=>{$r(a)},[a]),h.useEffect(()=>{if(!a||s.length===0){us(null);return}const r=s[0];us(r.username||r.name||r.localAccountId||null)},[a,s]),h.useEffect(()=>{if(!a||s.length===0)return;const r=s[0],n=_a();return zi(async()=>(await e.acquireTokenSilent({scopes:n,account:r})).accessToken),()=>Fr()},[a,s,e]),i.jsx(i.Fragment,{children:t})}function th({children:t}){return i.jsx(eh,{children:t})}function sh({children:t}){const{isLoading:e,isAuthenticated:s,getAccessTokenSilently:a,user:r}=Aa();return h.useEffect(()=>{$r(s)},[s]),h.useEffect(()=>{if(!s){us(null);return}const n=(r==null?void 0:r.sub)||(r==null?void 0:r.email)||(r==null?void 0:r.nickname)||(r==null?void 0:r.name)||null;us(n)},[s,r]),h.useEffect(()=>(s&&zi(()=>a()),()=>Fr()),[s,a]),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 rh({children:t}){return h.useEffect(()=>{$r(!1),us(null),Fr()},[]),i.jsx(i.Fragment,{children:t})}function ah({children:t}){return it()?Tr()==="entra"?i.jsx(th,{children:t}):i.jsx(sh,{children:t}):i.jsx(rh,{children:t})}function nh(){const t=Ea(),e=it(),s=hs(),{showLoginPrompt:a,promptMessage:r,closeLoginPrompt:n}=ot();return h.useEffect(()=>{a&&(!t||!e||s)&&n()},[a,t,e,s,n]),!t||!e||s||!a?null:Tr()==="entra"?i.jsx(oh,{message:r,onClose:n}):i.jsx(ih,{message:r,onClose:n})}function ih({message:t,onClose:e}){const{loginWithRedirect:s}=Aa();return i.jsx(fo,{message:t,onClose:e,onLogin:()=>s()})}function oh({message:t,onClose:e}){const{instance:s}=Ca();return i.jsx(fo,{message:t,onClose:e,onLogin:()=>s.loginRedirect({scopes:_a()}).catch(()=>{})})}function fo({message:t,onClose:e,onLogin:s}){const{t:a}=Ee();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":a("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($i,{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:a("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:s,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:a("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:a("common.cancel")})]})]})]})}function lh(){const{t}=Ee(),{goHome:e}=co(),{isDark:s}=ts(),a=bf(),r=h.useRef(!1),n=bc(),o=yc(),l=wc(),c=s?l:o,d=kc(),u=vc(),f=!!(d||u),m=Sc(),p=jc(),g=Cc(),x=Ai(),y=g?"border-b border-slate-200/80 dark:border-[#333645]":"",k="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(()=>{r.current},[l,n,o]),pa()?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:p||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:a,"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:k,style:{color:p||void 0},children:A.label})},A.url))})}),i.jsx(Sa,{})]})]})}):null}function ch({children:t}){const e=h.useRef(null),s=h.useCallback(r=>{e.current=r},[]),a=h.useCallback(()=>{var r;(r=e.current)==null||r.call(e)},[]);return i.jsx(lo.Provider,{value:{registerGoHome:s,goHome:a},children:t})}function dh(){const{t}=Ee(),[e,s]=h.useState(!1),[a,r]=h.useState(!1),[n,o]=h.useState(()=>localStorage.getItem("desktop-sidebar-collapsed")==="true"),l=ke(u=>u.conversations),c=pc();if(h.useEffect(()=>{localStorage.setItem("desktop-sidebar-collapsed",String(n))},[n]),c)return i.jsx(an,{children:i.jsx(Jf,{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(an,{children:i.jsx(sl,{children:i.jsx(Rc,{children:i.jsx(ah,{children:i.jsx(ch,{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&&(n?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(nd,{className:"h-4 w-4"})})}):i.jsx("div",{className:"hidden md:h-full md:flex",children:i.jsx(ri,{onToggleDesktopSidebar:()=>o(!0)})})),i.jsxs("div",{className:"flex-1 flex flex-col w-full min-h-0",children:[i.jsx(lh,{}),i.jsx("div",{className:"flex-1 flex justify-center w-full min-h-0",children:i.jsx(zf,{onOpenSettings:()=>s(!0),onOpenSidebar:()=>r(!0)})})]})]}),i.jsx(nh,{}),i.jsx(Zf,{isOpen:e,onClose:()=>s(!1)}),a&&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:()=>r(!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(ri,{onRequestClose:()=>r(!1)}),i.jsx("button",{onClick:()=>r(!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 oa=new Jo({auth:{clientId:ji(),authority:`https://login.microsoftonline.com/${xc()}`,redirectUri:typeof window<"u"?window.location.origin:"/"},cache:{cacheLocation:"sessionStorage"}});function uh({children:t}){const[e,s]=h.useState(!1);return h.useEffect(()=>{oa.initialize().then(()=>oa.handleRedirectPromise()).catch(a=>{console.error("[EntraAuth] Redirect processing failed:",a)}).finally(()=>s(!0))},[]),e?i.jsx(el,{instance:oa,children:t}):null}function fh({children:t}){if(!Ea()||!it())return i.jsx(i.Fragment,{children:t});if(Tr()==="entra")return i.jsx(uh,{children:t});const s=mc(),a=ji(),r=gc();return!s||!a?i.jsx(i.Fragment,{children:t}):i.jsx(tl,{domain:s,clientId:a,authorizationParams:{redirect_uri:window.location.origin,...r?{audience:r}:{}},cacheLocation:"memory",children:t})}uo(null);const ni=ic(),ii=document.querySelector('link[rel="icon"]');if(ii)ii.href=ni;else{const t=document.createElement("link");t.rel="icon",t.href=ni,document.head.appendChild(t)}const hh=Tc();var oi,li,ci,di,ui,fi;for(const t of hh){const e=((oi=t.src)==null?void 0:oi.trim())||"",s=((li=t.content)==null?void 0:li.trim())||"",a=((ci=t.id)==null?void 0:ci.trim())||"";if(!e&&!s||a&&document.querySelector(`script[data-orbitchat-startup-script-id="${a}"]`)||Array.from(document.querySelectorAll("script[data-orbitchat-startup-script]")).some(o=>{const l=e&&o.dataset.orbitchatStartupScriptSrc===e,c=s&&(o.textContent||"").trim()===s;return!!(l||c)}))continue;const n=document.createElement("script");e&&(n.src=e),s&&(n.text=s),n.async=t.async??!0,t.defer!==void 0&&(n.defer=t.defer),(di=t.type)!=null&&di.trim()&&(n.type=t.type.trim()),(ui=t.integrity)!=null&&ui.trim()&&(n.integrity=t.integrity.trim()),t.crossOrigin&&(n.crossOrigin=t.crossOrigin),(fi=t.referrerPolicy)!=null&&fi.trim()&&(n.referrerPolicy=t.referrerPolicy.trim()),n.dataset.orbitchatStartupScript="true",a&&(n.dataset.orbitchatStartupScriptId=a),e&&(n.dataset.orbitchatStartupScriptSrc=e),document.head.appendChild(n)}D("🚀 AI Chat Application started");D(`📱 App Version: v${Oa}`);Do.createRoot(document.getElementById("root")).render(i.jsx(h.StrictMode,{children:i.jsx(fh,{children:i.jsx(dh,{})})}));export{Pl as r,Ee as u};
375
+ }`;if(!s.trim())return[];try{const a=JSON.parse(s),r=new Set(Object.entries(a).filter(([,n])=>{if(typeof n=="string")return n.trim().length>0;if(n&&typeof n=="object"){const o=n;if(typeof o.apiKey=="string"&&o.apiKey.trim().length>0||typeof o.key=="string"&&o.key.trim().length>0)return!0}return!1}).map(([n])=>n));return e.filter(n=>r.has(n.id))}catch{return[]}}}return null}async function Da(){if(Ot&&Date.now()-aa<df)return Ot;try{const e=await fetch("/api/adapters?refresh=1",{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(e.ok){const s=await e.json(),a=so(s.adapters);if(a.length>0)return Ot=a,aa=Date.now(),U("Fetched adapters from /api/adapters:",Ot),Ot;U("/api/adapters response did not contain valid adapters, trying fallback")}U(`/api/adapters returned ${e.status}, trying fallback`)}catch(e){U("Could not fetch from /api/adapters, trying fallback:",e)}const t=uf();if(t&&t.length>0)return Ot=t,aa=Date.now(),U("Loaded adapters from config:",Ot),Ot;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 ff="h-[96px]";function hf({onAdapterSelect:t,className:e="",title:s="",subtitle:a="",eyebrow:r=""}){const{t:n}=Le(),[o,l]=h.useState([]),[c,d]=h.useState(!0),[u,f]=h.useState(null),m=h.useRef(null),p=h.useRef(null),[g,x]=h.useState(""),[y,k]=h.useState(!1),A=h.useCallback(()=>{const j=m.current;if(!j){k(!1);return}k(j.scrollHeight-j.scrollTop-j.clientHeight>20)},[]),L=()=>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"]'))??[])},v=j=>{const D=C()[j]??null;D&&(D.focus(),D.scrollIntoView({block:"nearest"}))},N=()=>{v(0)},R=()=>{const j=C();j.length!==0&&v(j.length-1)},b=j=>{if(!c&&!u&&I.length>0&&L()){if(j.key==="Tab"&&!j.shiftKey){j.preventDefault(),N();return}if(j.key==="ArrowDown"){j.preventDefault(),N();return}j.key==="ArrowUp"&&(j.preventDefault(),R())}},_=j=>{var G;if(!M||!L()||j.key!=="ArrowDown"&&j.key!=="ArrowUp")return;const E=document.activeElement;if(!(E instanceof HTMLElement)||E.dataset.agentCard!=="true")return;const D=C(),T=D.indexOf(E);if(T!==-1){if(j.preventDefault(),j.key==="ArrowDown"){v((T+1)%D.length);return}if(T===0){(G=p.current)==null||G.focus();return}v(T-1)}},S=g.trim().toLowerCase(),I=S?o.filter(j=>{var G,X;const E=j.name.toLowerCase().includes(S),D=((G=j.description)==null?void 0:G.toLowerCase().includes(S))??!1,T=((X=j.model)==null?void 0:X.toLowerCase().includes(S))??!1;return E||D||T}):o,M=g.trim().length>0,F=M||I.length===1;h.useEffect(()=>{const j=m.current;if(j)return A(),j.addEventListener("scroll",A,{passive:!0}),()=>j.removeEventListener("scroll",A)},[A,I]),h.useEffect(()=>{let j=!0;return(async()=>{try{d(!0),f(null);const T=(await Da()).slice().sort((G,X)=>G.name.localeCompare(X.name,void 0,{sensitivity:"base"}));j&&l(T)}catch(D){xe("[AgentSelectionList] Failed to load adapters",D),j&&f(n("agentSelectionList.unableToLoad"))}finally{j&&d(!1)}})(),()=>{j=!1}},[n]),h.useEffect(()=>{var j;c||u||o.length===0||(j=p.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,E)=>i.jsx("div",{className:`${ff} animate-pulse rounded-2xl border border-gray-200 bg-transparent dark:border-[#3b3c49]`},E))}):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:n("agentSelectionList.noAgentsAvailable")}):I.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:n("agentSelectionList.noSearchResults")}):i.jsxs("div",{className:"relative flex flex-col h-full min-h-0",children:[i.jsx("div",{ref:m,onKeyDown:_,className:"agent-selection-scroll flex-1 min-h-0 overflow-y-auto pr-1 pb-2",children:F?i.jsx("div",{className:"mx-auto flex w-full max-w-xl flex-col gap-3 lg:max-w-2xl",children:I.map(j=>i.jsx(Jn,{adapter:j,onSelect:E=>t(E.id)},j.id))}):i.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:I.map(j=>i.jsx(Jn,{adapter:j,onSelect:E=>t(E.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:[(r||s||a)&&i.jsxs("div",{className:"flex-shrink-0",children:[r&&i.jsx("p",{className:"text-sm font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-300",children:r}),s&&i.jsx("h2",{className:"mt-2 text-2xl font-bold text-gray-900 dark:text-white",children:s}),a&&i.jsx("p",{className:"mt-2 text-base text-gray-600 dark:text-gray-300",children:a})]}),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(Ta,{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:p,type:"text",placeholder:n("agentSelectionList.searchPlaceholder"),value:g,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"}),g&&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":n("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 Sa(){return Ea()?Tr()==="entra"?i.jsx(mf,{}):i.jsx(pf,{}):null}function pf(){const{user:t,logout:e,loginWithRedirect:s}=Aa();if(!hs()||!t)return i.jsx(ro,{onClick:()=>s()});const r=t.name||t.email||"User";return i.jsx(ao,{displayName:r,onClick:()=>e({logoutParams:{returnTo:window.location.origin}})})}function mf(){const{instance:t,accounts:e}=Ca();if(!hs()||e.length===0)return i.jsx(ro,{onClick:()=>t.loginRedirect({scopes:_a()}).catch(()=>{})});const a=e[0],r=a.name||a.username||"User";return i.jsx(ao,{displayName:r,onClick:()=>t.logoutRedirect({postLogoutRedirectUri:window.location.origin}).catch(()=>{})})}function ro({onClick:t}){const{t:e}=Le();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($i,{className:"h-4 w-4"}),i.jsx("span",{children:e("common.signIn")})]})}function ao({displayName:t,onClick:e}){const{t:s}=Le();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:s("authStatus.signOutButton.title"),"aria-label":s("authStatus.signOutButton.ariaLabel"),children:[i.jsx(Yc,{className:"h-4 w-4"}),i.jsx("span",{className:"hidden md:inline",children:s("common.logOut")})]})]})}function no({placement:t="default",compact:e=!1}){const{t:s}=Le();if(!Ni())return null;const a=Ac(),r=Nc(),n=Ic(),o=Lc(),l=Ec(),c=_c(),d=Mc(),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",p="justify-center",g=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:r||void 0,color:n||void 0},children:i.jsx("div",{className:g,children:i.jsx("div",{className:x,children:i.jsxs("div",{className:m,children:[a&&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:a}),d.length>0&&i.jsx("nav",{"aria-label":s("appFooter.navLinksAriaLabel"),children:i.jsx("ul",{className:`flex flex-wrap items-center ${p} ${e?"gap-1":"gap-1.5 sm:gap-2"}`,children:d.map((k,A)=>{const L=l==="inline"&&A>0;return i.jsxs("li",{className:"flex items-center",children:[L&&i.jsx("span",{className:"mr-1.5 text-slate-400 dark:text-slate-500","aria-hidden":"true",children:"·"}),i.jsx("a",{href:k.url,target:"_blank",rel:"noopener noreferrer",className:y,style:{color:n||void 0},children:k.label})]},k.url)})})})]})})})})}const gf=60*1e3;let na=null,ei=0;const ia=t=>{if(!t||t==="/")return"/";const e=t.trim();if(!e)return"/";const s=e.startsWith("/")?e:`/${e}`;return s==="/"?"/":s.endsWith("/")?s.slice(0,-1):s},io=()=>{if(typeof window>"u")return ia("/");const t=ia("/");if(typeof document>"u")return t;const e=document.querySelector("base[href]");if(!e)return t;try{const s=new URL(e.getAttribute("href")||"/",window.location.origin);return ia(s.pathname||t)}catch{return t}},Nr=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),xf=async()=>{const t=Date.now();if(na&&t-ei<gf)return na;let e=[];try{e=await Da()}catch(a){ge("[agentRouting] Unable to load adapters for slug resolution",a)}const s=new Map;return e.forEach(a=>{const r=Nr(a.name);r&&s.set(r,a.id);const n=Nr(a.id);n&&n!==r&&s.set(n,a.id)}),na=s,ei=t,s},ja=t=>{var n;const e=io(),s=t.startsWith("/")?t:`/${t}`;let a=s;if(e!=="/"){if(!s.startsWith(e))return null;a=s.slice(e.length)}const r=a.split("/").filter(Boolean);return r.length===0?null:((n=r[0])==null?void 0:n.toLowerCase())||null},oo=t=>{const e=io();if(!t)return e;const s=t.replace(/^\/+|\/+$/g,"");return e==="/"?s?`/${s}`:"/":`${e}/${s}`.replace(/\/{2,}/g,"/")},St=t=>{if(typeof window>"u")return;const e=oo(t),s=window.location.pathname;if(e===s)return;const a=window.location.search||"",r=window.location.hash||"";window.history.replaceState(window.history.state,"",`${e}${a}${r}`)},bf=()=>oo(null),yf=async t=>{const e=t.trim().toLowerCase();return e&&(await xf()).get(e)||null};function wf({currentConversation:t,showEmptyState:e,createConversation:s,configureApiSettings:a,clearError:r,clearCurrentConversationAdapter:n}){var ve;const{t:o}=Le(),l=o("agent.error.singleAdapterMissing"),[c,d]=h.useState(!1),[u,f]=h.useState(null),m=_r(),p=Na(),g=typeof window<"u"?ja(window.location.pathname):null,[x,y]=h.useState(g),[k,A]=h.useState(()=>!m&&e&&!g),L=h.useRef(null),C=h.useRef(new Map),v=h.useRef(0),N=3e4,R=!!t,b=(t==null?void 0:t.messages.length)??0,_=((ve=t==null?void 0:t.attachedFiles)==null?void 0:ve.length)??0,S=h.useMemo(()=>R&&(b>0||_>0),[_,b,R]),I=h.useCallback(()=>{Ke(()=>we.getState())},[]),M=h.useCallback((B,ae)=>{if(!B)return;const ie=ae||o("agent.error.configurationFailed");let je=!1;we.setState(re=>{const W=re.conversations.find(pe=>pe.id===B);return!W||W.messages.length>0?re:(je=!0,{conversations:re.conversations.map(pe=>pe.id===B?{...pe,adapterLoadError:ie}:pe)})}),je&&I()},[I,o]),F=h.useCallback(B=>{if(!B)return;let ae=!1;we.setState(ie=>{const je=ie.conversations.find(re=>re.id===B);return!je||!je.adapterLoadError?ie:(ae=!0,{conversations:ie.conversations.map(re=>re.id===B?{...re,adapterLoadError:null}:re)})}),ae&&I()},[I]),H=h.useCallback(B=>B instanceof Wi?B.status===401?o("agent.error.authenticationFailed"):B.status===404?o("agent.error.notFound"):B.message:B instanceof Error?B.message:o("agent.error.loadFailed"),[o]),j=h.useCallback(()=>{const B=we.getState(),ae=B.currentConversationId?B.conversations.find(ie=>ie.id===B.currentConversationId):null;if(!ae||ae.messages.length>0)try{return s()}catch(ie){ge("Cannot create a new conversation for agent selection:",ie instanceof Error?ie.message:"Unknown error")}return(ae==null?void 0:ae.id)||null},[s]),E=h.useCallback(async B=>{if(!(B!=null&&B.adapterName))return{ok:!1};try{const ae=await $e(),ie=new ae.ApiClient({apiUrl:B.apiUrl||Re(),sessionId:null,adapterName:B.adapterName});if(typeof ie.getAdapterInfo!="function")return{ok:!1};const je=await ie.getAdapterInfo();return we.setState(re=>({conversations:re.conversations.map(W=>W.id===B.id?{...W,adapterInfo:je,adapterLoadError:null,updatedAt:new Date}:W)})),we.getState().currentConversationId===B.id&&f(null),I(),{ok:!0}}catch(ae){const ie=H(ae),je=we.getState();je.currentConversationId===B.id&&f({conversationId:B.id,message:ie});const re=je.conversations.find(W=>W.id===B.id);return re&&re.messages.length===0&&M(B.id,ie),{ok:!1,error:ae}}},[H,M,I]),D=h.useCallback(async B=>{if(!B)return;const ae=we.getState(),ie=ae.currentConversationId?ae.conversations.find(je=>je.id===ae.currentConversationId):null;if(ie){d(!0),f(null),F(ie.id);try{const je=ie.apiUrl||Re();await a(je,void 0,B),r();const re=we.getState(),W=re.conversations.find(pe=>pe.id===re.currentConversationId);if((W==null?void 0:W.adapterName)===B&&(!W.adapterInfo||W.adapterInfo.notes===void 0)){const pe=await E(W);!pe.ok&&pe.error&&xe("Failed to load adapter info after selecting adapter:",pe.error)}}catch(je){xe("Failed to configure adapter from empty state:",je);const re=H(je);f({conversationId:ie.id,message:re}),M(ie.id,re)}finally{d(!1)}}},[F,r,a,E,H,M]),T=h.useCallback(B=>{m||(j(),A(!1),St(Nr(B)),D(B))},[j,D,m]),G=h.useCallback(()=>{m||(n(),St(null),A(!0))},[n,m]),X=h.useCallback(()=>{var je,re;if(m){const W=we.getState(),pe=W.currentConversationId?W.conversations.find(be=>be.id===W.currentConversationId):null;if(!!pe&&(pe.messages.length>0||(((je=pe.attachedFiles)==null?void 0:je.length)||0)>0))try{s()}catch(be){ge("Cannot go home (new conversation):",be instanceof Error?be.message:"Unknown error")}St(null),A(!1);return}y(null);const B=we.getState(),ae=B.currentConversationId?B.conversations.find(W=>W.id===B.currentConversationId):null;if(!!ae&&(ae.messages.length>0||(((re=ae.attachedFiles)==null?void 0:re.length)||0)>0))try{s()}catch(W){ge("Cannot go home (new conversation):",W instanceof Error?W.message:"Unknown error");return}else ae!=null&&ae.adapterName&&n();St(null),A(!0)},[n,s,m]),Z=!m&&e&&!x&&!(t!=null&&t.adapterName)&&!S||!m&&e&&k&&!(t!=null&&t.adapterName)&&!S;h.useEffect(()=>{if(m){St(null);return}if(!x){if(Z||!(t!=null&&t.adapterName)){St(null);return}St(Nr(t.adapterName))}},[t==null?void 0:t.adapterName,m,x,Z]);const fe=h.useCallback(async()=>{if(typeof window>"u")return;const B=++v.current;if(m){St(null),y(null);return}const ae=ja(window.location.pathname);if(!ae)return;const ie=await yf(ae);if(B===v.current){if(!ie){j(),St(null),n(),A(!0),y(null);return}j(),A(!1),St(ae),await D(ie),y(null)}},[n,j,D,m]),z=h.useRef(fe);h.useEffect(()=>{z.current=fe},[fe]),h.useEffect(()=>{const B=window.setTimeout(()=>{z.current()},0),ae=()=>{z.current()};return window.addEventListener("popstate",ae),()=>{window.clearTimeout(B),v.current+=1,window.removeEventListener("popstate",ae)}},[]);const se=t==null?void 0:t.id,Y=t==null?void 0:t.adapterName,J=t==null?void 0:t.apiUrl,ee=!!(t!=null&&t.adapterInfo);h.useEffect(()=>{if(!m||!p||!e||!se||S||c)return;const B=(Y==null?void 0:Y.trim())||p,ae=(Y==null?void 0:Y.trim())!==B||!ee;if(!B||!ae)return;let ie=!1;return(async()=>{d(!0),f(null),F(se);try{const re=J||Re();await a(re,void 0,B),r()}catch(re){if(!ie){const W=H(re);f({conversationId:se,message:W}),M(se,W)}}finally{ie||d(!1)}})(),()=>{ie=!0}},[F,r,a,S,H,c,m,M,e,Y,J,ee,se,p]),h.useEffect(()=>{(async()=>{var re;const ae=t==null?void 0:t.adapterName,ie=t?`${t.id}:${ae}`:null;if(!ie||L.current===ie)return;const je=!(t!=null&&t.adapterInfo)||(t==null?void 0:t.adapterInfo)&&t.adapterInfo.notes===void 0;if(ae&&je){L.current=ie,U("[ChatInterface] Loading adapter info - adapterName:",ae,"reason:",t!=null&&t.adapterInfo?"notes undefined":"missing");const W=await E(t);if(W.ok)U("[ChatInterface] Adapter info loaded successfully");else{const pe=W.error;xe("[ChatInterface] Failed to load adapter info:",pe);const _e=pe instanceof Error?pe.message:String(pe);if((_e.includes("429")||_e.includes("Too Many Requests"))&&ae){const Me=C.current.get(ie);Me&&clearTimeout(Me);const Ce=setTimeout(()=>{L.current===ie&&(L.current=null),C.current.delete(ie)},N);C.current.set(ie,Ce),ge(`[ChatInterface] Adapter info request rate-limited; retrying in ${N/1e3}s`)}else L.current=null}}else U("[ChatInterface] Skipping adapter info load:",{adapterName:ae,hasAdapterInfo:!!(t!=null&&t.adapterInfo),hasNotes:((re=t==null?void 0:t.adapterInfo)==null?void 0:re.notes)!==void 0,refValue:L.current})})()},[E,t]),h.useEffect(()=>{const B=C.current;return()=>{B.forEach(ae=>clearTimeout(ae)),B.clear()}},[]);const ue=m&&!p?l:(t==null?void 0:t.adapterLoadError)??(u&&u.conversationId===(t==null?void 0:t.id)?u.message:null);return{adapterNotesError:ue,handleAgentCardSelection:T,handleChangeAgent:G,goToAgentSelectionHome:X,hasAdapterConfigurationError:!!ue,isAgentSelectionVisible:k,isConfiguringAdapter:c,isSingleAdapterMode:m,setIsAgentSelectionVisible:A,shouldShowAgentSelectionList:Z}}const lo=h.createContext(null),kf={registerGoHome:()=>{},goHome:()=>{}};function co(){return h.useContext(lo)??kf}function vf({adapter:t,syntaxTheme:e,forcedThemeClass:s=""}){var r;const a=(r=t.notes)==null?void 0:r.trim();return a?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:a,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 ${s}`,syntaxTheme:e})})]}):null}const Sf='meta[name="description"]',jf='meta[property="og:title"]',Cf='meta[property="og:description"]',Af='meta[property="og:type"]',Nf='link[rel="canonical"]';function ti(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function If(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 Lf(t,e){const s=t==null?void 0:t.trim();if(s)return s;if(!e)return La();const a=If(e);return a.length>160?`${a.slice(0,157).trimEnd()}...`:a}function Ef(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 Tf(t){const e=t.trim();if(!e)return null;const s=`^${Ef(e).replace(/\\\*/g,".*")}$`;try{return new RegExp(s,"i")}catch{return null}}function Mf(t){return[vi(),...rc()].map(_f).filter(s=>!!s).includes(t)?!0:ac().some(s=>{const a=Tf(s);return a?a.test(t):!1})}function Ff(t){var a,r,n;const e=t==null?void 0:t.trim();if(!e)return null;const s=Q.adapters.find(o=>{var l;return((l=o==null?void 0:o.id)==null?void 0:l.trim())===e});return s?{id:s.id,name:((a=s.name)==null?void 0:a.trim())||s.id,description:((r=s.description)==null?void 0:r.trim())||void 0,notes:((n=s.notes)==null?void 0:n.trim())||void 0}:null}function $f(t){var a,r,n;if(typeof window>"u")return null;const e=ja(window.location.pathname);if(!e)return null;const s=Q.adapters.find(o=>{const l=ti(o.name||""),c=ti(o.id||"");return e===l||e===c});return s?{id:s.id,name:((a=s.name)==null?void 0:a.trim())||s.id,description:((r=s.description)==null?void 0:r.trim())||void 0,notes:((n=s.notes)==null?void 0:n.trim())||void 0}:null}function hr(t,e,s){if(typeof document>"u")return null;const a=document.querySelector(t);if(a)return a;const r=document.createElement("meta");return r.setAttribute(e,s),document.head.appendChild(r),r}function Rf(){if(typeof document>"u")return null;const t=document.querySelector(Nf);if(t)return t;const e=document.createElement("link");return e.rel="canonical",document.head.appendChild(e),e}function uo(t){if(typeof document>"u")return;const e=Ia(),s=t?`${t.name} | ${e}`:e,a=t?Lf(t.description,t.notes):La();document.title=s;const r=hr(Sf,"name","description");r&&(r.content=a);const n=hr(jf,"property","og:title");n&&(n.content=s);const o=hr(Cf,"property","og:description");o&&(o.content=a);const l=hr(Af,"property","og:type");l&&(l.content="website");const c=Rf();if(c&&typeof window<"u"){const d=vi(),u=window.location.origin,f=d?new URL(d.endsWith("/")?d:`${d}/`).origin:"",p=`${u&&Mf(u)?u:f||u}${window.location.pathname}`;c.href=p}}function Pf(){return nc()}class Ua{static async getAdapterModels(e,s){const a=await $e(),r=new a.ApiClient({apiUrl:"",adapterName:s});if(!r.getAdapterModels)throw new Error("getAdapterModels is not available on this API client");return r.getAdapterModels(e)}static async getAllModels(e){const s=await $e(),a=new s.ApiClient({apiUrl:"",adapterName:e});if(!a.getAllModels)throw new Error("getAllModels is not available on this API client");return a.getAllModels()}static async listAdapterModels(e,s){return(await Ua.getAdapterModels(e,s)).models}}const Df="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",Uf="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",Of="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 zf({onOpenSettings:t,onOpenSidebar:e}){var Vt,tt,Ft,qt,Se,st,bt;const{t:s}=Le(),{conversations:a,currentConversationId:r,createConversation:n,canCreateNewConversation:o,sendMessage:l,regenerateResponse:c,editMessageAndRegenerate:d,isLoading:u,configureApiSettings:f,error:m,clearError:p,createThread:g,clearCurrentConversationAdapter:x}=we(),{settings:y}=Lr(),k=hs(),A=it()&&!k,{theme:L,isDark:C}=ts(),v=L.mode==="dark"?"dark":L.mode==="light"?"light":"",N=C?"dark":"light",R=["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",v].filter(Boolean).join(" "),b=a.find(ce=>ce.id===r),_=a.some(ce=>{var ke;return(ce.messages.length>0||(((ke=ce.attachedFiles)==null?void 0:ke.length)||0)>0)&&!ce.adapterLoadError}),S=!b||b.messages.length===0,I=((Vt=b==null?void 0:b.adapterInfo)==null?void 0:Vt.supportsThreading)===!0,M=!!(b!=null&&b.adapterName&&(b!=null&&b.adapterInfo))&&!I,F=Ki({adapterName:b==null?void 0:b.adapterName,enabled:M,selectionScopeKey:r,supportsThreading:I}),H=ki(),j=Ia(),E=La().trim(),D=E.length>0,{registerGoHome:T}=co(),[G,X]=h.useState([]),[V,Z]=h.useState(null);h.useEffect(()=>{const ce=b==null?void 0:b.adapterName;let ke=!1;async function Ee(){if(Z(null),!ce){X([]);return}try{const te=await Ua.listAdapterModels(ce,ce);if(ke)return;X(te),Z(te.length>0?te[0].name:null)}catch{ke||(X([]),Z(null))}}return Ee(),()=>{ke=!0}},[b==null?void 0:b.adapterName]);const{adapterNotesError:fe,handleAgentCardSelection:z,handleChangeAgent:se,goToAgentSelectionHome:Y,hasAdapterConfigurationError:J,isAgentSelectionVisible:ee,isConfiguringAdapter:ue,isSingleAdapterMode:ve,shouldShowAgentSelectionList:B}=wf({currentConversation:b,showEmptyState:S,createConversation:n,configureApiSettings:f,clearError:p,clearCurrentConversationAdapter:x});h.useLayoutEffect(()=>(T(()=>Y()),()=>T(null)),[T,Y]);const ae="max-w-[96rem]",ie="max-w-[64rem]",je="max-w-[56rem]",re=`mx-auto w-full ${ae}`,W=o(),pe=!!(b!=null&&b.adapterName)&&((b==null?void 0:b.messages.length)||0)===0,_e=s(W?"chatInterface.newConversation.tooltipCanStart":A?"chatInterface.newConversation.tooltipGuestLimited":"chatInterface.newConversation.tooltipCannotStart"),be=!!(b&&!B),Me=B?"border-transparent dark:border-transparent md:border-transparent md:dark:border-transparent":"",Ce=!pa()&&B?"pt-0 pb-0 md:pt-0 md:pb-1":"",K=`${Of} ${Me} ${Ce}`.trim(),Fe=Ni(),oe=a.some(ce=>{var ke;return(ce.messages.length>0||(((ke=ce.attachedFiles)==null?void 0:ke.length)??0)>0)&&!ce.adapterLoadError}),Ae=Fe&&!oe,Tt=B?"pt-0 md:pt-0":"pt-4 md:pt-6",Be=h.useMemo(()=>{var te,rt,He;if(B)return null;const ce=Ff(b==null?void 0:b.adapterName)||$f();if(!ce&&!(b!=null&&b.adapterName))return null;const ke=(te=b==null?void 0:b.adapterName)==null?void 0:te.trim(),Ee=(He=(rt=b==null?void 0:b.adapterInfo)==null?void 0:rt.notes)==null?void 0:He.trim();return ce?{...ce,notes:Ee||ce.notes}:ke?{id:ke,name:ke,notes:Ee||void 0}:null},[(tt=b==null?void 0:b.adapterInfo)==null?void 0:tt.notes,b==null?void 0:b.adapterName,B]);h.useEffect(()=>{uo(Be)},[Be]),h.useEffect(()=>{let ce=null;const ke=()=>{ce&&(ce(),ce=null)};if(y.voiceEnabled){if(Bt.isAudioEnabled())return U("[ChatInterface] Audio streaming already enabled"),ke;const Ee=()=>{ke();const te=async()=>{ke(),await Bt.enableAudio()?U("[ChatInterface] Audio streaming enabled after user gesture"):(ge("[ChatInterface] User gesture did not enable audio streaming"),Ee())};document.addEventListener("pointerdown",te,{once:!0}),document.addEventListener("keydown",te,{once:!0}),ce=()=>{document.removeEventListener("pointerdown",te),document.removeEventListener("keydown",te)},U("[ChatInterface] Waiting for user gesture to enable audio streaming")};return Ee(),ke}return ke(),Bt.disableAudio(),U("[ChatInterface] Audio streaming disabled via settings"),ke},[y.voiceEnabled]);const et=(ce,ke,Ee,te)=>{var rt;l(ce,ke,Ee,V??((rt=b==null?void 0:b.adapterInfo)==null?void 0:rt.model)??void 0,te)},ps=async(ce,ke,Ee,te,rt)=>{var He;await l(Ee,void 0,ce,rt??V??((He=b==null?void 0:b.adapterInfo)==null?void 0:He.model)??void 0,te)},xt=()=>{try{n()}catch(ce){ge("Cannot create new conversation:",ce instanceof Error?ce.message:"Unknown error")}},Mt=h.useCallback(async(ce,ke)=>{if(b)try{await we.getState().deleteThread(b.id,ce,ke)}catch(Ee){xe("Failed to clear thread:",Ee)}},[b]);return i.jsx("main",{className:"flex-1 flex flex-col bg-transparent overflow-hidden","aria-label":s("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 ${ae} flex-col overflow-hidden md:pb-4 ${Df}`,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:p,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":s("chatInterface.error.dismissAriaLabel"),children:"×"})]})}),i.jsxs("div",{className:K,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:!_,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 ${_?"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":s("chatInterface.mobile.openChatsMenuAriaLabel"),children:[i.jsx(Zc,{className:"h-4 w-4"}),s("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":s("chatInterface.mobile.openSettingsAriaLabel"),children:[i.jsx(Nn,{className:"h-4 w-4"}),s("chatInterface.mobile.settingsButton")]})]}),i.jsx("div",{className:"ml-auto flex-shrink-0",children:i.jsx(Sa,{})})]}),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:be&&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)||s("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:s("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":s("chatInterface.settings.ariaLabel"),title:s("chatInterface.settings.title"),children:i.jsx(Nn,{className:"h-4 w-4"})})}),!ve&&!B&&!!(b!=null&&b.adapterName)&&i.jsx("button",{type:"button",onClick:()=>{pe&&se()},disabled:!pe,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 ${pe?"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:s(pe?"chatInterface.changeAgent.titleEnabled":"chatInterface.changeAgent.titleDisabled"),children:s("chatInterface.changeAgent.button")}),!B&&i.jsxs("button",{onClick:xt,disabled:!W,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 ${W?"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(cd,{className:"h-3.5 w-3.5"}),s("chatInterface.newConversation.button")]}),!pa()&&i.jsx("div",{className:"order-4 hidden flex-shrink-0 items-center md:inline-flex",children:i.jsx(Sa,{})})]})]})]}),S?i.jsxs("div",{className:`flex flex-1 flex-col min-h-0 ${Tt} ${B?"overflow-hidden":""}`,children:[B?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:`${re} 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:N}),D&&i.jsx("div",{className:"mt-2",children:i.jsx(_t,{content:E,className:R,syntaxTheme:N})})]})}),i.jsx(hf,{onAdapterSelect:z,className:`${re} 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 ${je} flex-col items-center gap-4 pb-8 md:gap-5 md:pb-12`,children:[fe?i.jsx("p",{className:"w-full text-center text-sm text-red-600 dark:text-red-400",children:fe}):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:tc(b.adapterName)||b.adapterName}):ue?i.jsx("p",{className:"w-full text-center text-sm text-gray-500 dark:text-[#bfc2cd]",children:s("chatInterface.empty.configuringAgent")}):null,Be&&Pf()&&i.jsx(vf,{adapter:Be,syntaxTheme:N,forcedThemeClass:v}),i.jsx("div",{className:"w-full min-w-0",children:i.jsx(Zn,{onSend:et,disabled:u||!b||!(b!=null&&b.adapterName)||J,autoFocusEnabled:!0,placeholder:H,isCentered:!0,maxWidthClass:je,adapterNotes:(Ft=b==null?void 0:b.adapterInfo)==null?void 0:Ft.notes,skillState:F,availableModels:G,defaultModel:((qt=b==null?void 0:b.adapterInfo)==null?void 0:qt.model)??null,selectedModel:V,onSelectModel:Z})})]})}),Ae&&i.jsx("div",{className:"shrink-0 pt-5 md:pt-6",children:i.jsx(no,{compact:!0})})]}):i.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[i.jsx(Bu,{messages:b.messages,onRegenerate:ce=>{var ke;return c(ce,V??((ke=b==null?void 0:b.adapterInfo)==null?void 0:ke.model)??void 0)},onEditMessage:(ce,ke)=>{var Ee;return d(ce,ke,V??((Ee=b==null?void 0:b.adapterInfo)==null?void 0:Ee.model)??void 0)},onStartThread:async(ce,ke)=>{try{await g(ce,ke)}catch(Ee){xe("Failed to create thread:",Ee)}},onClearThread:Mt,onSendThreadMessage:ps,sessionId:b.sessionId,isLoading:u,contentMaxWidthClass:ie,availableModels:G,defaultModel:((Se=b==null?void 0:b.adapterInfo)==null?void 0:Se.model)??null,selectedModel:V}),i.jsx("div",{className:Uf,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(Zn,{onSend:et,disabled:u||!b||!b.adapterName||ee||J,autoFocusEnabled:!0,placeholder:s("chatInterface.docked.placeholder"),maxWidthClass:ie,isCentered:!1,adapterNotes:(st=b==null?void 0:b.adapterInfo)==null?void 0:st.notes,skillState:F,availableModels:G,defaultModel:((bt=b==null?void 0:b.adapterInfo)==null?void 0:bt.model)??null,selectedModel:V,onSelectModel:Z})})})]})]})})})}function Bf({selectedAdapter:t,onAdapterChange:e,disabled:s,showDescriptions:a=!1,variant:r="sidebar",label:n,showLabel:o}){const{t:l}=Le(),[c,d]=h.useState([]),[u,f]=h.useState(!0),[m,p]=h.useState(null),[g,x]=h.useState(!1);h.useEffect(()=>{let _=!0;async function S(){try{f(!0),p(null);const I=await Da();_&&d(I)}catch(I){xe("Failed to load adapters:",I),_&&p(l("adapterSelector.failedToLoad"))}finally{_&&f(!1)}}return S(),()=>{_=!1}},[l]);const y=c.find(_=>_.id===t),k=typeof o=="boolean"?o:r==="prominent",A=n||l(r==="prominent"?"adapterSelector.selectAnAgent":"adapterSelector.defaultLabel"),L=h.useMemo(()=>r==="prominent"?"relative w-full text-left":"relative w-full",[r]),C=h.useMemo(()=>{const _="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 r==="prominent"?[_,"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(" ")},[r]),v=h.useMemo(()=>r==="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]",[r]),b=k?`mb-2 block text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-[#bfc2cd] ${r==="prominent"?"!text-sm !font-semibold !text-gray-700 dark:!text-white":""}`:"sr-only";return i.jsxs("div",{className:L,children:[i.jsx("label",{className:b,children:A}),i.jsxs("div",{className:"relative",children:[i.jsx("button",{type:"button",onClick:()=>!s&&x(!g),disabled:s||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")}),r==="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(fs,{className:`h-4 w-4 flex-shrink-0 transition-transform text-gray-400 dark:text-gray-300 ${g?"rotate-180":""}`})]})}),g&&!s&&c.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>x(!1)}),i.jsx("div",{className:v,children:i.jsx("div",{className:"max-h-72 overflow-auto py-2",children:c.map(_=>{const S=_.id===t;return i.jsx("button",{type:"button",onClick:()=>{S||e(_.id),x(!1)},className:`w-full px-4 py-3 text-left text-sm transition-colors ${S?"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:_.name}),a&&_.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:_.description})]})},_.id)})})})]})]}),m&&i.jsx("p",{className:"mt-1 text-xs text-red-600 dark:text-red-400",children:m})]})}const pr=100;function si({onClick:t,label:e,hoverClassName:s,icon:a}){return i.jsx("button",{onClick:t,className:`rounded-lg p-1.5 text-slate-400 transition-colors dark:text-[#6b6f7a] ${s}`,"aria-label":e,children:a})}function Hf(t,e){const s=new Date(e.getFullYear(),e.getMonth(),e.getDate()),a=new Date(s);a.setDate(a.getDate()-1);const r=new Date(s);r.setDate(r.getDate()-s.getDay());const n=new Date(e.getFullYear(),e.getMonth(),1);return t>=s?"today":t>=a?"yesterday":t>=r?"thisWeek":t>=n?"thisMonth":"earlier"}function Vf(t){const e=new Date,s=["today","yesterday","thisWeek","thisMonth","earlier"],a=new Map;for(const r of t){const n=Hf(r.updatedAt,e),o=a.get(n);o?o.push(r):a.set(n,[r])}return s.filter(r=>a.has(r)).map(r=>({label:r,conversations:a.get(r)}))}function ri({onRequestClose:t,onToggleDesktopSidebar:e}){const{t:s}=Le(),a=_r(),{conversations:r,currentConversationId:n,selectConversation:o,deleteConversation:l,deleteAllConversations:c,updateConversationTitle:d,getConversationCount:u,configureApiSettings:f,clearError:m}=we(),p=r.find(P=>P.id===n),[g,x]=h.useState(""),[y,k]=h.useState(null),[A,L]=h.useState(""),[C,v]=h.useState({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1}),[N,R]=h.useState({isOpen:!1,isDeleting:!1}),[b,_]=h.useState(!1),[S,I]=h.useState(null),[M,F]=h.useState(!1),[H,j]=h.useState(null),E=h.useRef(null),D=h.useRef(null),T=h.useRef(null),G=!p||p.messages.length===0,X=(S==null?void 0:S.conversationId)===n?S.adapterName:(p==null?void 0:p.adapterName)??null,V=(H==null?void 0:H.conversationId)===n?H.message:null,Z=h.useMemo(()=>r.filter(P=>{var K;return(P.messages.length>0||(((K=P.attachedFiles)==null?void 0:K.length)||0)>0)&&!P.adapterLoadError}),[r]),fe=h.useMemo(()=>{if(!g)return Z;const P=g.toLowerCase();return Z.filter(K=>(K.title||s("chatInterface.newChatTitle")).toLowerCase().includes(P)||K.messages.some(Fe=>Fe.content.toLowerCase().includes(P))||(K.attachedFiles||[]).some(Fe=>Fe.filename.toLowerCase().includes(P)))},[Z,g,s]),z=h.useMemo(()=>Vf(fe),[fe]),se=u(),Y=g.length>0,J=Z.length>0;h.useEffect(()=>{if(!n||!D.current)return;const P=D.current.querySelector('[aria-current="true"]');P&&P.scrollIntoView({block:"nearest",behavior:"smooth"})},[n]);const ee=h.useCallback(P=>{var Tt;if(P.key!=="ArrowDown"&&P.key!=="ArrowUp")return;P.preventDefault();const K=(Tt=D.current)==null?void 0:Tt.querySelectorAll('[role="option"]');if(!K||K.length===0)return;const Fe=document.activeElement,oe=Array.from(K).indexOf(Fe);let Ae;P.key==="ArrowDown"?Ae=oe<K.length-1?oe+1:0:Ae=oe>0?oe-1:K.length-1,K[Ae].focus()},[]),ue=async P=>{if(!(!G||!P)){I({conversationId:n??null,adapterName:P}),j(null),F(!0);try{const K=(p==null?void 0:p.apiUrl)||Re();await f(K,void 0,P),m(),_(!1)}catch(K){xe("Failed to configure adapter:",K),j({conversationId:n??null,message:K instanceof Error?K.message:s("sidebar.adapterConfigureFailed")})}finally{F(!1)}}},ve=async P=>{try{await o(P),t==null||t()}catch(K){xe("Failed to select conversation:",K)}},B=(P,K)=>{P.stopPropagation(),v({isOpen:!0,conversationId:K.id,conversationTitle:K.title||s("chatInterface.newChatTitle"),isDeleting:!1})},ae=async()=>{v(P=>({...P,isDeleting:!0}));try{await l(C.conversationId)}catch(P){xe("Failed to delete conversation:",P)}v({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},ie=()=>{v({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},je=(P,K)=>{P.stopPropagation(),k(K.id),L((K.title||s("chatInterface.newChatTitle")).slice(0,pr))},re=P=>{const K=A.slice(0,pr).trim();K&&d(P,K),k(null),L("")},W=()=>{k(null),L("")},pe=()=>{R({isOpen:!0,isDeleting:!1})},_e=async()=>{R(P=>({...P,isDeleting:!0}));try{await c()}catch(P){xe("Failed to clear all conversations:",P)}R({isOpen:!1,isDeleting:!1})},be=()=>{R({isOpen:!1,isDeleting:!1})},Me=P=>{var K,Fe,oe;return(K=P.adapterName)!=null&&K.trim()?P.adapterName:(oe=(Fe=P.adapterInfo)==null?void 0:Fe.adapter_name)!=null&&oe.trim()?P.adapterInfo.adapter_name:null};Ds(E,{enabled:b,onEscape:()=>_(!1)});const Ce=P=>{const K=n===P.id,Fe=a?null:Me(P),oe=P.title||s("chatInterface.newChatTitle");return i.jsxs("div",{role:"option","aria-selected":K,tabIndex:0,onKeyDown:Ae=>{(Ae.key==="Enter"||Ae.key===" ")&&(Ae.preventDefault(),ve(P.id))},onClick:()=>ve(P.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
+ ${K?"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":K?"true":void 0,"aria-label":s("sidebar.conversationCard.openAriaLabel",{title:oe}),children:[K&&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 ${K?"bg-sky-500 opacity-100 dark:bg-sky-400":"opacity-0"}`}),y===P.id?i.jsx("input",{type:"text",value:A,onChange:Ae=>L(Ae.target.value.slice(0,pr)),onKeyDown:Ae=>{Ae.key==="Enter"&&re(P.id),Ae.key==="Escape"&&W(),Ae.stopPropagation()},onBlur:()=>re(P.id),maxLength:pr,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":s("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] ${K?"font-semibold text-slate-900 dark:text-[#ececf1]":"font-medium text-slate-700 dark:text-[#c5c8d6]"}`,children:oe}),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(si,{onClick:Ae=>je(Ae,P),label:s("sidebar.conversationCard.editAriaLabel",{title:oe}),hoverClassName:"hover:bg-slate-200/80 hover:text-slate-600 dark:hover:bg-[#3c3f4a] dark:hover:text-[#c5c8d6]",icon:i.jsx(Ri,{className:"h-3.5 w-3.5"})}),i.jsx(si,{onClick:Ae=>B(Ae,P),label:s("sidebar.conversationCard.deleteAriaLabel",{title:oe}),hoverClassName:"hover:bg-red-100/80 hover:text-red-600 dark:hover:bg-red-900/30 dark:hover:text-red-400",icon:i.jsx(Oi,{className:"h-3.5 w-3.5"})})]})]}),Fe&&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:Fe})]})]},P.id)};return i.jsxs(i.Fragment,{children:[!a&&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:E,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:s("sidebar.selectAgent.title")}),i.jsxs("div",{className:"space-y-5",children:[i.jsx(Bf,{selectedAdapter:X,onAdapterChange:ue,disabled:M,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),_(!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:M,children:s("common.cancel")})})]})]})}),i.jsxs("nav",{"aria-label":s("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:[r.length>0&&r.some(P=>P.messages.length>0)&&i.jsxs("button",{onClick:pe,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:s("sidebar.deleteAllConversations.title"),children:[i.jsx(pd,{className:"h-4 w-4"}),s("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":s("sidebar.collapse.ariaLabel"),title:s("sidebar.collapse.title"),children:i.jsx(ad,{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}),J&&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(Ta,{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:T,type:"text",role:"searchbox","aria-label":s("sidebar.search.ariaLabel"),placeholder:s("sidebar.search.placeholder"),value:g,onChange:P=>x(P.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"}),g&&i.jsx("button",{type:"button",onClick:()=>{var P;x(""),(P=T.current)==null||P.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":s("sidebar.search.clearAriaLabel"),children:i.jsx(Je,{className:"h-3.5 w-3.5"})})]}),Y&&i.jsx("p",{"aria-live":"polite",className:"mt-2 text-center text-[11px] tabular-nums text-gray-400 dark:text-[#6e7490]",children:fe.length===0?s("sidebar.resultsNone"):s("sidebar.results",{count:fe.length})})]})]}),i.jsx("div",{ref:D,role:"listbox","aria-label":s("sidebar.conversations.ariaLabel"),onKeyDown:ee,className:"flex-1 overflow-y-auto bg-transparent px-3 py-2",children:fe.length===0?null:Y?i.jsx("div",{className:"space-y-1.5",children:fe.map(Ce)}):i.jsx("div",{className:"space-y-4",children:z.map(P=>i.jsxs("section",{"aria-label":s(`sidebar.timeGroups.${P.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:s(`sidebar.timeGroups.${P.label}`)}),i.jsx("div",{className:"space-y-1.5",children:P.conversations.map(Ce)})]},P.label))})}),(()=>{const P=Ai();return P.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":s("appHeader.navLinksAriaLabel"),children:i.jsx("ul",{className:"flex flex-wrap gap-2",children:P.map(K=>i.jsx("li",{children:i.jsx("a",{href:K.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:K.label})},K.url))})})})})(),i.jsx("div",{className:"shrink-0 border-t border-gray-200/80 dark:border-[#2d2f39]",children:i.jsx(no,{placement:"sidebar",compact:!0})})]}),i.jsx(vr,{isOpen:C.isOpen,onClose:ie,onConfirm:ae,title:s("sidebar.deleteConfirm.title"),message:s("sidebar.deleteConfirm.message",{title:C.conversationTitle}),confirmText:s("sidebar.deleteConfirm.confirmText"),cancelText:s("common.cancel"),type:"danger",isLoading:C.isDeleting}),i.jsx(vr,{isOpen:N.isOpen,onClose:be,onConfirm:_e,title:s("sidebar.clearAllConfirm.title"),message:s("sidebar.clearAllConfirm.message",{count:se}),confirmText:s("sidebar.clearAllConfirm.confirmText"),cancelText:s("common.cancel"),type:"danger",isLoading:N.isDeleting})]})}const qf="3.11.7",Wf={version:qf},Oa=Wf.version,Kf=["@@auth0spajs@@","a0.spajs","auth0","com.auth0"];function Gf(t){const e=t.toLowerCase();return Kf.some(s=>e.includes(s.toLowerCase()))}function Xf(t){const e=[];for(let s=0;s<t.length;s++){const a=t.key(s);a&&Gf(a)&&e.push(a)}e.forEach(s=>t.removeItem(s))}function ai(t){try{Xf(t),t.clear()}catch(e){console.warn("[Settings] Failed to clear browser storage during reset.",e)}}function Yf(){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(a=>{const r=a.indexOf("="),n=(r>-1?a.slice(0,r):a).trim();n&&t.forEach(o=>{const l=o?`;domain=${o}`:"";document.cookie=`${n}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${l}`})})}function Qf(){ai(localStorage),ai(sessionStorage),Yf()}function Zf({isOpen:t,onClose:e}){const{t:s}=Le(),{theme:a,updateTheme:r}=ts(),{settings:n,updateSettings:o}=Lr(),{activeLanguages:l,currentLanguage:c,setLanguage:d}=Pc(),[u,f]=h.useState(!1),[m,p]=h.useState(!1),g=h.useRef(null),x=h.useRef(null),y=h.useMemo(()=>[...l].sort((N,R)=>ar[N].localeCompare(ar[R])),[l]);h.useEffect(()=>{if(!m)return;const N=R=>{R.key==="Escape"&&(R.stopPropagation(),p(!1))};return document.addEventListener("keydown",N,{capture:!0}),()=>document.removeEventListener("keydown",N,{capture:!0})},[m]);const k=N=>{r({mode:N})},A=()=>{o({soundEnabled:!n.soundEnabled})},L=()=>{f(!0)},C=()=>{f(!1)},v=()=>{C(),Fr(),$r(!1),us(null),ot.getState().closeLoginPrompt(),Qf(),window.location.reload()};return Ds(g,{enabled:t&&!u,onEscape:e}),Ds(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":s("settings.dialog.closeOverlayAriaLabel"),className:"absolute inset-0"}),i.jsxs("div",{onClick:N=>N.stopPropagation(),ref:g,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:s("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":s("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(rd,{className:"w-5 h-5"}),s("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:s("settings.appearance.themeLabel")}),i.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{value:"light",label:s("settings.appearance.themeLight"),icon:hd},{value:"dark",label:s("settings.appearance.themeDark"),icon:sd},{value:"system",label:s("settings.appearance.themeSystem"),icon:td}].map(({value:N,label:R,icon:b})=>i.jsxs("button",{onClick:()=>k(N),className:`flex flex-col items-center gap-2 p-3 rounded-lg border-2 transition-all duration-200 ${a.mode===N?"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:R})]},N))})]}),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(Xc,{className:"w-4 h-4"}),s("settings.language.label")]}),i.jsxs("div",{className:"relative",children:[i.jsxs("button",{type:"button",onClick:()=>p(N=>!N),"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:ar[c]}),i.jsx(fs,{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:()=>p(!1)}),i.jsx("div",{role:"listbox","aria-label":s("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(N=>{const R=N===c;return i.jsxs("button",{type:"button",role:"option","aria-selected":R,onClick:()=>{d(N),p(!1)},className:`flex w-full items-center justify-between gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors ${R?"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:ar[N]}),R&&i.jsx(ds,{className:"h-4 w-4 flex-shrink-0 text-blue-600 dark:text-blue-400"})]},N)})})]})]})]})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:s("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($a,{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:s("settings.soundEffects.label")}),i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s("settings.soundEffects.description")})]})]}),i.jsx("button",{onClick:A,role:"switch","aria-checked":n.soundEnabled,"aria-label":s("settings.soundEffects.toggleAriaLabel"),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${n.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 ${n.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(Oi,{className:"w-5 h-5"}),s("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:s("settings.dataManagement.description")}),i.jsx("button",{onClick:L,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:s("settings.reset.button")})]})]}),i.jsxs("p",{className:"pt-2 text-center text-xs text-gray-400 dark:text-[#858999]",children:["v",Oa]})]}),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(Fa,{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:s("settings.reset.confirmTitle")}),i.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:s("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:s("common.cancel")}),i.jsx("button",{onClick:v,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:s("settings.reset.confirmButton")})]})]})})]})]}):null}function Jf({message:t}){const{t:e}=Le(),s=Ia();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:s}),i.jsxs("span",{className:"shrink-0 text-xs font-medium text-slate-400 dark:text-[#858999]",children:["v",Oa]})]}),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(dd,{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 eh({children:t}){const{instance:e,accounts:s}=Ca(),a=Zo();return h.useEffect(()=>{$r(a)},[a]),h.useEffect(()=>{if(!a||s.length===0){us(null);return}const r=s[0];us(r.username||r.name||r.localAccountId||null)},[a,s]),h.useEffect(()=>{if(!a||s.length===0)return;const r=s[0],n=_a();return zi(async()=>(await e.acquireTokenSilent({scopes:n,account:r})).accessToken),()=>Fr()},[a,s,e]),i.jsx(i.Fragment,{children:t})}function th({children:t}){return i.jsx(eh,{children:t})}function sh({children:t}){const{isLoading:e,isAuthenticated:s,getAccessTokenSilently:a,user:r}=Aa();return h.useEffect(()=>{$r(s)},[s]),h.useEffect(()=>{if(!s){us(null);return}const n=(r==null?void 0:r.sub)||(r==null?void 0:r.email)||(r==null?void 0:r.nickname)||(r==null?void 0:r.name)||null;us(n)},[s,r]),h.useEffect(()=>(s&&zi(()=>a()),()=>Fr()),[s,a]),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 rh({children:t}){return h.useEffect(()=>{$r(!1),us(null),Fr()},[]),i.jsx(i.Fragment,{children:t})}function ah({children:t}){return it()?Tr()==="entra"?i.jsx(th,{children:t}):i.jsx(sh,{children:t}):i.jsx(rh,{children:t})}function nh(){const t=Ea(),e=it(),s=hs(),{showLoginPrompt:a,promptMessage:r,closeLoginPrompt:n}=ot();return h.useEffect(()=>{a&&(!t||!e||s)&&n()},[a,t,e,s,n]),!t||!e||s||!a?null:Tr()==="entra"?i.jsx(oh,{message:r,onClose:n}):i.jsx(ih,{message:r,onClose:n})}function ih({message:t,onClose:e}){const{loginWithRedirect:s}=Aa();return i.jsx(fo,{message:t,onClose:e,onLogin:()=>s()})}function oh({message:t,onClose:e}){const{instance:s}=Ca();return i.jsx(fo,{message:t,onClose:e,onLogin:()=>s.loginRedirect({scopes:_a()}).catch(()=>{})})}function fo({message:t,onClose:e,onLogin:s}){const{t:a}=Le();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":a("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($i,{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:a("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:s,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:a("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:a("common.cancel")})]})]})]})}function lh(){const{t}=Le(),{goHome:e}=co(),{isDark:s}=ts(),a=bf(),r=h.useRef(!1),n=bc(),o=yc(),l=wc(),c=s?l:o,d=kc(),u=vc(),f=!!(d||u),m=Sc(),p=jc(),g=Cc(),x=Ai(),y=g?"border-b border-slate-200/80 dark:border-[#333645]":"",k="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(()=>{r.current},[l,n,o]),pa()?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:p||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:a,"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:k,style:{color:p||void 0},children:A.label})},A.url))})}),i.jsx(Sa,{})]})]})}):null}function ch({children:t}){const e=h.useRef(null),s=h.useCallback(r=>{e.current=r},[]),a=h.useCallback(()=>{var r;(r=e.current)==null||r.call(e)},[]);return i.jsx(lo.Provider,{value:{registerGoHome:s,goHome:a},children:t})}function dh(){const{t}=Le(),[e,s]=h.useState(!1),[a,r]=h.useState(!1),[n,o]=h.useState(()=>localStorage.getItem("desktop-sidebar-collapsed")==="true"),l=we(u=>u.conversations),c=pc();if(h.useEffect(()=>{localStorage.setItem("desktop-sidebar-collapsed",String(n))},[n]),c)return i.jsx(an,{children:i.jsx(Jf,{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(an,{children:i.jsx(sl,{children:i.jsx(Rc,{children:i.jsx(ah,{children:i.jsx(ch,{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&&(n?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(nd,{className:"h-4 w-4"})})}):i.jsx("div",{className:"hidden md:h-full md:flex",children:i.jsx(ri,{onToggleDesktopSidebar:()=>o(!0)})})),i.jsxs("div",{className:"flex-1 flex flex-col w-full min-h-0",children:[i.jsx(lh,{}),i.jsx("div",{className:"flex-1 flex justify-center w-full min-h-0",children:i.jsx(zf,{onOpenSettings:()=>s(!0),onOpenSidebar:()=>r(!0)})})]})]}),i.jsx(nh,{}),i.jsx(Zf,{isOpen:e,onClose:()=>s(!1)}),a&&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:()=>r(!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(ri,{onRequestClose:()=>r(!1)}),i.jsx("button",{onClick:()=>r(!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 oa=new Jo({auth:{clientId:ji(),authority:`https://login.microsoftonline.com/${xc()}`,redirectUri:typeof window<"u"?window.location.origin:"/"},cache:{cacheLocation:"sessionStorage"}});function uh({children:t}){const[e,s]=h.useState(!1);return h.useEffect(()=>{oa.initialize().then(()=>oa.handleRedirectPromise()).catch(a=>{console.error("[EntraAuth] Redirect processing failed:",a)}).finally(()=>s(!0))},[]),e?i.jsx(el,{instance:oa,children:t}):null}function fh({children:t}){if(!Ea()||!it())return i.jsx(i.Fragment,{children:t});if(Tr()==="entra")return i.jsx(uh,{children:t});const s=mc(),a=ji(),r=gc();return!s||!a?i.jsx(i.Fragment,{children:t}):i.jsx(tl,{domain:s,clientId:a,authorizationParams:{redirect_uri:window.location.origin,...r?{audience:r}:{}},cacheLocation:"memory",children:t})}uo(null);const ni=ic(),ii=document.querySelector('link[rel="icon"]');if(ii)ii.href=ni;else{const t=document.createElement("link");t.rel="icon",t.href=ni,document.head.appendChild(t)}const hh=Tc();var oi,li,ci,di,ui,fi;for(const t of hh){const e=((oi=t.src)==null?void 0:oi.trim())||"",s=((li=t.content)==null?void 0:li.trim())||"",a=((ci=t.id)==null?void 0:ci.trim())||"";if(!e&&!s||a&&document.querySelector(`script[data-orbitchat-startup-script-id="${a}"]`)||Array.from(document.querySelectorAll("script[data-orbitchat-startup-script]")).some(o=>{const l=e&&o.dataset.orbitchatStartupScriptSrc===e,c=s&&(o.textContent||"").trim()===s;return!!(l||c)}))continue;const n=document.createElement("script");e&&(n.src=e),s&&(n.text=s),n.async=t.async??!0,t.defer!==void 0&&(n.defer=t.defer),(di=t.type)!=null&&di.trim()&&(n.type=t.type.trim()),(ui=t.integrity)!=null&&ui.trim()&&(n.integrity=t.integrity.trim()),t.crossOrigin&&(n.crossOrigin=t.crossOrigin),(fi=t.referrerPolicy)!=null&&fi.trim()&&(n.referrerPolicy=t.referrerPolicy.trim()),n.dataset.orbitchatStartupScript="true",a&&(n.dataset.orbitchatStartupScriptId=a),e&&(n.dataset.orbitchatStartupScriptSrc=e),document.head.appendChild(n)}U("🚀 AI Chat Application started");U(`📱 App Version: v${Oa}`);Do.createRoot(document.getElementById("root")).render(i.jsx(h.StrictMode,{children:i.jsx(fh,{children:i.jsx(dh,{})})}));export{Pl as r,Le as u};