orbitchat 3.12.0 → 3.12.2

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 (58) hide show
  1. package/README.md +8 -7
  2. package/bin/orbitchat.js +11 -10
  3. package/dist/assets/{ChartRenderer-Dv1-lA9R.js → ChartRenderer-DDBqm2Py.js} +1 -1
  4. package/dist/assets/{MermaidRenderer-DXFZlHFF.js → MermaidRenderer-CgV7aCCX.js} +4 -4
  5. package/dist/assets/{MusicRenderer-CpffrqTQ.js → MusicRenderer-BXdebcAA.js} +1 -1
  6. package/dist/assets/{SVGRenderer-24uWGqbU.js → SVGRenderer-B8oxKCB3.js} +1 -1
  7. package/dist/assets/{architectureDiagram-3BPJPVTR-DutJcNMs.js → architectureDiagram-3BPJPVTR-DGHRmWdE.js} +1 -1
  8. package/dist/assets/{blockDiagram-GPEHLZMM-Br4HhB4r.js → blockDiagram-GPEHLZMM-DKGpv7g2.js} +1 -1
  9. package/dist/assets/{c4Diagram-AAUBKEIU-DAeinqKh.js → c4Diagram-AAUBKEIU-XYQtkB2-.js} +1 -1
  10. package/dist/assets/channel-BSeiDL4b.js +1 -0
  11. package/dist/assets/{chunk-2J33WTMH-YJCNV3Wc.js → chunk-2J33WTMH-CSXa3YbB.js} +1 -1
  12. package/dist/assets/{chunk-4BX2VUAB-DdwaEve7.js → chunk-4BX2VUAB-DDNVeJMa.js} +1 -1
  13. package/dist/assets/{chunk-55IACEB6-D0rIMGPs.js → chunk-55IACEB6-DAgJxyY1.js} +1 -1
  14. package/dist/assets/{chunk-727SXJPM-Bdw9UDhI.js → chunk-727SXJPM-DsrBVs3Y.js} +1 -1
  15. package/dist/assets/{chunk-AQP2D5EJ-C3cM5tlh.js → chunk-AQP2D5EJ-BhZbEA9D.js} +1 -1
  16. package/dist/assets/{chunk-FMBD7UC4-lfx2O5mz.js → chunk-FMBD7UC4-CRFjZxOp.js} +1 -1
  17. package/dist/assets/{chunk-ND2GUHAM-DK8H8vPe.js → chunk-ND2GUHAM-BAht_heQ.js} +1 -1
  18. package/dist/assets/{chunk-QZHKN3VN-Dmqn62ID.js → chunk-QZHKN3VN-eK0lHjjy.js} +1 -1
  19. package/dist/assets/classDiagram-4FO5ZUOK-D9XYfCnz.js +1 -0
  20. package/dist/assets/classDiagram-v2-Q7XG4LA2-D9XYfCnz.js +1 -0
  21. package/dist/assets/{cose-bilkent-S5V4N54A-Dr2ndMg7.js → cose-bilkent-S5V4N54A-CdFVZ1mc.js} +1 -1
  22. package/dist/assets/{dagre-BM42HDAG-Dq8pZNbW.js → dagre-BM42HDAG-7Ih6MQaQ.js} +1 -1
  23. package/dist/assets/{diagram-2AECGRRQ-Db7FgRcb.js → diagram-2AECGRRQ-DI03lRmN.js} +1 -1
  24. package/dist/assets/{diagram-5GNKFQAL-B06PoRkf.js → diagram-5GNKFQAL-Dm4n3Ook.js} +1 -1
  25. package/dist/assets/{diagram-KO2AKTUF-CFuoI9IC.js → diagram-KO2AKTUF-DwcJMmhM.js} +1 -1
  26. package/dist/assets/{diagram-LMA3HP47-CAZIzWkW.js → diagram-LMA3HP47-2G7ZBf5F.js} +1 -1
  27. package/dist/assets/{diagram-OG6HWLK6-C7eblq3x.js → diagram-OG6HWLK6-BowMOxY-.js} +1 -1
  28. package/dist/assets/{erDiagram-TEJ5UH35-BBZXjDXe.js → erDiagram-TEJ5UH35-Dg-f0Kex.js} +1 -1
  29. package/dist/assets/{flowDiagram-I6XJVG4X-CS7HoQSQ.js → flowDiagram-I6XJVG4X-eIxTbMn7.js} +1 -1
  30. package/dist/assets/{ganttDiagram-6RSMTGT7-D_Wty1PB.js → ganttDiagram-6RSMTGT7-B_VWHgyp.js} +1 -1
  31. package/dist/assets/{gitGraphDiagram-PVQCEYII-CP6fxzBG.js → gitGraphDiagram-PVQCEYII-C5xkJVnm.js} +1 -1
  32. package/dist/assets/index-CNULXWPY.css +1 -0
  33. package/dist/assets/index-_nm-QaRs.js +347 -0
  34. package/dist/assets/{infoDiagram-5YYISTIA-Bhn0ibjf.js → infoDiagram-5YYISTIA-I8E0Zg-2.js} +1 -1
  35. package/dist/assets/{ishikawaDiagram-YF4QCWOH-ATXyB8ZS.js → ishikawaDiagram-YF4QCWOH-BOs1tR_e.js} +1 -1
  36. package/dist/assets/{journeyDiagram-JHISSGLW-Buv9U5b1.js → journeyDiagram-JHISSGLW-pAMqZgHj.js} +1 -1
  37. package/dist/assets/{kanban-definition-UN3LZRKU-DMKrQE7f.js → kanban-definition-UN3LZRKU-C1rCg9YH.js} +1 -1
  38. package/dist/assets/locales-iHSQG_GN.js +1 -0
  39. package/dist/assets/{mindmap-definition-RKZ34NQL-BKkFnSVW.js → mindmap-definition-RKZ34NQL-CjBlLy1g.js} +1 -1
  40. package/dist/assets/{pieDiagram-4H26LBE5-DQ25hwc3.js → pieDiagram-4H26LBE5-CgX8DEnn.js} +1 -1
  41. package/dist/assets/{quadrantDiagram-W4KKPZXB-DHz4I0CR.js → quadrantDiagram-W4KKPZXB-BgHw56Yx.js} +1 -1
  42. package/dist/assets/{requirementDiagram-4Y6WPE33-L37uWgMf.js → requirementDiagram-4Y6WPE33-dt1w3tPB.js} +1 -1
  43. package/dist/assets/{sankeyDiagram-5OEKKPKP-Ch99ueO4.js → sankeyDiagram-5OEKKPKP-C8wi8Xk3.js} +1 -1
  44. package/dist/assets/{sequenceDiagram-3UESZ5HK-9xXQ57CP.js → sequenceDiagram-3UESZ5HK-BUYQEiON.js} +1 -1
  45. package/dist/assets/{stateDiagram-AJRCARHV-U4rVLskO.js → stateDiagram-AJRCARHV-CTHOOBPe.js} +1 -1
  46. package/dist/assets/{stateDiagram-v2-BHNVJYJU-DrUU5vv_.js → stateDiagram-v2-BHNVJYJU-C9kDkNCc.js} +1 -1
  47. package/dist/assets/{timeline-definition-PNZ67QCA-oK1bP60Z.js → timeline-definition-PNZ67QCA-DJur2Ntd.js} +1 -1
  48. package/dist/assets/{vennDiagram-CIIHVFJN-kV37gLDH.js → vennDiagram-CIIHVFJN-DUcqxDO6.js} +1 -1
  49. package/dist/assets/{wardleyDiagram-YWT4CUSO-C3uF828w.js → wardleyDiagram-YWT4CUSO-CObytPAY.js} +1 -1
  50. package/dist/assets/{xychartDiagram-2RQKCTM6-Dho1D5sg.js → xychartDiagram-2RQKCTM6-q0fWvo5y.js} +1 -1
  51. package/dist/index.html +3 -3
  52. package/package.json +1 -1
  53. package/dist/assets/channel-RYryYQTj.js +0 -1
  54. package/dist/assets/classDiagram-4FO5ZUOK-BlGcJD1O.js +0 -1
  55. package/dist/assets/classDiagram-v2-Q7XG4LA2-BlGcJD1O.js +0 -1
  56. package/dist/assets/index-B-s-ASrq.js +0 -376
  57. package/dist/assets/index-DzQUmBrn.css +0 -1
  58. package/dist/assets/locales-W7R9QlAG.js +0 -1
@@ -1,376 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MermaidRenderer-DXFZlHFF.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-24uWGqbU.js","assets/locales-W7R9QlAG.js","assets/vendor-markdown-Cy_-N5ZX.js","assets/vendor-markdown-dRWncRqa.css","assets/vendor-auth-aD_bwYde.js","assets/ChartRenderer-Dv1-lA9R.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-CpffrqTQ.js","assets/papaparse.min-D13ujVVP.js","assets/docx-preview-DehBmhog.js"])))=>i.map(i=>d[i]);
2
- var zo=Object.defineProperty;var Bo=(t,e,r)=>e in t?zo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Ze=(t,e,r)=>Bo(t,typeof e!="symbol"?e+"":e,r);import{r as m,j as a,a as Ho,R as pt,b as Rs,d as Vo}from"./vendor-react-BbEy7z12.js";import{z as qo,p as Wo,j as Ko,f as Go,e as Xo,a as Yo,d as Qo}from"./locales-W7R9QlAG.js";import{M as Zo,r as ua,a as Jo,b as el}from"./vendor-markdown-Cy_-N5ZX.js";import{_ as Nt,h as tl,v as rl,a as sl}from"./vendor-syntax-INF7-xC_.js";import{u as Mn,a as Fn,b as nl,P as al,M as il,A as ol}from"./vendor-auth-aD_bwYde.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const i of s)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 r(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(s){if(s.ep)return;s.ep=!0;const i=r(s);fetch(s.href,i)}})();const yi=m.createContext(void 0);function fa({children:t}){const[e,r]=m.useState(()=>{const o=localStorage.getItem("chat-theme");if(o){const l=JSON.parse(o);return{mode:l.mode||"dark",highContrast:!!l.highContrast}}return{mode:"dark",highContrast:!1}}),[n,s]=m.useState(!1);m.useEffect(()=>{const o=()=>{let l=!1;e.mode==="dark"?l=!0:e.mode==="light"?l=!1:l=window.matchMedia("(prefers-color-scheme: dark)").matches,s(l);const c=document.documentElement;c.dataset.theme=l?"dark":"light",l?c.classList.add("dark"):c.classList.remove("dark"),e.highContrast?c.classList.add("high-contrast"):c.classList.remove("high-contrast"),c.classList.remove("text-sm","text-lg"),c.classList.add("text-base")};if(o(),e.mode==="system"){const l=window.matchMedia("(prefers-color-scheme: dark)"),c=()=>{o()};return l.addEventListener("change",c),()=>l.removeEventListener("change",c)}},[e]),m.useEffect(()=>{localStorage.setItem("chat-theme",JSON.stringify(e))},[e]);const i=o=>{r(l=>({...l,...o}))};return a.jsx(yi.Provider,{value:{theme:e,updateTheme:i,isDark:n},children:t})}function lr(){const t=m.useContext(yi);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}const wi=m.createContext(void 0),tn={voiceEnabled:!1,soundEnabled:!1,autoSend:!1};function ll({children:t}){const[e,r]=m.useState(()=>{const s=localStorage.getItem("chat-settings");if(s)try{const i=JSON.parse(s);return{...tn,...i,voiceEnabled:!1}}catch{return tn}return tn});m.useEffect(()=>{localStorage.setItem("chat-settings",JSON.stringify(e))},[e]);const n=s=>{r(i=>({...i,...s}))};return a.jsx(wi.Provider,{value:{settings:e,updateSettings:n},children:t})}function Ds(){const t=m.useContext(wi);if(!t)throw new Error("useSettings must be used within SettingsProvider");return t}const he=t=>typeof t=="string",Mr=()=>{let t,e;const r=new Promise((n,s)=>{t=n,e=s});return r.resolve=t,r.reject=e,r},ma=t=>t==null?"":String(t),cl=(t,e,r)=>{t.forEach(n=>{e[n]&&(r[n]=e[n])})},dl=/###/g,ha=t=>t&&t.includes("###")?t.replace(dl,"."):t,pa=t=>!t||he(t),Rr=(t,e,r)=>{const n=he(e)?e.split("."):e;let s=0;for(;s<n.length-1;){if(pa(t))return{};const i=ha(n[s]);!t[i]&&r&&(t[i]=new r),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++s}return pa(t)?{}:{obj:t,k:ha(n[s])}},ga=(t,e,r)=>{const{obj:n,k:s}=Rr(t,e,Object);if(n!==void 0||e.length===1){n[s]=r;return}let i=e[e.length-1],o=e.slice(0,e.length-1),l=Rr(t,o,Object);for(;l.obj===void 0&&o.length;)i=`${o[o.length-1]}.${i}`,o=o.slice(0,o.length-1),l=Rr(t,o,Object),l!=null&&l.obj&&typeof l.obj[`${l.k}.${i}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${i}`]=r},ul=(t,e,r,n)=>{const{obj:s,k:i}=Rr(t,e,Object);s[i]=s[i]||[],s[i].push(r)},js=(t,e)=>{const{obj:r,k:n}=Rr(t,e);if(r&&Object.prototype.hasOwnProperty.call(r,n))return r[n]},fl=(t,e,r)=>{const n=js(t,r);return n!==void 0?n:js(e,r)},ki=(t,e,r)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(Object.prototype.hasOwnProperty.call(t,n)?he(t[n])||t[n]instanceof String||he(e[n])||e[n]instanceof String?r&&(t[n]=e[n]):ki(t[n],e[n],r):t[n]=e[n]);return t},Pt=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),ml={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"},hl=t=>he(t)?t.replace(/[&<>"'\/]/g,e=>ml[e]):t;class pl{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const r=this.regExpMap.get(e);if(r!==void 0)return r;const n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}}const gl=[" ",",","?","!",";"],xl=new pl(20),bl=(t,e,r)=>{e=e||"",r=r||"";const n=gl.filter(o=>!e.includes(o)&&!r.includes(o));if(n.length===0)return!0;const s=xl.getRegExp(`(${n.map(o=>o==="?"?"\\?":o).join("|")})`);let i=!s.test(t);if(!i){const o=t.indexOf(r);o>0&&!s.test(t.substring(0,o))&&(i=!0)}return i},xn=(t,e,r=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const n=e.split(r);let s=t;for(let i=0;i<n.length;){if(!s||typeof s!="object")return;let o,l="";for(let c=i;c<n.length;++c)if(c!==i&&(l+=r),l+=n[c],o=s[l],o!==void 0){if(["string","number","boolean"].includes(typeof o)&&c<n.length-1)continue;i+=c-i+1;break}s=o}return s},zr=t=>t==null?void 0:t.replace(/_/g,"-"),yl={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){var r,n;(n=(r=console==null?void 0:console[t])==null?void 0:r.apply)==null||n.call(r,console,e)}};class Cs{constructor(e,r={}){this.init(e,r)}init(e,r={}){this.prefix=r.prefix||"i18next:",this.logger=e||yl,this.options=r,this.debug=r.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,r,n,s){return s&&!this.debug?null:(e=e.map(i=>he(i)?i.replace(/[\r\n\x00-\x1F\x7F]/g," "):i),he(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[r](e))}create(e){return new Cs(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Cs(this.logger,e)}}var It=new Cs;class Us{constructor(){this.observers={}}on(e,r){return e.split(" ").forEach(n=>{this.observers[n]||(this.observers[n]=new Map);const s=this.observers[n].get(r)||0;this.observers[n].set(r,s+1)}),this}off(e,r){if(this.observers[e]){if(!r){delete this.observers[e];return}this.observers[e].delete(r)}}once(e,r){const n=(...s)=>{r(...s),this.off(e,n)};return this.on(e,n),this}emit(e,...r){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([s,i])=>{for(let o=0;o<i;o++)s(...r)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([s,i])=>{for(let o=0;o<i;o++)s(e,...r)})}}class xa extends Us{constructor(e,r={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.includes(e)||this.options.ns.push(e)}removeNamespaces(e){const r=this.options.ns.indexOf(e);r>-1&&this.options.ns.splice(r,1)}getResource(e,r,n,s={}){var d,u;const i=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,o=s.ignoreJSONStructure!==void 0?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let l;e.includes(".")?l=e.split("."):(l=[e,r],n&&(Array.isArray(n)?l.push(...n):he(n)&&i?l.push(...n.split(i)):l.push(n)));const c=js(this.data,l);return!c&&!r&&!n&&e.includes(".")&&(e=l[0],r=l[1],n=l.slice(2).join(".")),c||!o||!he(n)?c:xn((u=(d=this.data)==null?void 0:d[e])==null?void 0:u[r],n,i)}addResource(e,r,n,s,i={silent:!1}){const o=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator;let l=[e,r];n&&(l=l.concat(o?n.split(o):n)),e.includes(".")&&(l=e.split("."),s=r,r=l[1]),this.addNamespaces(r),ga(this.data,l,s),i.silent||this.emit("added",e,r,n,s)}addResources(e,r,n,s={silent:!1}){for(const i in n)(he(n[i])||Array.isArray(n[i]))&&this.addResource(e,r,i,n[i],{silent:!0});s.silent||this.emit("added",e,r,n)}addResourceBundle(e,r,n,s,i,o={silent:!1,skipCopy:!1}){let l=[e,r];e.includes(".")&&(l=e.split("."),s=n,n=r,r=l[1]),this.addNamespaces(r);let c=js(this.data,l)||{};o.skipCopy||(n=JSON.parse(JSON.stringify(n))),s?ki(c,n,i):c={...c,...n},ga(this.data,l,c),o.silent||this.emit("added",e,r,n)}removeResourceBundle(e,r){this.hasResourceBundle(e,r)&&delete this.data[e][r],this.removeNamespaces(r),this.emit("removed",e,r)}hasResourceBundle(e,r){return this.getResource(e,r)!==void 0}getResourceBundle(e,r){return r||(r=this.options.defaultNS),this.getResource(e,r)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const r=this.getDataByLanguage(e);return!!(r&&Object.keys(r)||[]).find(s=>r[s]&&Object.keys(r[s]).length>0)}toJSON(){return this.data}}var vi={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,r,n,s){return t.forEach(i=>{var o;e=((o=this.processors[i])==null?void 0:o.process(e,r,n,s))??e}),e}};const Si=Symbol("i18next/PATH_KEY");function wl(){const t=[],e=Object.create(null);let r;return e.get=(n,s)=>{var i;return(i=r==null?void 0:r.revoke)==null||i.call(r),s===Si?t:(t.push(s),r=Proxy.revocable(n,e),r.proxy)},Proxy.revocable(Object.create(null),e).proxy}function br(t,e){const{[Si]:r}=t(wl()),n=(e==null?void 0:e.keySeparator)??".",s=(e==null?void 0:e.nsSeparator)??":",i=(e==null?void 0:e.enableSelector)==="strict";if(r.length>1&&s){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(r[0]))return`${r[0]}${s}${r.slice(1).join(n)}`}return r.join(n)}const rn=t=>!he(t)&&typeof t!="boolean"&&typeof t!="number";class As extends Us{constructor(e,r={}){super(),cl(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=It.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,r={interpolation:{}}){const n={...r};if(e==null)return!1;const s=this.resolve(e,n);if((s==null?void 0:s.res)===void 0)return!1;const i=rn(s.res);return!(n.returnObjects===!1&&i)}extractFromKey(e,r){let n=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;n===void 0&&(n=":");const s=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator;let i=r.ns||this.options.defaultNS||[];const o=n&&e.includes(n),l=!this.options.userDefinedKeySeparator&&!r.keySeparator&&!this.options.userDefinedNsSeparator&&!r.nsSeparator&&!bl(e,n,s);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!==s||n===s&&this.options.ns.includes(d[0]))&&(i=d.shift()),e=d.join(s)}return{key:e,namespaces:he(i)?[i]:i}}translate(e,r,n){let s=typeof r=="object"?{...r}:r;if(typeof s!="object"&&this.options.overloadTranslationOptionHandler&&(s=this.options.overloadTranslationOptionHandler(arguments)),typeof s=="object"&&(s={...s}),s||(s={}),e==null)return"";typeof e=="function"&&(e=br(e,{...this.options,...s})),Array.isArray(e)||(e=[String(e)]),e=e.map(R=>typeof R=="function"?br(R,{...this.options,...s}):String(R));const i=s.returnDetails!==void 0?s.returnDetails:this.options.returnDetails,o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,{key:l,namespaces:c}=this.extractFromKey(e[e.length-1],s),d=c[c.length-1];let u=s.nsSeparator!==void 0?s.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const f=s.lng||this.language,p=s.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(s)}:`${d}${u}${l}`:i?{res:l,usedKey:l,exactUsedKey:l,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(s)}:l;const g=this.resolve(e,s);let h=g==null?void 0:g.res;const x=(g==null?void 0:g.usedKey)||l,y=(g==null?void 0:g.exactUsedKey)||l,k=["[object Number]","[object Function]","[object RegExp]"],C=s.joinArrays!==void 0?s.joinArrays:this.options.joinArrays,L=!this.i18nFormat||this.i18nFormat.handleAsObject,N=s.count!==void 0&&!he(s.count),v=As.hasDefaultValue(s),T=N?this.pluralResolver.getSuffix(f,s.count,s):"",_=s.ordinal&&N?this.pluralResolver.getSuffix(f,s.count,{ordinal:!1}):"",b=N&&!s.ordinal&&s.count===0,$=b&&s[`defaultValue${this.options.pluralSeparator}zero`]||s[`defaultValue${T}`]||s[`defaultValue${_}`]||s.defaultValue;let j=h;L&&!h&&v&&(j=$);const I=rn(j),O=Object.prototype.toString.apply(j);if(L&&j&&I&&!k.includes(O)&&!(he(C)&&Array.isArray(j))){if(!s.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const R=this.options.returnedObjectHandler?this.options.returnedObjectHandler(x,j,{...s,ns:c}):`key '${l} (${this.language})' returned an object instead of string.`;return i?(g.res=R,g.usedParams=this.getUsedParamsDetails(s),g):R}if(o){const R=Array.isArray(j),H=R?[]:{},A=R?y:x;for(const E in j)if(Object.prototype.hasOwnProperty.call(j,E)){const z=`${A}${o}${E}`;v&&!h?H[E]=this.translate(z,{...s,defaultValue:rn($)?$[E]:void 0,joinArrays:!1,ns:c}):H[E]=this.translate(z,{...s,joinArrays:!1,ns:c}),H[E]===z&&(H[E]=j[E])}h=H}}else if(L&&he(C)&&Array.isArray(h))h=h.join(C),h&&(h=this.extendTranslation(h,e,s,n));else{let R=!1,H=!1;!this.isValidLookup(h)&&v&&(R=!0,h=$),this.isValidLookup(h)||(H=!0,h=l);const E=(s.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&H?void 0:h,z=v&&$!==h&&this.options.updateMissing;if(H||R||z){if(this.logger.log(z?"updateKey":"missingKey",f,d,N&&!z?`${l}${this.pluralResolver.getSuffix(f,s.count,s)}`:l,z?$:h),o){const q=this.resolve(l,{...s,keySeparator:!1});q&&q.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 S=[];const W=this.languageUtils.getFallbackCodes(this.options.fallbackLng,s.lng||this.language);if(this.options.saveMissingTo==="fallback"&&W&&W[0])for(let q=0;q<W.length;q++)S.push(W[q]);else this.options.saveMissingTo==="all"?S=this.languageUtils.toResolveHierarchy(s.lng||this.language):S.push(s.lng||this.language);const K=(q,G,te)=>{var M;const Ce=v&&te!==h?te:E;this.options.missingKeyHandler?this.options.missingKeyHandler(q,d,G,Ce,z,s):(M=this.backendConnector)!=null&&M.saveMissing&&this.backendConnector.saveMissing(q,d,G,Ce,z,s),this.emit("missingKey",q,d,G,h)};this.options.saveMissing&&(this.options.saveMissingPlurals&&N?S.forEach(q=>{const G=this.pluralResolver.getSuffixes(q,s);b&&s[`defaultValue${this.options.pluralSeparator}zero`]&&!G.includes(`${this.options.pluralSeparator}zero`)&&G.push(`${this.options.pluralSeparator}zero`),G.forEach(te=>{K([q],l+te,s[`defaultValue${te}`]||$)})}):K(S,l,$))}h=this.extendTranslation(h,e,s,g,n),H&&h===l&&this.options.appendNamespaceToMissingKey&&(h=`${d}${u}${l}`),(H||R)&&this.options.parseMissingKeyHandler&&(h=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${l}`:l,R?h:void 0,s))}return i?(g.res=h,g.usedParams=this.getUsedParamsDetails(s),g):h}extendTranslation(e,r,n,s,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||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});const u=he(e)&&(((d=n==null?void 0:n.interpolation)==null?void 0:d.skipOnVariables)!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let f;if(u){const g=e.match(this.interpolator.nestingRegexp);f=g&&g.length}let 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||s.usedLng,n),u){const g=e.match(this.interpolator.nestingRegexp),h=g&&g.length;f<h&&(n.nest=!1)}!n.lng&&s&&s.res&&(n.lng=this.language||s.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...g)=>(i==null?void 0:i[0])===g[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${g[0]} in key: ${r[0]}`),null):this.translate(...g,r),n)),n.interpolation&&this.interpolator.reset()}const o=n.postProcess||this.options.postProcess,l=he(o)?[o]:o;return e!=null&&(l!=null&&l.length)&&n.applyPostProcessor!==!1&&(e=vi.handle(l,e,r,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...s,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,r={}){let n,s,i,o,l;return he(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(c=>typeof c=="function"?br(c,{...this.options,...r}):c)),e.forEach(c=>{if(this.isValidLookup(n))return;const d=this.extractFromKey(c,r),u=d.key;s=u;let f=d.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const p=r.count!==void 0&&!he(r.count),g=p&&!r.ordinal&&r.count===0,h=r.context!==void 0&&(he(r.context)||typeof r.context=="number")&&r.context!=="",x=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);f.forEach(y=>{var k,C;this.isValidLookup(n)||(l=y,!this.checkedLoadedFor[`${x[0]}-${y}`]&&((k=this.utils)!=null&&k.hasLoadedNamespace)&&!((C=this.utils)!=null&&C.hasLoadedNamespace(l))&&(this.checkedLoadedFor[`${x[0]}-${y}`]=!0,this.logger.warn(`key "${s}" for languages "${x.join(", ")}" won't get resolved as namespace "${l}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),x.forEach(L=>{var T;if(this.isValidLookup(n))return;o=L;const N=[u];if((T=this.i18nFormat)!=null&&T.addLookupKeys)this.i18nFormat.addLookupKeys(N,u,L,y,r);else{let _;p&&(_=this.pluralResolver.getSuffix(L,r.count,r));const b=`${this.options.pluralSeparator}zero`,$=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(r.ordinal&&_.startsWith($)&&N.push(u+_.replace($,this.options.pluralSeparator)),N.push(u+_),g&&N.push(u+b)),h){const j=`${u}${this.options.contextSeparator||"_"}${r.context}`;N.push(j),p&&(r.ordinal&&_.startsWith($)&&N.push(j+_.replace($,this.options.pluralSeparator)),N.push(j+_),g&&N.push(j+b))}}let v;for(;v=N.pop();)this.isValidLookup(n)||(i=v,n=this.getResource(L,y,v,r))}))})}),{res:n,usedKey:s,exactUsedKey:i,usedLng:o,usedNS:l}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,r,n,s={}){var i;return(i=this.i18nFormat)!=null&&i.getResource?this.i18nFormat.getResource(e,r,n,s):this.resourceStore.getResource(e,r,n,s)}getUsedParamsDetails(e={}){const r=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=e.replace&&!he(e.replace);let s=n?e.replace:e;if(n&&typeof e.count<"u"&&(s.count=e.count),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!n){s={...s};for(const i of r)delete s[i]}return s}static hasDefaultValue(e){const r="defaultValue";for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&n.startsWith(r)&&e[n]!==void 0)return!0;return!1}}class ba{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=It.create("languageUtils")}getScriptPartFromCode(e){if(e=zr(e),!e||!e.includes("-"))return null;const r=e.split("-");return r.length===2||(r.pop(),r[r.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(r.join("-"))}getLanguagePartFromCode(e){if(e=zr(e),!e||!e.includes("-"))return e;const r=e.split("-");return this.formatLanguageCode(r[0])}formatLanguageCode(e){if(he(e)&&e.includes("-")){let r;try{r=Intl.getCanonicalLocales(e)[0]}catch{}return r&&this.options.lowerCaseLng&&(r=r.toLowerCase()),r||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(e)}getBestMatchFromCodes(e){if(!e)return null;let r;return e.forEach(n=>{if(r)return;const s=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(s))&&(r=s)}),!r&&this.options.supportedLngs&&e.forEach(n=>{if(r)return;const s=this.getScriptPartFromCode(n);if(this.isSupportedCode(s))return r=s;const i=this.getLanguagePartFromCode(n);if(this.isSupportedCode(i))return r=i;r=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))}),r||(r=this.getFallbackCodes(this.options.fallbackLng)[0]),r}getFallbackCodes(e,r){if(!e)return[];if(typeof e=="function"&&(e=e(r)),he(e)&&(e=[e]),Array.isArray(e))return e;if(!r)return e.default||[];let n=e[r];return n||(n=e[this.getScriptPartFromCode(r)]),n||(n=e[this.formatLanguageCode(r)]),n||(n=e[this.getLanguagePartFromCode(r)]),n||(n=e.default),n||[]}toResolveHierarchy(e,r){const n=this.getFallbackCodes((r===!1?[]:r)||this.options.fallbackLng||[],e),s=[],i=o=>{o&&(this.isSupportedCode(o)?s.push(o):this.logger.warn(`rejecting language code not found in supportedLngs: ${o}`))};return he(e)&&(e.includes("-")||e.includes("_"))?(this.options.load!=="languageOnly"&&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=>{s.includes(o)||i(this.formatLanguageCode(o))}),s}}const ya={zero:0,one:1,two:2,few:3,many:4,other:5},wa={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class kl{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=It.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,r={}){const n=zr(e==="dev"?"en":e),s=r.ordinal?"ordinal":"cardinal",i=JSON.stringify({cleanedCode:n,type:s});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let o;try{o=new Intl.PluralRules(n,{type:s})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),wa;if(!e.match(/-|_/))return wa;const c=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(c,r)}return this.pluralRulesCache[i]=o,o}needsPlural(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),(n==null?void 0:n.resolvedOptions().pluralCategories.length)>1}getPluralFormsOfKey(e,r,n={}){return this.getSuffixes(e,n).map(s=>`${r}${s}`)}getSuffixes(e,r={}){let n=this.getRule(e,r);return n||(n=this.getRule("dev",r)),n?n.resolvedOptions().pluralCategories.sort((s,i)=>ya[s]-ya[i]).map(s=>`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${s}`):[]}getSuffix(e,r,n={}){const s=this.getRule(e,n);return s?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${s.select(r)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",r,n))}}const ka=(t,e,r,n=".",s=!0)=>{let i=fl(t,e,r);return!i&&s&&he(r)&&(i=xn(t,r,n),i===void 0&&(i=xn(e,r,n))),i},sn=t=>t.replace(/\$/g,"$$$$");class va{constructor(e={}){var r;this.logger=It.create("interpolator"),this.options=e,this.format=((r=e==null?void 0:e.interpolation)==null?void 0:r.format)||(n=>n),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:r,escapeValue:n,useRawValueToEscape:s,prefix:i,prefixEscaped:o,suffix:l,suffixEscaped:c,formatSeparator:d,unescapeSuffix:u,unescapePrefix:f,nestingPrefix:p,nestingPrefixEscaped:g,nestingSuffix:h,nestingSuffixEscaped:x,nestingOptionsSeparator:y,maxReplaces:k,alwaysFormat:C}=e.interpolation;this.escape=r!==void 0?r:hl,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=s!==void 0?s:!1,this.prefix=i?Pt(i):o||"{{",this.suffix=l?Pt(l):c||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":f?Pt(f):"-",this.unescapeSuffix=this.unescapePrefix?"":u?Pt(u):"",this.nestingPrefix=p?Pt(p):g||Pt("$t("),this.nestingSuffix=h?Pt(h):x||Pt(")"),this.nestingOptionsSeparator=y||",",this.maxReplaces=k||1e3,this.alwaysFormat=C!==void 0?C:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(r,n)=>(r==null?void 0:r.source)===n?(r.lastIndex=0,r):new RegExp(n,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,r,n,s){var g;let i,o,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=h=>{if(!h.includes(this.formatSeparator)){const C=ka(r,c,h,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(C,void 0,n,{...s,...r,interpolationkey:h}):C}const x=h.split(this.formatSeparator),y=x.shift().trim(),k=x.join(this.formatSeparator).trim();return this.format(ka(r,c,y,this.options.keySeparator,this.options.ignoreJSONStructure),k,n,{...s,...r,interpolationkey:y})};this.resetRegExp(),!this.escapeValue&&typeof e=="string"&&/\$t\([^)]*\{[^}]*\{\{/.test(e)&&this.logger.warn("nesting options string contains interpolated variables with escapeValue: false — if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true.");const u=(s==null?void 0:s.missingInterpolationHandler)||this.options.missingInterpolationHandler,f=((g=s==null?void 0:s.interpolation)==null?void 0:g.skipOnVariables)!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:h=>sn(h)},{regex:this.regexp,safeValue:h=>this.escapeValue?sn(this.escape(h)):sn(h)}].forEach(h=>{for(l=0;i=h.regex.exec(e);){const x=i[1].trim();if(o=d(x),o===void 0)if(typeof u=="function"){const k=u(e,i,s);o=he(k)?k:""}else if(s&&Object.prototype.hasOwnProperty.call(s,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=ma(o));const y=h.safeValue(o);if(e=e.replace(i[0],y),f?(h.regex.lastIndex+=o.length,h.regex.lastIndex-=i[0].length):h.regex.lastIndex=0,l++,l>=this.maxReplaces)break}}),e}nest(e,r,n={}){let s,i,o;const l=(c,d)=>{const u=this.nestingOptionsSeparator;if(!c.includes(u))return c;const f=c.split(new RegExp(`${Pt(u)}[ ]*{`));let p=`{${f[1]}`;c=f[0],p=this.interpolate(p,o);const g=p.match(/'/g),h=p.match(/"/g);(((g==null?void 0:g.length)??0)%2===0&&!h||((h==null?void 0:h.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(;s=this.nestingRegexp.exec(e);){let c=[];o={...n},o=o.replace&&!he(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const d=/{.*}/.test(s[1])?s[1].lastIndexOf("}")+1:s[1].indexOf(this.formatSeparator);if(d!==-1&&(c=s[1].slice(d).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),s[1]=s[1].slice(0,d)),i=r(l.call(this,s[1].trim(),o),o),i&&s[0]===e&&!he(i))return i;he(i)||(i=ma(i)),i||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${e}`),i=""),c.length&&(i=c.reduce((u,f)=>this.format(u,f,n.lng,{...n,interpolationkey:s[1].trim()}),i.trim())),e=e.replace(s[0],i),this.regexp.lastIndex=0}return e}}const vl=t=>{let e=t.toLowerCase().trim();const r={};if(t.includes("(")){const n=t.split("(");e=n[0].toLowerCase().trim();const s=n[1].slice(0,-1);e==="currency"&&!s.includes(":")?r.currency||(r.currency=s.trim()):e==="relativetime"&&!s.includes(":")?r.range||(r.range=s.trim()):s.split(";").forEach(o=>{if(o){const[l,...c]=o.split(":"),d=c.join(":").trim().replace(/^'+|'+$/g,""),u=l.trim();r[u]||(r[u]=d),d==="false"&&(r[u]=!1),d==="true"&&(r[u]=!0),isNaN(d)||(r[u]=parseInt(d,10))}})}return{formatName:e,formatOptions:r}},Sa=t=>{const e={};return(r,n,s)=>{let i=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(i={...i,[s.interpolationkey]:void 0});const o=n+JSON.stringify(i);let l=e[o];return l||(l=t(zr(n),s),e[o]=l),l(r)}},Sl=t=>(e,r,n)=>t(zr(r),n)(e);class jl{constructor(e={}){this.logger=It.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const n=r.cacheInBuiltFormats?Sa:Sl;this.formats={number:n((s,i)=>{const o=new Intl.NumberFormat(s,{...i});return l=>o.format(l)}),currency:n((s,i)=>{const o=new Intl.NumberFormat(s,{...i,style:"currency"});return l=>o.format(l)}),datetime:n((s,i)=>{const o=new Intl.DateTimeFormat(s,{...i});return l=>o.format(l)}),relativetime:n((s,i)=>{const o=new Intl.RelativeTimeFormat(s,{...i});return l=>o.format(l,i.range||"day")}),list:n((s,i)=>{const o=new Intl.ListFormat(s,{...i});return l=>o.format(l)})}}add(e,r){this.formats[e.toLowerCase().trim()]=r}addCached(e,r){this.formats[e.toLowerCase().trim()]=Sa(r)}format(e,r,n,s={}){if(!r||e==null)return e;const i=r.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}=vl(d);if(this.formats[u]){let g=c;try{const h=((p=s==null?void 0:s.formatParams)==null?void 0:p[s.interpolationkey])||{},x=h.locale||h.lng||s.locale||s.lng||n;g=this.formats[u](c,x,{...f,...s,...h})}catch(h){this.logger.warn(h)}return g}else this.logger.warn(`there was no format function for ${u}`);return c},e)}}const Cl=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Al extends Us{constructor(e,r,n,s={}){var i,o;super(),this.backend=e,this.store=r,this.services=n,this.languageUtils=n.languageUtils,this.options=s,this.logger=It.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],(o=(i=this.backend)==null?void 0:i.init)==null||o.call(i,n,s.backend,s)}queueLoad(e,r,n,s){const i={},o={},l={},c={};return e.forEach(d=>{let u=!0;r.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:s}),{toLoad:Object.keys(i),pending:Object.keys(o),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(e,r,n){const s=e.split("|"),i=s[0],o=s[1];r&&this.emit("failedLoading",i,o,r),!r&&n&&this.store.addResourceBundle(i,o,n,void 0,void 0,{skipCopy:!0}),this.state[e]=r?-1:2,r&&n&&(this.state[e]=0);const l={};this.queue.forEach(c=>{ul(c.loaded,[i],o),Cl(c,e),r&&c.errors.push(r),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(d=>{l[d]||(l[d]={});const u=c.loaded[d];u.length&&u.forEach(f=>{l[d][f]===void 0&&(l[d][f]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",l),this.queue=this.queue.filter(c=>!c.done)}read(e,r,n,s=0,i=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:r,fcName:n,tried:s,wait: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&&s<this.maxRetries){setTimeout(()=>{this.read(e,r,n,s+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,r);d&&typeof d.then=="function"?d.then(u=>l(null,u)).catch(l):l(null,d)}catch(d){l(d)}return}return c(e,r,l)}prepareLoading(e,r,n={},s){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();he(e)&&(e=this.languageUtils.toResolveHierarchy(e)),he(r)&&(r=[r]);const i=this.queueLoad(e,r,n,s);if(!i.toLoad.length)return i.pending.length||s(),null;i.toLoad.forEach(o=>{this.loadOne(o)})}load(e,r,n){this.prepareLoading(e,r,{},n)}reload(e,r,n){this.prepareLoading(e,r,{reload:!0},n)}loadOne(e,r=""){const n=e.split("|"),s=n[0],i=n[1];this.read(s,i,"read",void 0,void 0,(o,l)=>{o&&this.logger.warn(`${r}loading namespace ${i} for language ${s} failed`,o),!o&&l&&this.logger.log(`${r}loaded namespace ${i} for language ${s}`,l),this.loaded(e,o,l)})}saveMissing(e,r,n,s,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(r))){this.logger.warn(`did not save key "${n}" as the namespace "${r}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(n==null||n==="")){if((p=this.backend)!=null&&p.create){const g={...o,isUpdate:i},h=this.backend.create.bind(this.backend);if(h.length<6)try{let x;h.length===5?x=h(e,r,n,s,g):x=h(e,r,n,s),x&&typeof x.then=="function"?x.then(y=>l(null,y)).catch(l):l(null,x)}catch(x){l(x)}else h(e,r,n,s,l,g)}!e||!e[0]||this.store.addResource(e[0],r,n,s)}}}const nn=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",enableSelector:!1,partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),he(t[1])&&(e.defaultValue=t[1]),he(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const r=t[3]||t[2];Object.keys(r).forEach(n=>{e[n]=r[n]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),ja=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),cs=()=>{},Nl=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})};class Dr extends Us{constructor(e={},r){if(super(),this.options=ja(e),this.services={},this.logger=It,this.modules={external:[]},Nl(this),r&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,r),this;setTimeout(()=>{this.init(e,r)},0)}}init(e={},r){this.isInitializing=!0,typeof e=="function"&&(r=e,e={}),e.defaultNS==null&&e.ns&&(he(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const n=nn();this.options={...n,...this.options,...ja(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler);const s=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?It.init(s(this.modules.logger),this.options):It.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=jl;const u=new ba(this.options);this.store=new xa(this.options.resources,this.options);const f=this.services;f.logger=It,f.resourceStore=this.store,f.languageUtils=u,f.pluralResolver=new kl(u,{prepend:this.options.pluralSeparator}),d&&(f.formatter=s(d),f.formatter.init&&f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new va(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new Al(s(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(p,...g)=>{this.emit(p,...g)}),this.modules.languageDetector&&(f.languageDetector=s(this.modules.languageDetector),f.languageDetector.init&&f.languageDetector.init(f,this.options.detection,this.options)),this.modules.i18nFormat&&(f.i18nFormat=s(this.modules.i18nFormat),f.i18nFormat.init&&f.i18nFormat.init(this)),this.translator=new As(this.services,this.options),this.translator.on("*",(p,...g)=>{this.emit(p,...g)}),this.modules.external.forEach(p=>{p.init&&p.init(this)})}if(this.format=this.options.interpolation.format,r||(r=cs),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=Mr(),c=()=>{const d=(u,f)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),l.resolve(f),r(u,f)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),l}loadResources(e,r=cs){var i,o;let n=r;const s=he(e)?e:this.language;if(typeof e=="function"&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if((s==null?void 0:s.toLowerCase())==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();const l=[],c=d=>{if(!d||d==="cimode")return;this.services.languageUtils.toResolveHierarchy(d).forEach(f=>{f!=="cimode"&&(l.includes(f)||l.push(f))})};s?c(s):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>c(u)),(o=(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,r,n){const s=Mr();return typeof e=="function"&&(n=e,e=void 0),typeof r=="function"&&(n=r,r=void 0),e||(e=this.languages),r||(r=this.options.ns),n||(n=cs),this.services.backendConnector.reload(e,r,i=>{s.resolve(),n(i)}),s}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&vi.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!["cimode","dev"].includes(e)){for(let r=0;r<this.languages.length;r++){const n=this.languages[r];if(!["cimode","dev"].includes(n)&&this.store.hasLanguageSomeTranslations(n)){this.resolvedLanguage=n;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,r){this.isLanguageChangingTo=e;const n=Mr();this.emit("languageChanging",e);const s=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&&(s(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,n.resolve((...d)=>this.t(...d)),r&&r(l,(...d)=>this.t(...d))},o=l=>{var u,f;!e&&!l&&this.services.languageDetector&&(l=[]);const c=he(l)?l:l&&l[0],d=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(he(l)?[l]:l);d&&(this.language||s(d),this.translator.language||this.translator.changeLanguage(d),(f=(u=this.services.languageDetector)==null?void 0:u.cacheUserLanguage)==null||f.call(u,d)),this.loadResources(d,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,r,n,s){const i=s==null?void 0:s.scopeNs,o=(l,c,...d)=>{let u;typeof c!="object"?u=this.options.overloadTranslationOptionHandler([l,c].concat(d)):u={...c},u.lng=u.lng||o.lng,u.lngs=u.lngs||o.lngs;const f=u.ns!==void 0&&u.ns!==null;u.ns=u.ns||o.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||n||o.keyPrefix);const p={...this.options,...u};Array.isArray(i)&&!f&&(p.ns=i),typeof u.keyPrefix=="function"&&(u.keyPrefix=br(u.keyPrefix,p));const g=this.options.keySeparator||".";let h;return u.keyPrefix&&Array.isArray(l)?h=l.map(x=>(typeof x=="function"&&(x=br(x,p)),`${u.keyPrefix}${g}${x}`)):(typeof l=="function"&&(l=br(l,p)),h=u.keyPrefix?`${u.keyPrefix}${g}${l}`:l),this.t(h,u)};return he(e)?o.lng=e:o.lngs=e,o.ns=r,o.keyPrefix=n,o}t(...e){var r;return(r=this.translator)==null?void 0:r.translate(...e)}exists(...e){var r;return(r=this.translator)==null?void 0:r.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,r={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const n=r.lng||this.resolvedLanguage||this.languages[0],s=this.options?this.options.fallbackLng:!1,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(r.precheck){const l=r.precheck(this,o);if(l!==void 0)return l}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(n,e)&&(!s||o(i,e)))}loadNamespaces(e,r){const n=Mr();return this.options.ns?(he(e)&&(e=[e]),e.forEach(s=>{this.options.ns.includes(s)||this.options.ns.push(s)}),this.loadResources(s=>{n.resolve(),r&&r(s)}),n):(r&&r(),Promise.resolve())}loadLanguages(e,r){const n=Mr();he(e)&&(e=[e]);const s=this.options.preload||[],i=e.filter(o=>!s.includes(o)&&this.services.languageUtils.isSupportedCode(o));return i.length?(this.options.preload=s.concat(i),this.loadResources(o=>{n.resolve(),r&&r(o)}),n):(r&&r(),Promise.resolve())}dir(e){var s,i;if(e||(e=this.resolvedLanguage||(((s=this.languages)==null?void 0:s.length)>0?this.languages[0]:this.language)),!e)return"rtl";try{const o=new Intl.Locale(e);if(o&&o.getTextInfo){const l=o.getTextInfo();if(l&&l.direction)return l.direction}}catch{}const r=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],n=((i=this.services)==null?void 0:i.languageUtils)||new ba(nn());return e.toLowerCase().indexOf("-latn")>1?"ltr":r.includes(n.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},r){const n=new Dr(e,r);return n.createInstance=Dr.createInstance,n}cloneInstance(e={},r=cs){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const s={...this.options,...e,isClone:!0},i=new Dr(s);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 xa(l,s),i.services.resourceStore=i.store}if(e.interpolation){const c={...nn().interpolation,...this.options.interpolation,...e.interpolation},d={...s,interpolation:c};i.services.interpolator=new va(d)}return i.translator=new As(i.services,s),i.translator.on("*",(l,...c)=>{i.emit(l,...c)}),i.init(s,r),i.translator.options=s,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 Xe=Dr.createInstance();Xe.createInstance;Xe.dir;Xe.init;Xe.loadResources;Xe.reloadResources;Xe.use;Xe.changeLanguage;Xe.getFixedT;Xe.t;Xe.exists;Xe.setDefaultNamespace;Xe.hasLoadedNamespace;Xe.loadNamespaces;Xe.loadLanguages;const Il=(t,e,r,n)=>{var i,o,l,c;const s=[r,{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(s,"warn","react-i18next::",!0);or(s[0])&&(s[0]=`react-i18next:: ${s[0]}`),(c=(l=t==null?void 0:t.services)==null?void 0:l.logger)!=null&&c.warn?t.services.logger.warn(...s):console!=null&&console.warn&&console.warn(...s)},Ca={},bn=(t,e,r,n)=>{or(r)&&Ca[r]||(or(r)&&(Ca[r]=new Date),Il(t,e,r,n))},ji=(t,e)=>()=>{if(t.isInitialized)e();else{const r=()=>{setTimeout(()=>{t.off("initialized",r)},0),e()};t.on("initialized",r)}},yn=(t,e,r)=>{t.loadNamespaces(e,ji(t,r))},Aa=(t,e,r,n)=>{if(or(r)&&(r=[r]),t.options.preload&&t.options.preload.indexOf(e)>-1)return yn(t,r,n);r.forEach(s=>{t.options.ns.indexOf(s)<0&&t.options.ns.push(s)}),t.loadLanguages(e,ji(t,n))},Ll=(t,e,r={})=>!e.languages||!e.languages.length?(bn(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(t,{lng:r.lng,precheck:(n,s)=>{if(r.bindI18n&&r.bindI18n.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!s(n.isLanguageChangingTo,t))return!1}}),or=t=>typeof t=="string",El=t=>typeof t=="object"&&t!==null,_l=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,Tl={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},Ml=t=>Tl[t],Fl=t=>t.replace(_l,Ml);let wn={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:Fl,transDefaultProps:void 0};const $l=(t={})=>{wn={...wn,...t}},Pl=()=>wn;let Ci;const Rl=t=>{Ci=t},Dl=()=>Ci,Ul={type:"3rdParty",init(t){$l(t.options.react),Rl(t)}},Ol=m.createContext();class zl{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(r=>{this.usedNamespaces[r]||(this.usedNamespaces[r]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var an={exports:{}},on={};/**
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 Na;function Bl(){if(Na)return on;Na=1;var t=Ho();function e(f,p){return f===p&&(f!==0||1/f===1/p)||f!==f&&p!==p}var r=typeof Object.is=="function"?Object.is:e,n=t.useState,s=t.useEffect,i=t.useLayoutEffect,o=t.useDebugValue;function l(f,p){var g=p(),h=n({inst:{value:g,getSnapshot:p}}),x=h[0].inst,y=h[1];return i(function(){x.value=g,x.getSnapshot=p,c(x)&&y({inst:x})},[f,g,p]),s(function(){return c(x)&&y({inst:x}),f(function(){c(x)&&y({inst:x})})},[f]),o(g),g}function c(f){var p=f.getSnapshot;f=f.value;try{var g=p();return!r(f,g)}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 on.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:u,on}var Ia;function Hl(){return Ia||(Ia=1,an.exports=Bl()),an.exports}var Vl=Hl();const ql=(t,e)=>{if(or(e))return e;if(El(e)&&or(e.defaultValue))return e.defaultValue;if(typeof t=="function")return"";if(Array.isArray(t)){const r=t[t.length-1];return typeof r=="function"?"":r}return t},Wl={t:ql,ready:!1},Kl=()=>()=>{},Le=(t,e={})=>{var $,j,I;const{i18n:r}=e,{i18n:n,defaultNS:s}=m.useContext(Ol)||{},i=r||n||Dl();i&&!i.reportNamespaces&&(i.reportNamespaces=new zl),i||bn(i,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=m.useMemo(()=>{var O;return{...Pl(),...(O=i==null?void 0:i.options)==null?void 0:O.react,...e}},[i,e]),{useSuspense:l,keyPrefix:c}=o,d=s||(($=i==null?void 0:i.options)==null?void 0:$.defaultNS),u=or(d)?[d]:d||["translation"],f=m.useMemo(()=>u,u);(I=(j=i==null?void 0:i.reportNamespaces)==null?void 0:j.addUsedNamespaces)==null||I.call(j,f);const p=m.useRef(0),g=m.useCallback(O=>{if(!i)return Kl;const{bindI18n:R,bindI18nStore:H}=o,A=()=>{p.current+=1,O()};return R&&i.on(R,A),H&&i.store.on(H,A),()=>{R&&R.split(" ").forEach(E=>i.off(E,A)),H&&H.split(" ").forEach(E=>i.store.off(E,A))}},[i,o]),h=m.useRef(),x=m.useCallback(()=>{if(!i)return Wl;const O=!!(i.isInitialized||i.initializedStoreOnce)&&f.every(S=>Ll(S,i,o)),R=e.lng||i.language,H=p.current,A=h.current;if(A&&A.ready===O&&A.lng===R&&A.keyPrefix===c&&A.revision===H)return A;const z={t:i.getFixedT(R,o.nsMode==="fallback"?f:f[0],c,{scopeNs:f}),ready:O,lng:R,keyPrefix:c,revision:H};return h.current=z,z},[i,f,c,o,e.lng]),[y,k]=m.useState(0),{t:C,ready:L}=Vl.useSyncExternalStore(g,x,x);m.useEffect(()=>{if(i&&!L&&!l){const O=()=>k(R=>R+1);e.lng?Aa(i,e.lng,f,O):yn(i,f,O)}},[i,e.lng,f,L,l,y]);const N=i||{},v=m.useRef(null),T=m.useRef(),_=O=>{const R=Object.getOwnPropertyDescriptors(O);R.__original&&delete R.__original;const H=Object.create(Object.getPrototypeOf(O),R);if(!Object.prototype.hasOwnProperty.call(H,"__original"))try{Object.defineProperty(H,"__original",{value:O,writable:!1,enumerable:!1,configurable:!1})}catch{}return H},b=m.useMemo(()=>{const O=N,R=O==null?void 0:O.language;let H=O;O&&(v.current&&v.current.__original===O?T.current!==R?(H=_(O),v.current=H,T.current=R):H=v.current:(H=_(O),v.current=H,T.current=R));const A=!L&&!l?(...z)=>(bn(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."),C(...z)):C,E=[A,H,L];return E.t=A,E.i18n=H,E.ready=L,E},[C,N,L,N.resolvedLanguage,N.language,N.languages]);if(i&&l&&!L)throw new Promise(O=>{const R=()=>O();e.lng?Aa(i,e.lng,f,R):yn(i,f,R)});return b},Gl={de:{translation:Qo},en:{translation:Yo},es:{translation:Xo},fr:{translation:Go},ja:{translation:Ko},pt:{translation:Wo},zh:{translation:qo}};Xe.use(Ul).init({resources:Gl,lng:"en",fallbackLng:"en",interpolation:{escapeValue:!1},returnNull:!1});var Xl={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:!1,enableConversationThreads:!0,enableAutocomplete:!0},voice:{silenceTimeoutMs:4e3,recognitionLanguage:""},limits:{files:{perConversation:5,maxSizeMB:50,totalFiles:100},conversations:{maxConversations:10,messagesPerConversation:1e3,messagesPerThread:1e3,totalMessages:1e4},messages:{maxLength:1e4}},guestLimits:{files:{perConversation:1,maxSizeMB:5,totalFiles:1},conversations:{maxConversations:2,messagesPerConversation:5,messagesPerThread:2,totalMessages:10},messages:{maxLength:500},rateLimit:{enabled:!0,windowMs:6e4,maxRequests:60,chat:{windowMs:6e4,maxRequests:10}}},auth:{enabled:!1,provider:"entra"},header:{enabled:!0,logoUrl:"",logoUrlLight:"",logoUrlDark:"",logoHeight:"3.5rem",logoWidth:"auto",bgColor:"",textColor:"",showBorder:!1,navLinks:[{label:"Docs",url:"/"},{label:"About",url:"/about"}]},footer:{enabled:!0,text:"Copyright © 2025 Schmitech Inc.",bgColor:"",textColor:"",showBorder:!1,layout:"stacked",align:"center",topPadding:"large",navLinks:[{label:"Support",url:"/"},{label:"Privacy",url:"/about"}]},adapters:[{id:"simple-chat",name:"Simple AI Chat",apiUrl:"http://localhost:3000",description:"Basic chat interface using the default conversational agent (Similar to ChatGPT - no files).",inputPlaceholder:"Simple chat, ask anything..."},{id:"web-search",name:"Simple AI Chat (Web Search)",apiUrl:"http://localhost:3000",description:"Basic chat interface using the default conversational agent with web search supports.",inputPlaceholder:"Simple chat, ask anything..."},{id:"chat-with-files",name:"Simple AI Chat (Multimodal)",apiUrl:"http://localhost:3000",description:"Extract knowledge from PDF, Images, Word, etc. (Similar to ChatGPT Multimodal)",inputPlaceholder:"Files chat, ask anything..."},{id:"image-generator",name:"AI Image Generator",apiUrl:"http://localhost:3000",description:"Generate images from text descriptions using DALL-E 3 or Imagen 3.",inputPlaceholder:"Describe the image you want to create..."},{id:"video-generator",name:"AI Video Generator",apiUrl:"http://localhost:3000",description:"Generate videos from text descriptions.",inputPlaceholder:"Describe the video you want to create..."},{id:"audio-generator",name:"AI Audio Generator",apiUrl:"http://localhost:3000",description:"Convert text to natural-sounding speech using AI voices.",inputPlaceholder:"Type the text you want to convert to speech..."},{id:"qa-sql",name:"City FAQ Assistant (SQLite)",apiUrl:"http://localhost:3000",description:"Quick-test QA assistant over the sample city Q&A SQLite database.",inputPlaceholder:"Ask a city services question..."},{id:"qa-vector-chroma",name:"City FAQ Assistant (Chroma)",apiUrl:"http://localhost:3000",description:"Quick-test semantic QA assistant over the sample city Q&A Chroma collection.",inputPlaceholder:"Ask a city services question..."},{id:"hr-db-chatbot",name:"HR System Assistant",apiUrl:"http://localhost:3000",description:"HR database assistant: natural language queries over SQLite HR data via intent templates.",inputPlaceholder:"Ask HR questions..."},{id:"intent-sql-postgres",name:"Customer Orders Assistant",apiUrl:"http://localhost:3000",description:"Customer orders assistant: natural language queries over PostgreSQL customer orders data."},{id:"ecomm-analytics",name:"Business Analytics Assistant",apiUrl:"http://localhost:3000",description:"DuckDB analytics assistant: natural language analytics queries over the analytics demo. This agent is the perfect example of how to use something like OLAP to quickly discover insigths."},{id:"composite-multi-source-explorer",name:"Multi-Source Explorer",apiUrl:"http://localhost:3000",description:"Multi-domain assistant: natural language over HR (SQLite), customer orders (PostgreSQL), and sales analytics (DuckDB)—one chat, retrieval routes each question to the best source.",inputPlaceholder:"Ask about employees, orders, or sales analytics..."},{id:"intent-http-jsonplaceholder",name:"REST API Chat",apiUrl:"http://localhost:3000",description:"Natural language queries over the fake REST API."},{id:"intent-http-paris-opendata",name:"City of Paris Chat",apiUrl:"http://localhost:3000",description:"Paris open data: events and activities (Que Faire à Paris) via natural language."},{id:"intent-mongodb-mflix",name:"Chat With Movies DB",apiUrl:"http://localhost:3000",description:"MFlix movies assistant: query the sample_mflix MongoDB database via intent templates."},{id:"intent-graphql-spacex",name:"GraphQL Chatbot",apiUrl:"http://localhost:3000",description:"SpaceX GraphQL assistant: natural language queries over the SpaceX API.",inputPlaceholder:"Ask SpaceX questions..."},{id:"audio-transcription",name:"Audio Transcription",apiUrl:"http://localhost:3000",description:"Audio Transcription Test.",inputPlaceholder:"Use the microphone for voice..."},{id:"voice-chat",name:"Voice Chat",apiUrl:"http://localhost:3000",description:"Voice chat adapter test.",inputPlaceholder:"Use the microphone for voice..."},{id:"real-time-voice-chat",name:"Real-Time Voice Chat",apiUrl:"http://localhost:3000",description:"Real-time voice chat adapter test (websocket).",inputPlaceholder:"Use the microphone for voice..."},{id:"intent-elasticsearch-log",name:"Log Analysis Assistant",apiUrl:"http://localhost:3000",description:"Analyze app logs, troubleshoot errors, and monitor performance via Elasticsearch."}]};const kn="http://localhost:3000",Yl="/favicon.svg",Ql="/orbit-logo-light.png",Zl="/orbit-logo-dark.png",Jl={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 ds(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vn(t,e){if(!ds(t)||!ds(e))return e;const r={...t};return Object.keys(e).forEach(n=>{if(n==="__proto__"||n==="constructor"||n==="prototype")return;const s=r[n],i=e[n];ds(s)&&ds(i)?r[n]=vn(s,i):i!==void 0&&(r[n]=i)}),r}function ec(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;const r=e.toLowerCase();return r==="false"||r==="0"||r==="off"||r==="disabled"?null:e}function tc(t){return t==="single"?"single":"multi"}function rc(t){const e=t.trim();if(e.startsWith("["))try{const r=JSON.parse(e);return Array.isArray(r)?r.filter(Boolean):[]}catch{return[]}return e.split(/\s+/).filter(Boolean)}function sc(){const t=Xl||{},e=typeof window<"u"&&window.ORBIT_CHAT_CONFIG||{},r=!!(typeof window<"u"&&window.ORBIT_CHAT_CONFIG);let n=vn(Jl,t);return n=vn(n,e),(!r||!n.auth.domain)&&(n.auth.domain="dev-3c4dpzhecz4gundm.us.auth0.com"),(!r||!n.auth.clientId)&&(n.auth.clientId="9JSe5xtoi5mLXRuov2K7FHYU10ojCQLH"),!r||n.auth.audience,!r||n.auth.provider,!r||n.auth.tenantId,(!r||n.auth.scopes.length===0)&&(n.auth.scopes=rc("openid profile email User.Read")),n.outOfServiceMessage=ec(n.outOfServiceMessage),n.agentMode.mode=tc(n.agentMode.mode),n.agentMode.defaultAdapterId=typeof n.agentMode.defaultAdapterId=="string"?n.agentMode.defaultAdapterId.trim():"",n}const Z=sc();function Fe(){var e;const t=Z.adapters;if(Array.isArray(t)&&t.length>0){const r=(e=t[0].apiUrl)==null?void 0:e.trim();if(r)return r}return kn}function at(t){const e=t==null?void 0:t.trim();return e&&e.length>0?e:Fe()}function nc(){const t=Z.adapters;return Array.isArray(t)&&t.length>0?t[0].id:"default-key"}function ac(){return Z.agentMode.mode}function Os(){return ac()==="single"}function $n(){if(!Os())return null;const t=Z.agentMode.defaultAdapterId;return t&&Z.adapters.some(r=>{var n;return((n=r==null?void 0:r.id)==null?void 0:n.trim())===t})?t:null}function Ai(){const t=Array.isArray(Z.i18n.activeLanguages)?Z.i18n.activeLanguages.filter(e=>typeof e=="string"):[];return t.length>0?t:["en"]}function ic(){var e;const t=(e=Z.i18n.defaultLanguage)==null?void 0:e.trim();return t&&Ai().includes(t)?t:"en"}function Pn(){return Z.application.name}function Rn(){return Z.application.description}function Ni(){return Z.application.inputPlaceholder}function oc(t){var s;const e=t==null?void 0:t.trim();if(!e)return null;const r=Z.adapters.find(i=>{var o;return((o=i==null?void 0:i.id)==null?void 0:o.trim())===e});return((s=r==null?void 0:r.name)==null?void 0:s.trim())||null}function lc(t){var s;const e=t==null?void 0:t.trim();if(!e)return null;const r=Z.adapters.find(i=>{var o;return((o=i==null?void 0:i.id)==null?void 0:o.trim())===e});return((s=r==null?void 0:r.inputPlaceholder)==null?void 0:s.trim())||null}function Ii(){return Z.seo.siteUrl.trim()}function cc(){return Array.isArray(Z.seo.alternateSiteUrls)?Z.seo.alternateSiteUrls.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function dc(){return Array.isArray(Z.seo.hostPatterns)?Z.seo.hostPatterns.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function uc(){return Z.seo.exposeAgentNotes}function fc(){var e;return((e=Z.application.favicon)==null?void 0:e.trim())||Yl}function mc(){return Z.features.enableUpload}function hc(){return Z.features.enableAudioOutput}function pc(){return Z.features.enableAudioInput}function us(){return Z.features.enableFeedbackButtons}function gc(){return Z.features.enableConversationThreads}function Li(){return Z.features.enableAutocomplete}function xc(){return Math.max(1e3,Z.voice.silenceTimeoutMs)}function bc(){return Z.voice.recognitionLanguage}function yc(){const t=$n();if(t)return t;const e=Z.adapters;if(Array.isArray(e)&&e.length>0)for(const r of e){const n=typeof(r==null?void 0:r.id)=="string"?r.id.trim():"";if(n)return n}return null}function wc(){return Z.outOfServiceMessage}function Dn(){return Z.auth.enabled}function tt(){const{enabled:t,provider:e,domain:r,clientId:n,tenantId:s}=Z.auth;return!t||!n?!1:e==="entra"?!!s:!!r}function kc(){return Z.auth.domain}function Ei(){return Z.auth.clientId}function vc(){return Z.auth.audience}function zs(){return Z.auth.provider}function Sc(){return Z.auth.tenantId}function Un(){const t=Z.auth.scopes;return t.length>0?t:["openid","profile","email"]}function Sn(){return Z.header.enabled}function jc(){return Z.header.logoUrl}function Cc(){var e;return((e=Z.header.logoUrlLight)==null?void 0:e.trim())||Ql}function Ac(){var e;return((e=Z.header.logoUrlDark)==null?void 0:e.trim())||Zl}function Nc(){var t;return((t=Z.header.logoHeight)==null?void 0:t.trim())||""}function Ic(){var t;return((t=Z.header.logoWidth)==null?void 0:t.trim())||""}function Lc(){return Z.header.bgColor}function Ec(){return Z.header.textColor}function _c(){return Z.header.showBorder}function _i(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 Ti(){return _i(Z.header.navLinks)}function Mi(){return Z.footer.enabled}function Tc(){return Z.footer.text}function Mc(){return Z.footer.bgColor}function Fc(){return Z.footer.textColor}function $c(){return Z.footer.showBorder}function Pc(){return Z.footer.layout==="inline"?"inline":"stacked"}function Rc(){return Z.footer.topPadding==="normal"?"normal":"large"}function Dc(){const t=Z.startupScripts;return Array.isArray(t)?t.filter(e=>!!(e&&typeof e=="object")).map(e=>{const r=typeof e.src=="string"?e.src.trim():"",n=typeof e.content=="string"?e.content.trim():"",s=typeof e.id=="string"?e.id.trim():"";return{...e,src:r||void 0,content:n||void 0,id:s||void 0}}).filter(e=>!!(e.src||e.content)):[]}function Uc(){return _i(Z.footer.navLinks)}const Fi=["de","en","es","fr","ja","pt","zh"],fs={de:"Deutsch",en:"English",es:"Español",fr:"Français",ja:"日本語",pt:"Português",zh:"中文"};function vs(t){return Fi.includes(t)}const $i=m.createContext(void 0),Pi="orbit-chat-language";function Oc(){const t=Ai().filter(vs);return t.length>0?t:["en"]}function zc(t){const e=localStorage.getItem(Pi);if(e&&vs(e)&&t.includes(e))return e;const r=[...navigator.languages||[],navigator.language].filter(Boolean);for(const s of r){const i=s.split("-")[0].toLowerCase();if(vs(i)&&t.includes(i))return i}const n=ic();return vs(n)&&t.includes(n)?n:t[0]??"en"}function Bc({children:t}){const[e]=m.useState(()=>Oc()),[r,n]=m.useState(()=>zc(e));m.useEffect(()=>{Xe.changeLanguage(r)},[r]),m.useEffect(()=>{localStorage.setItem(Pi,r)},[r]);const s=i=>{Fi.includes(i)&&n(i)};return a.jsx($i.Provider,{value:{currentLanguage:r,activeLanguages:e,setLanguage:s},children:t})}function Hc(){const t=m.useContext($i);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 Vc=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ri=(...t)=>t.filter((e,r,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===r).join(" ").trim();/**
16
- * @license lucide-react v0.469.0 - ISC
17
- *
18
- * This source code is licensed under the ISC license.
19
- * See the LICENSE file in the root directory of this source tree.
20
- */var qc={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 Wc=m.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:s="",children:i,iconNode:o,...l},c)=>m.createElement("svg",{ref:c,...qc,width:e,height:e,stroke:t,strokeWidth:n?Number(r)*24/Number(e):r,className:Ri("lucide",s),...l},[...o.map(([d,u])=>m.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 ne=(t,e)=>{const r=m.forwardRef(({className:n,...s},i)=>m.createElement(Wc,{ref:i,iconNode:e,className:Ri(`lucide-${Vc(t)}`,n),...s}));return r.displayName=`${t}`,r};/**
31
- * @license lucide-react v0.469.0 - ISC
32
- *
33
- * This source code is licensed under the ISC license.
34
- * See the LICENSE file in the root directory of this source tree.
35
- */const Ns=ne("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 ir=ne("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 wr=ne("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 La=ne("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 Is=ne("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 jn=ne("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/**
61
- * @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 Kc=ne("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 Ea=ne("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
71
- * @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 _a=ne("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
76
- * @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 Bs=ne("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/**
81
- * @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 Gc=ne("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/**
86
- * @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 Xc=ne("FileArchive",[["path",{d:"M10 12v-1",key:"v7bkov"}],["path",{d:"M10 18v-2",key:"1cjy8d"}],["path",{d:"M10 7V6",key:"dljcrl"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v16a2 2 0 0 0 .274 1.01",key:"gkbcor"}],["circle",{cx:"10",cy:"20",r:"2",key:"1xzdoj"}]]);/**
91
- * @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 Yc=ne("FileAudio",[["path",{d:"M17.5 22h.5a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"rslqgf"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 19a2 2 0 1 1 4 0v1a2 2 0 1 1-4 0v-4a6 6 0 0 1 12 0v4a2 2 0 1 1-4 0v-1a2 2 0 1 1 4 0",key:"9f7x3i"}]]);/**
96
- * @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 Di=ne("FileCode",[["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}]]);/**
101
- * @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 Qc=ne("FileImage",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]]);/**
106
- * @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 Ui=ne("FileSpreadsheet",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]]);/**
111
- * @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 Cn=ne("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/**
116
- * @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 Zc=ne("FileVideo",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m10 11 5 3-5 3v-6Z",key:"7ntvm4"}]]);/**
121
- * @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 Jc=ne("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);/**
126
- * @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 ed=ne("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/**
131
- * @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 td=ne("Languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]);/**
136
- * @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 Oi=ne("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
141
- * @license lucide-react v0.469.0 - ISC
142
- *
143
- * This source code is licensed under the ISC license.
144
- * See the LICENSE file in the root directory of this source tree.
145
- */const zi=ne("LogIn",[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]]);/**
146
- * @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 rd=ne("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/**
151
- * @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 sd=ne("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/**
156
- * @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 nd=ne("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/**
161
- * @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 Ta=ne("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/**
166
- * @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 ad=ne("MicOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
171
- * @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 id=ne("Mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
176
- * @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 od=ne("Monitor",[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]]);/**
181
- * @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 ld=ne("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
186
- * @license lucide-react v0.469.0 - ISC
187
- *
188
- * This source code is licensed under the ISC license.
189
- * See the LICENSE file in the root directory of this source tree.
190
- */const cd=ne("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
191
- * @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 dd=ne("PanelLeftClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);/**
196
- * @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 ud=ne("PanelLeftOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]);/**
201
- * @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 fd=ne("Paperclip",[["path",{d:"M13.234 20.252 21 12.3",key:"1cbrk9"}],["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 0 2.828 2 2 0 0 0 2.828 0l8.414-8.586a4 4 0 0 0 0-5.656 4 4 0 0 0-5.656 0l-8.415 8.585a6 6 0 1 0 8.486 8.486",key:"1pkts6"}]]);/**
206
- * @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 md=ne("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/**
211
- * @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 Bi=ne("Pen",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]]);/**
216
- * @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 hd=ne("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
221
- * @license lucide-react v0.469.0 - ISC
222
- *
223
- * This source code is licensed under the ISC license.
224
- * See the LICENSE file in the root directory of this source tree.
225
- */const pd=ne("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/**
226
- * @license lucide-react v0.469.0 - ISC
227
- *
228
- * This source code is licensed under the ISC license.
229
- * See the LICENSE file in the root directory of this source tree.
230
- */const Hi=ne("Presentation",[["path",{d:"M2 3h20",key:"91anmk"}],["path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3",key:"2k9sn8"}],["path",{d:"m7 21 5-5 5 5",key:"bip4we"}]]);/**
231
- * @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 gd=ne("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
236
- * @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 xd=ne("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
241
- * @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 Ls=ne("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
246
- * @license lucide-react v0.469.0 - ISC
247
- *
248
- * This source code is licensed under the ISC license.
249
- * See the LICENSE file in the root directory of this source tree.
250
- */const Ma=ne("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
251
- * @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 On=ne("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/**
256
- * @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 bd=ne("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
261
- * @license lucide-react v0.469.0 - ISC
262
- *
263
- * This source code is licensed under the ISC license.
264
- * See the LICENSE file in the root directory of this source tree.
265
- */const yd=ne("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/**
266
- * @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 Vi=ne("ThumbsDown",[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]]);/**
271
- * @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 qi=ne("ThumbsUp",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
276
- * @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 Wi=ne("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/**
281
- * @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 wd=ne("Trash",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}]]);/**
286
- * @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 zn=ne("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
291
- * @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 kd=ne("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/**
296
- * @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 Bn=ne("Volume2",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]]);/**
301
- * @license lucide-react v0.469.0 - ISC
302
- *
303
- * This source code is licensed under the ISC license.
304
- * See the LICENSE file in the root directory of this source tree.
305
- */const vd=ne("VolumeX",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]]);/**
306
- * @license lucide-react v0.469.0 - ISC
307
- *
308
- * This source code is licensed under the ISC license.
309
- * See the LICENSE file in the root directory of this source tree.
310
- */const Ge=ne("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/**
311
- * @license lucide-react v0.469.0 - ISC
312
- *
313
- * This source code is licensed under the ISC license.
314
- * See the LICENSE file in the root directory of this source tree.
315
- */const Sd=ne("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);/**
316
- * @license lucide-react v0.469.0 - ISC
317
- *
318
- * This source code is licensed under the ISC license.
319
- * See the LICENSE file in the root directory of this source tree.
320
- */const jd=ne("ZoomIn",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);function Cd(t){const e=t.trim().split(`
321
- `);if(e.length<2)return!1;const r=e[0].trim();if(!r.startsWith("|")||(r.match(/\|/g)||[]).length<2)return!1;const n=e[1].trim();if(!n.startsWith("|")||!/^[\s|:|-]+$/.test(n)||!n.includes("-"))return!1;for(let s=2;s<e.length;s++){const i=e[s].trim();if(i!==""&&!i.startsWith("|"))return!1}return!0}function Ad(t){return t.replace(/(^|\n)(```|~~~)\s*\n([\s\S]*?)\n\2(\n|$)/g,(e,r,n,s,i)=>Cd(s)?`${r}
322
- ${s.trim()}
323
- ${i}`:e)}function Nd(t){const e={};let r=0;return t=t.replace(/\$\$([\s\S]*?)\$\$/g,(n,s)=>{const i=`__DISPLAY_MATH_${r++}__`;return e[i]=`$$${s}$$`,i}),t=t.replace(/\\\[([\s\S]*?)\\\]/g,(n,s)=>{const i=`__DISPLAY_MATH_${r++}__`;return e[i]=`$$${s}$$`,i}),t=t.replace(/\\\(([\s\S]*?)\\\)/g,(n,s)=>{const i=`__INLINE_MATH_${r++}__`;return e[i]=`$${s}$`,i}),t=t.replace(/(^|\n)(```|~~~)([^\n]*)\n([\s\S]*?)\n\2(\n|$)/g,(n,s,i,o,l,c)=>{const d=`__FENCED_CODE_${r++}__`;return e[d]=`${s}${i}${o}
324
- ${l}
325
- ${i}${c}`,d}),t=t.replace(/`([^`]+)`/g,n=>{const s=`__INLINE_CODE_${r++}__`;return e[s]=n,s}),{masked:t,masks:e}}function Id(t){const e={};let r=0;return t=t.replace(new RegExp("(?<!\\$)\\$(?!\\$)([^$\\n]+?)(?<!\\$)\\$(?!\\$)","g"),(n,s)=>{const i=s.trim();if(/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?(?:\s?[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion)?$/.test(i))return n;const l=`__INLINE_MATH_${r++}__`;return e[l]=`$${s}$`,l}),{masked:t,masks:e}}const Fa=/\\(?: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 Ld(t){const e=/(__INLINE_MATH_\d+__|__DISPLAY_MATH_\d+__|__CURRENCY_\d+__)/g,r=/^(__INLINE_MATH_\d+__|__DISPLAY_MATH_\d+__|__CURRENCY_\d+__)$/;return t.split(`
326
- `).map(n=>Fa.test(n)?n.split(e).map(s=>!s||r.test(s)||!Fa.test(s)||s.includes("$")?s:s.replace(/\\(?:iiint|iint|oint|int|sum|prod|lim|frac|sqrt|sin|cos|tan|sec|csc|cot|arcsin|arccos|arctan|ln|log|exp|Delta|nabla|partial)\b[^\n]*/g,i=>{const o=i.trimEnd();return o?`$${o}$${i.slice(o.length)}`:i})).join(""):n).join(`
327
- `)}function Ed(t){return t.replace(/\$([^$\n]*?)\s*=\s*\$([^$\n]+)\$\s*([^$\n]*?)\$/g,(e,r,n,s)=>{const i=String(r).trimEnd(),o=String(n).trim(),l=String(s).trim(),c=[o,l].filter(Boolean).join(" ");return`$${i} = ${c}$`})}function _d(t){const e=t.split(`
328
- `);for(let n=0;n<e.length-1;n++){const s=e[n],i=e[n+1]??"";if(!s||!i)continue;const o=i.trim();if(!(o.startsWith("|")&&o.includes("-")))continue;const c=s.indexOf("|");if(c<=0)continue;const d=s.slice(0,c);if(!d||d.trim()==="")continue;const u=d.trim(),f=u.replace(/\s+/g,""),p=f!==""&&/^[>]+$/.test(f),g=/^[-*+]\s*$/.test(u),h=/^\d+\.\s*$/.test(u);if(p||g||h)continue;const x=s.slice(c);if((x.match(/\|/g)||[]).length<2)continue;const k=d.replace(/\s+$/,""),C=x.replace(/^\s+/,"");k&&(e.splice(n,1,k,C),n++)}const r=[];for(let n=0;n<e.length;n++){const s=e[n],i=s.trim(),l=(e[n+1]??"").trim();i.startsWith("|")&&(i.match(/\|/g)||[]).length>=2&&l.startsWith("|")&&/^[\s|:-]+$/.test(l)&&l.includes("-")&&r.length>0&&r[r.length-1].trim()!==""&&r.push(""),r.push(s)}return r.join(`
329
- `)}const $a=["aligned","align","align*","array","cases","pmatrix","bmatrix","vmatrix","Vmatrix","matrix","smallmatrix","gather","gather*","multline","multline*","split","flalign","flalign*","eqnarray","equation","equation*"];function Td(t,e){let r=0,n=`__${e}_${r}__`;for(;Object.prototype.hasOwnProperty.call(t,n);)r++,n=`__${e}_${r}__`;return n}function Md(t,e){if(!$a.length)return t;const r=$a.join("|"),n=new RegExp(String.raw`\\begin\{(${r})\}([\s\S]*?)\\end\{\1\}`,"g");return t.replace(n,(s,i,o,l,c)=>{const d=c.slice(0,l),u=c.slice(l+s.length),f=/(\$\$|\\\[)\s*$/.test(d),p=/^\s*(\$\$|\\\])/.test(u);if(f&&p)return s;const g=d.lastIndexOf("\\["),h=d.lastIndexOf("\\]");if(g>h&&g!==-1&&/\\]/.test(u))return s;const y=/\$\$/g;let k=0;for(;y.exec(d)!==null;)k++;if(k%2===1&&/\$\$/.test(u))return s;if((d.replace(/\$\$/g,"__DD__").replace(/\\\$/g,"__ES__").match(/\$/g)||[]).length%2===1){const j=u.replace(/\$\$/g,"__DD__").replace(/\\\$/g,"__ES__");if(/^[^$]*\$(?!\$)/.test(j))return s}const _=Td(e,"LATEX_ENV"),b=s.trim();return e[_]=`
330
- $$
331
- ${b}
332
- $$
333
- `,_})}function Fd(t,e){for(const[r,n]of Object.entries(e)){const s=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");t=t.replace(s,()=>n)}return t}const $d=t=>{if(!t||typeof t!="string")return"";try{let e=t.replace(/\r\n/g,`
334
- `).replace(/\r/g,`
335
- `);e=Ad(e);const{masked:r,masks:n}=Nd(e);e=r,e=e.replace(/<br\s*\/?>/gi,`
336
- `),e=e.replace(/\\(ne|neq)\$(?=\s*[-+0-9A-Za-z(])/g,"\\$1"),e=Ed(e),e=_d(e),e=Md(e,n);const s=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,g,h,x)=>{const y=`__CURRENCY_${i++}__`,k=`__CURRENCY_${i++}__`;return s.set(y,g),s.set(k,x),`${y}${h}${k}`});const c=new RegExp(String.raw`-?\$\(?\d{1,3}(?:,\d{3})*(?:\.\d+)?\)?(?:\s?(?:[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion))?(?!\w)|\$-?\d+(?:\.\d+)?(?:\s?(?:[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion))?(?!\w)`,"g");e=e.replace(c,(p,g,h)=>{if(h.substring(g+p.length).match(/^[a-zA-Z]/)&&!p.match(/[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion$/))return p;const y=`__CURRENCY_${i++}__`;return s.set(y,p),y});const{masked:d,masks:u}=Id(e);return e=d,Object.assign(n,u),e=Ld(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,(g,h)=>{if(g.includes("$")||g.includes("__INLINE_MATH_")||g.includes("__DISPLAY_MATH_")||g.includes("__CURRENCY_"))return g;const x=String(h??"").trim();if(/^[A-Za-z]$/.test(x))return g;const y=/[\\^_+=<>]|\\b(?:frac|sqrt|sum|int|lim|log|ln|sin|cos|tan|exp)\b/.test(x),k=/\d/.test(x),C=/[()]/.test(x),L=(x.match(/[A-Z]/g)||[]).length,N=(x.match(/[a-z]/g)||[]).length,v=L>=2,T=k||C||v&&N>0;return!y&&!T?g:g.replace(h,`$${h}$`)})}),e=e.replace(new RegExp("(?<!\\\\)\\$(?!\\$)([^$\\n]*?)(?<!\\\\)\\$(?!\\$)","g"),(p,g)=>{if(p.includes("__CURRENCY_")||p.includes("__INLINE_MATH_")||p.includes("__DISPLAY_MATH_")||g.trim()==="")return p;const h=/^\d+(?:,\d{3})*(?:\.\d{2})?$/.test(g.trim()),x=/\\/.test(g),y=/[+\-*/=<>^_{}()]/.test(g),k=/[a-zA-Z].*\d|\d.*[a-zA-Z]/.test(g),C=/\\(?:alpha|beta|gamma|delta|epsilon|theta|lambda|mu|pi|sigma|omega)/.test(g),L=/\\(?:frac|sqrt|sum|int|lim|log|ln|sin|cos|tan|exp)/.test(g),N=/^[A-Za-z]$/.test(g.trim());return!h&&(x||y||k||C||L||N||g.length>1)?p:`\\$${g}\\$`}),e=e.split(`
337
- `).map(p=>{const g=p.indexOf("$$");return g===-1||p.trim()==="$$"||p.indexOf("$$",g+2)!==-1?p:p.replace("$$","\\$\\$")}).join(`
338
- `),s.forEach((p,g)=>{const h=p.replace(/\$/g,"&#36;");e=e.replace(new RegExp(g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),h)}),e=e.replace(/\\&#36;/g,"&#36;"),e=Fd(e,n),e=e.trimEnd()+`
339
- `,e}catch(e){return console.warn("Error preprocessing markdown:",e),t}},Pd=m.lazy(()=>Nt(()=>import("./MermaidRenderer-DXFZlHFF.js").then(t=>t.au),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.MermaidRenderer}))),Rd=m.lazy(()=>Nt(()=>import("./SVGRenderer-24uWGqbU.js"),__vite__mapDeps([6,1,3,5,7,8,9,2,10])).then(t=>({default:t.SVGRenderer}))),Dd=m.lazy(()=>Nt(()=>import("./ChartRenderer-Dv1-lA9R.js"),__vite__mapDeps([11,1,5,4,12,13,14,15,16,17,7,8,9,2,10])).then(t=>({default:t.ChartRenderer}))),Ud=m.lazy(()=>Nt(()=>import("./MusicRenderer-CpffrqTQ.js"),__vite__mapDeps([18,2,1,5,7,8,9,10])).then(t=>({default:t.MusicRenderer}))),Od=t=>{var n,s;if(!t)return typeof window<"u"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light";const e=t.closest(".markdown-content");if(e){if(e.classList.contains("dark"))return"dark";if(e.classList.contains("light"))return"light"}if(t.closest(".dark"))return"dark";if(t.closest(".light"))return"light";const r=t.closest("[data-theme]");if(r){const i=r.getAttribute("data-theme");if(i==="dark")return"dark";if(i==="light")return"light"}return typeof window<"u"&&((s=window.matchMedia)!=null&&s.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},zd=(t,e)=>{const[r,n]=m.useState("light"),s=m.useRef("light");return m.useEffect(()=>{var d,u,f;if(e||typeof window>"u"||typeof document>"u")return;const i=()=>{const p=Od(t.current);p!==s.current&&(s.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??r},Bd={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"},Hd=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?Bd[n]??n:""},Vd=t=>pt.Children.toArray(t).map(e=>typeof e=="string"||typeof e=="number"?String(e):"").join("").replace(/\n$/,""),Pa=({code:t})=>{const{t:e}=Le(),[r,n]=m.useState(!1),s=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:s,title:e(r?"markdown.codeBlock.copied":"markdown.codeBlock.copyTitle"),"aria-label":e(r?"markdown.codeBlock.copied":"markdown.codeBlock.copyAriaLabel"),children:[r?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(r?"markdown.codeBlock.copied":"markdown.codeBlock.copyLabel")})]})},qd=({inline:t,className:e="",children:r,enableGraphs:n=!0,enableMermaid:s=!0,enableSVG:i=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d})=>{const{t:u}=Le(),f=m.useRef(null),p=zd(f,d),g=a.jsx("div",{className:"markdown-code-block code-block-container",children:u("markdown.codeBlock.loadingRenderer")});if(t)return a.jsx("code",{className:e,children:r});const h=Hd(e),x=Vd(r);if(o&&(h==="chart"||h==="chart-json"||h==="chart-table"))return a.jsx("div",{ref:f,children:a.jsx(m.Suspense,{fallback:g,children:a.jsx(Dd,{code:x,language:h})})});if(l&&(h==="abc"||h==="music"))return a.jsx("div",{ref:f,children:a.jsx(m.Suspense,{fallback:g,children:a.jsx(Ud,{code:x})})});if(n){if(h==="mermaid"&&s)return a.jsx("div",{ref:f,children:a.jsx(m.Suspense,{fallback:g,children:a.jsx(Pd,{code:x})})});if(h==="svg"&&i)return a.jsx("div",{ref:f,children:a.jsx(m.Suspense,{fallback:g,children:a.jsx(Rd,{code:x})})})}if(c&&h){const y=p==="light"?rl:sl;return a.jsxs("div",{ref:f,className:"syntax-highlighted-wrapper code-block-container",children:[a.jsx(Pa,{code:x}),a.jsx(tl,{language:h,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(Pa,{code:x}),a.jsx("pre",{style:{margin:0,padding:0,background:"transparent",border:"none"},children:a.jsx("code",{children:x})})]})},Ra=new Set(["div","pre","blockquote","ul","ol","table","thead","tbody","tr","td","th","h1","h2","h3","h4","h5","h6","section","article","figure"]),Da=({children:t,href:e="",className:r="",standalone:n=!1,...s})=>{const i=pt.Children.toArray(t).map(f=>typeof f=="string"?f:"").join("").trim(),o=/^https?:\/\//i.test(e),l=!!(o&&i&&Ua(i)===Ua(e)),c=o?Wd(e):null,d=!!(n&&l&&c),u=["markdown-link",d?"markdown-link--card":"markdown-link--inline",r].filter(Boolean).join(" ");return a.jsxs("a",{...s,href:e,target:"_blank",rel:"noopener noreferrer",className:u,children:[a.jsx("span",{className:"markdown-link__content",children:d&&c?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"markdown-link__hostname",children:c.hostname}),c.path&&c.path!=="/"&&a.jsx("span",{className:"markdown-link__path",children:c.path})]}):t}),o&&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 Ua(t){return t.trim().replace(/\/$/,"")}function Wd(t){try{const e=new URL(t),r=e.hostname.replace(/^www\./i,""),n=`${e.pathname}${e.search}${e.hash}`||"/";return{hostname:r,path:n}}catch{return null}}const Dt=({content:t,className:e="",disableMath:r=!1,enableGraphs:n=!0,enableMermaid:s=!0,enableSVG:i=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d="dark"})=>{const u=$d(t);if(!u)return null;const f=r?[ua]:[ua,[Jo,{singleDollarTextMath:!0}]],p=[];r||p.push([el,{throwOnError:!1,errorColor:"#cc0000",strict:!1,trust:!0,macros:{"\\RR":"\\mathbb{R}","\\NN":"\\mathbb{N}","\\ZZ":"\\mathbb{Z}","\\QQ":"\\mathbb{Q}","\\CC":"\\mathbb{C}","\\dx":"\\,dx","\\dy":"\\,dy","\\dt":"\\,dt","\\dz":"\\,dz"}}]);const g={table:({children:h,...x})=>a.jsx("div",{style:{overflowX:"auto",WebkitOverflowScrolling:"touch"},children:a.jsx("table",{...x,children:h})}),a:Da,code:h=>{const{className:x,children:y,...k}=h,C=x&&/language-/.test(x),L="inline"in h&&typeof h.inline=="boolean"&&h.inline||!C,N=C;return a.jsx(qd,{inline:L,className:x,enableGraphs:n,enableMermaid:s,enableSVG:i,enableCharts:o,enableMusic:l,enableSyntaxHighlighting:c,syntaxTheme:d,"data-block-code":N?"true":void 0,...k,children:y})},p:({node:h,...x})=>{var N;const y=pt.Children.toArray(x.children).filter(v=>!(typeof v=="string"&&v.trim()==="")),k=y.some(v=>{if(!pt.isValidElement(v))return!1;const T=v.props;return(T==null?void 0:T["data-block-code"])==="true"?!0:typeof v.type=="string"?Ra.has(v.type):!1}),C=(N=h==null?void 0:h.children)==null?void 0:N.some(v=>{var T;if(v.type==="code")return!0;if(v.type==="element"){if(v.tagName&&Ra.has(v.tagName))return!0;if(v.tagName==="code"){const _=(T=v.properties)==null?void 0:T.className;return Array.isArray(_)?_.some(b=>typeof b=="string"&&b.startsWith("language-")):!0}}return!1});if(k||C)return a.jsx(a.Fragment,{children:x.children});if(y.length===1&&pt.isValidElement(y[0])&&y[0].type===Da){const v=y[0];return a.jsx("p",{...x,children:pt.cloneElement(v,{standalone:!0})})}return a.jsx("p",{...x})}};return a.jsx("div",{className:`markdown-content ${e}`,children:a.jsx(Zo,{remarkPlugins:f,rehypePlugins:p,components:g,children:u})})},Hn=()=>Z.debug.consoleDebug,D=(...t)=>{Hn()&&console.log(...t)},be=(...t)=>{Hn()&&console.warn(...t)},pe=(...t)=>{Hn()&&console.error(...t)},Be=(...t)=>{console.error(...t)};function Oa(t){return t==="mp3"?"audio/mpeg":t==="wav"?"audio/wav":t==="ogg"?"audio/ogg":t==="opus"?"audio/opus":t==="webm"?"audio/webm":`audio/${t}`}function ms({audio:t,audioUrl:e,audioFormat:r="mp3",autoPlay:n=!1,maxSizeMB:s=10,downloadFilename:i}){const{t:o}=Le(),{isDark:l}=lr(),c=m.useRef(null),[d,u]=m.useState(!1),[f,p]=m.useState(0),[g,h]=m.useState(0),[x,y]=m.useState(!0),[k,C]=m.useState(null),[L,N]=m.useState(null),[v,T]=m.useState(null);m.useEffect(()=>{if(!t)return;let E=null,z=!0;return(async()=>{try{y(!0),C(null),N(null);const K=t.length*3/4/(1024*1024);if(K>s)throw new Error(o("audio.player.audioFileTooLargePlaceholder",{sizeMB:K.toFixed(1),maxMB:s}));if(K>2&&(N(o("audio.player.largeAudioWarning",{sizeMB:K.toFixed(1)})),D("[AudioPlayer] Large audio file detected",{sizeMB:K.toFixed(2)})),!/^[A-Za-z0-9+/=]+$/.test(t.replace(/\s/g,"")))throw new Error(o("audio.player.invalidBase64Error"));const q=atob(t),G=new Uint8Array(q.length);for(let M=0;M<q.length;M++)G[M]=q.charCodeAt(M);const te=Oa(r),Ce=new Blob([G],{type:te});if(E=URL.createObjectURL(Ce),!z){E&&URL.revokeObjectURL(E);return}T(E),y(!1),D("[AudioPlayer] Audio loaded successfully",{format:r,mimeType:te,size:Ce.size})}catch(W){pe("[AudioPlayer] Failed to load audio:",W),z&&(C(o("audio.player.loadFailureError")),y(!1))}})(),()=>{z=!1,E&&URL.revokeObjectURL(E)}},[t,r,s,o]),m.useEffect(()=>{if(t||!e)return;let E=null,z=!1;return(async()=>{try{y(!0),C(null);const W=typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null,K=await fetch(e,{headers:W?{"X-Adapter-Name":W}:{}});if(!K.ok)throw new Error(`Server returned ${K.status}`);if(z)return;const q=await K.arrayBuffer();if(z)return;const G=new Blob([q],{type:Oa(r)});E=URL.createObjectURL(G),T(E),y(!1)}catch(W){pe("[AudioPlayer] Failed to fetch audio from",e,W),z||(C(o("audio.player.loadFailureError")),y(!1))}})(),()=>{z=!0,E&&URL.revokeObjectURL(E)}},[t,e,r,o]),m.useEffect(()=>{n&&v&&c.current&&c.current.play().catch(E=>{pe("[AudioPlayer] Auto-play failed:",E)})},[n,v]);const _=()=>{c.current&&p(c.current.duration)},b=()=>{c.current&&h(c.current.currentTime)},$=()=>u(!0),j=()=>u(!1),I=()=>{u(!1),h(0)},O=()=>{c.current&&(d?c.current.pause():c.current.play().catch(E=>{pe("[AudioPlayer] Playback failed:",E),C(o("audio.player.playbackFailureError"))}))},R=E=>{if(!c.current)return;const z=parseFloat(E.target.value);c.current.currentTime=z,h(z)},H=()=>{if(!v)return;const E=document.createElement("a");E.href=v,E.download=i||`generated-audio.${r}`,E.click()},A=E=>{if(!isFinite(E))return"0:00";const z=Math.floor(E/60),S=Math.floor(E%60);return`${z}:${S.toString().padStart(2,"0")}`};return k?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(Bn,{className:"h-4 w-4"}),a.jsx("span",{children:k})]}):a.jsxs("div",{className:"mt-3 flex flex-col gap-1",children:[L&&a.jsxs("div",{className:"text-xs text-amber-600 dark:text-amber-400 px-1",children:["⚠️ ",L]}),a.jsxs("div",{className:"flex items-center gap-3 rounded-md border border-gray-200 bg-white/80 px-3 py-2 dark:border-[#3b3c49] dark:bg-white/5",children:[a.jsx("audio",{ref:c,src:v??void 0,onLoadedMetadata:_,onTimeUpdate:b,onPlay:$,onPause:j,onEnded:I}),a.jsx("button",{onClick:O,disabled:x,className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 disabled:opacity-50 dark:bg-[#4a4b54] dark:hover:bg-[#565869]",title:o(d?"audio.player.pauseTitle":"audio.player.playTitle"),"aria-label":o(d?"audio.player.pauseAriaLabel":"audio.player.playAriaLabel"),children:x?a.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-gray-400 border-t-transparent"}):d?a.jsx(md,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"}):a.jsx(hd,{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:A(g)}),a.jsx("input",{type:"range",min:"0",max:f||0,value:g,onChange:R,disabled:x||!f,className:"flex-1 cursor-pointer accent-gray-600 dark:accent-[#bfc2cd]",style:{background:(()=>{const E=l?"rgb(191 194 205)":"rgb(75 85 99)",z=l?"rgba(255 255 255 / 0.12)":"rgb(229 231 235)",S=f?g/f*100:0;return`linear-gradient(to right, ${E} 0%, ${E} ${S}%, ${z} ${S}%, ${z} 100%)`})()}}),a.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:A(f)})]}),i&&a.jsx("button",{onClick:H,disabled:x||!v,className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 disabled:opacity-50 dark:bg-[#4a4b54] dark:hover:bg-[#565869]",title:o("audio.player.downloadAudioTooltip"),children:a.jsx(Bs,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"})})]})]})}function za({image:t,imageUrl:e,imageFormat:r="png",revisedPrompt:n}){const{t:s}=Le(),[i,o]=m.useState(!1),[l,c]=m.useState(!1),[d,u]=m.useState(null),f=m.useRef(null);m.useEffect(()=>{if(t||!e)return;let x=!1;return(async()=>{try{const y=typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null,k=await fetch(e,{headers:y?{"X-Adapter-Name":y}:{}});if(!k.ok){console.warn("[ImageDisplay] Server returned",k.status,"for",e);return}if(x)return;const C=await k.arrayBuffer();if(x)return;const L=new Blob([C],{type:`image/${r}`}),N=URL.createObjectURL(L);f.current=N,u(N)}catch(y){console.warn("[ImageDisplay] Failed to fetch image from",e,y)}})(),()=>{x=!0,f.current&&(URL.revokeObjectURL(f.current),f.current=null)}},[e,t,r]);const g=(t?`data:image/${r};base64,${t}`:null)??d;m.useEffect(()=>{if(!i)return;const x=y=>{y.key==="Escape"&&o(!1)};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[i]);const h=x=>{if(x.stopPropagation(),!g)return;const y=document.createElement("a");y.href=g,y.download=`generated-image.${r}`,y.click()};return g?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||s("imageDisplay.generatedImageTitle"),children:[a.jsx("img",{src:g,alt:n||s("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:h,title:s("imageDisplay.downloadImageTooltip"),style:{background:"rgba(0,0,0,0.55)",border:"none",borderRadius:"6px",padding:"5px",cursor:"pointer",color:"#fff",display:"flex",alignItems:"center"},children:a.jsx(Bs,{size:14})}),a.jsx("button",{onClick:x=>{x.stopPropagation(),o(!0)},title:s("imageDisplay.viewFullSizeTooltip"),style:{background:"rgba(0,0,0,0.55)",border:"none",borderRadius:"6px",padding:"5px",cursor:"pointer",color:"#fff",display:"flex",alignItems:"center"},children:a.jsx(jd,{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(Is,{size:14}):a.jsx(wr,{size:14}),s(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:s("imageDisplay.promptLabel")}),a.jsx("span",{style:{fontSize:"0.8rem",lineHeight:1.45,opacity:.85},children:n})]})]})]}),i&&typeof document<"u"&&Rs.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(Ge,{size:20})}),a.jsx("img",{src:g,alt:n||s("imageDisplay.generatedImageAlt"),style:{display:"block",width:"auto",height:"auto",maxWidth:"calc(100vw - 48px)",maxHeight:"calc(100vh - 80px)",objectFit:"contain",borderRadius:"8px",margin:"0 auto"},onClick:x=>x.stopPropagation()})]}),document.body)]}):null}const ln=[750,1500,3e3,5e3],Kd=new Set([403,404,409,425,429,500,502,503,504]),Gd=t=>new Promise(e=>setTimeout(e,t));function Ba({video:t,videoUrl:e,videoFormat:r="mp4",revisedPrompt:n,adapterName:s}){const{t:i}=Le(),[o,l]=m.useState(!1),[c,d]=m.useState(!1),[u,f]=m.useState(null),p=m.useRef(null);m.useEffect(()=>{if(t||!e)return;let y=!1;return(async()=>{try{const k=s||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null);let C=null;for(let T=0;T<=ln.length&&(C=await fetch(e,{headers:k?{"X-Adapter-Name":k}:{}}),!(C.ok||!Kd.has(C.status)||T===ln.length));T+=1)if(await Gd(ln[T]),y)return;if(!C||!C.ok){console.warn("[VideoDisplay] Server returned",C==null?void 0:C.status,"for",e);return}if(y)return;const L=await C.arrayBuffer();if(y)return;const N=new Blob([L],{type:`video/${r}`}),v=URL.createObjectURL(N);p.current=v,f(v)}catch(k){console.warn("[VideoDisplay] Failed to fetch video from",e,k)}})(),()=>{y=!0,p.current&&(URL.revokeObjectURL(p.current),p.current=null)}},[e,t,r,s]);const h=(t?`data:video/${r};base64,${t}`:null)??u;m.useEffect(()=>{if(!o)return;const y=k=>{k.key==="Escape"&&l(!1)};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[o]);const x=y=>{if(y.stopPropagation(),!h)return;const k=document.createElement("a");k.href=h,k.download=`generated-video.${r}`,k.click()};return h?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:h,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(Bs,{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(sd,{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(Is,{size:14}):a.jsx(wr,{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(Ge,{size:20})}),a.jsx("video",{src:h,controls:!0,autoPlay:!0,style:{maxWidth:"92vw",maxHeight:"92vh",borderRadius:"8px"},onClick:y=>y.stopPropagation()})]})]}):null}let Es=null;function Ki(t){Es=t}function Hs(){Es=null}async function Vn(){if(!Es)return null;try{return await Es()}catch{return null}}let An=!1,Br=null;const Nn=new Set;function Gi(){Nn.forEach(t=>t())}function kt(){return An}function Xd(){return Br}function Vs(t){An!==t&&(An=t,!t&&Br!==null&&(Br=null),Gi())}function yr(t){const e=typeof t=="string"&&t.trim().length>0?t.trim():null;Br!==e&&(Br=e,Gi())}function Yd(t){return Nn.add(t),()=>{Nn.delete(t)}}const Ha="orbitchat-guest-user-id";function hs(t){if(typeof t!="string")return null;const e=t.trim();return e.length>0?e:null}function Qd(t){const e=t.split(".");if(e.length<2)return null;try{const r=e[1].replace(/-/g,"+").replace(/_/g,"/"),n=r.padEnd(Math.ceil(r.length/4)*4,"="),s=atob(n);return JSON.parse(s)}catch{return null}}function Zd(){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 Jd(){if(typeof window>"u")return"guest:orbitchat:server";const t=window.localStorage.getItem(Ha);if(t&&t.trim().length>0)return t;const e=Zd();return window.localStorage.setItem(Ha,e),e}async function Xi(){const t=Xd();if(t)return t;const e=await Vn();if(e){const r=Qd(e),n=hs(r==null?void 0:r.sub)||hs(r==null?void 0:r.user_id)||hs(r==null?void 0:r.preferred_username)||hs(r==null?void 0:r.email);if(n)return n}return kt()?"authenticated:orbitchat:unknown":Jd()}const eu={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"},Va={pdf:"PDF",docx:"Word document",xlsx:"Excel workbook",pptx:"PowerPoint deck",md:"Markdown document",csv:"CSV file"},Ss=/[\uE000-\uF8FF]|\\[eE][0-9a-fA-F]{2,3}|\\[fF][0-8][0-9a-fA-F]{2,3}/,tu=/((?:p\.)?generated-docx-preview-num-\d+-\d+:before\s*\{[^}]*?)content\s*:\s*"([^"]*)"\s*;([^}]*?\})/g;function ru(t){var r;return Ss.test(t)?`•${((r=t.match(/(?:\\9|\t|\u00A0| )+$/))==null?void 0:r[0])||"\\9"}`:null}function qa(t){Array.from(t.querySelectorAll("style")).forEach(n=>{const s=n.textContent;!s||!Ss.test(s)||(n.textContent=s.replace(tu,(i,o,l,c)=>{const d=ru(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 s=n.textContent||"";Ss.test(s)&&(n.textContent=s.replace(Ss,"•"),n.style.fontFamily="")})}function su(t){return(t||"pdf").toLowerCase().replace(/^\./,"")||"pdf"}function nu(t){const e=window.atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.charCodeAt(n);return r.buffer}function au(t){return t==="xlsx"||t==="csv"?a.jsx(Ui,{className:"h-5 w-5"}):t==="pptx"?a.jsx(Hi,{className:"h-5 w-5"}):t==="md"?a.jsx(Di,{className:"h-5 w-5"}):a.jsx(Cn,{className:"h-5 w-5"})}function Wa({document:t,documentUrl:e,documentFormat:r="pdf",revisedPrompt:n,adapterName:s}){const{t:i}=Le(),o=su(r),[l,c]=m.useState(t||e?"loading":"idle"),[d,u]=m.useState(null),[f,p]=m.useState(null),[g,h]=m.useState([]),[x,y]=m.useState(""),[k,C]=m.useState(null),[L,N]=m.useState([]),[v,T]=m.useState(0),[_,b]=m.useState(!1),[$,j]=m.useState(null),I=m.useRef(null),O=m.useRef(null),R=m.useRef(null),H=n||Va[o]||i("documentDisplay.generatedDocument"),A=m.useMemo(()=>`generated-document.${o}`,[o]),E=eu[o]||"application/octet-stream";m.useEffect(()=>{if(!t&&!e)return;let K=!1;return(async()=>{c("loading"),j(null),h([]),y(""),C(null),N([]),T(0);try{const G=t?nu(t):await(async()=>{const M=(s==null?void 0:s.trim())||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),ee={"X-User-ID":await Xi()};M&&(ee["X-Adapter-Name"]=M);const Q=await Vn();Q&&(ee.Authorization=`Bearer ${Q}`);const J=await fetch(e,{headers:ee});if(!J.ok)throw new Error(`Server returned ${J.status}`);return J.arrayBuffer()})();if(K)return;const te=new Blob([G],{type:E}),Ce=URL.createObjectURL(te);if(I.current&&URL.revokeObjectURL(I.current),I.current=Ce,u(Ce),p(G.slice(0)),o==="xlsx"){const{default:M}=await Nt(async()=>{const{default:J}=await import("./index-CZz_ECqk.js");return{default:J}},[]),Q=(await M(te))[0];y((Q==null?void 0:Q.sheet)||"First sheet"),h(((Q==null?void 0:Q.data)||[]).slice(0,100).map(J=>J.slice(0,30).map(le=>le==null?"":String(le))))}if(o==="md"&&C(new TextDecoder("utf-8").decode(G)),o==="csv"){const M=new TextDecoder("utf-8").decode(G),{default:ee}=await Nt(async()=>{const{default:J}=await import("./papaparse.min-D13ujVVP.js").then(le=>le.p);return{default:J}},__vite__mapDeps([19,1])),Q=ee.parse(M,{skipEmptyLines:!0});T(Q.data.length),N(Q.data.slice(0,25))}c("ready")}catch(G){if(K)return;console.warn("[DocumentDisplay] Failed to load document from",e,G),j(G instanceof Error?G.message:"Unable to load document"),c("error")}})(),()=>{K=!0,I.current&&(URL.revokeObjectURL(I.current),I.current=null)}},[s,t,e,o,E]),m.useEffect(()=>{if(l!=="ready"||o!=="docx"||!f||!O.current)return;const K=O.current;K.replaceChildren(),Nt(()=>import("./docx-preview-DehBmhog.js"),__vite__mapDeps([20,1])).then(async({renderAsync:q})=>{await q(f.slice(0),K,void 0,{className:"generated-docx-preview",inWrapper:!1,ignoreWidth:!0,ignoreHeight:!0}),qa(K)}).catch(q=>{console.warn("[DocumentDisplay] Failed to render DOCX preview",q),j("Unable to render document preview")})},[f,o,l]),m.useEffect(()=>{if(!_||o!=="docx"||!f||!R.current)return;const K=R.current;K.replaceChildren(),Nt(()=>import("./docx-preview-DehBmhog.js"),__vite__mapDeps([20,1])).then(async({renderAsync:q})=>{await q(f.slice(0),K,void 0,{className:"generated-docx-preview",inWrapper:!1,ignoreWidth:!0,ignoreHeight:!0}),qa(K)}).catch(q=>{console.warn("[DocumentDisplay] Failed to render modal DOCX preview",q)})},[f,o,_]),m.useEffect(()=>{if(!_)return;const K=q=>{q.key==="Escape"&&b(!1)};return window.document.addEventListener("keydown",K),()=>window.document.removeEventListener("keydown",K)},[_]);const z=K=>{if(K==null||K.stopPropagation(),!d)return;const q=window.document.createElement("a");q.href=d,q.download=A,q.click()},S=l==="ready"&&(o==="pdf"||o==="docx"||o==="xlsx"||o==="md"||o==="csv"),W=S&&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:au(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:H}),a.jsxs("p",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:[Va[o]||`${o.toUpperCase()} document`,l==="loading"?` · ${i("documentDisplay.loadingPreview")}`:"",l==="error"?` · ${$||i("documentDisplay.previewUnavailableShort")}`:""]})]}),W&&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(Gc,{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(Bs,{className:"h-4 w-4"})})]}),S&&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:H,className:"block h-[460px] w-full border-0 bg-white"}),o==="docx"&&a.jsx("div",{ref:O,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:g.length>0?g.map((K,q)=>a.jsx("tr",{className:q===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:K.map((G,te)=>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:G},te))},q)):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"&&k!==null&&a.jsx("div",{className:"bg-white p-5 text-sm text-[#111827] dark:bg-[#171717] dark:text-[#ececf1]",children:a.jsx(Dt,{content:k,disableMath:!0})}),o==="csv"&&a.jsxs("div",{className:"p-3",children:[v>25&&a.jsx("p",{className:"mb-2 text-xs text-gray-500 dark:text-[#bfc2cd]",children:i("documentDisplay.csvRowsPreviewMessage",{count:v})}),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:L.length>0?L.map((K,q)=>a.jsx("tr",{className:q===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:K.map((G,te)=>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:G},te))},q)):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"&&!S&&a.jsx("div",{className:"px-3 py-4 text-sm text-gray-600 dark:text-[#bfc2cd]",children:i("documentDisplay.previewUnavailable")})]}),_&&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:K=>{K.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(Ge,{className:"h-5 w-5"})}),a.jsxs("div",{onClick:K=>K.stopPropagation(),className:"h-[92vh] w-[92vw] overflow-auto rounded-lg bg-white",children:[o==="pdf"&&a.jsx("iframe",{src:d,title:H,className:"h-full w-full border-0"}),o==="docx"&&a.jsx("div",{ref:R,className:"min-h-full bg-white p-8 text-[#111827]"}),o==="md"&&k!==null&&a.jsx("div",{className:"min-h-full bg-white p-8 text-sm text-[#111827]",children:a.jsx(Dt,{content:k,disableMath:!0})})]})]})]})}const iu=["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 Hr(t,{enabled:e,onEscape:r}){m.useEffect(()=>{if(!e||!t.current)return;const n=t.current,s=document.activeElement,i=Array.from(n.querySelectorAll(iu)).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"){r==null||r();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=s==null?void 0:s.focus)==null||d.call(s,{preventScroll:!0})}},[e,r,t])}function _s({isOpen:t,onClose:e,onConfirm:r,title:n,message:s,confirmText:i,cancelText:o,type:l="danger",isLoading:c=!1}){const d=m.useRef(null);Hr(d,{enabled:t,onEscape:e});const{t:u}=Le(),f=i??u("common.confirm"),p=o??u("common.cancel");if(!t)return null;const g=()=>{c||r()},x=(()=>{switch(l){case"danger":return{icon:"text-red-500",iconBg:"bg-red-100 dark:bg-red-900/20",confirmButton:"bg-red-600 hover:bg-red-700 focus:ring-red-500",border:"border-red-200 dark:border-red-800"};case"warning":return{icon:"text-amber-500",iconBg:"bg-amber-100 dark:bg-amber-900/20",confirmButton:"bg-amber-600 hover:bg-amber-700 focus:ring-amber-500",border:"border-amber-200 dark:border-amber-800"};default:return{icon:"text-blue-500",iconBg:"bg-blue-100 dark:bg-blue-900/20",confirmButton:"bg-blue-600 hover:bg-blue-700 focus:ring-blue-500",border:"border-blue-200 dark:border-blue-800"}}})(),y=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(zn,{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(Ge,{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:s})}),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:g,disabled:c,className:`px-4 py-3 md:py-2.5 text-white rounded-lg transition-all font-medium shadow-sm hover:shadow-md transform hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-white dark:focus:ring-offset-gray-800 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none ${x.confirmButton}`,children:c?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:Rs.createPortal(y,document.body)}const ou=["#","*","`","[","]","(",")","{","}","|","<",">"],Yi=t=>ou.some(e=>t.includes(e));function Qi(t){if(!t||t.length<1e3)return!1;const e=/^[A-Za-z0-9+/=]+$/,r=t.replace(/\s+/g,"");if(r.length>1e4&&e.test(r)){const n=/\b(the|and|for|are|but|not|you|all|can|function|const|let|var|class|return|import|export|async|await|if|else|while|true|false|null|undefined|http|https|www|error|data|response|request|api|json|xml|html|css|js|py|java|cpp|def|print|console|log)\b/i.test(t),s=Yi(t),i=/[-.,;:!?'"()]/.test(t);if(!n&&!s&&!i)return!0}return!!(r.length>5e4&&e.test(r)&&t.replace(/[A-Za-z0-9+/=\s]/g,"").length<10)}const lu=/(?:\u202F|\u2009|\u200A|\u200B|\u200C|\u200D|\uFEFF)/g;function Vr(t){if(!t)return t;let e=t.replace(lu," ");if(Qi(e))return"";const r=/([A-Za-z0-9+/=]{10000,})/g;return e=e.replace(r,n=>{const s=n.replace(/\s+/g,"");if(s.length>1e4&&/^[A-Za-z0-9+/=]+$/.test(s)){const i=/\b(function|const|let|var|class|return|import|export|if|else|while|for|true|false|null|def|print)\b/i.test(n),o=Yi(n),l=/[-.,;:!?'"()]/.test(n);if(!i&&!o&&!l)return""}return n}),e}function In(t,e=5e4){return!t||t.length<=e?t:Qi(t)?"":t.substring(0,e)+`
340
-
341
- ... (content truncated due to length)`}const cu={maxFilesPerConversation:Z.limits.files.perConversation,maxFileSizeMB:Z.limits.files.maxSizeMB,maxTotalFiles:Z.limits.files.totalFiles,maxConversations:Z.limits.conversations.maxConversations,maxMessagesPerConversation:Z.limits.conversations.messagesPerConversation,maxMessagesPerThread:Z.limits.conversations.messagesPerThread,maxTotalMessages:Z.limits.conversations.totalMessages,maxMessageLength:Z.limits.messages.maxLength};function du(t){const e=Z.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(cu,{get(t,e){if(tt()&&!kt()){const r=du(e);if(r!==void 0)return r}return t[e]}});function kr(){return m.useSyncExternalStore(Yd,kt,kt)}class Zi extends Error{constructor(r,n){super(r);Ze(this,"status");Ze(this,"statusText");this.name="ApiRequestError",this.status=n.status,this.statusText=n.statusText}}async function Ue(t={}){const e={"X-User-ID":await Xi(),...t},r=await Vn();return r&&(e.Authorization=`Bearer ${r}`),e}function Ct(t){return encodeURIComponent(t)}function uu(t){return!t||t.length===0?"":`?file_ids=${t.map(encodeURIComponent).join(",")}`}async function Fr(t){const e=`API request failed: ${t.status} ${t.statusText}`;try{if((t.headers.get("content-type")||"").includes("application/json")){const n=await t.json(),s=typeof n.detail=="string"&&n.detail.trim()||typeof n.error=="string"&&n.error.trim()||typeof n.message=="string"&&n.message.trim();if(s)return`${e}: ${s}`}else{const n=(await t.text()).trim();if(n)return`${e}: ${n}`}}catch{}return e}function Ka(t){if(!t.startsWith("data: "))return null;try{const e=JSON.parse(t.substring(6));return e.request_id&&!e.response&&!e.done?{text:"",done:!1,request_id:e.request_id}:{text:e.text||e.content||e.message||e.response||"",done:e.done||!1,request_id:e.request_id,audio:e.audio,audioFormat:e.audio_format||e.audioFormat,audio_chunk:e.audio_chunk,chunk_index:e.chunk_index,image:e.image,image_format:e.image_format,image_revised_prompt:e.image_revised_prompt,image_url:e.image_url,video:e.video,video_format:e.video_format,video_revised_prompt:e.video_revised_prompt,video_url:e.video_url,document:e.document,document_format:e.document_format,document_revised_prompt:e.document_revised_prompt,document_url:e.document_url,generated_audio_url:e.generated_audio_url,generated_audio_format:e.generated_audio_format,generated_audio_revised_prompt:e.generated_audio_revised_prompt,model:e.model,assistant_message_id:e.assistant_message_id,threading:e.threading}}catch{return null}}let ps=null;function fu(){let t=null,e=null;const r=(s,i,o)=>{t=i||null,e=o||null},n=(s,i)=>({async*streamChat(o,l,c,d,u,f,p,g,h,x,y,k,C,L){var T,_;const N={messages:[{role:"user",content:o}],stream:l!==!1};c&&c.length>0&&(N.file_ids=c),d&&(N.thread_id=d),u&&(N.audio_input=u),f&&(N.audio_format=f),p&&(N.language=p),g!==void 0&&(N.return_audio=g),h&&(N.tts_voice=h),x&&(N.source_language=x),y&&(N.target_language=y),k&&(N.model=k),C&&(N.skill=C),L&&(N.regenerate_of_message_id=L);const v=await fetch("/api/v1/chat",{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":s,...i?{"X-Session-ID":i}:{}}),body:JSON.stringify(N)});if(!v.ok)throw new Error(await Fr(v));if((T=v.headers.get("content-type"))!=null&&T.includes("text/event-stream")){const b=(_=v.body)==null?void 0:_.getReader(),$=new TextDecoder;let j="";if(!b)throw new Error("Response body is not readable");for(;;){const{done:I,value:O}=await b.read();if(I)break;j+=$.decode(O,{stream:!0});const R=j.split(`
342
- `);j=R.pop()||"";for(const H of R){const A=Ka(H);A&&(yield A)}}if(j.trim())for(const I of j.split(`
343
- `)){const O=Ka(I);O&&(yield O)}}else{const b=await v.json();yield{text:b.message||b.response||"",done:!0,audio:b.audio,audioFormat:b.audio_format||b.audioFormat,image:b.image,image_format:b.image_format,image_revised_prompt:b.image_revised_prompt,image_url:b.image_url,video:b.video,video_format:b.video_format,video_revised_prompt:b.video_revised_prompt,video_url:b.video_url,document:b.document,document_format:b.document_format,document_revised_prompt:b.document_revised_prompt,document_url:b.document_url,generated_audio_url:b.generated_audio_url,generated_audio_format:b.generated_audio_format,generated_audio_revised_prompt:b.generated_audio_revised_prompt,model:b.model,assistant_message_id:b.assistant_message_id,threading:b.threading}}},async createThread(o,l){const c=await fetch("/api/threads",{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":s,"X-Session-ID":l}),body:JSON.stringify({message_id:o,session_id:l})});if(!c.ok)throw new Error(`Failed to create thread: ${c.statusText}`);return c.json()},async getThreadInfo(o){const l=await fetch(`/api/threads/${Ct(o)}`,{headers:await Ue({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to get thread info: ${l.statusText}`);return l.json()},async deleteThread(o){const l=await fetch(`/api/threads/${Ct(o)}`,{method:"DELETE",headers:await Ue({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to delete thread: ${l.statusText}`);return l.json()},async submitFeedback(o,l,c,d){const u={message_id:o,session_id:l,feedback_type:c};d!==void 0&&(u.comment=d);const f=await fetch("/api/feedback",{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":s,"X-Session-ID":l}),body:JSON.stringify(u)});if(!f.ok)throw new Error(`Failed to submit feedback: ${f.statusText}`);return f.json()},async getSessionFeedback(o){const l=await fetch(`/api/feedback/${Ct(o)}`,{headers:await Ue({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to get feedback: ${l.statusText}`);return l.json()},async clearConversationHistory(o){const l=o||i;if(!l)throw new Error("No session ID available for clearing conversation history");const c=await fetch(`/api/admin/chat-history/${Ct(l)}`,{method:"DELETE",headers:await Ue({"X-Adapter-Name":s})});if(!c.ok)throw new Error(`Failed to clear history: ${c.statusText}`);return c.json()},async getConversationHistory(o,l){const c=o||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/${Ct(c)}${d}`,{headers:await Ue({"X-Adapter-Name":s})});if(!u.ok)throw new Error(`Failed to load history: ${u.statusText}`);return u.json()},async deleteConversationWithFiles(o,l){const c=o||i;if(!c)throw new Error("No session ID available for deleting conversation");const d=uu(l),u=await fetch(`/api/admin/conversations/${Ct(c)}${d}`,{method:"DELETE",headers:await Ue({"X-Adapter-Name":s})});if(!u.ok)throw new Error(`Failed to delete conversation: ${u.statusText}`);return u.json()},getSessionId:()=>i,async uploadFile(o){const l=new FormData;l.append("file",o);const c=await fetch("/api/files/upload",{method:"POST",headers:await Ue({"X-Adapter-Name":s}),body:l});if(!c.ok)throw new Error(`Failed to upload file: ${c.statusText}`);return c.json()},async listFiles(){const o=await fetch("/api/files",{headers:await Ue({"X-Adapter-Name":s})});if(!o.ok)throw new Error(`Failed to list files: ${o.statusText}`);const l=await o.json();return Array.isArray(l)?l:l.files||[]},async getFileInfo(o){const l=await fetch(`/api/files/${Ct(o)}`,{headers:await Ue({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to get file info: ${l.statusText}`);return l.json()},async queryFile(o,l,c){const d=await fetch(`/api/files/${Ct(o)}/query`,{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":s}),body:JSON.stringify({query:l,max_results:c})});if(!d.ok)throw new Error(`Failed to query file: ${d.statusText}`);return d.json()},async deleteFile(o){const l=await fetch(`/api/files/${Ct(o)}`,{method:"DELETE",headers:await Ue({"X-Adapter-Name":s})});if(!l.ok)throw new Error(`Failed to delete file: ${l.statusText}`);return l.json()},async validateApiKey(){const o=await fetch(`/api/admin/api-keys/${Ct(s)}/status`,{headers:await Ue({"X-Adapter-Name":s})});if(!o.ok)throw new Error(`Failed to validate API key: ${o.statusText}`);return o.json()},async getAdapterInfo(){const o="/api/admin/adapters/info",l=f=>{if(!f)return 0;const p=Number(f);if(Number.isFinite(p)&&p>0)return Math.min(p*1e3,3e4);const g=Date.parse(f);if(!Number.isNaN(g)){const h=g-Date.now();if(h>0)return Math.min(h,3e4)}return 0},c=f=>new Promise(p=>setTimeout(p,f)),d=async()=>fetch(o,{headers:await Ue({"X-Adapter-Name":s})});let u=await d();if(u.status===429){const f=l(u.headers.get("Retry-After"));f>0&&(await c(f),u=await d())}if(!u.ok){const f=await u.text(),p=`${u.status} ${u.statusText}`.trim(),g=u.status===401?`Adapter info request was unauthorized for '${s}'. Verify the adapter exists and you have access.`:`Failed to load adapter info (${p}) for '${s}'.`;throw console.warn("[ProxyApi] Adapter info request failed",{adapter:s,status:u.status,statusText:u.statusText,details:f||void 0}),new Zi(g,u)}return u.json()},async stopChat(o,l){const c=await fetch("/api/v1/chat/stop",{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":s}),body:JSON.stringify({session_id:o,request_id:l})});return c.ok?(await c.json()).status==="cancelled":(console.warn(`[ProxyApi] stopChat failed: ${c.status} ${c.statusText}`),!1)},async getAdapterModels(o){const l=await fetch(`/api/admin/adapters/${encodeURIComponent(o)}/models`,{headers:await Ue({"X-Adapter-Name":s})});if(!l.ok)throw new Error(await Fr(l));return l.json()},async getAllModels(){const o=await fetch("/api/admin/models",{headers:await Ue({"X-Adapter-Name":s})});if(!o.ok)throw new Error(await Fr(o));return o.json()},async getAdapterSkills(o){const l=await fetch(`/api/admin/adapters/${encodeURIComponent(o)}/skills`,{headers:await Ue({"X-Adapter-Name":s})});if(!l.ok)throw new Error(await Fr(l));return l.json()},async getAllSkills(){const o=await fetch("/api/admin/skills",{headers:await Ue({"X-Adapter-Name":s})});if(!o.ok)throw new Error(await Fr(o));return o.json()}});return{configureApi:r,streamChat:async function*(s,i,o,l,c,d,u,f,p,g,h,x,y,k){if(!e)throw new Error("Adapter name is required");yield*n(e,t).streamChat(s,i,o,l,c,d,u,f,p,g,h,x,y,k)},stopChat:async(s,i)=>{if(!e)throw new Error("Adapter name is required");return n(e,t).stopChat(s,i)},ApiClient:class{constructor(i){Ze(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 mu(){return ps||(D("Loading API via Express proxy"),ps=fu(),D("API loaded successfully"),ps)}async function Me(){return await mu()}class Ga{static async getAdapterSkills(e,r){const n=await Me(),s=new n.ApiClient({apiUrl:"",adapterName:r});return s.getAdapterSkills?(await s.getAdapterSkills(e)).available_skills:[]}static async getAllSkills(e){const r=await Me(),n=new r.ApiClient({apiUrl:"",adapterName:e});return n.getAllSkills?(await n.getAllSkills()).skills:[]}}const hu=6e4;function Ji(t={}){const{adapterName:e,enabled:r=!0,selectionScopeKey:n,supportsThreading:s=!1}=t,i=r&&!!e&&!s,o=n??e??"__default__",[l,c]=m.useState([]),[d,u]=m.useState(!1),[f,p]=m.useState(null),[g,h]=m.useState({}),x=m.useRef(null),y=m.useRef(new Map),k=m.useCallback(async v=>{var b,$;const T=v,_=y.current.get(T);if(_&&_.expiresAt>Date.now()){c(_.skills),p(v);return}x.current&&x.current.abort(),x.current=new AbortController,u(!0);try{const[j,I]=await Promise.all([Ga.getAdapterSkills(v,v),Ga.getAllSkills(v)]);if((b=x.current)!=null&&b.signal.aborted)return;const O=I.filter(R=>j.includes(R.name)&&R.enabled);y.current.set(T,{skills:O,expiresAt:Date.now()+hu}),c(O),p(v),D("[useSkills] Loaded",O.length,"skills for adapter",v)}catch(j){if(j instanceof Error&&j.name==="AbortError")return;be("[useSkills] Failed to load skills:",j instanceof Error?j.message:String(j)),c([]),p(v)}finally{($=x.current)!=null&&$.signal.aborted||u(!1)}},[]);m.useEffect(()=>{if(!i||!e)return;const v=window.setTimeout(()=>{k(e)},0);return()=>{var T;window.clearTimeout(v),(T=x.current)==null||T.abort()}},[i,e,k]);const C=m.useCallback(v=>{h(T=>{const _=T[o]??null;if(_===v||(_==null?void 0:_.name)===(v==null?void 0:v.name))return T;const b={...T};return v?b[o]=v:delete b[o],b})},[o]),L=m.useCallback(()=>{h(v=>{if(!v[o])return v;const T={...v};return delete T[o],T})},[o]),N=i?g[o]??null:null;return{skills:i&&f===e?l:[],isLoading:i?d||f!==e:!1,selectedSkill:N,selectSkill:C,clearSkill:L}}const Xa=t=>{let e;const r=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),r.forEach(g=>g(e,p))}},s=()=>e,l={setState:n,getState:s,getInitialState:()=>c,subscribe:d=>(r.add(d),()=>r.delete(d))},c=e=t(n,s,l);return l},pu=(t=>t?Xa(t):Xa),gu=t=>t;function xu(t,e=gu){const r=pt.useSyncExternalStore(t.subscribe,pt.useCallback(()=>e(t.getState()),[t,e]),pt.useCallback(()=>e(t.getInitialState()),[t,e]));return pt.useDebugValue(r),r}const Ya=t=>{const e=pu(t),r=n=>xu(e,n);return Object.assign(r,e),r},eo=(t=>t?Ya(t):Ya),rt=eo(t=>({showLoginPrompt:!1,promptMessage:"",openLoginPrompt:e=>t({showLoginPrompt:!0,promptMessage:e}),closeLoginPrompt:()=>t({showLoginPrompt:!1,promptMessage:""})})),gs=t=>{const e=t==null?void 0:t.trim();return e||(typeof window<"u"&&window.localStorage?localStorage.getItem("chat-adapter-name"):null)};class qr{static async uploadFile(e,r,n,s,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"}`);r&&r({filename:e.name,progress:0,status:"uploading"});const d=await Me(),u=(s==null?void 0:s.trim())||Fe(),f=gs(i);if(!f)throw new Error("Adapter not configured. Please select an adapter from the dropdown.");D(`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 g=await p.uploadFile(e);r&&r({filename:e.name,progress:75,status:"processing",fileId:g.file_id});let h;try{h=await this.pollFileStatus(g.file_id,30,2e3,void 0,u,f)}catch(x){const y=x instanceof Error?x.message:String(x);if(y.includes("was deleted"))throw new Error(`File ${g.file_id} was deleted during upload`);be(`File status polling failed for ${g.file_id}:`,x);const k=y.includes("processing failed")||y.includes("timeout");h={file_id:g.file_id,filename:g.filename,mime_type:g.mime_type,file_size:g.file_size,processing_status:k?"failed":g.status||"processing",chunk_count:g.chunk_count,error_message:k?y:void 0}}return r&&r({filename:e.name,progress:100,status:h.processing_status==="completed"?"completed":"processing",fileId:g.file_id}),h}catch(o){let l=o instanceof Error?o.message:"Upload failed";throw l.includes("401")&&(l="Authentication failed. Please check your adapter configuration."),r&&r({filename:e.name,progress:0,status:"error",error:l}),new Error(l)}}static async uploadFiles(e,r){const s=[],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=>{r&&r(f,p)})}));for(let d=0;d<c.length;d++){const u=c[d],f=o+d;u.status==="fulfilled"?s.push(u.value):(Be(`Failed to upload file ${e[f].name}:`,u.reason),i.push({index:f,file:e[f].name,error:u.reason}))}}if(s.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&&be(`[FileUploadService] ${i.length} of ${e.length} files failed to upload:`,i.map(o=>o.file)),s}static async listFiles(e,r,n){try{const s=await Me(),i=(r==null?void 0:r.trim())||Fe(),o=gs(n);if(!o)throw new Error("Adapter not configured");const l=new s.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(s){Be("Failed to list files:",s);const i=s instanceof Error?s.message:"Failed to list files";throw new Error(i)}}static async getFileInfo(e,r,n,s){try{const i=await Me(),o=(n==null?void 0:n.trim())||Fe(),l=gs(s);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`);Be(`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,r=30,n=2e3,s,i,o){for(let l=0;l<r;l++)try{if(s&&!s())throw new Error("Polling cancelled - component unmounted");const c=await this.getFileInfo(e,void 0,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<r-1&&await new Promise(d=>setTimeout(d,n))}catch(c){const d=c instanceof Error?c.message:String(c);if(d.includes("404")||d.includes("File not found")||d.includes("was deleted"))throw new Error(`File ${e} was deleted during upload`);if(d.includes("component unmounted")||d.includes("processing failed")||d.includes("processing_status")||d.includes("401")||d.includes("403")||d.includes("500")||d.includes("502")||d.includes("503")||d.includes("Authentication")||d.includes("Adapter not configured"))throw c;if(l<r-1){await new Promise(u=>setTimeout(u,n));continue}throw c}throw new Error(`File processing timeout: ${e} did not complete within ${r*n/1e3} seconds`)}static async deleteFile(e,r,n,s){try{const i=await Me(),o=(n==null?void 0:n.trim())||Fe(),l=gs(s);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 D(`File ${e} was already deleted from server`),{message:"File already deleted",file_id:e};Be(`Failed to delete file ${e}:`,i);const o=i instanceof Error?i.message:`Failed to delete file: ${e}`;throw new Error(o)}}}class bu{constructor(){Ze(this,"audioQueue",[]);Ze(this,"isPlaying",!1);Ze(this,"currentAudio",null);Ze(this,"audioContext",null);Ze(this,"isEnabled",!1);Ze(this,"onPlaybackStart",null);Ze(this,"onPlaybackEnd",null);Ze(this,"mimeTypeCache",new Map);Ze(this,"onChunkPlayed",null);Ze(this,"blobUrls",[]);Ze(this,"suppressPlaybackErrors",!1)}async enableAudio(){var e,r;try{if(!this.audioContext){const 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 s=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,s=l.play().then(()=>{l.pause()}).catch(()=>{D("[AudioStreamManager] HTMLAudioElement silent unlock failed (will retry on next gesture)")}).finally(()=>{URL.revokeObjectURL(o)})}catch{D("[AudioStreamManager] Could not create silent audio element")}if(await n,this.audioContext&&this.audioContext.state==="running"){const i=this.audioContext.createBuffer(1,1,22050),o=this.audioContext.createBufferSource();o.buffer=i,o.connect(this.audioContext.destination),o.start(0)}return await s,this.isEnabled=!0,D("[AudioStreamManager] Audio playback enabled",{audioContextState:(r=this.audioContext)==null?void 0:r.state}),!0}catch(n){return pe("[AudioStreamManager] Failed to enable audio:",n),!1}}createSilentWavBlob(){const o=new ArrayBuffer(844),l=new DataView(o),c=(d,u)=>{for(let f=0;f<u.length;f++)l.setUint8(d+f,u.charCodeAt(f))};return c(0,"RIFF"),l.setUint32(4,836,!0),c(8,"WAVE"),c(12,"fmt "),l.setUint32(16,16,!0),l.setUint16(20,1,!0),l.setUint16(22,1,!0),l.setUint32(24,8e3,!0),l.setUint32(28,8e3*2,!0),l.setUint16(32,2,!0),l.setUint16(34,16,!0),c(36,"data"),l.setUint32(40,800,!0),new Blob([o],{type:"audio/wav"})}disableAudio(){!this.isEnabled&&!this.isPlaying||(this.isEnabled=!1,this.stop(),D("[AudioStreamManager] Audio playback disabled"))}async ensureAudioContext(){var e;if(!this.audioContext){const r=typeof AudioContext<"u"?AudioContext:typeof window<"u"&&window.webkitAudioContext||null;if(r)try{this.audioContext=new r}catch(n){return pe("[AudioStreamManager] Failed to create AudioContext:",n),!1}}if(((e=this.audioContext)==null?void 0:e.state)==="suspended")try{await this.audioContext.resume()}catch(r){return D("[AudioStreamManager] AudioContext resume deferred",r),!1}return!0}resolveMimeType(e){const r=this.mimeTypeCache.get(e);if(r)return r;let n;switch(e){case"mp3":n="audio/mpeg";break;case"wav":n="audio/wav";break;case"webm":n="audio/webm";break;case"ogg":n="audio/ogg";break;case"opus":{const s=typeof document<"u"?document.createElement("audio"):null;s!=null&&s.canPlayType("audio/ogg; codecs=opus")?n="audio/ogg; codecs=opus":s!=null&&s.canPlayType("audio/webm; codecs=opus")?n="audio/webm; codecs=opus":n="audio/mp4";break}default:n=`audio/${e}`}return this.mimeTypeCache.set(e,n),D(`[AudioStreamManager] Resolved MIME type for "${e}": ${n}`),n}isAudioEnabled(){return this.isEnabled}setOnPlaybackStart(e){this.onPlaybackStart=e}setOnPlaybackEnd(e){this.onPlaybackEnd=e}setOnChunkPlayed(e){this.onChunkPlayed=e}async addChunk(e){if(!this.isEnabled){D(`[AudioStreamManager] Audio disabled, dropping chunk ${e.chunkIndex}`);return}D(`[AudioStreamManager] Adding chunk ${e.chunkIndex} to queue`),this.audioQueue.push(e),this.audioQueue.sort((r,n)=>r.chunkIndex-n.chunkIndex),this.isPlaying||this.playNextChunk().catch(r=>{pe("[AudioStreamManager] Playback chain error:",r)})}async playNextChunk(){var r,n;if(this.audioQueue.length===0){this.isPlaying=!1,D("[AudioStreamManager] Queue empty, playback complete"),this.onPlaybackEnd&&this.onPlaybackEnd();return}if(!this.isEnabled){D("[AudioStreamManager] Audio not enabled, skipping playback"),this.audioQueue=[],this.isPlaying=!1;return}this.suppressPlaybackErrors=!1,await this.ensureAudioContext(),this.isPlaying=!0;const e=this.audioQueue.shift();try{if(!this.isPlaying)return;if(this.onPlaybackStart&&e.chunkIndex===0&&this.onPlaybackStart(),D(`[AudioStreamManager] Playing chunk ${e.chunkIndex}`),!e.audio||e.audio.length===0)throw new Error(`Empty audio data for chunk ${e.chunkIndex}`);let s;try{s=atob(e.audio)}catch(f){throw new Error(`Failed to decode base64 audio for chunk ${e.chunkIndex}: ${f instanceof Error?f.message:String(f)}`)}if(s.length===0)throw new Error(`Decoded audio data is empty for chunk ${e.chunkIndex}`);const i=new Uint8Array(s.length);for(let f=0;f<s.length;f++)i[f]=s.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,d)}catch{u=!1}if(!u&&!this.suppressPlaybackErrors&&this.audioContext){D(`[AudioStreamManager] HTMLAudioElement failed for chunk ${e.chunkIndex}, trying AudioContext fallback`);try{u=await this.playViaAudioContext(i.buffer,e.chunkIndex)}catch(f){pe(`[AudioStreamManager] AudioContext fallback also failed for chunk ${e.chunkIndex}:`,f)}d()}this.currentAudio=null,this.playNextChunk().catch(f=>{pe("[AudioStreamManager] Playback chain error:",f)})}catch(s){if(this.suppressPlaybackErrors){D("[AudioStreamManager] Playback stopped, suppressing audio error");return}const i=s instanceof Error?s.message:String(s);console.error(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,i,s,{audioFormat:e.audioFormat,chunkIndex:e.chunkIndex,audioLength:(r=e.audio)==null?void 0:r.length,audioContextState:(n=this.audioContext)==null?void 0:n.state,isEnabled:this.isEnabled}),pe(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,s),this.playNextChunk().catch(o=>{pe("[AudioStreamManager] Playback chain error after recovery:",o)})}}playViaAudioElement(e,r,n){return new Promise(s=>{const i=new Audio;i.setAttribute("playsinline",""),i.setAttribute("webkit-playsinline",""),i.src=e,this.currentAudio=i;let o=!1;const l=u=>{o||(o=!0,s(u))},c=()=>{if(this.suppressPlaybackErrors){n(),l(!0);return}const u=i.error;pe(`[AudioStreamManager] Media error on chunk ${r.chunkIndex}:`,u?{code:u.code,message:u.message,SRC_NOT_SUPPORTED:u.code===MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED}:"unknown"),n(),l(!1)};i.addEventListener("error",c,{once:!0});const d=async()=>{if(!o)try{i.addEventListener("ended",()=>{o||(D(`[AudioStreamManager] Chunk ${r.chunkIndex} finished`),this.onChunkPlayed&&this.onChunkPlayed(r.chunkIndex),n(),l(!0))},{once:!0}),await i.play()}catch(u){if(this.suppressPlaybackErrors){n(),l(!0);return}D(`[AudioStreamManager] audio.play() rejected for chunk ${r.chunkIndex}:`,u),n(),l(!1)}};i.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA?d():i.addEventListener("canplay",()=>d(),{once:!0})})}playViaAudioContext(e,r){return new Promise((n,s)=>{if(!this.audioContext){s(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=()=>{D(`[AudioStreamManager] Chunk ${r} finished (AudioContext path)`),this.onChunkPlayed&&this.onChunkPlayed(r),n(!0)},l.start(0)},o=>{s(o)})})}stop(){D("[AudioStreamManager] Stopping playback"),this.suppressPlaybackErrors=!0,this.isPlaying=!1,this.audioQueue=[],this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.blobUrls.forEach(e=>URL.revokeObjectURL(e)),this.blobUrls=[]}reset(){this.stop(),D("[AudioStreamManager] Manager reset")}getQueueSize(){return this.audioQueue.length}isCurrentlyPlaying(){return this.isPlaying}}const Xt=new bu,yu=[{extensions:["pdf"],Icon:Cn,colorClass:"bg-red-500"},{extensions:["doc","docx"],Icon:Cn,colorClass:"bg-blue-500"},{extensions:["xls","xlsx","csv"],Icon:Ui,colorClass:"bg-emerald-600"},{extensions:["ppt","pptx"],Icon:Hi,colorClass:"bg-orange-500"},{extensions:["png","jpg","jpeg","webp","tiff","gif"],Icon:Qc,colorClass:"bg-violet-500"},{extensions:["wav","mp3","ogg","flac","webm","m4a","aac"],Icon:Yc,colorClass:"bg-teal-600"},{extensions:["mp4","mov","avi","mkv"],Icon:Zc,colorClass:"bg-pink-600"},{extensions:["zip","rar","7z","tar","gz"],Icon:Xc,colorClass:"bg-amber-600"},{extensions:["js","mjs","ts","tsx","py","java","sql","cpp","cxx","cc","c","h","hpp","go","rs","rb","php","sh","bash","zsh","yaml","yml","xml","css","scss","sass","less","json","html","vtt"],Icon:Di,colorClass:"bg-slate-500"}],wu=new Set(["png","jpg","jpeg","webp","tiff","gif"]);function ku(t){const e=/\.([a-z0-9]+)$/i.exec(t.trim());return e?e[1].toLowerCase():""}function vu(t){const e=ku(t),r=yu.find(n=>n.extensions.includes(e));return{Icon:(r==null?void 0:r.Icon)??Jc,colorClass:(r==null?void 0:r.colorClass)??"bg-gray-400 dark:bg-gray-500",label:e?e.toUpperCase():"",isImage:wu.has(e)}}const Wr=new Map;function to(t,e){const r=Wr.get(t);r&&r!==e&&URL.revokeObjectURL(r),Wr.set(t,e)}function Su(t){return Wr.get(t)}function Ln(t){const e=Wr.get(t);e&&(URL.revokeObjectURL(e),Wr.delete(t))}const ju=yc()||nc(),ro=()=>{if(Os())return $n()||void 0},Ur="",Cu=["New Chat","New Conversation"],Au=t=>t&&!Cu.includes(t)?t:Ur,Or=(t,e,r)=>({id:t,sessionId:e,title:Ur,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:r,adapterName:ro(),adapterLoadError:null}),Ts=()=>{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},Nu=t=>{localStorage.setItem("chatbot-session-id",t)};let Iu=0;const gr=t=>{const e=Date.now(),r=++Iu,n=Math.random().toString(36).substr(2,9);return`msg_${e}_${r}_${n}_${t}`},Yt=()=>{const t=Date.now(),e=Math.random().toString(36).substr(2,9);return`session_${t}_${e}`},so=t=>{const e=new Set;let r=!1;const n=t.map(s=>{if(!e.has(s.id))return e.add(s.id),s;r=!0;const i={...s,id:gr(s.role)};return e.add(i.id),be(`[chatStore] Re-keyed duplicate message id ${s.id}`),i});return r?n:t},Qa=t=>t.filter(e=>!e.isThreadMessage&&!(e.role==="assistant"&&e.isStreaming)).length,Za=t=>t.flatMap(r=>[r.imageUrl,r.videoUrl,r.documentUrl]).map(r=>{var n;return((n=r==null?void 0:r.match(/\/api\/files\/([^/]+)\/content/))==null?void 0:n[1])??null}).filter(r=>r!==null),Lu=(t,e)=>{if(t instanceof Date)return new Date(t);if(typeof t=="number"&&Number.isFinite(t)){const r=new Date(t);if(!Number.isNaN(r.getTime()))return r}if(typeof t=="string"){const r=new Date(t);if(!Number.isNaN(r.getTime()))return r}return e?new Date(e):new Date},Eu=(t,e)=>{const r=new Map;e.forEach((s,i)=>{s.databaseMessageId&&r.set(s.databaseMessageId,{message:s,index:i})});const n=new Set;return t.map((s,i)=>{var f;const o=s.role==="user"?"user":"assistant",l=typeof s.message_id=="string"&&s.message_id.length>0?s.message_id:void 0;let c;if(l&&r.has(l)){const p=r.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 g=1;g<e.length;g++){const h=(p+g)%e.length;if(!n.has(h)&&e[h].role===o){c=e[h],n.add(h);break}}}const d=s.timestamp?Lu(s.timestamp,c==null?void 0:c.timestamp):c!=null&&c.timestamp?new Date(c.timestamp):new Date,u=c?{...c,content:s.content??c.content,timestamp:d}:{id:l?`srv_${l}`:gr(o),content:s.content||"",role:o,timestamp:d};if(u.isStreaming=!1,l&&(u.databaseMessageId=l),!u.supportsThreading&&s.metadata&&typeof s.metadata=="object"){const p=s.metadata,g=p==null?void 0:p.retrieved_docs;Array.isArray(g)&&g.length>0&&(u.supportsThreading=!0)}return u})},_u=(t,e)=>{if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){const n=t[r],s=e[r];if(n.role!==s.role||n.content!==s.content||(n.databaseMessageId||null)!==(s.databaseMessageId||null)||+n.timestamp!=+s.timestamp)return!1}return!0},no=t=>{var s,i,o,l,c,d;const e=((i=(s=t.adapterInfo)==null?void 0:s.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 r=!1;try{const u=localStorage.getItem("chat-settings");u&&(r=JSON.parse(u).voiceEnabled===!0)}catch{be("Failed to read global voice setting")}const n=t.audioSettings;return{returnAudio:(n==null?void 0:n.enabled)??r??!!e,ttsVoice:(n==null?void 0:n.ttsVoice)||void 0,language:(n==null?void 0:n.language)||"en-US",audioFormat:n==null?void 0:n.audioFormat}},Tu=300;let xs=null;const qe=t=>{xs&&clearTimeout(xs),xs=setTimeout(()=>{xs=null;try{const e=t(),r=e.conversations.map(n=>({...n,messages:n.messages.map(s=>s.audio||s.image||s.video||s.document?Object.fromEntries(Object.entries(s).filter(([o])=>o!=="audio"&&o!=="image"&&o!=="video"&&o!=="document")):s)}));localStorage.setItem("chat-state",JSON.stringify({conversations:r,currentConversationId:e.currentConversationId}))}catch(e){e instanceof DOMException&&e.name==="QuotaExceededError"?be("[chatStore] localStorage quota exceeded — skipping save"):Be("[chatStore] Failed to save state to localStorage:",e)}},Tu)},Mu=32,xr=new Map;let Gt=null,it=null,Rt=null,ar=null;const En=(t,e)=>{const r=xr.get(t);if(r){if(r.timeoutId&&(clearTimeout(r.timeoutId),r.timeoutId=null),r.content){const n=r.content,s=r.messageId;r.content="",e(i=>({conversations:i.conversations.map(o=>{if(o.id!==t)return o;const l=[...o.messages],c=s?l.findIndex(u=>u.id===s):l.length-1,d=c!==-1?l[c]:void 0;return d&&d.role==="assistant"&&d.isStreaming&&(l[c]={...d,content:d.content+n}),{...o,messages:l,updatedAt:new Date}})}))}xr.delete(t)}},ht=(t,e,r,n)=>({conversations:t.conversations.map(s=>{var l;if(s.id!==e)return s;const i=[...s.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],...r(i[o])}),{...s,messages:i,updatedAt:new Date}})});let Ms=!1,Fs="";async function $r(){if(Ms&&Fs)return!0;try{const t=await Me(),e=localStorage.getItem("chat-api-url");e&&e===kn&&localStorage.removeItem("chat-api-url");const r=e&&e!==kn?e:Fe(),n=Ts(),s=localStorage.getItem("chat-adapter-name")||ju;return t.configureApi(r,n,s),Fs=r,Ms=!0,!0}catch(t){return Be("Failed to configure API:",t),!1}}async function Ja(t,e,r,n,s,i,o,l,c){let d=!1;const u=new AbortController;Gt=u,ar=n,it=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.");Rt=f.sessionId,f.sessionId&&(await Me()).configureApi(at(f.apiUrl),f.sessionId,f.adapterName);const p=await Me(),{returnAudio:g,ttsVoice:h,language:x}=no(f);for await(const y of p.streamChat(s,!0,i.length>0?i:void 0,void 0,void 0,void 0,x,g,h,void 0,void 0,o,void 0,c)){if(y.request_id&&!it&&(it=y.request_id,D(`[chatStore] >>> CAPTURED request_id for ${l} stop: ${y.request_id}`)),y.text){const k=Vr(y.text);k?(t().appendToLastMessage(k,n,r),d=!0):y.text.length>100&&be("[chatStore] Filtered out potential base64 audio data from regenerated message content")}if(y.audio&&y.done&&e(k=>ht(k,n,()=>({audio:y.audio,audioFormat:y.audioFormat||"mp3"}),r)),y.image&&y.done&&(d=!0,e(k=>ht(k,n,()=>({image:y.image,imageFormat:y.image_format||"png",imageRevisedPrompt:y.image_revised_prompt,imageUrl:y.image_url}),r))),(y.video||y.video_url)&&y.done&&(d=!0,e(k=>ht(k,n,()=>({video:y.video,videoFormat:y.video_format||"mp4",videoRevisedPrompt:y.video_revised_prompt,videoUrl:y.video_url}),r))),(y.document||y.document_url)&&y.done&&(d=!0,e(k=>ht(k,n,()=>({document:y.document,documentFormat:y.document_format||"pdf",documentRevisedPrompt:y.document_revised_prompt,documentUrl:y.document_url}),r))),y.generated_audio_url&&y.done&&(d=!0,e(k=>ht(k,n,()=>({generatedAudioFormat:y.generated_audio_format||"mp3",generatedAudioRevisedPrompt:y.generated_audio_revised_prompt,generatedAudioUrl:y.generated_audio_url}),r))),y.done){const k=y.threading;k!=null&&k.supports_threading&&e(C=>({conversations:C.conversations.map(L=>L.id!==n?L:{...L,messages:L.messages.map(N=>N.id===r?{...N,supportsThreading:!0,databaseMessageId:k.message_id}:N),updatedAt:new Date})})),y.assistant_message_id&&e(C=>({conversations:C.conversations.map(L=>L.id!==n?L:{...L,messages:L.messages.map(N=>N.id===r&&!N.databaseMessageId?{...N,databaseMessageId:y.assistant_message_id}:N),updatedAt:new Date})})),y.model&&e(C=>ht(C,n,()=>({model:y.model}),r));break}}!d&&!u.signal.aborted&&t().appendToLastMessage("No response received from the server. Please try again later.",n,r)}catch(f){if(f instanceof Error&&(f.name==="AbortError"||f.message==="Stream cancelled by user"||f.message.includes("aborted")))D(`[chatStore] ${l==="edit-regenerate"?"Edit-regenerate":"Regeneration"} stream was cancelled by user`),d=!0;else{Be(`${l==="edit-regenerate"?"Edit-regenerate":"Regenerate"} API error:`,f);let g="Sorry, there was an error regenerating the response.";f instanceof Error&&(f.message.startsWith("Server error:")?g=f.message.substring(14):(f.message.includes("Could not connect")||f.message.includes("timed out"))&&(g=f.message)),t().appendToLastMessage(g,n,r)}}Gt=null,it=null,Rt=null,ar=null,En(n,e),e(f=>{const p=f.conversations.map(h=>h.id===n?{...h,messages:h.messages.map(x=>x.id===r?{...x,isStreaming:!1}:x),updatedAt:new Date}:h),g=p.find(h=>h.id===f.currentConversationId);return{conversations:p,isLoading:g?g.messages.some(h=>h.role==="assistant"&&h.isStreaming):!1}})}const ye=eo((t,e)=>({conversations:[],currentConversationId:null,isLoading:!1,error:null,sessionId:Ts(),getSessionId:()=>e().sessionId,configureApiSettings:async(r,n,s)=>{const i=e(),o=i.conversations.find(c=>c.id===i.currentConversationId),l=(o==null?void 0:o.sessionId)||n||Ts();n&&Nu(n),t({sessionId:l});try{const c=await Me();if(!s||!s.trim())throw new Error("Adapter name is required");c.configureApi(r,l,s),Fs=r,Ms=!0;let d;try{const u=new c.ApiClient({apiUrl:r,sessionId:null,adapterName:s});typeof u.getAdapterInfo=="function"&&(d=await u.getAdapterInfo(),D("Adapter info loaded:",d))}catch(u){be("Failed to load adapter info:",u)}if(o)t(u=>({conversations:u.conversations.map(f=>f.id===o.id?{...f,adapterName:s,apiUrl:r,adapterInfo:d,adapterLoadError:null,updatedAt:new Date}:f)}));else if(s&&s.trim()){const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,f=Yt();t(p=>({conversations:[...p.conversations,{id:u,sessionId:f,title:Ur,messages:[],createdAt:new Date,updatedAt:new Date,adapterName:s,apiUrl:r,adapterInfo:d,adapterLoadError:null}],currentConversationId:u}))}}catch(c){throw pe("Failed to configure API:",c),t({isLoading:!1}),c instanceof Error?c:new Error("Failed to configure API settings")}s?localStorage.setItem("chat-adapter-name",s):localStorage.removeItem("chat-adapter-name"),t({isLoading:!1})},createConversation:()=>{var u;const r=e(),n=oe.maxConversations,s=r.conversations.length,i=r.currentConversationId?r.conversations.find(f=>f.id===r.currentConversationId):null;if(n!==null&&s>=n){if(tt()&&!kt()){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}),rt.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=Yt(),d={id:l,sessionId:c,title:Ur,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:Fe(),adapterName:ro(),adapterLoadError:null};return t(f=>({conversations:[d,...f.conversations],currentConversationId:l,sessionId:c,isLoading:!1})),qe(e),l},selectConversation:async r=>{const n=e().conversations.find(s=>s.id===r);if(n){const s=n.messages.some(c=>c.role==="assistant"&&c.isStreaming);t({currentConversationId:r,sessionId:n.sessionId,isLoading:s});const i=n.apiUrl||Fe(),o=n.adapterName;if(await $r()&&o){const c=await Me();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();D("Adapter info loaded for conversation:",u),t(f=>({conversations:f.conversations.map(p=>p.id===r?{...p,adapterInfo:u,adapterLoadError:null,updatedAt:new Date}:p)})),qe(e)}}catch(d){be("Failed to load adapter info for conversation:",d)}}e().loadFeedbackForConversation(n.sessionId).catch(()=>{})}qe(e)},deleteConversation:async r=>{var i,o;const n=e(),s=n.conversations.find(l=>l.id===r);if(D(`🗑️ Deleting conversation ${r}:`,{conversationId:r,sessionId:s==null?void 0:s.sessionId,title:s==null?void 0:s.title,messageCount:s==null?void 0:s.messages.length,fileCount:((i=s==null?void 0:s.attachedFiles)==null?void 0:i.length)||0}),n.currentConversationId===r&&Xt.stop(),s){const l=(s.attachedFiles||[]).map(d=>d.file_id),c=(s.messages||[]).flatMap(d=>(d.attachments||[]).map(u=>u.file_id));[...l,...c].forEach(Ln)}if(s!=null&&s.sessionId)try{if(!await $r())Be("Failed to configure API for conversation deletion");else{const c=s.apiUrl||Fe(),d=s.adapterName;d?D(`Using conversation's adapter for deletion: ${d} (conversation: ${r})`):be(`Skipping server deletion for conversation ${r}: adapter not configured`);const u=await Me(),f=new u.ApiClient({apiUrl:c,sessionId:s.sessionId,adapterName:d}),p=((o=s.attachedFiles)==null?void 0:o.map(x=>x.file_id))||[],g=Za(s.messages||[]),h=[...p,...g];if(D(`🔧 Calling deleteConversationWithFiles for session: ${s.sessionId}`),f.deleteConversationWithFiles){const x=await f.deleteConversationWithFiles(s.sessionId,h);D(`✅ Deleted conversation and files for session: ${s.sessionId}`,x),D(` - Deleted ${x.deleted_messages} messages`),D(` - Deleted ${x.deleted_files} files`),x.file_deletion_errors&&x.file_deletion_errors.length>0&&be(` - Errors deleting files: ${x.file_deletion_errors.join(", ")}`)}else be("⚠️ deleteConversationWithFiles method not available on API client")}}catch(l){Be("Failed to clear conversation history from server:",l)}else be(`⚠️ No session ID found for conversation ${r}, skipping server-side deletion`);t(l=>{var u;const c=l.conversations.filter(f=>f.id!==r),d=l.currentConversationId===r?((u=c[0])==null?void 0:u.id)||null:l.currentConversationId;if(c.length===0){const f=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,p=Yt(),g=Or(f,p,Fe());return qe(e),{conversations:[g],currentConversationId:f,sessionId:p}}return qe(e),{conversations:c,currentConversationId:d}})},deleteAllConversations:async()=>{const n=[...e().conversations];D(`🗑️ Deleting all conversations (${n.length} total)`),Xt.stop();const s=n.map(async u=>{var f;if(u!=null&&u.sessionId)try{if(!await $r()){Be("Failed to configure API for conversation deletion");return}const g=u.adapterName;if(!g){D(`Skipping server deletion for conversation ${u.id}: adapter not configured`);return}const h=await Me(),x=new h.ApiClient({apiUrl:at(u.apiUrl),sessionId:u.sessionId,adapterName:g}),y=[...((f=u.attachedFiles)==null?void 0:f.map(k=>k.file_id))||[],...Za(u.messages||[])];x.deleteConversationWithFiles?(await x.deleteConversationWithFiles(u.sessionId,y),D(`✅ Deleted conversation ${u.id} and files`)):be(`deleteConversationWithFiles not available for conversation ${u.id}`)}catch(p){Be(`Failed to delete conversation ${u.id} from server:`,p)}}),o=(await Promise.allSettled(s)).filter(u=>u.status==="rejected");o.length>0&&Be(`Some conversations failed to delete from server: ${o.length}`,o);const l=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,c=Yt(),d=Or(l,c,Fe());t({conversations:[d],currentConversationId:l,sessionId:c}),qe(e)},deleteThread:async(r,n,s)=>{const i=e().conversations.find(f=>f.id===r);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!==s)throw new Error("Thread not found for this message");const l=at(i.apiUrl||Fe()),c=await Me(),d=new c.ApiClient({apiUrl:l,sessionId:i.sessionId,adapterName:i.adapterName});await new(await Nt(async()=>{const{ThreadService:f}=await import("./threadService-B9Db3n0J.js");return{ThreadService:f}},[])).ThreadService(d).deleteThread(s),t(f=>({conversations:f.conversations.map(p=>{var x;if(p.id!==r)return p;const g=p.messages.filter(y=>y.isThreadMessage?!(y.threadId===s||y.parentMessageId===n):!0).map(y=>y.id!==n?y:{...y,threadInfo:void 0,supportsThreading:!0}),h=p.currentThreadId===s||p.currentThreadSessionId===((x=o.threadInfo)==null?void 0:x.thread_session_id);return{...p,messages:g,currentThreadId:h?void 0:p.currentThreadId,currentThreadSessionId:h?void 0:p.currentThreadSessionId,updatedAt:new Date}})})),qe(e)},sendMessage:async(r,n,s,i,o)=>{var c;let l=null;try{if(e().isLoading){be("Another request is already in progress");return}if(!await $r())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()&&!kt()&&p!==null&&e().conversations.length>p){rt.getState().openLoginPrompt(`You've reached the guest limit of ${p} conversation${p===1?"":"s"}. Sign in to continue chatting.`),t({isLoading:!1});return}const g=n?n.map(b=>{var j;const $=(j=f==null?void 0:f.attachedFiles)==null?void 0:j.find(I=>I.file_id===b);return $||{file_id:b,filename:"",mime_type:"",file_size:0}}).filter(b=>b!==void 0):[];g.length>0&&g.forEach(b=>{e().addFileToConversation(u,b)});const h=s||null;let x,y=null;if(h){if(x=f.messages.find(b=>{var $;return(($=b.threadInfo)==null?void 0:$.thread_id)===h}),!x)throw new Error("Thread metadata not found. Please recreate the thread from this message.");if(y=((c=x.threadInfo)==null?void 0:c.thread_session_id)||null,!y)throw new Error("Thread session is missing. Please recreate the thread from this message.")}const k=Qa(f.messages),C=oe.maxMessagesPerConversation;if(C!==null&&k>=C){tt()&&!kt()&&rt.getState().openLoginPrompt(`You've reached the guest limit of ${C} messages per conversation. Sign in to send more messages, or delete conversations to start over.`),be(`[chatStore] Conversation ${u} reached the message limit (${C}).`),t({isLoading:!1});return}const L=oe.maxTotalMessages;if(L!==null&&e().conversations.reduce(($,j)=>$+Qa(j.messages),0)>=L){tt()&&!kt()&&rt.getState().openLoginPrompt(`You've reached the guest limit of ${L} total messages. Sign in to continue chatting, or delete conversations to start over.`),be(`[chatStore] Workspace reached the total message limit (${L}).`),t({isLoading:!1});return}const N={id:gr("user"),content:r,role:"user",timestamp:new Date,attachments:g.length>0?g:void 0},v=gr("assistant"),T={id:v,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:i};if(h&&x){N.isThreadMessage=!0,N.threadId=h,N.parentMessageId=x.id,T.isThreadMessage=!0,T.threadId=h,T.parentMessageId=x.id;const b=oe.maxMessagesPerThread;if(b!==null&&f.messages.filter(j=>j.isThreadMessage?(j.threadId===h||j.parentMessageId===x.id)&&!(j.role==="assistant"&&j.isStreaming):!1).length>=b){tt()&&!kt()&&rt.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.`),be(`[chatStore] Thread ${h} reached the message limit (${b}).`),t({isLoading:!1});return}}t(b=>{const $=b.conversations.find(I=>I.id===u),j=($==null?void 0:$.messages.filter(I=>I.role==="assistant"&&I.isStreaming))||[];return j.length>0&&be(`Cleaning up ${j.length} existing streaming messages`),{conversations:b.conversations.map(I=>{if(I.id!==u)return I;const O=I.messages.filter(R=>!(R.role==="assistant"&&R.isStreaming));return{...I,messages:[...O,N,T],updatedAt:new Date,title:I.messages.length===0?r.slice(0,50)+(r.length>50?"...":""):I.title}}),isLoading:!0,error:null}}),l=u;let _=!1;Xt.reset();try{const b=e().conversations.find(S=>S.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 $=at(b.apiUrl),j=b.adapterName,I=y||b.sessionId,O=await Me();O.configureApi($,I,j),h&&I!==b.sessionId&&D(`[chatStore] Thread mode: using thread session ${I} (original: ${b.sessionId})`);const{returnAudio:R,ttsVoice:H,language:A,audioFormat:E}=no(b);D("[chatStore] Audio settings:",{returnAudio:R,ttsVoice:H,language:A,audioFormat:E});const z=new AbortController;Gt=z,Rt=I,ar=l,it=null;for await(const S of O.streamChat(r,!0,n,h||void 0,void 0,void 0,A,R,H,void 0,void 0,i,o)){if(S.request_id&&!it&&(it=S.request_id,D(`[chatStore] >>> CAPTURED request_id for stop: ${S.request_id}`)),S.audio_chunk&&Xt.addChunk({audio:S.audio_chunk,audioFormat:S.audioFormat||"opus",chunkIndex:S.chunk_index??0}),S.text){const W=Vr(S.text);W?(e().appendToLastMessage(W,l,v),_=!0):S.text.length>100&&be("[chatStore] Filtered out potential base64 audio data from message content")}if(S.audio&&S.done&&t(W=>ht(W,l,()=>({audio:S.audio,audioFormat:S.audioFormat||"mp3"}),v)),S.image&&S.done&&(_=!0,t(W=>ht(W,l,()=>({image:S.image,imageFormat:S.image_format||"png",imageRevisedPrompt:S.image_revised_prompt,imageUrl:S.image_url}),v))),(S.video||S.video_url)&&S.done&&(_=!0,t(W=>ht(W,l,()=>({video:S.video,videoFormat:S.video_format||"mp4",videoRevisedPrompt:S.video_revised_prompt,videoUrl:S.video_url}),v))),(S.document||S.document_url)&&S.done&&(_=!0,t(W=>ht(W,l,()=>({document:S.document,documentFormat:S.document_format||"pdf",documentRevisedPrompt:S.document_revised_prompt,documentUrl:S.document_url}),v))),S.generated_audio_url&&S.done&&(_=!0,t(W=>ht(W,l,()=>({generatedAudioFormat:S.generated_audio_format||"mp3",generatedAudioRevisedPrompt:S.generated_audio_revised_prompt,generatedAudioUrl:S.generated_audio_url}),v))),S.done){D("[chatStore] Stream completed, receivedAnyText:",_);const W=S.threading;W!=null&&W.supports_threading&&t(K=>({conversations:K.conversations.map(q=>q.id!==l?q:{...q,messages:q.messages.map(G=>G.id===v?{...G,supportsThreading:!0,databaseMessageId:W.message_id}:G),updatedAt:new Date})})),S.assistant_message_id&&t(K=>({conversations:K.conversations.map(q=>q.id!==l?q:{...q,messages:q.messages.map(G=>G.id===v&&!G.databaseMessageId?{...G,databaseMessageId:S.assistant_message_id}:G),updatedAt:new Date})})),S.model&&t(K=>ht(K,l,()=>({model:S.model}),v));break}}!_&&!z.signal.aborted&&e().appendToLastMessage("No response received from the server. Please try again later.",l,v)}catch(b){if(b instanceof Error&&(b.name==="AbortError"||b.message==="Stream cancelled by user"||b.message.includes("aborted")))D("[chatStore] Stream was cancelled by user"),_=!0;else{Be("Chat API error:",b);let j="Sorry, there was an error processing your request.";b instanceof Error&&(b.message.startsWith("Server error:")?j=b.message.substring(14):(b.message.includes("Could not connect")||b.message.includes("timed out"))&&(j=b.message)),e().appendToLastMessage(j,l,v)}}Gt=null,it=null,Rt=null,ar=null,En(l,t),t(b=>{const $=b.conversations.map(I=>I.id===l?{...I,messages:I.messages.map(O=>O.id===v?{...O,isStreaming:!1}:O),updatedAt:new Date}:I),j=$.find(I=>I.id===b.currentConversationId);return{conversations:$,isLoading:j?j.messages.some(I=>I.role==="assistant"&&I.isStreaming):!1}}),qe(e)}catch(d){Be("Chat store error:",d),t(u=>({isLoading:!1,...u.currentConversationId===l&&{error:`Failed to send message: ${d instanceof Error?d.message:"Unknown error"}`}}))}},createThread:async(r,n)=>{try{const s=e().conversations.find(p=>p.sessionId===n);if(!s)throw new Error("Conversation not found for session");if(!s.adapterName)throw new Error("Adapter not configured for this conversation");const i=s.messages.find(p=>p.id===r);if(!i)throw new Error("Message not found");const o=i.databaseMessageId||r,l=at(s.apiUrl||Fe()),c=await Me(),d=new c.ApiClient({apiUrl:l,sessionId:n,adapterName:s.adapterName}),f=await new(await Nt(async()=>{const{ThreadService:p}=await import("./threadService-B9Db3n0J.js");return{ThreadService:p}},[])).ThreadService(d).createThread(o,n);t(p=>({conversations:p.conversations.map(g=>g.sessionId!==n?g:{...g,messages:g.messages.map(h=>h.id===r?{...h,threadInfo:f,supportsThreading:!0}:h),currentThreadId:void 0,currentThreadSessionId:void 0})})),D(`[chatStore] Created thread ${f.thread_id} for message ${r}`)}catch(s){throw Be("Failed to create thread:",s),s}},appendToLastMessage:(r,n,s)=>{const i=Vr(r);if(!i&&r){be("[chatStore] Filtered out base64 audio data from message content");return}const o=In(i),l=n||e().currentConversationId;if(!l)return;const c=l,d=xr.get(c);d?(d.content+=o,d.messageId=s,d.timeoutId&&clearTimeout(d.timeoutId)):xr.set(c,{content:o,timeoutId:null,messageId:s});const u=()=>{const p=xr.get(c);if(!p||!p.content)return;const g=p.content,h=p.messageId;p.content="",p.timeoutId=null,t(x=>({conversations:x.conversations.map(y=>{if(y.id!==l)return y;const k=[...y.messages],C=h?k.findIndex(N=>N.id===h):k.length-1,L=C!==-1?k[C]:void 0;return L&&L.role==="assistant"&&L.isStreaming&&(k[C]={...L,content:L.content+g}),{...y,messages:k,updatedAt:new Date}})}))},f=xr.get(c);f.timeoutId=setTimeout(u,Mu)},regenerateResponse:async(r,n)=>{let s=null;try{if(e().isLoading){be("Another request is already in progress");return}if(!await $r())throw new Error("API not properly configured");const o=e(),l=o.conversations.find(g=>g.id===o.currentConversationId);if(!l)return;const c=l.messages.findIndex(g=>g.id===r);if(c===-1)return;const d=l.messages[c];if(!d||d.role!=="assistant")return;const u=l.messages[c-1];if(!u||u.role!=="user")return;const f=(u.attachments||[]).map(g=>g.file_id).filter(g=>typeof g=="string"&&g.length>0),p=gr("assistant");if(t(g=>({conversations:g.conversations.map(h=>h.id===g.currentConversationId?{...h,messages:[...h.messages.slice(0,c),{id:p,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:n,supportsThreading:d.supportsThreading,databaseMessageId:d.databaseMessageId,threadInfo:d.threadInfo,threadId:d.threadId,parentMessageId:d.parentMessageId,isThreadMessage:d.isThreadMessage},...h.messages.slice(c+1)],updatedAt:new Date}:h),isLoading:!0,error:null})),s=o.currentConversationId,!s)throw new Error("No conversation selected");await Ja(e,t,p,s,u.content,f,n,"regenerate",d.databaseMessageId)}catch(i){Be("Regenerate error:",i),t(o=>({isLoading:!1,...o.currentConversationId===s&&{error:`Failed to regenerate response: ${i instanceof Error?i.message:"Unknown error"}`}}))}},editMessageAndRegenerate:async(r,n,s)=>{let i=null;try{if(e().isLoading){await e().stopStreaming();const x=e().currentConversationId;x&&En(x,t)}const o=e(),l=o.conversations.find(x=>x.id===o.currentConversationId);if(!l)return;const c=l.messages.findIndex(x=>x.id===r);if(c===-1)return;const d=l.messages[c];if(d.role!=="user")return;const u=(d.attachments||[]).map(x=>x.file_id).filter(x=>typeof x=="string"&&x.length>0),f=gr("assistant"),p=l.messages[c+1],g=(p==null?void 0:p.role)==="assistant",h=g?c+2:c+1;if(t(x=>({conversations:x.conversations.map(y=>y.id===x.currentConversationId?{...y,messages:[...y.messages.slice(0,c),{...d,content:n,updatedAt:new Date},{id:f,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:s,supportsThreading:g?p.supportsThreading:void 0,databaseMessageId:g?p.databaseMessageId:void 0,threadInfo:g?p.threadInfo:void 0,threadId:g?p.threadId:void 0,parentMessageId:g?p.parentMessageId:void 0,isThreadMessage:g?p.isThreadMessage:void 0},...y.messages.slice(h)],updatedAt:new Date}:y),isLoading:!0,error:null})),i=o.currentConversationId,!i)throw new Error("No conversation selected");await Ja(e,t,f,i,n,u,s,"edit-regenerate",g?p.databaseMessageId:void 0),qe(e)}catch(o){Be("Edit & regenerate error:",o),t(l=>({isLoading:!1,...l.currentConversationId===i&&{error:`Failed to regenerate response: ${o instanceof Error?o.message:"Unknown error"}`}}))}},updateConversationTitle:(r,n)=>{t(s=>({conversations:s.conversations.map(i=>i.id===r?{...i,title:n,updatedAt:new Date}:i)})),qe(e)},clearError:()=>t({error:null}),cleanupStreamingMessages:()=>{const r=ar;t(n=>{let s=!1;return{conversations:n.conversations.map(o=>o.id===r?(o.messages.some(c=>c.role==="assistant"&&c.isStreaming)&&(s=!0),o):o.messages.some(c=>c.role==="assistant"&&c.isStreaming)?{...o,messages:o.messages.filter(c=>!(c.role==="assistant"&&c.isStreaming)),updatedAt:new Date}:o),isLoading:s}})},canCreateNewConversation:()=>{var o;const r=e(),n=oe.maxConversations;if(!r.currentConversationId)return n===null||r.conversations.length<n;const s=r.conversations.find(l=>l.id===r.currentConversationId);return!!s&&(s.messages.length>0||(((o=s.attachedFiles)==null?void 0:o.length)||0)>0)?n===null||r.conversations.length<n:!1},getConversationCount:()=>e().conversations.length,addFileToConversation:(r,n)=>{D("[chatStore] addFileToConversation called",{conversationId:r,fileId:n.file_id,filename:n.filename}),t(s=>({conversations:s.conversations.map(i=>i.id===r?{...i,attachedFiles:[...(i.attachedFiles||[]).filter(o=>o.file_id!==n.file_id),n],updatedAt:new Date}:i)})),qe(e)},removeFileFromConversation:async(r,n)=>{D("[chatStore] removeFileFromConversation called",{conversationId:r,fileId:n});try{const s=e().conversations.find(i=>i.id===r);if(!s)throw new Error("Conversation not found");if(!s.adapterName)throw new Error("Adapter not configured for this conversation. Cannot delete file.");await qr.deleteFile(n,void 0,at(s.apiUrl),s.adapterName),D(`[chatStore] Successfully deleted file ${n} from server`)}catch(s){s instanceof Error&&(s.message.includes("404")||s.message.includes("File not found"))?D(`[chatStore] File ${n} was already deleted from server`):pe(`[chatStore] Failed to delete file ${n} from server:`,s)}Ln(n),t(s=>({conversations:s.conversations.map(i=>i.id===r?{...i,attachedFiles:(i.attachedFiles||[]).filter(o=>o.file_id!==n),updatedAt:new Date}:i)})),qe(e)},loadConversationFiles:async r=>{try{const n=e().conversations.find(l=>l.id===r);if(!n)return;if(!n.adapterName){D(`Skipping file load for conversation ${r}: adapter not configured`);return}if(new Set((n.attachedFiles||[]).map(l=>l.file_id)).size===0){D(`No files to sync for conversation ${r}`);return}const i=await qr.listFiles(void 0,at(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===r);if(!c)return l;const d=(c.attachedFiles||[]).map(u=>o.get(u.file_id)||u).filter(u=>o.has(u.file_id)||!u.processing_status||u.processing_status==="processing");return{conversations:l.conversations.map(u=>u.id===r?{...u,attachedFiles:d,updatedAt:new Date}:u)}}),qe(e)}catch(n){Be(`Failed to load files for conversation ${r}:`,n)}},syncConversationFiles:async r=>{await e().loadConversationFiles(r)},syncConversationsWithBackend:async()=>{try{const r=e();if(r.conversations.length===0)return;const n=await Me(),s=oe.maxMessagesPerConversation!==null&&oe.maxMessagesPerConversation||void 0;let i=!1;const l=(await Promise.all(r.conversations.map(async c=>{var d;if(!c.sessionId)return null;if(!c.adapterName)return be(`[chatStore] Skipping backend sync for conversation ${c.id} - adapter not configured`),null;if(c.messages.length===0)return null;try{const u=new n.ApiClient({apiUrl:at(c.apiUrl),sessionId:c.sessionId,adapterName:c.adapterName});if(typeof u.getConversationHistory!="function")return i||(i=!0,be("[chatStore] Conversation history endpoint not supported by current API client")),null;const f=await u.getConversationHistory(c.sessionId,s),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 g=Eu(p,c.messages),h=c.messages.filter(y=>y.isThreadMessage),x=so(h.length>0?[...g,...h]:g);return _u(c.messages,x)?null:{id:c.id,sessionId:(f==null?void 0:f.session_id)||c.sessionId,messages:x,cleared:!1,updatedAt:((d=g[g.length-1])==null?void 0:d.timestamp)||new Date}}catch(u){return be(`[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:Ur,updatedAt:f.updatedAt,adapterLoadError:null}:{...u,sessionId:f.sessionId||u.sessionId,messages:f.messages,updatedAt:f.updatedAt,adapterLoadError:null}:u}),currentConversationId:c.currentConversationId}}),qe(e)}catch(r){be("Failed to synchronize conversations with backend:",r)}},stopStreaming:async()=>{var n;if(!e().isLoading){D("[chatStore] stopStreaming called but not currently loading");return}if(D("[chatStore] Stopping stream...",{hasAbortController:!!Gt,requestId:it,sessionId:Rt}),Gt&&Gt.abort(),it&&Rt)try{const s=await Me(),i=await((n=s.stopChat)==null?void 0:n.call(s,Rt,it));D(`[chatStore] Server-side cancellation result: ${i}`)}catch(s){be("[chatStore] Failed to cancel server-side stream:",s)}else be(`[chatStore] Cannot call stopChat - missing IDs: requestId=${it}, sessionId=${Rt}`);const r=ar||e().currentConversationId;t(r?s=>({conversations:s.conversations.map(i=>i.id!==r?i:{...i,messages:i.messages.map(o=>o.isStreaming?{...o,isStreaming:!1}:o),updatedAt:new Date}),isLoading:!1}):{isLoading:!1}),Gt=null,it=null,Rt=null,ar=null,D("[chatStore] Stream stopped successfully")},clearCurrentConversationAdapter:()=>{const r=e().currentConversationId;r&&(t(n=>({conversations:n.conversations.map(s=>s.id===r?{...s,adapterName:void 0,adapterInfo:void 0,adapterLoadError:null}:s)})),qe(e))},submitFeedback:async(r,n,s)=>{const i=e(),o=i.conversations.find(c=>c.id===i.currentConversationId);if(!o)return!1;const l=o.messages.find(c=>c.id===r);if(!(l!=null&&l.databaseMessageId))return be("[chatStore] Cannot submit feedback: no databaseMessageId on message"),!1;if(!o.adapterName)return!1;try{const c=await Me(),u=await new c.ApiClient({apiUrl:at(o.apiUrl||Fe()),sessionId:o.sessionId,adapterName:o.adapterName}).submitFeedback(l.databaseMessageId,o.sessionId,n,s),f=u.feedback_type,p=u.comment??null;return t(g=>({conversations:g.conversations.map(h=>h.id!==i.currentConversationId?h:{...h,messages:h.messages.map(x=>x.id===r?{...x,feedback:f,feedbackComment:p}:x),updatedAt:new Date})})),qe(e),!0}catch(c){return pe("[chatStore] Failed to submit feedback:",c),!1}},loadFeedbackForConversation:async r=>{var i;const s=e().conversations.find(o=>o.sessionId===r);if(s!=null&&s.adapterName)try{const o=await Me(),l=new o.ApiClient({apiUrl:at(s.apiUrl||Fe()),sessionId:s.sessionId,adapterName:s.adapterName}),c=new Set([r]);for(const f of s.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,{feedbackType:p.feedback_type,comment:p.comment??null});if(u.size===0)return;t(f=>({conversations:f.conversations.map(p=>p.sessionId!==r?p:{...p,messages:p.messages.map(g=>{if(g.databaseMessageId&&u.has(g.databaseMessageId)){const h=u.get(g.databaseMessageId);return{...g,feedback:h.feedbackType,feedbackComment:h.comment}}return g})})}))}catch(o){pe("[chatStore] Failed to load feedback:",o)}}})),Fu=async()=>{var c;const t=localStorage.getItem("chat-state"),e=Fe(),r=!!localStorage.getItem("chat-api-url");let n=Ts(),s=!1;if(t)try{const d=JSON.parse(t),u=g=>{if(g instanceof Date)return g;const h=g?new Date(g):new Date;return Number.isNaN(h.getTime())?new Date:h},p=(Array.isArray(d.conversations)?d.conversations:[]).map(g=>{const x=(Array.isArray(g.messages)?g.messages:[]).filter(L=>!(L.role==="assistant"&&L.isStreaming)).map(L=>({...L,timestamp:u(L.timestamp),isStreaming:!1})),y=so(x),k={id:g.id,sessionId:g.sessionId||Yt(),title:Au(g.title),messages:y,createdAt:u(g.createdAt),updatedAt:u(g.updatedAt),attachedFiles:g.attachedFiles||[],adapterName:g.adapterName,apiUrl:g.apiUrl,adapterInfo:g.adapterInfo,adapterLoadError:g.adapterLoadError||null,audioSettings:g.audioSettings,currentThreadId:void 0,currentThreadSessionId:void 0},C=k.messages.length===0&&!k.adapterName;return{...k,apiUrl:C&&!r?e:at(g.apiUrl)}});if(s=p.length>0,d.currentConversationId&&p.length>0){const g=p.find(h=>h.id===d.currentConversationId);g!=null&&g.sessionId&&(n=g.sessionId)}if(p.length===0){const g=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=Yt(),x=Or(g,h,Fe());ye.setState({conversations:[x],currentConversationId:g,sessionId:h}),n=h}else ye.setState({conversations:p,currentConversationId:d.currentConversationId||((c=p[0])==null?void 0:c.id)||null,sessionId:n}),!d.currentConversationId&&p.length>0&&(ye.setState({currentConversationId:p[0].id,sessionId:p[0].sessionId||n}),n=p[0].sessionId||n);D("📋 Loaded conversations:",ye.getState().conversations.map(g=>{var h;return{id:g.id,title:g.title,sessionId:g.sessionId,messageCount:((h=g.messages)==null?void 0:h.length)||0}})),setTimeout(()=>ye.getState().cleanupStreamingMessages(),100)}catch(d){Be("Failed to load chat state:",d);const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,f=Yt(),p=Or(u,f,Fe());ye.setState({conversations:[p],currentConversationId:u,sessionId:f}),n=f}else{const d=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,u=Yt(),f=Or(d,u,Fe());ye.setState({conversations:[f],currentConversationId:d,sessionId:u}),n=u}localStorage.removeItem("chat-api-key");const i=ye.getState(),o=i.currentConversationId?i.conversations.find(d=>d.id===i.currentConversationId):null,l=s&&(o!=null&&o.apiUrl)?o.apiUrl:Fe();try{const d=await Me(),u=o==null?void 0:o.adapterName;if(!u)D("No adapter selected yet. Waiting for user selection before configuring API.");else if(d.configureApi(l,n,u),Fs=l,Ms=!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();D("Adapter info loaded for existing adapter:",p);const g=ye.getState();g.currentConversationId&&(ye.setState({conversations:g.conversations.map(h=>h.id===g.currentConversationId?{...h,adapterInfo:p,adapterLoadError:null,updatedAt:new Date}:h)}),setTimeout(()=>{const h=ye.getState();localStorage.setItem("chat-state",JSON.stringify({conversations:h.conversations,currentConversationId:h.currentConversationId}))},0))}}catch(f){be("Failed to load adapter info for existing adapter:",f)}}catch(d){Be("Failed to initialize API:",d)}try{await ye.getState().syncConversationsWithBackend()}catch(d){be("Conversation history sync skipped:",d)}};typeof window<"u"&&Fu();function $u(t){return t.includes("image")?a.jsx(ed,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):t.includes("video")||t.includes("audio")?a.jsx(Sd,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):a.jsx(On,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"})}function Pu(t){return t.replace(/-/g," ")}function ao({skills:t,isLoading:e,selectedSkill:r,activeSkillName:n,query:s="",onSelect:i,onActiveSkillChange:o}){const{t:l}=Le(),c=pt.useRef(null),d=s.toLowerCase().replace(/-/g," "),u=d?t.filter(f=>f.name.replace(/-/g," ").toLowerCase().includes(d)||f.description.toLowerCase().includes(d)):t;return pt.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:s}):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 g=(r==null?void 0:r.name)===f.name,h=n===f.name||!n&&(g||!r&&p===0);return a.jsxs("button",{id:`skill-option-${f.name}`,type:"button",role:"option","aria-selected":h,"data-active":h?"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 ${h?"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 ${h?"text-gray-900 dark:text-white":"text-gray-500 group-hover:text-gray-700 dark:text-[#bfc2cd] dark:group-hover:text-gray-200"}`,children:$u(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:Pu(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})]}),g&&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(ir,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]},f.name)})})})}function Ru(t){return t.replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function io({availableModels:t,defaultModel:e,selectedModel:r,onSelect:n,wrapperClassName:s="relative hidden md:block",maxWidthClass:i="max-w-[220px]",triggerTitle:o,listboxLabel:l,staticPaddingClass:c="px-2.5 py-1.5",triggerPaddingClass:d="px-2.5 py-1.5"}){const{t:u}=Le(),f=o??u("modelPicker.selectModel"),p=l??u("modelPicker.selectModel"),g=m.useId(),[h,x]=m.useState(!1),[y,k]=m.useState(""),[C,L]=m.useState(0),[N,v]=m.useState(null),T=m.useRef(null),_=m.useRef(null),b=m.useRef(null),$=m.useRef(null),j=r??e,I=m.useMemo(()=>{const S=y.trim().toLowerCase();return S?t.filter(W=>`${W.name} ${W.provider} ${W.model}`.toLowerCase().includes(S)):t},[t,y]),O=m.useCallback(S=>{n(S),x(!1),k(""),requestAnimationFrame(()=>{var W;return(W=_.current)==null?void 0:W.focus()})},[n]),R=m.useCallback(()=>{if(!_.current)return;const S=_.current.getBoundingClientRect();v({bottom:window.innerHeight-S.top+10,right:Math.max(12,window.innerWidth-S.right)})},[]),H=m.useCallback(()=>{x(!1),k("")},[]),A=()=>{if(h){H();return}R();const S=t.findIndex(W=>W.name===j);L(Math.max(S,0)),x(!0)};if(m.useEffect(()=>{if(!h)return;const S=setTimeout(()=>{var G;return(G=b.current)==null?void 0:G.focus()},10),W=G=>{var ee,Q;const te=G.target,Ce=((ee=T.current)==null?void 0:ee.contains(te))??!1,M=((Q=$.current)==null?void 0:Q.contains(te))??!1;!Ce&&!M&&H()},K=G=>{var te;if(G.key==="Escape"){G.preventDefault(),H(),(te=_.current)==null||te.focus();return}if(I.length!==0){if(G.key==="ArrowDown")G.preventDefault(),L(Ce=>(Ce+1)%I.length);else if(G.key==="ArrowUp")G.preventDefault(),L(Ce=>(Ce-1+I.length)%I.length);else if(G.key==="Home")G.preventDefault(),L(0);else if(G.key==="End")G.preventDefault(),L(I.length-1);else if(G.key==="Enter"){G.preventDefault();const Ce=I[C];Ce&&O(Ce.name)}}},q=new ResizeObserver(R);return _.current&&q.observe(_.current),window.addEventListener("resize",R,{passive:!0}),document.addEventListener("scroll",R,{capture:!0,passive:!0}),document.addEventListener("pointerdown",W),document.addEventListener("keydown",K),()=>{clearTimeout(S),q.disconnect(),window.removeEventListener("resize",R),document.removeEventListener("scroll",R,{capture:!0}),document.removeEventListener("pointerdown",W),document.removeEventListener("keydown",K)}},[C,H,I,h,R,O]),m.useEffect(()=>{var S,W;h&&((W=(S=$.current)==null?void 0:S.querySelector(`[data-model-index="${C}"]`))==null||W.scrollIntoView({block:"nearest"}))},[C,h]),!e&&t.length===0)return null;const E=h&&N&&typeof document<"u"?Rs.createPortal(a.jsxs("div",{ref:$,style:{position:"fixed",bottom:N.bottom,right:N.right,width:"min(352px, calc(100vw - 24px))",zIndex:9999},className:"overflow-hidden rounded-2xl border border-gray-200/90 bg-white shadow-[0_18px_50px_-12px_rgba(0,0,0,0.3)] ring-1 ring-black/[0.03] dark:border-white/10 dark:bg-[#171717] dark:ring-white/[0.04]",children:[a.jsxs("div",{className:"flex items-start justify-between gap-4 px-4 pb-3 pt-4",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-sm font-semibold leading-5 text-gray-950 dark:text-white",children:u("modelPicker.chooseModel")}),a.jsx("p",{className:"mt-0.5 text-xs leading-4 text-gray-500 dark:text-gray-400",children:u("modelPicker.chooseModelHint")})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[a.jsx("span",{className:"rounded-full bg-gray-100 px-2 py-0.5 text-[11px] font-medium tabular-nums text-gray-500 dark:bg-white/[0.07] dark:text-gray-400",children:I.length}),a.jsx("button",{type:"button",onClick:()=>{H(),requestAnimationFrame(()=>{var S;return(S=_.current)==null?void 0:S.focus()})},className:"flex h-7 w-7 items-center justify-center rounded-lg text-gray-400 transition-colors motion-reduce:transition-none hover:bg-gray-100 hover:text-gray-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 dark:text-gray-500 dark:hover:bg-white/[0.08] dark:hover:text-gray-200 dark:focus-visible:ring-white/20","aria-label":u("common.close"),title:u("common.close"),children:a.jsx(Ge,{className:"h-4 w-4","aria-hidden":"true"})})]})]}),a.jsx("div",{className:"px-3 pb-3",children:a.jsxs("label",{className:"flex h-9 items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-2.5 transition-colors focus-within:border-gray-400 focus-within:bg-white focus-within:ring-2 focus-within:ring-gray-200/70 dark:border-white/10 dark:bg-white/[0.05] dark:focus-within:border-white/25 dark:focus-within:bg-white/[0.07] dark:focus-within:ring-white/10",children:[a.jsx(Ls,{className:"h-4 w-4 shrink-0 text-gray-400","aria-hidden":"true"}),a.jsx("input",{ref:b,type:"text",value:y,onChange:S=>{k(S.target.value),L(0)},placeholder:u("modelPicker.searchPlaceholder"),className:"min-w-0 flex-1 appearance-none border-0 bg-transparent p-0 text-sm text-gray-900 shadow-none outline-none ring-0 placeholder:text-gray-400 focus:border-0 focus:outline-none focus:ring-0 dark:text-white dark:placeholder:text-gray-500",role:"combobox","aria-expanded":h,"aria-haspopup":"listbox","aria-label":u("modelPicker.searchAriaLabel"),"aria-controls":g,"aria-activedescendant":I[C]?`${g}-option-${C}`:void 0})]})}),a.jsx("div",{className:"mx-3 border-t border-gray-100 dark:border-white/[0.07]"}),a.jsx("div",{id:g,role:"listbox","aria-label":p,className:"max-h-72 overflow-y-auto p-2",children:I.length===0?a.jsxs("div",{className:"flex flex-col items-center px-4 py-8 text-center",children:[a.jsx(Ls,{className:"mb-2 h-5 w-5 text-gray-300 dark:text-gray-600","aria-hidden":"true"}),a.jsx("p",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:u("modelPicker.noModelsMatch",{query:y})}),a.jsx("p",{className:"mt-1 text-xs text-gray-400 dark:text-gray-500",children:u("modelPicker.tryAnotherSearch")})]}):I.map((S,W)=>{const K=j===S.name,q=C===W;return a.jsxs("button",{id:`${g}-option-${W}`,"data-model-index":W,role:"option","aria-selected":K,type:"button",onMouseMove:()=>L(W),onClick:()=>O(S.name),className:`group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition-colors ${q?"bg-gray-100 dark:bg-white/[0.08]":"hover:bg-gray-50 dark:hover:bg-white/[0.05]"}`,children:[a.jsxs("span",{className:"min-w-0 flex-1",children:[a.jsx("span",{className:"block truncate text-sm font-medium text-gray-900 dark:text-gray-100",children:S.name}),a.jsxs("span",{className:"mt-0.5 block truncate text-xs text-gray-500 dark:text-gray-400",children:[Ru(S.provider),S.model!==S.name?` · ${S.model}`:""]})]}),a.jsx("span",{className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full ${K?"bg-gray-900 text-white dark:bg-white dark:text-gray-900":"text-transparent"}`,children:a.jsx(ir,{className:"h-3 w-3",strokeWidth:3,"aria-hidden":"true"})})]},S.name)})}),I.length>0&&a.jsxs("div",{className:"flex items-center justify-between border-t border-gray-100 bg-gray-50/80 px-4 py-2 text-[11px] text-gray-400 dark:border-white/[0.07] dark:bg-white/[0.025] dark:text-gray-500",children:[a.jsx("span",{children:u("modelPicker.modelCountHint",{filtered:I.length,total:t.length})}),a.jsx("span",{className:"hidden sm:inline",children:u("modelPicker.keyboardHint")})]})]}),document.body):null,z=a.jsxs("span",{className:"min-w-0 flex-1 text-left leading-none",children:[a.jsx("span",{className:"mb-1 block text-[10px] font-semibold uppercase tracking-[0.12em] text-gray-400 dark:text-gray-500",children:u("modelPicker.modelLabel")}),a.jsx("span",{className:"block truncate text-xs font-semibold text-gray-800 dark:text-gray-200",children:j??u("modelPicker.selectModel")})]});return a.jsx("div",{ref:T,className:s,children:t.length>1?a.jsxs(a.Fragment,{children:[a.jsxs("button",{ref:_,type:"button",onClick:A,className:`group inline-flex min-w-[124px] ${i} items-center gap-2 rounded-xl border border-gray-200 bg-white/80 ${d} shadow-sm transition-all motion-reduce:transition-none hover:border-gray-300 hover:bg-white hover:shadow focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 dark:border-white/10 dark:bg-white/[0.05] dark:hover:border-white/20 dark:hover:bg-white/[0.08] dark:focus-visible:ring-white/20`,"aria-haspopup":"listbox","aria-expanded":h,"aria-controls":h?g:void 0,title:f,children:[z,a.jsx(wr,{className:`h-3.5 w-3.5 shrink-0 text-gray-400 transition-transform duration-200 motion-reduce:transition-none ${h?"rotate-180":""}`,"aria-hidden":"true"})]}),E]}):a.jsx("div",{className:`inline-flex min-w-[124px] ${i} items-center gap-2 rounded-xl border border-gray-200 bg-white/60 ${c} shadow-sm dark:border-white/10 dark:bg-white/[0.04]`,title:j??void 0,children:z})})}function $s({filename:t,fileId:e,status:r,statusText:n,errorMessage:s,onRemove:i,removeTitle:o,className:l=""}){const c=r==="uploading"||r==="processing",d=r==="error",u=vu(t),f=e?Su(e):void 0,p=u.Icon,g=d?s||n:n||u.label;return a.jsxs("div",{className:`group relative flex w-full min-w-[168px] max-w-[240px] items-center gap-2.5 rounded-xl border p-2 transition-colors ${d?"border-red-200 bg-red-50 dark:border-red-500/30 dark:bg-[#1a1010]":"border-gray-200 bg-gray-50 dark:border-[#242424] dark:bg-[#101010]"} ${l}`,children:[a.jsx("div",{className:`flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-lg text-white ${d?"bg-red-500":u.colorClass}`,children:f&&!d?a.jsx("img",{src:f,alt:"",className:"h-full w-full object-cover"}):c?a.jsx(Oi,{className:"h-[18px] w-[18px] animate-spin"}):d?a.jsx(jn,{className:"h-[18px] w-[18px]"}):a.jsx(p,{className:"h-[18px] w-[18px]"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`truncate text-sm font-medium leading-tight ${d?"text-red-700 dark:text-red-300":"text-[#353740] dark:text-[#ececf1]"}`,title:t,children:t}),g&&a.jsx("p",{className:`truncate text-xs leading-tight mt-0.5 ${d?"text-red-500 dark:text-red-400":"text-gray-400 dark:text-[#8e8ea0]"}`,children:g})]}),i&&a.jsx("button",{type:"button",onClick:i,title:o,"aria-label":o,className:"absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full border border-gray-200 bg-white text-gray-500 shadow-sm transition-colors hover:text-red-600 dark:border-[#3c3f4a] dark:bg-[#2d2f39] dark:text-[#bfc2cd] dark:hover:text-red-400",children:a.jsx(Ge,{className:"h-3 w-3"})})]})}const cn=2e3;function oo({initialValue:t="",onSubmit:e,onCancel:r,isSubmitting:n=!1}){const{t:s}=Le(),[i,o]=m.useState(t??""),l=m.useRef(null);m.useEffect(()=>{const d=l.current;d&&(d.focus(),d.setSelectionRange(d.value.length,d.value.length))},[]),m.useEffect(()=>{const d=l.current;d&&(d.style.height="auto",d.style.height=`${Math.min(d.scrollHeight,120)}px`)},[i]);const c=()=>{n||e(i.trim())};return a.jsxs("div",{className:"mt-2 rounded-xl border border-gray-200 bg-gray-50 px-3 py-2 dark:border-[#242424] dark:bg-[#101010]",children:[a.jsx("div",{className:"mb-1 text-[11px] font-medium text-gray-500 dark:text-[#8e8ea0]",children:s("message.feedback.commentPrompt")}),a.jsx("textarea",{ref:l,className:"block w-full resize-none overflow-hidden bg-transparent text-sm leading-6 text-[#353740] placeholder-slate-500 outline-none disabled:opacity-60 dark:text-[#ececf1] dark:placeholder-[#70707c]",placeholder:s("message.feedback.commentPlaceholder"),"aria-label":s("message.feedback.commentPlaceholder"),value:i,onChange:d=>o(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),c()),d.key==="Escape"&&(d.preventDefault(),r())},disabled:n,rows:1,maxLength:cn,style:{minHeight:"24px",maxHeight:"120px"}}),a.jsxs("div",{className:"mt-1.5 flex items-center justify-end gap-2",children:[i.length>0&&a.jsx("span",{className:"mr-auto text-[11px] text-gray-500 dark:text-[#bfc2cd]",children:a.jsxs("span",{className:i.length>=cn?"text-red-600 font-semibold":"",children:[i.length,"/",cn]})}),a.jsx("button",{type:"button",onClick:r,disabled:n,className:"rounded-full bg-gray-200 px-3 py-1 text-xs font-medium text-gray-700 transition-colors hover:bg-gray-300 disabled:opacity-60 dark:bg-[#4a4b54] dark:text-gray-200 dark:hover:bg-[#565869]",children:s("message.feedback.commentCancel")}),a.jsxs("button",{type:"button",onClick:c,disabled:n,className:"flex items-center gap-1.5 rounded-full bg-blue-600 px-3 py-1 text-xs font-medium text-white transition-colors hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-60 dark:bg-blue-500 dark:hover:bg-blue-400",children:[a.jsx(Ns,{className:"h-3.5 w-3.5"}),s("message.feedback.commentSend")]})]})]})}const Du=[],Uu=(t="png")=>{const e=t.toLowerCase().replace(/^image\//,"");return e==="jpg"?"image/jpeg":`image/${e||"png"}`},Ou=(t,e)=>{const r=atob(t),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.charCodeAt(s);return new Blob([n],{type:e})},zu=async t=>{const e=URL.createObjectURL(t);try{const r=new Image;r.decoding="async";const n=new Promise((o,l)=>{r.onload=()=>o(r),r.onerror=()=>l(new Error("Failed to load generated image for clipboard copy"))});r.src=e,await n;const s=document.createElement("canvas");s.width=r.naturalWidth,s.height=r.naturalHeight;const i=s.getContext("2d");if(!i)throw new Error("Could not create canvas context for image clipboard copy");return i.drawImage(r,0,0),await new Promise((o,l)=>{s.toBlob(c=>{c?o(c):l(new Error("Could not encode generated image for clipboard copy"))},"image/png")})}finally{URL.revokeObjectURL(e)}},Bu=async(t,e)=>{const r=Uu(t.imageFormat);if(t.image)return Ou(t.image,r);if(!t.imageUrl)return null;const n=await fetch(t.imageUrl,{headers:e?{"X-Adapter-Name":e}:{}});if(!n.ok)throw new Error(`Could not fetch generated image for clipboard copy: ${n.status}`);const s=await n.blob();return s.type?s:new Blob([s],{type:r})},Hu=t=>t.imageUrl?new URL(t.imageUrl,window.location.origin).toString():t.imageRevisedPrompt||t.content;function ei({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(r=>a.jsx("span",{className:`inline-block ${e} animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]`,style:{animationDelay:`${r}ms`}},r))})}function Vu({reply:t}){const{t:e}=Le(),[r,n]=m.useState(!1),[s,i]=m.useState(!1),[o,l]=m.useState(!1),[c,d]=m.useState(!1),u=m.useRef(null),f=ye(x=>x.submitFeedback);m.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const p=()=>{i(!0),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{i(!1),u.current=null},2e3)},g=async x=>{if(!t.databaseMessageId||r)return;const y=t.feedback!==x,k=x==="down"&&y;n(!0);try{if(!await f(t.id,x))return;k?(i(!1),l(!0)):(l(!1),y?p():i(!1))}catch(C){pe("Failed to submit thread reply feedback:",C)}finally{n(!1)}},h=async x=>{if(t.databaseMessageId){d(!0);try{if(!await f(t.id,"down",x))return;l(!1),p()}catch(y){pe("Failed to submit thread reply feedback comment:",y)}finally{d(!1)}}};return a.jsxs("div",{className:"mt-0.5",children:[a.jsxs("div",{className:"flex items-center gap-0.5 text-gray-400 dark:text-[#8e8ea0]",children:[a.jsx("button",{onClick:()=>g("up"),disabled:r,className:`rounded-md p-1.5 transition-colors ${r?"opacity-50 cursor-not-allowed":""} ${t.feedback==="up"?"text-green-600 dark:text-green-400":"hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]"}`,title:e("message.feedback.good"),"aria-label":e("message.feedback.good"),children:a.jsx(qi,{className:"h-4 w-4"})}),a.jsx("button",{onClick:()=>g("down"),disabled:r,className:`rounded-md p-1.5 transition-colors ${r?"opacity-50 cursor-not-allowed":""} ${t.feedback==="down"?"text-red-600 dark:text-red-400":"hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]"}`,title:e("message.feedback.poor"),"aria-label":e("message.feedback.poor"),children:a.jsx(Vi,{className:"h-4 w-4"})}),t.feedback==="down"&&!o&&a.jsx("button",{type:"button",onClick:()=>l(!0),className:"inline-flex items-center rounded-md px-2 py-1 text-xs font-medium transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",children:t.feedbackComment?e("message.feedback.commentEdit"):e("message.feedback.commentPrompt")}),s&&a.jsxs("span",{className:"ml-1 inline-flex items-center gap-1.5 whitespace-nowrap rounded-lg bg-emerald-500 px-2.5 py-1 text-[11px] font-bold uppercase tracking-wider text-white shadow-sm animate-fadeIn dark:bg-emerald-600",children:[a.jsx(ir,{className:"h-3.5 w-3.5"}),e("message.feedback.thanks")]})]}),t.feedback==="down"&&o&&a.jsx(oo,{initialValue:t.feedbackComment,onSubmit:h,onCancel:()=>l(!1),isSubmitting:c})]})}function qu({message:t,onRegenerate:e,onEdit:r,onStartThread:n,onClearThread:s,onSendThreadMessage:i,threadMessages:o,sessionId:l,isThreadSendDisabled:c,availableModels:d=[],defaultModel:u=null,selectedModel:f=null}){var Ht,fr,Je;const{t:p}=Le(),[g,h]=m.useState(!1),[x,y]=m.useState(t.content||""),[k,C]=m.useState(!1),L=m.useRef(null),[N,v]=m.useState(!1),[T,_]=m.useState(!1),[b,$]=m.useState(!1),[j,I]=m.useState(!1),[O,R]=m.useState(!1),[H,A]=m.useState(""),[E,z]=m.useState(!1),[S,W]=m.useState(!1),[K,q]=m.useState(!1),[G,te]=m.useState(0),[Ce,M]=m.useState(!1),[ee,Q]=m.useState(!1),[J,le]=m.useState(()=>f??u),ge=m.useRef(f),V=m.useRef(((Ht=t.threadInfo)==null?void 0:Ht.thread_id)||null),Y=m.useRef(null),ie=m.useRef(null),xe=m.useRef(null),fe=m.useRef(!1),ae=m.useRef(0),re=m.useRef(""),Pe=m.useRef(!1),Ee=m.useRef(!0),_e=m.useRef(!1),Oe=m.useRef(null),U=m.useRef(null),B=t.role==="assistant",de=o??Du,Ie=de.filter(F=>!(F.role==="assistant"&&F.isStreaming)).length,we=de.some(F=>F.isStreaming),Ye=kr(),Lt=tt()&&!Ye,Ae=ye(F=>F.conversations.find(ce=>ce.id===F.currentConversationId)),ot=!!((t.image||t.imageUrl)&&B&&!t.isStreaming),vr=!!((t.video||t.videoUrl)&&B&&!t.isStreaming),gt=p(ot?"message.copyImageLabel":"message.copyLabel"),vt=gc(),cr=oe.maxMessageLength,We=oe.maxMessagesPerThread,St=We!==null&&Ie>=We,Ut=St?Lt?p("message.thread.limitReachedGuest",{count:We}):p("message.thread.limitReachedUser",{count:We}):null,{theme:Se,isDark:xt}=lr(),me=p("message.thread.placeholder"),ve=`thread-input-${t.id}`,{skills:Te,isLoading:De,selectedSkill:se,selectSkill:bt,clearSkill:dr}=Ji({adapterName:Ae==null?void 0:Ae.adapterName,enabled:vt&&!!t.threadInfo,selectionScopeKey:((fr=t.threadInfo)==null?void 0:fr.thread_id)||t.id}),Et=H.startsWith("/")?H.slice(1):"",Qt=Et.toLowerCase().replace(/-/g," "),lt=Qt?Te.filter(F=>F.name.replace(/-/g," ").toLowerCase().includes(Qt)||F.description.toLowerCase().includes(Qt)):Te,qs=lt.length>0?Math.min(G,lt.length-1):0,yt=lt[qs]??null,st=(yt==null?void 0:yt.name.replace(/-/g," "))??"",Kr=K&&yt&&H.startsWith("/")&&st.toLowerCase().startsWith(Et.toLowerCase())&&st.length>Et.length?st.slice(Et.length):null,ur=Se.mode==="dark"?"dark":Se.mode==="light"?"light":"",Zt=xt?"dark":"light",Jt=m.useMemo(()=>["message-markdown w-full min-w-0","prose prose-slate dark:prose-invert max-w-none",ur].filter(Boolean).join(" "),[ur]),Sr=m.useMemo(()=>["message-markdown w-full min-w-0","prose dark:prose-invert max-w-none",ur].filter(Boolean).join(" "),[ur]),_t=B?Jt:Sr,er=`${Jt} text-sm leading-6`,Tt=`${Sr} text-sm leading-6`;m.useEffect(()=>{var F,ce;!V.current&&((F=t.threadInfo)!=null&&F.thread_id)&&z(!0),V.current=((ce=t.threadInfo)==null?void 0:ce.thread_id)||null},[(Je=t.threadInfo)==null?void 0:Je.thread_id]),m.useEffect(()=>{t.threadInfo||setTimeout(()=>{A(""),z(!1),W(!1),q(!1),dr()},0)},[t.threadInfo,dr]),m.useEffect(()=>{Ie>0&&setTimeout(()=>{z(!0)},0)},[Ie]),m.useEffect(()=>()=>{Oe.current&&clearTimeout(Oe.current),U.current&&clearTimeout(U.current)},[]),m.useEffect(()=>{if(!g||!L.current)return;const F=L.current;F.focus(),F.setSelectionRange(F.value.length,F.value.length)},[g]),m.useEffect(()=>{if(!g||!L.current)return;const F=L.current;F.style.height="auto",F.style.height=`${F.scrollHeight}px`},[g,x]);const Gr=m.useCallback(()=>{const F=x.trim();if(!F||F===t.content){h(!1);return}r==null||r(t.id,F),h(!1)},[x,t.content,t.id,r]),Mt=m.useCallback(()=>{requestAnimationFrame(()=>{xe.current&&(xe.current.scrollTop=xe.current.scrollHeight)})},[]);m.useEffect(()=>{if(!E)return;const F=de.length,ce=F>ae.current,X=de[de.length-1],Ne=(X==null?void 0:X.content)||"",dt=Ne!==re.current,wt=(X==null?void 0:X.isStreaming)??!1,mr=Pe.current&&!wt;ce||wt&&dt||mr?(Mt(),Ee.current=!0):Ee.current&&dt&&Mt(),ae.current=F,re.current=Ne,Pe.current=wt},[E,de,Mt]),m.useEffect(()=>{E&&(Mt(),Ee.current=!0)},[E,Mt]);const Ot=B?"message-bubble message-bubble-assistant min-w-0 break-words leading-relaxed text-[#353740] dark:text-[#ececf1]":"message-bubble message-bubble-user inline-block min-w-0 break-words leading-relaxed rounded-[1.75rem] border border-black/[0.06] bg-[#f4f4f4] px-4 py-3 text-[#111827] shadow-[0_1px_2px_rgba(16,24,40,0.06)] dark:border-white/[0.08] dark:bg-[#2a2a2a] dark:text-[#f5f5f5] dark:shadow-[0_1px_3px_rgba(0,0,0,0.3)]",jr=m.useCallback(()=>{v(!0),Oe.current&&clearTimeout(Oe.current),Oe.current=setTimeout(()=>{v(!1),Oe.current=null},2e3)},[]),He=async()=>{try{if(ot){if("ClipboardItem"in window&&navigator.clipboard.write)try{const ce=(Ae==null?void 0:Ae.adapterName)||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),X=await Bu(t,ce);if(X){const Ne=X.type==="image/png"?X:await zu(X);await navigator.clipboard.write([new ClipboardItem({[Ne.type||"image/png"]:Ne})]),jr();return}}catch(ce){pe("Failed to copy generated image, falling back to text:",ce)}const F=Hu(t);if(F){await navigator.clipboard.writeText(F),jr();return}return}await navigator.clipboard.writeText(t.content),jr()}catch(F){pe(ot?"Failed to copy generated image:":"Failed to copy text:",F)}},Cr=ye(F=>F.submitFeedback),tr=()=>{$(!0),U.current&&clearTimeout(U.current),U.current=setTimeout(()=>{$(!1),U.current=null},2e3)},Xr=async F=>{if(!t.databaseMessageId||T)return;const ce=t.feedback!==F,X=F==="down"&&ce;_(!0);try{if(!await Cr(t.id,F))return;X?($(!1),I(!0)):(I(!1),ce?tr():$(!1))}catch(Ne){pe("Failed to submit feedback:",Ne)}finally{_(!1)}},zt=async F=>{if(t.databaseMessageId){R(!0);try{if(!await Cr(t.id,"down",F))return;I(!1),tr()}catch(ce){pe("Failed to submit feedback comment:",ce)}finally{R(!1)}}},ct=async()=>{if(!i||!t.threadInfo||St)return;const F=H.trim();if(!F)return;const ce=H,X=se,Ne=se==null?void 0:se.name;A(""),W(!0),q(!1),Ne&&dr();try{await i(t.threadInfo.thread_id,t.id,F,Ne,J??u??void 0),setTimeout(()=>{Y.current&&Y.current.focus()},100)}catch(dt){pe("Failed to send thread message:",dt),A(ce),X&&bt(X),setTimeout(()=>{Y.current&&Y.current.focus()},100)}finally{W(!1)}},Yr=m.useCallback(F=>{var ce;bt(F),q(!1),A(""),te(0),(ce=Y.current)==null||ce.focus()},[bt]),Qr=m.useCallback(()=>{var F;q(!1),A(""),te(0),(F=Y.current)==null||F.focus()},[]),Ws=m.useCallback(()=>{var F;A("/"),q(!0),te(0),(F=Y.current)==null||F.focus()},[]),jt=F=>{if(K){if(F.key==="ArrowDown"){F.preventDefault(),te(ce=>lt.length===0?0:(ce+1)%lt.length);return}if(F.key==="ArrowUp"){F.preventDefault(),te(ce=>lt.length===0?0:(ce-1+lt.length)%lt.length);return}if(F.key==="Home"){F.preventDefault(),te(0);return}if(F.key==="End"){F.preventDefault(),te(Math.max(lt.length-1,0));return}if((F.key==="Enter"&&!F.shiftKey||F.key==="Tab")&&yt){F.preventDefault(),Yr(yt);return}if(F.key==="Escape"){F.preventDefault(),Qr();return}}F.key==="Enter"&&!F.shiftKey&&(F.preventDefault(),ct())},Bt=!t.threadInfo||!i||c||we||S||St,Zr=!!t.threadInfo&&!!s&&Ie>0&&!we&&!S&&!c,Ar=async()=>{if(!(!t.threadInfo||!s)){Q(!0);try{await s(t.id,t.threadInfo.thread_id),M(!1),z(!1),A("")}catch(F){pe("Failed to clear thread:",F)}finally{Q(!1)}}};m.useEffect(()=>{ge.current=f},[f]),m.useEffect(()=>{le(ge.current??u)},[u]),m.useEffect(()=>{if(!E||Bt){_e.current=S;return}const F=Y.current;if(!F){_e.current=S;return}if(!(fe.current||_e.current)){_e.current=S;return}const X=requestAnimationFrame(()=>{var dt;fe.current&&((dt=ie.current)==null||dt.scrollIntoView({behavior:"auto",block:"nearest",inline:"nearest"})),F.focus();const Ne=F.value.length;F.setSelectionRange(Ne,Ne),fe.current=!1,_e.current=S});return()=>{cancelAnimationFrame(X),_e.current=S}},[E,Bt,S]),m.useEffect(()=>{if(Y.current){const ce=Y.current;ce.style.height="auto";const X=ce.scrollHeight;ce.style.height=`${Math.min(X,120)}px`,ce.style.overflowY=X>120?"auto":"hidden"}},[H]);const Jr=m.useMemo(()=>{if(t.isStreaming&&(!t.content||t.content==="…"))return a.jsx("div",{className:_t,children:a.jsx(ei,{})});const F=t.isStreaming&&B?" streaming-cursor":"";return a.jsx("div",{className:F||void 0,children:a.jsx(Dt,{content:In(Vr(t.content||"")),className:_t,syntaxTheme:Zt})})},[_t,t.content,t.isStreaming,B,Zt]),Nr=m.useMemo(()=>{const F=X=>X instanceof Date?X.getTime():new Date(X).getTime();return[...de].sort((X,Ne)=>F(X.timestamp)-F(Ne.timestamp)).map(X=>{const Ne=X.role==="assistant",dt=Ne?er:Tt,wt=X.isStreaming&&Ne?" streaming-cursor":"",mr=X.isStreaming&&(!X.content||X.content==="…")?a.jsx("div",{className:dt,children:a.jsx(ei,{size:"sm"})}):a.jsx("div",{className:wt||void 0,children:a.jsx(Dt,{content:In(Vr(X.content||"")),className:dt,syntaxTheme:Zt})});return a.jsx("div",{className:`min-w-0 flex ${Ne?"justify-start":"justify-end"}`,children:a.jsxs("div",{className:Ne?"min-w-0 w-full max-w-full":"min-w-0 max-w-[85%]",children:[a.jsxs("div",{className:Ne?"thread-markdown-wrapper overflow-x-visible text-sm text-[#353740] dark:text-[#ececf1]":"thread-markdown-wrapper overflow-x-visible text-sm rounded-[1.75rem] bg-[#f4f4f4] px-4 py-3 text-[#111827] dark:bg-[#2a2a2a] dark:text-[#f5f5f5]",children:[mr,X.audio&&Ne&&!X.isStreaming&&a.jsx(ms,{audio:X.audio,audioFormat:X.audioFormat,autoPlay:!1}),(X.image||X.imageUrl)&&Ne&&!X.isStreaming&&a.jsx(za,{image:X.image,imageUrl:X.imageUrl,imageFormat:X.imageFormat,revisedPrompt:X.imageRevisedPrompt}),(X.video||X.videoUrl)&&Ne&&!X.isStreaming&&a.jsx(Ba,{video:X.video,videoUrl:X.videoUrl,videoFormat:X.videoFormat,revisedPrompt:X.videoRevisedPrompt,adapterName:Ae==null?void 0:Ae.adapterName}),(X.document||X.documentUrl)&&Ne&&!X.isStreaming&&a.jsx(Wa,{document:X.document,documentUrl:X.documentUrl,documentFormat:X.documentFormat,revisedPrompt:X.documentRevisedPrompt,adapterName:Ae==null?void 0:Ae.adapterName}),X.generatedAudioUrl&&Ne&&!X.isStreaming&&a.jsx(ms,{audioUrl:X.generatedAudioUrl,audioFormat:X.generatedAudioFormat,downloadFilename:`generated-audio.${X.generatedAudioFormat||"mp3"}`,autoPlay:!1})]}),Ne&&!X.isStreaming&&X.model&&a.jsx("div",{className:"px-1 pt-0.5 text-[11px] text-gray-400 dark:text-[#9a9ab0]",children:p("message.generatedBy",{model:X.model})}),Ne&&!X.isStreaming&&us()&&a.jsx(Vu,{reply:X})]})},X.id)})},[Ae==null?void 0:Ae.adapterName,Zt,p,er,de,Tt]);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:B?void 0:"flex flex-col items-end",children:[a.jsxs("div",{className:Ot,children:[g?a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx("textarea",{ref:L,className:"w-full resize-none overflow-hidden bg-transparent outline-none text-[#111827] dark:text-[#f5f5f5] leading-relaxed",value:x,onChange:F=>y(F.target.value),onCompositionStart:()=>C(!0),onCompositionEnd:()=>C(!1),onKeyDown:F=>{F.key==="Enter"&&!F.shiftKey&&!k&&(F.preventDefault(),F.stopPropagation(),Gr()),F.key==="Escape"&&(F.stopPropagation(),h(!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:()=>{h(!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:Gr,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(Ns,{className:"w-3.5 h-3.5"}),p("common.send")]})]})]})]}):Jr,t.attachments&&t.attachments.length>0&&a.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:t.attachments.map(F=>a.jsx($s,{filename:F.filename,fileId:F.file_id,status:"completed",statusText:`${(F.file_size/1024).toFixed(1)} KB`},F.file_id))}),t.audio&&B&&!t.isStreaming&&a.jsx(ms,{audio:t.audio,audioFormat:t.audioFormat,autoPlay:!1}),(t.image||t.imageUrl)&&B&&!t.isStreaming&&a.jsx(za,{image:t.image,imageUrl:t.imageUrl,imageFormat:t.imageFormat,revisedPrompt:t.imageRevisedPrompt}),(t.video||t.videoUrl)&&B&&!t.isStreaming&&a.jsx(Ba,{video:t.video,videoUrl:t.videoUrl,videoFormat:t.videoFormat,revisedPrompt:t.videoRevisedPrompt,adapterName:Ae==null?void 0:Ae.adapterName}),(t.document||t.documentUrl)&&B&&!t.isStreaming&&a.jsx(Wa,{document:t.document,documentUrl:t.documentUrl,documentFormat:t.documentFormat,revisedPrompt:t.documentRevisedPrompt,adapterName:Ae==null?void 0:Ae.adapterName}),t.generatedAudioUrl&&B&&!t.isStreaming&&a.jsx(ms,{audioUrl:t.generatedAudioUrl,audioFormat:t.generatedAudioFormat,downloadFilename:`generated-audio.${t.generatedAudioFormat||"mp3"}`,autoPlay:!1})]}),!B&&!g&&a.jsxs("div",{className:"flex items-center gap-0.5 py-1 text-gray-400 dark:text-[#8e8ea0]",children:[a.jsx("button",{onClick:He,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:gt,"aria-label":gt,children:N?a.jsx(ir,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):a.jsx(_a,{className:"h-4 w-4"})}),r&&a.jsx("button",{onClick:()=>{y(t.content||""),h(!0)},className:"rounded-md p-1.5 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",title:p("message.editAriaLabel"),"aria-label":p("message.editAriaLabel"),children:a.jsx(Bi,{className:"h-4 w-4"})})]})]}),B&&!t.isStreaming&&t.model&&a.jsx("div",{className:"px-1 pt-0.5 text-[11px] text-gray-400 dark:text-[#9a9ab0]",children:p("message.generatedBy",{model:t.model})}),B&&!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:[!vr&&a.jsx("button",{onClick:He,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:gt,"aria-label":gt,children:N?a.jsx(ir,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):a.jsx(_a,{className:"h-4 w-4"})}),us()&&a.jsxs("div",{className:"relative flex items-center gap-0.5",children:[a.jsx("button",{onClick:()=>Xr("up"),disabled:T,className:`rounded-md p-1.5 transition-colors ${T?"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(qi,{className:"h-4 w-4"})}),a.jsx("button",{onClick:()=>Xr("down"),disabled:T,className:`rounded-md p-1.5 transition-colors ${T?"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(Vi,{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(ir,{className:"h-3.5 w-3.5"}),a.jsx("span",{children:p("message.feedback.thanks")})]})]})]}),us()&&t.feedback==="down"&&!j&&a.jsx("button",{type:"button",onClick:()=>I(!0),className:"inline-flex items-center rounded-md px-2 py-1 text-xs font-medium transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",children:t.feedbackComment?p("message.feedback.commentEdit"):p("message.feedback.commentPrompt")}),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(xd,{className:"h-4 w-4"})}),vt&&t.supportsThreading&&!t.threadInfo&&n&&l&&a.jsxs("button",{type:"button",onClick:()=>{fe.current=!0,z(!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(Ta,{className:"h-3.5 w-3.5 shrink-0"}),a.jsx("span",{children:p("message.thread.continueLabel")})]}),vt&&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:()=>z(F=>!F),className:"inline-flex min-w-0 items-center gap-1.5 rounded-md px-2 py-1.5 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1] transition-colors text-xs",children:[a.jsx(Ta,{className:"h-4 w-4"}),a.jsx("span",{className:"truncate",children:p("message.thread.replyCount",{count:Ie})}),E?a.jsx(Is,{className:"h-3 w-3"}):a.jsx(wr,{className:"h-3 w-3"})]}),Zr&&a.jsx("button",{type:"button",onClick:()=>M(!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")})]})]}),B&&!t.isStreaming&&us()&&t.feedback==="down"&&j&&a.jsx(oo,{initialValue:t.feedbackComment,onSubmit:zt,onCancel:()=>I(!1),isSubmitting:O}),vt&&t.threadInfo&&E&&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:xe,className:"thread-replies-scroll mt-2 space-y-2 pb-3",onScroll:()=>{if(!xe.current)return;const{scrollTop:F,scrollHeight:ce,clientHeight:X}=xe.current;Ee.current=ce-F-X<100},children:Ie>0?Nr:null}),Ut&&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:[Ut,Lt&&a.jsx("div",{className:"mt-2",children:a.jsx("button",{type:"button",onClick:()=>rt.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:ie,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:[se&&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(On,{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:se.name.replace(/-/g," ")}),a.jsx("button",{type:"button",onClick:()=>dr(),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(Ge,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),!se&&Te.length>0&&H.length===0&&!Bt&&a.jsxs("button",{type:"button",onClick:Ws,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:ve,className:"sr-only",children:p("message.thread.placeholder")}),Kr&&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:H}),a.jsx("span",{children:Kr})]}),a.jsx("textarea",{id:ve,ref:Y,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:me,"aria-label":p("message.thread.placeholder"),value:H,onChange:F=>{const ce=F.target.value;A(ce),ce.startsWith("/")&&te(0),q(ce.startsWith("/"))},onKeyDown:jt,disabled:Bt,rows:1,maxLength:cr,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(io,{availableModels:d,defaultModel:u,selectedModel:J,onSelect:le,maxWidthClass:"max-w-[120px]",triggerPaddingClass:"px-2 py-1",staticPaddingClass:"px-2 py-1",triggerTitle:p("message.thread.selectModelTitle"),listboxLabel:p("message.thread.selectModelTitle")}),H.trim().length>0&&a.jsx("button",{type:"button",onClick:ct,disabled:Bt||H.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(Ns,{className:"h-5 w-5 sm:h-4 sm:w-4"})})]})]}),K&&a.jsx("div",{className:"w-full pt-1",children:a.jsx(ao,{skills:Te,isLoading:De,selectedSkill:se,activeSkillName:yt==null?void 0:yt.name,query:Et,onActiveSkillChange:F=>{const ce=lt.findIndex(X=>X.name===F.name);ce>=0&&te(ce)},onSelect:Yr,onClose:Qr})})]}),Ie>0&&a.jsx("div",{className:"mt-2 flex justify-end",children:a.jsxs("button",{type:"button",onClick:()=>z(!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(Is,{className:"h-3 w-3"}),a.jsx("span",{children:p("message.thread.hideRepliesLabel")})]})})]})]}),a.jsx(_s,{isOpen:Ce,onClose:()=>{ee||M(!1)},onConfirm:Ar,title:p("message.confirmation.clearRepliesTitle"),message:p("message.confirmation.clearRepliesMessage"),confirmText:p("common.clear"),cancelText:p("common.cancel"),type:"danger",isLoading:ee})]})}let pr=null;function Wu(){if(typeof window>"u")return null;const t=window.AudioContext??window.webkitAudioContext;return t?((!pr||pr.state==="closed")&&(pr=new t),pr.state==="suspended"&&pr.resume(),pr):(D("[SoundEffects] AudioContext not supported in this browser"),null)}function Ku(t){const e=Wu();if(!e)return;const r=e.currentTime;for(const n of t){const s=e.createOscillator(),i=e.createGain();s.connect(i),i.connect(e.destination),s.frequency.value=n.frequency,s.type=n.type;const o=r+n.startTime,l=o+n.duration;i.gain.setValueAtTime(.001,o),i.gain.linearRampToValueAtTime(n.gain,o+.008),i.gain.exponentialRampToValueAtTime(.001,l),s.start(o),s.stop(l+.01)}}const Gu={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 Pr(t,e){if(!e)return;const r=Gu[t];if(!r){D(`[SoundEffects] Unknown sound effect type: ${t}`);return}try{Ku(r),D(`[SoundEffects] Playing ${t} sound effect`)}catch(n){D(`[SoundEffects] Failed to play ${t} sound effect:`,n)}}function Xu({messages:t,onRegenerate:e,onEditMessage:r,onStartThread:n,onClearThread:s,onSendThreadMessage:i,sessionId:o,isLoading:l,contentMaxWidthClass:c="max-w-[64rem]",availableModels:d,defaultModel:u,selectedModel:f}){const p=m.useRef(null),g=m.useRef(null),h=m.useRef(t.length),x=m.useRef(""),y=m.useRef(l),k=m.useRef(!0),{settings:C}=Ds(),{t:L}=Le(),{topLevelMessages:N,threadLookup:v}=m.useMemo(()=>{const b=new Map,$=[];return t.forEach(j=>{if(j.isThreadMessage&&j.parentMessageId){const I=b.get(j.parentMessageId)||[];b.set(j.parentMessageId,[...I,j]);return}$.push(j)}),{topLevelMessages:$,threadLookup:b}},[t]),T=()=>{if(!g.current)return;const{scrollTop:b,scrollHeight:$,clientHeight:j}=g.current,O=$-b-j<200;k.current=O},_=m.useCallback(()=>{requestAnimationFrame(()=>{g.current&&(g.current.scrollTop=g.current.scrollHeight)})},[]);return m.useEffect(()=>{const b=t.length,$=h.current,j=b>$,I=t[t.length-1],O=(I==null?void 0:I.content)||"",R=O!==x.current,H=(I==null?void 0:I.isStreaming)??!1;j||H&&R?(_(),k.current=!0):k.current&&R&&_(),h.current=b,x.current=O},[t,_]),m.useEffect(()=>{l&&(_(),k.current=!0)},[l,_]),m.useEffect(()=>{if(y.current&&!l){const b=t[t.length-1];(b==null?void 0:b.role)==="assistant"&&b.content&&Pr("messageReceived",C.soundEnabled)}y.current=l},[l,t,C.soundEnabled]),N.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:L("messageList.emptyStateHeading")}),a.jsx("p",{className:"mt-1 text-lg",children:L("messageList.emptyStateSubheading")})]})}):a.jsx("div",{ref:g,className:"message-list flex-1 overflow-y-auto pb-8 pt-4 sm:pt-6",onScroll:T,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:[N.map(b=>a.jsx("div",{className:`flex w-full ${b.role==="user"?"justify-end":"justify-start"}`,style:{contentVisibility:"auto",containIntrinsicSize:"420px"},children:a.jsx(qu,{message:b,onRegenerate:e,onEdit:r,onStartThread:n,onClearThread:s,onSendThreadMessage:i,threadMessages:v.get(b.id),sessionId:o,isThreadSendDisabled:l,availableModels:d,defaultModel:u,selectedModel:f})},b.id)),a.jsx("div",{ref:p,className:"h-8"})]})})})}const Yu=4e3;function Qu(t,e,r={}){var $;const{t:n}=Le(),[s,i]=m.useState(!1),[o,l]=m.useState(null),c=m.useRef(null),d=m.useRef(""),u=m.useRef(""),f=m.useRef(!1),p=m.useRef(null),g=typeof navigator<"u"?navigator.language:"en-US",h=Number.isFinite(r.silenceTimeoutMs)?Math.max(Math.floor(r.silenceTimeoutMs),1e3):Yu,x=(($=r.language)==null?void 0:$.trim())||g||"en-US",y=m.useCallback(j=>j.replace(/\s+/g," ").trim(),[]),k=m.useCallback(j=>{const I=y(j);I&&I!==u.current&&(u.current=I,t(I))},[y,t]),C=m.useCallback(()=>{if(!d.current)return;const j=d.current;d.current="",k(j)},[k]),L=typeof window<"u"&&("webkitSpeechRecognition"in window||"SpeechRecognition"in window),N=m.useCallback(()=>{!e||f.current||(f.current=!0,e())},[e]),v=m.useCallback(()=>{p.current!==null&&(clearTimeout(p.current),p.current=null)},[]),T=m.useCallback(()=>{v(),p.current=setTimeout(()=>{D("Speech recognition silence threshold reached, stopping recording"),c.current?c.current.stop():N()},h)},[v,N,h]),_=m.useCallback(()=>{if(!L){l(n("voice.browserNotSupported"));return}if(!c.current)try{f.current=!1;const j=window.SpeechRecognition||window.webkitSpeechRecognition,I=new j;I.continuous=!0,I.interimResults=!0,I.lang=x,I.maxAlternatives=1,I.onstart=()=>{i(!0),l(null),d.current="",u.current="",D("Speech recognition started"),T()},I.onresult=O=>{let R="",H="";for(let A=O.resultIndex;A<O.results.length;A++){const E=O.results[A][0].transcript;O.results[A].isFinal?R+=E:H+=E}H&&(d.current=y(H)),R&&(d.current="",k(R)),T()},I.onend=()=>{v(),C(),i(!1),c.current=null,D("Speech recognition ended"),N()},I.onerror=O=>{switch(v(),pe("Speech recognition error:",O.error),i(!1),c.current=null,d.current="",N(),O.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:O.error}))}},I.start(),c.current=I}catch(j){pe("Failed to start speech recognition:",j),l(n("voice.error.startFailed")),i(!1)}},[L,C,N,T,v,x,y,k,n]),b=m.useCallback(()=>{if(D("Stopping speech recognition..."),c.current){const j=c.current;j.onstart=null,j.onerror=null;try{j.stop()}catch(I){D("Recognition already stopped or error stopping:",I),v(),C(),j.onend=null,j.onresult=null,c.current=null,i(!1),N()}}v(),i(!1),l(null),D("Speech recognition stopped, isListening set to false")},[v,C,N]);return{isListening:s,isSupported:L,startListening:_,stopListening:b,error:o}}const Zu=300,ti=3,bs=5,Ju=6e4;function ri(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 ef(t,e={}){const{enabled:r=Li(),adapterName:n,sessionId:s,adapterSupportsAutocomplete:i,skill:o,inputRef:l}=e,[c,d]=m.useState([]),[u,f]=m.useState(!1),[p,g]=m.useState(-1),h=m.useRef(null),x=m.useRef(null),y=m.useRef(null),k=m.useRef(null),C=m.useRef(null),L=m.useRef(0),N=m.useRef([]),v=m.useRef([]),T=m.useRef(new Map);m.useEffect(()=>{N.current=c},[c]);const _=m.useCallback(A=>{const E=T.current.get(A);return E?E<=Date.now()?(T.current.delete(A),!1):!0:!1},[]),b=m.useCallback((A,E=!0)=>{const z=A.toLowerCase().trim(),S=v.current.length>0?v.current:N.current;if(!z)return S.slice(0,bs);const W=S.filter(K=>K.text.toLowerCase().includes(z));return W.length>0?W.slice(0,bs):E?S.slice(0,bs):[]},[]),$=m.useCallback(async A=>{if(!r||A.length<ti){d([]),v.current=[],x.current&&clearTimeout(x.current),y.current&&clearTimeout(y.current),f(!1);return}if(!n){d([]),v.current=[],x.current&&clearTimeout(x.current),f(!1);return}if(i===!1||_(n)){d([]),v.current=[],x.current&&clearTimeout(x.current),f(!1);return}k.current&&k.current.abort(),k.current=new AbortController;const E=L.current+1;L.current=E,x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{E===L.current&&f(!0)},150);try{const z={"X-Adapter-Name":n};s&&(z["X-Session-ID"]=s);const S=new URLSearchParams;S.set("q",A),S.set("limit",String(bs)),o&&S.set("skill",o);const W=`/api/v1/autocomplete?${S.toString()}`,K=await fetch(W,{method:"GET",headers:z,signal:k.current.signal});if(!K.ok){be("[useAutocomplete] Request failed:",K.status),[404,405,501].includes(K.status)?(T.current.set(n,Date.now()+Ju),d([]),v.current=[]):d(b(A));return}const q=await K.json(),G=Array.isArray(q==null?void 0:q.suggestions)?q.suggestions.map(te=>ri(typeof te=="string"?te:te==null?void 0:te.text)).filter(te=>te!==null):[];if(E!==L.current)return;G.length===0?d(b(A,!1)):(d(G),v.current=G),g(-1),D("[useAutocomplete] Received",G.length,"suggestions")}catch(z){if(z instanceof Error&&z.name==="AbortError")return;be("[useAutocomplete] Error:",z instanceof Error?z.message:String(z)),E===L.current&&d(b(A))}finally{E===L.current&&(x.current&&(clearTimeout(x.current),x.current=null),f(!1))}},[r,n,s,i,o,b,_]);m.useEffect(()=>{h.current&&clearTimeout(h.current);const A=()=>{k.current&&k.current.abort(),x.current&&clearTimeout(x.current),f(!1)},E=()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{y.current=null,d([]),A()},0)};if(!r||t.length<ti||i===!1||n&&_(n)){E();return}if(C.current){if(t===C.current){E();return}C.current=null}return h.current=setTimeout(()=>{$(t)},Zu),()=>{h.current&&clearTimeout(h.current),y.current&&(clearTimeout(y.current),y.current=null)}},[t,$,r,n,i,_]),m.useEffect(()=>()=>{k.current&&k.current.abort(),x.current&&clearTimeout(x.current)},[]);const j=m.useCallback(()=>{g(A=>{const E=N.current.length;return E===0?-1:A<E-1?A+1:0})},[]),I=m.useCallback(()=>{g(A=>{const E=N.current.length;return E===0?-1:A>0?A-1:E-1})},[]),O=m.useCallback(()=>{d([]),v.current=[],g(-1),k.current&&k.current.abort(),x.current&&clearTimeout(x.current),f(!1)},[]),R=m.useCallback(A=>{if(!(l!=null&&l.current))return;const E=()=>{const z=l.current;if(!z)return;const S=typeof A=="string"?A.length:z.value.length;z.focus({preventScroll:!0}),typeof z.setSelectionRange=="function"&&z.setSelectionRange(S,S)};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(E):setTimeout(E,0)},[l]),H=m.useCallback(A=>{C.current=A},[]);return{suggestions:c,isLoading:u,selectedIndex:p,setSelectedIndex:g,selectNext:j,selectPrevious:I,clearSuggestions:O,focusInputAfterSelection:R,suppressUntilQueryChange:H}}const Wt=new Map,tf=new Map,rf=new Map,sf=new Set,nf=()=>{if(typeof window>"u")return null;try{return localStorage.getItem("chat-adapter-name")}catch{return null}},lo=t=>typeof t=="object"&&t!==null&&"message"in t,af=t=>t instanceof Error?t.message:typeof t=="string"?t:lo(t)?t.message??"Unknown error":"Unknown error";function of({conversationId:t,onFilesSelected:e,onUploadError:r,onClose:n,onUploadingChange:s,onUploadSuccess:i,maxFiles:o=oe.maxFilesPerConversation,disabled:l=!1}){const{t:c}=Le(),[d,u]=m.useState(!1),[f,p]=m.useState(0),g=m.useRef(null),h=m.useRef(rf),x=m.useRef(sf),y=m.useRef(new Map),k=m.useRef(!0),C=m.useRef(tf),L=m.useRef(t),N=ye(M=>M.conversations),v=m.useMemo(()=>{if(!t)return new Map;const M=Wt.get(t);return M?new Map(M):new Map},[t,f]),T=m.useMemo(()=>{var Q;if(!t)return Array.from(v.entries());const M=N.find(J=>J.id===t),ee=new Set(((Q=M==null?void 0:M.attachedFiles)==null?void 0:Q.map(J=>J.file_id))||[]);return Array.from(v.entries()).filter(([,J])=>!J.fileId||!ee.has(J.fileId))},[t,N,v]),_=m.useCallback(M=>{if(!M){s==null||s(null,!1),p(le=>le+1);return}const ee=Wt.get(M)||new Map,Q=N.find(le=>le.id===M),J=new Map(ee);if(Q!=null&&Q.attachedFiles){const le=new Set(Q.attachedFiles.filter(ge=>ge.processing_status==="completed"||ge.processing_status==="failed"||ge.processing_status==="error").map(ge=>ge.file_id));J.forEach((ge,V)=>{ge.fileId&&le.has(ge.fileId)&&J.delete(V)})}J.size>0?(Wt.set(M,J),s==null||s(M,!0)):(Wt.delete(M),s==null||s(M,!1)),p(le=>le+1)},[N,s]);m.useEffect(()=>{L.current=t,setTimeout(()=>{_(t)},0)},[t,_]),m.useEffect(()=>{t&&setTimeout(()=>{_(t)},0)},[N,t,_]);const b=m.useCallback((M,ee)=>{if(!M)return;const Q=Wt.get(M)||new Map,J=ee(new Map(Q));J.size>0?Wt.set(M,J):Wt.delete(M),s==null||s(M,J.size>0),p(le=>le+1)},[s]),$=m.useCallback((M,ee)=>{if(!M)return;const Q=C.current.get(M)||[],J=ee([...Q||[]]),le=new Set(Q.map(ge=>ge.file_id));if(C.current.set(M,J),e(M,J),i){const ge=J.filter(V=>!le.has(V.file_id));ge.length>0&&i(M,ge)}p(ge=>ge+1)},[e,i]),j=ye(M=>M.removeFileFromConversation),I=ye(M=>M.addFileToConversation);m.useEffect(()=>(k.current=!0,()=>{k.current=!1}),[]);const O=m.useCallback(()=>{k.current=!1,new Map(y.current).forEach(ee=>ee.abort()),setTimeout(()=>{const ee=ye.getState(),Q=new Map(ee.conversations.map(le=>[le.id,le])),J=[];h.current.forEach((le,ge)=>{var V;if(le){const Y=Q.get(le);if(new Set(((V=Y==null?void 0:Y.attachedFiles)==null?void 0:V.map(xe=>xe.file_id))||[]).has(ge)){x.current.add(ge),h.current.delete(ge);return}}if(x.current.has(ge)){D(`[FileUpload] Skipping cleanup delete for ${ge}; file was previously attached and already handled`),h.current.delete(ge),x.current.delete(ge);return}J.push({fileId:ge,conversationId:le||null})}),J.length>0&&(n==null||n(),J.forEach(async({fileId:le,conversationId:ge})=>{try{if(ge)await j(ge,le);else{const V=nf();await qr.deleteFile(le,void 0,void 0,V??void 0),Ln(le)}}catch(V){if(lo(V)){const Y=V.message??"";!Y.includes("404")&&!Y.includes("File not found")&&be(`Failed to cleanup file ${le} during component unmount:`,V)}else be(`Failed to cleanup file ${le} during component unmount`,V)}}))},300)},[n,j]);m.useEffect(()=>O,[O]);const R=m.useCallback(async M=>{if(!M||M.length===0)return;const ee=Array.from(M),Q=ye.getState(),J=t||Q.currentConversationId;if(!J){r==null||r(c("fileUpload.selectBeforeUpload"));return}const le=Q.conversations.find(ae=>ae.id===J);if(!le){r==null||r(c("fileUpload.conversationNotFound"));return}const ge=le.attachedFiles||[],V=[],Y=ee.filter(ae=>ge.some(Pe=>Pe.filename===ae.name&&Pe.file_size===ae.size)?(V.push(ae.name),!1):!0);if(V.length>0&&(r==null||r(V.length===1?c("fileUpload.duplicateFileError",{filename:V[0]}):c("fileUpload.duplicateFilesError",{count:V.length}))),Y.length===0)return;if((C.current.get(J)||[]).length+Y.length>o){const ae=c("fileUpload.maxFilesPerConversationError",{count:o});tt()&&!kt()&&rt.getState().openLoginPrompt(c("fileUpload.maxFilesGuestLimitMessage",{count:o})),r==null||r(ae);return}if(oe.maxTotalFiles!==null&&Q.conversations.reduce((Pe,Ee)=>{var _e;return Pe+(((_e=Ee.attachedFiles)==null?void 0:_e.length)||0)},0)+Y.length>oe.maxTotalFiles){const Pe=c("fileUpload.maxTotalFilesError",{count:oe.maxTotalFiles});tt()&&!kt()&&rt.getState().openLoginPrompt(c("fileUpload.maxTotalFilesGuestLimitMessage",{count:oe.maxTotalFiles})),r==null||r(Pe);return}if(!le.adapterName){r==null||r(c("fileUpload.adapterNotConfigured"));return}const xe=le.adapterName,fe=at(le.apiUrl);for(let ae=0;ae<Y.length;ae++){const re=Y[ae],Pe=new AbortController;y.current.set(re.name,Pe);const Ee=`${J}-${re.name}-${Date.now()}-${ae}`;let _e=null;const Oe=re.type.startsWith("image/")?URL.createObjectURL(re):null;try{const U=await qr.uploadFile(re,B=>{if(b(J,de=>(de.set(Ee,B),de)),B.fileId&&!_e){_e=B.fileId,h.current.set(B.fileId,J),x.current.add(B.fileId),Oe&&to(B.fileId,Oe);const de={file_id:B.fileId,filename:re.name,mime_type:re.type||"application/octet-stream",file_size:re.size,processing_status:B.status==="uploading"?"uploading":B.status==="processing"?"processing":B.status==="completed"?"completed":void 0};D(`[FileUpload] Adding file ${B.fileId} to conversation ${J} immediately (status: ${de.processing_status})`),I(J,de)}},void 0,fe,xe).catch(B=>{if(B.message&&B.message.includes("was deleted")){_e&&h.current.delete(_e);const de=B.message.match(/File\s+([\w-]+)\s+was deleted/);return de&&de[1]&&h.current.delete(de[1]),D(`File ${re.name} was deleted during upload`),null}throw B});U?(h.current.set(U.file_id,J),x.current.add(U.file_id),D(`[FileUpload] Updating file ${U.file_id} in conversation ${J} with final status`),I(J,U),U.processing_status==="completed"||U.processing_status==="failed"||U.processing_status==="error"?b(J,de=>(de.delete(Ee),de)):b(J,de=>{const Ie=de.get(Ee);return Ie&&de.set(Ee,{...Ie,progress:90,status:"processing",fileId:U.file_id}),de}),$(J,de=>{if(new Set(de.map(Ye=>Ye.file_id)).has(U.file_id))return de;const we=[...de,U];return D(`[FileUpload] Updated uploadedFiles for ${J}: ${we.length} files`,we),we})):(be(`Upload completed for ${re.name} but uploadedAttachment is null`),b(J,B=>(B.delete(Ee),B)))}catch(U){const B=af(U);if(U instanceof DOMException&&U.name==="AbortError"||Pe.signal.aborted){D(`Upload cancelled for ${re.name}`),_e?h.current.delete(_e):Oe&&URL.revokeObjectURL(Oe);continue}if(B.includes("was deleted")){D(`File ${re.name} was deleted during upload`),_e&&h.current.delete(_e);const we=B.match(/File\s+([\w-]+)\s+was deleted/);we&&we[1]&&h.current.delete(we[1]);continue}k.current?(pe(`Failed to upload file ${re.name}:`,U),pe(`File type: ${re.type}, File name: ${re.name}`),r==null||r(B||`Failed to upload ${re.name}`)):be(`Upload error for ${re.name} (component unmounted):`,B),_e?h.current.delete(_e):Oe&&URL.revokeObjectURL(Oe);const de=Ee,Ie=J;setTimeout(()=>{b(Ie,we=>(we.delete(de),we))},5e3)}finally{y.current.delete(re.name)}}},[I,t,o,r,c,$,b]),H=m.useCallback(M=>{M.preventDefault(),M.stopPropagation(),l||u(!0)},[l]),A=m.useCallback(M=>{M.preventDefault(),M.stopPropagation(),u(!1)},[]),E=m.useCallback(M=>{if(M.preventDefault(),M.stopPropagation(),u(!1),l)return;const ee=M.dataTransfer.files;R(ee)},[l,R]),z=m.useCallback(M=>{const ee=M.target.files;R(ee),g.current&&(g.current.value="")},[R]),S=m.useCallback(()=>{!l&&g.current&&g.current.click()},[l]),W=m.useCallback(M=>{l||(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),S())},[l,S]),K=T.length>0,q=m.useMemo(()=>{const M=new Map;return N.forEach(ee=>{M.set(ee.id,ee.title||c("chatInterface.newChatTitle"))}),M},[N,c]),G=m.useMemo(()=>{const M=[];return Wt.forEach((ee,Q)=>{Q!==t&&ee.size>0&&M.push({conversationId:Q,uploads:Array.from(ee.entries()).map(([J,le])=>({key:J,progress:le}))})}),M},[t,f]),te=(M,ee)=>{const Q=M.status==="uploading"?c("fileUpload.uploadingStatus"):M.status==="processing"?c("fileUpload.processingStatus"):M.status==="completed"?c("fileUpload.completedStatus"):void 0;return a.jsx($s,{filename:M.filename,fileId:M.fileId,status:M.status,statusText:Q,errorMessage:M.error||(M.status==="error"?c("fileUpload.processingFailedMessage"):void 0)},ee)},Ce=T.length>0?a.jsx("div",{className:"w-full max-w-full overflow-hidden flex flex-wrap gap-2",role:"status","aria-live":"polite",children:T.map(([M,ee])=>te(ee,M))}):null;return a.jsxs("div",{className:"w-full max-w-full overflow-hidden space-y-2",children:[K&&Ce,!K&&a.jsxs("button",{type:"button",onClick:S,onKeyDown:W,onDragOver:H,onDragLeave:A,onDrop:E,disabled:l,className:`
344
- group relative w-full max-w-full rounded-lg border p-4 transition-all duration-200 text-left overflow-hidden
345
- ${d?"border-blue-300 bg-blue-50 ring-2 ring-blue-400 ring-inset dark:border-blue-500/40 dark:bg-[#101010] dark:ring-blue-500":l?"border-gray-200 bg-gray-50 cursor-not-allowed opacity-50 dark:border-[#242424] dark:bg-[#101010]":"border-gray-200 bg-gray-50 hover:bg-gray-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 focus-visible:ring-inset dark:border-[#242424] dark:bg-[#101010] dark:hover:bg-[#1a1a1a]"}
346
- `,"aria-label":c(l?"fileUpload.disabledAriaLabel":"fileUpload.enabledAriaLabel"),children:[a.jsx("input",{ref:g,type:"file",multiple:!0,onChange:z,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(kd,{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})})]})]})]}),G.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")}),G.map(({conversationId:M,uploads:ee})=>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:q.get(M)||"Conversation"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:ee.map(({key:Q,progress:J})=>te(J,Q))})]},M))]})]})}const si={"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"},dn=4,ys=3,lf=0,cf=0,un=2;function df(t){if(!t||typeof t!="object")return null;const e=t,r=["supportsAutocomplete","isAutocompleteSupported","autocompleteSupported"];for(const i of r)if(typeof e[i]=="boolean")return e[i];const n=["capabilities","features"],s=["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 s)if(typeof l[c]=="boolean")return l[c]}return null}function uf(t){if(!t)return"bin";if(si[t])return si[t];const e=t.split("/");return e.length===2&&e[1]?e[1]:"bin"}function ff(t){return t.replace(/[^a-zA-Z0-9._-]/g,"_").replace(/_+/g,"_")||"pasted-file"}function mf(t){const e=t.lastIndexOf(".");return e===-1||e===t.length-1?null:t.slice(e+1).toLowerCase()}function hf(t){const e=t.lastIndexOf(".");return e===-1?t:t.slice(0,e)}function fn(t){return!t||t==="processing"||t==="uploading"}function pf(t,e){const r=Date.now(),n=t.name&&t.name.trim().length>0?t.name.trim():"pasted-file",s=ff(hf(n)),o=mf(n)||uf(t.type),l=`${s}-${r}-${e}.${o}`;return new File([t],l,{type:t.type||"application/octet-stream"})}function ni({onSend:t,disabled:e=!1,placeholder:r=Ni(),autoFocusEnabled:n=!0,suppressMobileAutoFocus:s=!1,desktopOnlyAutoFocus:i=!1,isCentered:o=!1,maxWidthClass:l="max-w-5xl",adapterNotes:c,skillState:d,availableModels:u=[],defaultModel:f=null,selectedModel:p=null,onSelectModel:g}){var la;const{t:h}=Le(),[x,y]=m.useState(""),[k,C]=m.useState(!1),[L,N]=m.useState(!1),[v,T]=m.useState(!1),[_,b]=m.useState(!1),[$,j]=m.useState([]),[I,O]=m.useState({}),[R,H]=m.useState(new Map),[A,E]=m.useState(!1),[z,S]=m.useState(!1),[W,K]=m.useState(null),[q,G]=m.useState(null),[te,Ce]=m.useState(null),[M,ee]=m.useState({isOpen:!1,fileId:"",filename:"",isDeleting:!1}),Q=m.useRef(null),J=m.useRef(null),le=m.useRef(null),ge=m.useRef(null),V=m.useRef(null),Y=m.useRef(new Set),ie=m.useRef(""),xe=m.useRef(!1),fe=m.useRef(0),ae=m.useRef(null),{settings:re,updateSettings:Pe}=Ds(),{theme:Ee,isDark:_e}=lr(),Oe=Ee.mode==="dark"?"dark":Ee.mode==="light"?"light":"",U=_e?"dark":"light";Hr(J,{enabled:v,onEscape:()=>T(!1)});const B=m.useCallback((w,P)=>{w&&O(ue=>{if(ue[w]===P)return ue;const ke={...ue};return P?ke[w]=!0:delete ke[w],ke})},[]),[de,Ie]=m.useState(0),[we,Ye]=m.useState(!1),[Lt,Ae]=m.useState(0),[ot,vr]=m.useState(()=>({top:dn+ys,bottom:Math.max(dn-ys,0)})),[gt,vt]=m.useState(null),cr=kr(),We=tt()&&!cr,St=rt(w=>w.showLoginPrompt),{createConversation:Ut,currentConversationId:Se,conversations:xt,isLoading:me,syncConversationFiles:ve,stopStreaming:Te,removeFileFromConversation:De}=ye(),se=xt.find(w=>w.id===Se),bt=se?se.messages.filter(w=>!(w.role==="assistant"&&w.isStreaming)).length:0,dr=xt.reduce((w,P)=>w+P.messages.filter(ue=>!(ue.role==="assistant"&&ue.isStreaming)).length,0),Et=!!se&&oe.maxMessagesPerConversation!==null&&bt>=oe.maxMessagesPerConversation,Qt=oe.maxTotalMessages!==null&&dr>=oe.maxTotalMessages,lt=m.useCallback(()=>{Ie(w=>w+1)},[]),qs=xc(),yt=bc(),{isListening:st,isSupported:Kr,startListening:ur,stopListening:Zt,error:Jt}=Qu(w=>{y(P=>{const ue=P.length>0&&!/\s$/.test(P)?" ":"",ke=(P+ue+w).slice(0,oe.maxMessageLength);return ie.current=ke,ke})},lt,{silenceTimeoutMs:qs,language:yt||void 0}),Sr=hc(),_t=pc(),er=_t&&Kr,Tt=mc(),Gr=Li(),Mt=df(se==null?void 0:se.adapterInfo),{skills:Ot,isLoading:jr,selectedSkill:He,selectSkill:Cr,clearSkill:tr}=d,Xr=(se==null?void 0:se.adapterName)||null,{suggestions:zt,selectedIndex:ct,setSelectedIndex:Yr,selectNext:Qr,selectPrevious:Ws,clearSuggestions:jt,focusInputAfterSelection:Bt,suppressUntilQueryChange:Zr}=ef(x,{enabled:Gr&&!st,apiUrl:se==null?void 0:se.apiUrl,adapterName:Xr,sessionId:se==null?void 0:se.sessionId,adapterSupportsAutocomplete:Mt,skill:(He==null?void 0:He.name)||null,inputRef:Q}),Ar=zt.length>0,Jr=!st,Nr=Jr&&Ar&&!we,Ht=x.startsWith("/")?x.slice(1):"",fr=Ht.toLowerCase().replace(/-/g," "),Je=fr?Ot.filter(w=>w.name.replace(/-/g," ").toLowerCase().includes(fr)||w.description.toLowerCase().includes(fr)):Ot,F=Je.length>0?Math.min(Lt,Je.length-1):0,ce=Je[F]??null,X=(ce==null?void 0:ce.name.replace(/-/g," "))??"",Ne=we&&ce&&x.startsWith("/")&&X.toLowerCase().startsWith(Ht.toLowerCase())&&X.length>Ht.length?X.slice(Ht.length):null,dt=ct>=0?ct:0,wt=Ar?zt[dt]:null,mr=m.useMemo(()=>{if(!wt)return null;const w=wt.text||"";if(!x)return w;const P=x;return w.toLowerCase().startsWith(P.toLowerCase())&&w.length>P.length?w.slice(P.length):null},[wt,x]),Ks=Ne??mr,wo=x.trim().length===0&&!Ks,ko=m.useCallback(w=>{if(!x)return a.jsx("span",{className:"line-clamp-1 text-current",children:w});if(!w.toLowerCase().startsWith(x.toLowerCase()))return a.jsx("span",{className:"line-clamp-1 text-current",children:w});const P=w.slice(0,x.length),ue=w.slice(x.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:ue})]})},[x]),Gn=m.useCallback(w=>{var P;Cr(w),Ye(!1),y(""),jt(),Ae(0),(P=Q.current)==null||P.focus()},[jt,Cr]),vo=m.useCallback(()=>{var w;y("/"),Ye(!0),Ae(0),(w=Q.current)==null||w.focus()},[]),Xn=m.useCallback(()=>{var w;Ye(!1),y(""),Ae(0),(w=Q.current)==null||w.focus()},[]),Vt=m.useCallback(()=>{const w=Q.current;if(!w||typeof window>"u")return;const P=je=>{const Ve=je+ys,Re=Math.max(je-ys,0);w.style.paddingTop=`${Ve}px`,w.style.paddingBottom=`${Re}px`,vr({top:Ve,bottom:Re})},ue=window.getComputedStyle(w),ke=parseFloat(ue.lineHeight||"0");!Number.isNaN(ke)&&ke>0?vt(je=>je===ke?je:ke):vt(je=>je===null?je:null),P(dn)},[]),So=()=>{const w=Q.current;return w?w.selectionStart===w.selectionEnd&&w.selectionStart===x.length:!1},Yn=(se==null?void 0:se.attachedFiles)||[],hr=Se?Yn:$,jo=xt.reduce((w,P)=>{var ue;return w+(((ue=P.attachedFiles)==null?void 0:ue.length)||0)},0),Qn=oe.maxFilesPerConversation!==null&&oe.maxFilesPerConversation>0&&Yn.length>=oe.maxFilesPerConversation,Zn=oe.maxTotalFiles!==null&&jo>=oe.maxTotalFiles,Ir=((la=se==null?void 0:se.adapterInfo)==null?void 0:la.isFileSupported)??!1,Gs=hr.some(w=>w.processing_status?w.processing_status!=="completed"&&w.processing_status!=="error"&&w.processing_status!=="failed":!0),ut=Se?!!I[Se]:!1,es=Object.values(I).some(Boolean),Xs=x.trim().length>0,Ys=Et||Qt,ze=e||Gs||ut||Ys,Jn=Tt&&Ir,ts=Qn||Zn,Lr=!Jn||e||ut||Ys||ts,ea=!_&&(ut||R.size>0),ta=_||ut&&R.size===0;m.useLayoutEffect(()=>{if(Q.current){const w=Q.current,P=120;if(x.length===0){w.style.height="32px",w.style.overflowY="hidden",Vt();return}w.style.height="auto";const ue=w.scrollHeight;w.style.height=`${Math.min(ue,P)}px`,w.style.overflowY=ue>P?"auto":"hidden",Vt()}},[x,Vt]),m.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const w=Q.current;if(!w)return;const P=new ResizeObserver(()=>{Vt()});return P.observe(w),()=>{P.disconnect()}},[Vt]);const ra=()=>{const w=document.activeElement;return w&&w.tagName==="TEXTAREA"},rs=m.useCallback(()=>typeof window>"u"?!1:!!(i&&!window.matchMedia("(min-width: 1024px)").matches||s&&window.matchMedia("(max-width: 767px)").matches),[i,s]),ss=m.useCallback(()=>{var w;(w=Q.current)==null||w.focus({preventScroll:i})},[i]);m.useEffect(()=>{rs()||n&&!ze&&Q.current&&!ra()&&ss()},[n,ze,rs,ss]);const sa=!!He||Ot.length>0&&x.length===0&&!ze;m.useEffect(()=>{if(typeof window>"u"||!window.matchMedia("(max-width: 767px)").matches||!sa||document.activeElement!==Q.current)return;const w=window.requestAnimationFrame(()=>{const P=Q.current;!P||document.activeElement!==P||(P.blur(),P.focus({preventScroll:!0}))});return()=>window.cancelAnimationFrame(w)},[sa]);const Qs=m.useRef(me);m.useEffect(()=>{if(rs()){Qs.current=me;return}n&&Qs.current&&!me&&!ze&&Q.current&&setTimeout(()=>{Q.current&&!ra()&&ss()},100),Qs.current=me},[n,me,ze,rs,ss]),m.useEffect(()=>{if(!er||(de>fe.current&&(xe.current=!0,fe.current=de),!xe.current||de===0))return;const w=ie.current.trim(),P=ye.getState();if(D("[MessageInput] Auto-send check after voice completion:",{hasMessage:!!w,isInputDisabled:ze,isComposing:k,isLoading:P.isLoading}),xe.current=!1,!w)return;if(ze||k){D("[MessageInput] Auto-send skipped because input is currently disabled or composing");return}const ue=P.conversations.find(Re=>Re.id===P.currentConversationId),je=((ue==null?void 0:ue.attachedFiles)||[]).map(Re=>Re.file_id),Ve=He==null?void 0:He.name;D("[MessageInput] Auto-sending voice message immediately:",w),t(w,je.length>0?je:void 0,void 0,Ve),Ve&&tr(),setTimeout(()=>{Ye(!1)},0),jt(),setTimeout(()=>{y("")},0),ie.current="",Q.current&&(Q.current.style.height="auto",Q.current.style.overflowY="hidden",Vt())},[er,de,ze,k,t,He,tr,Vt,jt]),m.useEffect(()=>{ut&&_&&setTimeout(()=>{b(!1)},0)},[ut,_]);const ns=m.useCallback((w,P)=>{setTimeout(()=>{let ue=ye.getState(),ke=P||ue.currentConversationId;if(ke||(ke=Ut(),ue=ye.getState(),ke=ue.currentConversationId||ke),!ke){pe("[MessageInput] Unable to sync files: conversation ID missing");return}const je=new Set(w.map(Re=>Re.file_id)),Ve=[];Y.current.forEach((Re,$e)=>{const[,...Ke]=$e.split("-"),sr=Ke.join("-");je.has(sr)||Ve.push($e)}),Ve.forEach(Re=>Y.current.delete(Re)),w.forEach(Re=>{const $e=`${ke}-${Re.file_id}`;Y.current.has($e)||(Y.current.add($e),D(`[MessageInput] Adding file ${Re.file_id} to conversation ${ke}`),ue.addFileToConversation(ke,Re))})},0)},[Ut]);m.useEffect(()=>{if(Se!==ae.current)if(ae.current=Se||null,Se&&se){const w=se.attachedFiles||[];setTimeout(()=>{j(w.map(P=>({...P})))},0)}else setTimeout(()=>{j([])},0)},[Se,se]),m.useEffect(()=>{if(Se&&se){const w=se.attachedFiles||[];w.length>0?setTimeout(()=>{j(P=>{const ue=new Set(P.map(je=>je.file_id)),ke=w.filter(je=>!ue.has(je.file_id));return ke.length>0?(D(`[MessageInput] Syncing ${ke.length} missing files from conversation to UI`),[...P,...ke]):P})},0):w.length===0&&$.length>0&&setTimeout(()=>{j([])},0)}},[Se,se,xt,$.length]);const Zs=m.useRef(null),Js=m.useRef(""),as=(se==null?void 0:se.attachedFiles)||[],is=as.length>0?`${as.length}:${as.map(w=>w.file_id).join("|")}`:"",na=as.some(w=>fn(w.processing_status));m.useEffect(()=>{if(!Se||!(se!=null&&se.adapterName))return;const w=is!=="";if(w&&(Zs.current!==Se||Js.current!==is)?(D(`[MessageInput] Syncing files for conversation ${Se}...`),Zs.current=Se,Js.current=is,ve(Se).catch(ke=>{pe("[MessageInput] Failed to sync conversation files:",ke)})):w||(Zs.current=Se,Js.current=""),!na)return;D("[MessageInput] Files still processing, starting poll...");const ue=setInterval(async()=>{const je=ye.getState().conversations.find($e=>$e.id===Se);if(!je){clearInterval(ue);return}if((je.attachedFiles||[]).filter($e=>fn($e.processing_status)).length===0){D("[MessageInput] All files completed processing, stopping poll"),clearInterval(ue);return}try{await ve(Se)}catch($e){pe("[MessageInput] Failed to poll file status:",$e)}},3e3);return()=>{clearInterval(ue)}},[Se,se==null?void 0:se.adapterName,is,na,ve]),m.useEffect(()=>{setTimeout(()=>{O(w=>{const P=new Set(xt.map(je=>je.id));let ue=!1;const ke={...w};return Object.keys(ke).forEach(je=>{P.has(je)||(delete ke[je],ue=!0)}),ue?ke:w})},0)},[xt]);const aa=w=>{if(w.preventDefault(),Xs&&!ze&&!k){st&&Zt();const ue=((se==null?void 0:se.attachedFiles)||[]).map(je=>je.file_id),ke=He==null?void 0:He.name;t(x.trim(),ue.length>0?ue:void 0,void 0,ke),ke&&tr(),Ye(!1),Pr("messageSent",re.soundEnabled),y(""),ie.current="",j([]),b(!1),Q.current&&(Q.current.style.height="auto",Q.current.style.overflowY="hidden",Vt())}},os=m.useCallback(w=>{if(!w||w.length===0)return;const P=w.length===1?h("messageInput.uploadSuccess.single",{filename:w[0].filename}):h("messageInput.uploadSuccess.multiple",{count:w.length});Pr("success",re.soundEnabled),G(P),setTimeout(()=>{G(null)},6e3)},[re.soundEnabled,h]),Co=m.useCallback((w,P)=>{D(`[MessageInput] handleFilesSelected called with ${P.length} files for conversation ${w}:`,P),w&&(w===Se&&j(P),ns(P,w))},[Se,ns]),Ao=m.useCallback((w,P)=>{w===Se&&os(P)},[Se,os]),No=m.useCallback(w=>{ee({isOpen:!0,fileId:w.file_id,filename:w.filename,isDeleting:!1})},[]),Io=m.useCallback(()=>{ee(w=>w.isDeleting?w:{isOpen:!1,fileId:"",filename:"",isDeleting:!1})},[]),Lo=m.useCallback(async()=>{if(!(!Se||!M.fileId)){ee(w=>({...w,isDeleting:!0}));try{await De(Se,M.fileId),j(w=>w.filter(P=>P.file_id!==M.fileId)),ee({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}catch(w){const P=w instanceof Error?w.message:h("messageInput.fileRemoveFailed");pe("[MessageInput] Failed to remove file:",w),Ce(P),ee({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}}},[Se,M.fileId,De,h]),ia=m.useCallback(w=>w.replace(/\s+/g," ").trim(),[]),ls=m.useCallback(w=>{const P=ia(w);y(P),jt(),Zr(P),Bt(P)},[jt,Bt,ia,Zr]),en=m.useCallback(w=>{if(w<0)return;const P=zt[w]||zt[0];P&&ls(P.text)},[zt,ls]),Eo=w=>{if(we){if(w.key==="ArrowDown"){w.preventDefault(),Ae(P=>Je.length===0?0:(P+1)%Je.length);return}if(w.key==="ArrowUp"){w.preventDefault(),Ae(P=>Je.length===0?0:(P-1+Je.length)%Je.length);return}if(w.key==="Home"){w.preventDefault(),Ae(0);return}if(w.key==="End"){w.preventDefault(),Ae(Math.max(Je.length-1,0));return}if((w.key==="Enter"&&!w.shiftKey||w.key==="Tab")&&ce){w.preventDefault(),Gn(ce);return}if(w.key==="Escape"){w.preventDefault(),Xn();return}}if(Ar&&Jr){if(w.key==="ArrowDown"){w.preventDefault(),Qr();return}if(w.key==="ArrowUp"){w.preventDefault(),Ws();return}if(w.key==="Tab"){w.preventDefault();const P=ct>=0?ct:0;en(P);return}if(w.key==="ArrowRight"&&So()){if(mr&&wt){w.preventDefault(),ls(wt.text);return}if(ct>=0){w.preventDefault(),en(ct);return}}if(w.key==="Enter"&&ct>=0){w.preventDefault(),en(ct);return}if(w.key==="Escape"){w.preventDefault(),jt();return}}w.key==="Enter"&&!w.shiftKey&&!k&&(w.preventDefault(),aa(w))},_o=()=>{st?Zt():(jt(),ur())},To=()=>{const w=!re.voiceEnabled;Pe({voiceEnabled:w}),w&&Xt.enableAudio()},Mo=m.useCallback(async w=>{if(!Tt||!L||!Ir||ze)return;const P=w.clipboardData;if(!P||!P.items)return;const ke=Array.from(P.items).filter($e=>$e.kind==="file");if(ke.length===0)return;const je=[];if(ke.forEach(($e,Ke)=>{const sr=$e.getAsFile();sr&&je.push(pf(sr,Ke))}),je.length===0)return;w.preventDefault(),K(null),G(null),b(!1);let Ve=null;const Re=new Set;try{const $e=ye.getState(),Ke=$e.conversations.find(nt=>nt.id===$e.currentConversationId);if(((Ke==null?void 0:Ke.attachedFiles)||[]).length+je.length>oe.maxFilesPerConversation)throw We&&rt.getState().openLoginPrompt(h("fileUpload.maxFilesGuestLimitMessage",{count:oe.maxFilesPerConversation})),new Error(h("fileUpload.maxFilesPerConversationError",{count:oe.maxFilesPerConversation}));if(oe.maxTotalFiles!==null&&$e.conversations.reduce((ft,$t)=>{var Qe;return ft+(((Qe=$t.attachedFiles)==null?void 0:Qe.length)||0)},0)+je.length>oe.maxTotalFiles)throw We&&rt.getState().openLoginPrompt(h("fileUpload.maxTotalFilesGuestLimitMessage",{count:oe.maxTotalFiles})),new Error(h("fileUpload.maxTotalFilesError",{count:oe.maxTotalFiles}));if(!Ke)throw new Error(h("messageInput.conversationNotFoundShort"));if(!Ke.adapterName)throw new Error(h("fileUpload.adapterNotConfigured"));const Po=at(Ke.apiUrl),Ro=Ke.adapterName;Ve=Ke.id,B(Ve,!0);const Er=[],ca=[];for(let nt=0;nt<je.length;nt++){const ft=je[nt],$t=ft.name||`Clipboard file ${nt+1}`,Qe=`${$t}-${Date.now()}-${nt}`,_r=ft.type.startsWith("image/")?URL.createObjectURL(ft):null;_r&&Re.add(_r);let da=null;H(et=>{const qt=new Map(et);return qt.set(Qe,{filename:$t,progress:0,status:"uploading"}),qt});const Do=et=>{et.fileId&&!da&&(da=et.fileId,_r&&(to(et.fileId,_r),Re.delete(_r))),H(qt=>{const mt=new Map(qt),Tr=mt.get(Qe);return Tr&&mt.set(Qe,{...Tr,filename:$t,progress:et.progress,status:et.status,fileId:et.fileId}),mt})},Uo=()=>new Promise(et=>{H(qt=>{const mt=new Map(qt),Tr=mt.get(Qe);return Tr&&mt.set(Qe,{...Tr,progress:100,status:"completed"}),mt}),setTimeout(()=>{H(qt=>{const mt=new Map(qt);return mt.delete(Qe),mt}),et()},2500)});D(`[MessageInput] Pasting file: ${ft.name}, type: ${ft.type||"unknown"}, size: ${ft.size}`);const Oo=await qr.uploadFile(ft,et=>{D(`[MessageInput] Paste upload progress for ${ft.name}: ${et.progress}% - ${et.status}`),Do(et)},void 0,Po,Ro);Er.push(Oo),ca.push(Uo())}if(Er.length>0){let nt=Er;if(Ve&&Ve===Se){const ft=new Set($.map(Qe=>Qe.file_id)),$t=Er.filter(Qe=>!ft.has(Qe.file_id));$t.length>0?(j(Qe=>[...Qe,...$t]),nt=$t):nt=[]}nt.length>0&&ns(nt,Ve),await Promise.all(ca),os(Er)}}catch($e){const Ke=$e instanceof Error?$e.message:"Failed to paste file";pe("[MessageInput] Paste error:",$e),Pr("error",re.soundEnabled),K(Ke),Ke.toLowerCase().includes("maximum")&&Ce(Ke),setTimeout(()=>{K(null)},5e3),H(new Map),Re.forEach(sr=>URL.revokeObjectURL(sr))}finally{B(Ve,!1)}},[$,Se,L,Ir,We,ze,B,re.soundEnabled,os,ns,Tt,h]),oa=lc(se==null?void 0:se.adapterName);let Ft;Qt?Ft=We?h("messageInput.placeholder.guestLimitTotal",{count:oe.maxTotalMessages}):h("messageInput.placeholder.workspaceLimitTotal",{count:oe.maxTotalMessages}):Et?Ft=We?h("messageInput.placeholder.guestLimitPerConversation",{count:oe.maxMessagesPerConversation}):h("messageInput.placeholder.conversationLimitReached",{count:oe.maxMessagesPerConversation}):Gs||ut?Ft=h("messageInput.placeholder.filesUploading"):oa?Ft=oa:Jn?Ft=h("messageInput.placeholder.messageOrbit"):Ft=r;const rr=[];Qt&&oe.maxTotalMessages!==null&&(We?St&&rr.push(h("messageInput.limitWarning.guestTotalMessages",{count:oe.maxTotalMessages})):rr.push(h("messageInput.limitWarning.workspaceTotalMessages",{count:oe.maxTotalMessages}))),Et&&oe.maxMessagesPerConversation!==null&&(We?St&&rr.push(h("messageInput.limitWarning.guestPerConversation",{count:oe.maxMessagesPerConversation})):rr.push(h("messageInput.limitWarning.conversationLimitReached",{count:oe.maxMessagesPerConversation}))),te&&rr.push(te),m.useEffect(()=>{!_t||!Jt||Pr("error",re.soundEnabled)},[_t,re.soundEnabled,Jt]),m.useEffect(()=>{if(!te)return;const w=setTimeout(()=>Ce(null),5e3);return()=>clearTimeout(w)},[te]),m.useEffect(()=>{if(!_)return;const w=P=>{P.key!=="Escape"||P.defaultPrevented||b(!1)};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[_]),m.useEffect(()=>{var w;(_||ut||R.size>0||es)&&((w=le.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[_,ut,R.size,es]),m.useEffect(()=>{var w;Nr&&((w=ge.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[Nr]),m.useEffect(()=>{var w;we&&((w=V.current)==null||w.scrollIntoView({behavior:"smooth",block:"end"}))},[we,Je.length]);const Fo=l,$o=o?"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 ${$o}`,children:a.jsxs("div",{className:`mx-auto w-full ${Fo}`,children:[Jt&&_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(jn,{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:Jt})]}),W&&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(jn,{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:W})]}),q&&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(Kc,{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:q})]}),rr.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(zn,{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:rr.map((w,P)=>a.jsx("li",{className:"text-sm text-amber-800 dark:text-amber-200",children:w},`${w}-${P}`))}),We&&(Ys||ts)&&St&&a.jsx("button",{type:"button",onClick:()=>rt.getState().openLoginPrompt(h("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:h("messageInput.signInPrompt.button")})]})]}),a.jsxs("div",{className:"relative w-full",children:[a.jsxs("form",{onSubmit:aa,className:"flex w-full flex-col gap-2 md:gap-3",children:[a.jsxs("div",{className:`grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1.5 md:flex md:flex-row md:flex-nowrap md:gap-2 rounded-xl md:rounded-lg border px-2.5 py-1.5 md:px-4 md:py-3 shadow-sm transition-all ${L?"border-gray-400 shadow-md dark:border-[#3a3a3a] dark:shadow-lg":"border-gray-300 dark:border-[#242424]"} bg-gray-50 dark:bg-[#111111]`,children:[He&&a.jsx("div",{className:"col-span-2 flex w-full shrink-0 basis-full md:contents",children:a.jsxs("div",{className:"flex h-8 max-w-[45%] shrink-0 items-center gap-1.5 rounded-full border border-gray-300 bg-white px-2.5 text-xs text-gray-700 shadow-sm dark:border-[#3a3a3a] dark:bg-[#1a1a1a] dark:text-gray-200 sm:max-w-[38%] md:self-center md:max-w-[32%]",children:[a.jsx(On,{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:He.name.replace(/-/g," ")}),a.jsx("button",{type:"button",onClick:()=>{var w;tr(),(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":h("messageInput.selectedSkill.removeAriaLabel"),children:a.jsx(Ge,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]})}),!He&&Ot.length>0&&x.length===0&&!ze&&a.jsx("div",{className:"col-span-2 flex w-full shrink-0 basis-full md:contents",children:a.jsxs("button",{type:"button",onClick:vo,className:"flex h-8 shrink-0 items-center gap-1.5 rounded-full border border-gray-300 bg-white px-2.5 text-xs font-medium text-gray-600 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 dark:border-[#3a3a3a] dark:bg-[#1a1a1a] dark:text-gray-300 dark:hover:bg-white/10 dark:hover:text-gray-100 dark:focus-visible:ring-gray-600 md:self-center","aria-label":h("messageInput.skillsHint.ariaLabel"),title:h("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:"/"}),h("messageInput.skillsHint.text")]})}),a.jsxs("div",{className:"relative flex-1 w-full min-w-0 md:translate-y-0.5",children:[wo&&Ft&&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(ot.top-lf,0),paddingBottom:ot.bottom,paddingLeft:`${un}px`,paddingRight:0,lineHeight:gt?`${gt}px`:void 0},"aria-hidden":"true",children:Ft}),Ks&&L&&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(ot.top-cf,0),paddingBottom:ot.bottom,paddingLeft:`${un}px`,paddingRight:0,lineHeight:gt?`${gt}px`:void 0},"aria-hidden":"true",children:[a.jsx("span",{className:"invisible",children:x}),a.jsx("span",{children:Ks})]}),a.jsx("textarea",{ref:Q,"aria-label":h("messageInput.textarea.ariaLabel"),value:x,onChange:w=>{const P=w.target.value;y(P),P.startsWith("/")&&Ae(0),Ye(P.startsWith("/")&&Ot.length>0)},onKeyDown:Eo,onPaste:Mo,onCompositionStart:()=>C(!0),onCompositionEnd:()=>C(!1),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:Ft,disabled:ze,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:`${ot.top}px`,paddingBottom:`${ot.bottom}px`,paddingLeft:`${un}px`,paddingRight:0,border:"none",outline:"none",boxShadow:"none",WebkitAppearance:"none",MozAppearance:"none",appearance:"none",caretColor:x.trim()||L?"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:[o&&!Tt&&a.jsx("div",{className:"hidden md:block h-8 w-8 shrink-0","aria-hidden":"true"}),Tt&&a.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),Lr||b(!_)},disabled:Lr,onMouseEnter:()=>E(!0),onMouseLeave:()=>E(!1),className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${_||hr.length>0?"bg-gray-200 text-[#353740] dark:bg-[#565869] dark:text-[#ececf1]":Lr?"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:Ir?ts&&Qn&&oe.maxFilesPerConversation!==null?h("messageInput.fileUpload.titleLimitPerConversation",{count:oe.maxFilesPerConversation}):ts&&Zn&&oe.maxTotalFiles!==null?h("messageInput.fileUpload.titleLimitWorkspace",{count:oe.maxTotalFiles}):ze?h("messageInput.fileUpload.titleUploading"):hr.length>0?h("messageInput.fileUpload.titleAttached",{count:hr.length}):h("messageInput.fileUpload.attachAriaLabel"):h("messageInput.fileUpload.titleNotSupported"),"aria-label":h("messageInput.fileUpload.attachAriaLabel"),children:Lr&&A?a.jsx(Ge,{className:"h-4 w-4"}):a.jsx(fd,{className:"h-4 w-4"})}),x.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:x.length>=oe.maxMessageLength?"text-red-600 font-semibold":"",children:[x.length,"/",oe.maxMessageLength]})})]}),a.jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[a.jsx(io,{availableModels:u,defaultModel:f,selectedModel:p,onSelect:w=>g==null?void 0:g(w),wrapperClassName:"relative block",maxWidthClass:"max-w-[150px] md:max-w-[220px]"}),(Sr||_t)&&a.jsxs(a.Fragment,{children:[Sr&&a.jsx("button",{type:"button",onClick:To,className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${re.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:re.voiceEnabled?h("messageInput.voiceOutput.titleEnabled"):h("messageInput.voiceOutput.titleDisabled"),"aria-label":re.voiceEnabled?h("messageInput.voiceOutput.ariaLabelEnabled"):h("messageInput.voiceOutput.ariaLabelDisabled"),children:re.voiceEnabled?a.jsx(Bn,{className:"h-5 w-5"}):a.jsx(vd,{className:"h-5 w-5"})}),er&&a.jsx("button",{type:"button",onClick:_o,disabled:ze,onMouseEnter:()=>S(!0),onMouseLeave:()=>S(!1),className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${st?"!flex bg-red-100 text-red-600 dark:bg-red-900/40 dark:text-red-300":ze?"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:h(ze?"messageInput.voiceInput.titleUploading":st?"messageInput.voiceInput.titleListening":"messageInput.voiceInput.titleDisabled"),"aria-label":h(st?"messageInput.voiceInput.ariaLabelListening":"messageInput.voiceInput.ariaLabelDisabled"),children:st||ze&&z?a.jsx(ad,{className:"h-5 w-5"}):a.jsx(id,{className:"h-5 w-5"})})]}),c&&a.jsx("button",{type:"button",onClick:()=>T(!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:h("messageInput.agentInfo.title"),"aria-label":h("messageInput.agentInfo.ariaLabel"),children:a.jsx(Ea,{className:"h-5 w-5"})}),(Gs||ut)&&a.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center",children:a.jsx(Oi,{className:"h-4 w-4 animate-spin text-gray-500 dark:text-[#bfc2cd]"})}),me?a.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),Te()},className:"flex h-9 w-9 md:h-8 md:w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 bg-red-500 text-white hover:bg-red-600 dark:bg-red-600 dark:hover:bg-red-700",title:h("messageInput.stop.title"),"aria-label":h("messageInput.stop.ariaLabel"),children:a.jsx(bd,{className:"h-4 w-4 md:h-3 md:w-3 fill-current"})}):a.jsx("button",{type:"submit",disabled:!Xs||ze||k,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 ${Xs&&!ze&&!k?"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:h("messageInput.submit.title"),"aria-label":h("messageInput.submit.ariaLabel"),children:a.jsx(Ns,{className:"h-4 w-4"})})]})]})]}),hr.length>0&&a.jsx("div",{className:"flex flex-wrap gap-2",children:hr.map(w=>{const P=fn(w.processing_status),ue=w.processing_status==="failed"||w.processing_status==="error",ke=ue?"error":P?w.processing_status==="uploading"?"uploading":"processing":"completed",je=P?w.processing_status==="uploading"?h("messageInput.attachedFile.uploadingStatus"):h("messageInput.attachedFile.processingStatus"):void 0;return a.jsx($s,{filename:w.filename,fileId:w.file_id,status:ke,statusText:je,errorMessage:ue?w.error_message||h("messageInput.fileProcessingFailedTitle"):void 0,onRemove:()=>{ue?(Se&&De(Se,w.file_id),j(Ve=>Ve.filter(Re=>Re.file_id!==w.file_id))):No(w)},removeTitle:h(ue?"messageInput.attachedFile.removeTitleFailed":"messageInput.attachedFile.removeTitleNormal")},w.file_id)})}),Tt&&(Ir||es)&&a.jsxs("div",{ref:le,className:`${ea?"":"rounded-lg border border-gray-200/80 bg-white p-2.5 dark:border-[#3c3f4a] dark:bg-[#2a2b32]"} transition-all duration-200 ${!_&&!ut&&R.size===0&&!es?"hidden":""}`,children:[_&&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:h("messageInput.uploadPanel.headingAttach")}),a.jsx("button",{type:"button",onClick:()=>b(!1),className:"flex h-6 w-6 items-center justify-center rounded-md text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:text-[#6b6f7a] dark:hover:bg-[#3c3f4a] dark:hover:text-[#bfc2cd] transition-colors",title:h("messageInput.uploadPanel.closeTitle"),children:a.jsx(Ge,{className:"h-3.5 w-3.5"})})]}),!ea&&ut&&!_&&R.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:h("messageInput.uploadPanel.headingUploading")})}),R.size>0&&a.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:Array.from(R.entries()).map(([w,P])=>a.jsx($s,{filename:P.filename,fileId:P.fileId,status:P.status,statusText:P.status==="uploading"?h("messageInput.uploadProgress.statusUploading"):P.status==="processing"?h("messageInput.uploadProgress.statusProcessing"):P.status==="completed"?h("messageInput.uploadProgress.statusCompleted"):void 0,errorMessage:P.error},w))}),a.jsx("div",{className:`${ta?"block max-h-[40vh] overflow-y-auto":"hidden"}`,"aria-hidden":!ta,children:a.jsx(of,{conversationId:Se,onFilesSelected:Co,onUploadError:w=>{pe("File upload error:",w),Ce(w)},onUploadingChange:B,onUploadSuccess:Ao,maxFiles:oe.maxFilesPerConversation,disabled:Lr})})]}),a.jsx("div",{className:"h-3 md:h-1",children:er&&st&&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"}),h("messageInput.listeningIndicator")]})})]}),we&&a.jsx("div",{ref:V,className:"w-full pt-1",children:a.jsx(ao,{skills:Ot,isLoading:jr,selectedSkill:He,activeSkillName:ce==null?void 0:ce.name,query:Ht,onActiveSkillChange:w=>{const P=Je.findIndex(ue=>ue.name===w.name);P>=0&&Ae(P)},onSelect:Gn,onClose:Xn})}),Nr&&a.jsx("div",{ref:ge,role:"listbox","aria-label":h("messageInput.autocompletePanel.ariaLabel"),className:"w-full pt-1",children:zt.map((w,P)=>{const ue=P===ct;return a.jsx("button",{type:"button",role:"option","aria-selected":ue,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 ${ue?"bg-gray-100 dark:bg-[#2d2f39]":"hover:bg-gray-50 dark:hover:bg-[#2d2f39]/60"}`,onClick:()=>ls(w.text),onMouseEnter:()=>Yr(P),children:ko(w.text)},P)})}),a.jsx(_s,{isOpen:M.isOpen,onClose:Io,onConfirm:Lo,title:h("messageInput.fileDelete.title"),message:h("messageInput.fileDelete.message",{filename:M.filename}),confirmText:h("messageInput.fileDelete.confirmText"),cancelText:h("common.cancel"),type:"danger",isLoading:M.isDeleting})]})]})}),v&&c&&typeof document<"u"&&Rs.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:J,role:"dialog","aria-modal":"true","aria-labelledby":"agent-info-title",tabIndex:-1,className:"w-full max-w-2xl max-h-[calc(100vh-2rem)] overflow-y-auto rounded-2xl bg-white shadow-2xl transform animate-fadeIn dark:bg-[#1a1b1e]",children:[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(Ea,{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:h("messageInput.agentInfoModal.title")})]}),a.jsx("button",{type:"button",onClick:()=>T(!1),className:"p-2 hover:bg-gray-100 dark:hover:bg-[#25262f] rounded-lg transition-colors","aria-label":h("messageInput.agentInfoModal.closeAriaLabel"),children:a.jsx(Ge,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),a.jsx("div",{className:"p-6",children:a.jsx(Dt,{content:c,className:`message-markdown w-full min-w-0 prose prose-slate dark:prose-invert max-w-none text-sm leading-relaxed text-[#434654] dark:text-[#d7dae3] [&>:first-child]:mt-0 [&>:last-child]:mb-0 ${Oe}`,syntaxTheme:U})}),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:()=>T(!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:h("messageInput.agentInfoModal.confirmButton")})})]})}),document.body)]})}function ai({adapter:t,onSelect:e}){var l;const{t:r}=Le(),n=(l=t.description)==null?void 0:l.trim(),{isDark:s}=lr(),i=s?"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-blue-700 dark:text-blue-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(Dt,{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:r("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":r("agentCard.startConversationAriaLabel",{name:t.name}),children:a.jsx(La,{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":r("agentCard.startConversationAriaLabel",{name:t.name}),children:a.jsx(La,{className:"h-4 w-4","aria-hidden":"true"})})})]})}const nr=t=>{if(typeof t!="string")return;const e=t.trim();return e.length>0?e:void 0},gf=t=>{if(!t||typeof t!="object")return null;const e=t,r=nr(e.name);if(!r)return null;const n=nr(e.id);if(!n)return console.warn(`[middlewareConfig] Adapter "${r}" is missing a required 'id' field — skipping.`),null;const s=nr(e.apiUrl),i=nr(e.model),o=nr(e.inputPlaceholder),l=typeof e.notes=="string"?e.notes.trim():void 0;let c=nr(e.description)||nr(e.summary);if(!c&&typeof l=="string"){const u=l.split(/\r?\n/).find(f=>f.trim().length>0);c=u?u.trim():void 0}const d={id:n,name:r};return s&&(d.apiUrl=s),c&&(d.description=c),l&&(d.notes=l),i&&(d.model=i),o&&(d.inputPlaceholder=o),d},co=t=>Array.isArray(t)?t.map(gf).filter(e=>e!==null):[];let Kt=null,mn=0;const xf=3e4;function bf(){if(typeof window<"u"){const t=window.ORBIT_CHAT_CONFIG;if(t!=null&&t.adapters&&Array.isArray(t.adapters)){D("Loading adapters from window.ORBIT_CHAT_CONFIG");const e=co(t.adapters);if(e.length===0)return null;const r=`{
347
- "simple-chat": "default-key",
348
- "dialoga": "orbit_GOQzNNaC9uB0uNh5LrOCdlmPI0OHXnMz",
349
- "web-search": "orbit_XfxmYoTZgnp7zoMTKsIBfMBuYwj6U21P",
350
- "chat-with-files": "multimodal",
351
- "hr-db-chatbot": "human-resources",
352
- "intent-sql-sqlite-classified": "classified",
353
- "ecomm-analytics": "analytical",
354
- "intent-duckdb-ev-population": "electric-vehicle",
355
- "intent-http-jsonplaceholder": "rest-json-api",
356
- "intent-http-paris-opendata": "paris-opendata",
357
- "intent-mongodb-mflix": "mongodb-mflix",
358
- "intent-graphql-spacex": "graphql-spacex",
359
- "intent-sql-postgres": "postgres-customer-orders",
360
- "open-ai-real-time-voice-chat": "open-ai-real-time-voice-chat",
361
- "composite-multi-source-explorer": "composite-multi-source-explorer",
362
- "math-teacher-quadratic": "math-teacher-trig-identities",
363
- "qa-sql": "orbit_g6QuN5sPUh3fI2v0njoOJroXbAh1ILGP",
364
- "qa-vector-chroma": "orbit_Rxm90sh85f8l5bzOLJpqpMUP9HcoNAX3",
365
- "image-generator": "orbit_bZQ0h6kvpTphfCr9QgrCP13dkVclAsKQ",
366
- "video-generator": "orbit_9P1vnx1GNMvVNyNCKF71VvVvcYx9duuo",
367
- "intent-elasticsearch-log": "orbit_Ghpo8Q9mRdvVIODdw97ht7lBPpYBAzb6",
368
- "audio-transcription": "orbit_RTBIwFoB6DA2mBuuHfnKf0xabwE6XKs2",
369
- "voice-chat": "orbit_WjrkTqVjHE7mBa2ri8sAjENEVnLT9wbO",
370
- "real-time-voice-chat": "orbit_xkvziKTXpZ1ufHWKg76pUDPbMDBRSRqC",
371
- "tender-notices": "tender-notices",
372
- "award-notices": "award-notices",
373
- "contract-history": "contract-history",
374
- "standing-offers": "standing-offers"
375
- }`;if(!r.trim())return[];try{const n=JSON.parse(r),s=new Set(Object.entries(n).filter(([,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=>s.has(i.id))}catch{return[]}}}return null}async function qn(){if(Kt&&Date.now()-mn<xf)return Kt;try{const e=await fetch("/api/adapters?refresh=1",{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(e.ok){const r=await e.json(),n=co(r.adapters);if(n.length>0)return Kt=n,mn=Date.now(),D("Fetched adapters from /api/adapters:",Kt),Kt;D("/api/adapters response did not contain valid adapters, trying fallback")}D(`/api/adapters returned ${e.status}, trying fallback`)}catch(e){D("Could not fetch from /api/adapters, trying fallback:",e)}const t=bf();if(t&&t.length>0)return Kt=t,mn=Date.now(),D("Loaded adapters from config:",Kt),Kt;throw pe("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 yf="h-[96px]";function wf({onAdapterSelect:t,className:e="",title:r="",subtitle:n="",eyebrow:s=""}){const{t:i}=Le(),[o,l]=m.useState([]),[c,d]=m.useState(!0),[u,f]=m.useState(null),p=m.useRef(null),g=m.useRef(null),[h,x]=m.useState(""),[y,k]=m.useState(!1),C=m.useCallback(()=>{const A=p.current;if(!A){k(!1);return}k(A.scrollHeight-A.scrollTop-A.clientHeight>20)},[]),L=()=>typeof window<"u"&&window.matchMedia("(min-width: 768px)").matches,N=()=>{var A;return Array.from(((A=p.current)==null?void 0:A.querySelectorAll('[data-agent-card="true"]'))??[])},v=A=>{const z=N()[A]??null;z&&(z.focus(),z.scrollIntoView({block:"nearest"}))},T=()=>{v(0)},_=()=>{const A=N();A.length!==0&&v(A.length-1)},b=A=>{if(!c&&!u&&I.length>0&&L()){if(A.key==="Tab"&&!A.shiftKey){A.preventDefault(),T();return}if(A.key==="ArrowDown"){A.preventDefault(),T();return}A.key==="ArrowUp"&&(A.preventDefault(),_())}},$=A=>{var W;if(!O||!L()||A.key!=="ArrowDown"&&A.key!=="ArrowUp")return;const E=document.activeElement;if(!(E instanceof HTMLElement)||E.dataset.agentCard!=="true")return;const z=N(),S=z.indexOf(E);if(S!==-1){if(A.preventDefault(),A.key==="ArrowDown"){v((S+1)%z.length);return}if(S===0){(W=g.current)==null||W.focus();return}v(S-1)}},j=h.trim().toLowerCase(),I=j?o.filter(A=>{var W,K;const E=A.name.toLowerCase().includes(j),z=((W=A.description)==null?void 0:W.toLowerCase().includes(j))??!1,S=((K=A.model)==null?void 0:K.toLowerCase().includes(j))??!1;return E||z||S}):o,O=h.trim().length>0,R=O||I.length===1;m.useEffect(()=>{const A=p.current;if(A)return C(),A.addEventListener("scroll",C,{passive:!0}),()=>A.removeEventListener("scroll",C)},[C,I]),m.useEffect(()=>{let A=!0;return(async()=>{try{d(!0),f(null);const S=(await qn()).slice().sort((W,K)=>W.name.localeCompare(K.name,void 0,{sensitivity:"base"}));A&&l(S)}catch(z){pe("[AgentSelectionList] Failed to load adapters",z),A&&f(i("agentSelectionList.unableToLoad"))}finally{A&&d(!1)}})(),()=>{A=!1}},[i]),m.useEffect(()=>{var A;c||u||o.length===0||(A=g.current)==null||A.focus()},[c,u,o.length]);const H=()=>c?a.jsx("div",{className:"grid gap-4",children:Array.from({length:3}).map((A,E)=>a.jsx("div",{className:`${yf} animate-pulse rounded-2xl border border-gray-200 bg-transparent dark:border-[#3b3c49]`},E))}):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")}):I.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:$,className:"agent-selection-scroll flex-1 min-h-0 overflow-y-auto pr-1 pb-2",children:R?a.jsx("div",{className:"mx-auto flex w-full max-w-xl flex-col gap-3 lg:max-w-2xl",children:I.map(A=>a.jsx(ai,{adapter:A,onSelect:E=>t(E.id)},A.id))}):a.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:I.map(A=>a.jsx(ai,{adapter:A,onSelect:E=>t(E.id)},A.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:[(s||r||n)&&a.jsxs("div",{className:"flex-shrink-0",children:[s&&a.jsx("p",{className:"text-sm font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-300",children:s}),r&&a.jsx("h2",{className:"mt-2 text-2xl font-bold text-gray-900 dark:text-white",children:r}),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(Ls,{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:g,type:"text",placeholder:i("agentSelectionList.searchPlaceholder"),value:h,maxLength:100,disabled:c||!!u||o.length===0,onChange:A=>x(A.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"}),h&&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(Ge,{className:"h-3.5 w-3.5"})})]})})}),a.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:H()})]})}function _n(){return Dn()?zs()==="entra"?a.jsx(vf,{}):a.jsx(kf,{}):null}function kf(){const{user:t,logout:e,loginWithRedirect:r}=Fn();if(!kr()||!t)return a.jsx(uo,{onClick:()=>r()});const s=t.name||t.email||"User";return a.jsx(fo,{displayName:s,onClick:()=>e({logoutParams:{returnTo:window.location.origin}})})}function vf(){const{instance:t,accounts:e}=Mn();if(!kr()||e.length===0)return a.jsx(uo,{onClick:()=>t.loginRedirect({scopes:Un()}).catch(()=>{})});const n=e[0],s=n.name||n.username||"User";return a.jsx(fo,{displayName:s,onClick:()=>t.logoutRedirect({postLogoutRedirectUri:window.location.origin}).catch(()=>{})})}function uo({onClick:t}){const{t:e}=Le();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(zi,{className:"h-4 w-4"}),a.jsx("span",{children:e("common.signIn")})]})}function fo({displayName:t,onClick:e}){const{t:r}=Le();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:r("authStatus.signOutButton.title"),"aria-label":r("authStatus.signOutButton.ariaLabel"),children:[a.jsx(rd,{className:"h-4 w-4"}),a.jsx("span",{className:"hidden md:inline",children:r("common.logOut")})]})]})}function mo({placement:t="default",compact:e=!1}){const{t:r}=Le();if(!Mi())return null;const n=Tc(),s=Mc(),i=Fc(),o=$c(),l=Pc(),c=Rc(),d=Uc(),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",g="justify-center",h=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:s||void 0,color:i||void 0},children:a.jsx("div",{className:h,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":r("appFooter.navLinksAriaLabel"),children:a.jsx("ul",{className:`flex flex-wrap items-center ${g} ${e?"gap-1":"gap-1.5 sm:gap-2"}`,children:d.map((k,C)=>{const L=l==="inline"&&C>0;return a.jsxs("li",{className:"flex items-center",children:[L&&a.jsx("span",{className:"mr-1.5 text-slate-400 dark:text-slate-500","aria-hidden":"true",children:"·"}),a.jsx("a",{href:k.url,target:"_blank",rel:"noopener noreferrer",className:y,style:{color:i||void 0},children:k.label})]},k.url)})})})]})})})})}const Sf=60*1e3;let hn=null,ii=0;const pn=t=>{if(!t||t==="/")return"/";const e=t.trim();if(!e)return"/";const r=e.startsWith("/")?e:`/${e}`;return r==="/"?"/":r.endsWith("/")?r.slice(0,-1):r},ho=()=>{if(typeof window>"u")return pn("/");const t=pn("/");if(typeof document>"u")return t;const e=document.querySelector("base[href]");if(!e)return t;try{const r=new URL(e.getAttribute("href")||"/",window.location.origin);return pn(r.pathname||t)}catch{return t}},Ps=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),jf=async()=>{const t=Date.now();if(hn&&t-ii<Sf)return hn;let e=[];try{e=await qn()}catch(n){be("[agentRouting] Unable to load adapters for slug resolution",n)}const r=new Map;return e.forEach(n=>{const s=Ps(n.name);s&&r.set(s,n.id);const i=Ps(n.id);i&&i!==s&&r.set(i,n.id)}),hn=r,ii=t,r},Tn=t=>{var i;const e=ho(),r=t.startsWith("/")?t:`/${t}`;let n=r;if(e!=="/"){if(!r.startsWith(e))return null;n=r.slice(e.length)}const s=n.split("/").filter(Boolean);return s.length===0?null:((i=s[0])==null?void 0:i.toLowerCase())||null},po=t=>{const e=ho();if(!t)return e;const r=t.replace(/^\/+|\/+$/g,"");return e==="/"?r?`/${r}`:"/":`${e}/${r}`.replace(/\/{2,}/g,"/")},At=t=>{if(typeof window>"u")return;const e=po(t),r=window.location.pathname;if(e===r)return;const n=window.location.search||"",s=window.location.hash||"";window.history.replaceState(window.history.state,"",`${e}${n}${s}`)},Cf=()=>po(null),Af=async t=>{const e=t.trim().toLowerCase();return e&&(await jf()).get(e)||null};function Nf({currentConversation:t,showEmptyState:e,createConversation:r,configureApiSettings:n,clearError:s,clearCurrentConversationAdapter:i}){var ge;const{t:o}=Le(),l=o("agent.error.singleAdapterMissing"),[c,d]=m.useState(!1),[u,f]=m.useState(null),p=Os(),g=$n(),h=typeof window<"u"?Tn(window.location.pathname):null,[x,y]=m.useState(h),[k,C]=m.useState(()=>!p&&e&&!h),L=m.useRef(null),N=m.useRef(new Map),v=m.useRef(0),T=3e4,_=!!t,b=(t==null?void 0:t.messages.length)??0,$=((ge=t==null?void 0:t.attachedFiles)==null?void 0:ge.length)??0,j=m.useMemo(()=>_&&(b>0||$>0),[$,b,_]),I=m.useCallback(()=>{qe(()=>ye.getState())},[]),O=m.useCallback((V,Y)=>{if(!V)return;const ie=Y||o("agent.error.configurationFailed");let xe=!1;ye.setState(fe=>{const ae=fe.conversations.find(re=>re.id===V);return!ae||ae.messages.length>0?fe:(xe=!0,{conversations:fe.conversations.map(re=>re.id===V?{...re,adapterLoadError:ie}:re)})}),xe&&I()},[I,o]),R=m.useCallback(V=>{if(!V)return;let Y=!1;ye.setState(ie=>{const xe=ie.conversations.find(fe=>fe.id===V);return!xe||!xe.adapterLoadError?ie:(Y=!0,{conversations:ie.conversations.map(fe=>fe.id===V?{...fe,adapterLoadError:null}:fe)})}),Y&&I()},[I]),H=m.useCallback(V=>V instanceof Zi?V.status===401?o("agent.error.authenticationFailed"):V.status===404?o("agent.error.notFound"):V.message:V instanceof Error?V.message:o("agent.error.loadFailed"),[o]),A=m.useCallback(()=>{const V=ye.getState(),Y=V.currentConversationId?V.conversations.find(ie=>ie.id===V.currentConversationId):null;if(!Y||Y.messages.length>0)try{return r()}catch(ie){be("Cannot create a new conversation for agent selection:",ie instanceof Error?ie.message:"Unknown error")}return(Y==null?void 0:Y.id)||null},[r]),E=m.useCallback(async V=>{if(!(V!=null&&V.adapterName))return{ok:!1};try{const Y=await Me(),ie=new Y.ApiClient({apiUrl:V.apiUrl||Fe(),sessionId:null,adapterName:V.adapterName});if(typeof ie.getAdapterInfo!="function")return{ok:!1};const xe=await ie.getAdapterInfo();return ye.setState(fe=>({conversations:fe.conversations.map(ae=>ae.id===V.id?{...ae,adapterInfo:xe,adapterLoadError:null,updatedAt:new Date}:ae)})),ye.getState().currentConversationId===V.id&&f(null),I(),{ok:!0}}catch(Y){const ie=H(Y),xe=ye.getState();xe.currentConversationId===V.id&&f({conversationId:V.id,message:ie});const fe=xe.conversations.find(ae=>ae.id===V.id);return fe&&fe.messages.length===0&&O(V.id,ie),{ok:!1,error:Y}}},[H,O,I]),z=m.useCallback(async V=>{if(!V)return;const Y=ye.getState(),ie=Y.currentConversationId?Y.conversations.find(xe=>xe.id===Y.currentConversationId):null;if(ie){d(!0),f(null),R(ie.id);try{const xe=ie.apiUrl||Fe();await n(xe,void 0,V),s();const fe=ye.getState(),ae=fe.conversations.find(re=>re.id===fe.currentConversationId);if((ae==null?void 0:ae.adapterName)===V&&(!ae.adapterInfo||ae.adapterInfo.notes===void 0)){const re=await E(ae);!re.ok&&re.error&&pe("Failed to load adapter info after selecting adapter:",re.error)}}catch(xe){pe("Failed to configure adapter from empty state:",xe);const fe=H(xe);f({conversationId:ie.id,message:fe}),O(ie.id,fe)}finally{d(!1)}}},[R,s,n,E,H,O]),S=m.useCallback(V=>{p||(A(),C(!1),At(Ps(V)),z(V))},[A,z,p]),W=m.useCallback(()=>{p||(i(),At(null),C(!0))},[i,p]),K=m.useCallback(()=>{var xe,fe;if(p){const ae=ye.getState(),re=ae.currentConversationId?ae.conversations.find(Ee=>Ee.id===ae.currentConversationId):null;if(!!re&&(re.messages.length>0||(((xe=re.attachedFiles)==null?void 0:xe.length)||0)>0))try{r()}catch(Ee){be("Cannot go home (new conversation):",Ee instanceof Error?Ee.message:"Unknown error")}At(null),C(!1);return}y(null);const V=ye.getState(),Y=V.currentConversationId?V.conversations.find(ae=>ae.id===V.currentConversationId):null;if(!!Y&&(Y.messages.length>0||(((fe=Y.attachedFiles)==null?void 0:fe.length)||0)>0))try{r()}catch(ae){be("Cannot go home (new conversation):",ae instanceof Error?ae.message:"Unknown error");return}else Y!=null&&Y.adapterName&&i();At(null),C(!0)},[i,r,p]),G=!p&&e&&!x&&!(t!=null&&t.adapterName)&&!j||!p&&e&&k&&!(t!=null&&t.adapterName)&&!j;m.useEffect(()=>{if(p){At(null);return}if(!x){if(G||!(t!=null&&t.adapterName)){At(null);return}At(Ps(t.adapterName))}},[t==null?void 0:t.adapterName,p,x,G]);const te=m.useCallback(async()=>{if(typeof window>"u")return;const V=++v.current;if(p){At(null),y(null);return}const Y=Tn(window.location.pathname);if(!Y)return;const ie=await Af(Y);if(V===v.current){if(!ie){A(),At(null),i(),C(!0),y(null);return}A(),C(!1),At(Y),await z(ie),y(null)}},[i,A,z,p]),Ce=m.useRef(te);m.useEffect(()=>{Ce.current=te},[te]),m.useEffect(()=>{const V=window.setTimeout(()=>{Ce.current()},0),Y=()=>{Ce.current()};return window.addEventListener("popstate",Y),()=>{window.clearTimeout(V),v.current+=1,window.removeEventListener("popstate",Y)}},[]);const M=t==null?void 0:t.id,ee=t==null?void 0:t.adapterName,Q=t==null?void 0:t.apiUrl,J=!!(t!=null&&t.adapterInfo);m.useEffect(()=>{if(!p||!g||!e||!M||j||c)return;const V=(ee==null?void 0:ee.trim())||g,Y=(ee==null?void 0:ee.trim())!==V||!J;if(!V||!Y)return;let ie=!1;return(async()=>{d(!0),f(null),R(M);try{const fe=Q||Fe();await n(fe,void 0,V),s()}catch(fe){if(!ie){const ae=H(fe);f({conversationId:M,message:ae}),O(M,ae)}}finally{ie||d(!1)}})(),()=>{ie=!0}},[R,s,n,j,H,c,p,O,e,ee,Q,J,M,g]),m.useEffect(()=>{(async()=>{const Y=t==null?void 0:t.adapterName,ie=t?`${t.id}:${Y}`:null;if(!(!ie||L.current===ie))if(Y){L.current=ie,D("[ChatInterface] Refreshing adapter info from the backend - adapterName:",Y);const xe=await E(t);if(xe.ok)D("[ChatInterface] Adapter info loaded successfully");else{const fe=xe.error;pe("[ChatInterface] Failed to load adapter info:",fe);const ae=fe instanceof Error?fe.message:String(fe);if((ae.includes("429")||ae.includes("Too Many Requests"))&&Y){const Pe=N.current.get(ie);Pe&&clearTimeout(Pe);const Ee=setTimeout(()=>{L.current===ie&&(L.current=null),N.current.delete(ie)},T);N.current.set(ie,Ee),be(`[ChatInterface] Adapter info request rate-limited; retrying in ${T/1e3}s`)}else L.current=null}}else D("[ChatInterface] Skipping adapter info refresh: no adapter selected")})()},[E,t]),m.useEffect(()=>{const V=N.current;return()=>{V.forEach(Y=>clearTimeout(Y)),V.clear()}},[]);const le=p&&!g?l:(t==null?void 0:t.adapterLoadError)??(u&&u.conversationId===(t==null?void 0:t.id)?u.message:null);return{adapterNotesError:le,handleAgentCardSelection:S,handleChangeAgent:W,goToAgentSelectionHome:K,hasAdapterConfigurationError:!!le,isAgentSelectionVisible:k,isConfiguringAdapter:c,isSingleAdapterMode:p,setIsAgentSelectionVisible:C,shouldShowAgentSelectionList:G}}const go=m.createContext(null),If={registerGoHome:()=>{},goHome:()=>{}};function xo(){return m.useContext(go)??If}function Lf({adapter:t,syntaxTheme:e,forcedThemeClass:r=""}){var s;const n=(s=t.notes)==null?void 0:s.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(Dt,{content:n,className:`message-markdown prose prose-slate dark:prose-invert max-w-none text-sm leading-relaxed text-[#434654] dark:text-[#d7dae3] [&>:first-child]:mt-0 [&>:last-child]:mb-0 ${r}`,syntaxTheme:e})})]}):null}const Ef='meta[name="description"]',_f='meta[property="og:title"]',Tf='meta[property="og:description"]',Mf='meta[property="og:type"]',Ff='link[rel="canonical"]';function oi(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function $f(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 Pf(t,e){const r=t==null?void 0:t.trim();if(r)return r;if(!e)return Rn();const n=$f(e);return n.length>160?`${n.slice(0,157).trimEnd()}...`:n}function Rf(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Df(t){const e=t.trim();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Uf(t){const e=t.trim();if(!e)return null;const r=`^${Rf(e).replace(/\\\*/g,".*")}$`;try{return new RegExp(r,"i")}catch{return null}}function Of(t){return[Ii(),...cc()].map(Df).filter(r=>!!r).includes(t)?!0:dc().some(r=>{const n=Uf(r);return n?n.test(t):!1})}function zf(t){var n,s,i;const e=t==null?void 0:t.trim();if(!e)return null;const r=Z.adapters.find(o=>{var l;return((l=o==null?void 0:o.id)==null?void 0:l.trim())===e});return r?{id:r.id,name:((n=r.name)==null?void 0:n.trim())||r.id,description:((s=r.description)==null?void 0:s.trim())||void 0,notes:((i=r.notes)==null?void 0:i.trim())||void 0}:null}function Bf(t){var n,s,i;if(typeof window>"u")return null;const e=Tn(window.location.pathname);if(!e)return null;const r=Z.adapters.find(o=>{const l=oi(o.name||""),c=oi(o.id||"");return e===l||e===c});return r?{id:r.id,name:((n=r.name)==null?void 0:n.trim())||r.id,description:((s=r.description)==null?void 0:s.trim())||void 0,notes:((i=r.notes)==null?void 0:i.trim())||void 0}:null}function ws(t,e,r){if(typeof document>"u")return null;const n=document.querySelector(t);if(n)return n;const s=document.createElement("meta");return s.setAttribute(e,r),document.head.appendChild(s),s}function Hf(){if(typeof document>"u")return null;const t=document.querySelector(Ff);if(t)return t;const e=document.createElement("link");return e.rel="canonical",document.head.appendChild(e),e}function bo(t){if(typeof document>"u")return;const e=Pn(),r=t?`${t.name} | ${e}`:e,n=t?Pf(t.description,t.notes):Rn();document.title=r;const s=ws(Ef,"name","description");s&&(s.content=n);const i=ws(_f,"property","og:title");i&&(i.content=r);const o=ws(Tf,"property","og:description");o&&(o.content=n);const l=ws(Mf,"property","og:type");l&&(l.content="website");const c=Hf();if(c&&typeof window<"u"){const d=Ii(),u=window.location.origin,f=d?new URL(d.endsWith("/")?d:`${d}/`).origin:"",g=`${u&&Of(u)?u:f||u}${window.location.pathname}`;c.href=g}}function Vf(){return uc()}class Wn{static async getAdapterModels(e,r){const n=await Me(),s=new n.ApiClient({apiUrl:"",adapterName:r});if(!s.getAdapterModels)throw new Error("getAdapterModels is not available on this API client");return s.getAdapterModels(e)}static async getAllModels(e){const r=await Me(),n=new r.ApiClient({apiUrl:"",adapterName:e});if(!n.getAllModels)throw new Error("getAllModels is not available on this API client");return n.getAllModels()}static async listAdapterModels(e,r){return(await Wn.getAdapterModels(e,r)).models}}const qf="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",Wf="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",Kf="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 Gf({onOpenSettings:t,onOpenSidebar:e}){var vt,cr,We,St,Ut,Se,xt;const{t:r}=Le(),{conversations:n,currentConversationId:s,createConversation:i,canCreateNewConversation:o,sendMessage:l,regenerateResponse:c,editMessageAndRegenerate:d,isLoading:u,configureApiSettings:f,error:p,clearError:g,createThread:h,clearCurrentConversationAdapter:x}=ye(),{settings:y}=Ds(),k=kr(),C=tt()&&!k,{theme:L,isDark:N}=lr(),v=L.mode==="dark"?"dark":L.mode==="light"?"light":"",T=N?"dark":"light",_=["application-description agent-home-markdown prose prose-slate dark:prose-invert max-w-none text-sm md:text-base leading-relaxed","text-[#4a4c5a] dark:text-[#bfc2cd]","[&>:first-child]:mt-0 [&>:last-child]:mb-0",v].filter(Boolean).join(" "),b=n.find(me=>me.id===s),$=n.some(me=>{var ve;return(me.messages.length>0||(((ve=me.attachedFiles)==null?void 0:ve.length)||0)>0)&&!me.adapterLoadError}),j=!b||b.messages.length===0,I=((vt=b==null?void 0:b.adapterInfo)==null?void 0:vt.supportsThreading)===!0,O=!!(b!=null&&b.adapterName&&(b!=null&&b.adapterInfo))&&!I,R=Ji({adapterName:b==null?void 0:b.adapterName,enabled:O,selectionScopeKey:s,supportsThreading:I}),H=Ni(),A=Pn(),E=Rn().trim(),z=E.length>0,{registerGoHome:S}=xo(),[W,K]=m.useState([]),[q,G]=m.useState(null);m.useEffect(()=>{const me=b==null?void 0:b.adapterName;let ve=!1;async function Te(){if(G(null),!me){K([]);return}try{const De=await Wn.listAdapterModels(me,me);if(ve)return;K(De),G(De.length>0?De[0].name:null)}catch{ve||(K([]),G(null))}}return Te(),()=>{ve=!0}},[b==null?void 0:b.adapterName]);const{adapterNotesError:te,handleAgentCardSelection:Ce,handleChangeAgent:M,goToAgentSelectionHome:ee,hasAdapterConfigurationError:Q,isAgentSelectionVisible:J,isConfiguringAdapter:le,isSingleAdapterMode:ge,shouldShowAgentSelectionList:V}=Nf({currentConversation:b,showEmptyState:j,createConversation:i,configureApiSettings:f,clearError:g,clearCurrentConversationAdapter:x});m.useLayoutEffect(()=>(S(()=>ee()),()=>S(null)),[S,ee]);const Y="max-w-[96rem]",ie="max-w-[64rem]",xe="max-w-[56rem]",fe=`mx-auto w-full ${Y}`,ae=o(),re=!!(b!=null&&b.adapterName)&&((b==null?void 0:b.messages.length)||0)===0,Pe=r(ae?"chatInterface.newConversation.tooltipCanStart":C?"chatInterface.newConversation.tooltipGuestLimited":"chatInterface.newConversation.tooltipCannotStart"),Ee=!!(b&&!V),_e=V?"border-transparent dark:border-transparent md:border-transparent md:dark:border-transparent":"",Oe=!Sn()&&V?"pt-0 pb-0 md:pt-0 md:pb-1":"",B=`${Kf} ${_e} ${Oe}`.trim(),de=Mi(),Ie=n.some(me=>{var ve;return(me.messages.length>0||(((ve=me.attachedFiles)==null?void 0:ve.length)??0)>0)&&!me.adapterLoadError}),we=de&&!Ie,Ye=V?"pt-0 md:pt-0":"pt-4 md:pt-6",Lt=m.useMemo(()=>{var De,se,bt;if(V)return null;const me=zf(b==null?void 0:b.adapterName)||Bf();if(!me&&!(b!=null&&b.adapterName))return null;const ve=(De=b==null?void 0:b.adapterName)==null?void 0:De.trim(),Te=(bt=(se=b==null?void 0:b.adapterInfo)==null?void 0:se.notes)==null?void 0:bt.trim();return me?{...me,notes:Te||me.notes}:ve?{id:ve,name:ve,notes:Te||void 0}:null},[(cr=b==null?void 0:b.adapterInfo)==null?void 0:cr.notes,b==null?void 0:b.adapterName,V]);m.useEffect(()=>{bo(Lt)},[Lt]),m.useEffect(()=>{let me=null;const ve=()=>{me&&(me(),me=null)};if(y.voiceEnabled){if(Xt.isAudioEnabled())return D("[ChatInterface] Audio streaming already enabled"),ve;const Te=()=>{ve();const De=async()=>{ve(),await Xt.enableAudio()?D("[ChatInterface] Audio streaming enabled after user gesture"):(be("[ChatInterface] User gesture did not enable audio streaming"),Te())};document.addEventListener("pointerdown",De,{once:!0}),document.addEventListener("keydown",De,{once:!0}),me=()=>{document.removeEventListener("pointerdown",De),document.removeEventListener("keydown",De)},D("[ChatInterface] Waiting for user gesture to enable audio streaming")};return Te(),ve}return ve(),Xt.disableAudio(),D("[ChatInterface] Audio streaming disabled via settings"),ve},[y.voiceEnabled]);const Ae=(me,ve,Te,De)=>{var se;l(me,ve,Te,q??((se=b==null?void 0:b.adapterInfo)==null?void 0:se.model)??void 0,De)},ot=async(me,ve,Te,De,se)=>{var bt;await l(Te,void 0,me,se??q??((bt=b==null?void 0:b.adapterInfo)==null?void 0:bt.model)??void 0,De)},vr=()=>{try{i()}catch(me){be("Cannot create new conversation:",me instanceof Error?me.message:"Unknown error")}},gt=m.useCallback(async(me,ve)=>{if(b)try{await ye.getState().deleteThread(b.id,me,ve)}catch(Te){pe("Failed to clear thread:",Te)}},[b]);return a.jsx("main",{className:"flex-1 flex flex-col bg-transparent overflow-hidden","aria-label":r("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 ${Y} flex-col overflow-hidden md:pb-4 ${qf}`,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:g,className:"ml-4 rounded p-1 text-red-500 hover:bg-red-100 hover:text-red-700 dark:text-red-200 dark:hover:bg-red-800/40","aria-label":r("chatInterface.error.dismissAriaLabel"),children:"×"})]})}),a.jsxs("div",{className:B,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:!$,className:`inline-flex items-center justify-center gap-1.5 rounded-lg border px-3 py-2 text-xs font-semibold shadow-sm transition-all duration-150 ${$?"border-white/50 bg-white/80 text-gray-800 active:scale-[0.97] hover:bg-white dark:border-[#2f303d] dark:bg-[#232430] dark:text-[#ececf1]":"cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400 shadow-none dark:border-[#2f303d] dark:bg-[#181922] dark:text-[#6b6f7a]"}`,"aria-label":r("chatInterface.mobile.openChatsMenuAriaLabel"),children:[a.jsx(nd,{className:"h-4 w-4"}),r("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":r("chatInterface.mobile.openSettingsAriaLabel"),children:[a.jsx(Ma,{className:"h-4 w-4"}),r("chatInterface.mobile.settingsButton")]})]}),a.jsx("div",{className:"ml-auto flex-shrink-0",children:a.jsx(_n,{})})]}),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:Ee&&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)||r("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:r("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":r("chatInterface.settings.ariaLabel"),title:r("chatInterface.settings.title"),children:a.jsx(Ma,{className:"h-4 w-4"})})}),!ge&&!V&&!!(b!=null&&b.adapterName)&&a.jsx("button",{type:"button",onClick:()=>{re&&M()},disabled:!re,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 ${re?"border-blue-300 text-blue-700 hover:bg-blue-50 hover:border-blue-400 focus-visible:ring-blue-500 dark:border-blue-500/40 dark:text-blue-300 dark:hover:bg-blue-900/20 dark:hover:border-blue-400/60 dark:focus-visible:ring-blue-400/60":"cursor-not-allowed border-gray-200 text-gray-400 bg-transparent dark:border-[#3c3f4a] dark:text-[#6b6f7a]"}`,title:r(re?"chatInterface.changeAgent.titleEnabled":"chatInterface.changeAgent.titleDisabled"),children:r("chatInterface.changeAgent.button")}),!V&&a.jsxs("button",{onClick:vr,disabled:!ae,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 ${ae?"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:Pe,children:[a.jsx(pd,{className:"h-3.5 w-3.5"}),r("chatInterface.newConversation.button")]}),!Sn()&&a.jsx("div",{className:"order-4 hidden flex-shrink-0 items-center md:inline-flex",children:a.jsx(_n,{})})]})]})]}),j?a.jsxs("div",{className:`flex flex-1 flex-col min-h-0 ${Ye} ${V?"overflow-hidden":""}`,children:[V?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:`${fe} 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(Dt,{content:A,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:T}),z&&a.jsx("div",{className:"mt-2",children:a.jsx(Dt,{content:E,className:_,syntaxTheme:T})})]})}),a.jsx(wf,{onAdapterSelect:Ce,className:`${fe} 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 ${xe} flex-col items-center gap-4 pb-8 md:gap-5 md:pb-12`,children:[te?a.jsx("p",{className:"w-full text-center text-sm text-red-600 dark:text-red-400",children:te}):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:oc(b.adapterName)||b.adapterName}):le?a.jsx("p",{className:"w-full text-center text-sm text-gray-500 dark:text-[#bfc2cd]",children:r("chatInterface.empty.configuringAgent")}):null,Lt&&Vf()&&a.jsx(Lf,{adapter:Lt,syntaxTheme:T,forcedThemeClass:v}),a.jsx("div",{className:"w-full min-w-0",children:a.jsx(ni,{onSend:Ae,disabled:u||!b||!(b!=null&&b.adapterName)||Q,autoFocusEnabled:!0,desktopOnlyAutoFocus:ge,placeholder:H,isCentered:!0,maxWidthClass:xe,adapterNotes:(We=b==null?void 0:b.adapterInfo)==null?void 0:We.notes,skillState:R,availableModels:W,defaultModel:((St=b==null?void 0:b.adapterInfo)==null?void 0:St.model)??null,selectedModel:q,onSelectModel:G})})]})}),we&&a.jsx("div",{className:"shrink-0 pt-5 md:pt-6",children:a.jsx(mo,{compact:!0})})]}):a.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[a.jsx(Xu,{messages:b.messages,onRegenerate:me=>{var ve;return c(me,q??((ve=b==null?void 0:b.adapterInfo)==null?void 0:ve.model)??void 0)},onEditMessage:(me,ve)=>{var Te;return d(me,ve,q??((Te=b==null?void 0:b.adapterInfo)==null?void 0:Te.model)??void 0)},onStartThread:async(me,ve)=>{try{await h(me,ve)}catch(Te){pe("Failed to create thread:",Te)}},onClearThread:gt,onSendThreadMessage:ot,sessionId:b.sessionId,isLoading:u,contentMaxWidthClass:ie,availableModels:W,defaultModel:((Ut=b==null?void 0:b.adapterInfo)==null?void 0:Ut.model)??null,selectedModel:q}),a.jsx("div",{className:Wf,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(ni,{onSend:Ae,disabled:u||!b||!b.adapterName||J||Q,autoFocusEnabled:!0,placeholder:r("chatInterface.docked.placeholder"),maxWidthClass:ie,isCentered:!1,adapterNotes:(Se=b==null?void 0:b.adapterInfo)==null?void 0:Se.notes,skillState:R,availableModels:W,defaultModel:((xt=b==null?void 0:b.adapterInfo)==null?void 0:xt.model)??null,selectedModel:q,onSelectModel:G})})})]})]})})})}function Xf({selectedAdapter:t,onAdapterChange:e,disabled:r,showDescriptions:n=!1,variant:s="sidebar",label:i,showLabel:o}){const{t:l}=Le(),[c,d]=m.useState([]),[u,f]=m.useState(!0),[p,g]=m.useState(null),[h,x]=m.useState(!1);m.useEffect(()=>{let $=!0;async function j(){try{f(!0),g(null);const I=await qn();$&&d(I)}catch(I){pe("Failed to load adapters:",I),$&&g(l("adapterSelector.failedToLoad"))}finally{$&&f(!1)}}return j(),()=>{$=!1}},[l]);const y=c.find($=>$.id===t),k=typeof o=="boolean"?o:s==="prominent",C=i||l(s==="prominent"?"adapterSelector.selectAnAgent":"adapterSelector.defaultLabel"),L=m.useMemo(()=>s==="prominent"?"relative w-full text-left":"relative w-full",[s]),N=m.useMemo(()=>{const $="w-full rounded-md border bg-white px-4 py-3 text-left text-sm text-[#353740] focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 dark:bg-[#343541] dark:text-[#ececf1]";return s==="prominent"?[$,"border-gray-300 shadow-sm transition-all duration-200 focus-visible:ring-blue-500 dark:border-[#4a4b54] dark:focus-visible:ring-blue-400"].join(" "):["w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-left text-sm text-[#353740] focus:border-gray-400 focus:outline-none dark:border-[#4a4b54] dark:bg-[#343541] dark:text-[#ececf1] dark:focus:border-[#6b6f7a]"].join(" ")},[s]),v=m.useMemo(()=>s==="prominent"?"absolute z-20 mt-2 w-full rounded-xl border border-gray-200 bg-white shadow-xl ring-1 ring-black/5 dark:border-[#4a4b54] dark:bg-[#1f2027]":"absolute z-20 mt-1 w-full rounded-md border border-gray-200 bg-white shadow-lg ring-1 ring-black/5 dark:border-[#4a4b54] dark:bg-[#1f2027]",[s]),b=k?`mb-2 block text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-[#bfc2cd] ${s==="prominent"?"!text-sm !font-semibold !text-gray-700 dark:!text-white":""}`:"sr-only";return a.jsxs("div",{className:L,children:[a.jsx("label",{className:b,children:C}),a.jsxs("div",{className:"relative",children:[a.jsx("button",{type:"button",onClick:()=>!r&&x(!h),disabled:r||u||c.length===0,className:`${N} disabled:opacity-50 disabled:cursor-not-allowed`,"aria-label":C,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")}),s==="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(wr,{className:`h-4 w-4 flex-shrink-0 transition-transform text-gray-400 dark:text-gray-300 ${h?"rotate-180":""}`})]})}),h&&!r&&c.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>x(!1)}),a.jsx("div",{className:v,children:a.jsx("div",{className:"max-h-72 overflow-auto py-2",children:c.map($=>{const j=$.id===t;return a.jsx("button",{type:"button",onClick:()=>{j||e($.id),x(!1)},className:`w-full px-4 py-3 text-left text-sm transition-colors ${j?"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:$.name}),n&&$.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:$.description})]})},$.id)})})})]})]}),p&&a.jsx("p",{className:"mt-1 text-xs text-red-600 dark:text-red-400",children:p})]})}const ks=100;function li({onClick:t,label:e,hoverClassName:r,icon:n}){return a.jsx("button",{onClick:t,className:`rounded-lg p-1.5 text-slate-400 transition-colors dark:text-[#6b6f7a] ${r}`,"aria-label":e,children:n})}function Yf(t,e){const r=new Date(e.getFullYear(),e.getMonth(),e.getDate()),n=new Date(r);n.setDate(n.getDate()-1);const s=new Date(r);s.setDate(s.getDate()-r.getDay());const i=new Date(e.getFullYear(),e.getMonth(),1);return t>=r?"today":t>=n?"yesterday":t>=s?"thisWeek":t>=i?"thisMonth":"earlier"}function Qf(t){const e=new Date,r=["today","yesterday","thisWeek","thisMonth","earlier"],n=new Map;for(const s of t){const i=Yf(s.updatedAt,e),o=n.get(i);o?o.push(s):n.set(i,[s])}return r.filter(s=>n.has(s)).map(s=>({label:s,conversations:n.get(s)}))}function ci({onRequestClose:t,onToggleDesktopSidebar:e}){const{t:r}=Le(),n=Os(),{conversations:s,currentConversationId:i,selectConversation:o,deleteConversation:l,deleteAllConversations:c,updateConversationTitle:d,getConversationCount:u,configureApiSettings:f,clearError:p}=ye(),g=s.find(U=>U.id===i),[h,x]=m.useState(""),[y,k]=m.useState(null),[C,L]=m.useState(""),[N,v]=m.useState({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1}),[T,_]=m.useState({isOpen:!1,isDeleting:!1}),[b,$]=m.useState(!1),[j,I]=m.useState(null),[O,R]=m.useState(!1),[H,A]=m.useState(null),E=m.useRef(null),z=m.useRef(null),S=m.useRef(null),W=!g||g.messages.length===0,K=(j==null?void 0:j.conversationId)===i?j.adapterName:(g==null?void 0:g.adapterName)??null,q=(H==null?void 0:H.conversationId)===i?H.message:null,G=m.useMemo(()=>s.filter(U=>{var B;return(U.messages.length>0||(((B=U.attachedFiles)==null?void 0:B.length)||0)>0)&&!U.adapterLoadError}),[s]),te=m.useMemo(()=>{if(!h)return G;const U=h.toLowerCase();return G.filter(B=>(B.title||r("chatInterface.newChatTitle")).toLowerCase().includes(U)||B.messages.some(de=>de.content.toLowerCase().includes(U))||(B.attachedFiles||[]).some(de=>de.filename.toLowerCase().includes(U)))},[G,h,r]),Ce=m.useMemo(()=>Qf(te),[te]),M=u(),ee=h.length>0,Q=G.length>0;m.useEffect(()=>{if(!i||!z.current)return;const U=z.current.querySelector('[aria-current="true"]');U&&U.scrollIntoView({block:"nearest",behavior:"smooth"})},[i]);const J=m.useCallback(U=>{var Ye;if(U.key!=="ArrowDown"&&U.key!=="ArrowUp")return;U.preventDefault();const B=(Ye=z.current)==null?void 0:Ye.querySelectorAll('[role="option"]');if(!B||B.length===0)return;const de=document.activeElement,Ie=Array.from(B).indexOf(de);let we;U.key==="ArrowDown"?we=Ie<B.length-1?Ie+1:0:we=Ie>0?Ie-1:B.length-1,B[we].focus()},[]),le=async U=>{if(!(!W||!U)){I({conversationId:i??null,adapterName:U}),A(null),R(!0);try{const B=(g==null?void 0:g.apiUrl)||Fe();await f(B,void 0,U),p(),$(!1)}catch(B){pe("Failed to configure adapter:",B),A({conversationId:i??null,message:B instanceof Error?B.message:r("sidebar.adapterConfigureFailed")})}finally{R(!1)}}},ge=async U=>{try{await o(U),t==null||t()}catch(B){pe("Failed to select conversation:",B)}},V=(U,B)=>{U.stopPropagation(),v({isOpen:!0,conversationId:B.id,conversationTitle:B.title||r("chatInterface.newChatTitle"),isDeleting:!1})},Y=async()=>{v(U=>({...U,isDeleting:!0}));try{await l(N.conversationId)}catch(U){pe("Failed to delete conversation:",U)}v({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},ie=()=>{v({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},xe=(U,B)=>{U.stopPropagation(),k(B.id),L((B.title||r("chatInterface.newChatTitle")).slice(0,ks))},fe=U=>{const B=C.slice(0,ks).trim();B&&d(U,B),k(null),L("")},ae=()=>{k(null),L("")},re=()=>{_({isOpen:!0,isDeleting:!1})},Pe=async()=>{_(U=>({...U,isDeleting:!0}));try{await c()}catch(U){pe("Failed to clear all conversations:",U)}_({isOpen:!1,isDeleting:!1})},Ee=()=>{_({isOpen:!1,isDeleting:!1})},_e=U=>{var B,de,Ie;return(B=U.adapterName)!=null&&B.trim()?U.adapterName:(Ie=(de=U.adapterInfo)==null?void 0:de.adapter_name)!=null&&Ie.trim()?U.adapterInfo.adapter_name:null};Hr(E,{enabled:b,onEscape:()=>$(!1)});const Oe=U=>{const B=i===U.id,de=n?null:_e(U),Ie=U.title||r("chatInterface.newChatTitle");return a.jsxs("div",{role:"option","aria-selected":B,tabIndex:0,onKeyDown:we=>{(we.key==="Enter"||we.key===" ")&&(we.preventDefault(),ge(U.id))},onClick:()=>ge(U.id),className:`group relative flex w-full cursor-pointer items-center overflow-hidden rounded-xl border px-3 py-2 text-left text-sm transition-all duration-150
376
- ${B?"border-slate-200/70 bg-[linear-gradient(180deg,rgba(255,255,255,0.97),rgba(248,250,252,0.94))] shadow-[0_1px_2px_rgba(15,23,42,0.04),0_2px_10px_rgba(15,23,42,0.06)] dark:border-white/10 dark:bg-[linear-gradient(180deg,rgba(50,52,65,0.95),rgba(38,39,49,0.92))] dark:shadow-[0_2px_16px_rgba(0,0,0,0.32)]":"border-transparent hover:border-slate-200/60 hover:bg-slate-50 dark:hover:border-white/[0.05] dark:hover:bg-[#212228]"} focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500/50 dark:focus-visible:ring-sky-400/40`,"aria-current":B?"true":void 0,"aria-label":r("sidebar.conversationCard.openAriaLabel",{title:Ie}),children:[B&&a.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 bg-[linear-gradient(180deg,rgba(255,255,255,0.4),rgba(255,255,255,0))] dark:bg-[linear-gradient(180deg,rgba(255,255,255,0.045),rgba(255,255,255,0))]"}),a.jsx("span",{"aria-hidden":"true",className:`absolute inset-y-0 left-0 w-[3px] transition-opacity duration-150 ${B?"bg-sky-500 opacity-100 dark:bg-sky-400":"opacity-0"}`}),y===U.id?a.jsx("input",{type:"text",value:C,onChange:we=>L(we.target.value.slice(0,ks)),onKeyDown:we=>{we.key==="Enter"&&fe(U.id),we.key==="Escape"&&ae(),we.stopPropagation()},onBlur:()=>fe(U.id),maxLength:ks,className:"relative z-10 flex-1 rounded-lg border border-sky-300 bg-white px-2 py-1 text-sm text-[#353740] focus:outline-none focus:ring-2 focus:ring-sky-400/50 dark:border-sky-500/40 dark:bg-[#1a1b1e] dark:text-[#ececf1]",autoFocus:!0,"aria-label":r("sidebar.conversationCard.editInputAriaLabel")}):a.jsxs("div",{className:"relative z-10 flex min-w-0 flex-1 flex-col gap-1",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 tracking-[-0.006em] ${B?"font-semibold text-slate-900 dark:text-[#ececf1]":"font-medium text-slate-700 dark:text-[#c5c8d6]"}`,children:Ie}),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(li,{onClick:we=>xe(we,U),label:r("sidebar.conversationCard.editAriaLabel",{title:Ie}),hoverClassName:"hover:bg-slate-200/80 hover:text-slate-600 dark:hover:bg-[#3c3f4a] dark:hover:text-[#c5c8d6]",icon:a.jsx(Bi,{className:"h-3.5 w-3.5"})}),a.jsx(li,{onClick:we=>V(we,U),label:r("sidebar.conversationCard.deleteAriaLabel",{title:Ie}),hoverClassName:"hover:bg-red-100/80 hover:text-red-600 dark:hover:bg-red-900/30 dark:hover:text-red-400",icon:a.jsx(Wi,{className:"h-3.5 w-3.5"})})]})]}),de&&a.jsx("span",{className:"block max-w-full truncate text-left text-xs font-medium tracking-wide text-blue-700 dark:text-blue-300",children:de})]})]},U.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:E,role:"dialog","aria-modal":"true","aria-labelledby":"select-agent-title",tabIndex:-1,className:"w-full max-w-md rounded-2xl border border-gray-200 bg-white p-6 shadow-2xl dark:border-[#3d4050] dark:bg-[#1a1b1e]",children:[a.jsx("h2",{id:"select-agent-title",className:"mb-4 text-lg font-semibold text-gray-900 dark:text-[#ececf1]",children:r("sidebar.selectAgent.title")}),a.jsxs("div",{className:"space-y-5",children:[a.jsx(Xf,{selectedAdapter:K,onAdapterChange:le,disabled:O,variant:"prominent",showDescriptions:!0,showLabel:!1}),q&&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:q}),a.jsx("div",{className:"flex justify-end gap-3 pt-2",children:a.jsx("button",{type:"button",onClick:()=>{A(null),$(!1)},className:"rounded-lg px-4 py-2 text-sm font-medium text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50 dark:text-[#d1d5db] dark:hover:bg-[#2d2f39]",disabled:O,children:r("common.cancel")})})]})]})}),a.jsxs("nav",{"aria-label":r("sidebar.navAriaLabel"),className:"flex h-full md:h-[calc(100%-2rem)] md:mt-4 w-full md:w-72 flex-col border-r border-b border-gray-200 md:border-l md:border-t md:rounded-2xl md:overflow-hidden bg-transparent dark:border-[#2d2f39]",children:[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:[s.length>0&&s.some(U=>U.messages.length>0)&&a.jsxs("button",{onClick:re,className:"flex flex-1 items-center justify-center gap-2 rounded-lg border border-red-200 px-3 py-2 text-sm font-medium text-red-600 transition-all duration-150 hover:bg-red-50 hover:border-red-300 hover:shadow-sm dark:border-red-500/25 dark:text-red-400 dark:hover:bg-red-950/20 dark:hover:border-red-500/40",title:r("sidebar.deleteAllConversations.title"),children:[a.jsx(wd,{className:"h-4 w-4"}),r("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":r("sidebar.collapse.ariaLabel"),title:r("sidebar.collapse.title"),children:a.jsx(dd,{className:"h-4 w-4"})})]}),q&&!b&&a.jsx("p",{role:"alert",className:"mt-2 text-xs text-red-600 dark:text-red-400",children:q}),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(Ls,{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:S,type:"text",role:"searchbox","aria-label":r("sidebar.search.ariaLabel"),placeholder:r("sidebar.search.placeholder"),value:h,onChange:U=>x(U.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"}),h&&a.jsx("button",{type:"button",onClick:()=>{var U;x(""),(U=S.current)==null||U.focus()},className:"absolute right-3 top-1/2 z-10 inline-flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-full border border-slate-200/80 bg-white/90 text-slate-400 transition-colors hover:border-slate-300 hover:text-slate-600 focus:outline-none focus:ring-2 focus:ring-sky-200 dark:border-white/10 dark:bg-white/5 dark:text-slate-500 dark:hover:border-white/20 dark:hover:text-slate-200 dark:focus:ring-sky-500/20","aria-label":r("sidebar.search.clearAriaLabel"),children:a.jsx(Ge,{className:"h-3.5 w-3.5"})})]}),ee&&a.jsx("p",{"aria-live":"polite",className:"mt-2 text-center text-[11px] tabular-nums text-gray-400 dark:text-[#6e7490]",children:te.length===0?r("sidebar.resultsNone"):r("sidebar.results",{count:te.length})})]})]}),a.jsx("div",{ref:z,role:"listbox","aria-label":r("sidebar.conversations.ariaLabel"),onKeyDown:J,className:"flex-1 overflow-y-auto bg-transparent px-3 py-2",children:te.length===0?null:ee?a.jsx("div",{className:"space-y-1.5",children:te.map(Oe)}):a.jsx("div",{className:"space-y-4",children:Ce.map(U=>a.jsxs("section",{"aria-label":r(`sidebar.timeGroups.${U.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:r(`sidebar.timeGroups.${U.label}`)}),a.jsx("div",{className:"space-y-1.5",children:U.conversations.map(Oe)})]},U.label))})}),(()=>{const U=Ti();return U.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":r("appHeader.navLinksAriaLabel"),children:a.jsx("ul",{className:"flex flex-wrap gap-2",children:U.map(B=>a.jsx("li",{children:a.jsx("a",{href:B.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:B.label})},B.url))})})})})(),a.jsx("div",{className:"shrink-0 border-t border-gray-200/80 dark:border-[#2d2f39]",children:a.jsx(mo,{placement:"sidebar",compact:!0})})]}),a.jsx(_s,{isOpen:N.isOpen,onClose:ie,onConfirm:Y,title:r("sidebar.deleteConfirm.title"),message:r("sidebar.deleteConfirm.message",{title:N.conversationTitle}),confirmText:r("sidebar.deleteConfirm.confirmText"),cancelText:r("common.cancel"),type:"danger",isLoading:N.isDeleting}),a.jsx(_s,{isOpen:T.isOpen,onClose:Ee,onConfirm:Pe,title:r("sidebar.clearAllConfirm.title"),message:r("sidebar.clearAllConfirm.message",{count:M}),confirmText:r("sidebar.clearAllConfirm.confirmText"),cancelText:r("common.cancel"),type:"danger",isLoading:T.isDeleting})]})}const Zf="3.12.0",Jf={version:Zf},Kn=Jf.version,em=["@@auth0spajs@@","a0.spajs","auth0","com.auth0"];function tm(t){const e=t.toLowerCase();return em.some(r=>e.includes(r.toLowerCase()))}function rm(t){const e=[];for(let r=0;r<t.length;r++){const n=t.key(r);n&&tm(n)&&e.push(n)}e.forEach(r=>t.removeItem(r))}function di(t){try{rm(t),t.clear()}catch(e){console.warn("[Settings] Failed to clear browser storage during reset.",e)}}function sm(){if(typeof document>"u"||!document.cookie)return;const t=new Set([void 0]),e=window.location.hostname;e&&e!=="localhost"&&!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)&&(t.add(e),t.add(`.${e}`)),document.cookie.split(";").forEach(n=>{const s=n.indexOf("="),i=(s>-1?n.slice(0,s):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 nm(){di(localStorage),di(sessionStorage),sm()}function am({isOpen:t,onClose:e}){const{t:r}=Le(),{theme:n,updateTheme:s}=lr(),{settings:i,updateSettings:o}=Ds(),{activeLanguages:l,currentLanguage:c,setLanguage:d}=Hc(),[u,f]=m.useState(!1),[p,g]=m.useState(!1),h=m.useRef(null),x=m.useRef(null),y=m.useMemo(()=>[...l].sort((T,_)=>fs[T].localeCompare(fs[_])),[l]);m.useEffect(()=>{if(!p)return;const T=_=>{_.key==="Escape"&&(_.stopPropagation(),g(!1))};return document.addEventListener("keydown",T,{capture:!0}),()=>document.removeEventListener("keydown",T,{capture:!0})},[p]);const k=T=>{s({mode:T})},C=()=>{o({soundEnabled:!i.soundEnabled})},L=()=>{f(!0)},N=()=>{f(!1)},v=()=>{N(),Hs(),Vs(!1),yr(null),rt.getState().closeLoginPrompt(),nm(),window.location.reload()};return Hr(h,{enabled:t&&!u,onEscape:e}),Hr(x,{enabled:u,onEscape:N}),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":r("settings.dialog.closeOverlayAriaLabel"),className:"absolute inset-0"}),a.jsxs("div",{onClick:T=>T.stopPropagation(),ref:h,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:r("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":r("settings.dialog.closeButtonAriaLabel"),children:a.jsx(Ge,{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(cd,{className:"w-5 h-5"}),r("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:r("settings.appearance.themeLabel")}),a.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{value:"light",label:r("settings.appearance.themeLight"),icon:yd},{value:"dark",label:r("settings.appearance.themeDark"),icon:ld},{value:"system",label:r("settings.appearance.themeSystem"),icon:od}].map(({value:T,label:_,icon:b})=>a.jsxs("button",{onClick:()=>k(T),className:`flex flex-col items-center gap-2 p-3 rounded-lg border-2 transition-all duration-200 ${n.mode===T?"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:_})]},T))})]}),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(td,{className:"w-4 h-4"}),r("settings.language.label")]}),a.jsxs("div",{className:"relative",children:[a.jsxs("button",{type:"button",onClick:()=>g(T=>!T),"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:fs[c]}),a.jsx(wr,{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:()=>g(!1)}),a.jsx("div",{role:"listbox","aria-label":r("settings.language.label"),className:"absolute z-20 mt-2 max-h-60 w-full overflow-y-auto rounded-lg border border-gray-200 bg-white p-1 shadow-lg ring-1 ring-black/5 dark:border-[#2d2f39] dark:bg-[#1a1b1e] dark:ring-white/5",children:y.map(T=>{const _=T===c;return a.jsxs("button",{type:"button",role:"option","aria-selected":_,onClick:()=>{d(T),g(!1)},className:`flex w-full items-center justify-between gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors ${_?"bg-blue-50 font-medium text-blue-700 dark:bg-blue-900/20 dark:text-blue-300":"text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-[#25262f]"}`,children:[a.jsx("span",{className:"truncate",children:fs[T]}),_&&a.jsx(ir,{className:"h-4 w-4 flex-shrink-0 text-blue-600 dark:text-blue-400"})]},T)})})]})]})]})]}),a.jsxs("div",{className:"space-y-4",children:[a.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:r("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(Bn,{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:r("settings.soundEffects.label")}),a.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:r("settings.soundEffects.description")})]})]}),a.jsx("button",{onClick:C,role:"switch","aria-checked":i.soundEnabled,"aria-label":r("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(Wi,{className:"w-5 h-5"}),r("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:r("settings.dataManagement.description")}),a.jsx("button",{onClick:L,className:"w-full px-4 py-2 text-sm font-medium text-red-600 dark:text-red-400 border border-red-300 dark:border-red-700 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors",children:r("settings.reset.button")})]})]}),a.jsxs("p",{className:"pt-2 text-center text-xs text-gray-400 dark:text-[#858999]",children:["v",Kn]})]}),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(zn,{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:r("settings.reset.confirmTitle")}),a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:r("settings.reset.confirmMessage")})]})]}),a.jsxs("div",{className:"mt-4 flex gap-2 pt-2",children:[a.jsx("button",{onClick:N,className:"flex-1 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-[#2d2f39] rounded-lg hover:bg-gray-50 dark:hover:bg-[#1a1b1e] transition-colors",children:r("common.cancel")}),a.jsx("button",{onClick:v,className:"flex-1 px-4 py-2 text-sm font-semibold rounded-lg transition-colors bg-red-600 text-white hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-600",children:r("settings.reset.confirmButton")})]})]})})]})]}):null}function im({message:t}){const{t:e}=Le(),r=Pn();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:r}),a.jsxs("span",{className:"shrink-0 text-xs font-medium text-slate-400 dark:text-[#858999]",children:["v",Kn]})]}),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(gd,{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 om({children:t}){const{instance:e,accounts:r}=Mn(),n=nl();return m.useEffect(()=>{Vs(n)},[n]),m.useEffect(()=>{if(!n||r.length===0){yr(null);return}const s=r[0];yr(s.username||s.name||s.localAccountId||null)},[n,r]),m.useEffect(()=>{if(!n||r.length===0)return;const s=r[0],i=Un();return Ki(async()=>(await e.acquireTokenSilent({scopes:i,account:s})).accessToken),()=>Hs()},[n,r,e]),a.jsx(a.Fragment,{children:t})}function lm({children:t}){return a.jsx(om,{children:t})}function cm({children:t}){const{isLoading:e,isAuthenticated:r,getAccessTokenSilently:n,user:s}=Fn();return m.useEffect(()=>{Vs(r)},[r]),m.useEffect(()=>{if(!r){yr(null);return}const i=(s==null?void 0:s.sub)||(s==null?void 0:s.email)||(s==null?void 0:s.nickname)||(s==null?void 0:s.name)||null;yr(i)},[r,s]),m.useEffect(()=>(r&&Ki(()=>n()),()=>Hs()),[r,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 dm({children:t}){return m.useEffect(()=>{Vs(!1),yr(null),Hs()},[]),a.jsx(a.Fragment,{children:t})}function um({children:t}){return tt()?zs()==="entra"?a.jsx(lm,{children:t}):a.jsx(cm,{children:t}):a.jsx(dm,{children:t})}function fm(){const t=Dn(),e=tt(),r=kr(),{showLoginPrompt:n,promptMessage:s,closeLoginPrompt:i}=rt();return m.useEffect(()=>{n&&(!t||!e||r)&&i()},[n,t,e,r,i]),!t||!e||r||!n?null:zs()==="entra"?a.jsx(hm,{message:s,onClose:i}):a.jsx(mm,{message:s,onClose:i})}function mm({message:t,onClose:e}){const{loginWithRedirect:r}=Fn();return a.jsx(yo,{message:t,onClose:e,onLogin:()=>r()})}function hm({message:t,onClose:e}){const{instance:r}=Mn();return a.jsx(yo,{message:t,onClose:e,onLogin:()=>r.loginRedirect({scopes:Un()}).catch(()=>{})})}function yo({message:t,onClose:e,onLogin:r}){const{t:n}=Le();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(Ge,{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(zi,{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:r,className:"flex-1 rounded-lg bg-blue-600 px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:bg-blue-500 dark:hover:bg-blue-600",children:n("common.signIn")}),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 pm(){const{t}=Le(),{goHome:e}=xo(),{isDark:r}=lr(),n=Cf(),s=m.useRef(!1),i=jc(),o=Cc(),l=Ac(),c=r?l:o,d=Nc(),u=Ic(),f=!!(d||u),p=Lc(),g=Ec(),h=_c(),x=Ti(),y=h?"border-b border-slate-200/80 dark:border-[#333645]":"",k="inline-flex min-h-10 items-center rounded-md px-2.5 text-sm font-medium transition-colors hover:bg-slate-100 hover:text-blue-700 hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:hover:bg-[#2b2d39] dark:hover:text-blue-300";return m.useEffect(()=>{s.current},[l,i,o]),Sn()?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:g||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:C=>{C.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(C=>a.jsx("li",{children:a.jsx("a",{href:C.url,target:"_blank",rel:"noopener noreferrer",className:k,style:{color:g||void 0},children:C.label})},C.url))})}),a.jsx(_n,{})]})]})}):null}function gm({children:t}){const e=m.useRef(null),r=m.useCallback(s=>{e.current=s},[]),n=m.useCallback(()=>{var s;(s=e.current)==null||s.call(e)},[]);return a.jsx(go.Provider,{value:{registerGoHome:r,goHome:n},children:t})}function xm(){const{t}=Le(),[e,r]=m.useState(!1),[n,s]=m.useState(!1),[i,o]=m.useState(()=>localStorage.getItem("desktop-sidebar-collapsed")==="true"),l=ye(u=>u.conversations),c=wc();if(m.useEffect(()=>{localStorage.setItem("desktop-sidebar-collapsed",String(i))},[i]),c)return a.jsx(fa,{children:a.jsx(im,{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(fa,{children:a.jsx(ll,{children:a.jsx(Bc,{children:a.jsx(um,{children:a.jsx(gm,{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(ud,{className:"h-4 w-4"})})}):a.jsx("div",{className:"hidden md:h-full md:flex",children:a.jsx(ci,{onToggleDesktopSidebar:()=>o(!0)})})),a.jsxs("div",{className:"flex-1 flex flex-col w-full min-h-0",children:[a.jsx(pm,{}),a.jsx("div",{className:"flex-1 flex justify-center w-full min-h-0",children:a.jsx(Gf,{onOpenSettings:()=>r(!0),onOpenSidebar:()=>s(!0)})})]})]}),a.jsx(fm,{}),a.jsx(am,{isOpen:e,onClose:()=>r(!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:()=>s(!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(ci,{onRequestClose:()=>s(!1)}),a.jsx("button",{onClick:()=>s(!1),className:"absolute -right-3 top-[max(env(safe-area-inset-top),0.75rem)] rounded-full bg-white/95 p-3 text-gray-600 shadow-lg active:scale-95 transition-transform dark:bg-[#2d2f39] dark:text-[#ececf1]","aria-label":t("app.menu.closeAriaLabel"),children:a.jsx(Ge,{className:"h-5 w-5"})})]})]})]})})})})})})}const gn=new al({auth:{clientId:Ei(),authority:`https://login.microsoftonline.com/${Sc()}`,redirectUri:typeof window<"u"?window.location.origin:"/"},cache:{cacheLocation:"sessionStorage"}});function bm({children:t}){const[e,r]=m.useState(!1);return m.useEffect(()=>{gn.initialize().then(()=>gn.handleRedirectPromise()).catch(n=>{console.error("[EntraAuth] Redirect processing failed:",n)}).finally(()=>r(!0))},[]),e?a.jsx(il,{instance:gn,children:t}):null}function ym({children:t}){if(!Dn()||!tt())return a.jsx(a.Fragment,{children:t});if(zs()==="entra")return a.jsx(bm,{children:t});const r=kc(),n=Ei(),s=vc();return!r||!n?a.jsx(a.Fragment,{children:t}):a.jsx(ol,{domain:r,clientId:n,authorizationParams:{redirect_uri:window.location.origin,...s?{audience:s}:{}},cacheLocation:"memory",children:t})}bo(null);const ui=fc(),fi=document.querySelector('link[rel="icon"]');if(fi)fi.href=ui;else{const t=document.createElement("link");t.rel="icon",t.href=ui,document.head.appendChild(t)}const wm=Dc();var mi,hi,pi,gi,xi,bi;for(const t of wm){const e=((mi=t.src)==null?void 0:mi.trim())||"",r=((hi=t.content)==null?void 0:hi.trim())||"",n=((pi=t.id)==null?void 0:pi.trim())||"";if(!e&&!r||n&&document.querySelector(`script[data-orbitchat-startup-script-id="${n}"]`)||Array.from(document.querySelectorAll("script[data-orbitchat-startup-script]")).some(o=>{const l=e&&o.dataset.orbitchatStartupScriptSrc===e,c=r&&(o.textContent||"").trim()===r;return!!(l||c)}))continue;const i=document.createElement("script");e&&(i.src=e),r&&(i.text=r),i.async=t.async??!0,t.defer!==void 0&&(i.defer=t.defer),(gi=t.type)!=null&&gi.trim()&&(i.type=t.type.trim()),(xi=t.integrity)!=null&&xi.trim()&&(i.integrity=t.integrity.trim()),t.crossOrigin&&(i.crossOrigin=t.crossOrigin),(bi=t.referrerPolicy)!=null&&bi.trim()&&(i.referrerPolicy=t.referrerPolicy.trim()),i.dataset.orbitchatStartupScript="true",n&&(i.dataset.orbitchatStartupScriptId=n),e&&(i.dataset.orbitchatStartupScriptSrc=e),document.head.appendChild(i)}D("🚀 AI Chat Application started");D(`📱 App Version: v${Kn}`);Vo.createRoot(document.getElementById("root")).render(a.jsx(m.StrictMode,{children:a.jsx(ym,{children:a.jsx(xm,{})})}));export{Hl as r,Le as u};