orbitchat 3.10.9 → 3.11.1

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 (82) hide show
  1. package/bin/orbitchat.js +4 -0
  2. package/dist/assets/ChartRenderer-OBjJRngd.js +97 -0
  3. package/dist/assets/{MermaidRenderer-yw6DgH3b.js → MermaidRenderer-CPPq3mmd.js} +47 -47
  4. package/dist/assets/MusicRenderer-ZqWcBGEP.js +18 -0
  5. package/dist/assets/SVGRenderer-C23bZ16J.js +6 -0
  6. package/dist/assets/architectureDiagram-3BPJPVTR-1DcnIrTf.js +36 -0
  7. package/dist/assets/{blockDiagram-GPEHLZMM-SCn-DUpY.js → blockDiagram-GPEHLZMM-C3O1Y3wQ.js} +2 -2
  8. package/dist/assets/{c4Diagram-AAUBKEIU-CD0XXb4K.js → c4Diagram-AAUBKEIU-7ulfaeio.js} +4 -4
  9. package/dist/assets/channel-DIz7au4Z.js +1 -0
  10. package/dist/assets/{chunk-2J33WTMH-D1ecF70l.js → chunk-2J33WTMH-CtTVan3g.js} +1 -1
  11. package/dist/assets/{chunk-4BX2VUAB-BdC2_BbM.js → chunk-4BX2VUAB-D9LhpL0M.js} +1 -1
  12. package/dist/assets/{chunk-55IACEB6-EK7W6T2M.js → chunk-55IACEB6-o4c6_uWz.js} +1 -1
  13. package/dist/assets/{chunk-727SXJPM-CcXyDAeg.js → chunk-727SXJPM-qMeBxfHH.js} +1 -1
  14. package/dist/assets/{chunk-AQP2D5EJ-DW6XiznW.js → chunk-AQP2D5EJ-Bwo9IL4J.js} +1 -1
  15. package/dist/assets/{chunk-FMBD7UC4-CPehXR20.js → chunk-FMBD7UC4-BhdowZ3g.js} +1 -1
  16. package/dist/assets/{chunk-ND2GUHAM-CSSdlZau.js → chunk-ND2GUHAM-DHj38vtV.js} +1 -1
  17. package/dist/assets/{chunk-QZHKN3VN-DqF1rB9S.js → chunk-QZHKN3VN-BQlh1k-T.js} +1 -1
  18. package/dist/assets/classDiagram-4FO5ZUOK-B_41sQFe.js +1 -0
  19. package/dist/assets/classDiagram-v2-Q7XG4LA2-B_41sQFe.js +1 -0
  20. package/dist/assets/cose-bilkent-S5V4N54A-DIlweU0c.js +1 -0
  21. package/dist/assets/{cynefin-VYW2F7L2-CPNTSJVR.js → cynefin-VYW2F7L2-COfqkbsu.js} +1 -1
  22. package/dist/assets/dagre-BM42HDAG-Dg1vRQoJ.js +4 -0
  23. package/dist/assets/diagram-2AECGRRQ-5qMJzPlj.js +43 -0
  24. package/dist/assets/diagram-5GNKFQAL-BtLOXreJ.js +10 -0
  25. package/dist/assets/{diagram-KO2AKTUF-PtoEeRz1.js → diagram-KO2AKTUF-CItPbbPJ.js} +2 -2
  26. package/dist/assets/diagram-LMA3HP47-C-rMj79O.js +24 -0
  27. package/dist/assets/diagram-OG6HWLK6-CsH38nnV.js +24 -0
  28. package/dist/assets/{docx-preview-CMb3nQfR.js → docx-preview-DehBmhog.js} +1 -1
  29. package/dist/assets/{erDiagram-TEJ5UH35-BsN2y1Xk.js → erDiagram-TEJ5UH35-D4EO2CJ1.js} +13 -13
  30. package/dist/assets/{flowDiagram-I6XJVG4X-Cq2OCvg1.js → flowDiagram-I6XJVG4X-DgOIMYGk.js} +2 -2
  31. package/dist/assets/{ganttDiagram-6RSMTGT7-jqEV7dNL.js → ganttDiagram-6RSMTGT7-B1I1ERYN.js} +2 -2
  32. package/dist/assets/gitGraphDiagram-PVQCEYII-BbxU9vdc.js +106 -0
  33. package/dist/assets/index-BNiRF5ts.js +355 -0
  34. package/dist/assets/{index-C0slAIYD.js → index-Bm2RXT20.js} +1 -1
  35. package/dist/assets/index-Dn6drGB8.css +1 -0
  36. package/dist/assets/infoDiagram-5YYISTIA-BSCHNtfq.js +2 -0
  37. package/dist/assets/{ishikawaDiagram-YF4QCWOH-D9KfSIa7.js → ishikawaDiagram-YF4QCWOH-D3EauiiJ.js} +2 -2
  38. package/dist/assets/{journeyDiagram-JHISSGLW-tDXNol4d.js → journeyDiagram-JHISSGLW-BS1VWAga.js} +4 -4
  39. package/dist/assets/{kanban-definition-UN3LZRKU-DBwlSBF_.js → kanban-definition-UN3LZRKU-ClAYLC3L.js} +9 -9
  40. package/dist/assets/locales-4Dy5QB82.js +1 -0
  41. package/dist/assets/{mindmap-definition-RKZ34NQL-DnqCIXkX.js → mindmap-definition-RKZ34NQL-BkDMrGTA.js} +2 -2
  42. package/dist/assets/{papaparse.min-BWA-Odol.js → papaparse.min-D13ujVVP.js} +1 -1
  43. package/dist/assets/pieDiagram-4H26LBE5-BOj8AQSK.js +30 -0
  44. package/dist/assets/{quadrantDiagram-W4KKPZXB-CAZOzJOz.js → quadrantDiagram-W4KKPZXB-BM7sUdWh.js} +2 -2
  45. package/dist/assets/{requirementDiagram-4Y6WPE33-Ji0UfPIj.js → requirementDiagram-4Y6WPE33-D2pnnYZP.js} +2 -2
  46. package/dist/assets/{sankeyDiagram-5OEKKPKP-Bw7GXHmh.js → sankeyDiagram-5OEKKPKP-D3Z4Gd94.js} +2 -2
  47. package/dist/assets/{sequenceDiagram-3UESZ5HK-m5wt325o.js → sequenceDiagram-3UESZ5HK-DE73ZFHe.js} +14 -14
  48. package/dist/assets/stateDiagram-AJRCARHV-C7CGkF3t.js +1 -0
  49. package/dist/assets/stateDiagram-v2-BHNVJYJU-DHQUbGB3.js +1 -0
  50. package/dist/assets/{timeline-definition-PNZ67QCA-f8uHcy4Y.js → timeline-definition-PNZ67QCA-xIsXJSbZ.js} +2 -2
  51. package/dist/assets/{vendor-auth-CF3lY_Q5.js → vendor-auth-aD_bwYde.js} +2 -2
  52. package/dist/assets/vendor-markdown-Cy_-N5ZX.js +291 -0
  53. package/dist/assets/vendor-markdown-dRWncRqa.css +1 -0
  54. package/dist/assets/vendor-react-BbEy7z12.js +49 -0
  55. package/dist/assets/{vendor-syntax-DG6Vo7Ci.js → vendor-syntax-INF7-xC_.js} +9 -9
  56. package/dist/assets/{vennDiagram-CIIHVFJN-CuKQ09R1.js → vennDiagram-CIIHVFJN-a62PVgzJ.js} +2 -2
  57. package/dist/assets/{wardleyDiagram-YWT4CUSO-iQQlbl48.js → wardleyDiagram-YWT4CUSO-DDy1YaOr.js} +2 -2
  58. package/dist/assets/{xychartDiagram-2RQKCTM6-B4vp4-Xh.js → xychartDiagram-2RQKCTM6-6XfTk_6y.js} +2 -2
  59. package/dist/index.html +8 -6
  60. package/package.json +5 -3
  61. package/dist/assets/ChartRenderer-Cbyse7LH.js +0 -105
  62. package/dist/assets/MusicRenderer-BSZsjBll.js +0 -18
  63. package/dist/assets/SVGRenderer-DfMpobkd.js +0 -6
  64. package/dist/assets/architectureDiagram-3BPJPVTR-e2_vf6sQ.js +0 -36
  65. package/dist/assets/channel-zV0lWbMa.js +0 -1
  66. package/dist/assets/classDiagram-4FO5ZUOK-CcqSZVcR.js +0 -1
  67. package/dist/assets/classDiagram-v2-Q7XG4LA2-CcqSZVcR.js +0 -1
  68. package/dist/assets/cose-bilkent-S5V4N54A-eZksLHnB.js +0 -1
  69. package/dist/assets/dagre-BM42HDAG-28cMnF2H.js +0 -4
  70. package/dist/assets/diagram-2AECGRRQ-BO7iijXf.js +0 -43
  71. package/dist/assets/diagram-5GNKFQAL-DomATWxv.js +0 -10
  72. package/dist/assets/diagram-LMA3HP47-CASxB1FB.js +0 -24
  73. package/dist/assets/diagram-OG6HWLK6-CyXBWSCx.js +0 -24
  74. package/dist/assets/gitGraphDiagram-PVQCEYII-CZV87DUI.js +0 -106
  75. package/dist/assets/index-ADlI5-NQ.css +0 -1
  76. package/dist/assets/index-DJM2KXCF.js +0 -366
  77. package/dist/assets/infoDiagram-5YYISTIA-BTT1LXE4.js +0 -2
  78. package/dist/assets/pieDiagram-4H26LBE5-C4OTftBM.js +0 -30
  79. package/dist/assets/stateDiagram-AJRCARHV-BkfQ-aKY.js +0 -1
  80. package/dist/assets/stateDiagram-v2-BHNVJYJU-CrYKygqF.js +0 -1
  81. package/dist/assets/vendor-markdown-BRX1CUPf.js +0 -307
  82. package/dist/assets/vendor-react-BAJBiXxk.js +0 -9
@@ -0,0 +1,355 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MermaidRenderer-CPPq3mmd.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-C23bZ16J.js","assets/locales-4Dy5QB82.js","assets/vendor-markdown-Cy_-N5ZX.js","assets/vendor-markdown-dRWncRqa.css","assets/vendor-auth-aD_bwYde.js","assets/ChartRenderer-OBjJRngd.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-ZqWcBGEP.js","assets/papaparse.min-D13ujVVP.js","assets/docx-preview-DehBmhog.js"])))=>i.map(i=>d[i]);
2
+ var wo=Object.defineProperty;var ko=(t,e,s)=>e in t?wo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var Xe=(t,e,s)=>ko(t,typeof e!="symbol"?e+"":e,s);import{r as h,j as a,a as vo,R as vt,b as Ir,d as So}from"./vendor-react-BbEy7z12.js";import{z as jo,p as Co,j as No,f as Ao,e as Io,a as Lo,d as Eo}from"./locales-4Dy5QB82.js";import{M as To,r as Qn,a as _o,b as Mo}from"./vendor-markdown-Cy_-N5ZX.js";import{_ as St,h as Fo,v as $o,a as Po}from"./vendor-syntax-INF7-xC_.js";import{u as wn,a as kn,b as Ro,P as Do,M as Oo,A as Uo}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"]'))n(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();const ri=h.createContext(void 0);function Jn({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}}),[n,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 i=o=>{s(l=>({...l,...o}))};return a.jsx(ri.Provider,{value:{theme:e,updateTheme:i,isDark:n},children:t})}function ds(){const t=h.useContext(ri);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}const ni=h.createContext(void 0),Kr={voiceEnabled:!1,soundEnabled:!1,autoSend:!1};function zo({children:t}){const[e,s]=h.useState(()=>{const r=localStorage.getItem("chat-settings");if(r)try{const i=JSON.parse(r);return{...Kr,...i,voiceEnabled:!1}}catch{return Kr}return Kr});h.useEffect(()=>{localStorage.setItem("chat-settings",JSON.stringify(e))},[e]);const n=r=>{s(i=>({...i,...r}))};return a.jsx(ni.Provider,{value:{settings:e,updateSettings:n},children:t})}function Lr(){const t=h.useContext(ni);if(!t)throw new Error("useSettings must be used within SettingsProvider");return t}const he=t=>typeof t=="string",Ns=()=>{let t,e;const s=new Promise((n,r)=>{t=n,e=r});return s.resolve=t,s.reject=e,s},Zn=t=>t==null?"":String(t),Bo=(t,e,s)=>{t.forEach(n=>{e[n]&&(s[n]=e[n])})},Ho=/###/g,ea=t=>t&&t.includes("###")?t.replace(Ho,"."):t,ta=t=>!t||he(t),Es=(t,e,s)=>{const n=he(e)?e.split("."):e;let r=0;for(;r<n.length-1;){if(ta(t))return{};const i=ea(n[r]);!t[i]&&s&&(t[i]=new s),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++r}return ta(t)?{}:{obj:t,k:ea(n[r])}},sa=(t,e,s)=>{const{obj:n,k:r}=Es(t,e,Object);if(n!==void 0||e.length===1){n[r]=s;return}let i=e[e.length-1],o=e.slice(0,e.length-1),l=Es(t,o,Object);for(;l.obj===void 0&&o.length;)i=`${o[o.length-1]}.${i}`,o=o.slice(0,o.length-1),l=Es(t,o,Object),l!=null&&l.obj&&typeof l.obj[`${l.k}.${i}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${i}`]=s},Vo=(t,e,s,n)=>{const{obj:r,k:i}=Es(t,e,Object);r[i]=r[i]||[],r[i].push(s)},xr=(t,e)=>{const{obj:s,k:n}=Es(t,e);if(s&&Object.prototype.hasOwnProperty.call(s,n))return s[n]},qo=(t,e,s)=>{const n=xr(t,s);return n!==void 0?n:xr(e,s)},ai=(t,e,s)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(Object.prototype.hasOwnProperty.call(t,n)?he(t[n])||t[n]instanceof String||he(e[n])||e[n]instanceof String?s&&(t[n]=e[n]):ai(t[n],e[n],s):t[n]=e[n]);return t},Nt=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),Wo={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"},Ko=t=>he(t)?t.replace(/[&<>"'\/]/g,e=>Wo[e]):t;class Go{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 n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}}const Xo=[" ",",","?","!",";"],Yo=new Go(20),Qo=(t,e,s)=>{e=e||"",s=s||"";const n=Xo.filter(o=>!e.includes(o)&&!s.includes(o));if(n.length===0)return!0;const r=Yo.getRegExp(`(${n.map(o=>o==="?"?"\\?":o).join("|")})`);let i=!r.test(t);if(!i){const o=t.indexOf(s);o>0&&!r.test(t.substring(0,o))&&(i=!0)}return i},an=(t,e,s=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const n=e.split(s);let r=t;for(let i=0;i<n.length;){if(!r||typeof r!="object")return;let o,l="";for(let c=i;c<n.length;++c)if(c!==i&&(l+=s),l+=n[c],o=r[l],o!==void 0){if(["string","number","boolean"].includes(typeof o)&&c<n.length-1)continue;i+=c-i+1;break}r=o}return r},Fs=t=>t==null?void 0:t.replace(/_/g,"-"),Jo={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,n;(n=(s=console==null?void 0:console[t])==null?void 0:s.apply)==null||n.call(s,console,e)}};class br{constructor(e,s={}){this.init(e,s)}init(e,s={}){this.prefix=s.prefix||"i18next:",this.logger=e||Jo,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,n,r){return r&&!this.debug?null:(e=e.map(i=>he(i)?i.replace(/[\r\n\x00-\x1F\x7F]/g," "):i),he(e[0])&&(e[0]=`${n}${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 jt=new br;class Er{constructor(){this.observers={}}on(e,s){return e.split(" ").forEach(n=>{this.observers[n]||(this.observers[n]=new Map);const r=this.observers[n].get(s)||0;this.observers[n].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 n=(...r)=>{s(...r),this.off(e,n)};return this.on(e,n),this}emit(e,...s){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([r,i])=>{for(let o=0;o<i;o++)r(...s)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([r,i])=>{for(let o=0;o<i;o++)r(e,...s)})}}class ra 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,n,r={}){var d,u;const i=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],n&&(Array.isArray(n)?l.push(...n):he(n)&&i?l.push(...n.split(i)):l.push(n)));const c=xr(this.data,l);return!c&&!s&&!n&&e.includes(".")&&(e=l[0],s=l[1],n=l.slice(2).join(".")),c||!o||!he(n)?c:an((u=(d=this.data)==null?void 0:d[e])==null?void 0:u[s],n,i)}addResource(e,s,n,r,i={silent:!1}){const o=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator;let l=[e,s];n&&(l=l.concat(o?n.split(o):n)),e.includes(".")&&(l=e.split("."),r=s,s=l[1]),this.addNamespaces(s),sa(this.data,l,r),i.silent||this.emit("added",e,s,n,r)}addResources(e,s,n,r={silent:!1}){for(const i in n)(he(n[i])||Array.isArray(n[i]))&&this.addResource(e,s,i,n[i],{silent:!0});r.silent||this.emit("added",e,s,n)}addResourceBundle(e,s,n,r,i,o={silent:!1,skipCopy:!1}){let l=[e,s];e.includes(".")&&(l=e.split("."),r=n,n=s,s=l[1]),this.addNamespaces(s);let c=xr(this.data,l)||{};o.skipCopy||(n=JSON.parse(JSON.stringify(n))),r?ai(c,n,i):c={...c,...n},sa(this.data,l,c),o.silent||this.emit("added",e,s,n)}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 ii={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,s,n,r){return t.forEach(i=>{var o;e=((o=this.processors[i])==null?void 0:o.process(e,s,n,r))??e}),e}};const oi=Symbol("i18next/PATH_KEY");function Zo(){const t=[],e=Object.create(null);let s;return e.get=(n,r)=>{var i;return(i=s==null?void 0:s.revoke)==null||i.call(s),r===oi?t:(t.push(r),s=Proxy.revocable(n,e),s.proxy)},Proxy.revocable(Object.create(null),e).proxy}function ls(t,e){const{[oi]:s}=t(Zo()),n=(e==null?void 0:e.keySeparator)??".",r=(e==null?void 0:e.nsSeparator)??":",i=(e==null?void 0:e.enableSelector)==="strict";if(s.length>1&&r){const o=e==null?void 0:e.ns,l=i?Array.isArray(o)?o:o?[o]:null:Array.isArray(o)?o:null;if(l&&(i?l:l.length>1?l.slice(1):[]).includes(s[0]))return`${s[0]}${r}${s.slice(1).join(n)}`}return s.join(n)}const Gr=t=>!he(t)&&typeof t!="boolean"&&typeof t!="number";class yr extends Er{constructor(e,s={}){super(),Bo(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=s,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=jt.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,s={interpolation:{}}){const n={...s};if(e==null)return!1;const r=this.resolve(e,n);if((r==null?void 0:r.res)===void 0)return!1;const i=Gr(r.res);return!(n.returnObjects===!1&&i)}extractFromKey(e,s){let n=s.nsSeparator!==void 0?s.nsSeparator:this.options.nsSeparator;n===void 0&&(n=":");const r=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let i=s.ns||this.options.defaultNS||[];const o=n&&e.includes(n),l=!this.options.userDefinedKeySeparator&&!s.keySeparator&&!this.options.userDefinedNsSeparator&&!s.nsSeparator&&!Qo(e,n,r);if(o&&!l){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:he(i)?[i]:i};const d=e.split(n);(n!==r||n===r&&this.options.ns.includes(d[0]))&&(i=d.shift()),e=d.join(r)}return{key:e,namespaces:he(i)?[i]:i}}translate(e,s,n){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=ls(e,{...this.options,...r})),Array.isArray(e)||(e=[String(e)]),e=e.map(_=>typeof _=="function"?ls(_,{...this.options,...r}):String(_));const i=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,p=r.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if((f==null?void 0:f.toLowerCase())==="cimode")return p?i?{res:`${d}${u}${l}`,usedKey:l,exactUsedKey:l,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(r)}:`${d}${u}${l}`:i?{res:l,usedKey:l,exactUsedKey:l,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(r)}:l;const m=this.resolve(e,r);let g=m==null?void 0:m.res;const x=(m==null?void 0:m.usedKey)||l,y=(m==null?void 0:m.exactUsedKey)||l,v=["[object Number]","[object Function]","[object RegExp]"],A=r.joinArrays!==void 0?r.joinArrays:this.options.joinArrays,I=!this.i18nFormat||this.i18nFormat.handleAsObject,S=r.count!==void 0&&!he(r.count),C=yr.hasDefaultValue(r),L=S?this.pluralResolver.getSuffix(f,r.count,r):"",F=r.ordinal&&S?this.pluralResolver.getSuffix(f,r.count,{ordinal:!1}):"",b=S&&!r.ordinal&&r.count===0,E=b&&r[`defaultValue${this.options.pluralSeparator}zero`]||r[`defaultValue${L}`]||r[`defaultValue${F}`]||r.defaultValue;let k=g;I&&!g&&C&&(k=E);const N=Gr(k),T=Object.prototype.toString.apply(k);if(I&&k&&N&&!v.includes(T)&&!(he(A)&&Array.isArray(k))){if(!r.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const _=this.options.returnedObjectHandler?this.options.returnedObjectHandler(x,k,{...r,ns:c}):`key '${l} (${this.language})' returned an object instead of string.`;return i?(m.res=_,m.usedParams=this.getUsedParamsDetails(r),m):_}if(o){const _=Array.isArray(k),O=_?[]:{},j=_?y:x;for(const U in k)if(Object.prototype.hasOwnProperty.call(k,U)){const z=`${j}${o}${U}`;C&&!g?O[U]=this.translate(z,{...r,defaultValue:Gr(E)?E[U]:void 0,joinArrays:!1,ns:c}):O[U]=this.translate(z,{...r,joinArrays:!1,ns:c}),O[U]===z&&(O[U]=k[U])}g=O}}else if(I&&he(A)&&Array.isArray(g))g=g.join(A),g&&(g=this.extendTranslation(g,e,r,n));else{let _=!1,O=!1;!this.isValidLookup(g)&&C&&(_=!0,g=E),this.isValidLookup(g)||(O=!0,g=l);const U=(r.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&O?void 0:g,z=C&&E!==g&&this.options.updateMissing;if(O||_||z){if(this.logger.log(z?"updateKey":"missingKey",f,d,S&&!z?`${l}${this.pluralResolver.getSuffix(f,r.count,r)}`:l,z?E: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 R=[];const X=this.languageUtils.getFallbackCodes(this.options.fallbackLng,r.lng||this.language);if(this.options.saveMissingTo==="fallback"&&X&&X[0])for(let V=0;V<X.length;V++)R.push(X[V]);else this.options.saveMissingTo==="all"?R=this.languageUtils.toResolveHierarchy(r.lng||this.language):R.push(r.lng||this.language);const te=(V,ee,me)=>{var re;const D=C&&me!==g?me:U;this.options.missingKeyHandler?this.options.missingKeyHandler(V,d,ee,D,z,r):(re=this.backendConnector)!=null&&re.saveMissing&&this.backendConnector.saveMissing(V,d,ee,D,z,r),this.emit("missingKey",V,d,ee,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&S?R.forEach(V=>{const ee=this.pluralResolver.getSuffixes(V,r);b&&r[`defaultValue${this.options.pluralSeparator}zero`]&&!ee.includes(`${this.options.pluralSeparator}zero`)&&ee.push(`${this.options.pluralSeparator}zero`),ee.forEach(me=>{te([V],l+me,r[`defaultValue${me}`]||E)})}):te(R,l,E))}g=this.extendTranslation(g,e,r,m,n),O&&g===l&&this.options.appendNamespaceToMissingKey&&(g=`${d}${u}${l}`),(O||_)&&this.options.parseMissingKeyHandler&&(g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${l}`:l,_?g:void 0,r))}return i?(m.res=g,m.usedParams=this.getUsedParamsDetails(r),m):g}extendTranslation(e,s,n,r,i){var c,d;if((c=this.i18nFormat)!=null&&c.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||r.usedLng,r.usedNS,r.usedKey,{resolved:r});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});const u=he(e)&&(((d=n==null?void 0:n.interpolation)==null?void 0:d.skipOnVariables)!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let f;if(u){const m=e.match(this.interpolator.nestingRegexp);f=m&&m.length}let p=n.replace&&!he(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(p={...this.options.interpolation.defaultVariables,...p}),e=this.interpolator.interpolate(e,p,n.lng||this.language||r.usedLng,n),u){const m=e.match(this.interpolator.nestingRegexp),g=m&&m.length;f<g&&(n.nest=!1)}!n.lng&&r&&r.res&&(n.lng=this.language||r.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...m)=>(i==null?void 0:i[0])===m[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${m[0]} in key: ${s[0]}`),null):this.translate(...m,s),n)),n.interpolation&&this.interpolator.reset()}const o=n.postProcess||this.options.postProcess,l=he(o)?[o]:o;return e!=null&&(l!=null&&l.length)&&n.applyPostProcessor!==!1&&(e=ii.handle(l,e,s,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...r,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,s={}){let n,r,i,o,l;return he(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(c=>typeof c=="function"?ls(c,{...this.options,...s}):c)),e.forEach(c=>{if(this.isValidLookup(n))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 p=s.count!==void 0&&!he(s.count),m=p&&!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 v,A;this.isValidLookup(n)||(l=y,!this.checkedLoadedFor[`${x[0]}-${y}`]&&((v=this.utils)!=null&&v.hasLoadedNamespace)&&!((A=this.utils)!=null&&A.hasLoadedNamespace(l))&&(this.checkedLoadedFor[`${x[0]}-${y}`]=!0,this.logger.warn(`key "${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(I=>{var L;if(this.isValidLookup(n))return;o=I;const S=[u];if((L=this.i18nFormat)!=null&&L.addLookupKeys)this.i18nFormat.addLookupKeys(S,u,I,y,s);else{let F;p&&(F=this.pluralResolver.getSuffix(I,s.count,s));const b=`${this.options.pluralSeparator}zero`,E=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(s.ordinal&&F.startsWith(E)&&S.push(u+F.replace(E,this.options.pluralSeparator)),S.push(u+F),m&&S.push(u+b)),g){const k=`${u}${this.options.contextSeparator||"_"}${s.context}`;S.push(k),p&&(s.ordinal&&F.startsWith(E)&&S.push(k+F.replace(E,this.options.pluralSeparator)),S.push(k+F),m&&S.push(k+b))}}let C;for(;C=S.pop();)this.isValidLookup(n)||(i=C,n=this.getResource(I,y,C,s))}))})}),{res:n,usedKey:r,exactUsedKey:i,usedLng:o,usedNS:l}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,s,n,r={}){var i;return(i=this.i18nFormat)!=null&&i.getResource?this.i18nFormat.getResource(e,s,n,r):this.resourceStore.getResource(e,s,n,r)}getUsedParamsDetails(e={}){const s=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=e.replace&&!he(e.replace);let r=n?e.replace:e;if(n&&typeof e.count<"u"&&(r.count=e.count),this.options.interpolation.defaultVariables&&(r={...this.options.interpolation.defaultVariables,...r}),!n){r={...r};for(const i of s)delete r[i]}return r}static hasDefaultValue(e){const s="defaultValue";for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&n.startsWith(s)&&e[n]!==void 0)return!0;return!1}}class na{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=jt.create("languageUtils")}getScriptPartFromCode(e){if(e=Fs(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=Fs(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(n=>{if(s)return;const r=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(r))&&(s=r)}),!s&&this.options.supportedLngs&&e.forEach(n=>{if(s)return;const r=this.getScriptPartFromCode(n);if(this.isSupportedCode(r))return s=r;const i=this.getLanguagePartFromCode(n);if(this.isSupportedCode(i))return s=i;s=this.options.supportedLngs.find(o=>o===i?!0:!o.includes("-")&&!i.includes("-")?!1:!!(o.includes("-")&&!i.includes("-")&&o.slice(0,o.indexOf("-"))===i||o.startsWith(i)&&i.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 n=e[s];return n||(n=e[this.getScriptPartFromCode(s)]),n||(n=e[this.formatLanguageCode(s)]),n||(n=e[this.getLanguagePartFromCode(s)]),n||(n=e.default),n||[]}toResolveHierarchy(e,s){const n=this.getFallbackCodes((s===!1?[]:s)||this.options.fallbackLng||[],e),r=[],i=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"&&i(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&i(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&i(this.getLanguagePartFromCode(e))):he(e)&&i(this.formatLanguageCode(e)),n.forEach(o=>{r.includes(o)||i(this.formatLanguageCode(o))}),r}}const aa={zero:0,one:1,two:2,few:3,many:4,other:5},ia={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class el{constructor(e,s={}){this.languageUtils=e,this.options=s,this.logger=jt.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,s={}){const n=Fs(e==="dev"?"en":e),r=s.ordinal?"ordinal":"cardinal",i=JSON.stringify({cleanedCode:n,type:r});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let o;try{o=new Intl.PluralRules(n,{type:r})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),ia;if(!e.match(/-|_/))return ia;const c=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(c,s)}return this.pluralRulesCache[i]=o,o}needsPlural(e,s={}){let n=this.getRule(e,s);return n||(n=this.getRule("dev",s)),(n==null?void 0:n.resolvedOptions().pluralCategories.length)>1}getPluralFormsOfKey(e,s,n={}){return this.getSuffixes(e,n).map(r=>`${s}${r}`)}getSuffixes(e,s={}){let n=this.getRule(e,s);return n||(n=this.getRule("dev",s)),n?n.resolvedOptions().pluralCategories.sort((r,i)=>aa[r]-aa[i]).map(r=>`${this.options.prepend}${s.ordinal?`ordinal${this.options.prepend}`:""}${r}`):[]}getSuffix(e,s,n={}){const r=this.getRule(e,n);return r?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${r.select(s)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",s,n))}}const oa=(t,e,s,n=".",r=!0)=>{let i=qo(t,e,s);return!i&&r&&he(s)&&(i=an(t,s,n),i===void 0&&(i=an(e,s,n))),i},Xr=t=>t.replace(/\$/g,"$$$$");class la{constructor(e={}){var s;this.logger=jt.create("interpolator"),this.options=e,this.format=((s=e==null?void 0:e.interpolation)==null?void 0:s.format)||(n=>n),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:s,escapeValue:n,useRawValueToEscape:r,prefix:i,prefixEscaped:o,suffix:l,suffixEscaped:c,formatSeparator:d,unescapeSuffix:u,unescapePrefix:f,nestingPrefix:p,nestingPrefixEscaped:m,nestingSuffix:g,nestingSuffixEscaped:x,nestingOptionsSeparator:y,maxReplaces:v,alwaysFormat:A}=e.interpolation;this.escape=s!==void 0?s:Ko,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=r!==void 0?r:!1,this.prefix=i?Nt(i):o||"{{",this.suffix=l?Nt(l):c||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":f?Nt(f):"-",this.unescapeSuffix=this.unescapePrefix?"":u?Nt(u):"",this.nestingPrefix=p?Nt(p):m||Nt("$t("),this.nestingSuffix=g?Nt(g):x||Nt(")"),this.nestingOptionsSeparator=y||",",this.maxReplaces=v||1e3,this.alwaysFormat=A!==void 0?A:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(s,n)=>(s==null?void 0:s.source)===n?(s.lastIndex=0,s):new RegExp(n,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,s,n,r){var m;let i,o,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=g=>{if(!g.includes(this.formatSeparator)){const A=oa(s,c,g,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(A,void 0,n,{...r,...s,interpolationkey:g}):A}const x=g.split(this.formatSeparator),y=x.shift().trim(),v=x.join(this.formatSeparator).trim();return this.format(oa(s,c,y,this.options.keySeparator,this.options.ignoreJSONStructure),v,n,{...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=((m=r==null?void 0:r.interpolation)==null?void 0:m.skipOnVariables)!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:g=>Xr(g)},{regex:this.regexp,safeValue:g=>this.escapeValue?Xr(this.escape(g)):Xr(g)}].forEach(g=>{for(l=0;i=g.regex.exec(e);){const x=i[1].trim();if(o=d(x),o===void 0)if(typeof u=="function"){const v=u(e,i,r);o=he(v)?v:""}else if(r&&Object.prototype.hasOwnProperty.call(r,x))o="";else if(f){o=i[0];continue}else this.logger.warn(`missed to pass in variable ${x} for interpolating ${e}`),o="";else!he(o)&&!this.useRawValueToEscape&&(o=Zn(o));const y=g.safeValue(o);if(e=e.replace(i[0],y),f?(g.regex.lastIndex+=o.length,g.regex.lastIndex-=i[0].length):g.regex.lastIndex=0,l++,l>=this.maxReplaces)break}}),e}nest(e,s,n={}){let r,i,o;const l=(c,d)=>{const u=this.nestingOptionsSeparator;if(!c.includes(u))return c;const f=c.split(new RegExp(`${Nt(u)}[ ]*{`));let p=`{${f[1]}`;c=f[0],p=this.interpolate(p,o);const m=p.match(/'/g),g=p.match(/"/g);(((m==null?void 0:m.length)??0)%2===0&&!g||((g==null?void 0:g.length)??0)%2!==0)&&(p=p.replace(/'/g,'"'));try{o=JSON.parse(p),d&&(o={...d,...o})}catch(x){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,x),`${c}${u}${p}`}return o.defaultValue&&o.defaultValue.includes(this.prefix)&&delete o.defaultValue,c};for(;r=this.nestingRegexp.exec(e);){let c=[];o={...n},o=o.replace&&!he(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const d=/{.*}/.test(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)),i=s(l.call(this,r[1].trim(),o),o),i&&r[0]===e&&!he(i))return i;he(i)||(i=Zn(i)),i||(this.logger.warn(`missed to resolve ${r[1]} for nesting ${e}`),i=""),c.length&&(i=c.reduce((u,f)=>this.format(u,f,n.lng,{...n,interpolationkey:r[1].trim()}),i.trim())),e=e.replace(r[0],i),this.regexp.lastIndex=0}return e}}const tl=t=>{let e=t.toLowerCase().trim();const s={};if(t.includes("(")){const n=t.split("(");e=n[0].toLowerCase().trim();const r=n[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}},ca=t=>{const e={};return(s,n,r)=>{let i=r;r&&r.interpolationkey&&r.formatParams&&r.formatParams[r.interpolationkey]&&r[r.interpolationkey]&&(i={...i,[r.interpolationkey]:void 0});const o=n+JSON.stringify(i);let l=e[o];return l||(l=t(Fs(n),r),e[o]=l),l(s)}},sl=t=>(e,s,n)=>t(Fs(s),n)(e);class rl{constructor(e={}){this.logger=jt.create("formatter"),this.options=e,this.init(e)}init(e,s={interpolation:{}}){this.formatSeparator=s.interpolation.formatSeparator||",";const n=s.cacheInBuiltFormats?ca:sl;this.formats={number:n((r,i)=>{const o=new Intl.NumberFormat(r,{...i});return l=>o.format(l)}),currency:n((r,i)=>{const o=new Intl.NumberFormat(r,{...i,style:"currency"});return l=>o.format(l)}),datetime:n((r,i)=>{const o=new Intl.DateTimeFormat(r,{...i});return l=>o.format(l)}),relativetime:n((r,i)=>{const o=new Intl.RelativeTimeFormat(r,{...i});return l=>o.format(l,i.range||"day")}),list:n((r,i)=>{const o=new Intl.ListFormat(r,{...i});return l=>o.format(l)})}}add(e,s){this.formats[e.toLowerCase().trim()]=s}addCached(e,s){this.formats[e.toLowerCase().trim()]=ca(s)}format(e,s,n,r={}){if(!s||e==null)return e;const i=s.split(this.formatSeparator),o=[];for(let c=0;c<i.length;c++){let d=i[c];for(;d.indexOf("(")>-1&&!d.includes(")")&&c+1<i.length;)d=`${d}${this.formatSeparator}${i[++c]}`;o.push(d)}return o.reduce((c,d)=>{var p;const{formatName:u,formatOptions:f}=tl(d);if(this.formats[u]){let m=c;try{const g=((p=r==null?void 0:r.formatParams)==null?void 0:p[r.interpolationkey])||{},x=g.locale||g.lng||r.locale||r.lng||n;m=this.formats[u](c,x,{...f,...r,...g})}catch(g){this.logger.warn(g)}return m}else this.logger.warn(`there was no format function for ${u}`);return c},e)}}const nl=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class al extends Er{constructor(e,s,n,r={}){var i,o;super(),this.backend=e,this.store=s,this.services=n,this.languageUtils=n.languageUtils,this.options=r,this.logger=jt.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=(i=this.backend)==null?void 0:i.init)==null||o.call(i,n,r.backend,r)}queueLoad(e,s,n,r){const i={},o={},l={},c={};return e.forEach(d=>{let u=!0;s.forEach(f=>{const p=`${d}|${f}`;!n.reload&&this.store.hasResourceBundle(d,f)?this.state[p]=2:this.state[p]<0||(this.state[p]===1?o[p]===void 0&&(o[p]=!0):(this.state[p]=1,u=!1,o[p]===void 0&&(o[p]=!0),i[p]===void 0&&(i[p]=!0),c[f]===void 0&&(c[f]=!0)))}),u||(l[d]=!0)}),(Object.keys(i).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:r}),{toLoad:Object.keys(i),pending:Object.keys(o),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(e,s,n){const r=e.split("|"),i=r[0],o=r[1];s&&this.emit("failedLoading",i,o,s),!s&&n&&this.store.addResourceBundle(i,o,n,void 0,void 0,{skipCopy:!0}),this.state[e]=s?-1:2,s&&n&&(this.state[e]=0);const l={};this.queue.forEach(c=>{Vo(c.loaded,[i],o),nl(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,n,r=0,i=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:s,fcName:n,tried:r,wait:i,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,n,r+1,i*2,o)},i);return}o(d,u)},c=this.backend[n].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,n={},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 i=this.queueLoad(e,s,n,r);if(!i.toLoad.length)return i.pending.length||r(),null;i.toLoad.forEach(o=>{this.loadOne(o)})}load(e,s,n){this.prepareLoading(e,s,{},n)}reload(e,s,n){this.prepareLoading(e,s,{reload:!0},n)}loadOne(e,s=""){const n=e.split("|"),r=n[0],i=n[1];this.read(r,i,"read",void 0,void 0,(o,l)=>{o&&this.logger.warn(`${s}loading namespace ${i} for language ${r} failed`,o),!o&&l&&this.logger.log(`${s}loaded namespace ${i} for language ${r}`,l),this.loaded(e,o,l)})}saveMissing(e,s,n,r,i,o={},l=()=>{}){var c,d,u,f,p;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 "${n}" 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(!(n==null||n==="")){if((p=this.backend)!=null&&p.create){const m={...o,isUpdate:i},g=this.backend.create.bind(this.backend);if(g.length<6)try{let x;g.length===5?x=g(e,s,n,r,m):x=g(e,s,n,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,n,r,l,m)}!e||!e[0]||this.store.addResource(e[0],s,n,r)}}}const Yr=()=>({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(n=>{e[n]=s[n]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),da=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),tr=()=>{},il=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(s=>{typeof t[s]=="function"&&(t[s]=t[s].bind(t))})};class Ts extends Er{constructor(e={},s){if(super(),this.options=da(e),this.services={},this.logger=jt,this.modules={external:[]},il(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 n=Yr();this.options={...n,...this.options,...da(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler);const r=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?jt.init(r(this.modules.logger),this.options):jt.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=rl;const u=new na(this.options);this.store=new ra(this.options.resources,this.options);const f=this.services;f.logger=jt,f.resourceStore=this.store,f.languageUtils=u,f.pluralResolver=new el(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 la(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new al(r(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(p,...m)=>{this.emit(p,...m)}),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("*",(p,...m)=>{this.emit(p,...m)}),this.modules.external.forEach(p=>{p.init&&p.init(this)})}if(this.format=this.options.interpolation.format,s||(s=tr),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=Ns(),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=tr){var i,o;let n=s;const r=he(e)?e:this.language;if(typeof e=="function"&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if((r==null?void 0:r.toLowerCase())==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();const l=[],c=d=>{if(!d||d==="cimode")return;this.services.languageUtils.toResolveHierarchy(d).forEach(f=>{f!=="cimode"&&(l.includes(f)||l.push(f))})};r?c(r):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>c(u)),(o=(i=this.options.preload)==null?void 0:i.forEach)==null||o.call(i,d=>c(d)),this.services.backendConnector.load(l,this.options.ns,d=>{!d&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(d)})}else n(null)}reloadResources(e,s,n){const r=Ns();return typeof e=="function"&&(n=e,e=void 0),typeof s=="function"&&(n=s,s=void 0),e||(e=this.languages),s||(s=this.options.ns),n||(n=tr),this.services.backendConnector.reload(e,s,i=>{r.resolve(),n(i)}),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"&&ii.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 n=this.languages[s];if(!["cimode","dev"].includes(n)&&this.store.hasLanguageSomeTranslations(n)){this.resolvedLanguage=n;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,s){this.isLanguageChangingTo=e;const n=Ns();this.emit("languageChanging",e);const r=l=>{this.language=l,this.languages=this.services.languageUtils.toResolveHierarchy(l),this.resolvedLanguage=void 0,this.setResolvedLanguage(l)},i=(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,n.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,p=>{i(p,d)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?o(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(e),n}getFixedT(e,s,n,r){const i=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||n||o.keyPrefix);const p={...this.options,...u};Array.isArray(i)&&!f&&(p.ns=i),typeof u.keyPrefix=="function"&&(u.keyPrefix=ls(u.keyPrefix,p));const m=this.options.keySeparator||".";let g;return u.keyPrefix&&Array.isArray(l)?g=l.map(x=>(typeof x=="function"&&(x=ls(x,p)),`${u.keyPrefix}${m}${x}`)):(typeof l=="function"&&(l=ls(l,p)),g=u.keyPrefix?`${u.keyPrefix}${m}${l}`:l),this.t(g,u)};return he(e)?o.lng=e:o.lngs=e,o.ns=s,o.keyPrefix=n,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 n=s.lng||this.resolvedLanguage||this.languages[0],r=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(n.toLowerCase()==="cimode")return!0;const o=(l,c)=>{const d=this.services.backendConnector.state[`${l}|${c}`];return d===-1||d===0||d===2};if(s.precheck){const l=s.precheck(this,o);if(l!==void 0)return l}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(n,e)&&(!r||o(i,e)))}loadNamespaces(e,s){const n=Ns();return this.options.ns?(he(e)&&(e=[e]),e.forEach(r=>{this.options.ns.includes(r)||this.options.ns.push(r)}),this.loadResources(r=>{n.resolve(),s&&s(r)}),n):(s&&s(),Promise.resolve())}loadLanguages(e,s){const n=Ns();he(e)&&(e=[e]);const r=this.options.preload||[],i=e.filter(o=>!r.includes(o)&&this.services.languageUtils.isSupportedCode(o));return i.length?(this.options.preload=r.concat(i),this.loadResources(o=>{n.resolve(),s&&s(o)}),n):(s&&s(),Promise.resolve())}dir(e){var r,i;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"],n=((i=this.services)==null?void 0:i.languageUtils)||new na(Yr());return e.toLowerCase().indexOf("-latn")>1?"ltr":s.includes(n.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},s){const n=new Ts(e,s);return n.createInstance=Ts.createInstance,n}cloneInstance(e={},s=tr){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const r={...this.options,...e,isClone:!0},i=new Ts(r);if((e.debug!==void 0||e.prefix!==void 0)&&(i.logger=i.logger.clone(e)),["store","services","language"].forEach(l=>{i[l]=this[l]}),i.services={...this.services},i.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},n){const l=Object.keys(this.store.data).reduce((c,d)=>(c[d]={...this.store.data[d]},c[d]=Object.keys(c[d]).reduce((u,f)=>(u[f]={...c[d][f]},u),c[d]),c),{});i.store=new ra(l,r),i.services.resourceStore=i.store}if(e.interpolation){const c={...Yr().interpolation,...this.options.interpolation,...e.interpolation},d={...r,interpolation:c};i.services.interpolator=new la(d)}return i.translator=new yr(i.services,r),i.translator.on("*",(l,...c)=>{i.emit(l,...c)}),i.init(r,s),i.translator.options=r,i.translator.backendConnector.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},i}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const Ve=Ts.createInstance();Ve.createInstance;Ve.dir;Ve.init;Ve.loadResources;Ve.reloadResources;Ve.use;Ve.changeLanguage;Ve.getFixedT;Ve.t;Ve.exists;Ve.setDefaultNamespace;Ve.hasLoadedNamespace;Ve.loadNamespaces;Ve.loadLanguages;const ol=(t,e,s,n)=>{var i,o,l,c;const r=[s,{code:e,...n||{}}];if((o=(i=t==null?void 0:t.services)==null?void 0:i.logger)!=null&&o.forward)return t.services.logger.forward(r,"warn","react-i18next::",!0);ts(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)},ua={},on=(t,e,s,n)=>{ts(s)&&ua[s]||(ts(s)&&(ua[s]=new Date),ol(t,e,s,n))},li=(t,e)=>()=>{if(t.isInitialized)e();else{const s=()=>{setTimeout(()=>{t.off("initialized",s)},0),e()};t.on("initialized",s)}},ln=(t,e,s)=>{t.loadNamespaces(e,li(t,s))},fa=(t,e,s,n)=>{if(ts(s)&&(s=[s]),t.options.preload&&t.options.preload.indexOf(e)>-1)return ln(t,s,n);s.forEach(r=>{t.options.ns.indexOf(r)<0&&t.options.ns.push(r)}),t.loadLanguages(e,li(t,n))},ll=(t,e,s={})=>!e.languages||!e.languages.length?(on(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(t,{lng:s.lng,precheck:(n,r)=>{if(s.bindI18n&&s.bindI18n.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!r(n.isLanguageChangingTo,t))return!1}}),ts=t=>typeof t=="string",cl=t=>typeof t=="object"&&t!==null,dl=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,ul={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},fl=t=>ul[t],hl=t=>t.replace(dl,fl);let cn={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:hl,transDefaultProps:void 0};const ml=(t={})=>{cn={...cn,...t}},pl=()=>cn;let ci;const gl=t=>{ci=t},xl=()=>ci,bl={type:"3rdParty",init(t){ml(t.options.react),gl(t)}},yl=h.createContext();class wl{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(s=>{this.usedNamespaces[s]||(this.usedNamespaces[s]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var Qr={exports:{}},Jr={};/**
3
+ * @license React
4
+ * use-sync-external-store-shim.production.js
5
+ *
6
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
7
+ *
8
+ * This source code is licensed under the MIT license found in the
9
+ * LICENSE file in the root directory of this source tree.
10
+ */var ha;function kl(){if(ha)return Jr;ha=1;var t=vo();function e(f,p){return f===p&&(f!==0||1/f===1/p)||f!==f&&p!==p}var s=typeof Object.is=="function"?Object.is:e,n=t.useState,r=t.useEffect,i=t.useLayoutEffect,o=t.useDebugValue;function l(f,p){var m=p(),g=n({inst:{value:m,getSnapshot:p}}),x=g[0].inst,y=g[1];return i(function(){x.value=m,x.getSnapshot=p,c(x)&&y({inst:x})},[f,m,p]),r(function(){return c(x)&&y({inst:x}),f(function(){c(x)&&y({inst:x})})},[f]),o(m),m}function c(f){var p=f.getSnapshot;f=f.value;try{var m=p();return!s(f,m)}catch{return!0}}function d(f,p){return p()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:l;return Jr.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:u,Jr}var ma;function vl(){return ma||(ma=1,Qr.exports=kl()),Qr.exports}var Sl=vl();const jl=(t,e)=>{if(ts(e))return e;if(cl(e)&&ts(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},Cl={t:jl,ready:!1},Nl=()=>()=>{},Ee=(t,e={})=>{var E,k,N;const{i18n:s}=e,{i18n:n,defaultNS:r}=h.useContext(yl)||{},i=s||n||xl();i&&!i.reportNamespaces&&(i.reportNamespaces=new wl),i||on(i,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=h.useMemo(()=>{var T;return{...pl(),...(T=i==null?void 0:i.options)==null?void 0:T.react,...e}},[i,e]),{useSuspense:l,keyPrefix:c}=o,d=r||((E=i==null?void 0:i.options)==null?void 0:E.defaultNS),u=ts(d)?[d]:d||["translation"],f=h.useMemo(()=>u,u);(N=(k=i==null?void 0:i.reportNamespaces)==null?void 0:k.addUsedNamespaces)==null||N.call(k,f);const p=h.useRef(0),m=h.useCallback(T=>{if(!i)return Nl;const{bindI18n:_,bindI18nStore:O}=o,j=()=>{p.current+=1,T()};return _&&i.on(_,j),O&&i.store.on(O,j),()=>{_&&_.split(" ").forEach(U=>i.off(U,j)),O&&O.split(" ").forEach(U=>i.store.off(U,j))}},[i,o]),g=h.useRef(),x=h.useCallback(()=>{if(!i)return Cl;const T=!!(i.isInitialized||i.initializedStoreOnce)&&f.every(R=>ll(R,i,o)),_=e.lng||i.language,O=p.current,j=g.current;if(j&&j.ready===T&&j.lng===_&&j.keyPrefix===c&&j.revision===O)return j;const z={t:i.getFixedT(_,o.nsMode==="fallback"?f:f[0],c,{scopeNs:f}),ready:T,lng:_,keyPrefix:c,revision:O};return g.current=z,z},[i,f,c,o,e.lng]),[y,v]=h.useState(0),{t:A,ready:I}=Sl.useSyncExternalStore(m,x,x);h.useEffect(()=>{if(i&&!I&&!l){const T=()=>v(_=>_+1);e.lng?fa(i,e.lng,f,T):ln(i,f,T)}},[i,e.lng,f,I,l,y]);const S=i||{},C=h.useRef(null),L=h.useRef(),F=T=>{const _=Object.getOwnPropertyDescriptors(T);_.__original&&delete _.__original;const O=Object.create(Object.getPrototypeOf(T),_);if(!Object.prototype.hasOwnProperty.call(O,"__original"))try{Object.defineProperty(O,"__original",{value:T,writable:!1,enumerable:!1,configurable:!1})}catch{}return O},b=h.useMemo(()=>{const T=S,_=T==null?void 0:T.language;let O=T;T&&(C.current&&C.current.__original===T?L.current!==_?(O=F(T),C.current=O,L.current=_):O=C.current:(O=F(T),C.current=O,L.current=_));const j=!I&&!l?(...z)=>(on(i,"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(...z)):A,U=[j,O,I];return U.t=j,U.i18n=O,U.ready=I,U},[A,S,I,S.resolvedLanguage,S.language,S.languages]);if(i&&l&&!I)throw new Promise(T=>{const _=()=>T();e.lng?fa(i,e.lng,f,_):ln(i,f,_)});return b},Al={de:{translation:Eo},en:{translation:Lo},es:{translation:Io},fr:{translation:Ao},ja:{translation:No},pt:{translation:Co},zh:{translation:jo}};Ve.use(bl).init({resources:Al,lng:"en",fallbackLng:"en",interpolation:{escapeValue:!1},returnNull:!1});var Il={agentMode:{mode:"multi",defaultAdapterId:"chat-with-files"},application:{name:"ORBIT Chat",description:"Explore ideas with ORBIT's AI copilots, share context, and build together.",inputPlaceholder:"Message ORBIT...",settingsAboutMsg:"ORBIT Chat",locale:"en-US",favicon:null},i18n:{activeLanguages:["en","fr","es","pt","de","ja","zh"],defaultLanguage:"en"},seo:{includeSitemap:!1,siteUrl:"http://localhost:5173",exposeAgentNotes:!0},debug:{consoleDebug:!1},features:{enableUpload:!0,enableAudioOutput:!0,enableAudioInput:!0,enableFeedbackButtons:!0,enableConversationThreads:!0,enableAutocomplete:!0},voice:{silenceTimeoutMs:4e3,recognitionLanguage:""},outOfServiceMessage:null,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:"auth0"},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://99.79.50.155: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://99.79.50.155: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://99.79.50.155: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://99.79.50.155: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://99.79.50.155:3000",description:"Generate videos from text descriptions.",inputPlaceholder:"Describe the video you want to create..."},{id:"qa-sql",name:"City FAQ Assistant (SQLite)",apiUrl:"http://99.79.50.155: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://99.79.50.155: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://99.79.50.155: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://99.79.50.155:3000",description:"Customer orders assistant: natural language queries over PostgreSQL customer orders data."},{id:"ecomm-analytics",name:"Business Analytics Assistant",apiUrl:"http://99.79.50.155: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:"intent-http-jsonplaceholder",name:"REST API Chat",apiUrl:"http://99.79.50.155:3000",description:"Natural language queries over the fake REST API."},{id:"intent-http-paris-opendata",name:"City of Paris Chat",apiUrl:"http://99.79.50.155: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://99.79.50.155:3000",description:"MFlix movies assistant: query the sample_mflix MongoDB database via intent templates."},{id:"intent-graphql-spacex",name:"GraphQL Chatbot",apiUrl:"http://99.79.50.155:3000",description:"SpaceX GraphQL assistant: natural language queries over the SpaceX API.",inputPlaceholder:"Ask SpaceX questions..."},{id:"audio-transcription",name:"Audio Transcription",apiUrl:"http://99.79.50.155:3000",description:"Audio Transcription Test.",inputPlaceholder:"Use the microphone for voice..."},{id:"voice-chat",name:"Voice Chat",apiUrl:"http://99.79.50.155:3000",description:"Voice chat adapter test.",inputPlaceholder:"Use the microphone for voice..."},{id:"real-time-voice-chat",name:"Real-Time Voice Chat",apiUrl:"http://99.79.50.155:3000",description:"Real-time voice chat adapter test (websocket).",inputPlaceholder:"Use the microphone for voice..."}]};const dn="http://localhost:3000",Ll="/favicon.svg",El="/orbit-logo-light.png",Tl="/orbit-logo-dark.png",_l={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 sr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function un(t,e){if(!sr(t)||!sr(e))return e;const s={...t};return Object.keys(e).forEach(n=>{if(n==="__proto__"||n==="constructor"||n==="prototype")return;const r=s[n],i=e[n];sr(r)&&sr(i)?s[n]=un(r,i):i!==void 0&&(s[n]=i)}),s}function Ml(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 Fl(t){return t==="single"?"single":"multi"}function $l(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 Pl(){const t=Il||{},e=typeof window<"u"&&window.ORBIT_CHAT_CONFIG||{},s=!!(typeof window<"u"&&window.ORBIT_CHAT_CONFIG);let n=un(_l,t);return n=un(n,e),!s||n.auth.domain,(!s||!n.auth.clientId)&&(n.auth.clientId="b753fbd6-35f8-439e-8786-098955e2a43c"),!s||n.auth.audience,!s||n.auth.provider,(!s||!n.auth.tenantId)&&(n.auth.tenantId="6ffcc616-8f76-4a3b-9b52-37a22175c738"),(!s||n.auth.scopes.length===0)&&(n.auth.scopes=$l("openid profile email User.Read")),n.outOfServiceMessage=Ml(n.outOfServiceMessage),n.agentMode.mode=Fl(n.agentMode.mode),n.agentMode.defaultAdapterId=typeof n.agentMode.defaultAdapterId=="string"?n.agentMode.defaultAdapterId.trim():"",n}const Y=Pl();function $e(){var e;const t=Y.adapters;if(Array.isArray(t)&&t.length>0){const s=(e=t[0].apiUrl)==null?void 0:e.trim();if(s)return s}return dn}function it(t){const e=t==null?void 0:t.trim();return e&&e.length>0?e:$e()}function Rl(){const t=Y.adapters;return Array.isArray(t)&&t.length>0?t[0].id:"default-key"}function Dl(){return Y.agentMode.mode}function Tr(){return Dl()==="single"}function vn(){if(!Tr())return null;const t=Y.agentMode.defaultAdapterId;return t&&Y.adapters.some(s=>{var n;return((n=s==null?void 0:s.id)==null?void 0:n.trim())===t})?t:null}function di(){const t=Array.isArray(Y.i18n.activeLanguages)?Y.i18n.activeLanguages.filter(e=>typeof e=="string"):[];return t.length>0?t:["en"]}function Ol(){var e;const t=(e=Y.i18n.defaultLanguage)==null?void 0:e.trim();return t&&di().includes(t)?t:"en"}function Sn(){return Y.application.name}function jn(){return Y.application.description}function ui(){return Y.application.inputPlaceholder}function Ul(t){var r;const e=t==null?void 0:t.trim();if(!e)return null;const s=Y.adapters.find(i=>{var o;return((o=i==null?void 0:i.id)==null?void 0:o.trim())===e});return((r=s==null?void 0:s.name)==null?void 0:r.trim())||null}function zl(t){var r;const e=t==null?void 0:t.trim();if(!e)return null;const s=Y.adapters.find(i=>{var o;return((o=i==null?void 0:i.id)==null?void 0:o.trim())===e});return((r=s==null?void 0:s.inputPlaceholder)==null?void 0:r.trim())||null}function fi(){return Y.seo.siteUrl.trim()}function Bl(){return Array.isArray(Y.seo.alternateSiteUrls)?Y.seo.alternateSiteUrls.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function Hl(){return Array.isArray(Y.seo.hostPatterns)?Y.seo.hostPatterns.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function Vl(){return Y.seo.exposeAgentNotes}function ql(){var e;return((e=Y.application.favicon)==null?void 0:e.trim())||Ll}function Wl(){return Y.features.enableUpload}function Kl(){return Y.features.enableAudioOutput}function Gl(){return Y.features.enableAudioInput}function pa(){return Y.features.enableFeedbackButtons}function Xl(){return Y.features.enableConversationThreads}function hi(){return Y.features.enableAutocomplete}function Yl(){return Math.max(1e3,Y.voice.silenceTimeoutMs)}function Ql(){return Y.voice.recognitionLanguage}function Jl(){const t=vn();if(t)return t;const e=Y.adapters;if(Array.isArray(e)&&e.length>0)for(const s of e){const n=typeof(s==null?void 0:s.id)=="string"?s.id.trim():"";if(n)return n}return null}function Zl(){return Y.outOfServiceMessage}function Cn(){return Y.auth.enabled}function tt(){const{enabled:t,provider:e,domain:s,clientId:n,tenantId:r}=Y.auth;return!t||!n?!1:e==="entra"?!!r:!!s}function ec(){return Y.auth.domain}function mi(){return Y.auth.clientId}function tc(){return Y.auth.audience}function _r(){return Y.auth.provider}function sc(){return Y.auth.tenantId}function Nn(){const t=Y.auth.scopes;return t.length>0?t:["openid","profile","email"]}function fn(){return Y.header.enabled}function rc(){return Y.header.logoUrl}function nc(){var e;return((e=Y.header.logoUrlLight)==null?void 0:e.trim())||El}function ac(){var e;return((e=Y.header.logoUrlDark)==null?void 0:e.trim())||Tl}function ic(){var t;return((t=Y.header.logoHeight)==null?void 0:t.trim())||""}function oc(){var t;return((t=Y.header.logoWidth)==null?void 0:t.trim())||""}function lc(){return Y.header.bgColor}function cc(){return Y.header.textColor}function dc(){return Y.header.showBorder}function pi(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 gi(){return pi(Y.header.navLinks)}function xi(){return Y.footer.enabled}function uc(){return Y.footer.text}function fc(){return Y.footer.bgColor}function hc(){return Y.footer.textColor}function mc(){return Y.footer.showBorder}function pc(){return Y.footer.layout==="inline"?"inline":"stacked"}function gc(){return Y.footer.topPadding==="normal"?"normal":"large"}function xc(){const t=Y.startupScripts;return Array.isArray(t)?t.filter(e=>!!(e&&typeof e=="object")).map(e=>{const s=typeof e.src=="string"?e.src.trim():"",n=typeof e.content=="string"?e.content.trim():"",r=typeof e.id=="string"?e.id.trim():"";return{...e,src:s||void 0,content:n||void 0,id:r||void 0}}).filter(e=>!!(e.src||e.content)):[]}function bc(){return pi(Y.footer.navLinks)}const bi=["de","en","es","fr","ja","pt","zh"],rr={de:"Deutsch",en:"English",es:"Español",fr:"Français",ja:"日本語",pt:"Português",zh:"中文"};function hr(t){return bi.includes(t)}const yi=h.createContext(void 0),wi="orbit-chat-language";function yc(){const t=di().filter(hr);return t.length>0?t:["en"]}function wc(t){const e=localStorage.getItem(wi);if(e&&hr(e)&&t.includes(e))return e;const s=[...navigator.languages||[],navigator.language].filter(Boolean);for(const r of s){const i=r.split("-")[0].toLowerCase();if(hr(i)&&t.includes(i))return i}const n=Ol();return hr(n)&&t.includes(n)?n:t[0]??"en"}function kc({children:t}){const[e]=h.useState(()=>yc()),[s,n]=h.useState(()=>wc(e));h.useEffect(()=>{Ve.changeLanguage(s)},[s]),h.useEffect(()=>{localStorage.setItem(wi,s)},[s]);const r=i=>{bi.includes(i)&&n(i)};return a.jsx(yi.Provider,{value:{currentLanguage:s,activeLanguages:e,setLanguage:r},children:t})}function vc(){const t=h.useContext(yi);if(!t)throw new Error("useLanguage must be used within LanguageProvider");return t}/**
11
+ * @license lucide-react v0.469.0 - ISC
12
+ *
13
+ * This source code is licensed under the ISC license.
14
+ * See the LICENSE file in the root directory of this source tree.
15
+ */const Sc=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ki=(...t)=>t.filter((e,s,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===s).join(" ").trim();/**
16
+ * @license lucide-react v0.469.0 - ISC
17
+ *
18
+ * This source code is licensed under the ISC license.
19
+ * See the LICENSE file in the root directory of this source tree.
20
+ */var jc={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
21
+ * @license lucide-react v0.469.0 - ISC
22
+ *
23
+ * This source code is licensed under the ISC license.
24
+ * See the LICENSE file in the root directory of this source tree.
25
+ */const Cc=h.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:s=2,absoluteStrokeWidth:n,className:r="",children:i,iconNode:o,...l},c)=>h.createElement("svg",{ref:c,...jc,width:e,height:e,stroke:t,strokeWidth:n?Number(s)*24/Number(e):s,className:ki("lucide",r),...l},[...o.map(([d,u])=>h.createElement(d,u)),...Array.isArray(i)?i:[i]]));/**
26
+ * @license lucide-react v0.469.0 - ISC
27
+ *
28
+ * This source code is licensed under the ISC license.
29
+ * See the LICENSE file in the root directory of this source tree.
30
+ */const ae=(t,e)=>{const s=h.forwardRef(({className:n,...r},i)=>h.createElement(Cc,{ref:i,iconNode:e,className:ki(`lucide-${Sc(t)}`,n),...r}));return s.displayName=`${t}`,s};/**
31
+ * @license lucide-react v0.469.0 - ISC
32
+ *
33
+ * This source code is licensed under the ISC license.
34
+ * See the LICENSE file in the root directory of this source tree.
35
+ */const hn=ae("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/**
36
+ * @license lucide-react v0.469.0 - ISC
37
+ *
38
+ * This source code is licensed under the ISC license.
39
+ * See the LICENSE file in the root directory of this source tree.
40
+ */const $s=ae("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
41
+ * @license lucide-react v0.469.0 - ISC
42
+ *
43
+ * This source code is licensed under the ISC license.
44
+ * See the LICENSE file in the root directory of this source tree.
45
+ */const us=ae("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/**
46
+ * @license lucide-react v0.469.0 - ISC
47
+ *
48
+ * This source code is licensed under the ISC license.
49
+ * See the LICENSE file in the root directory of this source tree.
50
+ */const ga=ae("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
51
+ * @license lucide-react v0.469.0 - ISC
52
+ *
53
+ * This source code is licensed under the ISC license.
54
+ * See the LICENSE file in the root directory of this source tree.
55
+ */const wr=ae("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/**
56
+ * @license lucide-react v0.469.0 - ISC
57
+ *
58
+ * This source code is licensed under the ISC license.
59
+ * See the LICENSE file in the root directory of this source tree.
60
+ */const mr=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"}]]);/**
61
+ * @license lucide-react v0.469.0 - ISC
62
+ *
63
+ * This source code is licensed under the ISC license.
64
+ * See the LICENSE file in the root directory of this source tree.
65
+ */const Nc=ae("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/**
66
+ * @license lucide-react v0.469.0 - ISC
67
+ *
68
+ * This source code is licensed under the ISC license.
69
+ * See the LICENSE file in the root directory of this source tree.
70
+ */const xa=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"}]]);/**
71
+ * @license lucide-react v0.469.0 - ISC
72
+ *
73
+ * This source code is licensed under the ISC license.
74
+ * See the LICENSE file in the root directory of this source tree.
75
+ */const Ac=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"}]]);/**
76
+ * @license lucide-react v0.469.0 - ISC
77
+ *
78
+ * This source code is licensed under the ISC license.
79
+ * See the LICENSE file in the root directory of this source tree.
80
+ */const An=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"}]]);/**
81
+ * @license lucide-react v0.469.0 - ISC
82
+ *
83
+ * This source code is licensed under the ISC license.
84
+ * See the LICENSE file in the root directory of this source tree.
85
+ */const Ic=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"}]]);/**
86
+ * @license lucide-react v0.469.0 - ISC
87
+ *
88
+ * This source code is licensed under the ISC license.
89
+ * See the LICENSE file in the root directory of this source tree.
90
+ */const Lc=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"}]]);/**
91
+ * @license lucide-react v0.469.0 - ISC
92
+ *
93
+ * This source code is licensed under the ISC license.
94
+ * See the LICENSE file in the root directory of this source tree.
95
+ */const Ec=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"}]]);/**
96
+ * @license lucide-react v0.469.0 - ISC
97
+ *
98
+ * This source code is licensed under the ISC license.
99
+ * See the LICENSE file in the root directory of this source tree.
100
+ */const Tc=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"}]]);/**
101
+ * @license lucide-react v0.469.0 - ISC
102
+ *
103
+ * This source code is licensed under the ISC license.
104
+ * See the LICENSE file in the root directory of this source tree.
105
+ */const _c=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"}]]);/**
106
+ * @license lucide-react v0.469.0 - ISC
107
+ *
108
+ * This source code is licensed under the ISC license.
109
+ * See the LICENSE file in the root directory of this source tree.
110
+ */const Mc=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"}]]);/**
111
+ * @license lucide-react v0.469.0 - ISC
112
+ *
113
+ * This source code is licensed under the ISC license.
114
+ * See the LICENSE file in the root directory of this source tree.
115
+ */const Fc=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"}]]);/**
116
+ * @license lucide-react v0.469.0 - ISC
117
+ *
118
+ * This source code is licensed under the ISC license.
119
+ * See the LICENSE file in the root directory of this source tree.
120
+ */const pr=ae("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
121
+ * @license lucide-react v0.469.0 - ISC
122
+ *
123
+ * This source code is licensed under the ISC license.
124
+ * See the LICENSE file in the root directory of this source tree.
125
+ */const vi=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"}]]);/**
126
+ * @license lucide-react v0.469.0 - ISC
127
+ *
128
+ * This source code is licensed under the ISC license.
129
+ * See the LICENSE file in the root directory of this source tree.
130
+ */const $c=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"}]]);/**
131
+ * @license lucide-react v0.469.0 - ISC
132
+ *
133
+ * This source code is licensed under the ISC license.
134
+ * See the LICENSE file in the root directory of this source tree.
135
+ */const Pc=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"}]]);/**
136
+ * @license lucide-react v0.469.0 - ISC
137
+ *
138
+ * This source code is licensed under the ISC license.
139
+ * See the LICENSE file in the root directory of this source tree.
140
+ */const Rc=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"}]]);/**
141
+ * @license lucide-react v0.469.0 - ISC
142
+ *
143
+ * This source code is licensed under the ISC license.
144
+ * See the LICENSE file in the root directory of this source tree.
145
+ */const ba=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"}]]);/**
146
+ * @license lucide-react v0.469.0 - ISC
147
+ *
148
+ * This source code is licensed under the ISC license.
149
+ * See the LICENSE file in the root directory of this source tree.
150
+ */const Dc=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"}]]);/**
151
+ * @license lucide-react v0.469.0 - ISC
152
+ *
153
+ * This source code is licensed under the ISC license.
154
+ * See the LICENSE file in the root directory of this source tree.
155
+ */const Oc=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"}]]);/**
156
+ * @license lucide-react v0.469.0 - ISC
157
+ *
158
+ * This source code is licensed under the ISC license.
159
+ * See the LICENSE file in the root directory of this source tree.
160
+ */const Uc=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"}]]);/**
161
+ * @license lucide-react v0.469.0 - ISC
162
+ *
163
+ * This source code is licensed under the ISC license.
164
+ * See the LICENSE file in the root directory of this source tree.
165
+ */const zc=ae("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
166
+ * @license lucide-react v0.469.0 - ISC
167
+ *
168
+ * This source code is licensed under the ISC license.
169
+ * See the LICENSE file in the root directory of this source tree.
170
+ */const Bc=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"}]]);/**
171
+ * @license lucide-react v0.469.0 - ISC
172
+ *
173
+ * This source code is licensed under the ISC license.
174
+ * See the LICENSE file in the root directory of this source tree.
175
+ */const Hc=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"}]]);/**
176
+ * @license lucide-react v0.469.0 - ISC
177
+ *
178
+ * This source code is licensed under the ISC license.
179
+ * See the LICENSE file in the root directory of this source tree.
180
+ */const Vc=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"}]]);/**
181
+ * @license lucide-react v0.469.0 - ISC
182
+ *
183
+ * This source code is licensed under the ISC license.
184
+ * See the LICENSE file in the root directory of this source tree.
185
+ */const qc=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"}]]);/**
186
+ * @license lucide-react v0.469.0 - ISC
187
+ *
188
+ * This source code is licensed under the ISC license.
189
+ * See the LICENSE file in the root directory of this source tree.
190
+ */const Wc=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"}]]);/**
191
+ * @license lucide-react v0.469.0 - ISC
192
+ *
193
+ * This source code is licensed under the ISC license.
194
+ * See the LICENSE file in the root directory of this source tree.
195
+ */const Si=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"}]]);/**
196
+ * @license lucide-react v0.469.0 - ISC
197
+ *
198
+ * This source code is licensed under the ISC license.
199
+ * See the LICENSE file in the root directory of this source tree.
200
+ */const Kc=ae("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
201
+ * @license lucide-react v0.469.0 - ISC
202
+ *
203
+ * This source code is licensed under the ISC license.
204
+ * See the LICENSE file in the root directory of this source tree.
205
+ */const Gc=ae("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/**
206
+ * @license lucide-react v0.469.0 - ISC
207
+ *
208
+ * This source code is licensed under the ISC license.
209
+ * See the LICENSE file in the root directory of this source tree.
210
+ */const Xc=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"}]]);/**
211
+ * @license lucide-react v0.469.0 - ISC
212
+ *
213
+ * This source code is licensed under the ISC license.
214
+ * See the LICENSE file in the root directory of this source tree.
215
+ */const Yc=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"}]]);/**
216
+ * @license lucide-react v0.469.0 - ISC
217
+ *
218
+ * This source code is licensed under the ISC license.
219
+ * See the LICENSE file in the root directory of this source tree.
220
+ */const Qc=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"}]]);/**
221
+ * @license lucide-react v0.469.0 - ISC
222
+ *
223
+ * This source code is licensed under the ISC license.
224
+ * See the LICENSE file in the root directory of this source tree.
225
+ */const In=ae("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
226
+ * @license lucide-react v0.469.0 - ISC
227
+ *
228
+ * This source code is licensed under the ISC license.
229
+ * See the LICENSE file in the root directory of this source tree.
230
+ */const ya=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"}]]);/**
231
+ * @license lucide-react v0.469.0 - ISC
232
+ *
233
+ * This source code is licensed under the ISC license.
234
+ * See the LICENSE file in the root directory of this source tree.
235
+ */const Ln=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"}]]);/**
236
+ * @license lucide-react v0.469.0 - ISC
237
+ *
238
+ * This source code is licensed under the ISC license.
239
+ * See the LICENSE file in the root directory of this source tree.
240
+ */const Jc=ae("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
241
+ * @license lucide-react v0.469.0 - ISC
242
+ *
243
+ * This source code is licensed under the ISC license.
244
+ * See the LICENSE file in the root directory of this source tree.
245
+ */const Zc=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"}]]);/**
246
+ * @license lucide-react v0.469.0 - ISC
247
+ *
248
+ * This source code is licensed under the ISC license.
249
+ * See the LICENSE file in the root directory of this source tree.
250
+ */const ji=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"}]]);/**
251
+ * @license lucide-react v0.469.0 - ISC
252
+ *
253
+ * This source code is licensed under the ISC license.
254
+ * See the LICENSE file in the root directory of this source tree.
255
+ */const Ci=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"}]]);/**
256
+ * @license lucide-react v0.469.0 - ISC
257
+ *
258
+ * This source code is licensed under the ISC license.
259
+ * See the LICENSE file in the root directory of this source tree.
260
+ */const Ni=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"}]]);/**
261
+ * @license lucide-react v0.469.0 - ISC
262
+ *
263
+ * This source code is licensed under the ISC license.
264
+ * See the LICENSE file in the root directory of this source tree.
265
+ */const ed=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"}]]);/**
266
+ * @license lucide-react v0.469.0 - ISC
267
+ *
268
+ * This source code is licensed under the ISC license.
269
+ * See the LICENSE file in the root directory of this source tree.
270
+ */const En=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"}]]);/**
271
+ * @license lucide-react v0.469.0 - ISC
272
+ *
273
+ * This source code is licensed under the ISC license.
274
+ * See the LICENSE file in the root directory of this source tree.
275
+ */const td=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"}]]);/**
276
+ * @license lucide-react v0.469.0 - ISC
277
+ *
278
+ * This source code is licensed under the ISC license.
279
+ * See the LICENSE file in the root directory of this source tree.
280
+ */const kr=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"}]]);/**
281
+ * @license lucide-react v0.469.0 - ISC
282
+ *
283
+ * This source code is licensed under the ISC license.
284
+ * See the LICENSE file in the root directory of this source tree.
285
+ */const sd=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"}]]);/**
286
+ * @license lucide-react v0.469.0 - ISC
287
+ *
288
+ * This source code is licensed under the ISC license.
289
+ * See the LICENSE file in the root directory of this source tree.
290
+ */const Ye=ae("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/**
291
+ * @license lucide-react v0.469.0 - ISC
292
+ *
293
+ * This source code is licensed under the ISC license.
294
+ * See the LICENSE file in the root directory of this source tree.
295
+ */const rd=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"}]]);/**
296
+ * @license lucide-react v0.469.0 - ISC
297
+ *
298
+ * This source code is licensed under the ISC license.
299
+ * See the LICENSE file in the root directory of this source tree.
300
+ */const nd=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 ad(t){const e=t.trim().split(`
301
+ `);if(e.length<2)return!1;const s=e[0].trim();if(!s.startsWith("|")||(s.match(/\|/g)||[]).length<2)return!1;const n=e[1].trim();if(!n.startsWith("|")||!/^[\s|:|-]+$/.test(n)||!n.includes("-"))return!1;for(let r=2;r<e.length;r++){const i=e[r].trim();if(i!==""&&!i.startsWith("|"))return!1}return!0}function id(t){return t.replace(/(^|\n)(```|~~~)\s*\n([\s\S]*?)\n\2(\n|$)/g,(e,s,n,r,i)=>ad(r)?`${s}
302
+ ${r.trim()}
303
+ ${i}`:e)}function od(t){const e={};let s=0;return t=t.replace(/\$\$([\s\S]*?)\$\$/g,(n,r)=>{const i=`__DISPLAY_MATH_${s++}__`;return e[i]=`$$${r}$$`,i}),t=t.replace(/\\\[([\s\S]*?)\\\]/g,(n,r)=>{const i=`__DISPLAY_MATH_${s++}__`;return e[i]=`$$${r}$$`,i}),t=t.replace(/\\\(([\s\S]*?)\\\)/g,(n,r)=>{const i=`__INLINE_MATH_${s++}__`;return e[i]=`$${r}$`,i}),t=t.replace(/(^|\n)(```|~~~)([^\n]*)\n([\s\S]*?)\n\2(\n|$)/g,(n,r,i,o,l,c)=>{const d=`__FENCED_CODE_${s++}__`;return e[d]=`${r}${i}${o}
304
+ ${l}
305
+ ${i}${c}`,d}),t=t.replace(/`([^`]+)`/g,n=>{const r=`__INLINE_CODE_${s++}__`;return e[r]=n,r}),{masked:t,masks:e}}function ld(t){const e={};let s=0;return t=t.replace(new RegExp("(?<!\\$)\\$(?!\\$)([^$\\n]+?)(?<!\\$)\\$(?!\\$)","g"),(n,r)=>{const i=r.trim();if(/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?(?:\s?[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion)?$/.test(i))return n;const l=`__INLINE_MATH_${s++}__`;return e[l]=`$${r}$`,l}),{masked:t,masks:e}}const wa=/\\(?:iiint|iint|oint|int|sum|prod|lim|frac|sqrt|sin|cos|tan|sec|csc|cot|arcsin|arccos|arctan|ln|log|exp|Delta|nabla|partial)\b/;function cd(t){const e=/(__INLINE_MATH_\d+__|__DISPLAY_MATH_\d+__|__CURRENCY_\d+__)/g,s=/^(__INLINE_MATH_\d+__|__DISPLAY_MATH_\d+__|__CURRENCY_\d+__)$/;return t.split(`
306
+ `).map(n=>wa.test(n)?n.split(e).map(r=>!r||s.test(r)||!wa.test(r)||r.includes("$")?r:r.replace(/\\(?:iiint|iint|oint|int|sum|prod|lim|frac|sqrt|sin|cos|tan|sec|csc|cot|arcsin|arccos|arctan|ln|log|exp|Delta|nabla|partial)\b[^\n]*/g,i=>{const o=i.trimEnd();return o?`$${o}$${i.slice(o.length)}`:i})).join(""):n).join(`
307
+ `)}function dd(t){return t.replace(/\$([^$\n]*?)\s*=\s*\$([^$\n]+)\$\s*([^$\n]*?)\$/g,(e,s,n,r)=>{const i=String(s).trimEnd(),o=String(n).trim(),l=String(r).trim(),c=[o,l].filter(Boolean).join(" ");return`$${i} = ${c}$`})}function ud(t){const e=t.split(`
308
+ `);for(let n=0;n<e.length-1;n++){const r=e[n],i=e[n+1]??"";if(!r||!i)continue;const o=i.trim();if(!(o.startsWith("|")&&o.includes("-")))continue;const c=r.indexOf("|");if(c<=0)continue;const d=r.slice(0,c);if(!d||d.trim()==="")continue;const u=d.trim(),f=u.replace(/\s+/g,""),p=f!==""&&/^[>]+$/.test(f),m=/^[-*+]\s*$/.test(u),g=/^\d+\.\s*$/.test(u);if(p||m||g)continue;const x=r.slice(c);if((x.match(/\|/g)||[]).length<2)continue;const v=d.replace(/\s+$/,""),A=x.replace(/^\s+/,"");v&&(e.splice(n,1,v,A),n++)}const s=[];for(let n=0;n<e.length;n++){const r=e[n],i=r.trim(),l=(e[n+1]??"").trim();i.startsWith("|")&&(i.match(/\|/g)||[]).length>=2&&l.startsWith("|")&&/^[\s|:-]+$/.test(l)&&l.includes("-")&&s.length>0&&s[s.length-1].trim()!==""&&s.push(""),s.push(r)}return s.join(`
309
+ `)}const ka=["aligned","align","align*","array","cases","pmatrix","bmatrix","vmatrix","Vmatrix","matrix","smallmatrix","gather","gather*","multline","multline*","split","flalign","flalign*","eqnarray","equation","equation*"];function fd(t,e){let s=0,n=`__${e}_${s}__`;for(;Object.prototype.hasOwnProperty.call(t,n);)s++,n=`__${e}_${s}__`;return n}function hd(t,e){if(!ka.length)return t;const s=ka.join("|"),n=new RegExp(String.raw`\\begin\{(${s})\}([\s\S]*?)\\end\{\1\}`,"g");return t.replace(n,(r,i,o,l,c)=>{const d=c.slice(0,l),u=c.slice(l+r.length),f=/(\$\$|\\\[)\s*$/.test(d),p=/^\s*(\$\$|\\\])/.test(u);if(f&&p)return r;const m=d.lastIndexOf("\\["),g=d.lastIndexOf("\\]");if(m>g&&m!==-1&&/\\]/.test(u))return r;const y=/\$\$/g;let v=0;for(;y.exec(d)!==null;)v++;if(v%2===1&&/\$\$/.test(u))return r;if((d.replace(/\$\$/g,"__DD__").replace(/\\\$/g,"__ES__").match(/\$/g)||[]).length%2===1){const k=u.replace(/\$\$/g,"__DD__").replace(/\\\$/g,"__ES__");if(/^[^$]*\$(?!\$)/.test(k))return r}const F=fd(e,"LATEX_ENV"),b=r.trim();return e[F]=`
310
+ $$
311
+ ${b}
312
+ $$
313
+ `,F})}function md(t,e){for(const[s,n]of Object.entries(e)){const r=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");t=t.replace(r,()=>n)}return t}const pd=t=>{if(!t||typeof t!="string")return"";try{let e=t.replace(/\r\n/g,`
314
+ `).replace(/\r/g,`
315
+ `);e=id(e);const{masked:s,masks:n}=od(e);e=s,e=e.replace(/<br\s*\/?>/gi,`
316
+ `),e=e.replace(/\\(ne|neq)\$(?=\s*[-+0-9A-Za-z(])/g,"\\$1"),e=dd(e),e=ud(e),e=hd(e,n);const r=new Map;let i=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,(p,m,g,x)=>{const y=`__CURRENCY_${i++}__`,v=`__CURRENCY_${i++}__`;return r.set(y,m),r.set(v,x),`${y}${g}${v}`});const c=new RegExp(String.raw`-?\$\(?\d{1,3}(?:,\d{3})*(?:\.\d+)?\)?(?:\s?(?:[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion))?(?!\w)|\$-?\d+(?:\.\d+)?(?:\s?(?:[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion))?(?!\w)`,"g");e=e.replace(c,(p,m,g)=>{if(g.substring(m+p.length).match(/^[a-zA-Z]/)&&!p.match(/[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion$/))return p;const y=`__CURRENCY_${i++}__`;return r.set(y,p),y});const{masked:d,masks:u}=ld(e);return e=d,Object.assign(n,u),e=cd(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(p=>{e=e.replace(p,(m,g)=>{if(m.includes("$")||m.includes("__INLINE_MATH_")||m.includes("__DISPLAY_MATH_")||m.includes("__CURRENCY_"))return m;const x=String(g??"").trim();if(/^[A-Za-z]$/.test(x))return m;const y=/[\\^_+=<>]|\\b(?:frac|sqrt|sum|int|lim|log|ln|sin|cos|tan|exp)\b/.test(x),v=/\d/.test(x),A=/[()]/.test(x),I=(x.match(/[A-Z]/g)||[]).length,S=(x.match(/[a-z]/g)||[]).length,C=I>=2,L=v||A||C&&S>0;return!y&&!L?m:m.replace(g,`$${g}$`)})}),e=e.replace(new RegExp("(?<!\\\\)\\$(?!\\$)([^$\\n]*?)(?<!\\\\)\\$(?!\\$)","g"),(p,m)=>{if(p.includes("__CURRENCY_")||p.includes("__INLINE_MATH_")||p.includes("__DISPLAY_MATH_")||m.trim()==="")return p;const g=/^\d+(?:,\d{3})*(?:\.\d{2})?$/.test(m.trim()),x=/\\/.test(m),y=/[+\-*/=<>^_{}()]/.test(m),v=/[a-zA-Z].*\d|\d.*[a-zA-Z]/.test(m),A=/\\(?:alpha|beta|gamma|delta|epsilon|theta|lambda|mu|pi|sigma|omega)/.test(m),I=/\\(?:frac|sqrt|sum|int|lim|log|ln|sin|cos|tan|exp)/.test(m),S=/^[A-Za-z]$/.test(m.trim());return!g&&(x||y||v||A||I||S||m.length>1)?p:`\\$${m}\\$`}),e=e.split(`
317
+ `).map(p=>{const m=p.indexOf("$$");return m===-1||p.trim()==="$$"||p.indexOf("$$",m+2)!==-1?p:p.replace("$$","\\$\\$")}).join(`
318
+ `),r.forEach((p,m)=>{const g=p.replace(/\$/g,"&#36;");e=e.replace(new RegExp(m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),g)}),e=e.replace(/\\&#36;/g,"&#36;"),e=md(e,n),e=e.trimEnd()+`
319
+ `,e}catch(e){return console.warn("Error preprocessing markdown:",e),t}},gd=h.lazy(()=>St(()=>import("./MermaidRenderer-CPPq3mmd.js").then(t=>t.au),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.MermaidRenderer}))),xd=h.lazy(()=>St(()=>import("./SVGRenderer-C23bZ16J.js"),__vite__mapDeps([6,1,3,5,7,8,9,2,10])).then(t=>({default:t.SVGRenderer}))),bd=h.lazy(()=>St(()=>import("./ChartRenderer-OBjJRngd.js"),__vite__mapDeps([11,1,5,4,12,13,14,15,16,17,7,8,9,2,10])).then(t=>({default:t.ChartRenderer}))),yd=h.lazy(()=>St(()=>import("./MusicRenderer-ZqWcBGEP.js"),__vite__mapDeps([18,2,1,5,7,8,9,10])).then(t=>({default:t.MusicRenderer}))),wd=t=>{var n,r;if(!t)return typeof window<"u"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light";const e=t.closest(".markdown-content");if(e){if(e.classList.contains("dark"))return"dark";if(e.classList.contains("light"))return"light"}if(t.closest(".dark"))return"dark";if(t.closest(".light"))return"light";const s=t.closest("[data-theme]");if(s){const i=s.getAttribute("data-theme");if(i==="dark")return"dark";if(i==="light")return"light"}return typeof window<"u"&&((r=window.matchMedia)!=null&&r.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},kd=(t,e)=>{const[s,n]=h.useState("light"),r=h.useRef("light");return h.useEffect(()=>{var d,u,f;if(e||typeof window>"u"||typeof document>"u")return;const i=()=>{const p=wd(t.current);p!==r.current&&(r.current=p,n(p))};i();const o=((d=window.matchMedia)==null?void 0:d.call(window,"(prefers-color-scheme: dark)"))??null,l=()=>i();o==null||o.addEventListener("change",l);const c=typeof MutationObserver<"u"?new MutationObserver(()=>i()):null;if(c){const p=((f=(u=t.current)==null?void 0:u.closest)==null?void 0:f.call(u,".markdown-content"))??null;p&&c.observe(p,{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},vd={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"},Sd=t=>{if(!t)return"";const e=t.match(/(?:^|\s)language-([^\s]+)/);if(!e)return"";const n=e[1].toLowerCase().split("{")[0].split("[")[0].split("<")[0].split(":")[0].trim().replace(/[^a-z0-9+#-]+$/g,"");return n?vd[n]??n:""},jd=t=>vt.Children.toArray(t).map(e=>typeof e=="string"||typeof e=="number"?String(e):"").join("").replace(/\n$/,""),va=({code:t})=>{const{t:e}=Ee(),[s,n]=h.useState(!1),r=async()=>{try{await navigator.clipboard.writeText(t),n(!0),setTimeout(()=>n(!1),2e3)}catch{const i=document.createElement("textarea");i.value=t,i.style.position="fixed",i.style.opacity="0",document.body.appendChild(i),i.select();try{document.execCommand("copy"),n(!0),setTimeout(()=>n(!1),2e3)}catch(o){console.error("Failed to copy code:",o)}document.body.removeChild(i)}};return a.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?a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:a.jsx("path",{d:"M13.5 4.5L6 12L2.5 8.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.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"}),a.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"}),a.jsx("path",{d:"M9.5 6.5L13.5 2.5L9.5 2.5V6.5Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),a.jsx("span",{className:"code-copy-button-text",children:e(s?"markdown.codeBlock.copied":"markdown.codeBlock.copyLabel")})]})},Cd=({inline:t,className:e="",children:s,enableGraphs:n=!0,enableMermaid:r=!0,enableSVG:i=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d})=>{const{t:u}=Ee(),f=h.useRef(null),p=kd(f,d),m=a.jsx("div",{className:"markdown-code-block code-block-container",children:u("markdown.codeBlock.loadingRenderer")});if(t)return a.jsx("code",{className:e,children:s});const g=Sd(e),x=jd(s);if(o&&(g==="chart"||g==="chart-json"||g==="chart-table"))return a.jsx("div",{ref:f,children:a.jsx(h.Suspense,{fallback:m,children:a.jsx(bd,{code:x,language:g})})});if(l&&(g==="abc"||g==="music"))return a.jsx("div",{ref:f,children:a.jsx(h.Suspense,{fallback:m,children:a.jsx(yd,{code:x})})});if(n){if(g==="mermaid"&&r)return a.jsx("div",{ref:f,children:a.jsx(h.Suspense,{fallback:m,children:a.jsx(gd,{code:x})})});if(g==="svg"&&i)return a.jsx("div",{ref:f,children:a.jsx(h.Suspense,{fallback:m,children:a.jsx(xd,{code:x})})})}if(c&&g){const y=p==="light"?$o:Po;return a.jsxs("div",{ref:f,className:"syntax-highlighted-wrapper code-block-container",children:[a.jsx(va,{code:x}),a.jsx(Fo,{language:g,style:y,customStyle:{margin:"12px 0",borderRadius:"6px",fontSize:"0.9em"},showLineNumbers:!1,children:x})]})}return a.jsxs("div",{ref:f,className:`markdown-code-block code-block-container ${e}`.trim(),children:[a.jsx(va,{code:x}),a.jsx("pre",{style:{margin:0,padding:0,background:"transparent",border:"none"},children:a.jsx("code",{children:x})})]})},Sa=new Set(["div","pre","blockquote","ul","ol","table","thead","tbody","tr","td","th","h1","h2","h3","h4","h5","h6","section","article","figure"]),Nd=({children:t,href:e="",className:s="",...n})=>{const r=vt.Children.toArray(t).map(u=>typeof u=="string"?u:"").join("").trim(),i=/^https?:\/\//i.test(e),o=!!(i&&r&&ja(r)===ja(e)),l=i?Ad(e):null,c=!!(o&&l),d=["markdown-link",c?"markdown-link--card":"markdown-link--inline",s].filter(Boolean).join(" ");return a.jsxs("a",{...n,href:e,target:"_blank",rel:"noopener noreferrer",className:d,children:[a.jsx("span",{className:"markdown-link__content",children:c&&l?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"markdown-link__hostname",children:l.hostname}),l.path&&l.path!=="/"&&a.jsx("span",{className:"markdown-link__path",children:l.path})]}):t}),i&&a.jsx("span",{className:"markdown-link__icon","aria-hidden":"true",children:a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:a.jsx("path",{d:"M8 16L16 8M16 8H9M16 8V15",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})})})]})};function ja(t){return t.trim().replace(/\/$/,"")}function Ad(t){try{const e=new URL(t),s=e.hostname.replace(/^www\./i,""),n=`${e.pathname}${e.search}${e.hash}`||"/";return{hostname:s,path:n}}catch{return null}}const It=({content:t,className:e="",disableMath:s=!1,enableGraphs:n=!0,enableMermaid:r=!0,enableSVG:i=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d="dark"})=>{const u=pd(t);if(!u)return null;const f=s?[Qn]:[Qn,[_o,{singleDollarTextMath:!0}]],p=[];s||p.push([Mo,{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 m={table:({children:g,...x})=>a.jsx("div",{style:{overflowX:"auto",WebkitOverflowScrolling:"touch"},children:a.jsx("table",{...x,children:g})}),a:Nd,code:g=>{const{className:x,children:y,...v}=g,A=x&&/language-/.test(x),I="inline"in g&&typeof g.inline=="boolean"&&g.inline||!A,S=A;return a.jsx(Cd,{inline:I,className:x,enableGraphs:n,enableMermaid:r,enableSVG:i,enableCharts:o,enableMusic:l,enableSyntaxHighlighting:c,syntaxTheme:d,"data-block-code":S?"true":void 0,...v,children:y})},p:({node:g,...x})=>{var I;const v=vt.Children.toArray(x.children).filter(S=>!(typeof S=="string"&&S.trim()==="")).some(S=>{if(!vt.isValidElement(S))return!1;const C=S.props;return(C==null?void 0:C["data-block-code"])==="true"?!0:typeof S.type=="string"?Sa.has(S.type):!1}),A=(I=g==null?void 0:g.children)==null?void 0:I.some(S=>{var C;if(S.type==="code")return!0;if(S.type==="element"){if(S.tagName&&Sa.has(S.tagName))return!0;if(S.tagName==="code"){const L=(C=S.properties)==null?void 0:C.className;return Array.isArray(L)?L.some(F=>typeof F=="string"&&F.startsWith("language-")):!0}}return!1});return v||A?a.jsx(a.Fragment,{children:x.children}):a.jsx("p",{...x})}};return a.jsx("div",{className:`markdown-content ${e}`,children:a.jsx(To,{remarkPlugins:f,rehypePlugins:p,components:m,children:u})})},Tn=()=>Y.debug.consoleDebug,$=(...t)=>{Tn()&&console.log(...t)},ge=(...t)=>{Tn()&&console.warn(...t)},ye=(...t)=>{Tn()&&console.error(...t)},Oe=(...t)=>{console.error(...t)};function Ca({audio:t,audioFormat:e="mp3",autoPlay:s=!1,maxSizeMB:n=10}){const{t:r}=Ee(),i=h.useRef(null),[o,l]=h.useState(!1),[c,d]=h.useState(0),[u,f]=h.useState(0),[p,m]=h.useState(!0),[g,x]=h.useState(null),[y,v]=h.useState(null);h.useEffect(()=>{if(!t)return;let k=null,N=!0;return(async()=>{try{m(!0),x(null),v(null);const O=t.length*3/4/(1024*1024);if(O>n)throw new Error(r("audio.player.audioFileTooLargePlaceholder",{sizeMB:O.toFixed(1),maxMB:n}));if(O>2&&(v(r("audio.player.largeAudioWarning",{sizeMB:O.toFixed(1)})),$("[AudioPlayer] Large audio file detected",{sizeMB:O.toFixed(2)})),!/^[A-Za-z0-9+/=]+$/.test(t.replace(/\s/g,"")))throw new Error(r("audio.player.invalidBase64Error"));const j=atob(t),U=new Uint8Array(j.length);for(let X=0;X<j.length;X++)U[X]=j.charCodeAt(X);const z=e==="mp3"?"audio/mpeg":e==="wav"?"audio/wav":e==="ogg"?"audio/ogg":e==="opus"?"audio/opus":e==="webm"?"audio/webm":`audio/${e}`,R=new Blob([U],{type:z});if(k=URL.createObjectURL(R),!N||!i.current){k&&URL.revokeObjectURL(k);return}i.current.src=k,m(!1),$("[AudioPlayer] Audio loaded successfully",{format:e,mimeType:z,size:R.size}),s&&i.current&&i.current.play().catch(X=>{ye("[AudioPlayer] Auto-play failed:",X)})}catch(_){ye("[AudioPlayer] Failed to load audio:",_),N&&(x(r("audio.player.loadFailureError")),m(!1))}})(),()=>{N=!1,k&&URL.revokeObjectURL(k)}},[t,e,s,n,r]);const A=()=>{i.current&&d(i.current.duration)},I=()=>{i.current&&f(i.current.currentTime)},S=()=>l(!0),C=()=>l(!1),L=()=>{l(!1),f(0)},F=()=>{i.current&&(o?i.current.pause():i.current.play().catch(k=>{ye("[AudioPlayer] Playback failed:",k),x(r("audio.player.playbackFailureError"))}))},b=k=>{if(!i.current)return;const N=parseFloat(k.target.value);i.current.currentTime=N,f(N)},E=k=>{if(!isFinite(k))return"0:00";const N=Math.floor(k/60),T=Math.floor(k%60);return`${N}:${T.toString().padStart(2,"0")}`};return g?a.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:[a.jsx(kr,{className:"h-4 w-4"}),a.jsx("span",{children:g})]}):a.jsxs("div",{className:"mt-3 flex flex-col gap-1",children:[y&&a.jsxs("div",{className:"text-xs text-amber-600 dark:text-amber-400 px-1",children:["⚠️ ",y]}),a.jsxs("div",{className:"flex items-center gap-3 rounded-md border border-gray-300 bg-white px-3 py-2 dark:border-[#4a4b54] dark:bg-[#343541]",children:[a.jsx("audio",{ref:i,onLoadedMetadata:A,onTimeUpdate:I,onPlay:S,onPause:C,onEnded:L}),a.jsx("button",{onClick:F,disabled:p,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:r(o?"audio.player.pauseTitle":"audio.player.playTitle"),"aria-label":r(o?"audio.player.pauseAriaLabel":"audio.player.playAriaLabel"),children:p?a.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-gray-400 border-t-transparent"}):o?a.jsx(Wc,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"}):a.jsx(Kc,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"})}),a.jsxs("div",{className:"flex flex-1 items-center gap-2",children:[a.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:E(u)}),a.jsx("input",{type:"range",min:"0",max:c||0,value:u,onChange:b,disabled:p||!c,className:"flex-1 cursor-pointer accent-gray-600 dark:accent-[#bfc2cd]",style:{background:c?`linear-gradient(to right, rgb(75 85 99) 0%, rgb(75 85 99) ${u/c*100}%, rgb(229 231 235) ${u/c*100}%, rgb(229 231 235) 100%)`:"rgb(229 231 235)"}}),a.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:E(c)})]}),a.jsx(kr,{className:"h-4 w-4 text-gray-500 dark:text-[#bfc2cd]"})]})]})}function Na({image:t,imageUrl:e,imageFormat:s="png",revisedPrompt:n}){const{t:r}=Ee(),[i,o]=h.useState(!1),[l,c]=h.useState(!1),[d,u]=h.useState(null),f=h.useRef(null);h.useEffect(()=>{if(t||!e)return;let x=!1;return(async()=>{try{const y=typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null,v=await fetch(e,{headers:y?{"X-Adapter-Name":y}:{}});if(!v.ok){console.warn("[ImageDisplay] Server returned",v.status,"for",e);return}if(x)return;const A=await v.arrayBuffer();if(x)return;const I=new Blob([A],{type:`image/${s}`}),S=URL.createObjectURL(I);f.current=S,u(S)}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 m=(t?`data:image/${s};base64,${t}`:null)??d;h.useEffect(()=>{if(!i)return;const x=y=>{y.key==="Escape"&&o(!1)};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[i]);const g=x=>{if(x.stopPropagation(),!m)return;const y=document.createElement("a");y.href=m,y.download=`generated-image.${s}`,y.click()};return m?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"generated-image-wrapper",style:{marginTop:"0.75rem"},children:[a.jsxs("div",{className:"generated-image-container",style:{position:"relative",display:"inline-block",cursor:"zoom-in",maxWidth:"100%"},onClick:()=>o(!0),title:n||r("imageDisplay.generatedImageTitle"),children:[a.jsx("img",{src:m,alt:n||r("imageDisplay.generatedImageAlt"),style:{maxWidth:"100%",maxHeight:"480px",borderRadius:"8px",display:"block",objectFit:"contain"}}),a.jsxs("div",{style:{position:"absolute",bottom:"8px",right:"8px",display:"flex",gap:"6px"},children:[a.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:a.jsx(An,{size:14})}),a.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:a.jsx(nd,{size:14})})]})]}),n&&a.jsxs("div",{style:{marginTop:"8px",maxWidth:"480px"},children:[a.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?a.jsx(wr,{size:14}):a.jsx(us,{size:14}),r(l?"imageDisplay.hidePrompt":"imageDisplay.showPrompt")]}),l&&a.jsxs("div",{style:{marginTop:"8px",padding:"8px 10px",background:"rgba(128,128,128,0.08)",borderRadius:"6px"},children:[a.jsx("span",{style:{display:"block",fontSize:"0.65rem",fontWeight:600,opacity:.5,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"3px"},children:r("imageDisplay.promptLabel")}),a.jsx("span",{style:{fontSize:"0.8rem",lineHeight:1.45,opacity:.85},children:n})]})]})]}),i&&typeof document<"u"&&Ir.createPortal(a.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:[a.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:a.jsx(Ye,{size:20})}),a.jsx("img",{src:m,alt:n||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 Zr=[750,1500,3e3,5e3],Id=new Set([403,404,409,425,429,500,502,503,504]),Ld=t=>new Promise(e=>setTimeout(e,t));function Aa({video:t,videoUrl:e,videoFormat:s="mp4",revisedPrompt:n,adapterName:r}){const{t:i}=Ee(),[o,l]=h.useState(!1),[c,d]=h.useState(!1),[u,f]=h.useState(null),p=h.useRef(null);h.useEffect(()=>{if(t||!e)return;let y=!1;return(async()=>{try{const v=r||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null);let A=null;for(let L=0;L<=Zr.length&&(A=await fetch(e,{headers:v?{"X-Adapter-Name":v}:{}}),!(A.ok||!Id.has(A.status)||L===Zr.length));L+=1)if(await Ld(Zr[L]),y)return;if(!(A!=null&&A.ok)){console.warn("[VideoDisplay] Server returned",A.status,"for",e);return}if(y)return;const I=await A.arrayBuffer();if(y)return;const S=new Blob([I],{type:`video/${s}`}),C=URL.createObjectURL(S);p.current=C,f(C)}catch(v){console.warn("[VideoDisplay] Failed to fetch video from",e,v)}})(),()=>{y=!0,p.current&&(URL.revokeObjectURL(p.current),p.current=null)}},[e,t,s,r]);const g=(t?`data:video/${s};base64,${t}`:null)??u;h.useEffect(()=>{if(!o)return;const y=v=>{v.key==="Escape"&&l(!1)};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[o]);const x=y=>{if(y.stopPropagation(),!g)return;const v=document.createElement("a");v.href=g,v.download=`generated-video.${s}`,v.click()};return g?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"generated-video-wrapper",style:{marginTop:"0.75rem"},children:[a.jsxs("div",{style:{position:"relative",display:"inline-block",maxWidth:"100%"},children:[a.jsx("video",{src:g,controls:!0,style:{maxWidth:"100%",maxHeight:"480px",borderRadius:"8px",display:"block",backgroundColor:"#000"}}),a.jsxs("div",{style:{position:"absolute",bottom:"48px",right:"8px",display:"flex",gap:"6px"},children:[a.jsx("button",{onClick:x,title:i("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:a.jsx(An,{size:14})}),a.jsx("button",{onClick:y=>{y.stopPropagation(),l(!0)},title:i("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:a.jsx(Pc,{size:14})})]})]}),n&&a.jsxs("div",{style:{marginTop:"8px",maxWidth:"480px"},children:[a.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?a.jsx(wr,{size:14}):a.jsx(us,{size:14}),i(c?"videoDisplay.hidePrompt":"videoDisplay.showPrompt")]}),c&&a.jsxs("div",{style:{marginTop:"8px",padding:"8px 10px",background:"rgba(128,128,128,0.08)",borderRadius:"6px"},children:[a.jsx("span",{style:{display:"block",fontSize:"0.65rem",fontWeight:600,opacity:.5,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"3px"},children:i("videoDisplay.promptLabel")}),a.jsx("span",{style:{fontSize:"0.8rem",lineHeight:1.45,opacity:.85},children:n})]})]})]}),o&&a.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:[a.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:a.jsx(Ye,{size:20})}),a.jsx("video",{src:g,controls:!0,autoPlay:!0,style:{maxWidth:"92vw",maxHeight:"92vh",borderRadius:"8px"},onClick:y=>y.stopPropagation()})]})]}):null}let vr=null;function Ai(t){vr=t}function Mr(){vr=null}async function _n(){if(!vr)return null;try{return await vr()}catch{return null}}let mn=!1,Ps=null;const pn=new Set;function Ii(){pn.forEach(t=>t())}function xt(){return mn}function Ed(){return Ps}function Fr(t){mn!==t&&(mn=t,!t&&Ps!==null&&(Ps=null),Ii())}function cs(t){const e=typeof t=="string"&&t.trim().length>0?t.trim():null;Ps!==e&&(Ps=e,Ii())}function Td(t){return pn.add(t),()=>{pn.delete(t)}}const Ia="orbitchat-guest-user-id";function nr(t){if(typeof t!="string")return null;const e=t.trim();return e.length>0?e:null}function _d(t){const e=t.split(".");if(e.length<2)return null;try{const s=e[1].replace(/-/g,"+").replace(/_/g,"/"),n=s.padEnd(Math.ceil(s.length/4)*4,"="),r=atob(n);return JSON.parse(r)}catch{return null}}function Md(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return`guest:orbitchat:${t.randomUUID()}`;if(!t||typeof t.getRandomValues!="function")throw new Error("Secure random number generation is unavailable");const e=new Uint8Array(16);return t.getRandomValues(e),`guest:orbitchat:${Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}`}function Fd(){if(typeof window>"u")return"guest:orbitchat:server";const t=window.localStorage.getItem(Ia);if(t&&t.trim().length>0)return t;const e=Md();return window.localStorage.setItem(Ia,e),e}async function Li(){const t=Ed();if(t)return t;const e=await _n();if(e){const s=_d(e),n=nr(s==null?void 0:s.sub)||nr(s==null?void 0:s.user_id)||nr(s==null?void 0:s.preferred_username)||nr(s==null?void 0:s.email);if(n)return n}return xt()?"authenticated:orbitchat:unknown":Fd()}const $d={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"},La={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}/,Pd=/((?:p\.)?generated-docx-preview-num-\d+-\d+:before\s*\{[^}]*?)content\s*:\s*"([^"]*)"\s*;([^}]*?\})/g;function Rd(t){var s;return gr.test(t)?`•${((s=t.match(/(?:\\9|\t|\u00A0| )+$/))==null?void 0:s[0])||"\\9"}`:null}function Ea(t){Array.from(t.querySelectorAll("style")).forEach(n=>{const r=n.textContent;!r||!gr.test(r)||(n.textContent=r.replace(Pd,(i,o,l,c)=>{const d=Rd(l);if(!d)return i;const u=c.replace(/\s*font-family\s*:\s*[^;{}]+;?/gi,"");return`${o}content: "${d}";${u}`}))}),Array.from(t.querySelectorAll('span[style*="font-family"]')).forEach(n=>{if(!/\b(symbol|wingdings|webdings)\b/i.test(n.style.fontFamily))return;const r=n.textContent||"";gr.test(r)&&(n.textContent=r.replace(gr,"•"),n.style.fontFamily="")})}function Dd(t){return(t||"pdf").toLowerCase().replace(/^\./,"")||"pdf"}function Od(t){const e=window.atob(t),s=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)s[n]=e.charCodeAt(n);return s.buffer}function Ud(t){return t==="xlsx"||t==="csv"?a.jsx(Ec,{className:"h-5 w-5"}):t==="pptx"?a.jsx(Xc,{className:"h-5 w-5"}):t==="md"?a.jsx(Lc,{className:"h-5 w-5"}):a.jsx(Tc,{className:"h-5 w-5"})}function Ta({document:t,documentUrl:e,documentFormat:s="pdf",revisedPrompt:n,adapterName:r}){const{t:i}=Ee(),o=Dd(s),[l,c]=h.useState(t||e?"loading":"idle"),[d,u]=h.useState(null),[f,p]=h.useState(null),[m,g]=h.useState([]),[x,y]=h.useState(""),[v,A]=h.useState(null),[I,S]=h.useState([]),[C,L]=h.useState(0),[F,b]=h.useState(!1),[E,k]=h.useState(null),N=h.useRef(null),T=h.useRef(null),_=h.useRef(null),O=n||La[o]||i("documentDisplay.generatedDocument"),j=h.useMemo(()=>`generated-document.${o}`,[o]),U=$d[o]||"application/octet-stream";h.useEffect(()=>{if(!t&&!e)return;let te=!1;return(async()=>{c("loading"),k(null),g([]),y(""),A(null),S([]),L(0);try{const ee=t?Od(t):await(async()=>{const re=(r==null?void 0:r.trim())||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),q={"X-User-ID":await Li()};re&&(q["X-Adapter-Name"]=re);const Q=await _n();Q&&(q.Authorization=`Bearer ${Q}`);const se=await fetch(e,{headers:q});if(!se.ok)throw new Error(`Server returned ${se.status}`);return se.arrayBuffer()})();if(te)return;const me=new Blob([ee],{type:U}),D=URL.createObjectURL(me);if(N.current&&URL.revokeObjectURL(N.current),N.current=D,u(D),p(ee.slice(0)),o==="xlsx"){const{default:re}=await St(async()=>{const{default:se}=await import("./index-CZz_ECqk.js");return{default:se}},[]),Q=(await re(me))[0];y((Q==null?void 0:Q.sheet)||"First sheet"),g(((Q==null?void 0:Q.data)||[]).slice(0,100).map(se=>se.slice(0,30).map(fe=>fe==null?"":String(fe))))}if(o==="md"&&A(new TextDecoder("utf-8").decode(ee)),o==="csv"){const re=new TextDecoder("utf-8").decode(ee),{default:q}=await St(async()=>{const{default:se}=await import("./papaparse.min-D13ujVVP.js").then(fe=>fe.p);return{default:se}},__vite__mapDeps([19,1])),Q=q.parse(re,{skipEmptyLines:!0});L(Q.data.length),S(Q.data.slice(0,25))}c("ready")}catch(ee){if(te)return;console.warn("[DocumentDisplay] Failed to load document from",e,ee),k(ee instanceof Error?ee.message:"Unable to load document"),c("error")}})(),()=>{te=!0,N.current&&(URL.revokeObjectURL(N.current),N.current=null)}},[r,t,e,o,U]),h.useEffect(()=>{if(l!=="ready"||o!=="docx"||!f||!T.current)return;const te=T.current;te.replaceChildren(),St(()=>import("./docx-preview-DehBmhog.js"),__vite__mapDeps([20,1])).then(async({renderAsync:V})=>{await V(f.slice(0),te,void 0,{className:"generated-docx-preview",inWrapper:!1,ignoreWidth:!0,ignoreHeight:!0}),Ea(te)}).catch(V=>{console.warn("[DocumentDisplay] Failed to render DOCX preview",V),k("Unable to render document preview")})},[f,o,l]),h.useEffect(()=>{if(!F||o!=="docx"||!f||!_.current)return;const te=_.current;te.replaceChildren(),St(()=>import("./docx-preview-DehBmhog.js"),__vite__mapDeps([20,1])).then(async({renderAsync:V})=>{await V(f.slice(0),te,void 0,{className:"generated-docx-preview",inWrapper:!1,ignoreWidth:!0,ignoreHeight:!0}),Ea(te)}).catch(V=>{console.warn("[DocumentDisplay] Failed to render modal DOCX preview",V)})},[f,o,F]),h.useEffect(()=>{if(!F)return;const te=V=>{V.key==="Escape"&&b(!1)};return window.document.addEventListener("keydown",te),()=>window.document.removeEventListener("keydown",te)},[F]);const z=te=>{if(te==null||te.stopPropagation(),!d)return;const V=window.document.createElement("a");V.href=d,V.download=j,V.click()},R=l==="ready"&&(o==="pdf"||o==="docx"||o==="xlsx"||o==="md"||o==="csv"),X=R&&o!=="xlsx"&&o!=="csv";return l==="idle"?null:a.jsxs(a.Fragment,{children:[a.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:[a.jsxs("div",{className:"flex items-center gap-3 border-b border-gray-100 px-3 py-2.5 dark:border-[#3b3c49]",children:[a.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:Ud(o)}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"truncate text-sm font-medium text-[#353740] dark:text-[#ececf1]",children:O}),a.jsxs("p",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:[La[o]||`${o.toUpperCase()} document`,l==="loading"?` · ${i("documentDisplay.loadingPreview")}`:"",l==="error"?` · ${E||i("documentDisplay.previewUnavailableShort")}`:""]})]}),X&&a.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:i("documentDisplay.openPreviewTooltip"),"aria-label":i("documentDisplay.openPreviewTooltip"),children:a.jsx(Ic,{className:"h-4 w-4"})}),a.jsx("button",{type:"button",onClick:z,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:i("documentDisplay.downloadDocumentTooltip"),"aria-label":i("documentDisplay.downloadDocumentTooltip"),children:a.jsx(An,{className:"h-4 w-4"})})]}),R&&a.jsxs("div",{className:"max-h-[460px] overflow-auto bg-gray-50 dark:bg-[#171717]",children:[o==="pdf"&&d&&a.jsx("iframe",{src:d,title:O,className:"block h-[460px] w-full border-0 bg-white"}),o==="docx"&&a.jsx("div",{ref:T,className:"min-h-[240px] bg-white p-5 text-sm text-[#111827] dark:bg-white dark:text-[#111827]"}),o==="xlsx"&&a.jsxs("div",{className:"p-3",children:[x&&a.jsx("p",{className:"mb-2 text-xs font-medium text-gray-500 dark:text-[#bfc2cd]",children:x}),a.jsx("div",{className:"overflow-auto rounded-md border border-gray-200 bg-white dark:border-[#3b3c49] dark:bg-[#202123]",children:a.jsx("table",{className:"min-w-full border-collapse text-left text-xs",children:a.jsx("tbody",{children:m.length>0?m.map((te,V)=>a.jsx("tr",{className:V===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:te.map((ee,me)=>a.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:ee},me))},V)):a.jsx("tr",{children:a.jsx("td",{className:"px-3 py-4 text-sm text-gray-500 dark:text-[#bfc2cd]",children:i("documentDisplay.noSheetDataFound")})})})})})]}),o==="md"&&v!==null&&a.jsx("div",{className:"bg-white p-5 text-sm text-[#111827] dark:bg-[#171717] dark:text-[#ececf1]",children:a.jsx(It,{content:v,disableMath:!0})}),o==="csv"&&a.jsxs("div",{className:"p-3",children:[C>25&&a.jsx("p",{className:"mb-2 text-xs text-gray-500 dark:text-[#bfc2cd]",children:i("documentDisplay.csvRowsPreviewMessage",{count:C})}),a.jsx("div",{className:"overflow-auto rounded-md border border-gray-200 bg-white dark:border-[#3b3c49] dark:bg-[#202123]",children:a.jsx("table",{className:"min-w-full border-collapse text-left text-xs",children:a.jsx("tbody",{children:I.length>0?I.map((te,V)=>a.jsx("tr",{className:V===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:te.map((ee,me)=>a.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:ee},me))},V)):a.jsx("tr",{children:a.jsx("td",{className:"px-3 py-4 text-sm text-gray-500 dark:text-[#bfc2cd]",children:i("documentDisplay.noDataFound")})})})})})]})]}),l==="ready"&&!R&&a.jsx("div",{className:"px-3 py-4 text-sm text-gray-600 dark:text-[#bfc2cd]",children:i("documentDisplay.previewUnavailable")})]}),F&&d&&a.jsxs("div",{onClick:()=>b(!1),className:"fixed inset-0 z-[9999] flex items-center justify-center bg-black/85 p-4",children:[a.jsx("button",{onClick:te=>{te.stopPropagation(),b(!1)},className:"fixed right-4 top-4 flex items-center rounded-full border-0 bg-white/15 p-2 text-white",title:i("common.close"),"aria-label":i("common.close"),children:a.jsx(Ye,{className:"h-5 w-5"})}),a.jsxs("div",{onClick:te=>te.stopPropagation(),className:"h-[92vh] w-[92vw] overflow-auto rounded-lg bg-white",children:[o==="pdf"&&a.jsx("iframe",{src:d,title:O,className:"h-full w-full border-0"}),o==="docx"&&a.jsx("div",{ref:_,className:"min-h-full bg-white p-8 text-[#111827]"}),o==="md"&&v!==null&&a.jsx("div",{className:"min-h-full bg-white p-8 text-sm text-[#111827]",children:a.jsx(It,{content:v,disableMath:!0})})]})]})]})}const zd=["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 Rs(t,{enabled:e,onEscape:s}){h.useEffect(()=>{if(!e||!t.current)return;const n=t.current,r=document.activeElement,i=Array.from(n.querySelectorAll(zd)).filter(d=>d.tabIndex!==-1),o=i[0]||n,l=i[i.length-1]||n;o.focus({preventScroll:!0});const c=d=>{if(d.key==="Escape"){s==null||s();return}if(d.key!=="Tab")return;if(i.length===0){d.preventDefault(),n.focus({preventScroll:!0});return}const u=document.activeElement;if(d.shiftKey){(!u||u===o||!n.contains(u))&&(d.preventDefault(),l.focus({preventScroll:!0}));return}(!u||u===l||!n.contains(u))&&(d.preventDefault(),o.focus({preventScroll:!0}))};return document.addEventListener("keydown",c),()=>{var d;document.removeEventListener("keydown",c),(d=r==null?void 0:r.focus)==null||d.call(r,{preventScroll:!0})}},[e,s,t])}function Sr({isOpen:t,onClose:e,onConfirm:s,title:n,message:r,confirmText:i,cancelText:o,type:l="danger",isLoading:c=!1}){const d=h.useRef(null);Rs(d,{enabled:t,onEscape:e});const{t:u}=Ee(),f=i??u("common.confirm"),p=o??u("common.cancel");if(!t)return null;const m=()=>{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=a.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:a.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:[a.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-[#2d2f39]",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full ${x.iconBg} flex items-center justify-center`,children:a.jsx(En,{className:`w-5 h-5 ${x.icon}`})}),a.jsx("h2",{id:"confirm-title",className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:n})]}),a.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:a.jsx(Ye,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),a.jsx("div",{className:"p-6",children:a.jsx("p",{className:"text-gray-600 dark:text-gray-300 leading-relaxed",children:r})}),a.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:[a.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:p}),a.jsx("button",{type:"button",onClick:m,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?a.jsxs("div",{className:"flex items-center gap-2",children:[a.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 Bd=["#","*","`","[","]","(",")","{","}","|","<",">"],Ei=t=>Bd.some(e=>t.includes(e));function Ti(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 n=/\b(the|and|for|are|but|not|you|all|can|function|const|let|var|class|return|import|export|async|await|if|else|while|true|false|null|undefined|http|https|www|error|data|response|request|api|json|xml|html|css|js|py|java|cpp|def|print|console|log)\b/i.test(t),r=Ei(t),i=/[-.,;:!?'"()]/.test(t);if(!n&&!r&&!i)return!0}return!!(s.length>5e4&&e.test(s)&&t.replace(/[A-Za-z0-9+/=\s]/g,"").length<10)}const Hd=/(?:\u202F|\u2009|\u200A|\u200B|\u200C|\u200D|\uFEFF)/g;function Ds(t){if(!t)return t;let e=t.replace(Hd," ");if(Ti(e))return"";const s=/([A-Za-z0-9+/=]{10000,})/g;return e=e.replace(s,n=>{const r=n.replace(/\s+/g,"");if(r.length>1e4&&/^[A-Za-z0-9+/=]+$/.test(r)){const i=/\b(function|const|let|var|class|return|import|export|if|else|while|for|true|false|null|def|print)\b/i.test(n),o=Ei(n),l=/[-.,;:!?'"()]/.test(n);if(!i&&!o&&!l)return""}return n}),e}function gn(t,e=5e4){return!t||t.length<=e?t:Ti(t)?"":t.substring(0,e)+`
320
+
321
+ ... (content truncated due to length)`}const Vd={maxFilesPerConversation:Y.limits.files.perConversation,maxFileSizeMB:Y.limits.files.maxSizeMB,maxTotalFiles:Y.limits.files.totalFiles,maxConversations:Y.limits.conversations.maxConversations,maxMessagesPerConversation:Y.limits.conversations.maxMessagesPerConversation,maxMessagesPerThread:Y.limits.conversations.maxMessagesPerThread,maxTotalMessages:Y.limits.conversations.totalMessages,maxMessageLength:Y.limits.messages.maxLength};function qd(t){const e=Y.guestLimits;switch(t){case"maxConversations":return e.conversations.maxConversations;case"maxMessagesPerConversation":return e.conversations.messagesPerConversation;case"maxMessagesPerThread":return e.conversations.messagesPerThread;case"maxTotalMessages":return e.conversations.totalMessages;case"maxFilesPerConversation":return e.files.perConversation;case"maxTotalFiles":return e.files.totalFiles;case"maxMessageLength":return e.messages.maxLength;case"maxFileSizeMB":return e.files.maxSizeMB;default:return}}const oe=new Proxy(Vd,{get(t,e){if(tt()&&!xt()){const s=qd(e);if(s!==void 0)return s}return t[e]}});function fs(){return h.useSyncExternalStore(Td,xt,xt)}class _i extends Error{constructor(s,n){super(s);Xe(this,"status");Xe(this,"statusText");this.name="ApiRequestError",this.status=n.status,this.statusText=n.statusText}}async function Re(t={}){const e={"X-User-ID":await Li(),...t},s=await _n();return s&&(e.Authorization=`Bearer ${s}`),e}function wt(t){return encodeURIComponent(t)}function Wd(t){return!t||t.length===0?"":`?file_ids=${t.map(encodeURIComponent).join(",")}`}async function As(t){const e=`API request failed: ${t.status} ${t.statusText}`;try{if((t.headers.get("content-type")||"").includes("application/json")){const n=await t.json(),r=typeof n.detail=="string"&&n.detail.trim()||typeof n.error=="string"&&n.error.trim()||typeof n.message=="string"&&n.message.trim();if(r)return`${e}: ${r}`}else{const n=(await t.text()).trim();if(n)return`${e}: ${n}`}}catch{}return e}function _a(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,assistant_message_id:e.assistant_message_id,threading:e.threading}}catch{return null}}let ar=null;function Kd(){let t=null,e=null;const s=(r,i,o)=>{t=i||null,e=o||null},n=(r,i)=>({async*streamChat(o,l,c,d,u,f,p,m,g,x,y,v,A,I){var L,F;const S={messages:[{role:"user",content:o}],stream:l!==!1};c&&c.length>0&&(S.file_ids=c),d&&(S.thread_id=d),u&&(S.audio_input=u),f&&(S.audio_format=f),p&&(S.language=p),m!==void 0&&(S.return_audio=m),g&&(S.tts_voice=g),x&&(S.source_language=x),y&&(S.target_language=y),v&&(S.model=v),A&&(S.skill=A),I&&(S.regenerate_of_message_id=I);const C=await fetch("/api/v1/chat",{method:"POST",headers:await Re({"Content-Type":"application/json","X-Adapter-Name":r,...i?{"X-Session-ID":i}:{}}),body:JSON.stringify(S)});if(!C.ok)throw new Error(await As(C));if((L=C.headers.get("content-type"))!=null&&L.includes("text/event-stream")){const b=(F=C.body)==null?void 0:F.getReader(),E=new TextDecoder;let k="";if(!b)throw new Error("Response body is not readable");for(;;){const{done:N,value:T}=await b.read();if(N)break;k+=E.decode(T,{stream:!0});const _=k.split(`
322
+ `);k=_.pop()||"";for(const O of _){const j=_a(O);j&&(yield j)}}if(k.trim())for(const N of k.split(`
323
+ `)){const T=_a(N);T&&(yield T)}}else{const b=await C.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,assistant_message_id:b.assistant_message_id,threading:b.threading}}},async createThread(o,l){const c=await fetch("/api/threads",{method:"POST",headers:await Re({"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/${wt(o)}`,{headers:await Re({"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/${wt(o)}`,{method:"DELETE",headers:await Re({"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 Re({"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/${wt(o)}`,{headers:await Re({"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||i;if(!l)throw new Error("No session ID available for clearing conversation history");const c=await fetch(`/api/admin/chat-history/${wt(l)}`,{method:"DELETE",headers:await Re({"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||i;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/${wt(c)}${d}`,{headers:await Re({"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||i;if(!c)throw new Error("No session ID available for deleting conversation");const d=Wd(l),u=await fetch(`/api/admin/conversations/${wt(c)}${d}`,{method:"DELETE",headers:await Re({"X-Adapter-Name":r})});if(!u.ok)throw new Error(`Failed to delete conversation: ${u.statusText}`);return u.json()},getSessionId:()=>i,async uploadFile(o){const l=new FormData;l.append("file",o);const c=await fetch("/api/files/upload",{method:"POST",headers:await Re({"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 Re({"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/${wt(o)}`,{headers:await Re({"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/${wt(o)}/query`,{method:"POST",headers:await Re({"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/${wt(o)}`,{method:"DELETE",headers:await Re({"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/${wt(r)}/status`,{headers:await Re({"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 p=Number(f);if(Number.isFinite(p)&&p>0)return Math.min(p*1e3,3e4);const m=Date.parse(f);if(!Number.isNaN(m)){const g=m-Date.now();if(g>0)return Math.min(g,3e4)}return 0},c=f=>new Promise(p=>setTimeout(p,f)),d=async()=>fetch(o,{headers:await Re({"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(),p=`${u.status} ${u.statusText}`.trim(),m=u.status===401?`Adapter info request was unauthorized for '${r}'. Verify the adapter exists and you have access.`:`Failed to load adapter info (${p}) for '${r}'.`;throw console.warn("[ProxyApi] Adapter info request failed",{adapter:r,status:u.status,statusText:u.statusText,details:f||void 0}),new _i(m,u)}return u.json()},async stopChat(o,l){const c=await fetch("/api/v1/chat/stop",{method:"POST",headers:await Re({"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 Re({"X-Adapter-Name":r})});if(!l.ok)throw new Error(await As(l));return l.json()},async getAllModels(){const o=await fetch("/api/admin/models",{headers:await Re({"X-Adapter-Name":r})});if(!o.ok)throw new Error(await As(o));return o.json()},async getAdapterSkills(o){const l=await fetch(`/api/admin/adapters/${encodeURIComponent(o)}/skills`,{headers:await Re({"X-Adapter-Name":r})});if(!l.ok)throw new Error(await As(l));return l.json()},async getAllSkills(){const o=await fetch("/api/admin/skills",{headers:await Re({"X-Adapter-Name":r})});if(!o.ok)throw new Error(await As(o));return o.json()}});return{configureApi:s,streamChat:async function*(r,i,o,l,c,d,u,f,p,m,g,x,y,v){if(!e)throw new Error("Adapter name is required");yield*n(e,t).streamChat(r,i,o,l,c,d,u,f,p,m,g,x,y,v)},stopChat:async(r,i)=>{if(!e)throw new Error("Adapter name is required");return n(e,t).stopChat(r,i)},ApiClient:class{constructor(i){Xe(this,"client");const o=i.adapterName||null,l=i.sessionId||null;if(!o)throw new Error("Adapter name is required");this.client=n(o,l)}async*streamChat(...i){yield*this.client.streamChat(...i)}get createThread(){var i;return(i=this.client.createThread)==null?void 0:i.bind(this.client)}get getThreadInfo(){var i;return(i=this.client.getThreadInfo)==null?void 0:i.bind(this.client)}get deleteThread(){var i;return(i=this.client.deleteThread)==null?void 0:i.bind(this.client)}get submitFeedback(){var i;return(i=this.client.submitFeedback)==null?void 0:i.bind(this.client)}get getSessionFeedback(){var i;return(i=this.client.getSessionFeedback)==null?void 0:i.bind(this.client)}get clearConversationHistory(){var i;return(i=this.client.clearConversationHistory)==null?void 0:i.bind(this.client)}get getConversationHistory(){var i;return(i=this.client.getConversationHistory)==null?void 0:i.bind(this.client)}get deleteConversationWithFiles(){var i;return(i=this.client.deleteConversationWithFiles)==null?void 0:i.bind(this.client)}get getSessionId(){var i;return(i=this.client.getSessionId)==null?void 0:i.bind(this.client)}get uploadFile(){var i;return(i=this.client.uploadFile)==null?void 0:i.bind(this.client)}get listFiles(){var i;return(i=this.client.listFiles)==null?void 0:i.bind(this.client)}get getFileInfo(){var i;return(i=this.client.getFileInfo)==null?void 0:i.bind(this.client)}get queryFile(){var i;return(i=this.client.queryFile)==null?void 0:i.bind(this.client)}get deleteFile(){var i;return(i=this.client.deleteFile)==null?void 0:i.bind(this.client)}get validateApiKey(){var i;return(i=this.client.validateApiKey)==null?void 0:i.bind(this.client)}get getAdapterInfo(){var i;return(i=this.client.getAdapterInfo)==null?void 0:i.bind(this.client)}get stopChat(){var i;return(i=this.client.stopChat)==null?void 0:i.bind(this.client)}get getAdapterModels(){var i;return(i=this.client.getAdapterModels)==null?void 0:i.bind(this.client)}get getAllModels(){var i;return(i=this.client.getAllModels)==null?void 0:i.bind(this.client)}get getAdapterSkills(){var i;return(i=this.client.getAdapterSkills)==null?void 0:i.bind(this.client)}get getAllSkills(){var i;return(i=this.client.getAllSkills)==null?void 0:i.bind(this.client)}}}}async function Gd(){return ar||($("Loading API via Express proxy"),ar=Kd(),$("API loaded successfully"),ar)}async function Fe(){return await Gd()}class Ma{static async getAdapterSkills(e,s){const n=await Fe(),r=new n.ApiClient({apiUrl:"",adapterName:s});return r.getAdapterSkills?(await r.getAdapterSkills(e)).available_skills:[]}static async getAllSkills(e){const s=await Fe(),n=new s.ApiClient({apiUrl:"",adapterName:e});return n.getAllSkills?(await n.getAllSkills()).skills:[]}}const Xd=6e4;function Mi(t={}){const{adapterName:e,enabled:s=!0,selectionScopeKey:n,supportsThreading:r=!1}=t,i=s&&!!e&&!r,o=n??e??"__default__",[l,c]=h.useState([]),[d,u]=h.useState(!1),[f,p]=h.useState(null),[m,g]=h.useState({}),x=h.useRef(null),y=h.useRef(new Map),v=h.useCallback(async C=>{var b,E;const L=C,F=y.current.get(L);if(F&&F.expiresAt>Date.now()){c(F.skills),p(C);return}x.current&&x.current.abort(),x.current=new AbortController,u(!0);try{const[k,N]=await Promise.all([Ma.getAdapterSkills(C,C),Ma.getAllSkills(C)]);if((b=x.current)!=null&&b.signal.aborted)return;const T=N.filter(_=>k.includes(_.name)&&_.enabled);y.current.set(L,{skills:T,expiresAt:Date.now()+Xd}),c(T),p(C),$("[useSkills] Loaded",T.length,"skills for adapter",C)}catch(k){if(k instanceof Error&&k.name==="AbortError")return;ge("[useSkills] Failed to load skills:",k instanceof Error?k.message:String(k)),c([]),p(C)}finally{(E=x.current)!=null&&E.signal.aborted||u(!1)}},[]);h.useEffect(()=>{if(!i||!e)return;const C=window.setTimeout(()=>{v(e)},0);return()=>{var L;window.clearTimeout(C),(L=x.current)==null||L.abort()}},[i,e,v]);const A=h.useCallback(C=>{g(L=>{const F=L[o]??null;if(F===C||(F==null?void 0:F.name)===(C==null?void 0:C.name))return L;const b={...L};return C?b[o]=C:delete b[o],b})},[o]),I=h.useCallback(()=>{g(C=>{if(!C[o])return C;const L={...C};return delete L[o],L})},[o]),S=i?m[o]??null:null;return{skills:i&&f===e?l:[],isLoading:i?d||f!==e:!1,selectedSkill:S,selectSkill:A,clearSkill:I}}const Fa=t=>{let e;const s=new Set,n=(d,u)=>{const f=typeof d=="function"?d(e):d;if(!Object.is(f,e)){const p=e;e=u??(typeof f!="object"||f===null)?f:Object.assign({},e,f),s.forEach(m=>m(e,p))}},r=()=>e,l={setState:n,getState:r,getInitialState:()=>c,subscribe:d=>(s.add(d),()=>s.delete(d))},c=e=t(n,r,l);return l},Yd=(t=>t?Fa(t):Fa),Qd=t=>t;function Jd(t,e=Qd){const s=vt.useSyncExternalStore(t.subscribe,vt.useCallback(()=>e(t.getState()),[t,e]),vt.useCallback(()=>e(t.getInitialState()),[t,e]));return vt.useDebugValue(s),s}const $a=t=>{const e=Yd(t),s=n=>Jd(e,n);return Object.assign(s,e),s},Fi=(t=>t?$a(t):$a),st=Fi(t=>({showLoginPrompt:!1,promptMessage:"",openLoginPrompt:e=>t({showLoginPrompt:!0,promptMessage:e}),closeLoginPrompt:()=>t({showLoginPrompt:!1,promptMessage:""})})),ir=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,n,r,i){try{const o=oe.maxFileSizeMB*1024*1024;if(e.size>o)throw new Error(`File size exceeds maximum limit of ${oe.maxFileSizeMB}MB`);if(!(["application/pdf","text/plain","text/markdown","text/csv","application/json","text/html","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel","application/vnd.ms-excel.sheet.macroEnabled.12","text/x-python","text/x-python-script","text/x-java-source","text/x-java","text/x-sql","text/javascript","application/javascript","text/typescript","application/typescript","text/x-c++src","text/x-csrc","text/x-c","text/x-go","text/x-rust","text/x-ruby","text/x-php","text/x-shellscript","text/x-sh","text/yaml","text/x-yaml","text/xml","application/xml","text/css","text/x-scss","text/x-sass","text/x-less","image/png","image/jpeg","image/tiff","image/webp","audio/wav","audio/mpeg","audio/mp3","audio/mp4","audio/ogg","audio/flac","audio/webm","audio/x-m4a","audio/aac","text/vtt"].includes(e.type)||/\.(pdf|txt|md|csv|json|html|docx|pptx|xlsx|py|java|sql|js|mjs|ts|tsx|cpp|cxx|cc|c|h|hpp|go|rs|rb|php|sh|bash|zsh|yaml|yml|xml|css|scss|sass|less|png|jpe?g|tiff?|webp|wav|mp3|mp4|ogg|flac|webm|m4a|aac|vtt)$/i.test(e.name)||(e.type==="application/x-zip-compressed"||e.type==="application/zip")&&/\.xlsx$/i.test(e.name)))throw new Error(`File type not supported: ${e.type||"unknown"}`);s&&s({filename:e.name,progress:0,status:"uploading"});const d=await Fe(),u=(r==null?void 0:r.trim())||$e(),f=ir(i);if(!f)throw new Error("Adapter not configured. Please select an adapter from the dropdown.");$(`Using adapter: ${f}`);const p=new d.ApiClient({apiUrl:u,sessionId:null,adapterName:f});if(!p.uploadFile)throw new Error("File upload is not available.");const m=await p.uploadFile(e);s&&s({filename:e.name,progress:75,status:"processing",fileId:m.file_id});let g;try{g=await this.pollFileStatus(m.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 ${m.file_id} was deleted during upload`);ge(`File status polling failed for ${m.file_id}:`,x);const v=y.includes("processing failed")||y.includes("timeout");g={file_id:m.file_id,filename:m.filename,mime_type:m.mime_type,file_size:m.file_size,processing_status:v?"failed":m.status||"processing",chunk_count:m.chunk_count,error_message:v?y:void 0}}return s&&s({filename:e.name,progress:100,status:g.processing_status==="completed"?"completed":"processing",fileId:m.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=[],i=[];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,p=>{s&&s(f,p)})}));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),i.push({index:f,file:e[f].name,error:u.reason}))}}if(r.length===0&&i.length>0){const o=i[0].error;throw o instanceof Error?o:new Error(`All ${i.length} file uploads failed`)}return i.length>0&&ge(`[FileUploadService] ${i.length} of ${e.length} files failed to upload:`,i.map(o=>o.file)),r}static async listFiles(e,s,n){try{const r=await Fe(),i=(s==null?void 0:s.trim())||$e(),o=ir(n);if(!o)throw new Error("Adapter not configured");const l=new r.ApiClient({apiUrl:i,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 i=r instanceof Error?r.message:"Failed to list files";throw new Error(i)}}static async getFileInfo(e,s,n,r){try{const i=await Fe(),o=(n==null?void 0:n.trim())||$e(),l=ir(r);if(!l)throw new Error("Adapter not configured");const c=new i.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(i){if(i instanceof Error&&(i.message.includes("404")||i.message.includes("File not found")))throw new Error(`File ${e} was deleted`);Oe(`Failed to get file info for ${e}:`,i);const o=i instanceof Error?i.message:`Failed to get file info: ${e}`;throw new Error(o)}}static async pollFileStatus(e,s=30,n=2e3,r,i,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,i,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,n))}catch(c){const d=c instanceof Error?c.message:String(c);if(d.includes("404")||d.includes("File not found")||d.includes("was deleted"))throw new Error(`File ${e} was deleted during upload`);if(d.includes("component unmounted")||d.includes("processing failed")||d.includes("processing_status")||d.includes("401")||d.includes("403")||d.includes("500")||d.includes("502")||d.includes("503")||d.includes("Authentication")||d.includes("Adapter not configured"))throw c;if(l<s-1){await new Promise(u=>setTimeout(u,n));continue}throw c}throw new Error(`File processing timeout: ${e} did not complete within ${s*n/1e3} seconds`)}static async deleteFile(e,s,n,r){try{const i=await Fe(),o=(n==null?void 0:n.trim())||$e(),l=ir(r);if(!l)throw new Error("Adapter not configured");const c=new i.ApiClient({apiUrl:o,sessionId:null,adapterName:l});if(!c.deleteFile)throw new Error("File deletion is not available.");return await c.deleteFile(e)}catch(i){if(i instanceof Error&&(i.message.includes("404")||i.message.includes("File not found")||i.message.includes("Not Found")))return $(`File ${e} was already deleted from server`),{message:"File already deleted",file_id:e};Oe(`Failed to delete file ${e}:`,i);const o=i instanceof Error?i.message:`Failed to delete file: ${e}`;throw new Error(o)}}}class Zd{constructor(){Xe(this,"audioQueue",[]);Xe(this,"isPlaying",!1);Xe(this,"currentAudio",null);Xe(this,"audioContext",null);Xe(this,"isEnabled",!1);Xe(this,"onPlaybackStart",null);Xe(this,"onPlaybackEnd",null);Xe(this,"mimeTypeCache",new Map);Xe(this,"onChunkPlayed",null);Xe(this,"blobUrls",[]);Xe(this,"suppressPlaybackErrors",!1)}async enableAudio(){var e,s;try{if(!this.audioContext){const i=typeof AudioContext<"u"?AudioContext:typeof window<"u"&&window.webkitAudioContext||null;i&&(this.audioContext=new i)}const n=((e=this.audioContext)==null?void 0:e.state)==="suspended"?this.audioContext.resume():Promise.resolve();let r=Promise.resolve();try{const i=this.createSilentWavBlob(),o=URL.createObjectURL(i),l=new Audio;l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),l.src=o,l.volume=0,r=l.play().then(()=>{l.pause()}).catch(()=>{$("[AudioStreamManager] HTMLAudioElement silent unlock failed (will retry on next gesture)")}).finally(()=>{URL.revokeObjectURL(o)})}catch{$("[AudioStreamManager] Could not create silent audio element")}if(await n,this.audioContext&&this.audioContext.state==="running"){const i=this.audioContext.createBuffer(1,1,22050),o=this.audioContext.createBufferSource();o.buffer=i,o.connect(this.audioContext.destination),o.start(0)}return await r,this.isEnabled=!0,$("[AudioStreamManager] Audio playback enabled",{audioContextState:(s=this.audioContext)==null?void 0:s.state}),!0}catch(n){return ye("[AudioStreamManager] Failed to enable audio:",n),!1}}createSilentWavBlob(){const o=new ArrayBuffer(844),l=new DataView(o),c=(d,u)=>{for(let f=0;f<u.length;f++)l.setUint8(d+f,u.charCodeAt(f))};return c(0,"RIFF"),l.setUint32(4,836,!0),c(8,"WAVE"),c(12,"fmt "),l.setUint32(16,16,!0),l.setUint16(20,1,!0),l.setUint16(22,1,!0),l.setUint32(24,8e3,!0),l.setUint32(28,8e3*2,!0),l.setUint16(32,2,!0),l.setUint16(34,16,!0),c(36,"data"),l.setUint32(40,800,!0),new Blob([o],{type:"audio/wav"})}disableAudio(){!this.isEnabled&&!this.isPlaying||(this.isEnabled=!1,this.stop(),$("[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(n){return ye("[AudioStreamManager] Failed to create AudioContext:",n),!1}}if(((e=this.audioContext)==null?void 0:e.state)==="suspended")try{await this.audioContext.resume()}catch(s){return $("[AudioStreamManager] AudioContext resume deferred",s),!1}return!0}resolveMimeType(e){const s=this.mimeTypeCache.get(e);if(s)return s;let n;switch(e){case"mp3":n="audio/mpeg";break;case"wav":n="audio/wav";break;case"webm":n="audio/webm";break;case"ogg":n="audio/ogg";break;case"opus":{const r=typeof document<"u"?document.createElement("audio"):null;r!=null&&r.canPlayType("audio/ogg; codecs=opus")?n="audio/ogg; codecs=opus":r!=null&&r.canPlayType("audio/webm; codecs=opus")?n="audio/webm; codecs=opus":n="audio/mp4";break}default:n=`audio/${e}`}return this.mimeTypeCache.set(e,n),$(`[AudioStreamManager] Resolved MIME type for "${e}": ${n}`),n}isAudioEnabled(){return this.isEnabled}setOnPlaybackStart(e){this.onPlaybackStart=e}setOnPlaybackEnd(e){this.onPlaybackEnd=e}setOnChunkPlayed(e){this.onChunkPlayed=e}async addChunk(e){if(!this.isEnabled){$(`[AudioStreamManager] Audio disabled, dropping chunk ${e.chunkIndex}`);return}$(`[AudioStreamManager] Adding chunk ${e.chunkIndex} to queue`),this.audioQueue.push(e),this.audioQueue.sort((s,n)=>s.chunkIndex-n.chunkIndex),this.isPlaying||this.playNextChunk().catch(s=>{ye("[AudioStreamManager] Playback chain error:",s)})}async playNextChunk(){var s,n;if(this.audioQueue.length===0){this.isPlaying=!1,$("[AudioStreamManager] Queue empty, playback complete"),this.onPlaybackEnd&&this.onPlaybackEnd();return}if(!this.isEnabled){$("[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(),$(`[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 i=new Uint8Array(r.length);for(let f=0;f<r.length;f++)i[f]=r.charCodeAt(f);const o=this.resolveMimeType(e.audioFormat),l=new Blob([i],{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,o,d)}catch{u=!1}if(!u&&!this.suppressPlaybackErrors&&this.audioContext){$(`[AudioStreamManager] HTMLAudioElement failed for chunk ${e.chunkIndex}, trying AudioContext fallback`);try{u=await this.playViaAudioContext(i.buffer,e.chunkIndex)}catch(f){ye(`[AudioStreamManager] AudioContext fallback also failed for chunk ${e.chunkIndex}:`,f)}d()}this.currentAudio=null,this.playNextChunk().catch(f=>{ye("[AudioStreamManager] Playback chain error:",f)})}catch(r){if(this.suppressPlaybackErrors){$("[AudioStreamManager] Playback stopped, suppressing audio error");return}const i=r instanceof Error?r.message:String(r);console.error(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,i,r,{audioFormat:e.audioFormat,chunkIndex:e.chunkIndex,audioLength:(s=e.audio)==null?void 0:s.length,audioContextState:(n=this.audioContext)==null?void 0:n.state,isEnabled:this.isEnabled}),ye(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,r),this.playNextChunk().catch(o=>{ye("[AudioStreamManager] Playback chain error after recovery:",o)})}}playViaAudioElement(e,s,n,r){return new Promise(i=>{const o=new Audio;o.setAttribute("playsinline",""),o.setAttribute("webkit-playsinline",""),o.src=e,this.currentAudio=o;let l=!1;const c=f=>{l||(l=!0,i(f))},d=()=>{if(this.suppressPlaybackErrors){r(),c(!0);return}const f=o.error;ye(`[AudioStreamManager] Media error on chunk ${s.chunkIndex}:`,f?{code:f.code,message:f.message,SRC_NOT_SUPPORTED:f.code===MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED}:"unknown"),r(),c(!1)};o.addEventListener("error",d,{once:!0});const u=async()=>{if(!l)try{o.addEventListener("ended",()=>{l||($(`[AudioStreamManager] Chunk ${s.chunkIndex} finished`),this.onChunkPlayed&&this.onChunkPlayed(s.chunkIndex),r(),c(!0))},{once:!0}),await o.play()}catch(f){if(this.suppressPlaybackErrors){r(),c(!0);return}$(`[AudioStreamManager] audio.play() rejected for chunk ${s.chunkIndex}:`,f),r(),c(!1)}};o.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA?u():o.addEventListener("canplay",()=>u(),{once:!0})})}playViaAudioContext(e,s){return new Promise((n,r)=>{if(!this.audioContext){r(new Error("No AudioContext"));return}const i=e.slice(0);this.audioContext.decodeAudioData(i,o=>{if(!this.audioContext||this.suppressPlaybackErrors){n(!0);return}const l=this.audioContext.createBufferSource();l.buffer=o,l.connect(this.audioContext.destination),l.onended=()=>{$(`[AudioStreamManager] Chunk ${s} finished (AudioContext path)`),this.onChunkPlayed&&this.onChunkPlayed(s),n(!0)},l.start(0)},o=>{r(o)})})}stop(){$("[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(),$("[AudioStreamManager] Manager reset")}getQueueSize(){return this.audioQueue.length}isCurrentlyPlaying(){return this.isPlaying}}const Ut=new Zd,eu=Jl()||Rl(),$i=()=>{if(Tr())return vn()||void 0},_s="",tu=["New Chat","New Conversation"],su=t=>t&&!tu.includes(t)?t:_s,Ms=(t,e,s)=>({id:t,sessionId:e,title:_s,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:s,adapterName:$i(),adapterLoadError:null}),jr=()=>{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},ru=t=>{localStorage.setItem("chatbot-session-id",t)};let nu=0;const is=t=>{const e=Date.now(),s=++nu,n=Math.random().toString(36).substr(2,9);return`msg_${e}_${s}_${n}_${t}`},zt=()=>{const t=Date.now(),e=Math.random().toString(36).substr(2,9);return`session_${t}_${e}`},Pi=t=>{const e=new Set;let s=!1;const n=t.map(r=>{if(!e.has(r.id))return e.add(r.id),r;s=!0;const i={...r,id:is(r.role)};return e.add(i.id),ge(`[chatStore] Re-keyed duplicate message id ${r.id}`),i});return s?n:t},Pa=t=>t.filter(e=>!e.isThreadMessage&&!(e.role==="assistant"&&e.isStreaming)).length,Ra=t=>t.flatMap(s=>[s.imageUrl,s.videoUrl,s.documentUrl]).map(s=>{var n;return((n=s==null?void 0:s.match(/\/api\/files\/([^/]+)\/content/))==null?void 0:n[1])??null}).filter(s=>s!==null),au=(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},iu=(t,e)=>{const s=new Map;e.forEach((r,i)=>{r.databaseMessageId&&s.set(r.databaseMessageId,{message:r,index:i})});const n=new Set;return t.map((r,i)=>{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 p=s.get(l);c=p.message,n.add(p.index)}else{const p=i<e.length?i:0;if(!n.has(p)&&((f=e[p])==null?void 0:f.role)===o)c=e[p],n.add(p);else for(let m=1;m<e.length;m++){const g=(p+m)%e.length;if(!n.has(g)&&e[g].role===o){c=e[g],n.add(g);break}}}const d=r.timestamp?au(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}`:is(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 p=r.metadata,m=p==null?void 0:p.retrieved_docs;Array.isArray(m)&&m.length>0&&(u.supportsThreading=!0)}return u})},ou=(t,e)=>{if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++){const n=t[s],r=e[s];if(n.role!==r.role||n.content!==r.content||(n.databaseMessageId||null)!==(r.databaseMessageId||null)||+n.timestamp!=+r.timestamp)return!1}return!0},Ri=t=>{var r,i,o,l,c,d;const e=((i=(r=t.adapterInfo)==null?void 0:r.adapter_name)==null?void 0:i.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 n=t.audioSettings;return{returnAudio:(n==null?void 0:n.enabled)??s??!!e,ttsVoice:(n==null?void 0:n.ttsVoice)||void 0,language:(n==null?void 0:n.language)||"en-US",audioFormat:n==null?void 0:n.audioFormat}},lu=300;let or=null;const He=t=>{or&&clearTimeout(or),or=setTimeout(()=>{or=null;try{const e=t(),s=e.conversations.map(n=>({...n,messages:n.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"):Oe("[chatStore] Failed to save state to localStorage:",e)}},lu)},cu=32,os=new Map;let Ot=null,ot=null,At=null,es=null;const xn=(t,e)=>{const s=os.get(t);if(s){if(s.timeoutId&&(clearTimeout(s.timeoutId),s.timeoutId=null),s.content){const n=s.content,r=s.messageId;s.content="",e(i=>({conversations:i.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+n}),{...o,messages:l,updatedAt:new Date}})}))}os.delete(t)}},Bt=(t,e,s,n)=>({conversations:t.conversations.map(r=>{var l;if(r.id!==e)return r;const i=[...r.messages],o=n?i.findIndex(c=>c.id===n):i.length-1;return o!==-1&&((l=i[o])==null?void 0:l.role)==="assistant"&&(i[o]={...i[o],...s(i[o])}),{...r,messages:i,updatedAt:new Date}})});let Cr=!1,Nr="";async function Is(){if(Cr&&Nr)return!0;try{const t=await Fe(),e=localStorage.getItem("chat-api-url");e&&e===dn&&localStorage.removeItem("chat-api-url");const s=e&&e!==dn?e:$e(),n=jr(),r=localStorage.getItem("chat-adapter-name")||eu;return t.configureApi(s,n,r),Nr=s,Cr=!0,!0}catch(t){return Oe("Failed to configure API:",t),!1}}async function Da(t,e,s,n,r,i,o,l,c){let d=!1;const u=new AbortController;Ot=u,es=n,ot=null;try{const f=t().conversations.find(y=>y.id===n);if(!f)throw new Error("Conversation not found");if(!f.adapterName)throw new Error("Adapter not configured for this conversation. Please select an adapter first.");At=f.sessionId,f.sessionId&&(await Fe()).configureApi(it(f.apiUrl),f.sessionId,f.adapterName);const p=await Fe(),{returnAudio:m,ttsVoice:g,language:x}=Ri(f);for await(const y of p.streamChat(r,!0,i.length>0?i:void 0,void 0,void 0,void 0,x,m,g,void 0,void 0,o,void 0,c)){if(y.request_id&&!ot&&(ot=y.request_id,$(`[chatStore] >>> CAPTURED request_id for ${l} stop: ${y.request_id}`)),y.text){const v=Ds(y.text);v?(t().appendToLastMessage(v,n,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(v=>Bt(v,n,()=>({audio:y.audio,audioFormat:y.audioFormat||"mp3"}),s)),y.image&&y.done&&(d=!0,e(v=>Bt(v,n,()=>({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(v=>Bt(v,n,()=>({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(v=>Bt(v,n,()=>({document:y.document,documentFormat:y.document_format||"pdf",documentRevisedPrompt:y.document_revised_prompt,documentUrl:y.document_url}),s))),y.done){const v=y.threading;v!=null&&v.supports_threading&&e(A=>({conversations:A.conversations.map(I=>I.id!==n?I:{...I,messages:I.messages.map(S=>S.id===s?{...S,supportsThreading:!0,databaseMessageId:v.message_id}:S),updatedAt:new Date})})),y.assistant_message_id&&e(A=>({conversations:A.conversations.map(I=>I.id!==n?I:{...I,messages:I.messages.map(S=>S.id===s&&!S.databaseMessageId?{...S,databaseMessageId:y.assistant_message_id}:S),updatedAt:new Date})}));break}}!d&&!u.signal.aborted&&t().appendToLastMessage("No response received from the server. Please try again later.",n,s)}catch(f){if(f instanceof Error&&(f.name==="AbortError"||f.message==="Stream cancelled by user"||f.message.includes("aborted")))$(`[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 m="Sorry, there was an error regenerating the response.";f instanceof Error&&(f.message.startsWith("Server error:")?m=f.message.substring(14):(f.message.includes("Could not connect")||f.message.includes("timed out"))&&(m=f.message)),t().appendToLastMessage(m,n,s)}}Ot=null,ot=null,At=null,es=null,xn(n,e),e(f=>{const p=f.conversations.map(g=>g.id===n?{...g,messages:g.messages.map(x=>x.id===s?{...x,isStreaming:!1}:x),updatedAt:new Date}:g),m=p.find(g=>g.id===f.currentConversationId);return{conversations:p,isLoading:m?m.messages.some(g=>g.role==="assistant"&&g.isStreaming):!1}})}const ke=Fi((t,e)=>({conversations:[],currentConversationId:null,isLoading:!1,error:null,sessionId:jr(),getSessionId:()=>e().sessionId,configureApiSettings:async(s,n,r)=>{const i=e(),o=i.conversations.find(c=>c.id===i.currentConversationId),l=(o==null?void 0:o.sessionId)||n||jr();n&&ru(n),t({sessionId:l});try{const c=await Fe();if(!r||!r.trim())throw new Error("Adapter name is required");c.configureApi(s,l,r),Nr=s,Cr=!0;let d;try{const u=new c.ApiClient({apiUrl:s,sessionId:null,adapterName:r});typeof u.getAdapterInfo=="function"&&(d=await u.getAdapterInfo(),$("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=zt();t(p=>({conversations:[...p.conversations,{id:u,sessionId:f,title:_s,messages:[],createdAt:new Date,updatedAt:new Date,adapterName:r,apiUrl:s,adapterInfo:d,adapterLoadError:null}],currentConversationId:u}))}}catch(c){throw ye("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(),n=oe.maxConversations,r=s.conversations.length,i=s.currentConversationId?s.conversations.find(f=>f.id===s.currentConversationId):null;if(n!==null&&r>=n){if(tt()&&!xt()){const p=`You've reached the guest limit of ${n} conversation${n===1?"":"s"}. Sign in to unlock more conversations, or delete conversations to start over.`;throw t({error:p}),st.getState().openLoginPrompt(p),new Error("Guest conversation limit reached")}const f=`Maximum of ${n} conversations reached. Please delete an existing conversation before starting a new one.`;throw t({error:f}),new Error(f)}const o=!!i&&(i.messages.length>0||(((u=i.attachedFiles)==null?void 0:u.length)||0)>0);if(i&&!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=zt(),d={id:l,sessionId:c,title:_s,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:$e(),adapterName:$i(),adapterLoadError:null};return t(f=>({conversations:[d,...f.conversations],currentConversationId:l,sessionId:c,isLoading:!1})),He(e),l},selectConversation:async s=>{const n=e().conversations.find(r=>r.id===s);if(n){const r=n.messages.some(c=>c.role==="assistant"&&c.isStreaming);t({currentConversationId:s,sessionId:n.sessionId,isLoading:r});const i=n.apiUrl||$e(),o=n.adapterName;if(await Is()&&o){const c=await Fe();if(c.configureApi(i,n.sessionId,o),!n.adapterInfo)try{const d=new c.ApiClient({apiUrl:i,sessionId:null,adapterName:o});if(typeof d.getAdapterInfo=="function"){const u=await d.getAdapterInfo();$("Adapter info loaded for conversation:",u),t(f=>({conversations:f.conversations.map(p=>p.id===s?{...p,adapterInfo:u,adapterLoadError:null,updatedAt:new Date}:p)})),He(e)}}catch(d){ge("Failed to load adapter info for conversation:",d)}}e().loadFeedbackForConversation(n.sessionId).catch(()=>{})}He(e)},deleteConversation:async s=>{var i,o;const n=e(),r=n.conversations.find(l=>l.id===s);if($(`🗑️ 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:((i=r==null?void 0:r.attachedFiles)==null?void 0:i.length)||0}),n.currentConversationId===s&&Ut.stop(),r!=null&&r.sessionId)try{if(!await Is())Oe("Failed to configure API for conversation deletion");else{const c=r.apiUrl||$e(),d=r.adapterName;d?$(`Using conversation's adapter for deletion: ${d} (conversation: ${s})`):ge(`Skipping server deletion for conversation ${s}: adapter not configured`);const u=await Fe(),f=new u.ApiClient({apiUrl:c,sessionId:r.sessionId,adapterName:d}),p=((o=r.attachedFiles)==null?void 0:o.map(x=>x.file_id))||[],m=Ra(r.messages||[]),g=[...p,...m];if($(`🔧 Calling deleteConversationWithFiles for session: ${r.sessionId}`),f.deleteConversationWithFiles){const x=await f.deleteConversationWithFiles(r.sessionId,g);$(`✅ Deleted conversation and files for session: ${r.sessionId}`,x),$(` - Deleted ${x.deleted_messages} messages`),$(` - 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){Oe("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)}`,p=zt(),m=Ms(f,p,$e());return He(e),{conversations:[m],currentConversationId:f,sessionId:p}}return He(e),{conversations:c,currentConversationId:d}})},deleteAllConversations:async()=>{const n=[...e().conversations];$(`🗑️ Deleting all conversations (${n.length} total)`),Ut.stop();const r=n.map(async u=>{var f;if(u!=null&&u.sessionId)try{if(!await Is()){Oe("Failed to configure API for conversation deletion");return}const m=u.adapterName;if(!m){$(`Skipping server deletion for conversation ${u.id}: adapter not configured`);return}const g=await Fe(),x=new g.ApiClient({apiUrl:it(u.apiUrl),sessionId:u.sessionId,adapterName:m}),y=[...((f=u.attachedFiles)==null?void 0:f.map(v=>v.file_id))||[],...Ra(u.messages||[])];x.deleteConversationWithFiles?(await x.deleteConversationWithFiles(u.sessionId,y),$(`✅ Deleted conversation ${u.id} and files`)):ge(`deleteConversationWithFiles not available for conversation ${u.id}`)}catch(p){Oe(`Failed to delete conversation ${u.id} from server:`,p)}}),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=zt(),d=Ms(l,c,$e());t({conversations:[d],currentConversationId:l,sessionId:c}),He(e)},deleteThread:async(s,n,r)=>{const i=e().conversations.find(f=>f.id===s);if(!i)throw new Error("Conversation not found");if(!i.adapterName)throw new Error("Adapter not configured for this conversation");const o=i.messages.find(f=>f.id===n);if(!(o!=null&&o.threadInfo)||o.threadInfo.thread_id!==r)throw new Error("Thread not found for this message");const l=it(i.apiUrl||$e()),c=await Fe(),d=new c.ApiClient({apiUrl:l,sessionId:i.sessionId,adapterName:i.adapterName});await new(await St(async()=>{const{ThreadService:f}=await import("./threadService-B9Db3n0J.js");return{ThreadService:f}},[])).ThreadService(d).deleteThread(r),t(f=>({conversations:f.conversations.map(p=>{var x;if(p.id!==s)return p;const m=p.messages.filter(y=>y.isThreadMessage?!(y.threadId===r||y.parentMessageId===n):!0).map(y=>y.id!==n?y:{...y,threadInfo:void 0,supportsThreading:!0}),g=p.currentThreadId===r||p.currentThreadSessionId===((x=o.threadInfo)==null?void 0:x.thread_session_id);return{...p,messages:m,currentThreadId:g?void 0:p.currentThreadId,currentThreadSessionId:g?void 0:p.currentThreadSessionId,updatedAt:new Date}})})),He(e)},sendMessage:async(s,n,r,i,o)=>{var c;let l=null;try{if(e().isLoading){ge("Another request is already in progress");return}if(!await Is())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 p=oe.maxConversations;if(tt()&&!xt()&&p!==null&&e().conversations.length>p){st.getState().openLoginPrompt(`You've reached the guest limit of ${p} conversation${p===1?"":"s"}. Sign in to continue chatting.`),t({isLoading:!1});return}const m=n?n.map(b=>{var k;const E=(k=f==null?void 0:f.attachedFiles)==null?void 0:k.find(N=>N.file_id===b);return E||{file_id:b,filename:"",mime_type:"",file_size:0}}).filter(b=>b!==void 0):[];m.length>0&&m.forEach(b=>{e().addFileToConversation(u,b)});const g=r||null;let x,y=null;if(g){if(x=f.messages.find(b=>{var E;return((E=b.threadInfo)==null?void 0:E.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 v=Pa(f.messages),A=oe.maxMessagesPerConversation;if(A!==null&&v>=A){tt()&&!xt()&&st.getState().openLoginPrompt(`You've reached the guest limit of ${A} messages per conversation. Sign in to send more messages, or delete conversations to start over.`),ge(`[chatStore] Conversation ${u} reached the message limit (${A}).`),t({isLoading:!1});return}const I=oe.maxTotalMessages;if(I!==null&&e().conversations.reduce((E,k)=>E+Pa(k.messages),0)>=I){tt()&&!xt()&&st.getState().openLoginPrompt(`You've reached the guest limit of ${I} total messages. Sign in to continue chatting, or delete conversations to start over.`),ge(`[chatStore] Workspace reached the total message limit (${I}).`),t({isLoading:!1});return}const S={id:is("user"),content:s,role:"user",timestamp:new Date,attachments:m.length>0?m:void 0},C=is("assistant"),L={id:C,content:"",role:"assistant",timestamp:new Date,isStreaming:!0};if(g&&x){S.isThreadMessage=!0,S.threadId=g,S.parentMessageId=x.id,L.isThreadMessage=!0,L.threadId=g,L.parentMessageId=x.id;const b=oe.maxMessagesPerThread;if(b!==null&&f.messages.filter(k=>k.isThreadMessage?(k.threadId===g||k.parentMessageId===x.id)&&!(k.role==="assistant"&&k.isStreaming):!1).length>=b){tt()&&!xt()&&st.getState().openLoginPrompt(`You've reached the guest limit of ${b} messages per thread. Sign in to continue this thread, or delete conversations to start over.`),ge(`[chatStore] Thread ${g} reached the message limit (${b}).`),t({isLoading:!1});return}}t(b=>{const E=b.conversations.find(N=>N.id===u),k=(E==null?void 0:E.messages.filter(N=>N.role==="assistant"&&N.isStreaming))||[];return k.length>0&&ge(`Cleaning up ${k.length} existing streaming messages`),{conversations:b.conversations.map(N=>{if(N.id!==u)return N;const T=N.messages.filter(_=>!(_.role==="assistant"&&_.isStreaming));return{...N,messages:[...T,S,L],updatedAt:new Date,title:N.messages.length===0?s.slice(0,50)+(s.length>50?"...":""):N.title}}),isLoading:!0,error:null}}),l=u;let F=!1;Ut.reset();try{const b=e().conversations.find(R=>R.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 E=it(b.apiUrl),k=b.adapterName,N=y||b.sessionId,T=await Fe();T.configureApi(E,N,k),g&&N!==b.sessionId&&$(`[chatStore] Thread mode: using thread session ${N} (original: ${b.sessionId})`);const{returnAudio:_,ttsVoice:O,language:j,audioFormat:U}=Ri(b);$("[chatStore] Audio settings:",{returnAudio:_,ttsVoice:O,language:j,audioFormat:U});const z=new AbortController;Ot=z,At=N,es=l,ot=null;for await(const R of T.streamChat(s,!0,n,g||void 0,void 0,void 0,j,_,O,void 0,void 0,i,o)){if(R.request_id&&!ot&&(ot=R.request_id,$(`[chatStore] >>> CAPTURED request_id for stop: ${R.request_id}`)),R.audio_chunk&&Ut.addChunk({audio:R.audio_chunk,audioFormat:R.audioFormat||"opus",chunkIndex:R.chunk_index??0}),R.text){const X=Ds(R.text);X?(e().appendToLastMessage(X,l,C),F=!0):R.text.length>100&&ge("[chatStore] Filtered out potential base64 audio data from message content")}if(R.audio&&R.done&&t(X=>Bt(X,l,()=>({audio:R.audio,audioFormat:R.audioFormat||"mp3"}),C)),R.image&&R.done&&(F=!0,t(X=>Bt(X,l,()=>({image:R.image,imageFormat:R.image_format||"png",imageRevisedPrompt:R.image_revised_prompt,imageUrl:R.image_url}),C))),(R.video||R.video_url)&&R.done&&(F=!0,t(X=>Bt(X,l,()=>({video:R.video,videoFormat:R.video_format||"mp4",videoRevisedPrompt:R.video_revised_prompt,videoUrl:R.video_url}),C))),(R.document||R.document_url)&&R.done&&(F=!0,t(X=>Bt(X,l,()=>({document:R.document,documentFormat:R.document_format||"pdf",documentRevisedPrompt:R.document_revised_prompt,documentUrl:R.document_url}),C))),R.done){$("[chatStore] Stream completed, receivedAnyText:",F);const X=R.threading;X!=null&&X.supports_threading&&t(te=>({conversations:te.conversations.map(V=>V.id!==l?V:{...V,messages:V.messages.map(ee=>ee.id===C?{...ee,supportsThreading:!0,databaseMessageId:X.message_id}:ee),updatedAt:new Date})})),R.assistant_message_id&&t(te=>({conversations:te.conversations.map(V=>V.id!==l?V:{...V,messages:V.messages.map(ee=>ee.id===C&&!ee.databaseMessageId?{...ee,databaseMessageId:R.assistant_message_id}:ee),updatedAt:new Date})}));break}}!F&&!z.signal.aborted&&e().appendToLastMessage("No response received from the server. Please try again later.",l,C)}catch(b){if(b instanceof Error&&(b.name==="AbortError"||b.message==="Stream cancelled by user"||b.message.includes("aborted")))$("[chatStore] Stream was cancelled by user"),F=!0;else{Oe("Chat API error:",b);let k="Sorry, there was an error processing your request.";b instanceof Error&&(b.message.startsWith("Server error:")?k=b.message.substring(14):(b.message.includes("Could not connect")||b.message.includes("timed out"))&&(k=b.message)),e().appendToLastMessage(k,l,C)}}Ot=null,ot=null,At=null,es=null,xn(l,t),t(b=>{const E=b.conversations.map(N=>N.id===l?{...N,messages:N.messages.map(T=>T.id===C?{...T,isStreaming:!1}:T),updatedAt:new Date}:N),k=E.find(N=>N.id===b.currentConversationId);return{conversations:E,isLoading:k?k.messages.some(N=>N.role==="assistant"&&N.isStreaming):!1}}),He(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,n)=>{try{const r=e().conversations.find(p=>p.sessionId===n);if(!r)throw new Error("Conversation not found for session");if(!r.adapterName)throw new Error("Adapter not configured for this conversation");const i=r.messages.find(p=>p.id===s);if(!i)throw new Error("Message not found");const o=i.databaseMessageId||s,l=it(r.apiUrl||$e()),c=await Fe(),d=new c.ApiClient({apiUrl:l,sessionId:n,adapterName:r.adapterName}),f=await new(await St(async()=>{const{ThreadService:p}=await import("./threadService-B9Db3n0J.js");return{ThreadService:p}},[])).ThreadService(d).createThread(o,n);t(p=>({conversations:p.conversations.map(m=>m.sessionId!==n?m:{...m,messages:m.messages.map(g=>g.id===s?{...g,threadInfo:f,supportsThreading:!0}:g),currentThreadId:void 0,currentThreadSessionId:void 0})})),$(`[chatStore] Created thread ${f.thread_id} for message ${s}`)}catch(r){throw Oe("Failed to create thread:",r),r}},appendToLastMessage:(s,n,r)=>{const i=Ds(s);if(!i&&s){ge("[chatStore] Filtered out base64 audio data from message content");return}const o=gn(i),l=n||e().currentConversationId;if(!l)return;const c=l,d=os.get(c);d?(d.content+=o,d.messageId=r,d.timeoutId&&clearTimeout(d.timeoutId)):os.set(c,{content:o,timeoutId:null,messageId:r});const u=()=>{const p=os.get(c);if(!p||!p.content)return;const m=p.content,g=p.messageId;p.content="",p.timeoutId=null,t(x=>({conversations:x.conversations.map(y=>{if(y.id!==l)return y;const v=[...y.messages],A=g?v.findIndex(S=>S.id===g):v.length-1,I=A!==-1?v[A]:void 0;return I&&I.role==="assistant"&&I.isStreaming&&(v[A]={...I,content:I.content+m}),{...y,messages:v,updatedAt:new Date}})}))},f=os.get(c);f.timeoutId=setTimeout(u,cu)},regenerateResponse:async(s,n)=>{let r=null;try{if(e().isLoading){ge("Another request is already in progress");return}if(!await Is())throw new Error("API not properly configured");const o=e(),l=o.conversations.find(m=>m.id===o.currentConversationId);if(!l)return;const c=l.messages.findIndex(m=>m.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(m=>m.file_id).filter(m=>typeof m=="string"&&m.length>0),p=is("assistant");if(t(m=>({conversations:m.conversations.map(g=>g.id===m.currentConversationId?{...g,messages:[...g.messages.slice(0,c),{id:p,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,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 Da(e,t,p,r,u.content,f,n,"regenerate",d.databaseMessageId)}catch(i){Oe("Regenerate error:",i),t(o=>({isLoading:!1,...o.currentConversationId===r&&{error:`Failed to regenerate response: ${i instanceof Error?i.message:"Unknown error"}`}}))}},editMessageAndRegenerate:async(s,n,r)=>{let i=null;try{if(e().isLoading){await e().stopStreaming();const x=e().currentConversationId;x&&xn(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=is("assistant"),p=l.messages[c+1],m=(p==null?void 0:p.role)==="assistant",g=m?c+2:c+1;if(t(x=>({conversations:x.conversations.map(y=>y.id===x.currentConversationId?{...y,messages:[...y.messages.slice(0,c),{...d,content:n,updatedAt:new Date},{id:f,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,supportsThreading:m?p.supportsThreading:void 0,databaseMessageId:m?p.databaseMessageId:void 0,threadInfo:m?p.threadInfo:void 0,threadId:m?p.threadId:void 0,parentMessageId:m?p.parentMessageId:void 0,isThreadMessage:m?p.isThreadMessage:void 0},...y.messages.slice(g)],updatedAt:new Date}:y),isLoading:!0,error:null})),i=o.currentConversationId,!i)throw new Error("No conversation selected");await Da(e,t,f,i,n,u,r,"edit-regenerate",m?p.databaseMessageId:void 0),He(e)}catch(o){Oe("Edit & regenerate error:",o),t(l=>({isLoading:!1,...l.currentConversationId===i&&{error:`Failed to regenerate response: ${o instanceof Error?o.message:"Unknown error"}`}}))}},updateConversationTitle:(s,n)=>{t(r=>({conversations:r.conversations.map(i=>i.id===s?{...i,title:n,updatedAt:new Date}:i)})),He(e)},clearError:()=>t({error:null}),cleanupStreamingMessages:()=>{const s=es;t(n=>{let r=!1;return{conversations:n.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(),n=oe.maxConversations;if(!s.currentConversationId)return n===null||s.conversations.length<n;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)?n===null||s.conversations.length<n:!1},getConversationCount:()=>e().conversations.length,addFileToConversation:(s,n)=>{$("[chatStore] addFileToConversation called",{conversationId:s,fileId:n.file_id,filename:n.filename}),t(r=>({conversations:r.conversations.map(i=>i.id===s?{...i,attachedFiles:[...(i.attachedFiles||[]).filter(o=>o.file_id!==n.file_id),n],updatedAt:new Date}:i)})),He(e)},removeFileFromConversation:async(s,n)=>{$("[chatStore] removeFileFromConversation called",{conversationId:s,fileId:n});try{const r=e().conversations.find(i=>i.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(n,void 0,it(r.apiUrl),r.adapterName),$(`[chatStore] Successfully deleted file ${n} from server`)}catch(r){r instanceof Error&&(r.message.includes("404")||r.message.includes("File not found"))?$(`[chatStore] File ${n} was already deleted from server`):ye(`[chatStore] Failed to delete file ${n} from server:`,r)}t(r=>({conversations:r.conversations.map(i=>i.id===s?{...i,attachedFiles:(i.attachedFiles||[]).filter(o=>o.file_id!==n),updatedAt:new Date}:i)})),He(e)},loadConversationFiles:async s=>{try{const n=e().conversations.find(l=>l.id===s);if(!n)return;if(!n.adapterName){$(`Skipping file load for conversation ${s}: adapter not configured`);return}if(new Set((n.attachedFiles||[]).map(l=>l.file_id)).size===0){$(`No files to sync for conversation ${s}`);return}const i=await Os.listFiles(void 0,it(n.apiUrl),n.adapterName),o=new Map(i.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)}}),He(e)}catch(n){Oe(`Failed to load files for conversation ${s}:`,n)}},syncConversationFiles:async s=>{await e().loadConversationFiles(s)},syncConversationsWithBackend:async()=>{try{const s=e();if(s.conversations.length===0)return;const n=await Fe(),r=oe.maxMessagesPerConversation!==null&&oe.maxMessagesPerConversation||void 0;let i=!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;try{const u=new n.ApiClient({apiUrl:it(c.apiUrl),sessionId:c.sessionId,adapterName:c.adapterName});if(typeof u.getConversationHistory!="function")return i||(i=!0,ge("[chatStore] Conversation history endpoint not supported by current API client")),null;const f=await u.getConversationHistory(c.sessionId,r),p=Array.isArray(f==null?void 0:f.messages)?f.messages:[];if(p.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 m=iu(p,c.messages),g=c.messages.filter(y=>y.isThreadMessage),x=Pi(g.length>0?[...m,...g]:m);return ou(c.messages,x)?null:{id:c.id,sessionId:(f==null?void 0:f.session_id)||c.sessionId,messages:x,cleared:!1,updatedAt:((d=m[m.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:_s,updatedAt:f.updatedAt,adapterLoadError:null}:{...u,sessionId:f.sessionId||u.sessionId,messages:f.messages,updatedAt:f.updatedAt,adapterLoadError:null}:u}),currentConversationId:c.currentConversationId}}),He(e)}catch(s){ge("Failed to synchronize conversations with backend:",s)}},stopStreaming:async()=>{var n;if(!e().isLoading){$("[chatStore] stopStreaming called but not currently loading");return}if($("[chatStore] Stopping stream...",{hasAbortController:!!Ot,requestId:ot,sessionId:At}),Ot&&Ot.abort(),ot&&At)try{const r=await Fe(),i=await((n=r.stopChat)==null?void 0:n.call(r,At,ot));$(`[chatStore] Server-side cancellation result: ${i}`)}catch(r){ge("[chatStore] Failed to cancel server-side stream:",r)}else ge(`[chatStore] Cannot call stopChat - missing IDs: requestId=${ot}, sessionId=${At}`);const s=es||e().currentConversationId;t(s?r=>({conversations:r.conversations.map(i=>i.id!==s?i:{...i,messages:i.messages.map(o=>o.isStreaming?{...o,isStreaming:!1}:o),updatedAt:new Date}),isLoading:!1}):{isLoading:!1}),Ot=null,ot=null,At=null,es=null,$("[chatStore] Stream stopped successfully")},clearCurrentConversationAdapter:()=>{const s=e().currentConversationId;s&&(t(n=>({conversations:n.conversations.map(r=>r.id===s?{...r,adapterName:void 0,adapterInfo:void 0,adapterLoadError:null}:r)})),He(e))},submitFeedback:async(s,n)=>{const r=e(),i=r.conversations.find(l=>l.id===r.currentConversationId);if(!i)return;const o=i.messages.find(l=>l.id===s);if(!(o!=null&&o.databaseMessageId)){ge("[chatStore] Cannot submit feedback: no databaseMessageId on message");return}if(i.adapterName)try{const l=await Fe(),u=(await new l.ApiClient({apiUrl:it(i.apiUrl||$e()),sessionId:i.sessionId,adapterName:i.adapterName}).submitFeedback(o.databaseMessageId,i.sessionId,n)).feedback_type;t(f=>({conversations:f.conversations.map(p=>p.id!==r.currentConversationId?p:{...p,messages:p.messages.map(m=>m.id===s?{...m,feedback:u}:m),updatedAt:new Date})})),He(e)}catch(l){ye("[chatStore] Failed to submit feedback:",l)}},loadFeedbackForConversation:async s=>{var i;const r=e().conversations.find(o=>o.sessionId===s);if(r!=null&&r.adapterName)try{const o=await Fe(),l=new o.ApiClient({apiUrl:it(r.apiUrl||$e()),sessionId:r.sessionId,adapterName:r.adapterName}),c=new Set([s]);for(const f of r.messages)(i=f.threadInfo)!=null&&i.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 p of f.feedbacks)u.set(p.message_id,p.feedback_type);if(u.size===0)return;t(f=>({conversations:f.conversations.map(p=>p.sessionId!==s?p:{...p,messages:p.messages.map(m=>m.databaseMessageId&&u.has(m.databaseMessageId)?{...m,feedback:u.get(m.databaseMessageId)}:m)})}))}catch(o){ye("[chatStore] Failed to load feedback:",o)}}})),du=async()=>{var c;const t=localStorage.getItem("chat-state"),e=$e(),s=!!localStorage.getItem("chat-api-url");let n=jr(),r=!1;if(t)try{const d=JSON.parse(t),u=m=>{if(m instanceof Date)return m;const g=m?new Date(m):new Date;return Number.isNaN(g.getTime())?new Date:g},p=(Array.isArray(d.conversations)?d.conversations:[]).map(m=>{const x=(Array.isArray(m.messages)?m.messages:[]).filter(I=>!(I.role==="assistant"&&I.isStreaming)).map(I=>({...I,timestamp:u(I.timestamp),isStreaming:!1})),y=Pi(x),v={id:m.id,sessionId:m.sessionId||zt(),title:su(m.title),messages:y,createdAt:u(m.createdAt),updatedAt:u(m.updatedAt),attachedFiles:m.attachedFiles||[],adapterName:m.adapterName,apiUrl:m.apiUrl,adapterInfo:m.adapterInfo,adapterLoadError:m.adapterLoadError||null,audioSettings:m.audioSettings,currentThreadId:void 0,currentThreadSessionId:void 0},A=v.messages.length===0&&!v.adapterName;return{...v,apiUrl:A&&!s?e:it(m.apiUrl)}});if(r=p.length>0,d.currentConversationId&&p.length>0){const m=p.find(g=>g.id===d.currentConversationId);m!=null&&m.sessionId&&(n=m.sessionId)}if(p.length===0){const m=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,g=zt(),x=Ms(m,g,$e());ke.setState({conversations:[x],currentConversationId:m,sessionId:g}),n=g}else ke.setState({conversations:p,currentConversationId:d.currentConversationId||((c=p[0])==null?void 0:c.id)||null,sessionId:n}),!d.currentConversationId&&p.length>0&&(ke.setState({currentConversationId:p[0].id,sessionId:p[0].sessionId||n}),n=p[0].sessionId||n);$("📋 Loaded conversations:",ke.getState().conversations.map(m=>{var g;return{id:m.id,title:m.title,sessionId:m.sessionId,messageCount:((g=m.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=zt(),p=Ms(u,f,$e());ke.setState({conversations:[p],currentConversationId:u,sessionId:f}),n=f}else{const d=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,u=zt(),f=Ms(d,u,$e());ke.setState({conversations:[f],currentConversationId:d,sessionId:u}),n=u}localStorage.removeItem("chat-api-key");const i=ke.getState(),o=i.currentConversationId?i.conversations.find(d=>d.id===i.currentConversationId):null,l=r&&(o!=null&&o.apiUrl)?o.apiUrl:$e();try{const d=await Fe(),u=o==null?void 0:o.adapterName;if(!u)$("No adapter selected yet. Waiting for user selection before configuring API.");else if(d.configureApi(l,n,u),Nr=l,Cr=!0,!(o!=null&&o.adapterInfo))try{const f=new d.ApiClient({apiUrl:l,sessionId:null,adapterName:u});if(typeof f.getAdapterInfo=="function"){const p=await f.getAdapterInfo();$("Adapter info loaded for existing adapter:",p);const m=ke.getState();m.currentConversationId&&(ke.setState({conversations:m.conversations.map(g=>g.id===m.currentConversationId?{...g,adapterInfo:p,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){ge("Failed to load adapter info for existing adapter:",f)}}catch(d){Oe("Failed to initialize API:",d)}try{await ke.getState().syncConversationsWithBackend()}catch(d){ge("Conversation history sync skipped:",d)}};typeof window<"u"&&du();function uu(t){return t.includes("image")?a.jsx(Mc,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):t.includes("video")||t.includes("audio")?a.jsx(rd,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):a.jsx(Ln,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"})}function fu(t){return t.replace(/-/g," ")}function Di({skills:t,isLoading:e,selectedSkill:s,activeSkillName:n,query:r="",onSelect:i,onActiveSkillChange:o}){const{t:l}=Ee(),c=vt.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 vt.useEffect(()=>{var p;const f=(p=c.current)==null?void 0:p.querySelector('[data-active="true"]');f==null||f.scrollIntoView({block:"nearest"})},[n,u.length]),!e&&t.length===0?a.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:a.jsx("p",{className:"px-4 py-3 text-sm text-gray-500 dark:text-[#bfc2cd]",children:l("skillPicker.noSkillsAvailable")})}):a.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?a.jsx("div",{className:"px-4 py-3.5",children:a.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-[#bfc2cd]",children:[a.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?a.jsx("div",{className:"px-4 py-3.5",children:a.jsx("p",{className:"text-sm text-gray-500 dark:text-[#bfc2cd]",children:d?l("skillPicker.noMatchingSkills",{query:r}):l("skillPicker.noMatchingSkillsGeneric")})}):a.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,p)=>{const m=(s==null?void 0:s.name)===f.name,g=n===f.name||!n&&(m||!s&&p===0);return a.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:()=>i(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:[a.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:uu(f.name)}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"flex min-w-0 items-center gap-2",children:a.jsx("span",{className:"truncate text-sm font-medium capitalize leading-5 text-current",children:fu(f.name)})}),f.description&&a.jsx("p",{className:"mt-0.5 line-clamp-2 text-xs leading-5 text-gray-500 dark:text-[#bfc2cd]",children:f.description})]}),m&&a.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:a.jsx($s,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]},f.name)})})})}function Oi({availableModels:t,defaultModel:e,selectedModel:s,onSelect:n,wrapperClassName:r="relative hidden md:block",maxWidthClass:i="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"),p=l??u("modelPicker.selectModel"),[m,g]=h.useState(!1),[x,y]=h.useState(""),[v,A]=h.useState(null),I=h.useRef(null),S=h.useRef(null),C=h.useRef(null),L=h.useRef(null),F=s??e,b=x.trim()?t.filter(_=>_.name.toLowerCase().includes(x.trim().toLowerCase())):t,E=h.useCallback(()=>{if(!S.current)return;const _=S.current.getBoundingClientRect();A({bottom:window.innerHeight-_.top+8,right:window.innerWidth-_.right})},[]),k=h.useCallback(()=>{g(!1),y("")},[]),N=()=>{if(m){k();return}E(),g(!0)};if(h.useEffect(()=>{if(!m)return;const _=setTimeout(()=>{var z;return(z=C.current)==null?void 0:z.focus()},10),O=z=>{var V,ee;const R=z.target,X=((V=I.current)==null?void 0:V.contains(R))??!1,te=((ee=L.current)==null?void 0:ee.contains(R))??!1;!X&&!te&&k()},j=z=>{var R;z.key==="Escape"&&(z.preventDefault(),k(),(R=S.current)==null||R.focus())},U=new ResizeObserver(E);return S.current&&U.observe(S.current),window.addEventListener("resize",E,{passive:!0}),document.addEventListener("scroll",E,{capture:!0,passive:!0}),document.addEventListener("pointerdown",O),document.addEventListener("keydown",j),()=>{clearTimeout(_),U.disconnect(),window.removeEventListener("resize",E),document.removeEventListener("scroll",E,{capture:!0}),document.removeEventListener("pointerdown",O),document.removeEventListener("keydown",j)}},[k,m,E]),!e&&t.length===0)return null;const T=m&&v&&typeof document<"u"?Ir.createPortal(a.jsxs("div",{ref:L,style:{position:"fixed",bottom:v.bottom,right:v.right,width:288,zIndex:9999},className:"rounded-xl border border-gray-200 bg-white shadow-xl dark:border-[#2f303d] dark:bg-[#111111]",children:[a.jsx("div",{className:"p-2 border-b border-gray-100 dark:border-[#222222]",children:a.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-gray-50 px-3 py-1.5 dark:bg-[#1a1a1a]",children:[a.jsx(In,{className:"h-3.5 w-3.5 flex-shrink-0 text-gray-400 dark:text-[#6b6f7a]","aria-hidden":"true"}),a.jsx("input",{ref:C,type:"text",value:x,onChange:_=>y(_.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")})]})}),a.jsx("div",{role:"listbox","aria-label":p,className:"max-h-60 overflow-y-auto py-1",children:b.length===0?a.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(_=>{const O=F===_.name;return a.jsxs("button",{role:"option","aria-selected":O,type:"button",onClick:()=>{var j;n(_.name),k(),(j=S.current)==null||j.focus()},className:`flex w-full items-center gap-2.5 px-3 py-2 text-left text-xs transition-colors ${O?"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:[a.jsx("span",{className:`flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center rounded-full border ${O?"border-blue-500 bg-blue-500 dark:border-blue-400 dark:bg-blue-400":"border-gray-300 dark:border-[#5a5b65]"}`,children:O&&a.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-white"})}),a.jsx("span",{className:"truncate font-medium normal-case tracking-normal",children:_.name})]},_.name)})}),t.length>8&&a.jsx("div",{className:"border-t border-gray-100 px-3 py-1.5 dark:border-[#222222]",children:a.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 a.jsx("div",{ref:I,className:r,children:t.length>1?a.jsxs(a.Fragment,{children:[a.jsxs("button",{ref:S,type:"button",onClick:N,className:`inline-flex min-w-[100px] ${i} 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":m,title:f,children:[a.jsx("span",{className:"truncate flex-1",children:F}),a.jsx(us,{className:`h-3.5 w-3.5 flex-shrink-0 text-gray-400 transition-transform duration-150 dark:text-[#6b6f7a] ${m?"rotate-180":""}`,"aria-hidden":"true"})]}),T]}):a.jsx("div",{className:`inline-flex min-w-[100px] ${i} 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:F??void 0,children:a.jsx("span",{className:"truncate",children:F})})})}const hu=[],mu=(t="png")=>{const e=t.toLowerCase().replace(/^image\//,"");return e==="jpg"?"image/jpeg":`image/${e||"png"}`},pu=(t,e)=>{const s=atob(t),n=new Uint8Array(s.length);for(let r=0;r<s.length;r+=1)n[r]=s.charCodeAt(r);return new Blob([n],{type:e})},gu=async t=>{const e=URL.createObjectURL(t);try{const s=new Image;s.decoding="async";const n=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 n;const r=document.createElement("canvas");r.width=s.naturalWidth,r.height=s.naturalHeight;const i=r.getContext("2d");if(!i)throw new Error("Could not create canvas context for image clipboard copy");return i.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)}},xu=async(t,e)=>{const s=mu(t.imageFormat);if(t.image)return pu(t.image,s);if(!t.imageUrl)return null;const n=await fetch(t.imageUrl,{headers:e?{"X-Adapter-Name":e}:{}});if(!n.ok)throw new Error(`Could not fetch generated image for clipboard copy: ${n.status}`);const r=await n.blob();return r.type?r:new Blob([r],{type:s})},bu=t=>t.imageUrl?new URL(t.imageUrl,window.location.origin).toString():t.imageRevisedPrompt||t.content;function Oa({size:t="md"}){const e=t==="sm"?"h-2 w-2":"h-2.5 w-2.5";return a.jsx("div",{className:"flex items-center gap-1.5 py-1",children:[0,150,300].map(s=>a.jsx("span",{className:`inline-block ${e} animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]`,style:{animationDelay:`${s}ms`}},s))})}function yu({reply:t}){const{t:e}=Ee(),[s,n]=h.useState(!1),[r,i]=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;n(!0);try{await l(t.id,d),u?(i(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{i(!1),o.current=null},2e3)):i(!1)}catch(f){ye("Failed to submit thread reply feedback:",f)}finally{n(!1)}};return a.jsxs("div",{className:"flex items-center gap-0.5 mt-0.5",children:[a.jsx("button",{onClick:()=>c("up"),disabled:s,className:`rounded-md p-1.5 hover:bg-gray-100 dark:hover:bg-[#3c3f4a] transition-colors ${s?"opacity-50 cursor-not-allowed":""} ${t.feedback==="up"?"text-green-600 dark:text-green-400":"text-gray-400 dark:text-[#6e6e80] hover:text-gray-700 dark:hover:text-[#ececf1]"}`,title:e("message.feedback.good"),"aria-label":e("message.feedback.good"),children:a.jsx(Ci,{className:"h-3.5 w-3.5"})}),a.jsx("button",{onClick:()=>c("down"),disabled:s,className:`rounded-md p-1.5 hover:bg-gray-100 dark:hover:bg-[#3c3f4a] transition-colors ${s?"opacity-50 cursor-not-allowed":""} ${t.feedback==="down"?"text-red-600 dark:text-red-400":"text-gray-400 dark:text-[#6e6e80] hover:text-gray-700 dark:hover:text-[#ececf1]"}`,title:e("message.feedback.poor"),"aria-label":e("message.feedback.poor"),children:a.jsx(ji,{className:"h-3.5 w-3.5"})}),r&&a.jsxs("span",{className:"ml-1 inline-flex items-center gap-1 rounded-md bg-emerald-500/10 px-1.5 py-0.5 text-[10px] font-medium text-emerald-700 animate-fadeIn dark:bg-emerald-500/15 dark:text-emerald-300",children:[a.jsx($s,{className:"h-3 w-3"}),e("message.feedback.thanks")]})]})}function wu({message:t,onRegenerate:e,onEdit:s,onStartThread:n,onClearThread:r,onSendThreadMessage:i,threadMessages:o,sessionId:l,isThreadSendDisabled:c,availableModels:d=[],defaultModel:u=null,selectedModel:f=null}){var ys,ns,ws;const{t:p}=Ee(),[m,g]=h.useState(!1),[x,y]=h.useState(t.content||""),[v,A]=h.useState(!1),I=h.useRef(null),[S,C]=h.useState(!1),[L,F]=h.useState(!1),[b,E]=h.useState(!1),[k,N]=h.useState(""),[T,_]=h.useState(!1),[O,j]=h.useState(!1),[U,z]=h.useState(!1),[R,X]=h.useState(0),[te,V]=h.useState(!1),[ee,me]=h.useState(!1),[D,re]=h.useState(()=>f??u),q=h.useRef(f),Q=h.useRef(((ys=t.threadInfo)==null?void 0:ys.thread_id)||null),se=h.useRef(null),fe=h.useRef(null),Ne=h.useRef(null),B=h.useRef(!1),W=h.useRef(0),J=h.useRef(""),we=h.useRef(!1),ne=h.useRef(!0),K=h.useRef(!1),le=h.useRef(null),ve=h.useRef(null),ue=t.role==="assistant",Pe=o??hu,_e=Pe.filter(M=>!(M.role==="assistant"&&M.isStreaming)).length,H=Pe.some(M=>M.isStreaming),ce=fs(),Ue=tt()&&!ce,xe=ke(M=>M.conversations.find(be=>be.id===M.currentConversationId)),Ae=!!((t.image||t.imageUrl)&&ue&&!t.isStreaming),Lt=!!((t.video||t.videoUrl)&&ue&&!t.isStreaming),ze=p(Ae?"message.copyImageLabel":"message.copyLabel"),Qe=Xl(),hs=oe.maxMessageLength,ut=oe.maxMessagesPerThread,Et=ut!==null&&_e>=ut,Ht=Et?Ue?p("message.thread.limitReachedGuest",{count:ut}):p("message.thread.limitReachedUser",{count:ut}):null,{theme:Je,isDark:Tt}=ds(),Vt=p("message.thread.placeholder"),Se=`thread-input-${t.id}`,{skills:Ze,isLoading:ft,selectedSkill:de,selectSkill:Ce,clearSkill:Me}=Mi({adapterName:xe==null?void 0:xe.adapterName,enabled:Qe&&!!t.threadInfo,selectionScopeKey:((ns=t.threadInfo)==null?void 0:ns.thread_id)||t.id}),Z=k.startsWith("/")?k.slice(1):"",ht=Z.toLowerCase().replace(/-/g," "),qe=ht?Ze.filter(M=>M.name.replace(/-/g," ").toLowerCase().includes(ht)||M.description.toLowerCase().includes(ht)):Ze,ms=qe.length>0?Math.min(R,qe.length-1):0,rt=qe[ms]??null,ps=(rt==null?void 0:rt.name.replace(/-/g," "))??"",Us=U&&rt&&k.startsWith("/")&&ps.toLowerCase().startsWith(Z.toLowerCase())&&ps.length>Z.length?ps.slice(Z.length):null,ss=Je.mode==="dark"?"dark":Je.mode==="light"?"light":"",et=Tt?"dark":"light",zs=h.useMemo(()=>["message-markdown w-full min-w-0","prose prose-slate dark:prose-invert max-w-none",ss].filter(Boolean).join(" "),[ss]),Bs=h.useMemo(()=>["message-markdown w-full min-w-0","prose dark:prose-invert max-w-none",ss].filter(Boolean).join(" "),[ss]),rs=ue?zs:Bs,qt=`${zs} text-sm leading-6`,gs=`${Bs} text-sm leading-6`;h.useEffect(()=>{var M,be;!Q.current&&((M=t.threadInfo)!=null&&M.thread_id)&&_(!0),Q.current=((be=t.threadInfo)==null?void 0:be.thread_id)||null},[(ws=t.threadInfo)==null?void 0:ws.thread_id]),h.useEffect(()=>{t.threadInfo||setTimeout(()=>{N(""),_(!1),j(!1),z(!1),Me()},0)},[t.threadInfo,Me]),h.useEffect(()=>{_e>0&&setTimeout(()=>{_(!0)},0)},[_e]),h.useEffect(()=>()=>{le.current&&clearTimeout(le.current),ve.current&&clearTimeout(ve.current)},[]),h.useEffect(()=>{if(!m||!I.current)return;const M=I.current;M.focus(),M.setSelectionRange(M.value.length,M.value.length)},[m]),h.useEffect(()=>{if(!m||!I.current)return;const M=I.current;M.style.height="auto",M.style.height=`${M.scrollHeight}px`},[m,x]);const _t=h.useCallback(()=>{const M=x.trim();if(!M||M===t.content){g(!1);return}s==null||s(t.id,M),g(!1)},[x,t.content,t.id,s]),lt=h.useCallback(()=>{requestAnimationFrame(()=>{Ne.current&&(Ne.current.scrollTop=Ne.current.scrollHeight)})},[]);h.useEffect(()=>{if(!T)return;const M=Pe.length,be=M>W.current,G=Pe[Pe.length-1],je=(G==null?void 0:G.content)||"",ct=je!==J.current,We=(G==null?void 0:G.isStreaming)??!1,Xt=we.current&&!We;be||We&&ct||Xt?(lt(),ne.current=!0):ne.current&&ct&&lt(),W.current=M,J.current=je,we.current=We},[T,Pe,lt]),h.useEffect(()=>{T&&(lt(),ne.current=!0)},[T,lt]);const Mt=ue?"message-bubble message-bubble-assistant min-w-0 break-words leading-relaxed text-[#353740] dark:text-[#ececf1]":"message-bubble message-bubble-user relative inline-block min-w-0 break-words leading-relaxed rounded-[1.75rem] bg-[#f4f4f4] px-4 py-3 pr-10 text-[#111827] dark:bg-[#303030] dark:text-[#f5f5f5]",$r="border-gray-200 bg-white/80 dark:border-[#3b3c49] dark:bg-white/5",xs=h.useCallback(()=>{C(!0),le.current&&clearTimeout(le.current),le.current=setTimeout(()=>{C(!1),le.current=null},2e3)},[]),Wt=async()=>{try{if(Ae){if("ClipboardItem"in window&&navigator.clipboard.write)try{const be=(xe==null?void 0:xe.adapterName)||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),G=await xu(t,be);if(G){const je=G.type==="image/png"?G:await gu(G);await navigator.clipboard.write([new ClipboardItem({[je.type||"image/png"]:je})]),xs();return}}catch(be){ye("Failed to copy generated image, falling back to text:",be)}const M=bu(t);if(M){await navigator.clipboard.writeText(M),xs();return}return}await navigator.clipboard.writeText(t.content),xs()}catch(M){ye(Ae?"Failed to copy generated image:":"Failed to copy text:",M)}},Pr=ke(M=>M.submitFeedback),Be=async M=>{if(!t.databaseMessageId||L)return;const be=t.feedback!==M;F(!0);try{await Pr(t.id,M),be?(E(!0),ve.current&&clearTimeout(ve.current),ve.current=setTimeout(()=>{E(!1),ve.current=null},2e3)):E(!1)}catch(G){ye("Failed to submit feedback:",G)}finally{F(!1)}},bs=async()=>{if(!i||!t.threadInfo||Et)return;const M=k.trim();if(!M)return;const be=k,G=de,je=de==null?void 0:de.name;N(""),j(!0),z(!1),je&&Me();try{await i(t.threadInfo.thread_id,t.id,M,je,D??u??void 0),setTimeout(()=>{se.current&&se.current.focus()},100)}catch(ct){ye("Failed to send thread message:",ct),N(be),G&&Ce(G),setTimeout(()=>{se.current&&se.current.focus()},100)}finally{j(!1)}},Kt=h.useCallback(M=>{var be;Ce(M),z(!1),N(""),X(0),(be=se.current)==null||be.focus()},[Ce]),Hs=h.useCallback(()=>{var M;z(!1),N(""),X(0),(M=se.current)==null||M.focus()},[]),Ft=h.useCallback(()=>{var M;N("/"),z(!0),X(0),(M=se.current)==null||M.focus()},[]),mt=M=>{if(U){if(M.key==="ArrowDown"){M.preventDefault(),X(be=>qe.length===0?0:(be+1)%qe.length);return}if(M.key==="ArrowUp"){M.preventDefault(),X(be=>qe.length===0?0:(be-1+qe.length)%qe.length);return}if(M.key==="Home"){M.preventDefault(),X(0);return}if(M.key==="End"){M.preventDefault(),X(Math.max(qe.length-1,0));return}if((M.key==="Enter"&&!M.shiftKey||M.key==="Tab")&&rt){M.preventDefault(),Kt(rt);return}if(M.key==="Escape"){M.preventDefault(),Hs();return}}M.key==="Enter"&&!M.shiftKey&&(M.preventDefault(),bs())},Gt=!t.threadInfo||!i||c||H||O||Et,Rr=!!t.threadInfo&&!!r&&_e>0&&!H&&!O&&!c,Dr=async()=>{if(!(!t.threadInfo||!r)){me(!0);try{await r(t.id,t.threadInfo.thread_id),V(!1),_(!1),N("")}catch(M){ye("Failed to clear thread:",M)}finally{me(!1)}}};h.useEffect(()=>{q.current=f},[f]),h.useEffect(()=>{re(q.current??u)},[u]),h.useEffect(()=>{if(!T||Gt){K.current=O;return}const M=se.current;if(!M){K.current=O;return}if(!(B.current||K.current)){K.current=O;return}const G=requestAnimationFrame(()=>{var ct;B.current&&((ct=fe.current)==null||ct.scrollIntoView({behavior:"auto",block:"nearest",inline:"nearest"})),M.focus();const je=M.value.length;M.setSelectionRange(je,je),B.current=!1,K.current=O});return()=>{cancelAnimationFrame(G),K.current=O}},[T,Gt,O]),h.useEffect(()=>{if(se.current){const be=se.current;be.style.height="auto";const G=be.scrollHeight;be.style.height=`${Math.min(G,120)}px`,be.style.overflowY=G>120?"auto":"hidden"}},[k]);const bt=h.useMemo(()=>{if(t.isStreaming&&(!t.content||t.content==="…"))return a.jsx("div",{className:rs,children:a.jsx(Oa,{})});const M=t.isStreaming&&ue?" streaming-cursor":"";return a.jsx("div",{className:M||void 0,children:a.jsx(It,{content:gn(Ds(t.content||"")),className:rs,syntaxTheme:et})})},[rs,t.content,t.isStreaming,ue,et]),Vs=h.useMemo(()=>{const M=G=>G instanceof Date?G.getTime():new Date(G).getTime();return[...Pe].sort((G,je)=>M(G.timestamp)-M(je.timestamp)).map(G=>{const je=G.role==="assistant",ct=je?qt:gs,We=G.isStreaming&&je?" streaming-cursor":"",Xt=G.isStreaming&&(!G.content||G.content==="…")?a.jsx("div",{className:ct,children:a.jsx(Oa,{size:"sm"})}):a.jsx("div",{className:We||void 0,children:a.jsx(It,{content:gn(Ds(G.content||"")),className:ct,syntaxTheme:et})});return a.jsx("div",{className:`min-w-0 flex ${je?"justify-start":"justify-end"}`,children:a.jsxs("div",{className:je?"min-w-0 w-full max-w-full":"min-w-0 max-w-[85%]",children:[a.jsxs("div",{className:je?"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-[#303030] dark:text-[#f5f5f5]",children:[Xt,G.audio&&je&&!G.isStreaming&&a.jsx(Ca,{audio:G.audio,audioFormat:G.audioFormat,autoPlay:!1}),(G.image||G.imageUrl)&&je&&!G.isStreaming&&a.jsx(Na,{image:G.image,imageUrl:G.imageUrl,imageFormat:G.imageFormat,revisedPrompt:G.imageRevisedPrompt}),(G.video||G.videoUrl)&&je&&!G.isStreaming&&a.jsx(Aa,{video:G.video,videoUrl:G.videoUrl,videoFormat:G.videoFormat,revisedPrompt:G.videoRevisedPrompt,adapterName:xe==null?void 0:xe.adapterName}),(G.document||G.documentUrl)&&je&&!G.isStreaming&&a.jsx(Ta,{document:G.document,documentUrl:G.documentUrl,documentFormat:G.documentFormat,revisedPrompt:G.documentRevisedPrompt,adapterName:xe==null?void 0:xe.adapterName})]}),je&&!G.isStreaming&&pa()&&a.jsx(yu,{reply:G})]})},G.id)})},[xe==null?void 0:xe.adapterName,et,qt,Pe,gs]);return a.jsxs("div",{className:"group animate-fadeIn min-w-0 w-full px-0",children:[a.jsxs("div",{className:"min-w-0 space-y-1",children:[a.jsxs("div",{className:Mt,children:[m?a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx("textarea",{ref:I,className:"w-full resize-none overflow-hidden bg-transparent outline-none text-[#111827] dark:text-[#f5f5f5] leading-relaxed",value:x,onChange:M=>y(M.target.value),onCompositionStart:()=>A(!0),onCompositionEnd:()=>A(!1),onKeyDown:M=>{M.key==="Enter"&&!M.shiftKey&&!v&&(M.preventDefault(),M.stopPropagation(),_t()),M.key==="Escape"&&(M.stopPropagation(),g(!1),y(t.content||""))},maxLength:oe.maxMessageLength,rows:1,style:{minHeight:"24px"}}),a.jsxs("div",{className:"flex items-center justify-between gap-2 mt-1",children:[a.jsx("span",{className:"text-xs text-gray-400 dark:text-[#6e6e80]",children:p("message.edit.willRegenerateHint")}),a.jsxs("div",{className:"flex gap-2",children:[a.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:p("common.cancel")}),a.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:[a.jsx(hn,{className:"w-3.5 h-3.5"}),p("common.send")]})]})]})]}):bt,t.attachments&&t.attachments.length>0&&a.jsx("div",{className:"mt-3 space-y-2",children:t.attachments.map(M=>a.jsxs("div",{className:`flex items-center gap-3 rounded-xl border p-3 ${$r}`,children:[a.jsx(_c,{className:"h-4 w-4 text-gray-500 dark:text-[#bfc2cd]"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"truncate text-sm font-medium text-[#353740] dark:text-[#ececf1]",children:M.filename}),a.jsxs("p",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:[(M.file_size/1024).toFixed(1)," KB"]})]})]},M.file_id))}),t.audio&&ue&&!t.isStreaming&&a.jsx(Ca,{audio:t.audio,audioFormat:t.audioFormat,autoPlay:!1}),(t.image||t.imageUrl)&&ue&&!t.isStreaming&&a.jsx(Na,{image:t.image,imageUrl:t.imageUrl,imageFormat:t.imageFormat,revisedPrompt:t.imageRevisedPrompt}),(t.video||t.videoUrl)&&ue&&!t.isStreaming&&a.jsx(Aa,{video:t.video,videoUrl:t.videoUrl,videoFormat:t.videoFormat,revisedPrompt:t.videoRevisedPrompt,adapterName:xe==null?void 0:xe.adapterName}),(t.document||t.documentUrl)&&ue&&!t.isStreaming&&a.jsx(Ta,{document:t.document,documentUrl:t.documentUrl,documentFormat:t.documentFormat,revisedPrompt:t.documentRevisedPrompt,adapterName:xe==null?void 0:xe.adapterName}),!ue&&s&&!m&&a.jsx("button",{onClick:()=>{y(t.content||""),g(!0)},className:"absolute top-1/2 -translate-y-1/2 right-2 rounded-md p-1 text-gray-600 hover:text-gray-900 dark:text-gray-200 dark:hover:text-white transition-colors",title:p("message.editAriaLabel"),"aria-label":p("message.editAriaLabel"),children:a.jsx(Si,{className:"h-3.5 w-3.5"})})]}),ue&&!t.isStreaming&&a.jsxs("div",{className:"py-1 flex flex-nowrap items-center gap-0.5 text-gray-400 dark:text-[#8e8ea0] transition-opacity",children:[!Lt&&a.jsx("button",{onClick:Wt,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:S?a.jsx($s,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):a.jsx(Ac,{className:"h-4 w-4"})}),pa()&&a.jsxs("div",{className:"relative flex items-center gap-0.5",children:[a.jsx("button",{onClick:()=>Be("up"),disabled:L,className:`rounded-md p-1.5 transition-colors ${L?"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:p("message.feedback.good"),"aria-label":p("message.feedback.good"),children:a.jsx(Ci,{className:"h-4 w-4"})}),a.jsx("button",{onClick:()=>Be("down"),disabled:L,className:`rounded-md p-1.5 transition-colors ${L?"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:p("message.feedback.poor"),"aria-label":p("message.feedback.poor"),children:a.jsx(ji,{className:"h-4 w-4"})}),b&&a.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:[a.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"}),a.jsxs("div",{className:"relative flex items-center gap-1.5",children:[a.jsx($s,{className:"h-3.5 w-3.5"}),a.jsx("span",{children:p("message.feedback.thanks")})]})]})]}),e&&a.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:p("message.regenerateTitle"),"aria-label":p("message.regenerateAriaLabel"),children:a.jsx(Qc,{className:"h-4 w-4"})}),Qe&&t.supportsThreading&&!t.threadInfo&&n&&l&&a.jsxs("button",{type:"button",onClick:()=>{B.current=!0,_(!0),n(t.id,l)},className:"ml-1 inline-flex items-center gap-1.5 rounded-full border border-blue-200 bg-blue-50 px-2.5 py-1.5 text-xs text-blue-700 shadow-sm transition-all hover:border-blue-300 hover:bg-blue-100 hover:text-blue-800 hover:shadow-md dark:border-blue-500/30 dark:bg-blue-500/10 dark:text-blue-200 dark:hover:border-blue-400/50 dark:hover:bg-blue-500/20 dark:hover:text-blue-100 animate-follow-up-enter whitespace-nowrap",title:p("message.thread.continueDiscussionTitle"),"aria-label":p("message.thread.continueDiscussionAriaLabel"),children:[a.jsx(ba,{className:"h-3.5 w-3.5 shrink-0"}),a.jsx("span",{children:p("message.thread.continueLabel")})]}),Qe&&t.threadInfo&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"w-px h-4 shrink-0 bg-gray-200 dark:bg-[#3c3f4a] mx-1"}),a.jsxs("button",{onClick:()=>_(M=>!M),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:[a.jsx(ba,{className:"h-4 w-4"}),a.jsx("span",{className:"truncate",children:p("message.thread.replyCount",{count:_e})}),T?a.jsx(wr,{className:"h-3 w-3"}):a.jsx(us,{className:"h-3 w-3"})]}),Rr&&a.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:p("message.thread.clearTitle"),"aria-label":p("message.thread.clearAriaLabel"),children:p("common.clear")})]})]}),Qe&&t.threadInfo&&T&&a.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:[a.jsx("div",{ref:Ne,className:"thread-replies-scroll mt-2 space-y-2 pb-3",onScroll:()=>{if(!Ne.current)return;const{scrollTop:M,scrollHeight:be,clientHeight:G}=Ne.current;ne.current=be-M-G<100},children:_e>0?Vs:null}),Ht&&a.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:[Ht,Ue&&a.jsx("div",{className:"mt-2",children:a.jsx("button",{type:"button",onClick:()=>st.getState().openLoginPrompt(p("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:p("message.thread.signInForHigherLimits")})})]}),a.jsxs("div",{ref:fe,className:"mt-1 w-full max-w-[64rem] bg-transparent pt-1",children:[a.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:[de&&a.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:[a.jsx(Ln,{className:"h-3.5 w-3.5 shrink-0 text-gray-500 dark:text-gray-400","aria-hidden":"true"}),a.jsx("span",{className:"min-w-0 truncate font-medium capitalize",children:de.name.replace(/-/g," ")}),a.jsx("button",{type:"button",onClick:()=>Me(),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":p("message.thread.removeSkillAriaLabel"),children:a.jsx(Ye,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),!de&&Ze.length>0&&k.length===0&&!Gt&&a.jsxs("button",{type:"button",onClick:Ft,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("message.thread.skillsHintAriaLabel"),title:p("message.thread.skillsHint"),children:[a.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")]}),a.jsxs("div",{className:"relative flex min-h-8 flex-1 items-center min-w-0",children:[a.jsx("label",{htmlFor:Se,className:"sr-only",children:p("message.thread.placeholder")}),Us&&a.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:[a.jsx("span",{className:"invisible",children:k}),a.jsx("span",{children:Us})]}),a.jsx("textarea",{id:Se,ref:se,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:Vt,"aria-label":p("message.thread.placeholder"),value:k,onChange:M=>{const be=M.target.value;N(be),be.startsWith("/")&&X(0),z(be.startsWith("/"))},onKeyDown:mt,disabled:Gt,rows:1,maxLength:hs,style:{minHeight:"32px",maxHeight:"120px",outline:"none",boxShadow:"none",WebkitAppearance:"none",MozAppearance:"none",appearance:"none"}})]}),a.jsxs("div",{className:"flex items-center justify-between sm:justify-end gap-2",children:[a.jsx(Oi,{availableModels:d,defaultModel:u,selectedModel:D,onSelect:re,maxWidthClass:"max-w-[120px]",triggerPaddingClass:"px-2 py-1",staticPaddingClass:"px-2 py-1",triggerTitle:p("message.thread.selectModelTitle"),listboxLabel:p("message.thread.selectModelTitle")}),k.trim().length>0&&a.jsx("button",{type:"button",onClick:bs,disabled:Gt||k.trim().length===0,className:"flex h-10 w-10 sm:h-8 sm:w-8 items-center justify-center rounded-full transition active:scale-95 bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-400 disabled:cursor-not-allowed",title:p("message.thread.sendMessageTitle"),children:a.jsx(hn,{className:"h-5 w-5 sm:h-4 sm:w-4"})})]})]}),U&&a.jsx("div",{className:"w-full pt-1",children:a.jsx(Di,{skills:Ze,isLoading:ft,selectedSkill:de,activeSkillName:rt==null?void 0:rt.name,query:Z,onActiveSkillChange:M=>{const be=qe.findIndex(G=>G.name===M.name);be>=0&&X(be)},onSelect:Kt,onClose:Hs})})]}),_e>0&&a.jsx("div",{className:"mt-2 flex justify-end",children:a.jsxs("button",{type:"button",onClick:()=>_(!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":p("message.thread.hideRepliesAriaLabel"),children:[a.jsx(wr,{className:"h-3 w-3"}),a.jsx("span",{children:p("message.thread.hideRepliesLabel")})]})})]})]}),a.jsx(Sr,{isOpen:te,onClose:()=>{ee||V(!1)},onConfirm:Dr,title:p("message.confirmation.clearRepliesTitle"),message:p("message.confirmation.clearRepliesMessage"),confirmText:p("common.clear"),cancelText:p("common.cancel"),type:"danger",isLoading:ee})]})}let as=null;function ku(){if(typeof window>"u")return null;const t=window.AudioContext??window.webkitAudioContext;return t?((!as||as.state==="closed")&&(as=new t),as.state==="suspended"&&as.resume(),as):($("[SoundEffects] AudioContext not supported in this browser"),null)}function vu(t){const e=ku();if(!e)return;const s=e.currentTime;for(const n of t){const r=e.createOscillator(),i=e.createGain();r.connect(i),i.connect(e.destination),r.frequency.value=n.frequency,r.type=n.type;const o=s+n.startTime,l=o+n.duration;i.gain.setValueAtTime(.001,o),i.gain.linearRampToValueAtTime(n.gain,o+.008),i.gain.exponentialRampToValueAtTime(.001,l),r.start(o),r.stop(l+.01)}}const Su={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 Ls(t,e){if(!e)return;const s=Su[t];if(!s){$(`[SoundEffects] Unknown sound effect type: ${t}`);return}try{vu(s),$(`[SoundEffects] Playing ${t} sound effect`)}catch(n){$(`[SoundEffects] Failed to play ${t} sound effect:`,n)}}function ju({messages:t,onRegenerate:e,onEditMessage:s,onStartThread:n,onClearThread:r,onSendThreadMessage:i,sessionId:o,isLoading:l,contentMaxWidthClass:c="max-w-[64rem]",availableModels:d,defaultModel:u,selectedModel:f}){const p=h.useRef(null),m=h.useRef(null),g=h.useRef(t.length),x=h.useRef(""),y=h.useRef(l),v=h.useRef(!0),{settings:A}=Lr(),{t:I}=Ee(),{topLevelMessages:S,threadLookup:C}=h.useMemo(()=>{const b=new Map,E=[];return t.forEach(k=>{if(k.isThreadMessage&&k.parentMessageId){const N=b.get(k.parentMessageId)||[];b.set(k.parentMessageId,[...N,k]);return}E.push(k)}),{topLevelMessages:E,threadLookup:b}},[t]),L=()=>{if(!m.current)return;const{scrollTop:b,scrollHeight:E,clientHeight:k}=m.current,T=E-b-k<200;v.current=T},F=h.useCallback(()=>{requestAnimationFrame(()=>{m.current&&(m.current.scrollTop=m.current.scrollHeight)})},[]);return h.useEffect(()=>{const b=t.length,E=g.current,k=b>E,N=t[t.length-1],T=(N==null?void 0:N.content)||"",_=T!==x.current,O=(N==null?void 0:N.isStreaming)??!1;k||O&&_?(F(),v.current=!0):v.current&&_&&F(),g.current=b,x.current=T},[t,F]),h.useEffect(()=>{l&&(F(),v.current=!0)},[l,F]),h.useEffect(()=>{if(y.current&&!l){const b=t[t.length-1];(b==null?void 0:b.role)==="assistant"&&b.content&&Ls("messageReceived",A.soundEnabled)}y.current=l},[l,t,A.soundEnabled]),S.length===0?a.jsx("div",{className:"flex-1 flex items-center justify-center px-4 sm:px-6",children:a.jsxs("div",{className:"text-center text-lg text-gray-500 dark:text-[#bfc2cd]",children:[a.jsx("p",{className:"text-xl",children:I("messageList.emptyStateHeading")}),a.jsx("p",{className:"mt-1 text-lg",children:I("messageList.emptyStateSubheading")})]})}):a.jsx("div",{ref:m,className:"message-list flex-1 overflow-y-auto pb-8 pt-4 sm:pt-6",onScroll:L,children:a.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:a.jsxs("div",{className:`message-list__rail mx-auto w-full space-y-7 ${c}`,children:[S.map(b=>a.jsx("div",{className:`flex w-full ${b.role==="user"?"justify-end":"justify-start"}`,style:{contentVisibility:"auto",containIntrinsicSize:"420px"},children:a.jsx(wu,{message:b,onRegenerate:e,onEdit:s,onStartThread:n,onClearThread:r,onSendThreadMessage:i,threadMessages:C.get(b.id),sessionId:o,isThreadSendDisabled:l,availableModels:d,defaultModel:u,selectedModel:f})},b.id)),a.jsx("div",{ref:p,className:"h-8"})]})})})}const Cu=4e3;function Nu(t,e,s={}){var E;const{t:n}=Ee(),[r,i]=h.useState(!1),[o,l]=h.useState(null),c=h.useRef(null),d=h.useRef(""),u=h.useRef(""),f=h.useRef(!1),p=h.useRef(null),m=typeof navigator<"u"?navigator.language:"en-US",g=Number.isFinite(s.silenceTimeoutMs)?Math.max(Math.floor(s.silenceTimeoutMs),1e3):Cu,x=((E=s.language)==null?void 0:E.trim())||m||"en-US",y=h.useCallback(k=>k.replace(/\s+/g," ").trim(),[]),v=h.useCallback(k=>{const N=y(k);N&&N!==u.current&&(u.current=N,t(N))},[y,t]),A=h.useCallback(()=>{if(!d.current)return;const k=d.current;d.current="",v(k)},[v]),I=typeof window<"u"&&("webkitSpeechRecognition"in window||"SpeechRecognition"in window),S=h.useCallback(()=>{!e||f.current||(f.current=!0,e())},[e]),C=h.useCallback(()=>{p.current!==null&&(clearTimeout(p.current),p.current=null)},[]),L=h.useCallback(()=>{C(),p.current=setTimeout(()=>{$("Speech recognition silence threshold reached, stopping recording"),c.current?c.current.stop():S()},g)},[C,S,g]),F=h.useCallback(()=>{if(!I){l(n("voice.browserNotSupported"));return}if(!c.current)try{f.current=!1;const k=window.SpeechRecognition||window.webkitSpeechRecognition,N=new k;N.continuous=!0,N.interimResults=!0,N.lang=x,N.maxAlternatives=1,N.onstart=()=>{i(!0),l(null),d.current="",u.current="",$("Speech recognition started"),L()},N.onresult=T=>{let _="",O="";for(let j=T.resultIndex;j<T.results.length;j++){const U=T.results[j][0].transcript;T.results[j].isFinal?_+=U:O+=U}O&&(d.current=y(O)),_&&(d.current="",v(_)),L()},N.onend=()=>{C(),A(),i(!1),c.current=null,$("Speech recognition ended"),S()},N.onerror=T=>{switch(C(),ye("Speech recognition error:",T.error),i(!1),c.current=null,d.current="",S(),T.error){case"no-speech":l(n("voice.error.noSpeech"));break;case"audio-capture":l(n("voice.error.audioCapture"));break;case"not-allowed":l(n("voice.error.notAllowed"));break;case"network":l(n("voice.error.network"));break;default:l(n("voice.error.generic",{error:T.error}))}},N.start(),c.current=N}catch(k){ye("Failed to start speech recognition:",k),l(n("voice.error.startFailed")),i(!1)}},[I,A,S,L,C,x,y,v,n]),b=h.useCallback(()=>{if($("Stopping speech recognition..."),c.current){const k=c.current;k.onstart=null,k.onerror=null;try{k.stop()}catch(N){$("Recognition already stopped or error stopping:",N),C(),A(),k.onend=null,k.onresult=null,c.current=null,i(!1),S()}}C(),i(!1),l(null),$("Speech recognition stopped, isListening set to false")},[C,A,S]);return{isListening:r,isSupported:I,startListening:F,stopListening:b,error:o}}const Au=300,Ua=3,lr=5,Iu=6e4;function za(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 Lu(t,e={}){const{enabled:s=hi(),adapterName:n,sessionId:r,adapterSupportsAutocomplete:i,skill:o,inputRef:l}=e,[c,d]=h.useState([]),[u,f]=h.useState(!1),[p,m]=h.useState(-1),g=h.useRef(null),x=h.useRef(null),y=h.useRef(null),v=h.useRef(null),A=h.useRef(null),I=h.useRef(0),S=h.useRef([]),C=h.useRef([]),L=h.useRef(new Map);h.useEffect(()=>{S.current=c},[c]);const F=h.useCallback(j=>{const U=L.current.get(j);return U?U<=Date.now()?(L.current.delete(j),!1):!0:!1},[]),b=h.useCallback((j,U=!0)=>{const z=j.toLowerCase().trim(),R=C.current.length>0?C.current:S.current;if(!z)return R.slice(0,lr);const X=R.filter(te=>te.text.toLowerCase().includes(z));return X.length>0?X.slice(0,lr):U?R.slice(0,lr):[]},[]),E=h.useCallback(async j=>{if(!s||j.length<Ua){d([]),C.current=[],x.current&&clearTimeout(x.current),y.current&&clearTimeout(y.current),f(!1);return}if(!n){d([]),C.current=[],x.current&&clearTimeout(x.current),f(!1);return}if(i===!1||F(n)){d([]),C.current=[],x.current&&clearTimeout(x.current),f(!1);return}v.current&&v.current.abort(),v.current=new AbortController;const U=I.current+1;I.current=U,x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{U===I.current&&f(!0)},150);try{const z={"X-Adapter-Name":n};r&&(z["X-Session-ID"]=r);const R=new URLSearchParams;R.set("q",j),R.set("limit",String(lr)),o&&R.set("skill",o);const X=`/api/v1/autocomplete?${R.toString()}`,te=await fetch(X,{method:"GET",headers:z,signal:v.current.signal});if(!te.ok){ge("[useAutocomplete] Request failed:",te.status),[404,405,501].includes(te.status)?(L.current.set(n,Date.now()+Iu),d([]),C.current=[]):d(b(j));return}const V=await te.json(),ee=Array.isArray(V==null?void 0:V.suggestions)?V.suggestions.map(me=>za(typeof me=="string"?me:me==null?void 0:me.text)).filter(me=>me!==null):[];if(U!==I.current)return;ee.length===0?d(b(j,!1)):(d(ee),C.current=ee),m(-1),$("[useAutocomplete] Received",ee.length,"suggestions")}catch(z){if(z instanceof Error&&z.name==="AbortError")return;ge("[useAutocomplete] Error:",z instanceof Error?z.message:String(z)),U===I.current&&d(b(j))}finally{U===I.current&&(x.current&&(clearTimeout(x.current),x.current=null),f(!1))}},[s,n,r,i,o,b,F]);h.useEffect(()=>{g.current&&clearTimeout(g.current);const j=()=>{v.current&&v.current.abort(),x.current&&clearTimeout(x.current),f(!1)},U=()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{y.current=null,d([]),j()},0)};if(!s||t.length<Ua||i===!1||n&&F(n)){U();return}if(A.current){if(t===A.current){U();return}A.current=null}return g.current=setTimeout(()=>{E(t)},Au),()=>{g.current&&clearTimeout(g.current),y.current&&(clearTimeout(y.current),y.current=null)}},[t,E,s,n,i,F]),h.useEffect(()=>()=>{v.current&&v.current.abort(),x.current&&clearTimeout(x.current)},[]);const k=h.useCallback(()=>{m(j=>{const U=S.current.length;return U===0?-1:j<U-1?j+1:0})},[]),N=h.useCallback(()=>{m(j=>{const U=S.current.length;return U===0?-1:j>0?j-1:U-1})},[]),T=h.useCallback(()=>{d([]),C.current=[],m(-1),v.current&&v.current.abort(),x.current&&clearTimeout(x.current),f(!1)},[]),_=h.useCallback(j=>{if(!(l!=null&&l.current))return;const U=()=>{const z=l.current;if(!z)return;const R=typeof j=="string"?j.length:z.value.length;z.focus({preventScroll:!0}),typeof z.setSelectionRange=="function"&&z.setSelectionRange(R,R)};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(U):setTimeout(U,0)},[l]),O=h.useCallback(j=>{A.current=j},[]);return{suggestions:c,isLoading:u,selectedIndex:p,setSelectedIndex:m,selectNext:k,selectPrevious:N,clearSuggestions:T,focusInputAfterSelection:_,suppressUntilQueryChange:O}}const Rt=new Map,Eu=new Map,Tu=new Map,_u=new Set,Mu=()=>{if(typeof window>"u")return null;try{return localStorage.getItem("chat-adapter-name")}catch{return null}},Ui=t=>typeof t=="object"&&t!==null&&"message"in t,Fu=t=>t instanceof Error?t.message:typeof t=="string"?t:Ui(t)?t.message??"Unknown error":"Unknown error";function $u({conversationId:t,onFilesSelected:e,onUploadError:s,onClose:n,onUploadingChange:r,onUploadSuccess:i,maxFiles:o=oe.maxFilesPerConversation,disabled:l=!1}){const{t:c}=Ee(),[d,u]=h.useState(!1),[f,p]=h.useState(0),m=h.useRef(null),g=h.useRef(Tu),x=h.useRef(_u),y=h.useRef(new Map),v=h.useRef(!0),A=h.useRef(Eu),I=h.useRef(t),S=ke(D=>D.conversations),C=h.useMemo(()=>{if(!t)return new Map;const D=Rt.get(t);return D?new Map(D):new Map},[t,f]),L=h.useCallback(D=>{if(!D){r==null||r(null,!1),p(se=>se+1);return}const re=Rt.get(D)||new Map,q=S.find(se=>se.id===D),Q=new Map(re);if(q!=null&&q.attachedFiles){const se=new Set(q.attachedFiles.filter(fe=>fe.processing_status==="completed"||fe.processing_status==="failed"||fe.processing_status==="error").map(fe=>fe.file_id));Q.forEach((fe,Ne)=>{fe.fileId&&se.has(fe.fileId)&&Q.delete(Ne)})}Q.size>0?(Rt.set(D,Q),r==null||r(D,!0)):(Rt.delete(D),r==null||r(D,!1)),p(se=>se+1)},[S,r]);h.useEffect(()=>{I.current=t,setTimeout(()=>{L(t)},0)},[t,L]),h.useEffect(()=>{t&&setTimeout(()=>{L(t)},0)},[S,t,L]);const F=h.useCallback((D,re)=>{if(!D)return;const q=Rt.get(D)||new Map,Q=re(new Map(q));Q.size>0?Rt.set(D,Q):Rt.delete(D),r==null||r(D,Q.size>0),p(se=>se+1)},[r]),b=h.useCallback((D,re)=>{if(!D)return;const q=A.current.get(D)||[],Q=re([...q||[]]),se=new Set(q.map(fe=>fe.file_id));if(A.current.set(D,Q),e(D,Q),i){const fe=Q.filter(Ne=>!se.has(Ne.file_id));fe.length>0&&i(D,fe)}p(fe=>fe+1)},[e,i]),E=ke(D=>D.removeFileFromConversation),k=ke(D=>D.addFileToConversation);h.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);const N=h.useCallback(()=>{v.current=!1,new Map(y.current).forEach(re=>re.abort()),setTimeout(()=>{const re=ke.getState(),q=new Map(re.conversations.map(se=>[se.id,se])),Q=[];g.current.forEach((se,fe)=>{var Ne;if(se){const B=q.get(se);if(new Set(((Ne=B==null?void 0:B.attachedFiles)==null?void 0:Ne.map(J=>J.file_id))||[]).has(fe)){x.current.add(fe),g.current.delete(fe);return}}if(x.current.has(fe)){$(`[FileUpload] Skipping cleanup delete for ${fe}; file was previously attached and already handled`),g.current.delete(fe),x.current.delete(fe);return}Q.push({fileId:fe,conversationId:se||null})}),Q.length>0&&(n==null||n(),Q.forEach(async({fileId:se,conversationId:fe})=>{try{if(fe)await E(fe,se);else{const Ne=Mu();await Os.deleteFile(se,void 0,void 0,Ne??void 0)}}catch(Ne){if(Ui(Ne)){const B=Ne.message??"";!B.includes("404")&&!B.includes("File not found")&&ge(`Failed to cleanup file ${se} during component unmount:`,Ne)}else ge(`Failed to cleanup file ${se} during component unmount`,Ne)}}))},300)},[n,E]);h.useEffect(()=>N,[N]);const T=h.useCallback(async D=>{if(!D||D.length===0)return;const re=Array.from(D),q=ke.getState(),Q=t||q.currentConversationId;if(!Q){s==null||s(c("fileUpload.selectBeforeUpload"));return}const se=q.conversations.find(W=>W.id===Q);if(!se){s==null||s(c("fileUpload.conversationNotFound"));return}if((A.current.get(Q)||[]).length+re.length>o){const W=c("fileUpload.maxFilesPerConversationError",{count:o});tt()&&!xt()&&st.getState().openLoginPrompt(c("fileUpload.maxFilesGuestLimitMessage",{count:o})),s==null||s(W);return}if(oe.maxTotalFiles!==null&&q.conversations.reduce((we,ne)=>{var K;return we+(((K=ne.attachedFiles)==null?void 0:K.length)||0)},0)+re.length>oe.maxTotalFiles){const we=c("fileUpload.maxTotalFilesError",{count:oe.maxTotalFiles});tt()&&!xt()&&st.getState().openLoginPrompt(c("fileUpload.maxTotalFilesGuestLimitMessage",{count:oe.maxTotalFiles})),s==null||s(we);return}if(!se.adapterName){s==null||s(c("fileUpload.adapterNotConfigured"));return}const Ne=se.adapterName,B=it(se.apiUrl);for(let W=0;W<re.length;W++){const J=re[W],we=new AbortController;y.current.set(J.name,we);const ne=`${Q}-${J.name}-${Date.now()}-${W}`;let K=null;try{const le=await Os.uploadFile(J,ve=>{if(F(Q,ue=>(ue.set(ne,ve),ue)),ve.fileId&&!K){K=ve.fileId,g.current.set(ve.fileId,Q),x.current.add(ve.fileId);const ue={file_id:ve.fileId,filename:J.name,mime_type:J.type||"application/octet-stream",file_size:J.size,processing_status:ve.status==="uploading"?"uploading":ve.status==="processing"?"processing":ve.status==="completed"?"completed":void 0};$(`[FileUpload] Adding file ${ve.fileId} to conversation ${Q} immediately (status: ${ue.processing_status})`),k(Q,ue)}},void 0,B,Ne).catch(ve=>{if(ve.message&&ve.message.includes("was deleted")){K&&g.current.delete(K);const ue=ve.message.match(/File\s+([\w-]+)\s+was deleted/);return ue&&ue[1]&&g.current.delete(ue[1]),$(`File ${J.name} was deleted during upload`),null}throw ve});le?(g.current.set(le.file_id,Q),x.current.add(le.file_id),$(`[FileUpload] Updating file ${le.file_id} in conversation ${Q} with final status`),k(Q,le),le.processing_status==="completed"||le.processing_status==="failed"||le.processing_status==="error"?F(Q,ue=>(ue.delete(ne),ue)):F(Q,ue=>{const Pe=ue.get(ne);return Pe&&ue.set(ne,{...Pe,progress:90,status:"processing",fileId:le.file_id}),ue}),b(Q,ue=>{if(new Set(ue.map(H=>H.file_id)).has(le.file_id))return ue;const _e=[...ue,le];return $(`[FileUpload] Updated uploadedFiles for ${Q}: ${_e.length} files`,_e),_e})):(ge(`Upload completed for ${J.name} but uploadedAttachment is null`),F(Q,ve=>(ve.delete(ne),ve)))}catch(le){const ve=Fu(le);if(le instanceof DOMException&&le.name==="AbortError"||we.signal.aborted){$(`Upload cancelled for ${J.name}`),K&&g.current.delete(K);continue}if(ve.includes("was deleted")){$(`File ${J.name} was deleted during upload`),K&&g.current.delete(K);const _e=ve.match(/File\s+([\w-]+)\s+was deleted/);_e&&_e[1]&&g.current.delete(_e[1]);continue}v.current?(ye(`Failed to upload file ${J.name}:`,le),ye(`File type: ${J.type}, File name: ${J.name}`),s==null||s(ve||`Failed to upload ${J.name}`)):ge(`Upload error for ${J.name} (component unmounted):`,ve),K&&g.current.delete(K);const ue=ne,Pe=Q;setTimeout(()=>{F(Pe,_e=>(_e.delete(ue),_e))},5e3)}finally{y.current.delete(J.name)}}},[k,t,o,s,c,b,F]),_=h.useCallback(D=>{D.preventDefault(),D.stopPropagation(),l||u(!0)},[l]),O=h.useCallback(D=>{D.preventDefault(),D.stopPropagation(),u(!1)},[]),j=h.useCallback(D=>{if(D.preventDefault(),D.stopPropagation(),u(!1),l)return;const re=D.dataTransfer.files;T(re)},[l,T]),U=h.useCallback(D=>{const re=D.target.files;T(re),m.current&&(m.current.value="")},[T]),z=h.useCallback(()=>{!l&&m.current&&m.current.click()},[l]),R=h.useCallback(D=>{l||(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),z())},[l,z]),X=C.size>0,te=h.useMemo(()=>{const D=new Map;return S.forEach(re=>{D.set(re.id,re.title||c("chatInterface.newChatTitle"))}),D},[S,c]),V=h.useMemo(()=>{const D=[];return Rt.forEach((re,q)=>{q!==t&&re.size>0&&D.push({conversationId:q,uploads:Array.from(re.entries()).map(([Q,se])=>({key:Q,progress:se}))})}),D},[t,f]),ee=(D,re)=>{const q=D.status==="error";return a.jsxs("div",{className:`group relative w-full flex items-center gap-3 rounded-lg px-3 py-2.5 overflow-hidden transition-colors ${q?"border border-red-200 bg-red-50 dark:border-red-500/30 dark:bg-[#101010]":"border border-gray-200 bg-gray-50 dark:border-[#242424] dark:bg-[#101010]"}`,children:[!q&&a.jsx("div",{className:"absolute inset-0 bg-blue-50 dark:bg-white/[0.04] transition-all duration-500 ease-out rounded-lg",style:{width:`${D.progress}%`}}),a.jsxs("div",{className:"relative flex items-center gap-3 w-full min-w-0",children:[a.jsx("div",{className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-md ${q?"bg-red-100 dark:bg-red-500/15":"bg-blue-100 dark:bg-white/[0.06]"}`,children:q?a.jsx(mr,{className:"h-4 w-4 text-red-500 dark:text-red-400"}):a.jsx(pr,{className:"h-4 w-4 text-blue-600 dark:text-blue-400 animate-spin"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium text-[#353740] dark:text-[#ececf1] truncate",children:D.filename}),q?a.jsx("p",{className:"mt-0.5 text-xs text-red-600 dark:text-red-400 truncate",children:D.error||c("fileUpload.processingFailedMessage")}):a.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 bg-gray-200 dark:bg-[#242424] rounded-full h-1",children:a.jsx("div",{className:"bg-blue-500 dark:bg-blue-400 h-1 rounded-full transition-all duration-500 ease-out",style:{width:`${D.progress}%`}})}),a.jsxs("span",{className:"text-[11px] tabular-nums text-gray-400 dark:text-[#8e8ea0] shrink-0",children:[Math.round(D.progress),"%"]})]})]}),a.jsx("span",{className:`text-xs font-medium shrink-0 ${q?"text-red-500 dark:text-red-400":"text-gray-500 dark:text-[#bfc2cd]"}`,children:D.status==="uploading"?c("fileUpload.uploadingStatus"):D.status==="processing"?c("fileUpload.processingStatus"):D.status==="completed"?c("fileUpload.completedStatus"):c("fileUpload.failedStatus")})]})]},re)},me=a.jsx("div",{className:"w-full max-w-full overflow-hidden space-y-1.5",role:"status","aria-live":"polite",children:Array.from(C.entries()).map(([D,re])=>ee(re,D))});return a.jsxs("div",{className:"w-full max-w-full overflow-hidden space-y-2",children:[X&&me,!X&&a.jsxs("button",{type:"button",onClick:z,onKeyDown:R,onDragOver:_,onDragLeave:O,onDrop:j,disabled:l,className:`
324
+ group relative w-full max-w-full rounded-lg border p-4 transition-all duration-200 text-left overflow-hidden
325
+ ${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]"}
326
+ `,"aria-label":c(l?"fileUpload.disabledAriaLabel":"fileUpload.enabledAriaLabel"),children:[a.jsx("input",{ref:m,type:"file",multiple:!0,onChange:U,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"}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.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:a.jsx(td,{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"}`})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.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")}),a.jsx("p",{className:"text-xs text-gray-400 dark:text-[#8e8ea0] mt-0.5",children:c("fileUpload.fileTypesAndLimit",{count:o})})]})]})]}),V.length>0&&a.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:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-[#8e8ea0] px-1",children:c("fileUpload.otherConversationsLabel")}),V.map(({conversationId:D,uploads:re})=>a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("div",{className:"text-[11px] font-medium text-gray-400 dark:text-[#6b6f7a] px-1",children:te.get(D)||"Conversation"}),re.map(({key:q,progress:Q})=>ee(Q,q))]},D))]})]})}const Ba={"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"},cr=4,dr=3,Pu=0,Ru=0,en=2;function Du(t){if(!t||typeof t!="object")return null;const e=t,s=["supportsAutocomplete","isAutocompleteSupported","autocompleteSupported"];for(const i of s)if(typeof e[i]=="boolean")return e[i];const n=["capabilities","features"],r=["autocomplete","supportsAutocomplete","autocomplete_supported"];for(const i of n){const o=e[i];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 Ou(t){if(!t)return"bin";if(Ba[t])return Ba[t];const e=t.split("/");return e.length===2&&e[1]?e[1]:"bin"}function Uu(t){return t.replace(/[^a-zA-Z0-9._-]/g,"_").replace(/_+/g,"_")||"pasted-file"}function zu(t){const e=t.lastIndexOf(".");return e===-1||e===t.length-1?null:t.slice(e+1).toLowerCase()}function Bu(t){const e=t.lastIndexOf(".");return e===-1?t:t.slice(0,e)}function Hu(t,e){const s=Date.now(),n=t.name&&t.name.trim().length>0?t.name.trim():"pasted-file",r=Uu(Bu(n)),o=zu(n)||Ou(t.type),l=`${r}-${s}-${e}.${o}`;return new File([t],l,{type:t.type||"application/octet-stream"})}function Ha({onSend:t,disabled:e=!1,placeholder:s=ui(),autoFocusEnabled:n=!0,suppressMobileAutoFocus:r=!1,isCentered:i=!1,maxWidthClass:o="max-w-5xl",adapterNotes:l,skillState:c,availableModels:d=[],defaultModel:u=null,selectedModel:f=null,onSelectModel:p}){var Xn;const{t:m}=Ee(),[g,x]=h.useState(""),[y,v]=h.useState(!1),[A,I]=h.useState(!1),[S,C]=h.useState(!1),[L,F]=h.useState(!1),[b,E]=h.useState([]),[k,N]=h.useState({}),[T,_]=h.useState(new Map),[O,j]=h.useState(!1),[U,z]=h.useState(!1),[R,X]=h.useState(null),[te,V]=h.useState(null),[ee,me]=h.useState(null),[D,re]=h.useState({isOpen:!1,fileId:"",filename:"",isDeleting:!1}),q=h.useRef(null),Q=h.useRef(null),se=h.useRef(null),fe=h.useRef(null),Ne=h.useRef(null),B=h.useRef(new Set),W=h.useRef(""),J=h.useRef(!1),we=h.useRef(0),ne=h.useRef(null),{settings:K,updateSettings:le}=Lr(),{theme:ve,isDark:ue}=ds(),Pe=ve.mode==="dark"?"dark":ve.mode==="light"?"light":"",_e=ue?"dark":"light";Rs(Q,{enabled:S,onEscape:()=>C(!1)});const H=h.useCallback((w,P)=>{w&&N(ie=>{if(ie[w]===P)return ie;const pe={...ie};return P?pe[w]=!0:delete pe[w],pe})},[]),[ce,Ue]=h.useState(0),[xe,Ae]=h.useState(!1),[Lt,ze]=h.useState(0),[Qe,hs]=h.useState(()=>({top:cr+dr,bottom:Math.max(cr-dr,0)})),[ut,Et]=h.useState(null),Ht=fs(),Je=tt()&&!Ht,Tt=st(w=>w.showLoginPrompt),{createConversation:Vt,currentConversationId:Se,conversations:Ze,isLoading:ft,syncConversationFiles:de,stopStreaming:Ce,removeFileFromConversation:Me}=ke(),Z=Ze.find(w=>w.id===Se),ht=Z?Z.messages.filter(w=>!(w.role==="assistant"&&w.isStreaming)).length:0,qe=Ze.reduce((w,P)=>w+P.messages.filter(ie=>!(ie.role==="assistant"&&ie.isStreaming)).length,0),ms=!!Z&&oe.maxMessagesPerConversation!==null&&ht>=oe.maxMessagesPerConversation,rt=oe.maxTotalMessages!==null&&qe>=oe.maxTotalMessages,ps=h.useCallback(()=>{Ue(w=>w+1)},[]),Us=Yl(),ss=Ql(),{isListening:et,isSupported:zs,startListening:Bs,stopListening:rs,error:qt}=Nu(w=>{x(P=>{const ie=P.length>0&&!/\s$/.test(P)?" ":"",pe=(P+ie+w).slice(0,oe.maxMessageLength);return W.current=pe,pe})},ps,{silenceTimeoutMs:Us,language:ss||void 0}),gs=Kl(),_t=Gl(),lt=_t&&zs,Mt=Wl(),$r=hi(),xs=Du(Z==null?void 0:Z.adapterInfo),{skills:Wt,isLoading:Pr,selectedSkill:Be,selectSkill:bs,clearSkill:Kt}=c,Hs=(Z==null?void 0:Z.adapterName)||null,{suggestions:Ft,selectedIndex:mt,setSelectedIndex:Gt,selectNext:Rr,selectPrevious:Dr,clearSuggestions:bt,focusInputAfterSelection:Vs,suppressUntilQueryChange:ys}=Lu(g,{enabled:$r&&!et,apiUrl:Z==null?void 0:Z.apiUrl,adapterName:Hs,sessionId:Z==null?void 0:Z.sessionId,adapterSupportsAutocomplete:xs,skill:(Be==null?void 0:Be.name)||null,inputRef:q}),ns=Ft.length>0,ws=!et,M=ws&&ns&&!xe,be=g.startsWith("/")?g.slice(1):"",G=be.toLowerCase().replace(/-/g," "),je=G?Wt.filter(w=>w.name.replace(/-/g," ").toLowerCase().includes(G)||w.description.toLowerCase().includes(G)):Wt,ct=je.length>0?Math.min(Lt,je.length-1):0,We=je[ct]??null,Xt=(We==null?void 0:We.name.replace(/-/g," "))??"",Qi=xe&&We&&g.startsWith("/")&&Xt.toLowerCase().startsWith(be.toLowerCase())&&Xt.length>be.length?Xt.slice(be.length):null,Ji=mt>=0?mt:0,ks=ns?Ft[Ji]:null,Pn=h.useMemo(()=>{if(!ks)return null;const w=ks.text||"";if(!g)return w;const P=g;return w.toLowerCase().startsWith(P.toLowerCase())&&w.length>P.length?w.slice(P.length):null},[ks,g]),Or=Qi??Pn,Zi=g.trim().length===0&&!Or,eo=h.useCallback(w=>{if(!g)return a.jsx("span",{className:"line-clamp-1 text-current",children:w});if(!w.toLowerCase().startsWith(g.toLowerCase()))return a.jsx("span",{className:"line-clamp-1 text-current",children:w});const P=w.slice(0,g.length),ie=w.slice(g.length);return a.jsxs("span",{className:"line-clamp-1",children:[a.jsx("span",{className:"text-gray-500 dark:text-[#8e8ea0]",children:P}),a.jsx("span",{className:"font-semibold text-[#353740] dark:text-[#ececf1]",children:ie})]})},[g]),Rn=h.useCallback(w=>{var P;bs(w),Ae(!1),x(""),bt(),ze(0),(P=q.current)==null||P.focus()},[bt,bs]),to=h.useCallback(()=>{var w;x("/"),Ae(!0),ze(0),(w=q.current)==null||w.focus()},[]),Dn=h.useCallback(()=>{var w;Ae(!1),x(""),ze(0),(w=q.current)==null||w.focus()},[]),Yt=h.useCallback(()=>{const w=q.current;if(!w||typeof window>"u")return;const P=pt=>{const Zs=pt+dr,er=Math.max(pt-dr,0);w.style.paddingTop=`${Zs}px`,w.style.paddingBottom=`${er}px`,hs({top:Zs,bottom:er})},ie=window.getComputedStyle(w),pe=parseFloat(ie.lineHeight||"0");if(!Number.isNaN(pe)&&pe>0?Et(pt=>pt===pe?pt:pe):Et(pt=>pt===null?pt:null),!pe||Number.isNaN(pe)){P(cr);return}const Le=w.scrollHeight,Ke=w.clientHeight;if(Le>pe+2){P(cr);return}const Ie=Math.max(Ke-pe,0),Jt=Math.max(Ie/2,0);P(Jt)},[]),so=()=>{const w=q.current;return w?w.selectionStart===w.selectionEnd&&w.selectionStart===g.length:!1},On=(Z==null?void 0:Z.attachedFiles)||[],$t=Se?On:b,ro=Ze.reduce((w,P)=>{var ie;return w+(((ie=P.attachedFiles)==null?void 0:ie.length)||0)},0),Un=oe.maxFilesPerConversation!==null&&oe.maxFilesPerConversation>0&&On.length>=oe.maxFilesPerConversation,zn=oe.maxTotalFiles!==null&&ro>=oe.maxTotalFiles,vs=((Xn=Z==null?void 0:Z.adapterInfo)==null?void 0:Xn.isFileSupported)??!1,Ur=$t.some(w=>w.processing_status?w.processing_status!=="completed"&&w.processing_status!=="error"&&w.processing_status!=="failed":!0),nt=Se?!!k[Se]:!1,qs=Object.values(k).some(Boolean),zr=g.trim().length>0,Bn=ms||rt,De=e||Ur||nt||Bn,Hn=Mt&&vs,Ws=Un||zn,Ss=!Hn||De||Ws;h.useLayoutEffect(()=>{if(q.current){const w=q.current,P=120;w.style.height="auto";const ie=w.scrollHeight;w.style.height=`${Math.min(ie,P)}px`,w.style.overflowY=ie>P?"auto":"hidden",Yt()}},[g,Yt]),h.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const w=q.current;if(!w)return;const P=new ResizeObserver(()=>{Yt()});return P.observe(w),()=>{P.disconnect()}},[Yt]);const Vn=()=>{const w=document.activeElement;return w&&w.tagName==="TEXTAREA"},Ks=h.useCallback(()=>!r||typeof window>"u"?!1:window.matchMedia("(max-width: 767px)").matches,[r]);h.useEffect(()=>{Ks()||n&&!De&&q.current&&!Vn()&&q.current.focus()},[n,De,r,Ks]);const Br=h.useRef(ft);h.useEffect(()=>{if(Ks()){Br.current=ft;return}n&&Br.current&&!ft&&!De&&q.current&&setTimeout(()=>{q.current&&!Vn()&&q.current.focus()},100),Br.current=ft},[n,ft,De,r,Ks]),h.useEffect(()=>{if(!lt||(ce>we.current&&(J.current=!0,we.current=ce),!J.current||ce===0))return;const w=W.current.trim(),P=ke.getState();if($("[MessageInput] Auto-send check after voice completion:",{hasMessage:!!w,isInputDisabled:De,isComposing:y,isLoading:P.isLoading}),J.current=!1,!w)return;if(De||y){$("[MessageInput] Auto-send skipped because input is currently disabled or composing");return}const ie=P.conversations.find(Te=>Te.id===P.currentConversationId),Le=((ie==null?void 0:ie.attachedFiles)||[]).map(Te=>Te.file_id),Ke=Be==null?void 0:Be.name;$("[MessageInput] Auto-sending voice message immediately:",w),t(w,Le.length>0?Le:void 0,void 0,Ke),Ke&&Kt(),setTimeout(()=>{Ae(!1)},0),bt(),setTimeout(()=>{x("")},0),W.current="",q.current&&(q.current.style.height="auto",q.current.style.overflowY="hidden",Yt())},[lt,ce,De,y,t,Be,Kt,Yt,bt]),h.useEffect(()=>{nt&&L&&setTimeout(()=>{F(!1)},0)},[nt,L]),h.useEffect(()=>{!nt&&$t.length},[nt,L,$t.length]);const Gs=h.useCallback((w,P)=>{setTimeout(()=>{let ie=ke.getState(),pe=P||ie.currentConversationId;if(pe||(pe=Vt(),ie=ke.getState(),pe=ie.currentConversationId||pe),!pe){ye("[MessageInput] Unable to sync files: conversation ID missing");return}const Le=new Set(w.map(Te=>Te.file_id)),Ke=[];B.current.forEach((Te,Ie)=>{const[,...Jt]=Ie.split("-"),pt=Jt.join("-");Le.has(pt)||Ke.push(Ie)}),Ke.forEach(Te=>B.current.delete(Te)),w.forEach(Te=>{const Ie=`${pe}-${Te.file_id}`;B.current.has(Ie)||(B.current.add(Ie),$(`[MessageInput] Adding file ${Te.file_id} to conversation ${pe}`),ie.addFileToConversation(pe,Te))})},0)},[Vt]);h.useEffect(()=>{if(Se!==ne.current)if(ne.current=Se||null,Se&&Z){const w=Z.attachedFiles||[];setTimeout(()=>{E(w.map(P=>({...P})))},0)}else setTimeout(()=>{E([])},0)},[Se,Z]),h.useEffect(()=>{if(Se&&Z){const w=Z.attachedFiles||[];w.length>0?setTimeout(()=>{E(P=>{const ie=new Set(P.map(Le=>Le.file_id)),pe=w.filter(Le=>!ie.has(Le.file_id));return pe.length>0?($(`[MessageInput] Syncing ${pe.length} missing files from conversation to UI`),[...P,...pe]):P})},0):w.length===0&&b.length>0&&setTimeout(()=>{E([])},0)}},[Se,Z,Ze,b.length]);const Hr=h.useRef(null),Vr=h.useRef(""),Xs=(Z==null?void 0:Z.attachedFiles)||[],Ys=Xs.length>0?`${Xs.length}:${Xs.map(w=>w.file_id).join("|")}`:"",qn=Xs.some(w=>!w.processing_status||w.processing_status==="processing"||w.processing_status==="uploading");h.useEffect(()=>{if(!Se||!(Z!=null&&Z.adapterName))return;const w=Ys!=="";if(w&&(Hr.current!==Se||Vr.current!==Ys)?($(`[MessageInput] Syncing files for conversation ${Se}...`),Hr.current=Se,Vr.current=Ys,de(Se).catch(pe=>{ye("[MessageInput] Failed to sync conversation files:",pe)})):w||(Hr.current=Se,Vr.current=""),!qn)return;$("[MessageInput] Files still processing, starting poll...");const ie=setInterval(async()=>{const Le=ke.getState().conversations.find(Ie=>Ie.id===Se);if(!Le){clearInterval(ie);return}if((Le.attachedFiles||[]).filter(Ie=>!Ie.processing_status||Ie.processing_status==="processing"||Ie.processing_status==="uploading").length===0){$("[MessageInput] All files completed processing, stopping poll"),clearInterval(ie);return}try{await de(Se)}catch(Ie){ye("[MessageInput] Failed to poll file status:",Ie)}},3e3);return()=>{clearInterval(ie)}},[Se,Z==null?void 0:Z.adapterName,Ys,qn,de]),h.useEffect(()=>{setTimeout(()=>{N(w=>{const P=new Set(Ze.map(Le=>Le.id));let ie=!1;const pe={...w};return Object.keys(pe).forEach(Le=>{P.has(Le)||(delete pe[Le],ie=!0)}),ie?pe:w})},0)},[Ze]);const Wn=w=>{if(w.preventDefault(),zr&&!De&&!y){et&&rs();const ie=((Z==null?void 0:Z.attachedFiles)||[]).map(Le=>Le.file_id),pe=Be==null?void 0:Be.name;t(g.trim(),ie.length>0?ie:void 0,void 0,pe),pe&&Kt(),Ae(!1),Ls("messageSent",K.soundEnabled),x(""),W.current="",E([]),F(!1),q.current&&(q.current.style.height="auto",q.current.style.overflowY="hidden",Yt())}},Qs=h.useCallback(w=>{if(!w||w.length===0)return;const P=w.length===1?m("messageInput.uploadSuccess.single",{filename:w[0].filename}):m("messageInput.uploadSuccess.multiple",{count:w.length});Ls("success",K.soundEnabled),V(P),setTimeout(()=>{V(null)},6e3)},[K.soundEnabled,m]),no=h.useCallback((w,P)=>{$(`[MessageInput] handleFilesSelected called with ${P.length} files for conversation ${w}:`,P),w&&(w===Se&&E(P),Gs(P,w))},[Se,Gs]),ao=h.useCallback((w,P)=>{w===Se&&Qs(P)},[Se,Qs]),io=h.useCallback(w=>{re({isOpen:!0,fileId:w.file_id,filename:w.filename,isDeleting:!1})},[]),oo=h.useCallback(()=>{re(w=>w.isDeleting?w:{isOpen:!1,fileId:"",filename:"",isDeleting:!1})},[]),lo=h.useCallback(async()=>{if(!(!Se||!D.fileId)){re(w=>({...w,isDeleting:!0}));try{await Me(Se,D.fileId),E(w=>w.filter(P=>P.file_id!==D.fileId)),re({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}catch(w){const P=w instanceof Error?w.message:m("messageInput.fileRemoveFailed");ye("[MessageInput] Failed to remove file:",w),me(P),re({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}}},[Se,D.fileId,Me,m]),Kn=h.useCallback(w=>w.replace(/\s+/g," ").trim(),[]),Js=h.useCallback(w=>{const P=Kn(w);x(P),bt(),ys(P),Vs(P)},[bt,Vs,Kn,ys]),qr=h.useCallback(w=>{if(w<0)return;const P=Ft[w]||Ft[0];P&&Js(P.text)},[Ft,Js]),co=w=>{if(xe){if(w.key==="ArrowDown"){w.preventDefault(),ze(P=>je.length===0?0:(P+1)%je.length);return}if(w.key==="ArrowUp"){w.preventDefault(),ze(P=>je.length===0?0:(P-1+je.length)%je.length);return}if(w.key==="Home"){w.preventDefault(),ze(0);return}if(w.key==="End"){w.preventDefault(),ze(Math.max(je.length-1,0));return}if((w.key==="Enter"&&!w.shiftKey||w.key==="Tab")&&We){w.preventDefault(),Rn(We);return}if(w.key==="Escape"){w.preventDefault(),Dn();return}}if(ns&&ws){if(w.key==="ArrowDown"){w.preventDefault(),Rr();return}if(w.key==="ArrowUp"){w.preventDefault(),Dr();return}if(w.key==="Tab"){w.preventDefault();const P=mt>=0?mt:0;qr(P);return}if(w.key==="ArrowRight"&&so()){if(Pn&&ks){w.preventDefault(),Js(ks.text);return}if(mt>=0){w.preventDefault(),qr(mt);return}}if(w.key==="Enter"&&mt>=0){w.preventDefault(),qr(mt);return}if(w.key==="Escape"){w.preventDefault(),bt();return}}w.key==="Enter"&&!w.shiftKey&&!y&&(w.preventDefault(),Wn(w))},uo=()=>{et?rs():(bt(),Bs())},fo=()=>{const w=!K.voiceEnabled;le({voiceEnabled:w}),w&&Ut.enableAudio()},ho=h.useCallback(async w=>{if(!Mt||!A||!vs||De)return;const P=w.clipboardData;if(!P||!P.items)return;const pe=Array.from(P.items).filter(Te=>Te.kind==="file");if(pe.length===0)return;const Le=[];if(pe.forEach((Te,Ie)=>{const Jt=Te.getAsFile();Jt&&Le.push(Hu(Jt,Ie))}),Le.length===0)return;w.preventDefault(),X(null),V(null);let Ke=null;try{const Te=ke.getState(),Ie=Te.conversations.find(at=>at.id===Te.currentConversationId);if(((Ie==null?void 0:Ie.attachedFiles)||[]).length+Le.length>oe.maxFilesPerConversation)throw Je&&st.getState().openLoginPrompt(m("fileUpload.maxFilesGuestLimitMessage",{count:oe.maxFilesPerConversation})),new Error(m("fileUpload.maxFilesPerConversationError",{count:oe.maxFilesPerConversation}));if(oe.maxTotalFiles!==null&&Te.conversations.reduce((yt,Ct)=>{var Ge;return yt+(((Ge=Ct.attachedFiles)==null?void 0:Ge.length)||0)},0)+Le.length>oe.maxTotalFiles)throw Je&&st.getState().openLoginPrompt(m("fileUpload.maxTotalFilesGuestLimitMessage",{count:oe.maxTotalFiles})),new Error(m("fileUpload.maxTotalFilesError",{count:oe.maxTotalFiles}));if(!Ie)throw new Error(m("messageInput.conversationNotFoundShort"));if(!Ie.adapterName)throw new Error(m("fileUpload.adapterNotConfigured"));const Zs=it(Ie.apiUrl),er=Ie.adapterName;Ke=Ie.id,H(Ke,!0);const js=[],Yn=[];for(let at=0;at<Le.length;at++){const yt=Le[at],Ct=yt.name||`Clipboard file ${at+1}`,Ge=`${Ct}-${Date.now()}-${at}`;_(gt=>{const Pt=new Map(gt);return Pt.set(Ge,{filename:Ct,progress:0,status:"uploading"}),Pt});const xo=gt=>{_(Pt=>{const dt=new Map(Pt),Cs=dt.get(Ge);return Cs&&dt.set(Ge,{...Cs,filename:Ct,progress:gt.progress,status:gt.status,fileId:gt.fileId}),dt})},bo=()=>new Promise(gt=>{_(Pt=>{const dt=new Map(Pt),Cs=dt.get(Ge);return Cs&&dt.set(Ge,{...Cs,progress:100,status:"completed"}),dt}),setTimeout(()=>{_(Pt=>{const dt=new Map(Pt);return dt.delete(Ge),dt}),gt()},2500)});$(`[MessageInput] Pasting file: ${yt.name}, type: ${yt.type||"unknown"}, size: ${yt.size}`);const yo=await Os.uploadFile(yt,gt=>{$(`[MessageInput] Paste upload progress for ${yt.name}: ${gt.progress}% - ${gt.status}`),xo(gt)},void 0,Zs,er);js.push(yo),Yn.push(bo())}if(js.length>0){let at=js;if(Ke&&Ke===Se){const yt=new Set(b.map(Ge=>Ge.file_id)),Ct=js.filter(Ge=>!yt.has(Ge.file_id));Ct.length>0?(E(Ge=>[...Ge,...Ct]),at=Ct):at=[]}at.length>0&&Gs(at,Ke),await Promise.all(Yn),Qs(js)}}catch(Te){const Ie=Te instanceof Error?Te.message:"Failed to paste file";ye("[MessageInput] Paste error:",Te),Ls("error",K.soundEnabled),X(Ie),Ie.toLowerCase().includes("maximum")&&me(Ie),setTimeout(()=>{X(null)},5e3),_(new Map)}finally{H(Ke,!1)}},[b,Se,A,vs,Je,De,H,K.soundEnabled,Qs,Gs,Mt,m]),Gn=zl(Z==null?void 0:Z.adapterName),mo=Ur||nt?m("messageInput.placeholder.filesUploading"):Gn||(Hn?m("messageInput.placeholder.messageOrbit"):s),Wr=rt?Je?m("messageInput.placeholder.guestLimitTotal",{count:oe.maxTotalMessages}):m("messageInput.placeholder.workspaceLimitTotal",{count:oe.maxTotalMessages}):ms?Je?m("messageInput.placeholder.guestLimitPerConversation",{count:oe.maxMessagesPerConversation}):m("messageInput.placeholder.conversationLimitReached",{count:oe.maxMessagesPerConversation}):mo,Qt=[];rt&&oe.maxTotalMessages!==null&&(Je?Tt&&Qt.push(m("messageInput.limitWarning.guestTotalMessages",{count:oe.maxTotalMessages})):Qt.push(m("messageInput.limitWarning.workspaceTotalMessages",{count:oe.maxTotalMessages}))),ms&&oe.maxMessagesPerConversation!==null&&(Je?Tt&&Qt.push(m("messageInput.limitWarning.guestPerConversation",{count:oe.maxMessagesPerConversation})):Qt.push(m("messageInput.limitWarning.conversationLimitReached",{count:oe.maxMessagesPerConversation}))),ee&&Qt.push(ee),h.useEffect(()=>{!_t||!qt||Ls("error",K.soundEnabled)},[_t,K.soundEnabled,qt]),h.useEffect(()=>{if(!ee)return;const w=setTimeout(()=>me(null),5e3);return()=>clearTimeout(w)},[ee]),h.useEffect(()=>{var w;(L||nt||T.size>0||qs)&&((w=se.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[L,nt,T.size,qs]),h.useEffect(()=>{var w;M&&((w=fe.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[M]),h.useEffect(()=>{var w;xe&&((w=Ne.current)==null||w.scrollIntoView({behavior:"smooth",block:"end"}))},[xe,je.length]);const po=o,go=i?"flex justify-center":"";return a.jsxs(a.Fragment,{children:[a.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 ${go}`,children:a.jsxs("div",{className:`mx-auto w-full ${po}`,children:[qt&&_t&&a.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:[a.jsx(mr,{className:"h-4 w-4 mt-0.5 flex-shrink-0 text-red-500 dark:text-red-400"}),a.jsx("span",{className:"text-sm text-red-700 dark:text-red-300",children:qt})]}),R&&a.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:[a.jsx(mr,{className:"h-4 w-4 mt-0.5 flex-shrink-0 text-red-500 dark:text-red-400"}),a.jsx("span",{className:"text-sm text-red-700 dark:text-red-300",children:R})]}),te&&a.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:[a.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:a.jsx(Nc,{className:"h-3.5 w-3.5 text-emerald-600 dark:text-emerald-400"})}),a.jsx("span",{className:"text-sm text-[#353740] dark:text-[#ececf1]",children:te})]}),Qt.length>0&&a.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:[a.jsx(En,{className:"h-4 w-4 mt-0.5 flex-shrink-0 text-amber-500 dark:text-amber-400"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("ul",{className:"list-none space-y-0.5",children:Qt.map((w,P)=>a.jsx("li",{className:"text-sm text-amber-800 dark:text-amber-200",children:w},`${w}-${P}`))}),Je&&(Bn||Ws)&&Tt&&a.jsx("button",{type:"button",onClick:()=>st.getState().openLoginPrompt(m("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:m("messageInput.signInPrompt.button")})]})]}),a.jsxs("div",{className:"relative w-full",children:[a.jsxs("form",{onSubmit:Wn,className:"flex w-full flex-col gap-2 md:gap-3",children:[a.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:[Be&&a.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:[a.jsx(Ln,{className:"h-3.5 w-3.5 shrink-0 text-gray-500 dark:text-gray-400","aria-hidden":"true"}),a.jsx("span",{className:"min-w-0 truncate font-medium capitalize",children:Be.name.replace(/-/g," ")}),a.jsx("button",{type:"button",onClick:()=>{var w;Kt(),(w=q.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":m("messageInput.selectedSkill.removeAriaLabel"),children:a.jsx(Ye,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),!Be&&Wt.length>0&&g.length===0&&!De&&a.jsxs("button",{type:"button",onClick:to,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("messageInput.skillsHint.ariaLabel"),title:m("messageInput.skillsHint.title"),children:[a.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")]}),a.jsxs("div",{className:"relative flex-1 w-full min-w-0",children:[Zi&&Wr&&a.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(Qe.top-Pu,0),paddingBottom:Qe.bottom,paddingLeft:`${en}px`,paddingRight:0,lineHeight:ut?`${ut}px`:void 0},"aria-hidden":"true",children:Wr}),Or&&A&&a.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(Qe.top-Ru,0),paddingBottom:Qe.bottom,paddingLeft:`${en}px`,paddingRight:0,lineHeight:ut?`${ut}px`:void 0},"aria-hidden":"true",children:[a.jsx("span",{className:"invisible",children:g}),a.jsx("span",{children:Or})]}),a.jsx("textarea",{ref:q,"aria-label":m("messageInput.textarea.ariaLabel"),value:g,onChange:w=>{const P=w.target.value;x(P),P.startsWith("/")&&ze(0),Ae(P.startsWith("/")&&Wt.length>0)},onKeyDown:co,onPaste:ho,onCompositionStart:()=>v(!0),onCompositionEnd:()=>v(!1),onFocus:()=>I(!0),onBlur:()=>I(!1),placeholder:Wr,disabled:De,rows:1,maxLength:oe.maxMessageLength,className:"relative z-10 flex-1 w-full min-w-0 resize-none bg-transparent py-0 text-base md:text-sm text-[#353740] placeholder-transparent focus:outline-none dark:text-[#ececf1] dark:placeholder-transparent",style:{minHeight:"24px",maxHeight:"120px",paddingTop:`${Qe.top}px`,paddingBottom:`${Qe.bottom}px`,paddingLeft:`${en}px`,paddingRight:0,border:"none",outline:"none",boxShadow:"none",WebkitAppearance:"none",MozAppearance:"none",appearance:"none",caretColor:g.trim()||A?"inherit":"transparent"}})]}),a.jsxs("div",{className:"flex items-center justify-end gap-1 md:gap-2 flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[i&&!Mt&&a.jsx("div",{className:"hidden md:block h-8 w-8 shrink-0","aria-hidden":"true"}),Mt&&a.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),Ss||F(!L)},disabled:Ss,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 ${L||$t.length>0?"bg-gray-200 text-[#353740] dark:bg-[#565869] dark:text-[#ececf1]":Ss?"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:vs?Ws&&Un&&oe.maxFilesPerConversation!==null?m("messageInput.fileUpload.titleLimitPerConversation",{count:oe.maxFilesPerConversation}):Ws&&zn&&oe.maxTotalFiles!==null?m("messageInput.fileUpload.titleLimitWorkspace",{count:oe.maxTotalFiles}):De?m("messageInput.fileUpload.titleUploading"):$t.length>0?m("messageInput.fileUpload.titleAttached",{count:$t.length}):m("messageInput.fileUpload.attachAriaLabel"):m("messageInput.fileUpload.titleNotSupported"),"aria-label":m("messageInput.fileUpload.attachAriaLabel"),children:Ss&&O?a.jsx(Ye,{className:"h-4 w-4"}):a.jsx(qc,{className:"h-4 w-4"})}),g.length>0&&a.jsx("div",{className:"hidden md:block px-2 text-xs text-gray-500 dark:text-[#bfc2cd] md:min-w-[72px] md:text-right",children:a.jsxs("span",{className:g.length>=oe.maxMessageLength?"text-red-600 font-semibold":"",children:[g.length,"/",oe.maxMessageLength]})})]}),a.jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[a.jsx(Oi,{availableModels:d,defaultModel:u,selectedModel:f,onSelect:w=>p==null?void 0:p(w)}),(gs||_t)&&a.jsxs(a.Fragment,{children:[gs&&a.jsx("button",{type:"button",onClick:fo,className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${K.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:K.voiceEnabled?m("messageInput.voiceOutput.titleEnabled"):m("messageInput.voiceOutput.titleDisabled"),"aria-label":K.voiceEnabled?m("messageInput.voiceOutput.ariaLabelEnabled"):m("messageInput.voiceOutput.ariaLabelDisabled"),children:K.voiceEnabled?a.jsx(kr,{className:"h-5 w-5"}):a.jsx(sd,{className:"h-5 w-5"})}),lt&&a.jsx("button",{type:"button",onClick:uo,disabled:De,onMouseEnter:()=>z(!0),onMouseLeave:()=>z(!1),className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${et?"!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:m(De?"messageInput.voiceInput.titleUploading":et?"messageInput.voiceInput.titleListening":"messageInput.voiceInput.titleDisabled"),"aria-label":m(et?"messageInput.voiceInput.ariaLabelListening":"messageInput.voiceInput.ariaLabelDisabled"),children:et||De&&U?a.jsx(Dc,{className:"h-5 w-5"}):a.jsx(Oc,{className:"h-5 w-5"})})]}),l&&a.jsx("button",{type:"button",onClick:()=>C(!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:m("messageInput.agentInfo.title"),"aria-label":m("messageInput.agentInfo.ariaLabel"),children:a.jsx(xa,{className:"h-5 w-5"})}),(Ur||nt)&&a.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center",children:a.jsx(pr,{className:"h-4 w-4 animate-spin text-gray-500 dark:text-[#bfc2cd]"})}),ft?a.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),Ce()},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:m("messageInput.stop.title"),"aria-label":m("messageInput.stop.ariaLabel"),children:a.jsx(Jc,{className:"h-4 w-4 md:h-3 md:w-3 fill-current"})}):a.jsx("button",{type:"submit",disabled:!zr||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 ${zr&&!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:m("messageInput.submit.title"),"aria-label":m("messageInput.submit.ariaLabel"),children:a.jsx(hn,{className:"h-4 w-4"})})]})]})]}),$t.length>0&&a.jsx("div",{className:"flex flex-wrap gap-2",children:$t.map(w=>{const P=!w.processing_status||w.processing_status==="processing"||w.processing_status==="uploading",ie=w.processing_status==="failed"||w.processing_status==="error";return a.jsxs("div",{className:`flex items-center gap-2 rounded-md border px-2 py-1 text-xs ${ie?"border-red-200 bg-red-50 dark:border-red-800/50 dark:bg-red-950/30":"border-gray-200 bg-white dark:border-[#4a4b54] dark:bg-[#2d2f39]"}`,title:ie?w.error_message||m("messageInput.fileProcessingFailedTitle"):void 0,children:[P&&a.jsx(pr,{className:"h-3 w-3 animate-spin text-blue-500 dark:text-blue-400 flex-shrink-0"}),ie&&a.jsx(mr,{className:"h-3 w-3 text-red-500 dark:text-red-400 flex-shrink-0"}),a.jsx("span",{className:`truncate max-w-[150px] ${ie?"text-red-700 dark:text-red-300":"text-[#353740] dark:text-[#ececf1]"}`,children:w.filename}),P&&a.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:w.processing_status==="uploading"?m("messageInput.attachedFile.uploadingStatus"):m("messageInput.attachedFile.processingStatus")}),ie&&a.jsx("span",{className:"text-xs text-red-500 dark:text-red-400",children:m("messageInput.attachedFile.failedStatus")}),a.jsx("button",{type:"button",onClick:()=>{ie?(Se&&Me(Se,w.file_id),E(pe=>pe.filter(Le=>Le.file_id!==w.file_id))):io(w)},className:"rounded p-2 md:p-0.5 text-gray-500 transition-colors hover:bg-red-50 hover:text-red-600 dark:text-[#bfc2cd] dark:hover:bg-red-900/30 dark:hover:text-red-300",title:m(ie?"messageInput.attachedFile.removeTitleFailed":"messageInput.attachedFile.removeTitleNormal"),children:a.jsx(Ye,{className:"h-4 w-4 md:h-3 md:w-3"})})]},w.file_id)})}),Mt&&(vs||qs)&&a.jsxs("div",{ref:se,className:`rounded-lg border border-gray-200/80 bg-white p-2.5 dark:border-[#3c3f4a] dark:bg-[#2a2b32] transition-all duration-200 ${!L&&!nt&&T.size===0&&!qs?"hidden":""}`,children:[L&&a.jsxs("div",{className:"mb-2 flex items-center justify-between px-1",children:[a.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-[#8e8ea0] uppercase tracking-wider",children:m("messageInput.uploadPanel.headingAttach")}),a.jsx("button",{type:"button",onClick:()=>F(!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:m("messageInput.uploadPanel.closeTitle"),children:a.jsx(Ye,{className:"h-3.5 w-3.5"})})]}),(nt||T.size>0)&&!L&&T.size===0&&a.jsx("div",{className:"mb-2 px-1",children:a.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-[#8e8ea0] uppercase tracking-wider",children:m("messageInput.uploadPanel.headingUploading")})}),T.size>0&&a.jsx("div",{className:"mb-2 space-y-1.5",children:Array.from(T.entries()).map(([w,P])=>a.jsxs("div",{className:"group relative w-full flex items-center gap-3 rounded-lg px-3 py-2.5 bg-gray-50 dark:bg-[#1f1f24] overflow-hidden transition-colors",children:[a.jsx("div",{className:"absolute inset-0 bg-blue-50 dark:bg-blue-900/15 transition-all duration-500 ease-out rounded-lg",style:{width:`${P.progress??0}%`}}),a.jsxs("div",{className:"relative flex items-center gap-3 w-full min-w-0",children:[a.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-blue-100 dark:bg-blue-900/30",children:a.jsx(pr,{className:"h-4 w-4 text-blue-600 dark:text-blue-400 animate-spin"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium text-[#353740] dark:text-[#ececf1] truncate",children:P.filename}),a.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 bg-gray-200 dark:bg-[#3c3f4a] rounded-full h-1",children:a.jsx("div",{className:"bg-blue-500 dark:bg-blue-400 h-1 rounded-full transition-all duration-500 ease-out",style:{width:`${P.progress??0}%`}})}),a.jsxs("span",{className:"text-[11px] tabular-nums text-gray-400 dark:text-[#8e8ea0] shrink-0",children:[Math.round(P.progress??0),"%"]})]})]}),a.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-[#bfc2cd] shrink-0",children:P.status==="uploading"?m("messageInput.uploadProgress.statusUploading"):P.status==="processing"?m("messageInput.uploadProgress.statusProcessing"):P.status==="completed"?m("messageInput.uploadProgress.statusCompleted"):m("messageInput.uploadProgress.statusPending")})]})]},w))}),a.jsx("div",{className:`${L||nt?"block max-h-[40vh] overflow-y-auto":"hidden"}`,"aria-hidden":!(L||nt),children:a.jsx($u,{conversationId:Se,onFilesSelected:no,onUploadError:w=>{ye("File upload error:",w),me(w)},onUploadingChange:H,onUploadSuccess:ao,maxFiles:oe.maxFilesPerConversation,disabled:Ss})})]}),a.jsx("div",{className:"h-3 md:h-1",children:lt&&et&&a.jsxs("span",{className:"flex items-center gap-2 text-sm md:text-xs text-gray-500 dark:text-[#bfc2cd]",children:[a.jsx("span",{className:"h-2.5 w-2.5 md:h-2 md:w-2 animate-pulse rounded-full bg-red-500"}),m("messageInput.listeningIndicator")]})})]}),xe&&a.jsx("div",{ref:Ne,className:"w-full pt-1",children:a.jsx(Di,{skills:Wt,isLoading:Pr,selectedSkill:Be,activeSkillName:We==null?void 0:We.name,query:be,onActiveSkillChange:w=>{const P=je.findIndex(ie=>ie.name===w.name);P>=0&&ze(P)},onSelect:Rn,onClose:Dn})}),M&&a.jsx("div",{ref:fe,role:"listbox","aria-label":m("messageInput.autocompletePanel.ariaLabel"),className:"w-full pt-1",children:Ft.map((w,P)=>{const ie=P===mt;return a.jsx("button",{type:"button",role:"option","aria-selected":ie,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 ${ie?"bg-gray-100 dark:bg-[#2d2f39]":"hover:bg-gray-50 dark:hover:bg-[#2d2f39]/60"}`,onClick:()=>Js(w.text),onMouseEnter:()=>Gt(P),children:eo(w.text)},P)})}),a.jsx(Sr,{isOpen:D.isOpen,onClose:oo,onConfirm:lo,title:m("messageInput.fileDelete.title"),message:m("messageInput.fileDelete.message",{filename:D.filename}),confirmText:m("messageInput.fileDelete.confirmText"),cancelText:m("common.cancel"),type:"danger",isLoading:D.isDeleting})]})]})}),S&&l&&typeof document<"u"&&Ir.createPortal(a.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:a.jsxs("div",{ref:Q,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:[a.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-[#2d2f39]",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/20 flex items-center justify-center",children:a.jsx(xa,{className:"w-5 h-5 text-blue-500"})}),a.jsx("h2",{id:"agent-info-title",className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:m("messageInput.agentInfoModal.title")})]}),a.jsx("button",{type:"button",onClick:()=>C(!1),className:"p-2 hover:bg-gray-100 dark:hover:bg-[#25262f] rounded-lg transition-colors","aria-label":m("messageInput.agentInfoModal.closeAriaLabel"),children:a.jsx(Ye,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),a.jsx("div",{className:"p-6",children:a.jsx(It,{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 ${Pe}`,syntaxTheme:_e})}),a.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:a.jsx("button",{type:"button",onClick:()=>C(!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:m("messageInput.agentInfoModal.confirmButton")})})]})}),document.body)]})}function Va({adapter:t,onSelect:e}){var l;const{t:s}=Ee(),n=(l=t.description)==null?void 0:l.trim(),{isDark:r}=ds(),i=r?"dark":"light",o=()=>e(t);return a.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:[a.jsx("div",{className:"relative",children:a.jsx("div",{className:"min-w-0",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"truncate text-[15px] font-semibold text-sky-900 dark:text-sky-300 md:text-base",children:t.name}),n?a.jsx("div",{className:"mt-1 text-sm leading-5 text-slate-600 dark:text-slate-300",children:a.jsx(It,{content:n,className:"prose prose-slate max-w-none text-inherit dark:prose-invert [&>*]:mb-0 [&>*]:mt-0 [&_p]:overflow-hidden [&_p]:text-ellipsis [&_p]:[display:-webkit-box] [&_p]:[-webkit-box-orient:vertical] [&_p]:[-webkit-line-clamp:4]",syntaxTheme:i})}):a.jsx("p",{className:"mt-1 text-sm leading-5 text-slate-500 dark:text-slate-400",children:s("agentCard.configureMessage")})]}),a.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:a.jsx(ga,{className:"h-4 w-4","aria-hidden":"true"})})]})})}),a.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:a.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:a.jsx(ga,{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},Vu=t=>{if(!t||typeof t!="object")return null;const e=t,s=Zt(e.name);if(!s)return null;const n=Zt(e.id);if(!n)return console.warn(`[middlewareConfig] Adapter "${s}" is missing a required 'id' field — skipping.`),null;const r=Zt(e.apiUrl),i=Zt(e.model),o=Zt(e.inputPlaceholder),l=typeof e.notes=="string"?e.notes.trim():void 0;let c=Zt(e.description)||Zt(e.summary);if(!c&&typeof l=="string"){const u=l.split(/\r?\n/).find(f=>f.trim().length>0);c=u?u.trim():void 0}const d={id:n,name:s};return r&&(d.apiUrl=r),c&&(d.description=c),l&&(d.notes=l),i&&(d.model=i),o&&(d.inputPlaceholder=o),d},zi=t=>Array.isArray(t)?t.map(Vu).filter(e=>e!==null):[];let Dt=null,tn=0;const qu=3e4;function Wu(){if(typeof window<"u"){const t=window.ORBIT_CHAT_CONFIG;if(t!=null&&t.adapters&&Array.isArray(t.adapters)){$("Loading adapters from window.ORBIT_CHAT_CONFIG");const e=zi(t.adapters);if(e.length===0)return null;const s=`{
327
+ "simple-chat": "default-key",
328
+ "web-search": "orbit_XfxmYoTZgnp7zoMTKsIBfMBuYwj6U21P",
329
+ "chat-with-files": "multimodal",
330
+ "hr-db-chatbot": "human-resources",
331
+ "intent-sql-sqlite-classified": "classified",
332
+ "ecomm-analytics": "analytical",
333
+ "intent-duckdb-ev-population": "electric-vehicle",
334
+ "intent-http-jsonplaceholder": "rest-json-api",
335
+ "intent-http-paris-opendata": "paris-opendata",
336
+ "intent-mongodb-mflix": "mongodb-mflix",
337
+ "intent-graphql-spacex": "graphql-spacex",
338
+ "intent-sql-postgres": "postgres-customer-orders",
339
+ "open-ai-real-time-voice-chat": "open-ai-real-time-voice-chat",
340
+ "composite-multi-source-explorer": "composite-multi-source-explorer",
341
+ "math-teacher-quadratic": "math-teacher-trig-identities",
342
+ "qa-sql": "orbit_g6QuN5sPUh3fI2v0njoOJroXbAh1ILGP",
343
+ "qa-vector-chroma": "orbit_Rxm90sh85f8l5bzOLJpqpMUP9HcoNAX3",
344
+ "image-generator": "orbit_bZQ0h6kvpTphfCr9QgrCP13dkVclAsKQ",
345
+ "video-generator": "orbit_9P1vnx1GNMvVNyNCKF71VvVvcYx9duuo",
346
+ "intent-elasticsearch-log": "orbit_Ghpo8Q9mRdvVIODdw97ht7lBPpYBAzb6",
347
+ "audio-transcription": "orbit_RTBIwFoB6DA2mBuuHfnKf0xabwE6XKs2",
348
+ "voice-chat": "orbit_WjrkTqVjHE7mBa2ri8sAjENEVnLT9wbO",
349
+ "real-time-voice-chat": "orbit_xkvziKTXpZ1ufHWKg76pUDPbMDBRSRqC",
350
+ "tender-notices": "tender-notices",
351
+ "award-notices": "award-notices",
352
+ "contract-history": "contract-history",
353
+ "standing-offers": "standing-offers"
354
+ }`;if(!s.trim())return[];try{const n=JSON.parse(s),r=new Set(Object.entries(n).filter(([,i])=>{if(typeof i=="string")return i.trim().length>0;if(i&&typeof i=="object"){const o=i;if(typeof o.apiKey=="string"&&o.apiKey.trim().length>0||typeof o.key=="string"&&o.key.trim().length>0)return!0}return!1}).map(([i])=>i));return e.filter(i=>r.has(i.id))}catch{return[]}}}return null}async function Mn(){if(Dt&&Date.now()-tn<qu)return Dt;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(),n=zi(s.adapters);if(n.length>0)return Dt=n,tn=Date.now(),$("Fetched adapters from /api/adapters:",Dt),Dt;$("/api/adapters response did not contain valid adapters, trying fallback")}$(`/api/adapters returned ${e.status}, trying fallback`)}catch(e){$("Could not fetch from /api/adapters, trying fallback:",e)}const t=Wu();if(t&&t.length>0)return Dt=t,tn=Date.now(),$("Loaded adapters from config:",Dt),Dt;throw ye("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 Ku="h-[96px]";function Gu({onAdapterSelect:t,className:e="",title:s="",subtitle:n="",eyebrow:r=""}){const{t:i}=Ee(),[o,l]=h.useState([]),[c,d]=h.useState(!0),[u,f]=h.useState(null),p=h.useRef(null),m=h.useRef(null),[g,x]=h.useState(""),[y,v]=h.useState(!1),A=h.useCallback(()=>{const j=p.current;if(!j){v(!1);return}v(j.scrollHeight-j.scrollTop-j.clientHeight>20)},[]),I=()=>typeof window<"u"&&window.matchMedia("(min-width: 768px)").matches,S=()=>{var j;return Array.from(((j=p.current)==null?void 0:j.querySelectorAll('[data-agent-card="true"]'))??[])},C=j=>{const z=S()[j]??null;z&&(z.focus(),z.scrollIntoView({block:"nearest"}))},L=()=>{C(0)},F=()=>{const j=S();j.length!==0&&C(j.length-1)},b=j=>{if(!c&&!u&&N.length>0&&I()){if(j.key==="Tab"&&!j.shiftKey){j.preventDefault(),L();return}if(j.key==="ArrowDown"){j.preventDefault(),L();return}j.key==="ArrowUp"&&(j.preventDefault(),F())}},E=j=>{var X;if(!T||!I()||j.key!=="ArrowDown"&&j.key!=="ArrowUp")return;const U=document.activeElement;if(!(U instanceof HTMLElement)||U.dataset.agentCard!=="true")return;const z=S(),R=z.indexOf(U);if(R!==-1){if(j.preventDefault(),j.key==="ArrowDown"){C((R+1)%z.length);return}if(R===0){(X=m.current)==null||X.focus();return}C(R-1)}},k=g.trim().toLowerCase(),N=k?o.filter(j=>{var X,te;const U=j.name.toLowerCase().includes(k),z=((X=j.description)==null?void 0:X.toLowerCase().includes(k))??!1,R=((te=j.model)==null?void 0:te.toLowerCase().includes(k))??!1;return U||z||R}):o,T=g.trim().length>0,_=T||N.length===1;h.useEffect(()=>{const j=p.current;if(j)return A(),j.addEventListener("scroll",A,{passive:!0}),()=>j.removeEventListener("scroll",A)},[A,N]),h.useEffect(()=>{let j=!0;return(async()=>{try{d(!0),f(null);const R=(await Mn()).slice().sort((X,te)=>X.name.localeCompare(te.name,void 0,{sensitivity:"base"}));j&&l(R)}catch(z){ye("[AgentSelectionList] Failed to load adapters",z),j&&f(i("agentSelectionList.unableToLoad"))}finally{j&&d(!1)}})(),()=>{j=!1}},[i]),h.useEffect(()=>{var j;c||u||o.length===0||(j=m.current)==null||j.focus()},[c,u,o.length]);const O=()=>c?a.jsx("div",{className:"grid gap-4",children:Array.from({length:3}).map((j,U)=>a.jsx("div",{className:`${Ku} animate-pulse rounded-2xl border border-gray-200 bg-transparent dark:border-[#3b3c49]`},U))}):u?a.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?a.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:i("agentSelectionList.noAgentsAvailable")}):N.length===0?a.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:i("agentSelectionList.noSearchResults")}):a.jsxs("div",{className:"relative flex flex-col h-full min-h-0",children:[a.jsx("div",{ref:p,onKeyDown:E,className:"agent-selection-scroll flex-1 min-h-0 overflow-y-auto pr-1 pb-2",children:_?a.jsx("div",{className:"mx-auto flex w-full max-w-xl flex-col gap-3 lg:max-w-2xl",children:N.map(j=>a.jsx(Va,{adapter:j,onSelect:U=>t(U.id)},j.id))}):a.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:N.map(j=>a.jsx(Va,{adapter:j,onSelect:U=>t(U.id)},j.id))})}),y&&a.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 a.jsxs("div",{className:`flex w-full flex-col gap-4 md:gap-6 ${e}`,children:[(r||s||n)&&a.jsxs("div",{className:"flex-shrink-0",children:[r&&a.jsx("p",{className:"text-sm font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-300",children:r}),s&&a.jsx("h2",{className:"mt-2 text-2xl font-bold text-gray-900 dark:text-white",children:s}),n&&a.jsx("p",{className:"mt-2 text-base text-gray-600 dark:text-gray-300",children:n})]}),a.jsx("div",{className:"flex w-full flex-shrink-0 justify-center",children:a.jsx("div",{className:"w-full max-w-xl lg:max-w-2xl",children:a.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:[a.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))]"}),a.jsx(In,{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"}),a.jsx("input",{ref:m,type:"text",placeholder:i("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&&a.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":i("agentSelectionList.clearSearchAriaLabel"),children:a.jsx(Ye,{className:"h-3.5 w-3.5"})})]})})}),a.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:O()})]})}function bn(){return Cn()?_r()==="entra"?a.jsx(Yu,{}):a.jsx(Xu,{}):null}function Xu(){const{user:t,logout:e,loginWithRedirect:s}=kn();if(!fs()||!t)return a.jsx(Bi,{onClick:()=>s()});const r=t.name||t.email||"User";return a.jsx(Hi,{displayName:r,onClick:()=>e({logoutParams:{returnTo:window.location.origin}})})}function Yu(){const{instance:t,accounts:e}=wn();if(!fs()||e.length===0)return a.jsx(Bi,{onClick:()=>t.loginRedirect({scopes:Nn()}).catch(()=>{})});const n=e[0],r=n.name||n.username||"User";return a.jsx(Hi,{displayName:r,onClick:()=>t.logoutRedirect({postLogoutRedirectUri:window.location.origin}).catch(()=>{})})}function Bi({onClick:t}){const{t:e}=Ee();return a.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:[a.jsx(vi,{className:"h-4 w-4"}),a.jsx("span",{children:e("common.signIn")})]})}function Hi({displayName:t,onClick:e}){const{t:s}=Ee();return a.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-sm text-gray-600 dark:text-[#bfc2cd]",children:[a.jsx("span",{className:"hidden max-w-[170px] truncate font-medium md:block",title:t,children:t}),a.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:[a.jsx($c,{className:"h-4 w-4"}),a.jsx("span",{className:"hidden md:inline",children:s("common.logOut")})]})]})}function Vi({placement:t="default",compact:e=!1}){const{t:s}=Ee();if(!xi())return null;const n=uc(),r=fc(),i=hc(),o=mc(),l=pc(),c=gc(),d=bc(),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",p=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",m="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 a.jsx("footer",{className:`shrink-0 bg-white dark:bg-black text-sm ${f} ${u}`.trim(),style:{backgroundColor:r||void 0,color:i||void 0},children:a.jsx("div",{className:g,children:a.jsx("div",{className:x,children:a.jsxs("div",{className:p,children:[n&&a.jsx("p",{className:`${e?"text-xs leading-snug":"text-sm"} text-slate-700 dark:text-slate-200 ${t==="sidebar"?"pt-0.5":""}`.trim(),children:n}),d.length>0&&a.jsx("nav",{"aria-label":s("appFooter.navLinksAriaLabel"),children:a.jsx("ul",{className:`flex flex-wrap items-center ${m} ${e?"gap-1":"gap-1.5 sm:gap-2"}`,children:d.map((v,A)=>{const I=l==="inline"&&A>0;return a.jsxs("li",{className:"flex items-center",children:[I&&a.jsx("span",{className:"mr-1.5 text-slate-400 dark:text-slate-500","aria-hidden":"true",children:"·"}),a.jsx("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",className:y,style:{color:i||void 0},children:v.label})]},v.url)})})})]})})})})}const Qu=60*1e3;let sn=null,qa=0;const rn=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},qi=()=>{if(typeof window>"u")return rn("/");const t=rn("/");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 rn(s.pathname||t)}catch{return t}},Ar=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),Ju=async()=>{const t=Date.now();if(sn&&t-qa<Qu)return sn;let e=[];try{e=await Mn()}catch(n){ge("[agentRouting] Unable to load adapters for slug resolution",n)}const s=new Map;return e.forEach(n=>{const r=Ar(n.name);r&&s.set(r,n.id);const i=Ar(n.id);i&&i!==r&&s.set(i,n.id)}),sn=s,qa=t,s},yn=t=>{var i;const e=qi(),s=t.startsWith("/")?t:`/${t}`;let n=s;if(e!=="/"){if(!s.startsWith(e))return null;n=s.slice(e.length)}const r=n.split("/").filter(Boolean);return r.length===0?null:((i=r[0])==null?void 0:i.toLowerCase())||null},Wi=t=>{const e=qi();if(!t)return e;const s=t.replace(/^\/+|\/+$/g,"");return e==="/"?s?`/${s}`:"/":`${e}/${s}`.replace(/\/{2,}/g,"/")},kt=t=>{if(typeof window>"u")return;const e=Wi(t),s=window.location.pathname;if(e===s)return;const n=window.location.search||"",r=window.location.hash||"";window.history.replaceState(window.history.state,"",`${e}${n}${r}`)},Zu=()=>Wi(null),ef=async t=>{const e=t.trim().toLowerCase();return e&&(await Ju()).get(e)||null};function tf({currentConversation:t,showEmptyState:e,createConversation:s,configureApiSettings:n,clearError:r,clearCurrentConversationAdapter:i}){var Ne;const{t:o}=Ee(),l=o("agent.error.singleAdapterMissing"),[c,d]=h.useState(!1),[u,f]=h.useState(null),p=Tr(),m=vn(),g=typeof window<"u"?yn(window.location.pathname):null,[x,y]=h.useState(g),[v,A]=h.useState(()=>!p&&e&&!g),I=h.useRef(null),S=h.useRef(new Map),C=h.useRef(0),L=3e4,F=!!t,b=(t==null?void 0:t.messages.length)??0,E=((Ne=t==null?void 0:t.attachedFiles)==null?void 0:Ne.length)??0,k=h.useMemo(()=>F&&(b>0||E>0),[E,b,F]),N=h.useCallback(()=>{He(()=>ke.getState())},[]),T=h.useCallback((B,W)=>{if(!B)return;const J=W||o("agent.error.configurationFailed");let we=!1;ke.setState(ne=>{const K=ne.conversations.find(le=>le.id===B);return!K||K.messages.length>0?ne:(we=!0,{conversations:ne.conversations.map(le=>le.id===B?{...le,adapterLoadError:J}:le)})}),we&&N()},[N,o]),_=h.useCallback(B=>{if(!B)return;let W=!1;ke.setState(J=>{const we=J.conversations.find(ne=>ne.id===B);return!we||!we.adapterLoadError?J:(W=!0,{conversations:J.conversations.map(ne=>ne.id===B?{...ne,adapterLoadError:null}:ne)})}),W&&N()},[N]),O=h.useCallback(B=>B instanceof _i?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=ke.getState(),W=B.currentConversationId?B.conversations.find(J=>J.id===B.currentConversationId):null;if(!W||W.messages.length>0)try{return s()}catch(J){ge("Cannot create a new conversation for agent selection:",J instanceof Error?J.message:"Unknown error")}return(W==null?void 0:W.id)||null},[s]),U=h.useCallback(async B=>{if(!(B!=null&&B.adapterName))return{ok:!1};try{const W=await Fe(),J=new W.ApiClient({apiUrl:B.apiUrl||$e(),sessionId:null,adapterName:B.adapterName});if(typeof J.getAdapterInfo!="function")return{ok:!1};const we=await J.getAdapterInfo();return ke.setState(ne=>({conversations:ne.conversations.map(K=>K.id===B.id?{...K,adapterInfo:we,adapterLoadError:null,updatedAt:new Date}:K)})),ke.getState().currentConversationId===B.id&&f(null),N(),{ok:!0}}catch(W){const J=O(W),we=ke.getState();we.currentConversationId===B.id&&f({conversationId:B.id,message:J});const ne=we.conversations.find(K=>K.id===B.id);return ne&&ne.messages.length===0&&T(B.id,J),{ok:!1,error:W}}},[O,T,N]),z=h.useCallback(async B=>{if(!B)return;const W=ke.getState(),J=W.currentConversationId?W.conversations.find(we=>we.id===W.currentConversationId):null;if(J){d(!0),f(null),_(J.id);try{const we=J.apiUrl||$e();await n(we,void 0,B),r();const ne=ke.getState(),K=ne.conversations.find(le=>le.id===ne.currentConversationId);if((K==null?void 0:K.adapterName)===B&&(!K.adapterInfo||K.adapterInfo.notes===void 0)){const le=await U(K);!le.ok&&le.error&&ye("Failed to load adapter info after selecting adapter:",le.error)}}catch(we){ye("Failed to configure adapter from empty state:",we);const ne=O(we);f({conversationId:J.id,message:ne}),T(J.id,ne)}finally{d(!1)}}},[_,r,n,U,O,T]),R=h.useCallback(B=>{p||(j(),A(!1),kt(Ar(B)),z(B))},[j,z,p]),X=h.useCallback(()=>{p||(i(),kt(null),A(!0))},[i,p]),te=h.useCallback(()=>{var we,ne;if(p){const K=ke.getState(),le=K.currentConversationId?K.conversations.find(ue=>ue.id===K.currentConversationId):null;if(!!le&&(le.messages.length>0||(((we=le.attachedFiles)==null?void 0:we.length)||0)>0))try{s()}catch(ue){ge("Cannot go home (new conversation):",ue instanceof Error?ue.message:"Unknown error")}kt(null),A(!1);return}y(null);const B=ke.getState(),W=B.currentConversationId?B.conversations.find(K=>K.id===B.currentConversationId):null;if(!!W&&(W.messages.length>0||(((ne=W.attachedFiles)==null?void 0:ne.length)||0)>0))try{s()}catch(K){ge("Cannot go home (new conversation):",K instanceof Error?K.message:"Unknown error");return}else W!=null&&W.adapterName&&i();kt(null),A(!0)},[i,s,p]),ee=!p&&e&&!x&&!(t!=null&&t.adapterName)&&!k||!p&&e&&v&&!(t!=null&&t.adapterName)&&!k;h.useEffect(()=>{if(p){kt(null);return}if(!x){if(ee||!(t!=null&&t.adapterName)){kt(null);return}kt(Ar(t.adapterName))}},[t==null?void 0:t.adapterName,p,x,ee]);const me=h.useCallback(async()=>{if(typeof window>"u")return;const B=++C.current;if(p){kt(null),y(null);return}const W=yn(window.location.pathname);if(!W)return;const J=await ef(W);if(B===C.current){if(!J){j(),kt(null),i(),A(!0),y(null);return}j(),A(!1),kt(W),await z(J),y(null)}},[i,j,z,p]),D=h.useRef(me);h.useEffect(()=>{D.current=me},[me]),h.useEffect(()=>{const B=window.setTimeout(()=>{D.current()},0),W=()=>{D.current()};return window.addEventListener("popstate",W),()=>{window.clearTimeout(B),C.current+=1,window.removeEventListener("popstate",W)}},[]);const re=t==null?void 0:t.id,q=t==null?void 0:t.adapterName,Q=t==null?void 0:t.apiUrl,se=!!(t!=null&&t.adapterInfo);h.useEffect(()=>{if(!p||!m||!e||!re||k||c)return;const B=(q==null?void 0:q.trim())||m,W=(q==null?void 0:q.trim())!==B||!se;if(!B||!W)return;let J=!1;return(async()=>{d(!0),f(null),_(re);try{const ne=Q||$e();await n(ne,void 0,B),r()}catch(ne){if(!J){const K=O(ne);f({conversationId:re,message:K}),T(re,K)}}finally{J||d(!1)}})(),()=>{J=!0}},[_,r,n,k,O,c,p,T,e,q,Q,se,re,m]),h.useEffect(()=>{(async()=>{var we;const W=t==null?void 0:t.adapterName;if(I.current===W)return;const J=!(t!=null&&t.adapterInfo)||(t==null?void 0:t.adapterInfo)&&t.adapterInfo.notes===void 0;if(W&&J){I.current=W,$("[ChatInterface] Loading adapter info - adapterName:",W,"reason:",t!=null&&t.adapterInfo?"notes undefined":"missing");const ne=await U(t);if(ne.ok)$("[ChatInterface] Adapter info loaded successfully");else{const K=ne.error;ye("[ChatInterface] Failed to load adapter info:",K);const le=K instanceof Error?K.message:String(K);if((le.includes("429")||le.includes("Too Many Requests"))&&W){const ue=S.current.get(W);ue&&clearTimeout(ue);const Pe=setTimeout(()=>{I.current===W&&(I.current=null),S.current.delete(W)},L);S.current.set(W,Pe),ge(`[ChatInterface] Adapter info request rate-limited; retrying in ${L/1e3}s`)}else I.current=null}}else $("[ChatInterface] Skipping adapter info load:",{adapterName:W,hasAdapterInfo:!!(t!=null&&t.adapterInfo),hasNotes:((we=t==null?void 0:t.adapterInfo)==null?void 0:we.notes)!==void 0,refValue:I.current})})()},[U,t]),h.useEffect(()=>{const B=S.current;return()=>{B.forEach(W=>clearTimeout(W)),B.clear()}},[]);const fe=p&&!m?l:(t==null?void 0:t.adapterLoadError)??((u==null?void 0:u.conversationId)===(t==null?void 0:t.id)?u.message:null);return{adapterNotesError:fe,handleAgentCardSelection:R,handleChangeAgent:X,goToAgentSelectionHome:te,hasAdapterConfigurationError:!!fe,isAgentSelectionVisible:v,isConfiguringAdapter:c,isSingleAdapterMode:p,setIsAgentSelectionVisible:A,shouldShowAgentSelectionList:ee}}const Ki=h.createContext(null),sf={registerGoHome:()=>{},goHome:()=>{}};function Gi(){return h.useContext(Ki)??sf}function rf({adapter:t,syntaxTheme:e,forcedThemeClass:s=""}){var r;const n=(r=t.notes)==null?void 0:r.trim();return n?a.jsxs("section",{"aria-labelledby":"agent-seo-content-title",className:"mx-auto w-full max-w-[56rem] px-1 text-left sm:px-0",children:[a.jsx("h2",{id:"agent-seo-content-title",className:"sr-only",children:t.name}),a.jsx("div",{children:a.jsx(It,{content:n,className:`message-markdown prose prose-slate dark:prose-invert max-w-none text-sm leading-relaxed text-[#434654] dark:text-[#d7dae3] [&>:first-child]:mt-0 [&>:last-child]:mb-0 ${s}`,syntaxTheme:e})})]}):null}const nf='meta[name="description"]',af='meta[property="og:title"]',of='meta[property="og:description"]',lf='meta[property="og:type"]',cf='link[rel="canonical"]';function Wa(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function df(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 uf(t,e){const s=t==null?void 0:t.trim();if(s)return s;if(!e)return jn();const n=df(e);return n.length>160?`${n.slice(0,157).trimEnd()}...`:n}function ff(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hf(t){const e=t.trim();if(!e)return null;try{return new URL(e).origin}catch{return null}}function mf(t){const e=t.trim();if(!e)return null;const s=`^${ff(e).replace(/\\\*/g,".*")}$`;try{return new RegExp(s,"i")}catch{return null}}function pf(t){return[fi(),...Bl()].map(hf).filter(s=>!!s).includes(t)?!0:Hl().some(s=>{const n=mf(s);return n?n.test(t):!1})}function gf(t){var n,r,i;const e=t==null?void 0:t.trim();if(!e)return null;const s=Y.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:((n=s.name)==null?void 0:n.trim())||s.id,description:((r=s.description)==null?void 0:r.trim())||void 0,notes:((i=s.notes)==null?void 0:i.trim())||void 0}:null}function xf(t){var n,r,i;if(typeof window>"u")return null;const e=yn(window.location.pathname);if(!e)return null;const s=Y.adapters.find(o=>{const l=Wa(o.name||""),c=Wa(o.id||"");return e===l||e===c});return s?{id:s.id,name:((n=s.name)==null?void 0:n.trim())||s.id,description:((r=s.description)==null?void 0:r.trim())||void 0,notes:((i=s.notes)==null?void 0:i.trim())||void 0}:null}function ur(t,e,s){if(typeof document>"u")return null;const n=document.querySelector(t);if(n)return n;const r=document.createElement("meta");return r.setAttribute(e,s),document.head.appendChild(r),r}function bf(){if(typeof document>"u")return null;const t=document.querySelector(cf);if(t)return t;const e=document.createElement("link");return e.rel="canonical",document.head.appendChild(e),e}function Xi(t){if(typeof document>"u")return;const e=Sn(),s=t?`${t.name} | ${e}`:e,n=t?uf(t.description,t.notes):jn();document.title=s;const r=ur(nf,"name","description");r&&(r.content=n);const i=ur(af,"property","og:title");i&&(i.content=s);const o=ur(of,"property","og:description");o&&(o.content=n);const l=ur(lf,"property","og:type");l&&(l.content="website");const c=bf();if(c&&typeof window<"u"){const d=fi(),u=window.location.origin,f=d?new URL(d.endsWith("/")?d:`${d}/`).origin:"",m=`${u&&pf(u)?u:f||u}${window.location.pathname}`;c.href=m}}function yf(){return Vl()}class Fn{static async getAdapterModels(e,s){const n=await Fe(),r=new n.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 Fe(),n=new s.ApiClient({apiUrl:"",adapterName:e});if(!n.getAllModels)throw new Error("getAllModels is not available on this API client");return n.getAllModels()}static async listAdapterModels(e,s){return(await Fn.getAdapterModels(e,s)).models}}const wf="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",kf="shrink-0 sticky bottom-[calc(var(--app-footer-height,0px)+0.25rem)] z-10 -mx-4 mt-auto overflow-visible bg-transparent pb-[max(env(safe-area-inset-bottom),0.5rem)] shadow-none backdrop-blur-0 transition-all duration-200 dark:bg-transparent md:bottom-[calc(var(--app-footer-height,0px)+0.5rem)] md:z-10 md:mx-0 md:mt-0 md:overflow-visible md:rounded-none md:border-0 md:bg-transparent md:pb-0 md:shadow-none md:backdrop-blur-0 md:dark:bg-transparent md:dark:border-0 [&>div]:bg-transparent md:[&>div]:rounded-none md:[&>div]:px-0",vf="relative z-20 shrink-0 -mx-4 px-4 pt-2 pb-2 bg-transparent border-b border-transparent dark:border-transparent dark:bg-transparent md:static md:mx-0 md:px-0 md:pt-6 md:pb-6 md:bg-transparent md:border-gray-200 md:dark:border-[#4a4b54] md:dark:bg-transparent";function Sf({onOpenSettings:t,onOpenSidebar:e}){var Ht,Je,Tt,Vt,Se,Ze,ft;const{t:s}=Ee(),{conversations:n,currentConversationId:r,createConversation:i,canCreateNewConversation:o,sendMessage:l,regenerateResponse:c,editMessageAndRegenerate:d,isLoading:u,configureApiSettings:f,error:p,clearError:m,createThread:g,clearCurrentConversationAdapter:x}=ke(),{settings:y}=Lr(),v=fs(),A=tt()&&!v,{theme:I,isDark:S}=ds(),C=I.mode==="dark"?"dark":I.mode==="light"?"light":"",L=S?"dark":"light",F=["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",C].filter(Boolean).join(" "),b=n.find(de=>de.id===r),E=n.some(de=>{var Ce;return(de.messages.length>0||(((Ce=de.attachedFiles)==null?void 0:Ce.length)||0)>0)&&!de.adapterLoadError}),k=!b||b.messages.length===0,N=((Ht=b==null?void 0:b.adapterInfo)==null?void 0:Ht.supportsThreading)===!0,T=!!(b!=null&&b.adapterName&&(b!=null&&b.adapterInfo))&&!N,_=Mi({adapterName:b==null?void 0:b.adapterName,enabled:T,selectionScopeKey:r,supportsThreading:N}),O=ui(),j=Sn(),U=jn().trim(),z=U.length>0,{registerGoHome:R}=Gi(),[X,te]=h.useState([]),[V,ee]=h.useState(null);h.useEffect(()=>{const de=b==null?void 0:b.adapterName;let Ce=!1;async function Me(){if(ee(null),!de){te([]);return}try{const Z=await Fn.listAdapterModels(de,de);if(Ce)return;te(Z),ee(Z.length>0?Z[0].name:null)}catch{Ce||(te([]),ee(null))}}return Me(),()=>{Ce=!0}},[b==null?void 0:b.adapterName]);const{adapterNotesError:me,handleAgentCardSelection:D,handleChangeAgent:re,goToAgentSelectionHome:q,hasAdapterConfigurationError:Q,isAgentSelectionVisible:se,isConfiguringAdapter:fe,isSingleAdapterMode:Ne,shouldShowAgentSelectionList:B}=tf({currentConversation:b,showEmptyState:k,createConversation:i,configureApiSettings:f,clearError:m,clearCurrentConversationAdapter:x});h.useLayoutEffect(()=>(R(()=>q()),()=>R(null)),[R,q]);const W="max-w-[96rem]",J="max-w-[64rem]",we="max-w-[56rem]",ne=`mx-auto w-full ${W}`,K=o(),le=!!(b!=null&&b.adapterName)&&((b==null?void 0:b.messages.length)||0)===0,ve=s(K?"chatInterface.newConversation.tooltipCanStart":A?"chatInterface.newConversation.tooltipGuestLimited":"chatInterface.newConversation.tooltipCannotStart"),ue=!!(b&&!B),Pe=B?"border-transparent dark:border-transparent md:border-transparent md:dark:border-transparent":"",_e=!fn()&&B?"pt-0 pb-0 md:pt-0 md:pb-1":"",ce=`${vf} ${Pe} ${_e}`.trim(),Ue=xi(),xe=n.some(de=>{var Ce;return(de.messages.length>0||(((Ce=de.attachedFiles)==null?void 0:Ce.length)??0)>0)&&!de.adapterLoadError}),Ae=Ue&&!xe,Lt=B?"pt-0 md:pt-0":"pt-4 md:pt-6",ze=h.useMemo(()=>{var Z,ht,qe;if(B)return null;const de=gf(b==null?void 0:b.adapterName)||xf();if(!de&&!(b!=null&&b.adapterName))return null;const Ce=(Z=b==null?void 0:b.adapterName)==null?void 0:Z.trim(),Me=(qe=(ht=b==null?void 0:b.adapterInfo)==null?void 0:ht.notes)==null?void 0:qe.trim();return de?{...de,notes:Me||de.notes}:Ce?{id:Ce,name:Ce,notes:Me||void 0}:null},[(Je=b==null?void 0:b.adapterInfo)==null?void 0:Je.notes,b==null?void 0:b.adapterName,B]);h.useEffect(()=>{Xi(ze)},[ze]),h.useEffect(()=>{let de=null;const Ce=()=>{de&&(de(),de=null)};if(y.voiceEnabled){if(Ut.isAudioEnabled())return $("[ChatInterface] Audio streaming already enabled"),Ce;const Me=()=>{Ce();const Z=async()=>{Ce(),await Ut.enableAudio()?$("[ChatInterface] Audio streaming enabled after user gesture"):(ge("[ChatInterface] User gesture did not enable audio streaming"),Me())};document.addEventListener("pointerdown",Z,{once:!0}),document.addEventListener("keydown",Z,{once:!0}),de=()=>{document.removeEventListener("pointerdown",Z),document.removeEventListener("keydown",Z)},$("[ChatInterface] Waiting for user gesture to enable audio streaming")};return Me(),Ce}return Ce(),Ut.disableAudio(),$("[ChatInterface] Audio streaming disabled via settings"),Ce},[y.voiceEnabled]);const Qe=(de,Ce,Me,Z)=>{l(de,Ce,Me,V??void 0,Z)},hs=async(de,Ce,Me,Z,ht)=>{await l(Me,void 0,de,ht??V??void 0,Z)},ut=()=>{try{i()}catch(de){ge("Cannot create new conversation:",de instanceof Error?de.message:"Unknown error")}},Et=h.useCallback(async(de,Ce)=>{if(b)try{await ke.getState().deleteThread(b.id,de,Ce)}catch(Me){ye("Failed to clear thread:",Me)}},[b]);return a.jsx("main",{className:"flex-1 flex flex-col bg-transparent overflow-hidden","aria-label":s("chatInterface.workspace.ariaLabel"),children:a.jsx("div",{className:"flex h-full w-full flex-col overflow-hidden px-3 sm:px-5 lg:px-8",children:a.jsxs("div",{className:`mx-auto flex h-full w-full ${W} flex-col overflow-hidden md:pb-4 ${wf}`,children:[p&&a.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:a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsx("p",{children:p}),a.jsx("button",{onClick:m,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:"×"})]})}),a.jsxs("div",{className:ce,children:[e&&a.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2 md:hidden",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("button",{onClick:e,disabled:!E,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 ${E?"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:[a.jsx(Rc,{className:"h-4 w-4"}),s("chatInterface.mobile.chatsButton")]}),a.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:[a.jsx(ya,{className:"h-4 w-4"}),s("chatInterface.mobile.settingsButton")]})]}),a.jsx("div",{className:"ml-auto flex-shrink-0",children:a.jsx(bn,{})})]}),a.jsxs("div",{className:"flex flex-col gap-2 md:gap-4 sm:flex-row sm:items-end sm:justify-between",children:[a.jsx("div",{className:"min-w-0 flex-1",children:ue&&a.jsx("div",{className:"space-y-1.5 md:space-y-3",children:a.jsxs("div",{className:"md:space-y-1",children:[a.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[a.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&&a.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&&a.jsx("div",{className:"hidden md:flex items-center text-sm text-gray-500 dark:text-[#bfc2cd]",children:a.jsx("span",{children:s("chatInterface.updatedAt",{time:b.updatedAt.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})})})]})})}),a.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:[a.jsx("div",{className:"hidden flex-shrink-0 items-center md:inline-flex",children:a.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:a.jsx(ya,{className:"h-4 w-4"})})}),!Ne&&!B&&!!(b!=null&&b.adapterName)&&a.jsx("button",{type:"button",onClick:()=>{le&&re()},disabled:!le,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 ${le?"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(le?"chatInterface.changeAgent.titleEnabled":"chatInterface.changeAgent.titleDisabled"),children:s("chatInterface.changeAgent.button")}),!B&&a.jsxs("button",{onClick:ut,disabled:!K,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 ${K?"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:ve,children:[a.jsx(Gc,{className:"h-3.5 w-3.5"}),s("chatInterface.newConversation.button")]}),!fn()&&a.jsx("div",{className:"order-4 hidden flex-shrink-0 items-center md:inline-flex",children:a.jsx(bn,{})})]})]})]}),k?a.jsxs("div",{className:`flex flex-1 flex-col min-h-0 ${Lt} ${B?"overflow-hidden":""}`,children:[B?a.jsx("div",{className:"flex-1 flex flex-col md:justify-start min-h-0 overflow-hidden",children:a.jsx("div",{className:"w-full flex flex-col min-h-0 overflow-hidden flex-1",children:a.jsxs("div",{className:"flex flex-col min-h-0 flex-1 gap-3 overflow-hidden md:gap-6",children:[a.jsx("div",{className:`${ne} flex-shrink-0 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between`,children:a.jsxs("div",{className:"flex-1",children:[a.jsx(It,{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:L}),z&&a.jsx("div",{className:"mt-2",children:a.jsx(It,{content:U,className:F,syntaxTheme:L})})]})}),a.jsx(Gu,{onAdapterSelect:D,className:`${ne} md:flex-1 md:min-h-0 md:overflow-hidden`})]})})}):a.jsx("div",{className:"flex flex-1 w-full min-h-0 flex-col overflow-y-auto pt-4 md:pt-6",children:a.jsxs("div",{className:`mx-auto flex w-full ${we} flex-col items-center gap-4 pb-8 md:gap-5 md:pb-12`,children:[me?a.jsx("p",{className:"w-full text-center text-sm text-red-600 dark:text-red-400",children:me}):b!=null&&b.adapterName?a.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:Ul(b.adapterName)||b.adapterName}):fe?a.jsx("p",{className:"w-full text-center text-sm text-gray-500 dark:text-[#bfc2cd]",children:s("chatInterface.empty.configuringAgent")}):null,ze&&yf()&&a.jsx(rf,{adapter:ze,syntaxTheme:L,forcedThemeClass:C}),a.jsx("div",{className:"w-full min-w-0",children:a.jsx(Ha,{onSend:Qe,disabled:u||!b||!(b!=null&&b.adapterName)||Q,autoFocusEnabled:!0,placeholder:O,isCentered:!0,maxWidthClass:we,adapterNotes:(Tt=b==null?void 0:b.adapterInfo)==null?void 0:Tt.notes,skillState:_,availableModels:X,defaultModel:((Vt=b==null?void 0:b.adapterInfo)==null?void 0:Vt.model)??null,selectedModel:V,onSelectModel:ee})})]})}),Ae&&a.jsx("div",{className:"shrink-0 pt-5 md:pt-6",children:a.jsx(Vi,{compact:!0})})]}):a.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[a.jsx(ju,{messages:b.messages,onRegenerate:de=>c(de,V??void 0),onEditMessage:(de,Ce)=>d(de,Ce,V??void 0),onStartThread:async(de,Ce)=>{try{await g(de,Ce)}catch(Me){ye("Failed to create thread:",Me)}},onClearThread:Et,onSendThreadMessage:hs,sessionId:b.sessionId,isLoading:u,contentMaxWidthClass:J,availableModels:X,defaultModel:((Se=b==null?void 0:b.adapterInfo)==null?void 0:Se.model)??null,selectedModel:V}),a.jsx("div",{className:kf,children:a.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:a.jsx(Ha,{onSend:Qe,disabled:u||!b||!b.adapterName||se||Q,autoFocusEnabled:!0,placeholder:s("chatInterface.docked.placeholder"),maxWidthClass:J,isCentered:!1,adapterNotes:(Ze=b==null?void 0:b.adapterInfo)==null?void 0:Ze.notes,skillState:_,availableModels:X,defaultModel:((ft=b==null?void 0:b.adapterInfo)==null?void 0:ft.model)??null,selectedModel:V,onSelectModel:ee})})})]})]})})})}function jf({selectedAdapter:t,onAdapterChange:e,disabled:s,showDescriptions:n=!1,variant:r="sidebar",label:i,showLabel:o}){const{t:l}=Ee(),[c,d]=h.useState([]),[u,f]=h.useState(!0),[p,m]=h.useState(null),[g,x]=h.useState(!1);h.useEffect(()=>{let E=!0;async function k(){try{f(!0),m(null);const N=await Mn();E&&d(N)}catch(N){ye("Failed to load adapters:",N),E&&m(l("adapterSelector.failedToLoad"))}finally{E&&f(!1)}}return k(),()=>{E=!1}},[l]);const y=c.find(E=>E.id===t),v=typeof o=="boolean"?o:r==="prominent",A=i||l(r==="prominent"?"adapterSelector.selectAnAgent":"adapterSelector.defaultLabel"),I=h.useMemo(()=>r==="prominent"?"relative w-full text-left":"relative w-full",[r]),S=h.useMemo(()=>{const E="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"?[E,"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]),C=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=v?`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 a.jsxs("div",{className:I,children:[a.jsx("label",{className:b,children:A}),a.jsxs("div",{className:"relative",children:[a.jsx("button",{type:"button",onClick:()=>!s&&x(!g),disabled:s||u||c.length===0,className:`${S} disabled:opacity-50 disabled:cursor-not-allowed`,"aria-label":A,children:a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex flex-col min-w-0",children:[a.jsx("span",{className:`truncate font-medium ${y?"text-[#11121a] dark:text-white":"text-gray-500 dark:text-gray-400"}`,children:u?l("adapterSelector.loadingAgents"):p?l("adapterSelector.errorLoadingAgents"):y?y.name:c.length===0?l("adapterSelector.noAgentsAvailable"):l("adapterSelector.selectAnAgent")}),r==="prominent"&&(y==null?void 0:y.description)&&a.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:y.description})]}),a.jsx(us,{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&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>x(!1)}),a.jsx("div",{className:C,children:a.jsx("div",{className:"max-h-72 overflow-auto py-2",children:c.map(E=>{const k=E.id===t;return a.jsx("button",{type:"button",onClick:()=>{k||e(E.id),x(!1)},className:`w-full px-4 py-3 text-left text-sm transition-colors ${k?"bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-200":"text-[#353740] hover:bg-gray-50 dark:text-[#ececf1] dark:hover:bg-[#2a2d35]"}`,children:a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx("span",{className:"font-medium truncate",children:E.name}),n&&E.description&&a.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",style:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:E.description})]})},E.id)})})})]})]}),p&&a.jsx("p",{className:"mt-1 text-xs text-red-600 dark:text-red-400",children:p})]})}const fr=100;function Cf(t,e){const s=new Date(e.getFullYear(),e.getMonth(),e.getDate()),n=new Date(s);n.setDate(n.getDate()-1);const r=new Date(s);r.setDate(r.getDate()-s.getDay());const i=new Date(e.getFullYear(),e.getMonth(),1);return t>=s?"today":t>=n?"yesterday":t>=r?"thisWeek":t>=i?"thisMonth":"earlier"}function Nf(t){const e=new Date,s=["today","yesterday","thisWeek","thisMonth","earlier"],n=new Map;for(const r of t){const i=Cf(r.updatedAt,e),o=n.get(i);o?o.push(r):n.set(i,[r])}return s.filter(r=>n.has(r)).map(r=>({label:r,conversations:n.get(r)}))}function Ka({onRequestClose:t,onToggleDesktopSidebar:e}){const{t:s}=Ee(),n=Tr(),{conversations:r,currentConversationId:i,selectConversation:o,deleteConversation:l,deleteAllConversations:c,updateConversationTitle:d,getConversationCount:u,configureApiSettings:f,clearError:p}=ke(),m=r.find(H=>H.id===i),[g,x]=h.useState(""),[y,v]=h.useState(null),[A,I]=h.useState(""),[S,C]=h.useState({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1}),[L,F]=h.useState({isOpen:!1,isDeleting:!1}),[b,E]=h.useState(!1),[k,N]=h.useState(null),[T,_]=h.useState(!1),[O,j]=h.useState(null),U=h.useRef(null),z=h.useRef(null),R=h.useRef(null),X=!m||m.messages.length===0,te=(k==null?void 0:k.conversationId)===i?k.adapterName:(m==null?void 0:m.adapterName)??null,V=(O==null?void 0:O.conversationId)===i?O.message:null,ee=h.useMemo(()=>r.filter(H=>{var ce;return(H.messages.length>0||(((ce=H.attachedFiles)==null?void 0:ce.length)||0)>0)&&!H.adapterLoadError}),[r]),me=h.useMemo(()=>{if(!g)return ee;const H=g.toLowerCase();return ee.filter(ce=>(ce.title||s("chatInterface.newChatTitle")).toLowerCase().includes(H)||ce.messages.some(Ue=>Ue.content.toLowerCase().includes(H))||(ce.attachedFiles||[]).some(Ue=>Ue.filename.toLowerCase().includes(H)))},[ee,g,s]),D=h.useMemo(()=>Nf(me),[me]),re=u(),q=g.length>0,Q=ee.length>0;h.useEffect(()=>{if(!i||!z.current)return;const H=z.current.querySelector('[aria-current="true"]');H&&H.scrollIntoView({block:"nearest",behavior:"smooth"})},[i]);const se=h.useCallback(H=>{var Lt;if(H.key!=="ArrowDown"&&H.key!=="ArrowUp")return;H.preventDefault();const ce=(Lt=z.current)==null?void 0:Lt.querySelectorAll('[role="option"]');if(!ce||ce.length===0)return;const Ue=document.activeElement,xe=Array.from(ce).indexOf(Ue);let Ae;H.key==="ArrowDown"?Ae=xe<ce.length-1?xe+1:0:Ae=xe>0?xe-1:ce.length-1,ce[Ae].focus()},[]),fe=async H=>{if(!(!X||!H)){N({conversationId:i??null,adapterName:H}),j(null),_(!0);try{const ce=(m==null?void 0:m.apiUrl)||$e();await f(ce,void 0,H),p(),E(!1)}catch(ce){ye("Failed to configure adapter:",ce),j({conversationId:i??null,message:ce instanceof Error?ce.message:s("sidebar.adapterConfigureFailed")})}finally{_(!1)}}},Ne=async H=>{try{await o(H),t==null||t()}catch(ce){ye("Failed to select conversation:",ce)}},B=(H,ce)=>{H.stopPropagation(),C({isOpen:!0,conversationId:ce.id,conversationTitle:ce.title||s("chatInterface.newChatTitle"),isDeleting:!1})},W=async()=>{C(H=>({...H,isDeleting:!0}));try{await l(S.conversationId)}catch(H){ye("Failed to delete conversation:",H)}C({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},J=()=>{C({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},we=(H,ce)=>{H.stopPropagation(),v(ce.id),I((ce.title||s("chatInterface.newChatTitle")).slice(0,fr))},ne=H=>{const ce=A.slice(0,fr).trim();ce&&d(H,ce),v(null),I("")},K=()=>{v(null),I("")},le=()=>{F({isOpen:!0,isDeleting:!1})},ve=async()=>{F(H=>({...H,isDeleting:!0}));try{await c()}catch(H){ye("Failed to clear all conversations:",H)}F({isOpen:!1,isDeleting:!1})},ue=()=>{F({isOpen:!1,isDeleting:!1})},Pe=H=>{var ce,Ue,xe;return(ce=H.adapterName)!=null&&ce.trim()?H.adapterName:(xe=(Ue=H.adapterInfo)==null?void 0:Ue.adapter_name)!=null&&xe.trim()?H.adapterInfo.adapter_name:null};Rs(U,{enabled:b,onEscape:()=>E(!1)});const _e=H=>{const ce=i===H.id,Ue=Pe(H),xe=H.title||s("chatInterface.newChatTitle");return a.jsx("div",{role:"option","aria-selected":ce,tabIndex:0,onKeyDown:Ae=>{(Ae.key==="Enter"||Ae.key===" ")&&(Ae.preventDefault(),Ne(H.id))},onClick:()=>Ne(H.id),className:`group relative flex w-full cursor-pointer items-center rounded-lg px-3 py-2 text-left text-sm transition-colors duration-100
355
+ ${ce?"bg-slate-100 dark:bg-[#2a2b36]":"hover:bg-slate-100/70 dark:hover:bg-[#25262f]"} focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/50 dark:focus-visible:ring-sky-400/40`,"aria-current":ce?"true":void 0,"aria-label":s("sidebar.conversationCard.openAriaLabel",{title:xe}),children:y===H.id?a.jsx("input",{type:"text",value:A,onChange:Ae=>I(Ae.target.value.slice(0,fr)),onKeyDown:Ae=>{Ae.key==="Enter"&&ne(H.id),Ae.key==="Escape"&&K(),Ae.stopPropagation()},onBlur:()=>ne(H.id),maxLength:fr,className:"flex-1 rounded border border-sky-300 bg-white px-2 py-0.5 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")}):a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[a.jsx("h3",{className:`flex-1 truncate text-sm leading-snug ${ce?"font-medium text-slate-900 dark:text-[#ececf1]":"font-normal text-slate-700 dark:text-[#c5c8d6]"}`,children:xe}),a.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:[a.jsx("button",{onClick:Ae=>we(Ae,H),className:"rounded p-1 text-slate-400 transition-colors hover:bg-slate-200/80 hover:text-slate-600 dark:text-[#6b6f7a] dark:hover:bg-[#3c3f4a] dark:hover:text-[#c5c8d6]","aria-label":s("sidebar.conversationCard.editAriaLabel",{title:xe}),children:a.jsx(Si,{className:"h-3 w-3"})}),a.jsx("button",{onClick:Ae=>B(Ae,H),className:"rounded p-1 text-slate-400 transition-colors hover:bg-red-100/80 hover:text-red-600 dark:text-[#6b6f7a] dark:hover:bg-red-900/30 dark:hover:text-red-400","aria-label":s("sidebar.conversationCard.deleteAriaLabel",{title:xe}),children:a.jsx(Ni,{className:"h-3 w-3"})})]})]}),Ue&&a.jsx("span",{className:"truncate text-[11px] leading-none text-slate-400 dark:text-[#6b6f7a]",children:Ue})]})},H.id)};return a.jsxs(a.Fragment,{children:[!n&&b&&a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm px-4",children:a.jsxs("div",{ref:U,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:[a.jsx("h2",{id:"select-agent-title",className:"mb-4 text-lg font-semibold text-gray-900 dark:text-[#ececf1]",children:s("sidebar.selectAgent.title")}),a.jsxs("div",{className:"space-y-5",children:[a.jsx(jf,{selectedAdapter:te,onAdapterChange:fe,disabled:T,variant:"prominent",showDescriptions:!0,showLabel:!1}),V&&a.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}),a.jsx("div",{className:"flex justify-end gap-3 pt-2",children:a.jsx("button",{type:"button",onClick:()=>{j(null),E(!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:T,children:s("common.cancel")})})]})]})}),a.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:[a.jsxs("div",{className:"bg-transparent px-4 pb-4 pt-4 dark:border-[#2d2f39]",children:[a.jsxs("div",{className:"flex items-center gap-2 pb-3",children:[r.length>0&&r.some(H=>H.messages.length>0)&&a.jsxs("button",{onClick:le,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:[a.jsx(ed,{className:"h-4 w-4"}),s("sidebar.deleteAllConversations.button")]}),e&&a.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:a.jsx(Hc,{className:"h-4 w-4"})})]}),V&&!b&&a.jsx("p",{role:"alert",className:"mt-2 text-xs text-red-600 dark:text-red-400",children:V}),Q&&a.jsxs("div",{className:"border-t border-gray-200 pt-4 mt-4 dark:border-[#2d2f39]",children:[a.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:[a.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))]"}),a.jsx(In,{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"}),a.jsx("input",{ref:R,type:"text",role:"searchbox","aria-label":s("sidebar.search.ariaLabel"),placeholder:s("sidebar.search.placeholder"),value:g,onChange:H=>x(H.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&&a.jsx("button",{type:"button",onClick:()=>{var H;x(""),(H=R.current)==null||H.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:a.jsx(Ye,{className:"h-3.5 w-3.5"})})]}),q&&a.jsx("p",{"aria-live":"polite",className:"mt-2 text-center text-[11px] tabular-nums text-gray-400 dark:text-[#6e7490]",children:me.length===0?s("sidebar.resultsNone"):s("sidebar.results",{count:me.length})})]})]}),a.jsx("div",{ref:z,role:"listbox","aria-label":s("sidebar.conversations.ariaLabel"),onKeyDown:se,className:"flex-1 overflow-y-auto bg-transparent px-3 py-2",children:me.length===0?null:q?a.jsx("div",{className:"space-y-1",children:me.map(_e)}):a.jsx("div",{className:"space-y-4",children:D.map(H=>a.jsxs("section",{"aria-label":s(`sidebar.timeGroups.${H.label}`),children:[a.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.${H.label}`)}),a.jsx("div",{className:"space-y-1",children:H.conversations.map(_e)})]},H.label))})}),(()=>{const H=gi();return H.length===0?null:a.jsx("div",{className:"shrink-0 border-t border-gray-200/80 px-4 py-3 md:hidden dark:border-[#2d2f39]",children:a.jsx("nav",{"aria-label":s("appHeader.navLinksAriaLabel"),children:a.jsx("ul",{className:"flex flex-wrap gap-2",children:H.map(ce=>a.jsx("li",{children:a.jsx("a",{href:ce.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:ce.label})},ce.url))})})})})(),a.jsx("div",{className:"shrink-0 border-t border-gray-200/80 dark:border-[#2d2f39]",children:a.jsx(Vi,{placement:"sidebar",compact:!0})})]}),a.jsx(Sr,{isOpen:S.isOpen,onClose:J,onConfirm:W,title:s("sidebar.deleteConfirm.title"),message:s("sidebar.deleteConfirm.message",{title:S.conversationTitle}),confirmText:s("sidebar.deleteConfirm.confirmText"),cancelText:s("common.cancel"),type:"danger",isLoading:S.isDeleting}),a.jsx(Sr,{isOpen:L.isOpen,onClose:ue,onConfirm:ve,title:s("sidebar.clearAllConfirm.title"),message:s("sidebar.clearAllConfirm.message",{count:re}),confirmText:s("sidebar.clearAllConfirm.confirmText"),cancelText:s("common.cancel"),type:"danger",isLoading:L.isDeleting})]})}const Af="3.11.1",If={version:Af},$n=If.version,Lf=["@@auth0spajs@@","a0.spajs","auth0","com.auth0"];function Ef(t){const e=t.toLowerCase();return Lf.some(s=>e.includes(s.toLowerCase()))}function Tf(t){const e=[];for(let s=0;s<t.length;s++){const n=t.key(s);n&&Ef(n)&&e.push(n)}e.forEach(s=>t.removeItem(s))}function Ga(t){try{Tf(t),t.clear()}catch(e){console.warn("[Settings] Failed to clear browser storage during reset.",e)}}function _f(){if(typeof document>"u"||!document.cookie)return;const t=new Set([void 0]),e=window.location.hostname;e&&e!=="localhost"&&!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)&&(t.add(e),t.add(`.${e}`)),document.cookie.split(";").forEach(n=>{const r=n.indexOf("="),i=(r>-1?n.slice(0,r):n).trim();i&&t.forEach(o=>{const l=o?`;domain=${o}`:"";document.cookie=`${i}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/${l}`})})}function Mf(){Ga(localStorage),Ga(sessionStorage),_f()}function Ff({isOpen:t,onClose:e}){const{t:s}=Ee(),{theme:n,updateTheme:r}=ds(),{settings:i,updateSettings:o}=Lr(),{activeLanguages:l,currentLanguage:c,setLanguage:d}=vc(),[u,f]=h.useState(!1),[p,m]=h.useState(!1),g=h.useRef(null),x=h.useRef(null),y=h.useMemo(()=>[...l].sort((L,F)=>rr[L].localeCompare(rr[F])),[l]);h.useEffect(()=>{if(!p)return;const L=F=>{F.key==="Escape"&&(F.stopPropagation(),m(!1))};return document.addEventListener("keydown",L,{capture:!0}),()=>document.removeEventListener("keydown",L,{capture:!0})},[p]);const v=L=>{r({mode:L})},A=()=>{o({soundEnabled:!i.soundEnabled})},I=()=>{f(!0)},S=()=>{f(!1)},C=()=>{S(),Mr(),Fr(!1),cs(null),st.getState().closeLoginPrompt(),Mf(),window.location.reload()};return Rs(g,{enabled:t&&!u,onEscape:e}),Rs(x,{enabled:u,onEscape:S}),t?a.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:[a.jsx("button",{type:"button",onClick:e,"aria-label":s("settings.dialog.closeOverlayAriaLabel"),className:"absolute inset-0"}),a.jsxs("div",{onClick:L=>L.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:[a.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:[a.jsx("h2",{id:"settings-title",className:"text-xl font-semibold text-gray-900 dark:text-gray-100",children:s("settings.dialog.title")}),a.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:a.jsx(Ye,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),a.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:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[a.jsx(Bc,{className:"w-5 h-5"}),s("settings.appearance.heading")]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:s("settings.appearance.themeLabel")}),a.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{value:"light",label:s("settings.appearance.themeLight"),icon:Zc},{value:"dark",label:s("settings.appearance.themeDark"),icon:zc},{value:"system",label:s("settings.appearance.themeSystem"),icon:Uc}].map(({value:L,label:F,icon:b})=>a.jsxs("button",{onClick:()=>v(L),className:`flex flex-col items-center gap-2 p-3 rounded-lg border-2 transition-all duration-200 ${n.mode===L?"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:[a.jsx(b,{className:"w-5 h-5"}),a.jsx("span",{className:"text-sm font-medium",children:F})]},L))})]}),l.length>1&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2",children:[a.jsx(Fc,{className:"w-4 h-4"}),s("settings.language.label")]}),a.jsxs("div",{className:"relative",children:[a.jsxs("button",{type:"button",onClick:()=>m(L=>!L),"aria-haspopup":"listbox","aria-expanded":p,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 ${p?"border-blue-500":"border-gray-200 dark:border-[#2d2f39] hover:border-gray-300 dark:hover:border-[#43465a]"}`,children:[a.jsx("span",{className:"font-medium text-gray-900 dark:text-gray-100",children:rr[c]}),a.jsx(us,{className:`h-4 w-4 flex-shrink-0 text-gray-400 transition-transform duration-200 dark:text-gray-500 ${p?"rotate-180":""}`})]}),p&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),a.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(L=>{const F=L===c;return a.jsxs("button",{type:"button",role:"option","aria-selected":F,onClick:()=>{d(L),m(!1)},className:`flex w-full items-center justify-between gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors ${F?"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:[a.jsx("span",{className:"truncate",children:rr[L]}),F&&a.jsx($s,{className:"h-4 w-4 flex-shrink-0 text-blue-600 dark:text-blue-400"})]},L)})})]})]})]})]}),a.jsxs("div",{className:"space-y-4",children:[a.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:s("settings.chat.heading")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(kr,{className:"w-4 h-4 text-gray-600 dark:text-gray-400"}),a.jsxs("div",{children:[a.jsx("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:s("settings.soundEffects.label")}),a.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s("settings.soundEffects.description")})]})]}),a.jsx("button",{onClick:A,role:"switch","aria-checked":i.soundEnabled,"aria-label":s("settings.soundEffects.toggleAriaLabel"),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${i.soundEnabled?"bg-blue-600":"bg-gray-200 dark:bg-[#3c3f4a]"}`,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${i.soundEnabled?"translate-x-6":"translate-x-1"}`})})]})]}),a.jsxs("div",{className:"space-y-4 pt-4 border-t border-gray-200 dark:border-[#2d2f39]",children:[a.jsxs("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[a.jsx(Ni,{className:"w-5 h-5"}),s("settings.dataManagement.heading")]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:s("settings.dataManagement.description")}),a.jsx("button",{onClick:I,className:"w-full px-4 py-2 text-sm font-medium text-red-600 dark:text-red-400 border border-red-300 dark:border-red-700 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors",children:s("settings.reset.button")})]})]}),a.jsxs("p",{className:"pt-2 text-center text-xs text-gray-400 dark:text-[#858999]",children:["v",$n]})]}),u&&a.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/70 p-4",children:a.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:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.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:a.jsx(En,{className:"w-5 h-5 text-red-600 dark:text-red-400"})}),a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("p",{id:"reset-dialog-title",className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:s("settings.reset.confirmTitle")}),a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:s("settings.reset.confirmMessage")})]})]}),a.jsxs("div",{className:"mt-4 flex gap-2 pt-2",children:[a.jsx("button",{onClick:S,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")}),a.jsx("button",{onClick:C,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 $f({message:t}){const{t:e}=Ee(),s=Sn();return a.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:a.jsxs("div",{className:"mx-auto flex min-h-[calc(100dvh-3rem)] w-full max-w-5xl flex-col",children:[a.jsxs("header",{className:"flex items-center justify-between gap-4",children:[a.jsx("p",{className:"min-w-0 truncate text-lg font-semibold tracking-tight sm:text-xl",children:s}),a.jsxs("span",{className:"shrink-0 text-xs font-medium text-slate-400 dark:text-[#858999]",children:["v",$n]})]}),a.jsx("section",{className:"flex flex-1 items-center justify-center py-12",children:a.jsxs("div",{className:"w-full max-w-lg space-y-8",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("span",{className:"relative flex h-2.5 w-2.5 shrink-0",children:[a.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-amber-400 opacity-60 dark:bg-amber-500"}),a.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-amber-500 dark:bg-amber-400"})]}),a.jsx("span",{className:"text-xs font-semibold uppercase tracking-widest text-amber-700 dark:text-amber-400",children:e("outOfService.statusBadge")})]}),a.jsxs("div",{className:"space-y-4",children:[a.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-slate-950 dark:text-white sm:text-4xl",children:e("outOfService.heading")}),a.jsx("p",{className:"max-w-md whitespace-pre-wrap text-base leading-relaxed text-slate-500 dark:text-slate-400",children:t})]}),a.jsx("div",{className:"border-t border-slate-200 dark:border-[#242424]"}),a.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[a.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:[a.jsx(Yc,{className:"h-4 w-4","aria-hidden":"true"}),e("outOfService.retryButton")]}),a.jsx("span",{className:"hidden text-slate-300 dark:text-slate-700 sm:block","aria-hidden":"true",children:"·"})]})]})})]})})}function Pf({children:t}){const{instance:e,accounts:s}=wn(),n=Ro();return h.useEffect(()=>{Fr(n)},[n]),h.useEffect(()=>{if(!n||s.length===0){cs(null);return}const r=s[0];cs(r.username||r.name||r.localAccountId||null)},[n,s]),h.useEffect(()=>{if(!n||s.length===0)return;const r=s[0],i=Nn();return Ai(async()=>(await e.acquireTokenSilent({scopes:i,account:r})).accessToken),()=>Mr()},[n,s,e]),a.jsx(a.Fragment,{children:t})}function Rf({children:t}){return a.jsx(Pf,{children:t})}function Df({children:t}){const{isLoading:e,isAuthenticated:s,getAccessTokenSilently:n,user:r}=kn();return h.useEffect(()=>{Fr(s)},[s]),h.useEffect(()=>{if(!s){cs(null);return}const i=(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;cs(i)},[s,r]),h.useEffect(()=>(s&&Ai(()=>n()),()=>Mr()),[s,n]),e?a.jsx("div",{className:"flex items-center justify-center h-screen bg-white dark:bg-[#212121]",children:a.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 dark:border-gray-100"})}):a.jsx(a.Fragment,{children:t})}function Of({children:t}){return h.useEffect(()=>{Fr(!1),cs(null),Mr()},[]),a.jsx(a.Fragment,{children:t})}function Uf({children:t}){return tt()?_r()==="entra"?a.jsx(Rf,{children:t}):a.jsx(Df,{children:t}):a.jsx(Of,{children:t})}function zf(){const t=Cn(),e=tt(),s=fs(),{showLoginPrompt:n,promptMessage:r,closeLoginPrompt:i}=st();return h.useEffect(()=>{n&&(!t||!e||s)&&i()},[n,t,e,s,i]),!t||!e||s||!n?null:_r()==="entra"?a.jsx(Hf,{message:r,onClose:i}):a.jsx(Bf,{message:r,onClose:i})}function Bf({message:t,onClose:e}){const{loginWithRedirect:s}=kn();return a.jsx(Yi,{message:t,onClose:e,onLogin:()=>s()})}function Hf({message:t,onClose:e}){const{instance:s}=wn();return a.jsx(Yi,{message:t,onClose:e,onLogin:()=>s.loginRedirect({scopes:Nn()}).catch(()=>{})})}function Yi({message:t,onClose:e,onLogin:s}){const{t:n}=Ee();return a.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center",children:[a.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:e,"aria-hidden":"true"}),a.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:[a.jsx("button",{onClick:e,className:"absolute right-3 top-3 rounded-full p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]","aria-label":n("common.close"),children:a.jsx(Ye,{className:"h-4 w-4"})}),a.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[a.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900/40",children:a.jsx(vi,{className:"h-5 w-5 text-blue-600 dark:text-blue-300"})}),a.jsx("h2",{className:"text-lg font-semibold text-gray-900 dark:text-[#ececf1]",children:n("loginPrompt.heading")})]}),a.jsx("p",{className:"mb-6 text-sm leading-relaxed text-gray-600 dark:text-[#bfc2cd]",children:t}),a.jsxs("div",{className:"flex gap-3",children:[a.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:n("common.signIn")}),a.jsx("button",{onClick:e,className:"flex-1 rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 dark:border-[#4a4b54] dark:bg-[#2d2f39] dark:text-[#bfc2cd] dark:hover:bg-[#3c3f4a]",children:n("common.cancel")})]})]})]})}function Vf(){const{t}=Ee(),{goHome:e}=Gi(),{isDark:s}=ds(),n=Zu(),r=h.useRef(!1),i=rc(),o=nc(),l=ac(),c=s?l:o,d=ic(),u=oc(),f=!!(d||u),p=lc(),m=cc(),g=dc(),x=gi(),y=g?"border-b border-slate-200/80 dark:border-[#333645]":"",v="inline-flex min-h-10 items-center rounded-md px-2.5 text-sm font-medium transition-colors hover:bg-slate-100 hover:text-blue-700 hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:hover:bg-[#2b2d39] dark:hover:text-blue-300";return h.useEffect(()=>{r.current},[l,i,o]),fn()?a.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:p||void 0,color:m||void 0},children:a.jsxs("div",{className:"mx-auto flex w-full max-w-[96rem] items-center justify-between gap-3",children:[a.jsx("div",{className:"flex min-w-0 flex-1 items-center justify-center gap-2 md:justify-start md:gap-3",children:a.jsx("a",{href:n,"aria-label":t("appHeader.homeLinkAriaLabel"),onClick:A=>{A.preventDefault(),e()},className:"inline-flex items-center rounded-sm px-1 py-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 dark:focus-visible:ring-blue-300 dark:focus-visible:ring-offset-black md:-ml-1",children:a.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}:{}}})})}),a.jsxs("div",{className:"hidden min-w-0 flex-1 items-center justify-end gap-2 sm:gap-4 md:flex",children:[x.length>0&&a.jsx("nav",{"aria-label":t("appHeader.navLinksAriaLabel"),className:"hidden sm:block",children:a.jsx("ul",{className:"flex items-center gap-1.5 sm:gap-2",children:x.map(A=>a.jsx("li",{children:a.jsx("a",{href:A.url,target:"_blank",rel:"noopener noreferrer",className:v,style:{color:m||void 0},children:A.label})},A.url))})}),a.jsx(bn,{})]})]})}):null}function qf({children:t}){const e=h.useRef(null),s=h.useCallback(r=>{e.current=r},[]),n=h.useCallback(()=>{var r;(r=e.current)==null||r.call(e)},[]);return a.jsx(Ki.Provider,{value:{registerGoHome:s,goHome:n},children:t})}function Wf(){const{t}=Ee(),[e,s]=h.useState(!1),[n,r]=h.useState(!1),[i,o]=h.useState(()=>localStorage.getItem("desktop-sidebar-collapsed")==="true"),l=ke(u=>u.conversations),c=Zl();if(h.useEffect(()=>{localStorage.setItem("desktop-sidebar-collapsed",String(i))},[i]),c)return a.jsx(Jn,{children:a.jsx($f,{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 a.jsx(Jn,{children:a.jsx(zo,{children:a.jsx(kc,{children:a.jsx(Uf,{children:a.jsx(qf,{children:a.jsxs("div",{className:"h-dvh flex flex-col bg-white dark:bg-black text-slate-900 dark:text-slate-100",children:[a.jsxs("div",{className:"flex-1 flex flex-col md:flex-row md:pl-4 min-h-0",children:[d&&(i?a.jsx("div",{className:"hidden md:flex md:w-16 md:h-full shrink-0 items-start justify-center pt-8",children:a.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:a.jsx(Vc,{className:"h-4 w-4"})})}):a.jsx("div",{className:"hidden md:h-full md:flex",children:a.jsx(Ka,{onToggleDesktopSidebar:()=>o(!0)})})),a.jsxs("div",{className:"flex-1 flex flex-col w-full min-h-0",children:[a.jsx(Vf,{}),a.jsx("div",{className:"flex-1 flex justify-center w-full min-h-0",children:a.jsx(Sf,{onOpenSettings:()=>s(!0),onOpenSidebar:()=>r(!0)})})]})]}),a.jsx(zf,{}),a.jsx(Ff,{isOpen:e,onClose:()=>s(!1)}),n&&a.jsxs("div",{className:"fixed inset-0 z-50 flex md:hidden",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:()=>r(!1),"aria-hidden":"true"}),a.jsxs("div",{className:"relative z-10 h-full w-[min(20rem,90vw)] animate-slideIn bg-white dark:bg-black",children:[a.jsx(Ka,{onRequestClose:()=>r(!1)}),a.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:a.jsx(Ye,{className:"h-5 w-5"})})]})]})]})})})})})})}const nn=new Do({auth:{clientId:mi(),authority:`https://login.microsoftonline.com/${sc()}`,redirectUri:typeof window<"u"?window.location.origin:"/"},cache:{cacheLocation:"sessionStorage"}});function Kf({children:t}){const[e,s]=h.useState(!1);return h.useEffect(()=>{nn.initialize().then(()=>nn.handleRedirectPromise()).catch(n=>{console.error("[EntraAuth] Redirect processing failed:",n)}).finally(()=>s(!0))},[]),e?a.jsx(Oo,{instance:nn,children:t}):null}function Gf({children:t}){if(!Cn()||!tt())return a.jsx(a.Fragment,{children:t});if(_r()==="entra")return a.jsx(Kf,{children:t});const s=ec(),n=mi(),r=tc();return!s||!n?a.jsx(a.Fragment,{children:t}):a.jsx(Uo,{domain:s,clientId:n,authorizationParams:{redirect_uri:window.location.origin,...r?{audience:r}:{}},cacheLocation:"memory",children:t})}Xi(null);const Xa=ql(),Ya=document.querySelector('link[rel="icon"]');if(Ya)Ya.href=Xa;else{const t=document.createElement("link");t.rel="icon",t.href=Xa,document.head.appendChild(t)}const Xf=xc();var Qa,Ja,Za,ei,ti,si;for(const t of Xf){const e=((Qa=t.src)==null?void 0:Qa.trim())||"",s=((Ja=t.content)==null?void 0:Ja.trim())||"",n=((Za=t.id)==null?void 0:Za.trim())||"";if(!e&&!s||n&&document.querySelector(`script[data-orbitchat-startup-script-id="${n}"]`)||Array.from(document.querySelectorAll("script[data-orbitchat-startup-script]")).some(o=>{const l=e&&o.dataset.orbitchatStartupScriptSrc===e,c=s&&(o.textContent||"").trim()===s;return!!(l||c)}))continue;const i=document.createElement("script");e&&(i.src=e),s&&(i.text=s),i.async=t.async??!0,t.defer!==void 0&&(i.defer=t.defer),(ei=t.type)!=null&&ei.trim()&&(i.type=t.type.trim()),(ti=t.integrity)!=null&&ti.trim()&&(i.integrity=t.integrity.trim()),t.crossOrigin&&(i.crossOrigin=t.crossOrigin),(si=t.referrerPolicy)!=null&&si.trim()&&(i.referrerPolicy=t.referrerPolicy.trim()),i.dataset.orbitchatStartupScript="true",n&&(i.dataset.orbitchatStartupScriptId=n),e&&(i.dataset.orbitchatStartupScriptSrc=e),document.head.appendChild(i)}$("🚀 AI Chat Application started");$(`📱 App Version: v${$n}`);So.createRoot(document.getElementById("root")).render(a.jsx(h.StrictMode,{children:a.jsx(Gf,{children:a.jsx(Wf,{})})}));export{vl as r,Ee as u};