orbitchat 3.13.0 → 3.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/assets/{ChartRenderer-BVIHiEuQ.js → ChartRenderer-C2e8Hk-R.js} +1 -1
  2. package/dist/assets/{MermaidRenderer-06v_lvtx.js → MermaidRenderer-xd7zfbS-.js} +4 -4
  3. package/dist/assets/{MusicRenderer-BM9JdQ9g.js → MusicRenderer-CrMDit8N.js} +1 -1
  4. package/dist/assets/{SVGRenderer-s536z9z0.js → SVGRenderer-vTFqYYOJ.js} +1 -1
  5. package/dist/assets/{architectureDiagram-3BPJPVTR-Yb23zmqI.js → architectureDiagram-3BPJPVTR-B45qwMrj.js} +1 -1
  6. package/dist/assets/{blockDiagram-GPEHLZMM-oeOxfnK-.js → blockDiagram-GPEHLZMM-DpACKoUx.js} +1 -1
  7. package/dist/assets/{c4Diagram-AAUBKEIU-CC7hiowO.js → c4Diagram-AAUBKEIU-Bx1j9oRq.js} +1 -1
  8. package/dist/assets/channel-DEGNXU4Z.js +1 -0
  9. package/dist/assets/{chunk-2J33WTMH-7b0E1KLS.js → chunk-2J33WTMH-DpKtqyzY.js} +1 -1
  10. package/dist/assets/{chunk-4BX2VUAB-C3dLzy2P.js → chunk-4BX2VUAB-COZv64NX.js} +1 -1
  11. package/dist/assets/{chunk-55IACEB6-DPT6Tf2I.js → chunk-55IACEB6-Cu9DHOzo.js} +1 -1
  12. package/dist/assets/{chunk-727SXJPM-ByrSgTIS.js → chunk-727SXJPM-C_C43W4B.js} +1 -1
  13. package/dist/assets/{chunk-AQP2D5EJ-Dnfrcz_y.js → chunk-AQP2D5EJ-CJfw0Qoy.js} +1 -1
  14. package/dist/assets/{chunk-FMBD7UC4-3ss7w7DZ.js → chunk-FMBD7UC4-Cmci46bI.js} +1 -1
  15. package/dist/assets/{chunk-ND2GUHAM-DIHBH20U.js → chunk-ND2GUHAM-hke8dSkX.js} +1 -1
  16. package/dist/assets/{chunk-QZHKN3VN-ztfujm2X.js → chunk-QZHKN3VN-d_l2hUnO.js} +1 -1
  17. package/dist/assets/classDiagram-4FO5ZUOK-xdjj6ARr.js +1 -0
  18. package/dist/assets/classDiagram-v2-Q7XG4LA2-xdjj6ARr.js +1 -0
  19. package/dist/assets/{cose-bilkent-S5V4N54A-kEz_TZ-F.js → cose-bilkent-S5V4N54A-Dzep_zMS.js} +1 -1
  20. package/dist/assets/{dagre-BM42HDAG-BoYXy_WQ.js → dagre-BM42HDAG-HaAYzN5b.js} +1 -1
  21. package/dist/assets/{diagram-2AECGRRQ-CGl2Nlh-.js → diagram-2AECGRRQ-DWGp-6kd.js} +1 -1
  22. package/dist/assets/{diagram-5GNKFQAL-Dt79RH-K.js → diagram-5GNKFQAL--nOGBoOE.js} +1 -1
  23. package/dist/assets/{diagram-KO2AKTUF-Bmmx_DO9.js → diagram-KO2AKTUF-BIPTLiUw.js} +1 -1
  24. package/dist/assets/{diagram-LMA3HP47-ktO1TF9w.js → diagram-LMA3HP47-vVC7FkQ3.js} +1 -1
  25. package/dist/assets/{diagram-OG6HWLK6-lGmaynfj.js → diagram-OG6HWLK6-CCuEiRwx.js} +1 -1
  26. package/dist/assets/{erDiagram-TEJ5UH35-BipSkH8k.js → erDiagram-TEJ5UH35-DOBZMyhb.js} +1 -1
  27. package/dist/assets/{flowDiagram-I6XJVG4X-Cd5HlKU5.js → flowDiagram-I6XJVG4X-CU6YZgeK.js} +1 -1
  28. package/dist/assets/{ganttDiagram-6RSMTGT7-DWXVGBzc.js → ganttDiagram-6RSMTGT7-DujS_wtO.js} +1 -1
  29. package/dist/assets/{gitGraphDiagram-PVQCEYII-CIwyaP39.js → gitGraphDiagram-PVQCEYII-DQHsGslQ.js} +1 -1
  30. package/dist/assets/index-CUN-rdx_.css +1 -0
  31. package/dist/assets/index-pk0xbZh9.js +353 -0
  32. package/dist/assets/{infoDiagram-5YYISTIA-BELkkv7w.js → infoDiagram-5YYISTIA-DRbDJtjy.js} +1 -1
  33. package/dist/assets/{ishikawaDiagram-YF4QCWOH-qBTg22wB.js → ishikawaDiagram-YF4QCWOH-Cc33PPm2.js} +1 -1
  34. package/dist/assets/{journeyDiagram-JHISSGLW-Bg0XWC2C.js → journeyDiagram-JHISSGLW-CCXSOurS.js} +1 -1
  35. package/dist/assets/{kanban-definition-UN3LZRKU-BBWNQtJQ.js → kanban-definition-UN3LZRKU-CZe-Zvig.js} +1 -1
  36. package/dist/assets/{mindmap-definition-RKZ34NQL-CjFB0WoJ.js → mindmap-definition-RKZ34NQL-CjLs00m5.js} +1 -1
  37. package/dist/assets/{pieDiagram-4H26LBE5-DLft15uJ.js → pieDiagram-4H26LBE5-CNSS6AQ3.js} +1 -1
  38. package/dist/assets/{quadrantDiagram-W4KKPZXB-BjsL3E9S.js → quadrantDiagram-W4KKPZXB-DFS_zppW.js} +1 -1
  39. package/dist/assets/{requirementDiagram-4Y6WPE33-BHo1co6c.js → requirementDiagram-4Y6WPE33-C0xdMRkS.js} +1 -1
  40. package/dist/assets/{sankeyDiagram-5OEKKPKP-D4eHZFXc.js → sankeyDiagram-5OEKKPKP-CbkqJFIC.js} +1 -1
  41. package/dist/assets/{sequenceDiagram-3UESZ5HK-CNzuymm-.js → sequenceDiagram-3UESZ5HK-oQN5hWGT.js} +1 -1
  42. package/dist/assets/{stateDiagram-AJRCARHV-BH9nKONT.js → stateDiagram-AJRCARHV-D7Xf6CIb.js} +1 -1
  43. package/dist/assets/{stateDiagram-v2-BHNVJYJU-CillwhoX.js → stateDiagram-v2-BHNVJYJU-BphAw4xA.js} +1 -1
  44. package/dist/assets/{timeline-definition-PNZ67QCA-Ibm70OsG.js → timeline-definition-PNZ67QCA-ByMynw2t.js} +1 -1
  45. package/dist/assets/{vennDiagram-CIIHVFJN-DPvJ1m0U.js → vennDiagram-CIIHVFJN-Dr8krogC.js} +1 -1
  46. package/dist/assets/{wardleyDiagram-YWT4CUSO-5SFvvwOM.js → wardleyDiagram-YWT4CUSO-JnZQ3swy.js} +1 -1
  47. package/dist/assets/{xychartDiagram-2RQKCTM6-BI8jqDwb.js → xychartDiagram-2RQKCTM6-BXIHG0kx.js} +1 -1
  48. package/dist/index.html +2 -2
  49. package/package.json +1 -1
  50. package/dist/assets/channel-I_6n2Gp7.js +0 -1
  51. package/dist/assets/classDiagram-4FO5ZUOK-Dc6wCsh6.js +0 -1
  52. package/dist/assets/classDiagram-v2-Q7XG4LA2-Dc6wCsh6.js +0 -1
  53. package/dist/assets/index-DDyyF-Pb.css +0 -1
  54. package/dist/assets/index-DmPdEvue.js +0 -353
@@ -0,0 +1,353 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MermaidRenderer-xd7zfbS-.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-vTFqYYOJ.js","assets/locales-Dwnt_iav.js","assets/vendor-markdown-Cy_-N5ZX.js","assets/vendor-markdown-dRWncRqa.css","assets/vendor-auth-aD_bwYde.js","assets/ChartRenderer-C2e8Hk-R.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-CrMDit8N.js","assets/papaparse.min-D13ujVVP.js","assets/docx-preview-DehBmhog.js"])))=>i.map(i=>d[i]);
2
+ var Jo=Object.defineProperty;var Zo=(t,e,r)=>e in t?Jo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Ze=(t,e,r)=>Zo(t,typeof e!="symbol"?e+"":e,r);import{r as m,j as n,a as el,R as xt,b as Hs,d as tl}from"./vendor-react-BbEy7z12.js";import{z as rl,p as sl,j as al,f as nl,e as il,a as ol,d as ll}from"./locales-Dwnt_iav.js";import{M as cl,r as yn,a as dl,b as ul}from"./vendor-markdown-Cy_-N5ZX.js";import{_ as Et,h as fl,v as ml,a as hl}from"./vendor-syntax-INF7-xC_.js";import{u as za,a as Ba,b as gl,P as pl,M as xl,A as bl}from"./vendor-auth-aD_bwYde.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&s(o)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function s(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();const Fi=m.createContext(void 0);function wn({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}}),[s,a]=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,a(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 n.jsx(Fi.Provider,{value:{theme:e,updateTheme:i,isDark:s},children:t})}function mr(){const t=m.useContext(Fi);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}const Ri=m.createContext(void 0),la={voiceEnabled:!1,soundEnabled:!1,autoSend:!1};function yl({children:t}){const[e,r]=m.useState(()=>{const a=localStorage.getItem("chat-settings");if(a)try{const i=JSON.parse(a);return{...la,...i,voiceEnabled:!1}}catch{return la}return la});m.useEffect(()=>{localStorage.setItem("chat-settings",JSON.stringify(e))},[e]);const s=a=>{r(i=>({...i,...a}))};return n.jsx(Ri.Provider,{value:{settings:e,updateSettings:s},children:t})}function qs(){const t=m.useContext(Ri);if(!t)throw new Error("useSettings must be used within SettingsProvider");return t}const he=t=>typeof t=="string",Fr=()=>{let t,e;const r=new Promise((s,a)=>{t=s,e=a});return r.resolve=t,r.reject=e,r},kn=t=>t==null?"":String(t),wl=(t,e,r)=>{t.forEach(s=>{e[s]&&(r[s]=e[s])})},kl=/###/g,vn=t=>t&&t.includes("###")?t.replace(kl,"."):t,Sn=t=>!t||he(t),Dr=(t,e,r)=>{const s=he(e)?e.split("."):e;let a=0;for(;a<s.length-1;){if(Sn(t))return{};const i=vn(s[a]);!t[i]&&r&&(t[i]=new r),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++a}return Sn(t)?{}:{obj:t,k:vn(s[a])}},jn=(t,e,r)=>{const{obj:s,k:a}=Dr(t,e,Object);if(s!==void 0||e.length===1){s[a]=r;return}let i=e[e.length-1],o=e.slice(0,e.length-1),l=Dr(t,o,Object);for(;l.obj===void 0&&o.length;)i=`${o[o.length-1]}.${i}`,o=o.slice(0,o.length-1),l=Dr(t,o,Object),l!=null&&l.obj&&typeof l.obj[`${l.k}.${i}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${i}`]=r},vl=(t,e,r,s)=>{const{obj:a,k:i}=Dr(t,e,Object);a[i]=a[i]||[],a[i].push(r)},Ls=(t,e)=>{const{obj:r,k:s}=Dr(t,e);if(r&&Object.prototype.hasOwnProperty.call(r,s))return r[s]},Sl=(t,e,r)=>{const s=Ls(t,r);return s!==void 0?s:Ls(e,r)},$i=(t,e,r)=>{for(const s in e)s!=="__proto__"&&s!=="constructor"&&(Object.prototype.hasOwnProperty.call(t,s)?he(t[s])||t[s]instanceof String||he(e[s])||e[s]instanceof String?r&&(t[s]=e[s]):$i(t[s],e[s],r):t[s]=e[s]);return t},zt=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),jl={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"},Cl=t=>he(t)?t.replace(/[&<>"'\/]/g,e=>jl[e]):t;class Al{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 s=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,s),this.regExpQueue.push(e),s}}const Nl=[" ",",","?","!",";"],Il=new Al(20),El=(t,e,r)=>{e=e||"",r=r||"";const s=Nl.filter(o=>!e.includes(o)&&!r.includes(o));if(s.length===0)return!0;const a=Il.getRegExp(`(${s.map(o=>o==="?"?"\\?":o).join("|")})`);let i=!a.test(t);if(!i){const o=t.indexOf(r);o>0&&!a.test(t.substring(0,o))&&(i=!0)}return i},Sa=(t,e,r=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const s=e.split(r);let a=t;for(let i=0;i<s.length;){if(!a||typeof a!="object")return;let o,l="";for(let c=i;c<s.length;++c)if(c!==i&&(l+=r),l+=s[c],o=a[l],o!==void 0){if(["string","number","boolean"].includes(typeof o)&&c<s.length-1)continue;i+=c-i+1;break}a=o}return a},Br=t=>t==null?void 0:t.replace(/_/g,"-"),Ll={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,s;(s=(r=console==null?void 0:console[t])==null?void 0:r.apply)==null||s.call(r,console,e)}};class _s{constructor(e,r={}){this.init(e,r)}init(e,r={}){this.prefix=r.prefix||"i18next:",this.logger=e||Ll,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,s,a){return a&&!this.debug?null:(e=e.map(i=>he(i)?i.replace(/[\r\n\x00-\x1F\x7F]/g," "):i),he(e[0])&&(e[0]=`${s}${this.prefix} ${e[0]}`),this.logger[r](e))}create(e){return new _s(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new _s(this.logger,e)}}var Lt=new _s;class Ws{constructor(){this.observers={}}on(e,r){return e.split(" ").forEach(s=>{this.observers[s]||(this.observers[s]=new Map);const a=this.observers[s].get(r)||0;this.observers[s].set(r,a+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 s=(...a)=>{r(...a),this.off(e,s)};return this.on(e,s),this}emit(e,...r){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([a,i])=>{for(let o=0;o<i;o++)a(...r)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([a,i])=>{for(let o=0;o<i;o++)a(e,...r)})}}class Cn extends Ws{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,s,a={}){var d,u;const i=a.keySeparator!==void 0?a.keySeparator:this.options.keySeparator,o=a.ignoreJSONStructure!==void 0?a.ignoreJSONStructure:this.options.ignoreJSONStructure;let l;e.includes(".")?l=e.split("."):(l=[e,r],s&&(Array.isArray(s)?l.push(...s):he(s)&&i?l.push(...s.split(i)):l.push(s)));const c=Ls(this.data,l);return!c&&!r&&!s&&e.includes(".")&&(e=l[0],r=l[1],s=l.slice(2).join(".")),c||!o||!he(s)?c:Sa((u=(d=this.data)==null?void 0:d[e])==null?void 0:u[r],s,i)}addResource(e,r,s,a,i={silent:!1}){const o=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator;let l=[e,r];s&&(l=l.concat(o?s.split(o):s)),e.includes(".")&&(l=e.split("."),a=r,r=l[1]),this.addNamespaces(r),jn(this.data,l,a),i.silent||this.emit("added",e,r,s,a)}addResources(e,r,s,a={silent:!1}){for(const i in s)(he(s[i])||Array.isArray(s[i]))&&this.addResource(e,r,i,s[i],{silent:!0});a.silent||this.emit("added",e,r,s)}addResourceBundle(e,r,s,a,i,o={silent:!1,skipCopy:!1}){let l=[e,r];e.includes(".")&&(l=e.split("."),a=s,s=r,r=l[1]),this.addNamespaces(r);let c=Ls(this.data,l)||{};o.skipCopy||(s=JSON.parse(JSON.stringify(s))),a?$i(c,s,i):c={...c,...s},jn(this.data,l,c),o.silent||this.emit("added",e,r,s)}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(a=>r[a]&&Object.keys(r[a]).length>0)}toJSON(){return this.data}}var Pi={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,r,s,a){return t.forEach(i=>{var o;e=((o=this.processors[i])==null?void 0:o.process(e,r,s,a))??e}),e}};const Di=Symbol("i18next/PATH_KEY");function _l(){const t=[],e=Object.create(null);let r;return e.get=(s,a)=>{var i;return(i=r==null?void 0:r.revoke)==null||i.call(r),a===Di?t:(t.push(a),r=Proxy.revocable(s,e),r.proxy)},Proxy.revocable(Object.create(null),e).proxy}function wr(t,e){const{[Di]:r}=t(_l()),s=(e==null?void 0:e.keySeparator)??".",a=(e==null?void 0:e.nsSeparator)??":",i=(e==null?void 0:e.enableSelector)==="strict";if(r.length>1&&a){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]}${a}${r.slice(1).join(s)}`}return r.join(s)}const ca=t=>!he(t)&&typeof t!="boolean"&&typeof t!="number";class Ts extends Ws{constructor(e,r={}){super(),wl(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=r,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Lt.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,r={interpolation:{}}){const s={...r};if(e==null)return!1;const a=this.resolve(e,s);if((a==null?void 0:a.res)===void 0)return!1;const i=ca(a.res);return!(s.returnObjects===!1&&i)}extractFromKey(e,r){let s=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;s===void 0&&(s=":");const a=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator;let i=r.ns||this.options.defaultNS||[];const o=s&&e.includes(s),l=!this.options.userDefinedKeySeparator&&!r.keySeparator&&!this.options.userDefinedNsSeparator&&!r.nsSeparator&&!El(e,s,a);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(s);(s!==a||s===a&&this.options.ns.includes(d[0]))&&(i=d.shift()),e=d.join(a)}return{key:e,namespaces:he(i)?[i]:i}}translate(e,r,s){let a=typeof r=="object"?{...r}:r;if(typeof a!="object"&&this.options.overloadTranslationOptionHandler&&(a=this.options.overloadTranslationOptionHandler(arguments)),typeof a=="object"&&(a={...a}),a||(a={}),e==null)return"";typeof e=="function"&&(e=wr(e,{...this.options,...a})),Array.isArray(e)||(e=[String(e)]),e=e.map(U=>typeof U=="function"?wr(U,{...this.options,...a}):String(U));const i=a.returnDetails!==void 0?a.returnDetails:this.options.returnDetails,o=a.keySeparator!==void 0?a.keySeparator:this.options.keySeparator,{key:l,namespaces:c}=this.extractFromKey(e[e.length-1],a),d=c[c.length-1];let u=a.nsSeparator!==void 0?a.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const f=a.lng||this.language,p=a.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(a)}:`${d}${u}${l}`:i?{res:l,usedKey:l,exactUsedKey:l,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(a)}:l;const g=this.resolve(e,a);let h=g==null?void 0:g.res;const x=(g==null?void 0:g.usedKey)||l,b=(g==null?void 0:g.exactUsedKey)||l,k=["[object Number]","[object Function]","[object RegExp]"],S=a.joinArrays!==void 0?a.joinArrays:this.options.joinArrays,E=!this.i18nFormat||this.i18nFormat.handleAsObject,_=a.count!==void 0&&!he(a.count),v=Ts.hasDefaultValue(a),M=_?this.pluralResolver.getSuffix(f,a.count,a):"",F=a.ordinal&&_?this.pluralResolver.getSuffix(f,a.count,{ordinal:!1}):"",y=_&&!a.ordinal&&a.count===0,A=y&&a[`defaultValue${this.options.pluralSeparator}zero`]||a[`defaultValue${M}`]||a[`defaultValue${F}`]||a.defaultValue;let N=h;E&&!h&&v&&(N=A);const I=ca(N),$=Object.prototype.toString.apply(N);if(E&&N&&I&&!k.includes($)&&!(he(S)&&Array.isArray(N))){if(!a.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const U=this.options.returnedObjectHandler?this.options.returnedObjectHandler(x,N,{...a,ns:c}):`key '${l} (${this.language})' returned an object instead of string.`;return i?(g.res=U,g.usedParams=this.getUsedParamsDetails(a),g):U}if(o){const U=Array.isArray(N),X=U?[]:{},j=U?b:x;for(const L in N)if(Object.prototype.hasOwnProperty.call(N,L)){const B=`${j}${o}${L}`;v&&!h?X[L]=this.translate(B,{...a,defaultValue:ca(A)?A[L]:void 0,joinArrays:!1,ns:c}):X[L]=this.translate(B,{...a,joinArrays:!1,ns:c}),X[L]===B&&(X[L]=N[L])}h=X}}else if(E&&he(S)&&Array.isArray(h))h=h.join(S),h&&(h=this.extendTranslation(h,e,a,s));else{let U=!1,X=!1;!this.isValidLookup(h)&&v&&(U=!0,h=A),this.isValidLookup(h)||(X=!0,h=l);const L=(a.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&X?void 0:h,B=v&&A!==h&&this.options.updateMissing;if(X||U||B){if(this.logger.log(B?"updateKey":"missingKey",f,d,_&&!B?`${l}${this.pluralResolver.getSuffix(f,a.count,a)}`:l,B?A:h),o){const J=this.resolve(l,{...a,keySeparator:!1});J&&J.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 C=[];const H=this.languageUtils.getFallbackCodes(this.options.fallbackLng,a.lng||this.language);if(this.options.saveMissingTo==="fallback"&&H&&H[0])for(let J=0;J<H.length;J++)C.push(H[J]);else this.options.saveMissingTo==="all"?C=this.languageUtils.toResolveHierarchy(a.lng||this.language):C.push(a.lng||this.language);const q=(J,K,V)=>{var T;const oe=v&&V!==h?V:L;this.options.missingKeyHandler?this.options.missingKeyHandler(J,d,K,oe,B,a):(T=this.backendConnector)!=null&&T.saveMissing&&this.backendConnector.saveMissing(J,d,K,oe,B,a),this.emit("missingKey",J,d,K,h)};this.options.saveMissing&&(this.options.saveMissingPlurals&&_?C.forEach(J=>{const K=this.pluralResolver.getSuffixes(J,a);y&&a[`defaultValue${this.options.pluralSeparator}zero`]&&!K.includes(`${this.options.pluralSeparator}zero`)&&K.push(`${this.options.pluralSeparator}zero`),K.forEach(V=>{q([J],l+V,a[`defaultValue${V}`]||A)})}):q(C,l,A))}h=this.extendTranslation(h,e,a,g,s),X&&h===l&&this.options.appendNamespaceToMissingKey&&(h=`${d}${u}${l}`),(X||U)&&this.options.parseMissingKeyHandler&&(h=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${l}`:l,U?h:void 0,a))}return i?(g.res=h,g.usedParams=this.getUsedParamsDetails(a),g):h}extendTranslation(e,r,s,a,i){var c,d;if((c=this.i18nFormat)!=null&&c.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...s},s.lng||this.language||a.usedLng,a.usedNS,a.usedKey,{resolved:a});else if(!s.skipInterpolation){s.interpolation&&this.interpolator.init({...s,interpolation:{...this.options.interpolation,...s.interpolation}});const u=he(e)&&(((d=s==null?void 0:s.interpolation)==null?void 0:d.skipOnVariables)!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let f;if(u){const g=e.match(this.interpolator.nestingRegexp);f=g&&g.length}let p=s.replace&&!he(s.replace)?s.replace:s;if(this.options.interpolation.defaultVariables&&(p={...this.options.interpolation.defaultVariables,...p}),e=this.interpolator.interpolate(e,p,s.lng||this.language||a.usedLng,s),u){const g=e.match(this.interpolator.nestingRegexp),h=g&&g.length;f<h&&(s.nest=!1)}!s.lng&&a&&a.res&&(s.lng=this.language||a.usedLng),s.nest!==!1&&(e=this.interpolator.nest(e,(...g)=>(i==null?void 0:i[0])===g[0]&&!s.context?(this.logger.warn(`It seems you are nesting recursively key: ${g[0]} in key: ${r[0]}`),null):this.translate(...g,r),s)),s.interpolation&&this.interpolator.reset()}const o=s.postProcess||this.options.postProcess,l=he(o)?[o]:o;return e!=null&&(l!=null&&l.length)&&s.applyPostProcessor!==!1&&(e=Pi.handle(l,e,r,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...a,usedParams:this.getUsedParamsDetails(s)},...s}:s,this)),e}resolve(e,r={}){let s,a,i,o,l;return he(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(c=>typeof c=="function"?wr(c,{...this.options,...r}):c)),e.forEach(c=>{if(this.isValidLookup(s))return;const d=this.extractFromKey(c,r),u=d.key;a=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(b=>{var k,S;this.isValidLookup(s)||(l=b,!this.checkedLoadedFor[`${x[0]}-${b}`]&&((k=this.utils)!=null&&k.hasLoadedNamespace)&&!((S=this.utils)!=null&&S.hasLoadedNamespace(l))&&(this.checkedLoadedFor[`${x[0]}-${b}`]=!0,this.logger.warn(`key "${a}" 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(E=>{var M;if(this.isValidLookup(s))return;o=E;const _=[u];if((M=this.i18nFormat)!=null&&M.addLookupKeys)this.i18nFormat.addLookupKeys(_,u,E,b,r);else{let F;p&&(F=this.pluralResolver.getSuffix(E,r.count,r));const y=`${this.options.pluralSeparator}zero`,A=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(r.ordinal&&F.startsWith(A)&&_.push(u+F.replace(A,this.options.pluralSeparator)),_.push(u+F),g&&_.push(u+y)),h){const N=`${u}${this.options.contextSeparator||"_"}${r.context}`;_.push(N),p&&(r.ordinal&&F.startsWith(A)&&_.push(N+F.replace(A,this.options.pluralSeparator)),_.push(N+F),g&&_.push(N+y))}}let v;for(;v=_.pop();)this.isValidLookup(s)||(i=v,s=this.getResource(E,b,v,r))}))})}),{res:s,usedKey:a,exactUsedKey:i,usedLng:o,usedNS:l}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,r,s,a={}){var i;return(i=this.i18nFormat)!=null&&i.getResource?this.i18nFormat.getResource(e,r,s,a):this.resourceStore.getResource(e,r,s,a)}getUsedParamsDetails(e={}){const r=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],s=e.replace&&!he(e.replace);let a=s?e.replace:e;if(s&&typeof e.count<"u"&&(a.count=e.count),this.options.interpolation.defaultVariables&&(a={...this.options.interpolation.defaultVariables,...a}),!s){a={...a};for(const i of r)delete a[i]}return a}static hasDefaultValue(e){const r="defaultValue";for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&s.startsWith(r)&&e[s]!==void 0)return!0;return!1}}class An{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Lt.create("languageUtils")}getScriptPartFromCode(e){if(e=Br(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=Br(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(s=>{if(r)return;const a=this.formatLanguageCode(s);(!this.options.supportedLngs||this.isSupportedCode(a))&&(r=a)}),!r&&this.options.supportedLngs&&e.forEach(s=>{if(r)return;const a=this.getScriptPartFromCode(s);if(this.isSupportedCode(a))return r=a;const i=this.getLanguagePartFromCode(s);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 s=e[r];return s||(s=e[this.getScriptPartFromCode(r)]),s||(s=e[this.formatLanguageCode(r)]),s||(s=e[this.getLanguagePartFromCode(r)]),s||(s=e.default),s||[]}toResolveHierarchy(e,r){const s=this.getFallbackCodes((r===!1?[]:r)||this.options.fallbackLng||[],e),a=[],i=o=>{o&&(this.isSupportedCode(o)?a.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)),s.forEach(o=>{a.includes(o)||i(this.formatLanguageCode(o))}),a}}const Nn={zero:0,one:1,two:2,few:3,many:4,other:5},In={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Tl{constructor(e,r={}){this.languageUtils=e,this.options=r,this.logger=Lt.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,r={}){const s=Br(e==="dev"?"en":e),a=r.ordinal?"ordinal":"cardinal",i=JSON.stringify({cleanedCode:s,type:a});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let o;try{o=new Intl.PluralRules(s,{type:a})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),In;if(!e.match(/-|_/))return In;const c=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(c,r)}return this.pluralRulesCache[i]=o,o}needsPlural(e,r={}){let s=this.getRule(e,r);return s||(s=this.getRule("dev",r)),(s==null?void 0:s.resolvedOptions().pluralCategories.length)>1}getPluralFormsOfKey(e,r,s={}){return this.getSuffixes(e,s).map(a=>`${r}${a}`)}getSuffixes(e,r={}){let s=this.getRule(e,r);return s||(s=this.getRule("dev",r)),s?s.resolvedOptions().pluralCategories.sort((a,i)=>Nn[a]-Nn[i]).map(a=>`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${a}`):[]}getSuffix(e,r,s={}){const a=this.getRule(e,s);return a?`${this.options.prepend}${s.ordinal?`ordinal${this.options.prepend}`:""}${a.select(r)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",r,s))}}const En=(t,e,r,s=".",a=!0)=>{let i=Sl(t,e,r);return!i&&a&&he(r)&&(i=Sa(t,r,s),i===void 0&&(i=Sa(e,r,s))),i},da=t=>t.replace(/\$/g,"$$$$");class Ln{constructor(e={}){var r;this.logger=Lt.create("interpolator"),this.options=e,this.format=((r=e==null?void 0:e.interpolation)==null?void 0:r.format)||(s=>s),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:r,escapeValue:s,useRawValueToEscape:a,prefix:i,prefixEscaped:o,suffix:l,suffixEscaped:c,formatSeparator:d,unescapeSuffix:u,unescapePrefix:f,nestingPrefix:p,nestingPrefixEscaped:g,nestingSuffix:h,nestingSuffixEscaped:x,nestingOptionsSeparator:b,maxReplaces:k,alwaysFormat:S}=e.interpolation;this.escape=r!==void 0?r:Cl,this.escapeValue=s!==void 0?s:!0,this.useRawValueToEscape=a!==void 0?a:!1,this.prefix=i?zt(i):o||"{{",this.suffix=l?zt(l):c||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":f?zt(f):"-",this.unescapeSuffix=this.unescapePrefix?"":u?zt(u):"",this.nestingPrefix=p?zt(p):g||zt("$t("),this.nestingSuffix=h?zt(h):x||zt(")"),this.nestingOptionsSeparator=b||",",this.maxReplaces=k||1e3,this.alwaysFormat=S!==void 0?S:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(r,s)=>(r==null?void 0:r.source)===s?(r.lastIndex=0,r):new RegExp(s,"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,s,a){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 S=En(r,c,h,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(S,void 0,s,{...a,...r,interpolationkey:h}):S}const x=h.split(this.formatSeparator),b=x.shift().trim(),k=x.join(this.formatSeparator).trim();return this.format(En(r,c,b,this.options.keySeparator,this.options.ignoreJSONStructure),k,s,{...a,...r,interpolationkey:b})};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=(a==null?void 0:a.missingInterpolationHandler)||this.options.missingInterpolationHandler,f=((g=a==null?void 0:a.interpolation)==null?void 0:g.skipOnVariables)!==void 0?a.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:h=>da(h)},{regex:this.regexp,safeValue:h=>this.escapeValue?da(this.escape(h)):da(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,a);o=he(k)?k:""}else if(a&&Object.prototype.hasOwnProperty.call(a,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=kn(o));const b=h.safeValue(o);if(e=e.replace(i[0],b),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,s={}){let a,i,o;const l=(c,d)=>{const u=this.nestingOptionsSeparator;if(!c.includes(u))return c;const f=c.split(new RegExp(`${zt(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(;a=this.nestingRegexp.exec(e);){let c=[];o={...s},o=o.replace&&!he(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const d=/{.*}/.test(a[1])?a[1].lastIndexOf("}")+1:a[1].indexOf(this.formatSeparator);if(d!==-1&&(c=a[1].slice(d).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),a[1]=a[1].slice(0,d)),i=r(l.call(this,a[1].trim(),o),o),i&&a[0]===e&&!he(i))return i;he(i)||(i=kn(i)),i||(this.logger.warn(`missed to resolve ${a[1]} for nesting ${e}`),i=""),c.length&&(i=c.reduce((u,f)=>this.format(u,f,s.lng,{...s,interpolationkey:a[1].trim()}),i.trim())),e=e.replace(a[0],i),this.regexp.lastIndex=0}return e}}const Ml=t=>{let e=t.toLowerCase().trim();const r={};if(t.includes("(")){const s=t.split("(");e=s[0].toLowerCase().trim();const a=s[1].slice(0,-1);e==="currency"&&!a.includes(":")?r.currency||(r.currency=a.trim()):e==="relativetime"&&!a.includes(":")?r.range||(r.range=a.trim()):a.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}},_n=t=>{const e={};return(r,s,a)=>{let i=a;a&&a.interpolationkey&&a.formatParams&&a.formatParams[a.interpolationkey]&&a[a.interpolationkey]&&(i={...i,[a.interpolationkey]:void 0});const o=s+JSON.stringify(i);let l=e[o];return l||(l=t(Br(s),a),e[o]=l),l(r)}},Fl=t=>(e,r,s)=>t(Br(r),s)(e);class Rl{constructor(e={}){this.logger=Lt.create("formatter"),this.options=e,this.init(e)}init(e,r={interpolation:{}}){this.formatSeparator=r.interpolation.formatSeparator||",";const s=r.cacheInBuiltFormats?_n:Fl;this.formats={number:s((a,i)=>{const o=new Intl.NumberFormat(a,{...i});return l=>o.format(l)}),currency:s((a,i)=>{const o=new Intl.NumberFormat(a,{...i,style:"currency"});return l=>o.format(l)}),datetime:s((a,i)=>{const o=new Intl.DateTimeFormat(a,{...i});return l=>o.format(l)}),relativetime:s((a,i)=>{const o=new Intl.RelativeTimeFormat(a,{...i});return l=>o.format(l,i.range||"day")}),list:s((a,i)=>{const o=new Intl.ListFormat(a,{...i});return l=>o.format(l)})}}add(e,r){this.formats[e.toLowerCase().trim()]=r}addCached(e,r){this.formats[e.toLowerCase().trim()]=_n(r)}format(e,r,s,a={}){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}=Ml(d);if(this.formats[u]){let g=c;try{const h=((p=a==null?void 0:a.formatParams)==null?void 0:p[a.interpolationkey])||{},x=h.locale||h.lng||a.locale||a.lng||s;g=this.formats[u](c,x,{...f,...a,...h})}catch(h){this.logger.warn(h)}return g}else this.logger.warn(`there was no format function for ${u}`);return c},e)}}const $l=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Pl extends Ws{constructor(e,r,s,a={}){var i,o;super(),this.backend=e,this.store=r,this.services=s,this.languageUtils=s.languageUtils,this.options=a,this.logger=Lt.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=a.maxParallelReads||10,this.readingCalls=0,this.maxRetries=a.maxRetries>=0?a.maxRetries:5,this.retryTimeout=a.retryTimeout>=1?a.retryTimeout:350,this.state={},this.queue=[],(o=(i=this.backend)==null?void 0:i.init)==null||o.call(i,s,a.backend,a)}queueLoad(e,r,s,a){const i={},o={},l={},c={};return e.forEach(d=>{let u=!0;r.forEach(f=>{const p=`${d}|${f}`;!s.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:a}),{toLoad:Object.keys(i),pending:Object.keys(o),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(e,r,s){const a=e.split("|"),i=a[0],o=a[1];r&&this.emit("failedLoading",i,o,r),!r&&s&&this.store.addResourceBundle(i,o,s,void 0,void 0,{skipCopy:!0}),this.state[e]=r?-1:2,r&&s&&(this.state[e]=0);const l={};this.queue.forEach(c=>{vl(c.loaded,[i],o),$l(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,s,a=0,i=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:r,fcName:s,tried:a,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&&a<this.maxRetries){setTimeout(()=>{this.read(e,r,s,a+1,i*2,o)},i);return}o(d,u)},c=this.backend[s].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,s={},a){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),a&&a();he(e)&&(e=this.languageUtils.toResolveHierarchy(e)),he(r)&&(r=[r]);const i=this.queueLoad(e,r,s,a);if(!i.toLoad.length)return i.pending.length||a(),null;i.toLoad.forEach(o=>{this.loadOne(o)})}load(e,r,s){this.prepareLoading(e,r,{},s)}reload(e,r,s){this.prepareLoading(e,r,{reload:!0},s)}loadOne(e,r=""){const s=e.split("|"),a=s[0],i=s[1];this.read(a,i,"read",void 0,void 0,(o,l)=>{o&&this.logger.warn(`${r}loading namespace ${i} for language ${a} failed`,o),!o&&l&&this.logger.log(`${r}loaded namespace ${i} for language ${a}`,l),this.loaded(e,o,l)})}saveMissing(e,r,s,a,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 "${s}" 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(!(s==null||s==="")){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,s,a,g):x=h(e,r,s,a),x&&typeof x.then=="function"?x.then(b=>l(null,b)).catch(l):l(null,x)}catch(x){l(x)}else h(e,r,s,a,l,g)}!e||!e[0]||this.store.addResource(e[0],r,s,a)}}}const ua=()=>({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(s=>{e[s]=r[s]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),Tn=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),ms=()=>{},Dl=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(r=>{typeof t[r]=="function"&&(t[r]=t[r].bind(t))})};class Ur extends Ws{constructor(e={},r){if(super(),this.options=Tn(e),this.services={},this.logger=Lt,this.modules={external:[]},Dl(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 s=ua();this.options={...s,...this.options,...Tn(e)},this.options.interpolation={...s.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=s.overloadTranslationOptionHandler);const a=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?Lt.init(a(this.modules.logger),this.options):Lt.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=Rl;const u=new An(this.options);this.store=new Cn(this.options.resources,this.options);const f=this.services;f.logger=Lt,f.resourceStore=this.store,f.languageUtils=u,f.pluralResolver=new Tl(u,{prepend:this.options.pluralSeparator}),d&&(f.formatter=a(d),f.formatter.init&&f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new Ln(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new Pl(a(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(p,...g)=>{this.emit(p,...g)}),this.modules.languageDetector&&(f.languageDetector=a(this.modules.languageDetector),f.languageDetector.init&&f.languageDetector.init(f,this.options.detection,this.options)),this.modules.i18nFormat&&(f.i18nFormat=a(this.modules.i18nFormat),f.i18nFormat.init&&f.i18nFormat.init(this)),this.translator=new Ts(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=ms),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=Fr(),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=ms){var i,o;let s=r;const a=he(e)?e:this.language;if(typeof e=="function"&&(s=e),!this.options.resources||this.options.partialBundledLanguages){if((a==null?void 0:a.toLowerCase())==="cimode"&&(!this.options.preload||this.options.preload.length===0))return s();const l=[],c=d=>{if(!d||d==="cimode")return;this.services.languageUtils.toResolveHierarchy(d).forEach(f=>{f!=="cimode"&&(l.includes(f)||l.push(f))})};a?c(a):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),s(d)})}else s(null)}reloadResources(e,r,s){const a=Fr();return typeof e=="function"&&(s=e,e=void 0),typeof r=="function"&&(s=r,r=void 0),e||(e=this.languages),r||(r=this.options.ns),s||(s=ms),this.services.backendConnector.reload(e,r,i=>{a.resolve(),s(i)}),a}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"&&Pi.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 s=this.languages[r];if(!["cimode","dev"].includes(s)&&this.store.hasLanguageSomeTranslations(s)){this.resolvedLanguage=s;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 s=Fr();this.emit("languageChanging",e);const a=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&&(a(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,s.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||a(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),s}getFixedT(e,r,s,a){const i=a==null?void 0:a.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||s||o.keyPrefix);const p={...this.options,...u};Array.isArray(i)&&!f&&(p.ns=i),typeof u.keyPrefix=="function"&&(u.keyPrefix=wr(u.keyPrefix,p));const g=this.options.keySeparator||".";let h;return u.keyPrefix&&Array.isArray(l)?h=l.map(x=>(typeof x=="function"&&(x=wr(x,p)),`${u.keyPrefix}${g}${x}`)):(typeof l=="function"&&(l=wr(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=s,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 s=r.lng||this.resolvedLanguage||this.languages[0],a=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(s.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(s,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(s,e)&&(!a||o(i,e)))}loadNamespaces(e,r){const s=Fr();return this.options.ns?(he(e)&&(e=[e]),e.forEach(a=>{this.options.ns.includes(a)||this.options.ns.push(a)}),this.loadResources(a=>{s.resolve(),r&&r(a)}),s):(r&&r(),Promise.resolve())}loadLanguages(e,r){const s=Fr();he(e)&&(e=[e]);const a=this.options.preload||[],i=e.filter(o=>!a.includes(o)&&this.services.languageUtils.isSupportedCode(o));return i.length?(this.options.preload=a.concat(i),this.loadResources(o=>{s.resolve(),r&&r(o)}),s):(r&&r(),Promise.resolve())}dir(e){var a,i;if(e||(e=this.resolvedLanguage||(((a=this.languages)==null?void 0:a.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"],s=((i=this.services)==null?void 0:i.languageUtils)||new An(ua());return e.toLowerCase().indexOf("-latn")>1?"ltr":r.includes(s.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},r){const s=new Ur(e,r);return s.createInstance=Ur.createInstance,s}cloneInstance(e={},r=ms){const s=e.forkResourceStore;s&&delete e.forkResourceStore;const a={...this.options,...e,isClone:!0},i=new Ur(a);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)},s){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 Cn(l,a),i.services.resourceStore=i.store}if(e.interpolation){const c={...ua().interpolation,...this.options.interpolation,...e.interpolation},d={...a,interpolation:c};i.services.interpolator=new Ln(d)}return i.translator=new Ts(i.services,a),i.translator.on("*",(l,...c)=>{i.emit(l,...c)}),i.init(a,r),i.translator.options=a,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 Je=Ur.createInstance();Je.createInstance;Je.dir;Je.init;Je.loadResources;Je.reloadResources;Je.use;Je.changeLanguage;Je.getFixedT;Je.t;Je.exists;Je.setDefaultNamespace;Je.hasLoadedNamespace;Je.loadNamespaces;Je.loadLanguages;const Ul=(t,e,r,s)=>{var i,o,l,c;const a=[r,{code:e,...s||{}}];if((o=(i=t==null?void 0:t.services)==null?void 0:i.logger)!=null&&o.forward)return t.services.logger.forward(a,"warn","react-i18next::",!0);fr(a[0])&&(a[0]=`react-i18next:: ${a[0]}`),(c=(l=t==null?void 0:t.services)==null?void 0:l.logger)!=null&&c.warn?t.services.logger.warn(...a):console!=null&&console.warn&&console.warn(...a)},Mn={},ja=(t,e,r,s)=>{fr(r)&&Mn[r]||(fr(r)&&(Mn[r]=new Date),Ul(t,e,r,s))},Ui=(t,e)=>()=>{if(t.isInitialized)e();else{const r=()=>{setTimeout(()=>{t.off("initialized",r)},0),e()};t.on("initialized",r)}},Ca=(t,e,r)=>{t.loadNamespaces(e,Ui(t,r))},Fn=(t,e,r,s)=>{if(fr(r)&&(r=[r]),t.options.preload&&t.options.preload.indexOf(e)>-1)return Ca(t,r,s);r.forEach(a=>{t.options.ns.indexOf(a)<0&&t.options.ns.push(a)}),t.loadLanguages(e,Ui(t,s))},Ol=(t,e,r={})=>!e.languages||!e.languages.length?(ja(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(t,{lng:r.lng,precheck:(s,a)=>{if(r.bindI18n&&r.bindI18n.indexOf("languageChanging")>-1&&s.services.backendConnector.backend&&s.isLanguageChangingTo&&!a(s.isLanguageChangingTo,t))return!1}}),fr=t=>typeof t=="string",zl=t=>typeof t=="object"&&t!==null,Bl=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,Vl={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},Hl=t=>Vl[t],ql=t=>t.replace(Bl,Hl);let Aa={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:ql,transDefaultProps:void 0};const Wl=(t={})=>{Aa={...Aa,...t}},Kl=()=>Aa;let Oi;const Gl=t=>{Oi=t},Xl=()=>Oi,Yl={type:"3rdParty",init(t){Wl(t.options.react),Gl(t)}},Ql=m.createContext();class Jl{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(r=>{this.usedNamespaces[r]||(this.usedNamespaces[r]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var fa={exports:{}},ma={};/**
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 Rn;function Zl(){if(Rn)return ma;Rn=1;var t=el();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,s=t.useState,a=t.useEffect,i=t.useLayoutEffect,o=t.useDebugValue;function l(f,p){var g=p(),h=s({inst:{value:g,getSnapshot:p}}),x=h[0].inst,b=h[1];return i(function(){x.value=g,x.getSnapshot=p,c(x)&&b({inst:x})},[f,g,p]),a(function(){return c(x)&&b({inst:x}),f(function(){c(x)&&b({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 ma.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:u,ma}var $n;function ec(){return $n||($n=1,fa.exports=Zl()),fa.exports}var tc=ec();const rc=(t,e)=>{if(fr(e))return e;if(zl(e)&&fr(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},sc={t:rc,ready:!1},ac=()=>()=>{},Ee=(t,e={})=>{var A,N,I;const{i18n:r}=e,{i18n:s,defaultNS:a}=m.useContext(Ql)||{},i=r||s||Xl();i&&!i.reportNamespaces&&(i.reportNamespaces=new Jl),i||ja(i,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=m.useMemo(()=>{var $;return{...Kl(),...($=i==null?void 0:i.options)==null?void 0:$.react,...e}},[i,e]),{useSuspense:l,keyPrefix:c}=o,d=a||((A=i==null?void 0:i.options)==null?void 0:A.defaultNS),u=fr(d)?[d]:d||["translation"],f=m.useMemo(()=>u,u);(I=(N=i==null?void 0:i.reportNamespaces)==null?void 0:N.addUsedNamespaces)==null||I.call(N,f);const p=m.useRef(0),g=m.useCallback($=>{if(!i)return ac;const{bindI18n:U,bindI18nStore:X}=o,j=()=>{p.current+=1,$()};return U&&i.on(U,j),X&&i.store.on(X,j),()=>{U&&U.split(" ").forEach(L=>i.off(L,j)),X&&X.split(" ").forEach(L=>i.store.off(L,j))}},[i,o]),h=m.useRef(),x=m.useCallback(()=>{if(!i)return sc;const $=!!(i.isInitialized||i.initializedStoreOnce)&&f.every(C=>Ol(C,i,o)),U=e.lng||i.language,X=p.current,j=h.current;if(j&&j.ready===$&&j.lng===U&&j.keyPrefix===c&&j.revision===X)return j;const B={t:i.getFixedT(U,o.nsMode==="fallback"?f:f[0],c,{scopeNs:f}),ready:$,lng:U,keyPrefix:c,revision:X};return h.current=B,B},[i,f,c,o,e.lng]),[b,k]=m.useState(0),{t:S,ready:E}=tc.useSyncExternalStore(g,x,x);m.useEffect(()=>{if(i&&!E&&!l){const $=()=>k(U=>U+1);e.lng?Fn(i,e.lng,f,$):Ca(i,f,$)}},[i,e.lng,f,E,l,b]);const _=i||{},v=m.useRef(null),M=m.useRef(),F=$=>{const U=Object.getOwnPropertyDescriptors($);U.__original&&delete U.__original;const X=Object.create(Object.getPrototypeOf($),U);if(!Object.prototype.hasOwnProperty.call(X,"__original"))try{Object.defineProperty(X,"__original",{value:$,writable:!1,enumerable:!1,configurable:!1})}catch{}return X},y=m.useMemo(()=>{const $=_,U=$==null?void 0:$.language;let X=$;$&&(v.current&&v.current.__original===$?M.current!==U?(X=F($),v.current=X,M.current=U):X=v.current:(X=F($),v.current=X,M.current=U));const j=!E&&!l?(...B)=>(ja(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."),S(...B)):S,L=[j,X,E];return L.t=j,L.i18n=X,L.ready=E,L},[S,_,E,_.resolvedLanguage,_.language,_.languages]);if(i&&l&&!E)throw new Promise($=>{const U=()=>$();e.lng?Fn(i,e.lng,f,U):Ca(i,f,U)});return y},nc={de:{translation:ll},en:{translation:ol},es:{translation:il},fr:{translation:nl},ja:{translation:al},pt:{translation:sl},zh:{translation:rl}};Je.use(Yl).init({resources:nc,lng:"en",fallbackLng:"en",interpolation:{escapeValue:!1},returnNull:!1});var ic={agentMode:{mode:"single",defaultAdapterId:"chat-with-files"},application:{name:"ORBIT Chat",description:"Explore ideas with ORBIT's AI copilots, share context, and build together.",inputPlaceholder:"Message ORBIT...",settingsAboutMsg:"ORBIT Chat",locale:"en-US",favicon:null},i18n:{activeLanguages:["en","fr","es","pt","de","ja","zh"],defaultLanguage:"en"},seo:{includeSitemap:!1,siteUrl:"http://localhost:5173",exposeAgentNotes:!0},debug:{consoleDebug:!1},features:{enableUpload:!0,enableAudioOutput:!0,enableAudioInput:!0,enableFeedbackButtons:!0,enableConversationThreads:!0,enableAutocomplete:!0},voice:{silenceTimeoutMs:4e3,recognitionLanguage:""},limits:{files:{perConversation:5,maxSizeMB:50,totalFiles:100},conversations:{maxConversations:10,messagesPerConversation:1e3,messagesPerThread:1e3,totalMessages:1e4},messages:{maxLength:1e4}},guestLimits:{files:{perConversation:1,maxSizeMB:5,totalFiles:1},conversations:{maxConversations:2,messagesPerConversation:5,messagesPerThread:2,totalMessages:10},messages:{maxLength:500},rateLimit:{enabled:!0,windowMs:6e4,maxRequests:60,chat:{windowMs:6e4,maxRequests:10}}},auth:{enabled:!1,provider:"entra"},header:{enabled:!0,logoUrl:"",logoUrlLight:"",logoUrlDark:"",logoHeight:"3.5rem",logoWidth:"auto",bgColor:"",textColor:"",showBorder:!1,navLinks:[{label:"Docs",url:"/"},{label:"About",url:"/about"}]},footer:{enabled:!0,text:"Copyright © 2025 Schmitech Inc.",bgColor:"",textColor:"",showBorder:!1,layout:"stacked",align:"center",topPadding:"large",navLinks:[{label:"Support",url:"/"},{label:"Privacy",url:"/about"}]},adapters:[{id:"simple-chat",name:"Simple AI Chat",apiUrl:"http://localhost:3000",description:"Basic chat interface using the default conversational agent (Similar to ChatGPT - no files).",inputPlaceholder:"Simple chat, ask anything..."},{id:"web-search",name:"Simple AI Chat (Web Search)",apiUrl:"http://localhost:3000",description:"Basic chat interface using the default conversational agent with web search supports.",inputPlaceholder:"Simple chat, ask anything..."},{id:"chat-with-files",name:"Simple AI Chat (Multimodal)",apiUrl:"http://localhost:3000",description:"Extract knowledge from PDF, Images, Word, etc. (Similar to ChatGPT Multimodal)",inputPlaceholder:"Files chat, ask anything..."},{id:"image-generator",name:"AI Image Generator",apiUrl:"http://localhost:3000",description:"Generate images from text descriptions using DALL-E 3 or Imagen 3.",inputPlaceholder:"Describe the image you want to create..."},{id:"video-generator",name:"AI Video Generator",apiUrl:"http://localhost:3000",description:"Generate videos from text descriptions.",inputPlaceholder:"Describe the video you want to create..."},{id:"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:"intent-elasticsearch-log",name:"Log Analysis Assistant",apiUrl:"http://localhost:3000",description:"Analyze app logs, troubleshoot errors, and monitor performance via Elasticsearch."}]};const Na="http://localhost:3000",oc="/favicon.svg",lc="/orbit-logo-light.png",cc="/orbit-logo-dark.png",dc={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 hs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ia(t,e){if(!hs(t)||!hs(e))return e;const r={...t};return Object.keys(e).forEach(s=>{if(s==="__proto__"||s==="constructor"||s==="prototype")return;const a=r[s],i=e[s];hs(a)&&hs(i)?r[s]=Ia(a,i):i!==void 0&&(r[s]=i)}),r}function uc(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 fc(t){return t==="single"?"single":"multi"}function mc(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 hc(){const t=ic||{},e=typeof window<"u"&&window.ORBIT_CHAT_CONFIG||{},r=!!(typeof window<"u"&&window.ORBIT_CHAT_CONFIG);let s=Ia(dc,t);return s=Ia(s,e),(!r||!s.auth.domain)&&(s.auth.domain="dev-3c4dpzhecz4gundm.us.auth0.com"),(!r||!s.auth.clientId)&&(s.auth.clientId="9JSe5xtoi5mLXRuov2K7FHYU10ojCQLH"),!r||s.auth.audience,!r||s.auth.provider,!r||s.auth.tenantId,(!r||s.auth.scopes.length===0)&&(s.auth.scopes=mc("openid profile email User.Read")),s.outOfServiceMessage=uc(s.outOfServiceMessage),s.agentMode.mode=fc(s.agentMode.mode),s.agentMode.defaultAdapterId=typeof s.agentMode.defaultAdapterId=="string"?s.agentMode.defaultAdapterId.trim():"",s}const re=hc();function Pe(){var e;const t=re.adapters;if(Array.isArray(t)&&t.length>0){const r=(e=t[0].apiUrl)==null?void 0:e.trim();if(r)return r}return Na}function lt(t){const e=t==null?void 0:t.trim();return e&&e.length>0?e:Pe()}function gc(){const t=re.adapters;return Array.isArray(t)&&t.length>0?t[0].id:"default-key"}function pc(){return re.agentMode.mode}function Ks(){return pc()==="single"}function Va(){if(!Ks())return null;const t=re.agentMode.defaultAdapterId;return t&&re.adapters.some(r=>{var s;return((s=r==null?void 0:r.id)==null?void 0:s.trim())===t})?t:null}function zi(){const t=Array.isArray(re.i18n.activeLanguages)?re.i18n.activeLanguages.filter(e=>typeof e=="string"):[];return t.length>0?t:["en"]}function xc(){var e;const t=(e=re.i18n.defaultLanguage)==null?void 0:e.trim();return t&&zi().includes(t)?t:"en"}function Ha(){return re.application.name}function qa(){return re.application.description}function Bi(){return re.application.inputPlaceholder}function Pn(t){var a;const e=t==null?void 0:t.trim();if(!e)return null;const r=re.adapters.find(i=>{var o;return((o=i==null?void 0:i.id)==null?void 0:o.trim())===e});return((a=r==null?void 0:r.name)==null?void 0:a.trim())||null}function bc(t){var a;const e=t==null?void 0:t.trim();if(!e)return null;const r=re.adapters.find(i=>{var o;return((o=i==null?void 0:i.id)==null?void 0:o.trim())===e});return((a=r==null?void 0:r.inputPlaceholder)==null?void 0:a.trim())||null}function yc(t){const e=t==null?void 0:t.trim();return!!(e&&re.adapters.some(r=>{var s;return((s=r==null?void 0:r.id)==null?void 0:s.trim())===e&&r.realtimeVoice===!0}))}function Vi(){return re.seo.siteUrl.trim()}function wc(){return Array.isArray(re.seo.alternateSiteUrls)?re.seo.alternateSiteUrls.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function kc(){return Array.isArray(re.seo.hostPatterns)?re.seo.hostPatterns.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function vc(){return re.seo.exposeAgentNotes}function Sc(){var e;return((e=re.application.favicon)==null?void 0:e.trim())||oc}function jc(){return re.features.enableUpload}function Cc(){return re.features.enableAudioOutput}function Ac(){return re.features.enableAudioInput}function gs(){return re.features.enableFeedbackButtons}function Nc(){return re.features.enableConversationThreads}function Hi(){return re.features.enableAutocomplete}function Ic(){return Math.max(1e3,re.voice.silenceTimeoutMs)}function Ec(){return re.voice.recognitionLanguage}function Lc(){const t=Va();if(t)return t;const e=re.adapters;if(Array.isArray(e)&&e.length>0)for(const r of e){const s=typeof(r==null?void 0:r.id)=="string"?r.id.trim():"";if(s)return s}return null}function _c(){return re.outOfServiceMessage}function Wa(){return re.auth.enabled}function st(){const{enabled:t,provider:e,domain:r,clientId:s,tenantId:a}=re.auth;return!t||!s?!1:e==="entra"?!!a:!!r}function Tc(){return re.auth.domain}function qi(){return re.auth.clientId}function Mc(){return re.auth.audience}function Gs(){return re.auth.provider}function Fc(){return re.auth.tenantId}function Ka(){const t=re.auth.scopes;return t.length>0?t:["openid","profile","email"]}function Ea(){return re.header.enabled}function Rc(){return re.header.logoUrl}function $c(){var e;return((e=re.header.logoUrlLight)==null?void 0:e.trim())||lc}function Pc(){var e;return((e=re.header.logoUrlDark)==null?void 0:e.trim())||cc}function Dc(){var t;return((t=re.header.logoHeight)==null?void 0:t.trim())||""}function Uc(){var t;return((t=re.header.logoWidth)==null?void 0:t.trim())||""}function Oc(){return re.header.bgColor}function zc(){return re.header.textColor}function Bc(){return re.header.showBorder}function Wi(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 Ki(){return Wi(re.header.navLinks)}function Gi(){return re.footer.enabled}function Vc(){return re.footer.text}function Hc(){return re.footer.bgColor}function qc(){return re.footer.textColor}function Wc(){return re.footer.showBorder}function Kc(){return re.footer.layout==="inline"?"inline":"stacked"}function Gc(){return re.footer.topPadding==="normal"?"normal":"large"}function Xc(){const t=re.startupScripts;return Array.isArray(t)?t.filter(e=>!!(e&&typeof e=="object")).map(e=>{const r=typeof e.src=="string"?e.src.trim():"",s=typeof e.content=="string"?e.content.trim():"",a=typeof e.id=="string"?e.id.trim():"";return{...e,src:r||void 0,content:s||void 0,id:a||void 0}}).filter(e=>!!(e.src||e.content)):[]}function Yc(){return Wi(re.footer.navLinks)}const Xi=["de","en","es","fr","ja","pt","zh"],ps={de:"Deutsch",en:"English",es:"Español",fr:"Français",ja:"日本語",pt:"Português",zh:"中文"};function Ns(t){return Xi.includes(t)}const Yi=m.createContext(void 0),Qi="orbit-chat-language";function Qc(){const t=zi().filter(Ns);return t.length>0?t:["en"]}function Jc(t){const e=localStorage.getItem(Qi);if(e&&Ns(e)&&t.includes(e))return e;const r=[...navigator.languages||[],navigator.language].filter(Boolean);for(const a of r){const i=a.split("-")[0].toLowerCase();if(Ns(i)&&t.includes(i))return i}const s=xc();return Ns(s)&&t.includes(s)?s:t[0]??"en"}function Zc({children:t}){const[e]=m.useState(()=>Qc()),[r,s]=m.useState(()=>Jc(e));m.useEffect(()=>{Je.changeLanguage(r)},[r]),m.useEffect(()=>{localStorage.setItem(Qi,r)},[r]);const a=i=>{Xi.includes(i)&&s(i)};return n.jsx(Yi.Provider,{value:{currentLanguage:r,activeLanguages:e,setLanguage:a},children:t})}function ed(){const t=m.useContext(Yi);if(!t)throw new Error("useLanguage must be used within LanguageProvider");return t}/**
11
+ * @license lucide-react v0.469.0 - ISC
12
+ *
13
+ * This source code is licensed under the ISC license.
14
+ * See the LICENSE file in the root directory of this source tree.
15
+ */const td=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ji=(...t)=>t.filter((e,r,s)=>!!e&&e.trim()!==""&&s.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 rd={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 sd=m.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:r=2,absoluteStrokeWidth:s,className:a="",children:i,iconNode:o,...l},c)=>m.createElement("svg",{ref:c,...rd,width:e,height:e,stroke:t,strokeWidth:s?Number(r)*24/Number(e):r,className:Ji("lucide",a),...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 ie=(t,e)=>{const r=m.forwardRef(({className:s,...a},i)=>m.createElement(sd,{ref:i,iconNode:e,className:Ji(`lucide-${td(t)}`,s),...a}));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 Ms=ie("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/**
36
+ * @license lucide-react v0.469.0 - ISC
37
+ *
38
+ * This source code is licensed under the ISC license.
39
+ * See the LICENSE file in the root directory of this source tree.
40
+ */const ur=ie("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 vr=ie("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 Dn=ie("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 Fs=ie("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 La=ie("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 ad=ie("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 _a=ie("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 Un=ie("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 Xs=ie("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 nd=ie("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 id=ie("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 od=ie("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 Zi=ie("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 ld=ie("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 eo=ie("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 Ta=ie("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 cd=ie("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 dd=ie("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 ud=ie("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 fd=ie("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 Rs=ie("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 to=ie("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 md=ie("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 hd=ie("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 gd=ie("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 On=ie("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 ro=ie("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 Is=ie("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 pd=ie("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 xd=ie("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 bd=ie("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 yd=ie("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 wd=ie("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 kd=ie("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 vd=ie("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 so=ie("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 Sd=ie("PhoneOff",[["path",{d:"M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.42 19.42 0 0 1-3.33-2.67m-2.67-3.34a19.79 19.79 0 0 1-3.07-8.63A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91",key:"z86iuo"}],["line",{x1:"22",x2:"2",y1:"2",y2:"22",key:"11kh81"}]]);/**
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 jd=ie("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
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 Cd=ie("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/**
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 ao=ie("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"}]]);/**
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 Ad=ie("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"}]]);/**
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 Nd=ie("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"}]]);/**
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 $s=ie("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
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 zn=ie("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"}]]);/**
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 Ga=ie("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"}]]);/**
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 Id=ie("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
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 Ed=ie("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"}]]);/**
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 no=ie("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"}]]);/**
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 io=ie("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"}]]);/**
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 oo=ie("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"}]]);/**
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 Ld=ie("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"}]]);/**
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 Xa=ie("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"}]]);/**
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 _d=ie("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"}]]);/**
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 Ys=ie("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"}]]);/**
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 Td=ie("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"}]]);/**
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 Ge=ie("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/**
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 Md=ie("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"}]]);/**
321
+ * @license lucide-react v0.469.0 - ISC
322
+ *
323
+ * This source code is licensed under the ISC license.
324
+ * See the LICENSE file in the root directory of this source tree.
325
+ */const Fd=ie("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 Rd(t){const e=t.trim().split(`
326
+ `);if(e.length<2)return!1;const r=e[0].trim();if(!r.startsWith("|")||(r.match(/\|/g)||[]).length<2)return!1;const s=e[1].trim();if(!s.startsWith("|")||!/^[\s|:|-]+$/.test(s)||!s.includes("-"))return!1;for(let a=2;a<e.length;a++){const i=e[a].trim();if(i!==""&&!i.startsWith("|"))return!1}return!0}function $d(t){return t.replace(/(^|\n)(```|~~~)\s*\n([\s\S]*?)\n\2(\n|$)/g,(e,r,s,a,i)=>Rd(a)?`${r}
327
+ ${a.trim()}
328
+ ${i}`:e)}function Pd(t){const e={};let r=0;return t=t.replace(/\$\$([\s\S]*?)\$\$/g,(s,a)=>{const i=`__DISPLAY_MATH_${r++}__`;return e[i]=`$$${a}$$`,i}),t=t.replace(/\\\[([\s\S]*?)\\\]/g,(s,a)=>{const i=`__DISPLAY_MATH_${r++}__`;return e[i]=`$$${a}$$`,i}),t=t.replace(/\\\(([\s\S]*?)\\\)/g,(s,a)=>{const i=`__INLINE_MATH_${r++}__`;return e[i]=`$${a}$`,i}),t=t.replace(/(^|\n)(```|~~~)([^\n]*)\n([\s\S]*?)\n\2(\n|$)/g,(s,a,i,o,l,c)=>{const d=`__FENCED_CODE_${r++}__`;return e[d]=`${a}${i}${o}
329
+ ${l}
330
+ ${i}${c}`,d}),t=t.replace(/`([^`]+)`/g,s=>{const a=`__INLINE_CODE_${r++}__`;return e[a]=s,a}),{masked:t,masks:e}}function Dd(t){const e={};let r=0;return t=t.replace(new RegExp("(?<!\\$)\\$(?!\\$)([^$\\n]+?)(?<!\\$)\\$(?!\\$)","g"),(s,a)=>{const i=a.trim();if(/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?(?:\s?[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion)?$/.test(i))return s;const l=`__INLINE_MATH_${r++}__`;return e[l]=`$${a}$`,l}),{masked:t,masks:e}}const Bn=/\\(?: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 Ud(t){const e=/(__INLINE_MATH_\d+__|__DISPLAY_MATH_\d+__|__CURRENCY_\d+__)/g,r=/^(__INLINE_MATH_\d+__|__DISPLAY_MATH_\d+__|__CURRENCY_\d+__)$/;return t.split(`
331
+ `).map(s=>Bn.test(s)?s.split(e).map(a=>!a||r.test(a)||!Bn.test(a)||a.includes("$")?a:a.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(""):s).join(`
332
+ `)}function Od(t){return t.replace(/\$([^$\n]*?)\s*=\s*\$([^$\n]+)\$\s*([^$\n]*?)\$/g,(e,r,s,a)=>{const i=String(r).trimEnd(),o=String(s).trim(),l=String(a).trim(),c=[o,l].filter(Boolean).join(" ");return`$${i} = ${c}$`})}function zd(t){const e=t.split(`
333
+ `);for(let s=0;s<e.length-1;s++){const a=e[s],i=e[s+1]??"";if(!a||!i)continue;const o=i.trim();if(!(o.startsWith("|")&&o.includes("-")))continue;const c=a.indexOf("|");if(c<=0)continue;const d=a.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=a.slice(c);if((x.match(/\|/g)||[]).length<2)continue;const k=d.replace(/\s+$/,""),S=x.replace(/^\s+/,"");k&&(e.splice(s,1,k,S),s++)}const r=[];for(let s=0;s<e.length;s++){const a=e[s],i=a.trim(),l=(e[s+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(a)}return r.join(`
334
+ `)}const Vn=["aligned","align","align*","array","cases","pmatrix","bmatrix","vmatrix","Vmatrix","matrix","smallmatrix","gather","gather*","multline","multline*","split","flalign","flalign*","eqnarray","equation","equation*"];function Bd(t,e){let r=0,s=`__${e}_${r}__`;for(;Object.prototype.hasOwnProperty.call(t,s);)r++,s=`__${e}_${r}__`;return s}function Vd(t,e){if(!Vn.length)return t;const r=Vn.join("|"),s=new RegExp(String.raw`\\begin\{(${r})\}([\s\S]*?)\\end\{\1\}`,"g");return t.replace(s,(a,i,o,l,c)=>{const d=c.slice(0,l),u=c.slice(l+a.length),f=/(\$\$|\\\[)\s*$/.test(d),p=/^\s*(\$\$|\\\])/.test(u);if(f&&p)return a;const g=d.lastIndexOf("\\["),h=d.lastIndexOf("\\]");if(g>h&&g!==-1&&/\\]/.test(u))return a;const b=/\$\$/g;let k=0;for(;b.exec(d)!==null;)k++;if(k%2===1&&/\$\$/.test(u))return a;if((d.replace(/\$\$/g,"__DD__").replace(/\\\$/g,"__ES__").match(/\$/g)||[]).length%2===1){const N=u.replace(/\$\$/g,"__DD__").replace(/\\\$/g,"__ES__");if(/^[^$]*\$(?!\$)/.test(N))return a}const F=Bd(e,"LATEX_ENV"),y=a.trim();return e[F]=`
335
+ $$
336
+ ${y}
337
+ $$
338
+ `,F})}function Hd(t,e){for(const[r,s]of Object.entries(e)){const a=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");t=t.replace(a,()=>s)}return t}const qd=t=>{if(!t||typeof t!="string")return"";try{let e=t.replace(/\r\n/g,`
339
+ `).replace(/\r/g,`
340
+ `);e=$d(e);const{masked:r,masks:s}=Pd(e);e=r,e=e.replace(/<br\s*\/?>/gi,`
341
+ `),e=e.replace(/\\(ne|neq)\$(?=\s*[-+0-9A-Za-z(])/g,"\\$1"),e=Od(e),e=zd(e),e=Vd(e,s);const a=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 b=`__CURRENCY_${i++}__`,k=`__CURRENCY_${i++}__`;return a.set(b,g),a.set(k,x),`${b}${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 b=`__CURRENCY_${i++}__`;return a.set(b,p),b});const{masked:d,masks:u}=Dd(e);return e=d,Object.assign(s,u),e=Ud(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 b=/[\\^_+=<>]|\\b(?:frac|sqrt|sum|int|lim|log|ln|sin|cos|tan|exp)\b/.test(x),k=/\d/.test(x),S=/[()]/.test(x),E=(x.match(/[A-Z]/g)||[]).length,_=(x.match(/[a-z]/g)||[]).length,v=E>=2,M=k||S||v&&_>0;return!b&&!M?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),b=/[+\-*/=<>^_{}()]/.test(g),k=/[a-zA-Z].*\d|\d.*[a-zA-Z]/.test(g),S=/\\(?:alpha|beta|gamma|delta|epsilon|theta|lambda|mu|pi|sigma|omega)/.test(g),E=/\\(?:frac|sqrt|sum|int|lim|log|ln|sin|cos|tan|exp)/.test(g),_=/^[A-Za-z]$/.test(g.trim());return!h&&(x||b||k||S||E||_||g.length>1)?p:`\\$${g}\\$`}),e=e.split(`
342
+ `).map(p=>{const g=p.indexOf("$$");return g===-1||p.trim()==="$$"||p.indexOf("$$",g+2)!==-1?p:p.replace("$$","\\$\\$")}).join(`
343
+ `),a.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=Hd(e,s),e=e.trimEnd()+`
344
+ `,e}catch(e){return console.warn("Error preprocessing markdown:",e),t}},Wd=m.lazy(()=>Et(()=>import("./MermaidRenderer-xd7zfbS-.js").then(t=>t.au),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.MermaidRenderer}))),Kd=m.lazy(()=>Et(()=>import("./SVGRenderer-vTFqYYOJ.js"),__vite__mapDeps([6,1,3,5,7,8,9,2,10])).then(t=>({default:t.SVGRenderer}))),Gd=m.lazy(()=>Et(()=>import("./ChartRenderer-C2e8Hk-R.js"),__vite__mapDeps([11,1,5,4,12,13,14,15,16,17,7,8,9,2,10])).then(t=>({default:t.ChartRenderer}))),Xd=m.lazy(()=>Et(()=>import("./MusicRenderer-CrMDit8N.js"),__vite__mapDeps([18,2,1,5,7,8,9,10])).then(t=>({default:t.MusicRenderer}))),Yd=t=>{var s,a;if(!t)return typeof window<"u"&&((s=window.matchMedia)!=null&&s.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"&&((a=window.matchMedia)!=null&&a.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Qd=(t,e)=>{const[r,s]=m.useState("light"),a=m.useRef("light");return m.useEffect(()=>{var d,u,f;if(e||typeof window>"u"||typeof document>"u")return;const i=()=>{const p=Yd(t.current);p!==a.current&&(a.current=p,s(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},Jd={js:"javascript",jsx:"javascript",ts:"typescript",tsx:"tsx",sh:"bash",shell:"bash",shellsession:"bash",yml:"yaml",yaml:"yaml",py:"python",rb:"ruby",kt:"kotlin",md:"markdown",csharp:"csharp","c#":"csharp","c++":"cpp",tf:"hcl",terraform:"hcl",docker:"dockerfile",dotenv:"env",env:"env",plaintext:"text",text:"text"},Zd=t=>{if(!t)return"";const e=t.match(/(?:^|\s)language-([^\s]+)/);if(!e)return"";const s=e[1].toLowerCase().split("{")[0].split("[")[0].split("<")[0].split(":")[0].trim().replace(/[^a-z0-9+#-]+$/g,"");return s?Jd[s]??s:""},eu=t=>xt.Children.toArray(t).map(e=>typeof e=="string"||typeof e=="number"?String(e):"").join("").replace(/\n$/,""),Hn=({code:t})=>{const{t:e}=Ee(),[r,s]=m.useState(!1),a=async()=>{try{await navigator.clipboard.writeText(t),s(!0),setTimeout(()=>s(!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"),s(!0),setTimeout(()=>s(!1),2e3)}catch(o){console.error("Failed to copy code:",o)}document.body.removeChild(i)}};return n.jsxs("button",{className:"code-copy-button",onClick:a,title:e(r?"markdown.codeBlock.copied":"markdown.codeBlock.copyTitle"),"aria-label":e(r?"markdown.codeBlock.copied":"markdown.codeBlock.copyAriaLabel"),children:[r?n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n.jsx("path",{d:"M13.5 4.5L6 12L2.5 8.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n.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"}),n.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"}),n.jsx("path",{d:"M9.5 6.5L13.5 2.5L9.5 2.5V6.5Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),n.jsx("span",{className:"code-copy-button-text",children:e(r?"markdown.codeBlock.copied":"markdown.codeBlock.copyLabel")})]})},tu=({inline:t,className:e="",children:r,enableGraphs:s=!0,enableMermaid:a=!0,enableSVG:i=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d})=>{const{t:u}=Ee(),f=m.useRef(null),p=Qd(f,d),g=n.jsx("div",{className:"markdown-code-block code-block-container",children:u("markdown.codeBlock.loadingRenderer")});if(t)return n.jsx("code",{className:e,children:r});const h=Zd(e),x=eu(r);if(o&&(h==="chart"||h==="chart-json"||h==="chart-table"))return n.jsx("div",{ref:f,children:n.jsx(m.Suspense,{fallback:g,children:n.jsx(Gd,{code:x,language:h})})});if(l&&(h==="abc"||h==="music"))return n.jsx("div",{ref:f,children:n.jsx(m.Suspense,{fallback:g,children:n.jsx(Xd,{code:x})})});if(s){if(h==="mermaid"&&a)return n.jsx("div",{ref:f,children:n.jsx(m.Suspense,{fallback:g,children:n.jsx(Wd,{code:x})})});if(h==="svg"&&i)return n.jsx("div",{ref:f,children:n.jsx(m.Suspense,{fallback:g,children:n.jsx(Kd,{code:x})})})}if(c&&h){const b=p==="light"?ml:hl;return n.jsxs("div",{ref:f,className:"syntax-highlighted-wrapper code-block-container",children:[n.jsx(Hn,{code:x}),n.jsx(fl,{language:h,style:b,customStyle:{margin:"12px 0",borderRadius:"6px",fontSize:"0.9em"},showLineNumbers:!1,children:x})]})}return n.jsxs("div",{ref:f,className:`markdown-code-block code-block-container ${e}`.trim(),children:[n.jsx(Hn,{code:x}),n.jsx("pre",{style:{margin:0,padding:0,background:"transparent",border:"none"},children:n.jsx("code",{children:x})})]})},qn=new Set(["div","pre","blockquote","ul","ol","table","thead","tbody","tr","td","th","h1","h2","h3","h4","h5","h6","section","article","figure"]),Wn=({children:t,href:e="",className:r="",standalone:s=!1,...a})=>{const i=xt.Children.toArray(t).map(f=>typeof f=="string"?f:"").join("").trim(),o=/^https?:\/\//i.test(e),l=!!(o&&i&&Kn(i)===Kn(e)),c=o?ru(e):null,d=!!(s&&l&&c),u=["markdown-link",d?"markdown-link--card":"markdown-link--inline",r].filter(Boolean).join(" ");return n.jsxs("a",{...a,href:e,target:"_blank",rel:"noopener noreferrer",className:u,children:[n.jsx("span",{className:"markdown-link__content",children:d&&c?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"markdown-link__hostname",children:c.hostname}),c.path&&c.path!=="/"&&n.jsx("span",{className:"markdown-link__path",children:c.path})]}):t}),o&&n.jsx("span",{className:"markdown-link__icon","aria-hidden":"true",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n.jsx("path",{d:"M8 16L16 8M16 8H9M16 8V15",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})})})]})};function Kn(t){return t.trim().replace(/\/$/,"")}function ru(t){try{const e=new URL(t),r=e.hostname.replace(/^www\./i,""),s=`${e.pathname}${e.search}${e.hash}`||"/";return{hostname:r,path:s}}catch{return null}}const _t=({content:t,className:e="",disableMath:r=!1,enableGraphs:s=!0,enableMermaid:a=!0,enableSVG:i=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d="dark"})=>{const u=qd(t);if(!u)return null;const f=r?[yn]:[yn,[dl,{singleDollarTextMath:!0}]],p=[];r||p.push([ul,{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})=>n.jsx("div",{style:{overflowX:"auto",WebkitOverflowScrolling:"touch"},children:n.jsx("table",{...x,children:h})}),a:Wn,code:h=>{const{className:x,children:b,...k}=h,S=x&&/language-/.test(x),E="inline"in h&&typeof h.inline=="boolean"&&h.inline||!S,_=S;return n.jsx(tu,{inline:E,className:x,enableGraphs:s,enableMermaid:a,enableSVG:i,enableCharts:o,enableMusic:l,enableSyntaxHighlighting:c,syntaxTheme:d,"data-block-code":_?"true":void 0,...k,children:b})},p:({node:h,...x})=>{var _;const b=xt.Children.toArray(x.children).filter(v=>!(typeof v=="string"&&v.trim()==="")),k=b.some(v=>{if(!xt.isValidElement(v))return!1;const M=v.props;return(M==null?void 0:M["data-block-code"])==="true"?!0:typeof v.type=="string"?qn.has(v.type):!1}),S=(_=h==null?void 0:h.children)==null?void 0:_.some(v=>{var M;if(v.type==="code")return!0;if(v.type==="element"){if(v.tagName&&qn.has(v.tagName))return!0;if(v.tagName==="code"){const F=(M=v.properties)==null?void 0:M.className;return Array.isArray(F)?F.some(y=>typeof y=="string"&&y.startsWith("language-")):!0}}return!1});if(k||S)return n.jsx(n.Fragment,{children:x.children});if(b.length===1&&xt.isValidElement(b[0])&&b[0].type===Wn){const v=b[0];return n.jsx("p",{...x,children:xt.cloneElement(v,{standalone:!0})})}return n.jsx("p",{...x})}};return n.jsx("div",{className:`markdown-content ${e}`,children:n.jsx(cl,{remarkPlugins:f,rehypePlugins:p,components:g,children:u})})},Ya=()=>re.debug.consoleDebug,z=(...t)=>{Ya()&&console.log(...t)},ye=(...t)=>{Ya()&&console.warn(...t)},xe=(...t)=>{Ya()&&console.error(...t)},Be=(...t)=>{console.error(...t)};function Gn(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 xs({audio:t,audioUrl:e,audioFormat:r="mp3",autoPlay:s=!1,maxSizeMB:a=10,downloadFilename:i}){const{t:o}=Ee(),{isDark:l}=mr(),c=m.useRef(null),[d,u]=m.useState(!1),[f,p]=m.useState(0),[g,h]=m.useState(0),[x,b]=m.useState(!0),[k,S]=m.useState(null),[E,_]=m.useState(null),[v,M]=m.useState(null);m.useEffect(()=>{if(!t)return;let L=null,B=!0;return(async()=>{try{b(!0),S(null),_(null);const q=t.length*3/4/(1024*1024);if(q>a)throw new Error(o("audio.player.audioFileTooLargePlaceholder",{sizeMB:q.toFixed(1),maxMB:a}));if(q>2&&(_(o("audio.player.largeAudioWarning",{sizeMB:q.toFixed(1)})),z("[AudioPlayer] Large audio file detected",{sizeMB:q.toFixed(2)})),!/^[A-Za-z0-9+/=]+$/.test(t.replace(/\s/g,"")))throw new Error(o("audio.player.invalidBase64Error"));const J=atob(t),K=new Uint8Array(J.length);for(let T=0;T<J.length;T++)K[T]=J.charCodeAt(T);const V=Gn(r),oe=new Blob([K],{type:V});if(L=URL.createObjectURL(oe),!B){L&&URL.revokeObjectURL(L);return}M(L),b(!1),z("[AudioPlayer] Audio loaded successfully",{format:r,mimeType:V,size:oe.size})}catch(H){xe("[AudioPlayer] Failed to load audio:",H),B&&(S(o("audio.player.loadFailureError")),b(!1))}})(),()=>{B=!1,L&&URL.revokeObjectURL(L)}},[t,r,a,o]),m.useEffect(()=>{if(t||!e)return;let L=null,B=!1;return(async()=>{try{b(!0),S(null);const H=typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null,q=await fetch(e,{headers:H?{"X-Adapter-Name":H}:{}});if(!q.ok)throw new Error(`Server returned ${q.status}`);if(B)return;const J=await q.arrayBuffer();if(B)return;const K=new Blob([J],{type:Gn(r)});L=URL.createObjectURL(K),M(L),b(!1)}catch(H){xe("[AudioPlayer] Failed to fetch audio from",e,H),B||(S(o("audio.player.loadFailureError")),b(!1))}})(),()=>{B=!0,L&&URL.revokeObjectURL(L)}},[t,e,r,o]),m.useEffect(()=>{s&&v&&c.current&&c.current.play().catch(L=>{xe("[AudioPlayer] Auto-play failed:",L)})},[s,v]);const F=()=>{c.current&&p(c.current.duration)},y=()=>{c.current&&h(c.current.currentTime)},A=()=>u(!0),N=()=>u(!1),I=()=>{u(!1),h(0)},$=()=>{c.current&&(d?c.current.pause():c.current.play().catch(L=>{xe("[AudioPlayer] Playback failed:",L),S(o("audio.player.playbackFailureError"))}))},U=L=>{if(!c.current)return;const B=parseFloat(L.target.value);c.current.currentTime=B,h(B)},X=()=>{if(!v)return;const L=document.createElement("a");L.href=v,L.download=i||`generated-audio.${r}`,L.click()},j=L=>{if(!isFinite(L))return"0:00";const B=Math.floor(L/60),C=Math.floor(L%60);return`${B}:${C.toString().padStart(2,"0")}`};return k?n.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:[n.jsx(Ys,{className:"h-4 w-4"}),n.jsx("span",{children:k})]}):n.jsxs("div",{className:"mt-3 flex flex-col gap-1",children:[E&&n.jsxs("div",{className:"text-xs text-amber-600 dark:text-amber-400 px-1",children:["⚠️ ",E]}),n.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:[n.jsx("audio",{ref:c,src:v??void 0,onLoadedMetadata:F,onTimeUpdate:y,onPlay:A,onPause:N,onEnded:I}),n.jsx("button",{onClick:$,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?n.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-gray-400 border-t-transparent"}):d?n.jsx(vd,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"}):n.jsx(jd,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"})}),n.jsxs("div",{className:"flex flex-1 items-center gap-2",children:[n.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:j(g)}),n.jsx("input",{type:"range",min:"0",max:f||0,value:g,onChange:U,disabled:x||!f,className:"flex-1 cursor-pointer accent-gray-600 dark:accent-[#bfc2cd]",style:{background:(()=>{const L=l?"rgb(191 194 205)":"rgb(75 85 99)",B=l?"rgba(255 255 255 / 0.12)":"rgb(229 231 235)",C=f?g/f*100:0;return`linear-gradient(to right, ${L} 0%, ${L} ${C}%, ${B} ${C}%, ${B} 100%)`})()}}),n.jsx("span",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:j(f)})]}),i&&n.jsx("button",{onClick:X,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:n.jsx(Xs,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"})})]})]})}function Xn({image:t,imageUrl:e,imageFormat:r="png",revisedPrompt:s}){const{t:a}=Ee(),[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 b=typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null,k=await fetch(e,{headers:b?{"X-Adapter-Name":b}:{}});if(!k.ok){console.warn("[ImageDisplay] Server returned",k.status,"for",e);return}if(x)return;const S=await k.arrayBuffer();if(x)return;const E=new Blob([S],{type:`image/${r}`}),_=URL.createObjectURL(E);f.current=_,u(_)}catch(b){console.warn("[ImageDisplay] Failed to fetch image from",e,b)}})(),()=>{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=b=>{b.key==="Escape"&&o(!1)};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[i]);const h=x=>{if(x.stopPropagation(),!g)return;const b=document.createElement("a");b.href=g,b.download=`generated-image.${r}`,b.click()};return g?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"generated-image-wrapper",style:{marginTop:"0.75rem"},children:[n.jsxs("div",{className:"generated-image-container",style:{position:"relative",display:"inline-block",cursor:"zoom-in",maxWidth:"100%"},onClick:()=>o(!0),title:s||a("imageDisplay.generatedImageTitle"),children:[n.jsx("img",{src:g,alt:s||a("imageDisplay.generatedImageAlt"),style:{maxWidth:"100%",maxHeight:"480px",borderRadius:"8px",display:"block",objectFit:"contain"}}),n.jsxs("div",{style:{position:"absolute",bottom:"8px",right:"8px",display:"flex",gap:"6px"},children:[n.jsx("button",{onClick:h,title:a("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:n.jsx(Xs,{size:14})}),n.jsx("button",{onClick:x=>{x.stopPropagation(),o(!0)},title:a("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:n.jsx(Fd,{size:14})})]})]}),s&&n.jsxs("div",{style:{marginTop:"8px",maxWidth:"480px"},children:[n.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?n.jsx(Fs,{size:14}):n.jsx(vr,{size:14}),a(l?"imageDisplay.hidePrompt":"imageDisplay.showPrompt")]}),l&&n.jsxs("div",{style:{marginTop:"8px",padding:"8px 10px",background:"rgba(128,128,128,0.08)",borderRadius:"6px"},children:[n.jsx("span",{style:{display:"block",fontSize:"0.65rem",fontWeight:600,opacity:.5,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"3px"},children:a("imageDisplay.promptLabel")}),n.jsx("span",{style:{fontSize:"0.8rem",lineHeight:1.45,opacity:.85},children:s})]})]})]}),i&&typeof document<"u"&&Hs.createPortal(n.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:[n.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:n.jsx(Ge,{size:20})}),n.jsx("img",{src:g,alt:s||a("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 ha=[750,1500,3e3,5e3],su=new Set([403,404,409,425,429,500,502,503,504]),au=t=>new Promise(e=>setTimeout(e,t));function Yn({video:t,videoUrl:e,videoFormat:r="mp4",revisedPrompt:s,adapterName:a}){const{t:i}=Ee(),[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 b=!1;return(async()=>{try{const k=a||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null);let S=null;for(let M=0;M<=ha.length&&(S=await fetch(e,{headers:k?{"X-Adapter-Name":k}:{}}),!(S.ok||!su.has(S.status)||M===ha.length));M+=1)if(await au(ha[M]),b)return;if(!S||!S.ok){console.warn("[VideoDisplay] Server returned",S==null?void 0:S.status,"for",e);return}if(b)return;const E=await S.arrayBuffer();if(b)return;const _=new Blob([E],{type:`video/${r}`}),v=URL.createObjectURL(_);p.current=v,f(v)}catch(k){console.warn("[VideoDisplay] Failed to fetch video from",e,k)}})(),()=>{b=!0,p.current&&(URL.revokeObjectURL(p.current),p.current=null)}},[e,t,r,a]);const h=(t?`data:video/${r};base64,${t}`:null)??u;m.useEffect(()=>{if(!o)return;const b=k=>{k.key==="Escape"&&l(!1)};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[o]);const x=b=>{if(b.stopPropagation(),!h)return;const k=document.createElement("a");k.href=h,k.download=`generated-video.${r}`,k.click()};return h?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"generated-video-wrapper",style:{marginTop:"0.75rem"},children:[n.jsxs("div",{style:{position:"relative",display:"inline-block",maxWidth:"100%"},children:[n.jsx("video",{src:h,controls:!0,style:{maxWidth:"100%",maxHeight:"480px",borderRadius:"8px",display:"block",backgroundColor:"#000"}}),n.jsxs("div",{style:{position:"absolute",bottom:"48px",right:"8px",display:"flex",gap:"6px"},children:[n.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:n.jsx(Xs,{size:14})}),n.jsx("button",{onClick:b=>{b.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:n.jsx(hd,{size:14})})]})]}),s&&n.jsxs("div",{style:{marginTop:"8px",maxWidth:"480px"},children:[n.jsxs("button",{type:"button",onClick:()=>d(b=>!b),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?n.jsx(Fs,{size:14}):n.jsx(vr,{size:14}),i(c?"videoDisplay.hidePrompt":"videoDisplay.showPrompt")]}),c&&n.jsxs("div",{style:{marginTop:"8px",padding:"8px 10px",background:"rgba(128,128,128,0.08)",borderRadius:"6px"},children:[n.jsx("span",{style:{display:"block",fontSize:"0.65rem",fontWeight:600,opacity:.5,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"3px"},children:i("videoDisplay.promptLabel")}),n.jsx("span",{style:{fontSize:"0.8rem",lineHeight:1.45,opacity:.85},children:s})]})]})]}),o&&n.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:[n.jsx("button",{onClick:b=>{b.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:n.jsx(Ge,{size:20})}),n.jsx("video",{src:h,controls:!0,autoPlay:!0,style:{maxWidth:"92vw",maxHeight:"92vh",borderRadius:"8px"},onClick:b=>b.stopPropagation()})]})]}):null}let Ps=null;function lo(t){Ps=t}function Qs(){Ps=null}async function Qa(){if(!Ps)return null;try{return await Ps()}catch{return null}}let Ma=!1,Vr=null;const Fa=new Set;function co(){Fa.forEach(t=>t())}function vt(){return Ma}function nu(){return Vr}function Js(t){Ma!==t&&(Ma=t,!t&&Vr!==null&&(Vr=null),co())}function kr(t){const e=typeof t=="string"&&t.trim().length>0?t.trim():null;Vr!==e&&(Vr=e,co())}function iu(t){return Fa.add(t),()=>{Fa.delete(t)}}const Qn="orbitchat-guest-user-id";function bs(t){if(typeof t!="string")return null;const e=t.trim();return e.length>0?e:null}function ou(t){const e=t.split(".");if(e.length<2)return null;try{const r=e[1].replace(/-/g,"+").replace(/_/g,"/"),s=r.padEnd(Math.ceil(r.length/4)*4,"="),a=atob(s);return JSON.parse(a)}catch{return null}}function lu(){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,s=>s.toString(16).padStart(2,"0")).join("")}`}function cu(){if(typeof window>"u")return"guest:orbitchat:server";const t=window.localStorage.getItem(Qn);if(t&&t.trim().length>0)return t;const e=lu();return window.localStorage.setItem(Qn,e),e}async function uo(){const t=nu();if(t)return t;const e=await Qa();if(e){const r=ou(e),s=bs(r==null?void 0:r.sub)||bs(r==null?void 0:r.user_id)||bs(r==null?void 0:r.preferred_username)||bs(r==null?void 0:r.email);if(s)return s}return vt()?"authenticated:orbitchat:unknown":cu()}const du={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"},Jn={pdf:"PDF",docx:"Word document",xlsx:"Excel workbook",pptx:"PowerPoint deck",md:"Markdown document",csv:"CSV file"},Es=/[\uE000-\uF8FF]|\\[eE][0-9a-fA-F]{2,3}|\\[fF][0-8][0-9a-fA-F]{2,3}/,uu=/((?:p\.)?generated-docx-preview-num-\d+-\d+:before\s*\{[^}]*?)content\s*:\s*"([^"]*)"\s*;([^}]*?\})/g;function fu(t){var r;return Es.test(t)?`•${((r=t.match(/(?:\\9|\t|\u00A0| )+$/))==null?void 0:r[0])||"\\9"}`:null}function Zn(t){Array.from(t.querySelectorAll("style")).forEach(s=>{const a=s.textContent;!a||!Es.test(a)||(s.textContent=a.replace(uu,(i,o,l,c)=>{const d=fu(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(s=>{if(!/\b(symbol|wingdings|webdings)\b/i.test(s.style.fontFamily))return;const a=s.textContent||"";Es.test(a)&&(s.textContent=a.replace(Es,"•"),s.style.fontFamily="")})}function mu(t){return(t||"pdf").toLowerCase().replace(/^\./,"")||"pdf"}function hu(t){const e=window.atob(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s+=1)r[s]=e.charCodeAt(s);return r.buffer}function gu(t){return t==="xlsx"||t==="csv"?n.jsx(eo,{className:"h-5 w-5"}):t==="pptx"?n.jsx(ao,{className:"h-5 w-5"}):t==="md"?n.jsx(Zi,{className:"h-5 w-5"}):n.jsx(Ta,{className:"h-5 w-5"})}function ei({document:t,documentUrl:e,documentFormat:r="pdf",revisedPrompt:s,adapterName:a}){const{t:i}=Ee(),o=mu(r),[l,c]=m.useState(t||e?"loading":"idle"),[d,u]=m.useState(null),[f,p]=m.useState(null),[g,h]=m.useState([]),[x,b]=m.useState(""),[k,S]=m.useState(null),[E,_]=m.useState([]),[v,M]=m.useState(0),[F,y]=m.useState(!1),[A,N]=m.useState(null),I=m.useRef(null),$=m.useRef(null),U=m.useRef(null),X=s||Jn[o]||i("documentDisplay.generatedDocument"),j=m.useMemo(()=>`generated-document.${o}`,[o]),L=du[o]||"application/octet-stream";m.useEffect(()=>{if(!t&&!e)return;let q=!1;return(async()=>{c("loading"),N(null),h([]),b(""),S(null),_([]),M(0);try{const K=t?hu(t):await(async()=>{const T=(a==null?void 0:a.trim())||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),Q={"X-User-ID":await uo()};T&&(Q["X-Adapter-Name"]=T);const R=await Qa();R&&(Q.Authorization=`Bearer ${R}`);const W=await fetch(e,{headers:Q});if(!W.ok)throw new Error(`Server returned ${W.status}`);return W.arrayBuffer()})();if(q)return;const V=new Blob([K],{type:L}),oe=URL.createObjectURL(V);if(I.current&&URL.revokeObjectURL(I.current),I.current=oe,u(oe),p(K.slice(0)),o==="xlsx"){const{default:T}=await Et(async()=>{const{default:W}=await import("./index-CZz_ECqk.js");return{default:W}},[]),R=(await T(V))[0];b((R==null?void 0:R.sheet)||"First sheet"),h(((R==null?void 0:R.data)||[]).slice(0,100).map(W=>W.slice(0,30).map(ne=>ne==null?"":String(ne))))}if(o==="md"&&S(new TextDecoder("utf-8").decode(K)),o==="csv"){const T=new TextDecoder("utf-8").decode(K),{default:Q}=await Et(async()=>{const{default:W}=await import("./papaparse.min-D13ujVVP.js").then(ne=>ne.p);return{default:W}},__vite__mapDeps([19,1])),R=Q.parse(T,{skipEmptyLines:!0});M(R.data.length),_(R.data.slice(0,25))}c("ready")}catch(K){if(q)return;console.warn("[DocumentDisplay] Failed to load document from",e,K),N(K instanceof Error?K.message:"Unable to load document"),c("error")}})(),()=>{q=!0,I.current&&(URL.revokeObjectURL(I.current),I.current=null)}},[a,t,e,o,L]),m.useEffect(()=>{if(l!=="ready"||o!=="docx"||!f||!$.current)return;const q=$.current;q.replaceChildren(),Et(()=>import("./docx-preview-DehBmhog.js"),__vite__mapDeps([20,1])).then(async({renderAsync:J})=>{await J(f.slice(0),q,void 0,{className:"generated-docx-preview",inWrapper:!1,ignoreWidth:!0,ignoreHeight:!0}),Zn(q)}).catch(J=>{console.warn("[DocumentDisplay] Failed to render DOCX preview",J),N("Unable to render document preview")})},[f,o,l]),m.useEffect(()=>{if(!F||o!=="docx"||!f||!U.current)return;const q=U.current;q.replaceChildren(),Et(()=>import("./docx-preview-DehBmhog.js"),__vite__mapDeps([20,1])).then(async({renderAsync:J})=>{await J(f.slice(0),q,void 0,{className:"generated-docx-preview",inWrapper:!1,ignoreWidth:!0,ignoreHeight:!0}),Zn(q)}).catch(J=>{console.warn("[DocumentDisplay] Failed to render modal DOCX preview",J)})},[f,o,F]),m.useEffect(()=>{if(!F)return;const q=J=>{J.key==="Escape"&&y(!1)};return window.document.addEventListener("keydown",q),()=>window.document.removeEventListener("keydown",q)},[F]);const B=q=>{if(q==null||q.stopPropagation(),!d)return;const J=window.document.createElement("a");J.href=d,J.download=j,J.click()},C=l==="ready"&&(o==="pdf"||o==="docx"||o==="xlsx"||o==="md"||o==="csv"),H=C&&o!=="xlsx"&&o!=="csv";return l==="idle"?null:n.jsxs(n.Fragment,{children:[n.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:[n.jsxs("div",{className:"flex items-center gap-3 border-b border-gray-100 px-3 py-2.5 dark:border-[#3b3c49]",children:[n.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:gu(o)}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-sm font-medium text-[#353740] dark:text-[#ececf1]",children:X}),n.jsxs("p",{className:"text-xs text-gray-500 dark:text-[#bfc2cd]",children:[Jn[o]||`${o.toUpperCase()} document`,l==="loading"?` · ${i("documentDisplay.loadingPreview")}`:"",l==="error"?` · ${A||i("documentDisplay.previewUnavailableShort")}`:""]})]}),H&&n.jsx("button",{type:"button",onClick:()=>y(!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:n.jsx(nd,{className:"h-4 w-4"})}),n.jsx("button",{type:"button",onClick:B,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:n.jsx(Xs,{className:"h-4 w-4"})})]}),C&&n.jsxs("div",{className:"max-h-[460px] overflow-auto bg-gray-50 dark:bg-[#171717]",children:[o==="pdf"&&d&&n.jsx("iframe",{src:d,title:X,className:"block h-[460px] w-full border-0 bg-white"}),o==="docx"&&n.jsx("div",{ref:$,className:"min-h-[240px] bg-white p-5 text-sm text-[#111827] dark:bg-white dark:text-[#111827]"}),o==="xlsx"&&n.jsxs("div",{className:"p-3",children:[x&&n.jsx("p",{className:"mb-2 text-xs font-medium text-gray-500 dark:text-[#bfc2cd]",children:x}),n.jsx("div",{className:"overflow-auto rounded-md border border-gray-200 bg-white dark:border-[#3b3c49] dark:bg-[#202123]",children:n.jsx("table",{className:"min-w-full border-collapse text-left text-xs",children:n.jsx("tbody",{children:g.length>0?g.map((q,J)=>n.jsx("tr",{className:J===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:q.map((K,V)=>n.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:K},V))},J)):n.jsx("tr",{children:n.jsx("td",{className:"px-3 py-4 text-sm text-gray-500 dark:text-[#bfc2cd]",children:i("documentDisplay.noSheetDataFound")})})})})})]}),o==="md"&&k!==null&&n.jsx("div",{className:"bg-white p-5 text-sm text-[#111827] dark:bg-[#171717] dark:text-[#ececf1]",children:n.jsx(_t,{content:k,disableMath:!0})}),o==="csv"&&n.jsxs("div",{className:"p-3",children:[v>25&&n.jsx("p",{className:"mb-2 text-xs text-gray-500 dark:text-[#bfc2cd]",children:i("documentDisplay.csvRowsPreviewMessage",{count:v})}),n.jsx("div",{className:"overflow-auto rounded-md border border-gray-200 bg-white dark:border-[#3b3c49] dark:bg-[#202123]",children:n.jsx("table",{className:"min-w-full border-collapse text-left text-xs",children:n.jsx("tbody",{children:E.length>0?E.map((q,J)=>n.jsx("tr",{className:J===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:q.map((K,V)=>n.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:K},V))},J)):n.jsx("tr",{children:n.jsx("td",{className:"px-3 py-4 text-sm text-gray-500 dark:text-[#bfc2cd]",children:i("documentDisplay.noDataFound")})})})})})]})]}),l==="ready"&&!C&&n.jsx("div",{className:"px-3 py-4 text-sm text-gray-600 dark:text-[#bfc2cd]",children:i("documentDisplay.previewUnavailable")})]}),F&&d&&n.jsxs("div",{onClick:()=>y(!1),className:"fixed inset-0 z-[9999] flex items-center justify-center bg-black/85 p-4",children:[n.jsx("button",{onClick:q=>{q.stopPropagation(),y(!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:n.jsx(Ge,{className:"h-5 w-5"})}),n.jsxs("div",{onClick:q=>q.stopPropagation(),className:"h-[92vh] w-[92vw] overflow-auto rounded-lg bg-white",children:[o==="pdf"&&n.jsx("iframe",{src:d,title:X,className:"h-full w-full border-0"}),o==="docx"&&n.jsx("div",{ref:U,className:"min-h-full bg-white p-8 text-[#111827]"}),o==="md"&&k!==null&&n.jsx("div",{className:"min-h-full bg-white p-8 text-sm text-[#111827]",children:n.jsx(_t,{content:k,disableMath:!0})})]})]})]})}const pu=["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 s=t.current,a=document.activeElement,i=Array.from(s.querySelectorAll(pu)).filter(d=>d.tabIndex!==-1),o=i[0]||s,l=i[i.length-1]||s;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(),s.focus({preventScroll:!0});return}const u=document.activeElement;if(d.shiftKey){(!u||u===o||!s.contains(u))&&(d.preventDefault(),l.focus({preventScroll:!0}));return}(!u||u===l||!s.contains(u))&&(d.preventDefault(),o.focus({preventScroll:!0}))};return document.addEventListener("keydown",c),()=>{var d;document.removeEventListener("keydown",c),(d=a==null?void 0:a.focus)==null||d.call(a,{preventScroll:!0})}},[e,r,t])}function Ds({isOpen:t,onClose:e,onConfirm:r,title:s,message:a,confirmText:i,cancelText:o,type:l="danger",isLoading:c=!1}){const d=m.useRef(null);Hr(d,{enabled:t,onEscape:e});const{t:u}=Ee(),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"}}})(),b=n.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:n.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:[n.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-[#2d2f39]",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:`w-10 h-10 rounded-full ${x.iconBg} flex items-center justify-center`,children:n.jsx(Xa,{className:`w-5 h-5 ${x.icon}`})}),n.jsx("h2",{id:"confirm-title",className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:s})]}),n.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:n.jsx(Ge,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),n.jsx("div",{className:"p-6",children:n.jsx("p",{className:"text-gray-600 dark:text-gray-300 leading-relaxed",children:a})}),n.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:[n.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}),n.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?n.jsxs("div",{className:"flex items-center gap-2",children:[n.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"?b:Hs.createPortal(b,document.body)}const xu=["#","*","`","[","]","(",")","{","}","|","<",">"],fo=t=>xu.some(e=>t.includes(e));function mo(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 s=/\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),a=fo(t),i=/[-.,;:!?'"()]/.test(t);if(!s&&!a&&!i)return!0}return!!(r.length>5e4&&e.test(r)&&t.replace(/[A-Za-z0-9+/=\s]/g,"").length<10)}const bu=/(?:\u202F|\u2009|\u200A|\u200B|\u200C|\u200D|\uFEFF)/g;function qr(t){if(!t)return t;let e=t.replace(bu," ");if(mo(e))return"";const r=/([A-Za-z0-9+/=]{10000,})/g;return e=e.replace(r,s=>{const a=s.replace(/\s+/g,"");if(a.length>1e4&&/^[A-Za-z0-9+/=]+$/.test(a)){const i=/\b(function|const|let|var|class|return|import|export|if|else|while|for|true|false|null|def|print)\b/i.test(s),o=fo(s),l=/[-.,;:!?'"()]/.test(s);if(!i&&!o&&!l)return""}return s}),e}function Ra(t,e=5e4){return!t||t.length<=e?t:mo(t)?"":t.substring(0,e)+`
345
+
346
+ ... (content truncated due to length)`}const yu={maxFilesPerConversation:re.limits.files.perConversation,maxFileSizeMB:re.limits.files.maxSizeMB,maxTotalFiles:re.limits.files.totalFiles,maxConversations:re.limits.conversations.maxConversations,maxMessagesPerConversation:re.limits.conversations.messagesPerConversation,maxMessagesPerThread:re.limits.conversations.messagesPerThread,maxTotalMessages:re.limits.conversations.totalMessages,maxMessageLength:re.limits.messages.maxLength};function wu(t){const e=re.guestLimits;switch(t){case"maxConversations":return e.conversations.maxConversations;case"maxMessagesPerConversation":return e.conversations.messagesPerConversation;case"maxMessagesPerThread":return e.conversations.messagesPerThread;case"maxTotalMessages":return e.conversations.totalMessages;case"maxFilesPerConversation":return e.files.perConversation;case"maxTotalFiles":return e.files.totalFiles;case"maxMessageLength":return e.messages.maxLength;case"maxFileSizeMB":return e.files.maxSizeMB;default:return}}const le=new Proxy(yu,{get(t,e){if(st()&&!vt()){const r=wu(e);if(r!==void 0)return r}return t[e]}});function Sr(){return m.useSyncExternalStore(iu,vt,vt)}class ho extends Error{constructor(r,s){super(r);Ze(this,"status");Ze(this,"statusText");this.name="ApiRequestError",this.status=s.status,this.statusText=s.statusText}}async function Ue(t={}){const e={"X-User-ID":await uo(),...t},r=await Qa();return r&&(e.Authorization=`Bearer ${r}`),e}function kt(t){return encodeURIComponent(t)}function ku(t){return!t||t.length===0?"":`?file_ids=${t.map(encodeURIComponent).join(",")}`}async function Rr(t){const e=`API request failed: ${t.status} ${t.statusText}`;try{if((t.headers.get("content-type")||"").includes("application/json")){const s=await t.json(),a=typeof s.detail=="string"&&s.detail.trim()||typeof s.error=="string"&&s.error.trim()||typeof s.message=="string"&&s.message.trim();if(a)return`${e}: ${a}`}else{const s=(await t.text()).trim();if(s)return`${e}: ${s}`}}catch{}return e}function ti(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 ys=null;function vu(){let t=null,e=null;const r=(i,o,l)=>{t=o||null,e=l||null},s=(i,o={})=>{const l=new URL(`/api/ws/voice/${kt(i)}`,window.location.origin),c=o.sessionId||t;return c&&l.searchParams.set("session_id",c),o.targetLanguage&&l.searchParams.set("target_language",o.targetLanguage),l.protocol=l.protocol==="https:"?"wss:":"ws:",l.toString()},a=(i,o)=>({getRealtimeVoiceWebSocketUrl:(l,c={})=>s(l,{sessionId:o||void 0,...c}),async*streamChat(l,c,d,u,f,p,g,h,x,b,k,S,E,_){var F,y;const v={messages:[{role:"user",content:l}],stream:c!==!1};d&&d.length>0&&(v.file_ids=d),u&&(v.thread_id=u),f&&(v.audio_input=f),p&&(v.audio_format=p),g&&(v.language=g),h!==void 0&&(v.return_audio=h),x&&(v.tts_voice=x),b&&(v.source_language=b),k&&(v.target_language=k),S&&(v.model=S),E&&(v.skill=E),_&&(v.regenerate_of_message_id=_);const M=await fetch("/api/v1/chat",{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":i,...o?{"X-Session-ID":o}:{}}),body:JSON.stringify(v)});if(!M.ok)throw new Error(await Rr(M));if((F=M.headers.get("content-type"))!=null&&F.includes("text/event-stream")){const A=(y=M.body)==null?void 0:y.getReader(),N=new TextDecoder;let I="";if(!A)throw new Error("Response body is not readable");for(;;){const{done:$,value:U}=await A.read();if($)break;I+=N.decode(U,{stream:!0});const X=I.split(`
347
+ `);I=X.pop()||"";for(const j of X){const L=ti(j);L&&(yield L)}}if(I.trim())for(const $ of I.split(`
348
+ `)){const U=ti($);U&&(yield U)}}else{const A=await M.json();yield{text:A.message||A.response||"",done:!0,audio:A.audio,audioFormat:A.audio_format||A.audioFormat,image:A.image,image_format:A.image_format,image_revised_prompt:A.image_revised_prompt,image_url:A.image_url,video:A.video,video_format:A.video_format,video_revised_prompt:A.video_revised_prompt,video_url:A.video_url,document:A.document,document_format:A.document_format,document_revised_prompt:A.document_revised_prompt,document_url:A.document_url,generated_audio_url:A.generated_audio_url,generated_audio_format:A.generated_audio_format,generated_audio_revised_prompt:A.generated_audio_revised_prompt,model:A.model,assistant_message_id:A.assistant_message_id,threading:A.threading}}},async createThread(l,c){const d=await fetch("/api/threads",{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":i,"X-Session-ID":c}),body:JSON.stringify({message_id:l,session_id:c})});if(!d.ok)throw new Error(`Failed to create thread: ${d.statusText}`);return d.json()},async getThreadInfo(l){const c=await fetch(`/api/threads/${kt(l)}`,{headers:await Ue({"X-Adapter-Name":i})});if(!c.ok)throw new Error(`Failed to get thread info: ${c.statusText}`);return c.json()},async deleteThread(l){const c=await fetch(`/api/threads/${kt(l)}`,{method:"DELETE",headers:await Ue({"X-Adapter-Name":i})});if(!c.ok)throw new Error(`Failed to delete thread: ${c.statusText}`);return c.json()},async submitFeedback(l,c,d,u){const f={message_id:l,session_id:c,feedback_type:d};u!==void 0&&(f.comment=u);const p=await fetch("/api/feedback",{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":i,"X-Session-ID":c}),body:JSON.stringify(f)});if(!p.ok)throw new Error(`Failed to submit feedback: ${p.statusText}`);return p.json()},async getSessionFeedback(l){const c=await fetch(`/api/feedback/${kt(l)}`,{headers:await Ue({"X-Adapter-Name":i})});if(!c.ok)throw new Error(`Failed to get feedback: ${c.statusText}`);return c.json()},async clearConversationHistory(l){const c=l||o;if(!c)throw new Error("No session ID available for clearing conversation history");const d=await fetch(`/api/admin/chat-history/${kt(c)}`,{method:"DELETE",headers:await Ue({"X-Adapter-Name":i})});if(!d.ok)throw new Error(`Failed to clear history: ${d.statusText}`);return d.json()},async getConversationHistory(l,c){const d=l||o;if(!d)throw new Error("No session ID available for conversation history");const u=typeof c=="number"&&Number.isFinite(c)&&c>0?`?limit=${Math.floor(c)}`:"",f=await fetch(`/api/admin/chat-history/${kt(d)}${u}`,{headers:await Ue({"X-Adapter-Name":i})});if(!f.ok)throw new Error(`Failed to load history: ${f.statusText}`);return f.json()},async deleteConversationWithFiles(l,c){const d=l||o;if(!d)throw new Error("No session ID available for deleting conversation");const u=ku(c),f=await fetch(`/api/admin/conversations/${kt(d)}${u}`,{method:"DELETE",headers:await Ue({"X-Adapter-Name":i})});if(!f.ok)throw new Error(`Failed to delete conversation: ${f.statusText}`);return f.json()},getSessionId:()=>o,async uploadFile(l){const c=new FormData;c.append("file",l);const d=await fetch("/api/files/upload",{method:"POST",headers:await Ue({"X-Adapter-Name":i}),body:c});if(!d.ok)throw new Error(`Failed to upload file: ${d.statusText}`);return d.json()},async listFiles(){const l=await fetch("/api/files",{headers:await Ue({"X-Adapter-Name":i})});if(!l.ok)throw new Error(`Failed to list files: ${l.statusText}`);const c=await l.json();return Array.isArray(c)?c:c.files||[]},async getFileInfo(l,c){const d=await fetch(`/api/files/${kt(l)}`,{headers:await Ue({"X-Adapter-Name":i}),signal:c});if(!d.ok)throw new Error(`Failed to get file info: ${d.statusText}`);return d.json()},async queryFile(l,c,d){const u=await fetch(`/api/files/${kt(l)}/query`,{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":i}),body:JSON.stringify({query:c,max_results:d})});if(!u.ok)throw new Error(`Failed to query file: ${u.statusText}`);return u.json()},async deleteFile(l){const c=await fetch(`/api/files/${kt(l)}`,{method:"DELETE",headers:await Ue({"X-Adapter-Name":i})});if(!c.ok)throw new Error(`Failed to delete file: ${c.statusText}`);return c.json()},async validateApiKey(){const l=await fetch(`/api/admin/api-keys/${kt(i)}/status`,{headers:await Ue({"X-Adapter-Name":i})});if(!l.ok)throw new Error(`Failed to validate API key: ${l.statusText}`);return l.json()},async getAdapterInfo(){const l="/api/admin/adapters/info",c=p=>{if(!p)return 0;const g=Number(p);if(Number.isFinite(g)&&g>0)return Math.min(g*1e3,3e4);const h=Date.parse(p);if(!Number.isNaN(h)){const x=h-Date.now();if(x>0)return Math.min(x,3e4)}return 0},d=p=>new Promise(g=>setTimeout(g,p)),u=async()=>fetch(l,{headers:await Ue({"X-Adapter-Name":i})});let f=await u();if(f.status===429){const p=c(f.headers.get("Retry-After"));p>0&&(await d(p),f=await u())}if(!f.ok){const p=await f.text(),g=`${f.status} ${f.statusText}`.trim(),h=f.status===401?`Adapter info request was unauthorized for '${i}'. Verify the adapter exists and you have access.`:`Failed to load adapter info (${g}) for '${i}'.`;throw console.warn("[ProxyApi] Adapter info request failed",{adapter:i,status:f.status,statusText:f.statusText,details:p||void 0}),new ho(h,f)}return f.json()},async stopChat(l,c){const d=await fetch("/api/v1/chat/stop",{method:"POST",headers:await Ue({"Content-Type":"application/json","X-Adapter-Name":i}),body:JSON.stringify({session_id:l,request_id:c})});return d.ok?(await d.json()).status==="cancelled":(console.warn(`[ProxyApi] stopChat failed: ${d.status} ${d.statusText}`),!1)},async getAdapterModels(l){const c=await fetch(`/api/admin/adapters/${encodeURIComponent(l)}/models`,{headers:await Ue({"X-Adapter-Name":i})});if(!c.ok)throw new Error(await Rr(c));return c.json()},async getAllModels(){const l=await fetch("/api/admin/models",{headers:await Ue({"X-Adapter-Name":i})});if(!l.ok)throw new Error(await Rr(l));return l.json()},async getAdapterSkills(l){const c=await fetch(`/api/admin/adapters/${encodeURIComponent(l)}/skills`,{headers:await Ue({"X-Adapter-Name":i})});if(!c.ok)throw new Error(await Rr(c));return c.json()},async getAllSkills(){const l=await fetch("/api/admin/skills",{headers:await Ue({"X-Adapter-Name":i})});if(!l.ok)throw new Error(await Rr(l));return l.json()}});return{configureApi:r,getRealtimeVoiceWebSocketUrl:s,streamChat:async function*(i,o,l,c,d,u,f,p,g,h,x,b,k,S){if(!e)throw new Error("Adapter name is required");yield*a(e,t).streamChat(i,o,l,c,d,u,f,p,g,h,x,b,k,S)},stopChat:async(i,o)=>{if(!e)throw new Error("Adapter name is required");return a(e,t).stopChat(i,o)},ApiClient:class{constructor(o){Ze(this,"client");const l=o.adapterName||null,c=o.sessionId||null;if(!l)throw new Error("Adapter name is required");this.client=a(l,c)}async*streamChat(...o){yield*this.client.streamChat(...o)}get createThread(){var o;return(o=this.client.createThread)==null?void 0:o.bind(this.client)}get getThreadInfo(){var o;return(o=this.client.getThreadInfo)==null?void 0:o.bind(this.client)}get deleteThread(){var o;return(o=this.client.deleteThread)==null?void 0:o.bind(this.client)}get submitFeedback(){var o;return(o=this.client.submitFeedback)==null?void 0:o.bind(this.client)}get getSessionFeedback(){var o;return(o=this.client.getSessionFeedback)==null?void 0:o.bind(this.client)}get clearConversationHistory(){var o;return(o=this.client.clearConversationHistory)==null?void 0:o.bind(this.client)}get getConversationHistory(){var o;return(o=this.client.getConversationHistory)==null?void 0:o.bind(this.client)}get deleteConversationWithFiles(){var o;return(o=this.client.deleteConversationWithFiles)==null?void 0:o.bind(this.client)}get getSessionId(){var o;return(o=this.client.getSessionId)==null?void 0:o.bind(this.client)}get uploadFile(){var o;return(o=this.client.uploadFile)==null?void 0:o.bind(this.client)}get listFiles(){var o;return(o=this.client.listFiles)==null?void 0:o.bind(this.client)}get getFileInfo(){var o;return(o=this.client.getFileInfo)==null?void 0:o.bind(this.client)}get queryFile(){var o;return(o=this.client.queryFile)==null?void 0:o.bind(this.client)}get deleteFile(){var o;return(o=this.client.deleteFile)==null?void 0:o.bind(this.client)}get validateApiKey(){var o;return(o=this.client.validateApiKey)==null?void 0:o.bind(this.client)}get getAdapterInfo(){var o;return(o=this.client.getAdapterInfo)==null?void 0:o.bind(this.client)}get stopChat(){var o;return(o=this.client.stopChat)==null?void 0:o.bind(this.client)}get getAdapterModels(){var o;return(o=this.client.getAdapterModels)==null?void 0:o.bind(this.client)}get getAllModels(){var o;return(o=this.client.getAllModels)==null?void 0:o.bind(this.client)}get getAdapterSkills(){var o;return(o=this.client.getAdapterSkills)==null?void 0:o.bind(this.client)}get getAllSkills(){var o;return(o=this.client.getAllSkills)==null?void 0:o.bind(this.client)}get getRealtimeVoiceWebSocketUrl(){var o;return(o=this.client.getRealtimeVoiceWebSocketUrl)==null?void 0:o.bind(this.client)}}}}async function Su(){return ys||(z("Loading API via Express proxy"),ys=vu(),z("API loaded successfully"),ys)}async function Re(){return await Su()}class ri{static async getAdapterSkills(e,r){const s=await Re(),a=new s.ApiClient({apiUrl:"",adapterName:r});return a.getAdapterSkills?(await a.getAdapterSkills(e)).available_skills:[]}static async getAllSkills(e){const r=await Re(),s=new r.ApiClient({apiUrl:"",adapterName:e});return s.getAllSkills?(await s.getAllSkills()).skills:[]}}const ju=6e4;function go(t={}){const{adapterName:e,enabled:r=!0,selectionScopeKey:s,supportsThreading:a=!1}=t,i=r&&!!e&&!a,o=s??e??"__default__",[l,c]=m.useState([]),[d,u]=m.useState(!1),[f,p]=m.useState(null),[g,h]=m.useState({}),x=m.useRef(null),b=m.useRef(new Map),k=m.useCallback(async v=>{var y,A;const M=v,F=b.current.get(M);if(F&&F.expiresAt>Date.now()){c(F.skills),p(v);return}x.current&&x.current.abort(),x.current=new AbortController,u(!0);try{const[N,I]=await Promise.all([ri.getAdapterSkills(v,v),ri.getAllSkills(v)]);if((y=x.current)!=null&&y.signal.aborted)return;const $=I.filter(U=>N.includes(U.name)&&U.enabled);b.current.set(M,{skills:$,expiresAt:Date.now()+ju}),c($),p(v),z("[useSkills] Loaded",$.length,"skills for adapter",v)}catch(N){if(N instanceof Error&&N.name==="AbortError")return;ye("[useSkills] Failed to load skills:",N instanceof Error?N.message:String(N)),c([]),p(v)}finally{(A=x.current)!=null&&A.signal.aborted||u(!1)}},[]);m.useEffect(()=>{if(!i||!e)return;const v=window.setTimeout(()=>{k(e)},0);return()=>{var M;window.clearTimeout(v),(M=x.current)==null||M.abort()}},[i,e,k]);const S=m.useCallback(v=>{h(M=>{const F=M[o]??null;if(F===v||(F==null?void 0:F.name)===(v==null?void 0:v.name))return M;const y={...M};return v?y[o]=v:delete y[o],y})},[o]),E=m.useCallback(()=>{h(v=>{if(!v[o])return v;const M={...v};return delete M[o],M})},[o]),_=i?g[o]??null:null;return{skills:i&&f===e?l:[],isLoading:i?d||f!==e:!1,selectedSkill:_,selectSkill:S,clearSkill:E}}const si=t=>{let e;const r=new Set,s=(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))}},a=()=>e,l={setState:s,getState:a,getInitialState:()=>c,subscribe:d=>(r.add(d),()=>r.delete(d))},c=e=t(s,a,l);return l},Cu=(t=>t?si(t):si),Au=t=>t;function Nu(t,e=Au){const r=xt.useSyncExternalStore(t.subscribe,xt.useCallback(()=>e(t.getState()),[t,e]),xt.useCallback(()=>e(t.getInitialState()),[t,e]));return xt.useDebugValue(r),r}const ai=t=>{const e=Cu(t),r=s=>Nu(e,s);return Object.assign(r,e),r},po=(t=>t?ai(t):ai),at=po(t=>({showLoginPrompt:!1,promptMessage:"",openLoginPrompt:e=>t({showLoginPrompt:!0,promptMessage:e}),closeLoginPrompt:()=>t({showLoginPrompt:!1,promptMessage:""})})),ws=t=>{const e=t==null?void 0:t.trim();return e||(typeof window<"u"&&window.localStorage?localStorage.getItem("chat-adapter-name"):null)},ks=new Map,ni=(t,e)=>new Promise(r=>{if(e!=null&&e.aborted){r();return}const s=()=>{clearTimeout(a),e==null||e.removeEventListener("abort",s),r()},a=setTimeout(s,t);e==null||e.addEventListener("abort",s,{once:!0})});class Vt{static cancelFilePoll(e){var r;(r=ks.get(e))==null||r.abort()}static async uploadFile(e,r,s,a,i){try{const o=le.maxFileSizeMB*1024*1024;if(e.size>o)throw new Error(`File size exceeds maximum limit of ${le.maxFileSizeMB}MB`);if(!(["application/pdf","text/plain","text/markdown","text/csv","application/json","text/html","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel","application/vnd.ms-excel.sheet.macroEnabled.12","text/x-python","text/x-python-script","text/x-java-source","text/x-java","text/x-sql","text/javascript","application/javascript","text/typescript","application/typescript","text/x-c++src","text/x-csrc","text/x-c","text/x-go","text/x-rust","text/x-ruby","text/x-php","text/x-shellscript","text/x-sh","text/yaml","text/x-yaml","text/xml","application/xml","text/css","text/x-scss","text/x-sass","text/x-less","image/png","image/jpeg","image/tiff","image/webp","audio/wav","audio/mpeg","audio/mp3","audio/mp4","audio/ogg","audio/flac","audio/webm","audio/x-m4a","audio/aac","text/vtt"].includes(e.type)||/\.(pdf|txt|md|csv|json|html|docx|pptx|xlsx|py|java|sql|js|mjs|ts|tsx|cpp|cxx|cc|c|h|hpp|go|rs|rb|php|sh|bash|zsh|yaml|yml|xml|css|scss|sass|less|png|jpe?g|tiff?|webp|wav|mp3|mp4|ogg|flac|webm|m4a|aac|vtt)$/i.test(e.name)||(e.type==="application/x-zip-compressed"||e.type==="application/zip")&&/\.xlsx$/i.test(e.name)))throw new Error(`File type not supported: ${e.type||"unknown"}`);r&&r({filename:e.name,progress:0,status:"uploading"});const d=await Re(),u=(a==null?void 0:a.trim())||Pe(),f=ws(i);if(!f)throw new Error("Adapter not configured. Please select an adapter from the dropdown.");z(`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;const x=new AbortController;ks.set(g.file_id,x);try{h=await this.pollFileStatus(g.file_id,30,2e3,void 0,u,f,x.signal)}catch(b){const k=b instanceof Error?b.message:String(b);if(k.includes("was deleted"))throw new Error(`File ${g.file_id} was deleted during upload`);ye(`File status polling failed for ${g.file_id}:`,b);const S=k.includes("processing failed")||k.includes("timeout");h={file_id:g.file_id,filename:g.filename,mime_type:g.mime_type,file_size:g.file_size,processing_status:S?"failed":g.status||"processing",chunk_count:g.chunk_count,error_message:S?k:void 0}}finally{ks.get(g.file_id)===x&&ks.delete(g.file_id)}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 a=[],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"?a.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(a.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&&ye(`[FileUploadService] ${i.length} of ${e.length} files failed to upload:`,i.map(o=>o.file)),a}static async listFiles(e,r,s){try{const a=await Re(),i=(r==null?void 0:r.trim())||Pe(),o=ws(s);if(!o)throw new Error("Adapter not configured");const l=new a.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(a){Be("Failed to list files:",a);const i=a instanceof Error?a.message:"Failed to list files";throw new Error(i)}}static async getFileInfo(e,r,s,a,i){try{const o=await Re(),l=(s==null?void 0:s.trim())||Pe(),c=ws(a);if(!c)throw new Error("Adapter not configured");const d=new o.ApiClient({apiUrl:l,sessionId:null,adapterName:c});if(!d.getFileInfo)throw new Error("File info retrieval is not available.");const u=await d.getFileInfo(e,i);return{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(o){if(o instanceof DOMException&&o.name==="AbortError")throw new Error(`File ${e} was deleted`);if(o instanceof Error&&(o.message.includes("404")||o.message.includes("File not found")||o.message.includes("Not Found")))throw new Error(`File ${e} was deleted`);Be(`Failed to get file info for ${e}:`,o);const l=o instanceof Error?o.message:`Failed to get file info: ${e}`;throw new Error(l)}}static async pollFileStatus(e,r=30,s=2e3,a,i,o,l){for(let c=0;c<r;c++)try{if(l!=null&&l.aborted)throw new Error(`File ${e} was deleted during upload`);if(a&&!a())throw new Error("Polling cancelled - component unmounted");const d=await this.getFileInfo(e,void 0,i,o,l);if(d.processing_status==="completed")return d;if(d.processing_status==="error"||d.processing_status==="failed"){const u=d.error_message;throw new Error(u||`File processing failed for ${e}`)}c<r-1&&await ni(s,l)}catch(d){const u=d instanceof Error?d.message:String(d);if(u.includes("404")||u.includes("File not found")||u.includes("was deleted"))throw new Error(`File ${e} was deleted during upload`);if(u.includes("component unmounted")||u.includes("processing failed")||u.includes("processing_status")||u.includes("401")||u.includes("403")||u.includes("500")||u.includes("502")||u.includes("503")||u.includes("Authentication")||u.includes("Adapter not configured"))throw d;if(c<r-1){await ni(s,l);continue}throw d}throw new Error(`File processing timeout: ${e} did not complete within ${r*s/1e3} seconds`)}static async deleteFile(e,r,s,a){try{const i=await Re(),o=(s==null?void 0:s.trim())||Pe(),l=ws(a);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 z(`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 Iu{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 s=((e=this.audioContext)==null?void 0:e.state)==="suspended"?this.audioContext.resume():Promise.resolve();let a=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,a=l.play().then(()=>{l.pause()}).catch(()=>{z("[AudioStreamManager] HTMLAudioElement silent unlock failed (will retry on next gesture)")}).finally(()=>{URL.revokeObjectURL(o)})}catch{z("[AudioStreamManager] Could not create silent audio element")}if(await s,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 a,this.isEnabled=!0,z("[AudioStreamManager] Audio playback enabled",{audioContextState:(r=this.audioContext)==null?void 0:r.state}),!0}catch(s){return xe("[AudioStreamManager] Failed to enable audio:",s),!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(),z("[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(s){return xe("[AudioStreamManager] Failed to create AudioContext:",s),!1}}if(((e=this.audioContext)==null?void 0:e.state)==="suspended")try{await this.audioContext.resume()}catch(r){return z("[AudioStreamManager] AudioContext resume deferred",r),!1}return!0}resolveMimeType(e){const r=this.mimeTypeCache.get(e);if(r)return r;let s;switch(e){case"mp3":s="audio/mpeg";break;case"wav":s="audio/wav";break;case"webm":s="audio/webm";break;case"ogg":s="audio/ogg";break;case"opus":{const a=typeof document<"u"?document.createElement("audio"):null;a!=null&&a.canPlayType("audio/ogg; codecs=opus")?s="audio/ogg; codecs=opus":a!=null&&a.canPlayType("audio/webm; codecs=opus")?s="audio/webm; codecs=opus":s="audio/mp4";break}default:s=`audio/${e}`}return this.mimeTypeCache.set(e,s),z(`[AudioStreamManager] Resolved MIME type for "${e}": ${s}`),s}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){z(`[AudioStreamManager] Audio disabled, dropping chunk ${e.chunkIndex}`);return}z(`[AudioStreamManager] Adding chunk ${e.chunkIndex} to queue`),this.audioQueue.push(e),this.audioQueue.sort((r,s)=>r.chunkIndex-s.chunkIndex),this.isPlaying||this.playNextChunk().catch(r=>{xe("[AudioStreamManager] Playback chain error:",r)})}async playNextChunk(){var r,s;if(this.audioQueue.length===0){this.isPlaying=!1,z("[AudioStreamManager] Queue empty, playback complete"),this.onPlaybackEnd&&this.onPlaybackEnd();return}if(!this.isEnabled){z("[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(),z(`[AudioStreamManager] Playing chunk ${e.chunkIndex}`),!e.audio||e.audio.length===0)throw new Error(`Empty audio data for chunk ${e.chunkIndex}`);let a;try{a=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(a.length===0)throw new Error(`Decoded audio data is empty for chunk ${e.chunkIndex}`);const i=new Uint8Array(a.length);for(let f=0;f<a.length;f++)i[f]=a.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){z(`[AudioStreamManager] HTMLAudioElement failed for chunk ${e.chunkIndex}, trying AudioContext fallback`);try{u=await this.playViaAudioContext(i.buffer,e.chunkIndex)}catch(f){xe(`[AudioStreamManager] AudioContext fallback also failed for chunk ${e.chunkIndex}:`,f)}d()}this.currentAudio=null,this.playNextChunk().catch(f=>{xe("[AudioStreamManager] Playback chain error:",f)})}catch(a){if(this.suppressPlaybackErrors){z("[AudioStreamManager] Playback stopped, suppressing audio error");return}const i=a instanceof Error?a.message:String(a);console.error(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,i,a,{audioFormat:e.audioFormat,chunkIndex:e.chunkIndex,audioLength:(r=e.audio)==null?void 0:r.length,audioContextState:(s=this.audioContext)==null?void 0:s.state,isEnabled:this.isEnabled}),xe(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,a),this.playNextChunk().catch(o=>{xe("[AudioStreamManager] Playback chain error after recovery:",o)})}}playViaAudioElement(e,r,s){return new Promise(a=>{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,a(u))},c=()=>{if(this.suppressPlaybackErrors){s(),l(!0);return}const u=i.error;xe(`[AudioStreamManager] Media error on chunk ${r.chunkIndex}:`,u?{code:u.code,message:u.message,SRC_NOT_SUPPORTED:u.code===MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED}:"unknown"),s(),l(!1)};i.addEventListener("error",c,{once:!0});const d=async()=>{if(!o)try{i.addEventListener("ended",()=>{o||(z(`[AudioStreamManager] Chunk ${r.chunkIndex} finished`),this.onChunkPlayed&&this.onChunkPlayed(r.chunkIndex),s(),l(!0))},{once:!0}),await i.play()}catch(u){if(this.suppressPlaybackErrors){s(),l(!0);return}z(`[AudioStreamManager] audio.play() rejected for chunk ${r.chunkIndex}:`,u),s(),l(!1)}};i.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA?d():i.addEventListener("canplay",()=>d(),{once:!0})})}playViaAudioContext(e,r){return new Promise((s,a)=>{if(!this.audioContext){a(new Error("No AudioContext"));return}const i=e.slice(0);this.audioContext.decodeAudioData(i,o=>{if(!this.audioContext||this.suppressPlaybackErrors){s(!0);return}const l=this.audioContext.createBufferSource();l.buffer=o,l.connect(this.audioContext.destination),l.onended=()=>{z(`[AudioStreamManager] Chunk ${r} finished (AudioContext path)`),this.onChunkPlayed&&this.onChunkPlayed(r),s(!0)},l.start(0)},o=>{a(o)})})}stop(){z("[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(),z("[AudioStreamManager] Manager reset")}getQueueSize(){return this.audioQueue.length}isCurrentlyPlaying(){return this.isPlaying}}const er=new Iu,Eu=[{extensions:["pdf"],Icon:Ta,colorClass:"bg-red-500"},{extensions:["doc","docx"],Icon:Ta,colorClass:"bg-blue-500"},{extensions:["xls","xlsx","csv"],Icon:eo,colorClass:"bg-emerald-600"},{extensions:["ppt","pptx"],Icon:ao,colorClass:"bg-orange-500"},{extensions:["png","jpg","jpeg","webp","tiff","gif"],Icon:ld,colorClass:"bg-violet-500"},{extensions:["wav","mp3","ogg","flac","webm","m4a","aac"],Icon:od,colorClass:"bg-teal-600"},{extensions:["mp4","mov","avi","mkv"],Icon:cd,colorClass:"bg-pink-600"},{extensions:["zip","rar","7z","tar","gz"],Icon:id,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:Zi,colorClass:"bg-slate-500"}],Lu=new Set(["png","jpg","jpeg","webp","tiff","gif"]);function _u(t){const e=/\.([a-z0-9]+)$/i.exec(t.trim());return e?e[1].toLowerCase():""}function Tu(t){const e=_u(t),r=Eu.find(s=>s.extensions.includes(e));return{Icon:(r==null?void 0:r.Icon)??dd,colorClass:(r==null?void 0:r.colorClass)??"bg-gray-400 dark:bg-gray-500",label:e?e.toUpperCase():"",isImage:Lu.has(e)}}const Wr=new Map;function xo(t,e){const r=Wr.get(t);r&&r!==e&&URL.revokeObjectURL(r),Wr.set(t,e)}function Mu(t){return Wr.get(t)}function $a(t){const e=Wr.get(t);e&&(URL.revokeObjectURL(e),Wr.delete(t))}const Fu=Lc()||gc(),bo=()=>{if(Ks())return Va()||void 0},Or="",Ru=["New Chat","New Conversation"],$u=t=>t&&!Ru.includes(t)?t:Or,zr=(t,e,r)=>({id:t,sessionId:e,title:Or,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:r,adapterName:bo(),adapterLoadError:null}),Us=()=>{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},Pu=t=>{localStorage.setItem("chatbot-session-id",t)};let Du=0;const It=t=>{const e=Date.now(),r=++Du,s=Math.random().toString(36).substr(2,9);return`msg_${e}_${r}_${s}_${t}`},tr=()=>{const t=Date.now(),e=Math.random().toString(36).substr(2,9);return`session_${t}_${e}`},yo=t=>{const e=new Set;let r=!1;const s=t.map(a=>{if(!e.has(a.id))return e.add(a.id),a;r=!0;const i={...a,id:It(a.role)};return e.add(i.id),ye(`[chatStore] Re-keyed duplicate message id ${a.id}`),i});return r?s:t},ii=t=>t.filter(e=>!e.isThreadMessage&&!(e.role==="assistant"&&e.isStreaming)).length,oi=t=>t.flatMap(r=>[r.imageUrl,r.videoUrl,r.documentUrl]).map(r=>{var s;return((s=r==null?void 0:r.match(/\/api\/files\/([^/]+)\/content/))==null?void 0:s[1])??null}).filter(r=>r!==null),Uu=(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},Ou=(t,e)=>{const r=new Map;e.forEach((a,i)=>{a.databaseMessageId&&r.set(a.databaseMessageId,{message:a,index:i})});const s=new Set;return t.map((a,i)=>{var f;const o=a.role==="user"?"user":"assistant",l=typeof a.message_id=="string"&&a.message_id.length>0?a.message_id:void 0;let c;if(l&&r.has(l)){const p=r.get(l);c=p.message,s.add(p.index)}else{const p=i<e.length?i:0;if(!s.has(p)&&((f=e[p])==null?void 0:f.role)===o)c=e[p],s.add(p);else for(let g=1;g<e.length;g++){const h=(p+g)%e.length;if(!s.has(h)&&e[h].role===o){c=e[h],s.add(h);break}}}const d=a.timestamp?Uu(a.timestamp,c==null?void 0:c.timestamp):c!=null&&c.timestamp?new Date(c.timestamp):new Date,u=c?{...c,content:a.content??c.content,timestamp:d}:{id:l?`srv_${l}`:It(o),content:a.content||"",role:o,timestamp:d};if(u.isStreaming=!1,l&&(u.databaseMessageId=l),!u.supportsThreading&&a.metadata&&typeof a.metadata=="object"){const p=a.metadata,g=p==null?void 0:p.retrieved_docs;Array.isArray(g)&&g.length>0&&(u.supportsThreading=!0)}return u})},zu=(t,e)=>{if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){const s=t[r],a=e[r];if(s.role!==a.role||s.content!==a.content||(s.databaseMessageId||null)!==(a.databaseMessageId||null)||+s.timestamp!=+a.timestamp)return!1}return!0},wo=t=>{var a,i,o,l,c,d;const e=((i=(a=t.adapterInfo)==null?void 0:a.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{ye("Failed to read global voice setting")}const s=t.audioSettings;return{returnAudio:(s==null?void 0:s.enabled)??r??!!e,ttsVoice:(s==null?void 0:s.ttsVoice)||void 0,language:(s==null?void 0:s.language)||"en-US",audioFormat:s==null?void 0:s.audioFormat}},Bu=300;let vs=null;const He=t=>{vs&&clearTimeout(vs),vs=setTimeout(()=>{vs=null;try{const e=t(),r=e.conversations.map(s=>({...s,messages:s.messages.map(a=>a.audio||a.image||a.video||a.document?Object.fromEntries(Object.entries(a).filter(([o])=>o!=="audio"&&o!=="image"&&o!=="video"&&o!=="document")):a)}));localStorage.setItem("chat-state",JSON.stringify({conversations:r,currentConversationId:e.currentConversationId}))}catch(e){e instanceof DOMException&&e.name==="QuotaExceededError"?ye("[chatStore] localStorage quota exceeded — skipping save"):Be("[chatStore] Failed to save state to localStorage:",e)}},Bu)},Vu=32,yr=new Map;let Zt=null,ct=null,Bt=null,dr=null;const Pa=(t,e)=>{const r=yr.get(t);if(r){if(r.timeoutId&&(clearTimeout(r.timeoutId),r.timeoutId=null),r.content){const s=r.content,a=r.messageId;r.content="",e(i=>({conversations:i.conversations.map(o=>{if(o.id!==t)return o;const l=[...o.messages],c=a?l.findIndex(u=>u.id===a):l.length-1,d=c!==-1?l[c]:void 0;return d&&d.role==="assistant"&&d.isStreaming&&(l[c]={...d,content:d.content+s}),{...o,messages:l,updatedAt:new Date}})}))}yr.delete(t)}},pt=(t,e,r,s)=>({conversations:t.conversations.map(a=>{var l;if(a.id!==e)return a;const i=[...a.messages],o=s?i.findIndex(c=>c.id===s):i.length-1;return o!==-1&&((l=i[o])==null?void 0:l.role)==="assistant"&&(i[o]={...i[o],...r(i[o])}),{...a,messages:i,updatedAt:new Date}})});let Os=!1,zs="";async function $r(){if(Os&&zs)return!0;try{const t=await Re(),e=localStorage.getItem("chat-api-url");e&&e===Na&&localStorage.removeItem("chat-api-url");const r=e&&e!==Na?e:Pe(),s=Us(),a=localStorage.getItem("chat-adapter-name")||Fu;return t.configureApi(r,s,a),zs=r,Os=!0,!0}catch(t){return Be("Failed to configure API:",t),!1}}async function li(t,e,r,s,a,i,o,l,c){let d=!1;const u=new AbortController;Zt=u,dr=s,ct=null;try{const f=t().conversations.find(b=>b.id===s);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.");Bt=f.sessionId,f.sessionId&&(await Re()).configureApi(lt(f.apiUrl),f.sessionId,f.adapterName);const p=await Re(),{returnAudio:g,ttsVoice:h,language:x}=wo(f);for await(const b of p.streamChat(a,!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(b.request_id&&!ct&&(ct=b.request_id,z(`[chatStore] >>> CAPTURED request_id for ${l} stop: ${b.request_id}`)),b.text){const k=qr(b.text);k?(t().appendToLastMessage(k,s,r),d=!0):b.text.length>100&&ye("[chatStore] Filtered out potential base64 audio data from regenerated message content")}if(b.audio&&b.done&&e(k=>pt(k,s,()=>({audio:b.audio,audioFormat:b.audioFormat||"mp3"}),r)),b.image&&b.done&&(d=!0,e(k=>pt(k,s,()=>({image:b.image,imageFormat:b.image_format||"png",imageRevisedPrompt:b.image_revised_prompt,imageUrl:b.image_url}),r))),(b.video||b.video_url)&&b.done&&(d=!0,e(k=>pt(k,s,()=>({video:b.video,videoFormat:b.video_format||"mp4",videoRevisedPrompt:b.video_revised_prompt,videoUrl:b.video_url}),r))),(b.document||b.document_url)&&b.done&&(d=!0,e(k=>pt(k,s,()=>({document:b.document,documentFormat:b.document_format||"pdf",documentRevisedPrompt:b.document_revised_prompt,documentUrl:b.document_url}),r))),b.generated_audio_url&&b.done&&(d=!0,e(k=>pt(k,s,()=>({generatedAudioFormat:b.generated_audio_format||"mp3",generatedAudioRevisedPrompt:b.generated_audio_revised_prompt,generatedAudioUrl:b.generated_audio_url}),r))),b.done){const k=b.threading;k!=null&&k.supports_threading&&e(S=>({conversations:S.conversations.map(E=>E.id!==s?E:{...E,messages:E.messages.map(_=>_.id===r?{..._,supportsThreading:!0,databaseMessageId:k.message_id}:_),updatedAt:new Date})})),b.assistant_message_id&&e(S=>({conversations:S.conversations.map(E=>E.id!==s?E:{...E,messages:E.messages.map(_=>_.id===r&&!_.databaseMessageId?{..._,databaseMessageId:b.assistant_message_id}:_),updatedAt:new Date})})),b.model&&e(S=>pt(S,s,()=>({model:b.model}),r));break}}!d&&!u.signal.aborted&&t().appendToLastMessage("No response received from the server. Please try again later.",s,r)}catch(f){if(f instanceof Error&&(f.name==="AbortError"||f.message==="Stream cancelled by user"||f.message.includes("aborted")))z(`[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,s,r)}}Zt=null,ct=null,Bt=null,dr=null,Pa(s,e),e(f=>{const p=f.conversations.map(h=>h.id===s?{...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 ge=po((t,e)=>({conversations:[],currentConversationId:null,isLoading:!1,error:null,realtimeVoice:{status:"idle",transcript:""},_pendingRealtimeTurns:{},sessionId:Us(),getSessionId:()=>e().sessionId,setRealtimeVoiceState:r=>t(s=>({realtimeVoice:{...s.realtimeVoice,...r}})),beginRealtimeVoiceTurn:(r,s)=>{s.trim()&&t(a=>{const i=a._pendingRealtimeTurns[r];let o=i==null?void 0:i.userMessageId,l=i==null?void 0:i.assistantMessageId;return{conversations:a.conversations.map(d=>{if(d.id!==r)return d;const u=i?d.messages.find(f=>f.id===i.userMessageId):void 0;return u&&!u.content?{...d,messages:d.messages.map(f=>f.id===u.id?{...f,content:s}:f),updatedAt:new Date}:(o=It("user"),l=It("assistant"),{...d,messages:[...d.messages,{id:o,content:s,role:"user",timestamp:new Date,isStreaming:!0},{id:l,content:"",role:"assistant",timestamp:new Date,isStreaming:!0}],updatedAt:new Date,title:d.messages.length===0?s.slice(0,50):d.title})}),_pendingRealtimeTurns:o&&l?{...a._pendingRealtimeTurns,[r]:{userMessageId:o,assistantMessageId:l}}:a._pendingRealtimeTurns,realtimeVoice:{...a.realtimeVoice,transcript:`You: ${s}
349
+ Assistant: `}}})},appendRealtimeVoiceAssistantDelta:(r,s)=>{s&&t(a=>{const i=a._pendingRealtimeTurns[r];let o=i==null?void 0:i.userMessageId,l=i==null?void 0:i.assistantMessageId;return{conversations:a.conversations.map(d=>{if(d.id!==r)return d;const u=i?d.messages.find(f=>f.id===i.assistantMessageId):void 0;return u&&(u.isStreaming||!u.content)?{...d,messages:d.messages.map(f=>f.id===u.id?{...f,content:f.content+s}:f),updatedAt:new Date}:(o=It("user"),l=It("assistant"),{...d,messages:[...d.messages,{id:o,content:"",role:"user",timestamp:new Date,isStreaming:!0},{id:l,content:s,role:"assistant",timestamp:new Date,isStreaming:!0}],updatedAt:new Date})}),_pendingRealtimeTurns:o&&l?{...a._pendingRealtimeTurns,[r]:{userMessageId:o,assistantMessageId:l}}:a._pendingRealtimeTurns,realtimeVoice:{...a.realtimeVoice,transcript:a.realtimeVoice.transcript+s}}})},finishRealtimeVoiceTurn:(r,s)=>{t(a=>({conversations:a.conversations.map(i=>i.id!==r?i:{...i,messages:i.messages.map(o=>{if(!o.isStreaming)return o;const l=o.role==="user"?s==null?void 0:s.userMessageId:s==null?void 0:s.assistantMessageId;return{...o,isStreaming:!1,...l?{databaseMessageId:l}:{}}}),updatedAt:new Date})})),He(e)},configureApiSettings:async(r,s,a)=>{const i=e(),o=i.conversations.find(c=>c.id===i.currentConversationId),l=(o==null?void 0:o.sessionId)||s||Us();s&&Pu(s),t({sessionId:l});try{const c=await Re();if(!a||!a.trim())throw new Error("Adapter name is required");c.configureApi(r,l,a),zs=r,Os=!0;let d;try{const u=new c.ApiClient({apiUrl:r,sessionId:null,adapterName:a});typeof u.getAdapterInfo=="function"&&(d=await u.getAdapterInfo(),z("Adapter info loaded:",d))}catch(u){ye("Failed to load adapter info:",u)}if(o)t(u=>({conversations:u.conversations.map(f=>f.id===o.id?{...f,adapterName:a,apiUrl:r,adapterInfo:d,adapterLoadError:null,updatedAt:new Date}:f)}));else if(a&&a.trim()){const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,f=tr();t(p=>({conversations:[...p.conversations,{id:u,sessionId:f,title:Or,messages:[],createdAt:new Date,updatedAt:new Date,adapterName:a,apiUrl:r,adapterInfo:d,adapterLoadError:null}],currentConversationId:u}))}}catch(c){throw xe("Failed to configure API:",c),t({isLoading:!1}),c instanceof Error?c:new Error("Failed to configure API settings")}a?localStorage.setItem("chat-adapter-name",a):localStorage.removeItem("chat-adapter-name"),t({isLoading:!1})},createConversation:()=>{var u;const r=e(),s=le.maxConversations,a=r.conversations.length,i=r.currentConversationId?r.conversations.find(f=>f.id===r.currentConversationId):null;if(s!==null&&a>=s){if(st()&&!vt()){const p=`You've reached the guest limit of ${s} conversation${s===1?"":"s"}. Sign in to unlock more conversations, or delete conversations to start over.`;throw t({error:p}),at.getState().openLoginPrompt(p),new Error("Guest conversation limit reached")}const f=`Maximum of ${s} 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=tr(),d={id:l,sessionId:c,title:Or,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:Pe(),adapterName:bo(),adapterLoadError:null};return t(f=>({conversations:[d,...f.conversations],currentConversationId:l,sessionId:c,isLoading:!1})),He(e),l},selectConversation:async r=>{const s=e().conversations.find(a=>a.id===r);if(s){const a=s.messages.some(c=>c.role==="assistant"&&c.isStreaming);t({currentConversationId:r,sessionId:s.sessionId,isLoading:a});const i=s.apiUrl||Pe(),o=s.adapterName;if(await $r()&&o){const c=await Re();if(c.configureApi(i,s.sessionId,o),!s.adapterInfo)try{const d=new c.ApiClient({apiUrl:i,sessionId:null,adapterName:o});if(typeof d.getAdapterInfo=="function"){const u=await d.getAdapterInfo();z("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)})),He(e)}}catch(d){ye("Failed to load adapter info for conversation:",d)}}e().loadFeedbackForConversation(s.sessionId).catch(()=>{})}He(e)},deleteConversation:async r=>{var i,o;const s=e(),a=s.conversations.find(l=>l.id===r);if(z(`🗑️ Deleting conversation ${r}:`,{conversationId:r,sessionId:a==null?void 0:a.sessionId,title:a==null?void 0:a.title,messageCount:a==null?void 0:a.messages.length,fileCount:((i=a==null?void 0:a.attachedFiles)==null?void 0:i.length)||0}),s.currentConversationId===r&&er.stop(),a){const l=(a.attachedFiles||[]).map(d=>d.file_id),c=(a.messages||[]).flatMap(d=>(d.attachments||[]).map(u=>u.file_id));[...l,...c].forEach(Vt.cancelFilePoll),[...l,...c].forEach($a)}if(a!=null&&a.sessionId)try{if(!await $r())Be("Failed to configure API for conversation deletion");else{const c=a.apiUrl||Pe(),d=a.adapterName;d?z(`Using conversation's adapter for deletion: ${d} (conversation: ${r})`):ye(`Skipping server deletion for conversation ${r}: adapter not configured`);const u=await Re(),f=new u.ApiClient({apiUrl:c,sessionId:a.sessionId,adapterName:d}),p=((o=a.attachedFiles)==null?void 0:o.map(x=>x.file_id))||[],g=oi(a.messages||[]),h=[...p,...g];if(z(`🔧 Calling deleteConversationWithFiles for session: ${a.sessionId}`),f.deleteConversationWithFiles){const x=await f.deleteConversationWithFiles(a.sessionId,h);z(`✅ Deleted conversation and files for session: ${a.sessionId}`,x),z(` - Deleted ${x.deleted_messages} messages`),z(` - Deleted ${x.deleted_files} files`),x.file_deletion_errors&&x.file_deletion_errors.length>0&&ye(` - Errors deleting files: ${x.file_deletion_errors.join(", ")}`)}else ye("⚠️ deleteConversationWithFiles method not available on API client")}}catch(l){Be("Failed to clear conversation history from server:",l)}else ye(`⚠️ 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=tr(),g=zr(f,p,Pe());return He(e),{conversations:[g],currentConversationId:f,sessionId:p}}return He(e),{conversations:c,currentConversationId:d}})},deleteAllConversations:async()=>{const s=[...e().conversations];z(`🗑️ Deleting all conversations (${s.length} total)`),er.stop(),s.forEach(u=>{var g;const f=((g=u.attachedFiles)==null?void 0:g.map(h=>h.file_id))||[],p=(u.messages||[]).flatMap(h=>(h.attachments||[]).map(x=>x.file_id));[...f,...p].forEach(Vt.cancelFilePoll)});const a=s.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){z(`Skipping server deletion for conversation ${u.id}: adapter not configured`);return}const h=await Re(),x=new h.ApiClient({apiUrl:lt(u.apiUrl),sessionId:u.sessionId,adapterName:g}),b=[...((f=u.attachedFiles)==null?void 0:f.map(k=>k.file_id))||[],...oi(u.messages||[])];x.deleteConversationWithFiles?(await x.deleteConversationWithFiles(u.sessionId,b),z(`✅ Deleted conversation ${u.id} and files`)):ye(`deleteConversationWithFiles not available for conversation ${u.id}`)}catch(p){Be(`Failed to delete conversation ${u.id} from server:`,p)}}),o=(await Promise.allSettled(a)).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=tr(),d=zr(l,c,Pe());t({conversations:[d],currentConversationId:l,sessionId:c}),He(e)},deleteThread:async(r,s,a)=>{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===s);if(!(o!=null&&o.threadInfo)||o.threadInfo.thread_id!==a)throw new Error("Thread not found for this message");const l=lt(i.apiUrl||Pe()),c=await Re(),d=new c.ApiClient({apiUrl:l,sessionId:i.sessionId,adapterName:i.adapterName});await new(await Et(async()=>{const{ThreadService:f}=await import("./threadService-B9Db3n0J.js");return{ThreadService:f}},[])).ThreadService(d).deleteThread(a),t(f=>({conversations:f.conversations.map(p=>{var x;if(p.id!==r)return p;const g=p.messages.filter(b=>b.isThreadMessage?!(b.threadId===a||b.parentMessageId===s):!0).map(b=>b.id!==s?b:{...b,threadInfo:void 0,supportsThreading:!0}),h=p.currentThreadId===a||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}})})),He(e)},sendMessage:async(r,s,a,i,o)=>{var c;let l=null;try{if(e().isLoading){ye("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(y=>y.id===u);if(!f)throw new Error("Conversation not found");const p=le.maxConversations;if(st()&&!vt()&&p!==null&&e().conversations.length>p){at.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=s?s.map(y=>{var N;const A=(N=f==null?void 0:f.attachedFiles)==null?void 0:N.find(I=>I.file_id===y);return A||{file_id:y,filename:"",mime_type:"",file_size:0}}).filter(y=>y!==void 0):[];g.length>0&&g.forEach(y=>{e().addFileToConversation(u,y)});const h=a||null;let x,b=null;if(h){if(x=f.messages.find(y=>{var A;return((A=y.threadInfo)==null?void 0:A.thread_id)===h}),!x)throw new Error("Thread metadata not found. Please recreate the thread from this message.");if(b=((c=x.threadInfo)==null?void 0:c.thread_session_id)||null,!b)throw new Error("Thread session is missing. Please recreate the thread from this message.")}const k=ii(f.messages),S=le.maxMessagesPerConversation;if(S!==null&&k>=S){st()&&!vt()&&at.getState().openLoginPrompt(`You've reached the guest limit of ${S} messages per conversation. Sign in to send more messages, or delete conversations to start over.`),ye(`[chatStore] Conversation ${u} reached the message limit (${S}).`),t({isLoading:!1});return}const E=le.maxTotalMessages;if(E!==null&&e().conversations.reduce((A,N)=>A+ii(N.messages),0)>=E){st()&&!vt()&&at.getState().openLoginPrompt(`You've reached the guest limit of ${E} total messages. Sign in to continue chatting, or delete conversations to start over.`),ye(`[chatStore] Workspace reached the total message limit (${E}).`),t({isLoading:!1});return}const _={id:It("user"),content:r,role:"user",timestamp:new Date,attachments:g.length>0?g:void 0},v=It("assistant"),M={id:v,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:i};if(h&&x){_.isThreadMessage=!0,_.threadId=h,_.parentMessageId=x.id,M.isThreadMessage=!0,M.threadId=h,M.parentMessageId=x.id;const y=le.maxMessagesPerThread;if(y!==null&&f.messages.filter(N=>N.isThreadMessage?(N.threadId===h||N.parentMessageId===x.id)&&!(N.role==="assistant"&&N.isStreaming):!1).length>=y){st()&&!vt()&&at.getState().openLoginPrompt(`You've reached the guest limit of ${y} messages per thread. Sign in to continue this thread, or delete conversations to start over.`),ye(`[chatStore] Thread ${h} reached the message limit (${y}).`),t({isLoading:!1});return}}t(y=>{const A=y.conversations.find(I=>I.id===u),N=(A==null?void 0:A.messages.filter(I=>I.role==="assistant"&&I.isStreaming))||[];return N.length>0&&ye(`Cleaning up ${N.length} existing streaming messages`),{conversations:y.conversations.map(I=>{if(I.id!==u)return I;const $=I.messages.filter(U=>!(U.role==="assistant"&&U.isStreaming));return{...I,messages:[...$,_,M],updatedAt:new Date,title:I.messages.length===0?r.slice(0,50)+(r.length>50?"...":""):I.title}}),isLoading:!0,error:null}}),l=u;let F=!1;er.reset();try{const y=e().conversations.find(C=>C.id===l);if(!y)throw new Error("Conversation not found");if(!y.adapterName)throw new Error("Adapter not configured for this conversation. Please select an adapter first.");const A=lt(y.apiUrl),N=y.adapterName,I=b||y.sessionId,$=await Re();$.configureApi(A,I,N),h&&I!==y.sessionId&&z(`[chatStore] Thread mode: using thread session ${I} (original: ${y.sessionId})`);const{returnAudio:U,ttsVoice:X,language:j,audioFormat:L}=wo(y);z("[chatStore] Audio settings:",{returnAudio:U,ttsVoice:X,language:j,audioFormat:L});const B=new AbortController;Zt=B,Bt=I,dr=l,ct=null;for await(const C of $.streamChat(r,!0,s,h||void 0,void 0,void 0,j,U,X,void 0,void 0,i,o)){if(C.request_id&&!ct&&(ct=C.request_id,z(`[chatStore] >>> CAPTURED request_id for stop: ${C.request_id}`)),C.audio_chunk&&er.addChunk({audio:C.audio_chunk,audioFormat:C.audioFormat||"opus",chunkIndex:C.chunk_index??0}),C.text){const H=qr(C.text);H?(e().appendToLastMessage(H,l,v),F=!0):C.text.length>100&&ye("[chatStore] Filtered out potential base64 audio data from message content")}if(C.audio&&C.done&&t(H=>pt(H,l,()=>({audio:C.audio,audioFormat:C.audioFormat||"mp3"}),v)),C.image&&C.done&&(F=!0,t(H=>pt(H,l,()=>({image:C.image,imageFormat:C.image_format||"png",imageRevisedPrompt:C.image_revised_prompt,imageUrl:C.image_url}),v))),(C.video||C.video_url)&&C.done&&(F=!0,t(H=>pt(H,l,()=>({video:C.video,videoFormat:C.video_format||"mp4",videoRevisedPrompt:C.video_revised_prompt,videoUrl:C.video_url}),v))),(C.document||C.document_url)&&C.done&&(F=!0,t(H=>pt(H,l,()=>({document:C.document,documentFormat:C.document_format||"pdf",documentRevisedPrompt:C.document_revised_prompt,documentUrl:C.document_url}),v))),C.generated_audio_url&&C.done&&(F=!0,t(H=>pt(H,l,()=>({generatedAudioFormat:C.generated_audio_format||"mp3",generatedAudioRevisedPrompt:C.generated_audio_revised_prompt,generatedAudioUrl:C.generated_audio_url}),v))),C.done){z("[chatStore] Stream completed, receivedAnyText:",F);const H=C.threading;H!=null&&H.supports_threading&&t(q=>({conversations:q.conversations.map(J=>J.id!==l?J:{...J,messages:J.messages.map(K=>K.id===v?{...K,supportsThreading:!0,databaseMessageId:H.message_id}:K),updatedAt:new Date})})),C.assistant_message_id&&t(q=>({conversations:q.conversations.map(J=>J.id!==l?J:{...J,messages:J.messages.map(K=>K.id===v&&!K.databaseMessageId?{...K,databaseMessageId:C.assistant_message_id}:K),updatedAt:new Date})})),C.model&&t(q=>pt(q,l,()=>({model:C.model}),v));break}}!F&&!B.signal.aborted&&e().appendToLastMessage("No response received from the server. Please try again later.",l,v)}catch(y){if(y instanceof Error&&(y.name==="AbortError"||y.message==="Stream cancelled by user"||y.message.includes("aborted")))z("[chatStore] Stream was cancelled by user"),F=!0;else{Be("Chat API error:",y);let N="Sorry, there was an error processing your request.";y instanceof Error&&(y.message.startsWith("Server error:")?N=y.message.substring(14):(y.message.includes("Could not connect")||y.message.includes("timed out"))&&(N=y.message)),e().appendToLastMessage(N,l,v)}}Zt=null,ct=null,Bt=null,dr=null,Pa(l,t),t(y=>{const A=y.conversations.map(I=>I.id===l?{...I,messages:I.messages.map($=>$.id===v?{...$,isStreaming:!1}:$),updatedAt:new Date}:I),N=A.find(I=>I.id===y.currentConversationId);return{conversations:A,isLoading:N?N.messages.some(I=>I.role==="assistant"&&I.isStreaming):!1}}),He(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,s)=>{try{const a=e().conversations.find(p=>p.sessionId===s);if(!a)throw new Error("Conversation not found for session");if(!a.adapterName)throw new Error("Adapter not configured for this conversation");const i=a.messages.find(p=>p.id===r);if(!i)throw new Error("Message not found");const o=i.databaseMessageId||r,l=lt(a.apiUrl||Pe()),c=await Re(),d=new c.ApiClient({apiUrl:l,sessionId:s,adapterName:a.adapterName}),f=await new(await Et(async()=>{const{ThreadService:p}=await import("./threadService-B9Db3n0J.js");return{ThreadService:p}},[])).ThreadService(d).createThread(o,s);t(p=>({conversations:p.conversations.map(g=>g.sessionId!==s?g:{...g,messages:g.messages.map(h=>h.id===r?{...h,threadInfo:f,supportsThreading:!0}:h),currentThreadId:void 0,currentThreadSessionId:void 0})})),z(`[chatStore] Created thread ${f.thread_id} for message ${r}`)}catch(a){throw Be("Failed to create thread:",a),a}},appendToLastMessage:(r,s,a)=>{const i=qr(r);if(!i&&r){ye("[chatStore] Filtered out base64 audio data from message content");return}const o=Ra(i),l=s||e().currentConversationId;if(!l)return;const c=l,d=yr.get(c);d?(d.content+=o,d.messageId=a,d.timeoutId&&clearTimeout(d.timeoutId)):yr.set(c,{content:o,timeoutId:null,messageId:a});const u=()=>{const p=yr.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(b=>{if(b.id!==l)return b;const k=[...b.messages],S=h?k.findIndex(_=>_.id===h):k.length-1,E=S!==-1?k[S]:void 0;return E&&E.role==="assistant"&&E.isStreaming&&(k[S]={...E,content:E.content+g}),{...b,messages:k,updatedAt:new Date}})}))},f=yr.get(c);f.timeoutId=setTimeout(u,Vu)},regenerateResponse:async(r,s)=>{let a=null;try{if(e().isLoading){ye("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=It("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:s,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})),a=o.currentConversationId,!a)throw new Error("No conversation selected");await li(e,t,p,a,u.content,f,s,"regenerate",d.databaseMessageId)}catch(i){Be("Regenerate error:",i),t(o=>({isLoading:!1,...o.currentConversationId===a&&{error:`Failed to regenerate response: ${i instanceof Error?i.message:"Unknown error"}`}}))}},editMessageAndRegenerate:async(r,s,a)=>{let i=null;try{if(e().isLoading){await e().stopStreaming();const x=e().currentConversationId;x&&Pa(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=It("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(b=>b.id===x.currentConversationId?{...b,messages:[...b.messages.slice(0,c),{...d,content:s,updatedAt:new Date},{id:f,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:a,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},...b.messages.slice(h)],updatedAt:new Date}:b),isLoading:!0,error:null})),i=o.currentConversationId,!i)throw new Error("No conversation selected");await li(e,t,f,i,s,u,a,"edit-regenerate",g?p.databaseMessageId:void 0),He(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,s)=>{t(a=>({conversations:a.conversations.map(i=>i.id===r?{...i,title:s,updatedAt:new Date}:i)})),He(e)},clearError:()=>t({error:null}),cleanupStreamingMessages:()=>{const r=dr;t(s=>{let a=!1;return{conversations:s.conversations.map(o=>o.id===r?(o.messages.some(c=>c.role==="assistant"&&c.isStreaming)&&(a=!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:a}})},canCreateNewConversation:()=>{var o;const r=e(),s=le.maxConversations;if(!r.currentConversationId)return s===null||r.conversations.length<s;const a=r.conversations.find(l=>l.id===r.currentConversationId);return!!a&&(a.messages.length>0||(((o=a.attachedFiles)==null?void 0:o.length)||0)>0)?s===null||r.conversations.length<s:!1},getConversationCount:()=>e().conversations.length,addFileToConversation:(r,s)=>{z("[chatStore] addFileToConversation called",{conversationId:r,fileId:s.file_id,filename:s.filename}),t(a=>({conversations:a.conversations.map(i=>i.id===r?{...i,attachedFiles:[...(i.attachedFiles||[]).filter(o=>o.file_id!==s.file_id),s],updatedAt:new Date}:i)})),He(e)},removeFileFromConversation:async(r,s)=>{z("[chatStore] removeFileFromConversation called",{conversationId:r,fileId:s}),Vt.cancelFilePoll(s);try{const a=e().conversations.find(i=>i.id===r);if(!a)throw new Error("Conversation not found");if(!a.adapterName)throw new Error("Adapter not configured for this conversation. Cannot delete file.");await Vt.deleteFile(s,void 0,lt(a.apiUrl),a.adapterName),z(`[chatStore] Successfully deleted file ${s} from server`)}catch(a){a instanceof Error&&(a.message.includes("404")||a.message.includes("File not found"))?z(`[chatStore] File ${s} was already deleted from server`):xe(`[chatStore] Failed to delete file ${s} from server:`,a)}$a(s),t(a=>({conversations:a.conversations.map(i=>i.id===r?{...i,attachedFiles:(i.attachedFiles||[]).filter(o=>o.file_id!==s),updatedAt:new Date}:i)})),He(e)},loadConversationFiles:async r=>{try{const s=e().conversations.find(l=>l.id===r);if(!s)return;if(!s.adapterName){z(`Skipping file load for conversation ${r}: adapter not configured`);return}if(new Set((s.attachedFiles||[]).map(l=>l.file_id)).size===0){z(`No files to sync for conversation ${r}`);return}const i=await Vt.listFiles(void 0,lt(s.apiUrl),s.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)}}),He(e)}catch(s){Be(`Failed to load files for conversation ${r}:`,s)}},syncConversationFiles:async r=>{await e().loadConversationFiles(r)},syncConversationsWithBackend:async()=>{try{const r=e();if(r.conversations.length===0)return;const s=await Re(),a=le.maxMessagesPerConversation!==null&&le.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 ye(`[chatStore] Skipping backend sync for conversation ${c.id} - adapter not configured`),null;if(c.messages.length===0)return null;try{const u=new s.ApiClient({apiUrl:lt(c.apiUrl),sessionId:c.sessionId,adapterName:c.adapterName});if(typeof u.getConversationHistory!="function")return i||(i=!0,ye("[chatStore] Conversation history endpoint not supported by current API client")),null;const f=await u.getConversationHistory(c.sessionId,a),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=Ou(p,c.messages),h=c.messages.filter(b=>b.isThreadMessage),x=yo(h.length>0?[...g,...h]:g);return zu(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 ye(`[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:Or,updatedAt:f.updatedAt,adapterLoadError:null}:{...u,sessionId:f.sessionId||u.sessionId,messages:f.messages,updatedAt:f.updatedAt,adapterLoadError:null}:u}),currentConversationId:c.currentConversationId}}),He(e)}catch(r){ye("Failed to synchronize conversations with backend:",r)}},stopStreaming:async()=>{var s;if(!e().isLoading){z("[chatStore] stopStreaming called but not currently loading");return}if(z("[chatStore] Stopping stream...",{hasAbortController:!!Zt,requestId:ct,sessionId:Bt}),Zt&&Zt.abort(),ct&&Bt)try{const a=await Re(),i=await((s=a.stopChat)==null?void 0:s.call(a,Bt,ct));z(`[chatStore] Server-side cancellation result: ${i}`)}catch(a){ye("[chatStore] Failed to cancel server-side stream:",a)}else ye(`[chatStore] Cannot call stopChat - missing IDs: requestId=${ct}, sessionId=${Bt}`);const r=dr||e().currentConversationId;t(r?a=>({conversations:a.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}),Zt=null,ct=null,Bt=null,dr=null,z("[chatStore] Stream stopped successfully")},clearCurrentConversationAdapter:()=>{const r=e().currentConversationId;r&&(t(s=>({conversations:s.conversations.map(a=>a.id===r?{...a,adapterName:void 0,adapterInfo:void 0,adapterLoadError:null}:a)})),He(e))},submitFeedback:async(r,s,a)=>{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 ye("[chatStore] Cannot submit feedback: no databaseMessageId on message"),!1;if(!o.adapterName)return!1;try{const c=await Re(),u=await new c.ApiClient({apiUrl:lt(o.apiUrl||Pe()),sessionId:o.sessionId,adapterName:o.adapterName}).submitFeedback(l.databaseMessageId,o.sessionId,s,a),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})})),He(e),!0}catch(c){return xe("[chatStore] Failed to submit feedback:",c),!1}},loadFeedbackForConversation:async r=>{var i;const a=e().conversations.find(o=>o.sessionId===r);if(a!=null&&a.adapterName)try{const o=await Re(),l=new o.ApiClient({apiUrl:lt(a.apiUrl||Pe()),sessionId:a.sessionId,adapterName:a.adapterName}),c=new Set([r]);for(const f of a.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){xe("[chatStore] Failed to load feedback:",o)}}})),Hu=async()=>{var c;const t=localStorage.getItem("chat-state"),e=Pe(),r=!!localStorage.getItem("chat-api-url");let s=Us(),a=!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(E=>!(E.role==="assistant"&&E.isStreaming)).map(E=>({...E,timestamp:u(E.timestamp),isStreaming:!1})),b=yo(x),k={id:g.id,sessionId:g.sessionId||tr(),title:$u(g.title),messages:b,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},S=k.messages.length===0&&!k.adapterName;return{...k,apiUrl:S&&!r?e:lt(g.apiUrl)}});if(a=p.length>0,d.currentConversationId&&p.length>0){const g=p.find(h=>h.id===d.currentConversationId);g!=null&&g.sessionId&&(s=g.sessionId)}if(p.length===0){const g=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=tr(),x=zr(g,h,Pe());ge.setState({conversations:[x],currentConversationId:g,sessionId:h}),s=h}else ge.setState({conversations:p,currentConversationId:d.currentConversationId||((c=p[0])==null?void 0:c.id)||null,sessionId:s}),!d.currentConversationId&&p.length>0&&(ge.setState({currentConversationId:p[0].id,sessionId:p[0].sessionId||s}),s=p[0].sessionId||s);z("📋 Loaded conversations:",ge.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(()=>ge.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=tr(),p=zr(u,f,Pe());ge.setState({conversations:[p],currentConversationId:u,sessionId:f}),s=f}else{const d=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,u=tr(),f=zr(d,u,Pe());ge.setState({conversations:[f],currentConversationId:d,sessionId:u}),s=u}localStorage.removeItem("chat-api-key");const i=ge.getState(),o=i.currentConversationId?i.conversations.find(d=>d.id===i.currentConversationId):null,l=a&&(o!=null&&o.apiUrl)?o.apiUrl:Pe();try{const d=await Re(),u=o==null?void 0:o.adapterName;if(!u)z("No adapter selected yet. Waiting for user selection before configuring API.");else if(d.configureApi(l,s,u),zs=l,Os=!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();z("Adapter info loaded for existing adapter:",p);const g=ge.getState();g.currentConversationId&&(ge.setState({conversations:g.conversations.map(h=>h.id===g.currentConversationId?{...h,adapterInfo:p,adapterLoadError:null,updatedAt:new Date}:h)}),setTimeout(()=>{const h=ge.getState();localStorage.setItem("chat-state",JSON.stringify({conversations:h.conversations,currentConversationId:h.currentConversationId}))},0))}}catch(f){ye("Failed to load adapter info for existing adapter:",f)}}catch(d){Be("Failed to initialize API:",d)}try{await ge.getState().syncConversationsWithBackend()}catch(d){ye("Conversation history sync skipped:",d)}};typeof window<"u"&&Hu();function qu(t){return t.includes("image")?n.jsx(ud,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):t.includes("video")||t.includes("audio")?n.jsx(Md,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):n.jsx(Ga,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"})}function Wu(t){return t.replace(/-/g," ")}function ko({skills:t,isLoading:e,selectedSkill:r,activeSkillName:s,query:a="",onSelect:i,onActiveSkillChange:o}){const{t:l}=Ee(),c=xt.useRef(null),d=a.toLowerCase().replace(/-/g," "),u=d?t.filter(f=>f.name.replace(/-/g," ").toLowerCase().includes(d)||f.description.toLowerCase().includes(d)):t;return xt.useEffect(()=>{var p;const f=(p=c.current)==null?void 0:p.querySelector('[data-active="true"]');f==null||f.scrollIntoView({block:"nearest"})},[s,u.length]),!e&&t.length===0?n.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:n.jsx("p",{className:"px-4 py-3 text-sm text-gray-500 dark:text-[#bfc2cd]",children:l("skillPicker.noSkillsAvailable")})}):n.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?n.jsx("div",{className:"px-4 py-3.5",children:n.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-[#bfc2cd]",children:[n.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?n.jsx("div",{className:"px-4 py-3.5",children:n.jsx("p",{className:"text-sm text-gray-500 dark:text-[#bfc2cd]",children:d?l("skillPicker.noMatchingSkills",{query:a}):l("skillPicker.noMatchingSkillsGeneric")})}):n.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=s===f.name||!s&&(g||!r&&p===0);return n.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:[n.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:qu(f.name)}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"flex min-w-0 items-center gap-2",children:n.jsx("span",{className:"truncate text-sm font-medium capitalize leading-5 text-current",children:Wu(f.name)})}),f.description&&n.jsx("p",{className:"mt-0.5 line-clamp-2 text-xs leading-5 text-gray-500 dark:text-[#bfc2cd]",children:f.description})]}),g&&n.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:n.jsx(ur,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]},f.name)})})})}function Ku(t){return t.replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Da({availableModels:t,defaultModel:e,selectedModel:r,onSelect:s,wrapperClassName:a="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}=Ee(),f=o??u("modelPicker.selectModel"),p=l??u("modelPicker.selectModel"),g=m.useId(),[h,x]=m.useState(!1),[b,k]=m.useState(""),[S,E]=m.useState(0),[_,v]=m.useState(null),M=m.useRef(null),F=m.useRef(null),y=m.useRef(null),A=m.useRef(null),N=r??e,I=m.useMemo(()=>{const C=b.trim().toLowerCase();return C?t.filter(H=>`${H.name} ${H.provider} ${H.model}`.toLowerCase().includes(C)):t},[t,b]),$=m.useCallback(C=>{s(C),x(!1),k(""),requestAnimationFrame(()=>{var H;return(H=F.current)==null?void 0:H.focus()})},[s]),U=m.useCallback(()=>{if(!F.current)return;const C=F.current.getBoundingClientRect(),H=Math.min(352,window.innerWidth-24),q=C.right-H;v({bottom:window.innerHeight-C.top+10,left:Math.min(window.innerWidth-H-12,Math.max(12,q))})},[]),X=m.useCallback(()=>{x(!1),k("")},[]),j=()=>{if(h){X();return}U();const C=t.findIndex(H=>H.name===N);E(Math.max(C,0)),x(!0)};if(m.useEffect(()=>{if(!h)return;const C=setTimeout(()=>{var K;return(K=y.current)==null?void 0:K.focus()},10),H=K=>{var Q,R;const V=K.target,oe=((Q=M.current)==null?void 0:Q.contains(V))??!1,T=((R=A.current)==null?void 0:R.contains(V))??!1;!oe&&!T&&X()},q=K=>{var V;if(K.key==="Escape"){K.preventDefault(),X(),(V=F.current)==null||V.focus();return}if(I.length!==0){if(K.key==="ArrowDown")K.preventDefault(),E(oe=>(oe+1)%I.length);else if(K.key==="ArrowUp")K.preventDefault(),E(oe=>(oe-1+I.length)%I.length);else if(K.key==="Home")K.preventDefault(),E(0);else if(K.key==="End")K.preventDefault(),E(I.length-1);else if(K.key==="Enter"){K.preventDefault();const oe=I[S];oe&&$(oe.name)}}},J=new ResizeObserver(U);return F.current&&J.observe(F.current),window.addEventListener("resize",U,{passive:!0}),document.addEventListener("scroll",U,{capture:!0,passive:!0}),document.addEventListener("pointerdown",H),document.addEventListener("keydown",q),()=>{clearTimeout(C),J.disconnect(),window.removeEventListener("resize",U),document.removeEventListener("scroll",U,{capture:!0}),document.removeEventListener("pointerdown",H),document.removeEventListener("keydown",q)}},[S,X,I,h,U,$]),m.useEffect(()=>{var C,H;h&&((H=(C=A.current)==null?void 0:C.querySelector(`[data-model-index="${S}"]`))==null||H.scrollIntoView({block:"nearest"}))},[S,h]),!e&&t.length===0)return null;const L=h&&_&&typeof document<"u"?Hs.createPortal(n.jsxs("div",{ref:A,style:{position:"fixed",bottom:_.bottom,left:_.left,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:[n.jsxs("div",{className:"flex items-start justify-between gap-4 px-4 pb-3 pt-4",children:[n.jsxs("div",{children:[n.jsx("h2",{className:"text-sm font-semibold leading-5 text-gray-950 dark:text-white",children:u("modelPicker.chooseModel")}),n.jsx("p",{className:"mt-0.5 text-xs leading-4 text-gray-500 dark:text-gray-400",children:u("modelPicker.chooseModelHint")})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[n.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}),n.jsx("button",{type:"button",onClick:()=>{X(),requestAnimationFrame(()=>{var C;return(C=F.current)==null?void 0:C.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:n.jsx(Ge,{className:"h-4 w-4","aria-hidden":"true"})})]})]}),n.jsx("div",{className:"px-3 pb-3",children:n.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:[n.jsx($s,{className:"h-4 w-4 shrink-0 text-gray-400","aria-hidden":"true"}),n.jsx("input",{ref:y,type:"text",value:b,onChange:C=>{k(C.target.value),E(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[S]?`${g}-option-${S}`:void 0})]})}),n.jsx("div",{className:"mx-3 border-t border-gray-100 dark:border-white/[0.07]"}),n.jsx("div",{id:g,role:"listbox","aria-label":p,className:"max-h-72 overflow-y-auto p-2",children:I.length===0?n.jsxs("div",{className:"flex flex-col items-center px-4 py-8 text-center",children:[n.jsx($s,{className:"mb-2 h-5 w-5 text-gray-300 dark:text-gray-600","aria-hidden":"true"}),n.jsx("p",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:u("modelPicker.noModelsMatch",{query:b})}),n.jsx("p",{className:"mt-1 text-xs text-gray-400 dark:text-gray-500",children:u("modelPicker.tryAnotherSearch")})]}):I.map((C,H)=>{const q=N===C.name,J=S===H;return n.jsxs("button",{id:`${g}-option-${H}`,"data-model-index":H,role:"option","aria-selected":q,type:"button",onMouseMove:()=>E(H),onClick:()=>$(C.name),className:`group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition-colors ${J?"bg-gray-100 dark:bg-white/[0.08]":"hover:bg-gray-50 dark:hover:bg-white/[0.05]"}`,children:[n.jsxs("span",{className:"min-w-0 flex-1",children:[n.jsx("span",{className:"block truncate text-sm font-medium text-gray-900 dark:text-gray-100",children:C.name}),n.jsxs("span",{className:"mt-0.5 block truncate text-xs text-gray-500 dark:text-gray-400",children:[Ku(C.provider),C.model!==C.name?` · ${C.model}`:""]})]}),n.jsx("span",{className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full ${q?"bg-gray-900 text-white dark:bg-white dark:text-gray-900":"text-transparent"}`,children:n.jsx(ur,{className:"h-3 w-3",strokeWidth:3,"aria-hidden":"true"})})]},C.name)})}),I.length>0&&n.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:[n.jsx("span",{children:u("modelPicker.modelCountHint",{filtered:I.length,total:t.length})}),n.jsx("span",{className:"hidden sm:inline",children:u("modelPicker.keyboardHint")})]})]}),document.body):null,B=n.jsx("span",{className:"min-w-0 flex-1 truncate text-left text-xs font-medium text-gray-800 dark:text-gray-200",children:N??u("modelPicker.selectModel")});return n.jsx("div",{ref:M,className:a,children:t.length>1?n.jsxs(n.Fragment,{children:[n.jsxs("button",{ref:F,type:"button",onClick:j,className:`group inline-flex h-8 min-w-[124px] ${i} items-center gap-2 rounded-full 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:[B,n.jsx(vr,{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"})]}),L]}):n.jsx("div",{className:`inline-flex h-8 min-w-[124px] ${i} items-center gap-2 rounded-full border border-gray-200 bg-white/60 ${c} shadow-sm dark:border-white/10 dark:bg-white/[0.04]`,title:N??void 0,children:B})})}function Bs({filename:t,fileId:e,status:r,statusText:s,errorMessage:a,onRemove:i,removeTitle:o,className:l=""}){const c=r==="uploading"||r==="processing",d=r==="error",u=Tu(t),f=e?Mu(e):void 0,p=u.Icon,g=d?a||s:s||u.label;return n.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:[n.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?n.jsxs("div",{className:"relative h-full w-full",children:[n.jsx("img",{src:f,alt:"",className:"h-full w-full object-cover"}),c&&n.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/35",children:n.jsx(Rs,{className:"h-[18px] w-[18px] animate-spin text-white drop-shadow"})})]}):c?n.jsx(Rs,{className:"h-[18px] w-[18px] animate-spin"}):d?n.jsx(La,{className:"h-[18px] w-[18px]"}):n.jsx(p,{className:"h-[18px] w-[18px]"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.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&&n.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&&n.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:n.jsx(Ge,{className:"h-3 w-3"})})]})}const ga=2e3;function vo({initialValue:t="",onSubmit:e,onCancel:r,isSubmitting:s=!1}){const{t:a}=Ee(),[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=()=>{s||e(i.trim())};return n.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:[n.jsx("div",{className:"mb-1 text-[11px] font-medium text-gray-500 dark:text-[#8e8ea0]",children:a("message.feedback.commentPrompt")}),n.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:a("message.feedback.commentPlaceholder"),"aria-label":a("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:s,rows:1,maxLength:ga,style:{minHeight:"24px",maxHeight:"120px"}}),n.jsxs("div",{className:"mt-1.5 flex items-center justify-end gap-2",children:[i.length>0&&n.jsx("span",{className:"mr-auto text-[11px] text-gray-500 dark:text-[#bfc2cd]",children:n.jsxs("span",{className:i.length>=ga?"text-red-600 font-semibold":"",children:[i.length,"/",ga]})}),n.jsx("button",{type:"button",onClick:r,disabled:s,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:a("message.feedback.commentCancel")}),n.jsxs("button",{type:"button",onClick:c,disabled:s,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:[n.jsx(Ms,{className:"h-3.5 w-3.5"}),a("message.feedback.commentSend")]})]})]})}const Gu=[],Xu=(t="png")=>{const e=t.toLowerCase().replace(/^image\//,"");return e==="jpg"?"image/jpeg":`image/${e||"png"}`},Yu=(t,e)=>{const r=atob(t),s=new Uint8Array(r.length);for(let a=0;a<r.length;a+=1)s[a]=r.charCodeAt(a);return new Blob([s],{type:e})},Qu=async t=>{const e=URL.createObjectURL(t);try{const r=new Image;r.decoding="async";const s=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 s;const a=document.createElement("canvas");a.width=r.naturalWidth,a.height=r.naturalHeight;const i=a.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)=>{a.toBlob(c=>{c?o(c):l(new Error("Could not encode generated image for clipboard copy"))},"image/png")})}finally{URL.revokeObjectURL(e)}},Ju=async(t,e)=>{const r=Xu(t.imageFormat);if(t.image)return Yu(t.image,r);if(!t.imageUrl)return null;const s=await fetch(t.imageUrl,{headers:e?{"X-Adapter-Name":e}:{}});if(!s.ok)throw new Error(`Could not fetch generated image for clipboard copy: ${s.status}`);const a=await s.blob();return a.type?a:new Blob([a],{type:r})},Zu=t=>t.imageUrl?new URL(t.imageUrl,window.location.origin).toString():t.imageRevisedPrompt||t.content;function ci({size:t="md"}){const e=t==="sm"?"h-2 w-2":"h-2.5 w-2.5";return n.jsx("div",{className:"flex items-center gap-1.5 py-1",children:[0,150,300].map(r=>n.jsx("span",{className:`inline-block ${e} animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]`,style:{animationDelay:`${r}ms`}},r))})}function ef({reply:t}){const{t:e}=Ee(),[r,s]=m.useState(!1),[a,i]=m.useState(!1),[o,l]=m.useState(!1),[c,d]=m.useState(!1),u=m.useRef(null),f=ge(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 b=t.feedback!==x,k=x==="down"&&b;s(!0);try{if(!await f(t.id,x))return;k?(i(!1),l(!0)):(l(!1),b?p():i(!1))}catch(S){xe("Failed to submit thread reply feedback:",S)}finally{s(!1)}},h=async x=>{if(t.databaseMessageId){d(!0);try{if(!await f(t.id,"down",x))return;l(!1),p()}catch(b){xe("Failed to submit thread reply feedback comment:",b)}finally{d(!1)}}};return n.jsxs("div",{className:"mt-0.5",children:[n.jsxs("div",{className:"flex items-center gap-0.5 text-gray-400 dark:text-[#8e8ea0]",children:[n.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:n.jsx(io,{className:"h-4 w-4"})}),n.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:n.jsx(no,{className:"h-4 w-4"})}),t.feedback==="down"&&!o&&n.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")}),a&&n.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:[n.jsx(ur,{className:"h-3.5 w-3.5"}),e("message.feedback.thanks")]})]}),t.feedback==="down"&&o&&n.jsx(vo,{initialValue:t.feedbackComment,onSubmit:h,onCancel:()=>l(!1),isSubmitting:c})]})}function tf({message:t,onRegenerate:e,onEdit:r,onStartThread:s,onClearThread:a,onSendThreadMessage:i,threadMessages:o,sessionId:l,isThreadSendDisabled:c,availableModels:d=[],defaultModel:u=null,selectedModel:f=null,assistantActions:p="full"}){var rt,ts,ht;const{t:g}=Ee(),[h,x]=m.useState(!1),[b,k]=m.useState(t.content||""),[S,E]=m.useState(!1),_=m.useRef(null),[v,M]=m.useState(!1),[F,y]=m.useState(!1),[A,N]=m.useState(!1),[I,$]=m.useState(!1),[U,X]=m.useState(!1),[j,L]=m.useState(""),[B,C]=m.useState(!1),[H,q]=m.useState(!1),[J,K]=m.useState(!1),[V,oe]=m.useState(0),[T,Q]=m.useState(!1),[R,W]=m.useState(!1),[ne,fe]=m.useState(()=>f??u),D=m.useRef(f),G=m.useRef(((rt=t.threadInfo)==null?void 0:rt.thread_id)||null),se=m.useRef(null),ve=m.useRef(null),ue=m.useRef(null),pe=m.useRef(!1),ce=m.useRef(0),Ae=m.useRef(""),Te=m.useRef(!1),$e=m.useRef(!0),_e=m.useRef(!1),Y=m.useRef(null),ee=m.useRef(null),ae=t.role==="assistant",Ce=p==="full",Se=o??Gu,me=Se.filter(P=>!(P.role==="assistant"&&P.isStreaming)).length,nt=Se.some(P=>P.isStreaming),Le=Sr(),et=st()&&!Le,Fe=ge(P=>P.conversations.find(we=>we.id===P.currentConversationId)),St=!!((t.image||t.imageUrl)&&ae&&!t.isStreaming),hr=!!((t.video||t.videoUrl)&&ae&&!t.isStreaming),Tt=g(St?"message.copyImageLabel":"message.copyLabel"),Xe=Nc(),Ht=le.maxMessageLength,jt=le.maxMessagesPerThread,je=jt!==null&&me>=jt,dt=je?et?g("message.thread.limitReachedGuest",{count:jt}):g("message.thread.limitReachedUser",{count:jt}):null,{theme:ut,isDark:qt}=mr(),gr=g("message.thread.placeholder"),be=`thread-input-${t.id}`,{skills:Z,isLoading:De,selectedSkill:Me,selectSkill:Ye,clearSkill:tt}=go({adapterName:Fe==null?void 0:Fe.adapterName,enabled:Xe&&!!t.threadInfo,selectionScopeKey:((ts=t.threadInfo)==null?void 0:ts.thread_id)||t.id}),rr=j.startsWith("/")?j.slice(1):"",jr=rr.toLowerCase().replace(/-/g," "),ft=jr?Z.filter(P=>P.name.replace(/-/g," ").toLowerCase().includes(jr)||P.description.toLowerCase().includes(jr)):Z,bt=ft.length>0?Math.min(V,ft.length-1):0,yt=ft[bt]??null,Cr=(yt==null?void 0:yt.name.replace(/-/g," "))??"",Ar=J&&yt&&j.startsWith("/")&&Cr.toLowerCase().startsWith(rr.toLowerCase())&&Cr.length>rr.length?Cr.slice(rr.length):null,Mt=ut.mode==="dark"?"dark":ut.mode==="light"?"light":"",sr=qt?"dark":"light",Wt=m.useMemo(()=>["message-markdown w-full min-w-0","prose prose-slate dark:prose-invert max-w-none",Mt].filter(Boolean).join(" "),[Mt]),ar=m.useMemo(()=>["message-markdown w-full min-w-0","prose dark:prose-invert max-w-none",Mt].filter(Boolean).join(" "),[Mt]),Ct=ae?Wt:ar,Kr=`${Wt} text-sm leading-6`,Gr=`${ar} text-sm leading-6`;m.useEffect(()=>{var P,we;!G.current&&((P=t.threadInfo)!=null&&P.thread_id)&&C(!0),G.current=((we=t.threadInfo)==null?void 0:we.thread_id)||null},[(ht=t.threadInfo)==null?void 0:ht.thread_id]),m.useEffect(()=>{t.threadInfo||setTimeout(()=>{L(""),C(!1),q(!1),K(!1),tt()},0)},[t.threadInfo,tt]),m.useEffect(()=>{me>0&&setTimeout(()=>{C(!0)},0)},[me]),m.useEffect(()=>()=>{Y.current&&clearTimeout(Y.current),ee.current&&clearTimeout(ee.current)},[]),m.useEffect(()=>{if(!h||!_.current)return;const P=_.current;P.focus(),P.setSelectionRange(P.value.length,P.value.length)},[h]),m.useEffect(()=>{if(!h||!_.current)return;const P=_.current;P.style.height="auto",P.style.height=`${P.scrollHeight}px`},[h,b]);const Ft=m.useCallback(()=>{const P=b.trim();if(!P||P===t.content){x(!1);return}r==null||r(t.id,P),x(!1)},[b,t.content,t.id,r]),Rt=m.useCallback(()=>{requestAnimationFrame(()=>{ue.current&&(ue.current.scrollTop=ue.current.scrollHeight)})},[]);m.useEffect(()=>{if(!B)return;const P=Se.length,we=P>ce.current,te=Se[Se.length-1],Ie=(te==null?void 0:te.content)||"",it=Ie!==Ae.current,Dt=(te==null?void 0:te.isStreaming)??!1,Er=Te.current&&!Dt;we||Dt&&it||Er?(Rt(),$e.current=!0):$e.current&&it&&Rt(),ce.current=P,Ae.current=Ie,Te.current=Dt},[B,Se,Rt]),m.useEffect(()=>{B&&(Rt(),$e.current=!0)},[B,Rt]);const qe=ae?"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)]",pr=m.useCallback(()=>{M(!0),Y.current&&clearTimeout(Y.current),Y.current=setTimeout(()=>{M(!1),Y.current=null},2e3)},[]),nr=async()=>{try{if(St){if("ClipboardItem"in window&&navigator.clipboard.write)try{const we=(Fe==null?void 0:Fe.adapterName)||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),te=await Ju(t,we);if(te){const Ie=te.type==="image/png"?te:await Qu(te);await navigator.clipboard.write([new ClipboardItem({[Ie.type||"image/png"]:Ie})]),pr();return}}catch(we){xe("Failed to copy generated image, falling back to text:",we)}const P=Zu(t);if(P){await navigator.clipboard.writeText(P),pr();return}return}await navigator.clipboard.writeText(t.content),pr()}catch(P){xe(St?"Failed to copy generated image:":"Failed to copy text:",P)}},Xr=ge(P=>P.submitFeedback),$t=()=>{N(!0),ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>{N(!1),ee.current=null},2e3)},mt=async P=>{if(!t.databaseMessageId||F)return;const we=t.feedback!==P,te=P==="down"&&we;y(!0);try{if(!await Xr(t.id,P))return;te?(N(!1),$(!0)):($(!1),we?$t():N(!1))}catch(Ie){xe("Failed to submit feedback:",Ie)}finally{y(!1)}},Zs=async P=>{if(t.databaseMessageId){X(!0);try{if(!await Xr(t.id,"down",P))return;$(!1),$t()}catch(we){xe("Failed to submit feedback comment:",we)}finally{X(!1)}}},Yr=async()=>{if(!i||!t.threadInfo||je)return;const P=j.trim();if(!P)return;const we=j,te=Me,Ie=Me==null?void 0:Me.name;L(""),q(!0),K(!1),Ie&&tt();try{await i(t.threadInfo.thread_id,t.id,P,Ie,ne??u??void 0),setTimeout(()=>{se.current&&se.current.focus()},100)}catch(it){xe("Failed to send thread message:",it),L(we),te&&Ye(te),setTimeout(()=>{se.current&&se.current.focus()},100)}finally{q(!1)}},Qr=m.useCallback(P=>{var we;Ye(P),K(!1),L(""),oe(0),(we=se.current)==null||we.focus()},[Ye]),wt=m.useCallback(()=>{var P;K(!1),L(""),oe(0),(P=se.current)==null||P.focus()},[]),Jr=m.useCallback(()=>{var P;L("/"),K(!0),oe(0),(P=se.current)==null||P.focus()},[]),Zr=P=>{if(J){if(P.key==="ArrowDown"){P.preventDefault(),oe(we=>ft.length===0?0:(we+1)%ft.length);return}if(P.key==="ArrowUp"){P.preventDefault(),oe(we=>ft.length===0?0:(we-1+ft.length)%ft.length);return}if(P.key==="Home"){P.preventDefault(),oe(0);return}if(P.key==="End"){P.preventDefault(),oe(Math.max(ft.length-1,0));return}if((P.key==="Enter"&&!P.shiftKey||P.key==="Tab")&&yt){P.preventDefault(),Qr(yt);return}if(P.key==="Escape"){P.preventDefault(),wt();return}}P.key==="Enter"&&!P.shiftKey&&(P.preventDefault(),Yr())},Pt=!t.threadInfo||!i||c||nt||H||je,es=!!t.threadInfo&&!!a&&me>0&&!nt&&!H&&!c,Nr=async()=>{if(!(!t.threadInfo||!a)){W(!0);try{await a(t.id,t.threadInfo.thread_id),Q(!1),C(!1),L("")}catch(P){xe("Failed to clear thread:",P)}finally{W(!1)}}};m.useEffect(()=>{D.current=f},[f]),m.useEffect(()=>{fe(D.current??u)},[u]),m.useEffect(()=>{if(!B||Pt){_e.current=H;return}const P=se.current;if(!P){_e.current=H;return}if(!(pe.current||_e.current)){_e.current=H;return}const te=requestAnimationFrame(()=>{var it;pe.current&&((it=ve.current)==null||it.scrollIntoView({behavior:"auto",block:"nearest",inline:"nearest"})),P.focus();const Ie=P.value.length;P.setSelectionRange(Ie,Ie),pe.current=!1,_e.current=H});return()=>{cancelAnimationFrame(te),_e.current=H}},[B,Pt,H]),m.useEffect(()=>{if(se.current){const we=se.current;we.style.height="auto";const te=we.scrollHeight;we.style.height=`${Math.min(te,120)}px`,we.style.overflowY=te>120?"auto":"hidden"}},[j]);const ir=m.useMemo(()=>{if(t.isStreaming&&(!t.content||t.content==="…"))return n.jsx("div",{className:Ct,children:n.jsx(ci,{})});const P=t.isStreaming&&ae?" streaming-cursor":"";return n.jsx("div",{className:P||void 0,children:n.jsx(_t,{content:Ra(qr(t.content||"")),className:Ct,syntaxTheme:sr})})},[Ct,t.content,t.isStreaming,ae,sr]),Ir=m.useMemo(()=>{const P=te=>te instanceof Date?te.getTime():new Date(te).getTime();return[...Se].sort((te,Ie)=>P(te.timestamp)-P(Ie.timestamp)).map(te=>{const Ie=te.role==="assistant",it=Ie?Kr:Gr,Dt=te.isStreaming&&Ie?" streaming-cursor":"",Er=te.isStreaming&&(!te.content||te.content==="…")?n.jsx("div",{className:it,children:n.jsx(ci,{size:"sm"})}):n.jsx("div",{className:Dt||void 0,children:n.jsx(_t,{content:Ra(qr(te.content||"")),className:it,syntaxTheme:sr})});return n.jsx("div",{className:`min-w-0 flex ${Ie?"justify-start":"justify-end"}`,children:n.jsxs("div",{className:Ie?"min-w-0 w-full max-w-full":"min-w-0 max-w-[85%]",children:[n.jsxs("div",{className:Ie?"thread-markdown-wrapper overflow-x-visible text-sm text-[#353740] dark:text-[#ececf1]":"thread-markdown-wrapper overflow-x-visible text-sm rounded-[1.75rem] bg-[#f4f4f4] px-4 py-3 text-[#111827] dark:bg-[#2a2a2a] dark:text-[#f5f5f5]",children:[Er,te.audio&&Ie&&!te.isStreaming&&n.jsx(xs,{audio:te.audio,audioFormat:te.audioFormat,autoPlay:!1}),(te.image||te.imageUrl)&&Ie&&!te.isStreaming&&n.jsx(Xn,{image:te.image,imageUrl:te.imageUrl,imageFormat:te.imageFormat,revisedPrompt:te.imageRevisedPrompt}),(te.video||te.videoUrl)&&Ie&&!te.isStreaming&&n.jsx(Yn,{video:te.video,videoUrl:te.videoUrl,videoFormat:te.videoFormat,revisedPrompt:te.videoRevisedPrompt,adapterName:Fe==null?void 0:Fe.adapterName}),(te.document||te.documentUrl)&&Ie&&!te.isStreaming&&n.jsx(ei,{document:te.document,documentUrl:te.documentUrl,documentFormat:te.documentFormat,revisedPrompt:te.documentRevisedPrompt,adapterName:Fe==null?void 0:Fe.adapterName}),te.generatedAudioUrl&&Ie&&!te.isStreaming&&n.jsx(xs,{audioUrl:te.generatedAudioUrl,audioFormat:te.generatedAudioFormat,downloadFilename:`generated-audio.${te.generatedAudioFormat||"mp3"}`,autoPlay:!1})]}),Ie&&!te.isStreaming&&te.model&&n.jsx("div",{className:"px-1 pt-0.5 text-[11px] text-gray-400 dark:text-[#9a9ab0]",children:g("message.generatedBy",{model:te.model})}),Ie&&!te.isStreaming&&gs()&&n.jsx(ef,{reply:te})]})},te.id)})},[Fe==null?void 0:Fe.adapterName,sr,g,Kr,Se,Gr]);return n.jsxs("div",{className:"group animate-fadeIn min-w-0 w-full px-0",children:[n.jsxs("div",{className:"min-w-0 space-y-1",children:[n.jsxs("div",{className:ae?void 0:"flex flex-col items-end",children:[n.jsxs("div",{className:qe,children:[h?n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("textarea",{ref:_,className:"w-full resize-none overflow-hidden bg-transparent outline-none text-[#111827] dark:text-[#f5f5f5] leading-relaxed",value:b,onChange:P=>k(P.target.value),onCompositionStart:()=>E(!0),onCompositionEnd:()=>E(!1),onKeyDown:P=>{P.key==="Enter"&&!P.shiftKey&&!S&&(P.preventDefault(),P.stopPropagation(),Ft()),P.key==="Escape"&&(P.stopPropagation(),x(!1),k(t.content||""))},maxLength:le.maxMessageLength,rows:1,style:{minHeight:"24px"}}),n.jsxs("div",{className:"flex items-center justify-between gap-2 mt-1",children:[n.jsx("span",{className:"text-xs text-gray-400 dark:text-[#6e6e80]",children:g("message.edit.willRegenerateHint")}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{onClick:()=>{x(!1),k(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:g("common.cancel")}),n.jsxs("button",{onClick:Ft,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:[n.jsx(Ms,{className:"w-3.5 h-3.5"}),g("common.send")]})]})]})]}):ir,t.attachments&&t.attachments.length>0&&n.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:t.attachments.map(P=>n.jsx(Bs,{filename:P.filename,fileId:P.file_id,status:"completed",statusText:`${(P.file_size/1024).toFixed(1)} KB`},P.file_id))}),t.audio&&ae&&!t.isStreaming&&n.jsx(xs,{audio:t.audio,audioFormat:t.audioFormat,autoPlay:!1}),(t.image||t.imageUrl)&&ae&&!t.isStreaming&&n.jsx(Xn,{image:t.image,imageUrl:t.imageUrl,imageFormat:t.imageFormat,revisedPrompt:t.imageRevisedPrompt}),(t.video||t.videoUrl)&&ae&&!t.isStreaming&&n.jsx(Yn,{video:t.video,videoUrl:t.videoUrl,videoFormat:t.videoFormat,revisedPrompt:t.videoRevisedPrompt,adapterName:Fe==null?void 0:Fe.adapterName}),(t.document||t.documentUrl)&&ae&&!t.isStreaming&&n.jsx(ei,{document:t.document,documentUrl:t.documentUrl,documentFormat:t.documentFormat,revisedPrompt:t.documentRevisedPrompt,adapterName:Fe==null?void 0:Fe.adapterName}),t.generatedAudioUrl&&ae&&!t.isStreaming&&n.jsx(xs,{audioUrl:t.generatedAudioUrl,audioFormat:t.generatedAudioFormat,downloadFilename:`generated-audio.${t.generatedAudioFormat||"mp3"}`,autoPlay:!1})]}),!ae&&!h&&n.jsxs("div",{className:"flex items-center gap-0.5 py-1 text-gray-400 dark:text-[#8e8ea0]",children:[n.jsx("button",{onClick:nr,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:Tt,"aria-label":Tt,children:v?n.jsx(ur,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):n.jsx(Un,{className:"h-4 w-4"})}),r&&n.jsx("button",{onClick:()=>{k(t.content||""),x(!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:g("message.editAriaLabel"),"aria-label":g("message.editAriaLabel"),children:n.jsx(so,{className:"h-4 w-4"})})]})]}),ae&&!t.isStreaming&&t.model&&n.jsx("div",{className:"px-1 pt-0.5 text-[11px] text-gray-400 dark:text-[#9a9ab0]",children:g("message.generatedBy",{model:t.model})}),ae&&!t.isStreaming&&n.jsxs("div",{className:"py-1 flex flex-nowrap items-center gap-0.5 text-gray-400 dark:text-[#8e8ea0] transition-opacity",children:[!hr&&n.jsx("button",{onClick:nr,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:Tt,"aria-label":Tt,children:v?n.jsx(ur,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):n.jsx(Un,{className:"h-4 w-4"})}),Ce&&gs()&&n.jsxs("div",{className:"relative flex items-center gap-0.5",children:[n.jsx("button",{onClick:()=>mt("up"),disabled:F,className:`rounded-md p-1.5 transition-colors ${F?"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:g("message.feedback.good"),"aria-label":g("message.feedback.good"),children:n.jsx(io,{className:"h-4 w-4"})}),n.jsx("button",{onClick:()=>mt("down"),disabled:F,className:`rounded-md p-1.5 transition-colors ${F?"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:g("message.feedback.poor"),"aria-label":g("message.feedback.poor"),children:n.jsx(no,{className:"h-4 w-4"})}),A&&n.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:[n.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"}),n.jsxs("div",{className:"relative flex items-center gap-1.5",children:[n.jsx(ur,{className:"h-3.5 w-3.5"}),n.jsx("span",{children:g("message.feedback.thanks")})]})]})]}),Ce&&gs()&&t.feedback==="down"&&!I&&n.jsx("button",{type:"button",onClick:()=>$(!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?g("message.feedback.commentEdit"):g("message.feedback.commentPrompt")}),Ce&&e&&n.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:g("message.regenerateTitle"),"aria-label":g("message.regenerateAriaLabel"),children:n.jsx(Nd,{className:"h-4 w-4"})}),Ce&&Xe&&t.supportsThreading&&!t.threadInfo&&s&&l&&n.jsxs("button",{type:"button",onClick:()=>{pe.current=!0,C(!0),s(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:g("message.thread.continueDiscussionTitle"),"aria-label":g("message.thread.continueDiscussionAriaLabel"),children:[n.jsx(On,{className:"h-3.5 w-3.5 shrink-0"}),n.jsx("span",{children:g("message.thread.continueLabel")})]}),Ce&&Xe&&t.threadInfo&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"w-px h-4 shrink-0 bg-gray-200 dark:bg-[#3c3f4a] mx-1"}),n.jsxs("button",{onClick:()=>C(P=>!P),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:[n.jsx(On,{className:"h-4 w-4"}),n.jsx("span",{className:"truncate",children:g("message.thread.replyCount",{count:me})}),B?n.jsx(Fs,{className:"h-3 w-3"}):n.jsx(vr,{className:"h-3 w-3"})]}),es&&n.jsx("button",{type:"button",onClick:()=>Q(!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:g("message.thread.clearTitle"),"aria-label":g("message.thread.clearAriaLabel"),children:g("common.clear")})]})]}),ae&&!t.isStreaming&&Ce&&gs()&&t.feedback==="down"&&I&&n.jsx(vo,{initialValue:t.feedbackComment,onSubmit:Zs,onCancel:()=>$(!1),isSubmitting:U}),Xe&&t.threadInfo&&B&&n.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:[n.jsx("div",{ref:ue,className:"thread-replies-scroll mt-2 space-y-2 pb-3",onScroll:()=>{if(!ue.current)return;const{scrollTop:P,scrollHeight:we,clientHeight:te}=ue.current;$e.current=we-P-te<100},children:me>0?Ir:null}),dt&&n.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:[dt,et&&n.jsx("div",{className:"mt-2",children:n.jsx("button",{type:"button",onClick:()=>at.getState().openLoginPrompt(g("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:g("message.thread.signInForHigherLimits")})})]}),n.jsxs("div",{ref:ve,className:"mt-1 w-full max-w-[64rem] bg-transparent pt-1",children:[n.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:[Me&&n.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:[n.jsx(Ga,{className:"h-3.5 w-3.5 shrink-0 text-gray-500 dark:text-gray-400","aria-hidden":"true"}),n.jsx("span",{className:"min-w-0 truncate font-medium capitalize",children:Me.name.replace(/-/g," ")}),n.jsx("button",{type:"button",onClick:()=>tt(),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":g("message.thread.removeSkillAriaLabel"),children:n.jsx(Ge,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),!Me&&Z.length>0&&j.length===0&&!Pt&&n.jsxs("button",{type:"button",onClick:Jr,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":g("message.thread.skillsHintAriaLabel"),title:g("message.thread.skillsHint"),children:[n.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:"/"}),g("messageInput.skillsHint.text")]}),n.jsxs("div",{className:"relative flex min-h-8 flex-1 items-center min-w-0",children:[n.jsx("label",{htmlFor:be,className:"sr-only",children:g("message.thread.placeholder")}),Ar&&n.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:[n.jsx("span",{className:"invisible",children:j}),n.jsx("span",{children:Ar})]}),n.jsx("textarea",{id:be,ref:se,className:"relative z-10 block h-8 w-full min-w-0 resize-none overflow-hidden bg-transparent px-0 py-0 text-base leading-8 text-[#353740] placeholder-slate-500 outline-none transition focus:outline-none disabled:opacity-60 dark:text-[#ececf1] dark:placeholder-[#70707c] sm:text-sm sm:leading-8",placeholder:gr,"aria-label":g("message.thread.placeholder"),value:j,onChange:P=>{const we=P.target.value;L(we),we.startsWith("/")&&oe(0),K(we.startsWith("/"))},onKeyDown:Zr,disabled:Pt,rows:1,maxLength:Ht,style:{minHeight:"32px",maxHeight:"120px",outline:"none",boxShadow:"none",WebkitAppearance:"none",MozAppearance:"none",appearance:"none"}})]}),n.jsxs("div",{className:"flex items-center justify-between sm:justify-end gap-2",children:[n.jsx(Da,{availableModels:d,defaultModel:u,selectedModel:ne,onSelect:fe,maxWidthClass:"max-w-[120px]",triggerPaddingClass:"px-2 py-1",staticPaddingClass:"px-2 py-1",triggerTitle:g("message.thread.selectModelTitle"),listboxLabel:g("message.thread.selectModelTitle")}),j.trim().length>0&&n.jsx("button",{type:"button",onClick:Yr,disabled:Pt||j.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:g("message.thread.sendMessageTitle"),children:n.jsx(Ms,{className:"h-5 w-5 sm:h-4 sm:w-4"})})]})]}),J&&n.jsx("div",{className:"w-full pt-1",children:n.jsx(ko,{skills:Z,isLoading:De,selectedSkill:Me,activeSkillName:yt==null?void 0:yt.name,query:rr,onActiveSkillChange:P=>{const we=ft.findIndex(te=>te.name===P.name);we>=0&&oe(we)},onSelect:Qr,onClose:wt})})]}),me>0&&n.jsx("div",{className:"mt-2 flex justify-end",children:n.jsxs("button",{type:"button",onClick:()=>C(!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":g("message.thread.hideRepliesAriaLabel"),children:[n.jsx(Fs,{className:"h-3 w-3"}),n.jsx("span",{children:g("message.thread.hideRepliesLabel")})]})})]})]}),n.jsx(Ds,{isOpen:T,onClose:()=>{R||Q(!1)},onConfirm:Nr,title:g("message.confirmation.clearRepliesTitle"),message:g("message.confirmation.clearRepliesMessage"),confirmText:g("common.clear"),cancelText:g("common.cancel"),type:"danger",isLoading:R})]})}let br=null;function rf(){if(typeof window>"u")return null;const t=window.AudioContext??window.webkitAudioContext;return t?((!br||br.state==="closed")&&(br=new t),br.state==="suspended"&&br.resume(),br):(z("[SoundEffects] AudioContext not supported in this browser"),null)}function sf(t){const e=rf();if(!e)return;const r=e.currentTime;for(const s of t){const a=e.createOscillator(),i=e.createGain();a.connect(i),i.connect(e.destination),a.frequency.value=s.frequency,a.type=s.type;const o=r+s.startTime,l=o+s.duration;i.gain.setValueAtTime(.001,o),i.gain.linearRampToValueAtTime(s.gain,o+.008),i.gain.exponentialRampToValueAtTime(.001,l),a.start(o),a.stop(l+.01)}}const af={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=af[t];if(!r){z(`[SoundEffects] Unknown sound effect type: ${t}`);return}try{sf(r),z(`[SoundEffects] Playing ${t} sound effect`)}catch(s){z(`[SoundEffects] Failed to play ${t} sound effect:`,s)}}function di({messages:t,onRegenerate:e,onEditMessage:r,onStartThread:s,onClearThread:a,onSendThreadMessage:i,sessionId:o,isLoading:l,contentMaxWidthClass:c="max-w-[64rem]",availableModels:d,defaultModel:u,selectedModel:f,assistantActions:p="full"}){const g=m.useRef(null),h=m.useRef(null),x=m.useRef(t.length),b=m.useRef(""),k=m.useRef(l),S=m.useRef(!0),{settings:E}=qs(),{t:_}=Ee(),{topLevelMessages:v,threadLookup:M}=m.useMemo(()=>{const A=new Map,N=[];return t.forEach(I=>{if(I.isThreadMessage&&I.parentMessageId){const $=A.get(I.parentMessageId)||[];A.set(I.parentMessageId,[...$,I]);return}N.push(I)}),{topLevelMessages:N,threadLookup:A}},[t]),F=()=>{if(!h.current)return;const{scrollTop:A,scrollHeight:N,clientHeight:I}=h.current,U=N-A-I<200;S.current=U},y=m.useCallback(()=>{requestAnimationFrame(()=>{h.current&&(h.current.scrollTop=h.current.scrollHeight)})},[]);return m.useEffect(()=>{const A=t.length,N=x.current,I=A>N,$=t[t.length-1],U=($==null?void 0:$.content)||"",X=U!==b.current,j=($==null?void 0:$.isStreaming)??!1;I||j&&X?(y(),S.current=!0):S.current&&X&&y(),x.current=A,b.current=U},[t,y]),m.useEffect(()=>{l&&(y(),S.current=!0)},[l,y]),m.useEffect(()=>{if(k.current&&!l){const A=t[t.length-1];(A==null?void 0:A.role)==="assistant"&&A.content&&Pr("messageReceived",E.soundEnabled)}k.current=l},[l,t,E.soundEnabled]),v.length===0?n.jsx("div",{className:"flex-1 flex items-center justify-center px-4 sm:px-6",children:n.jsxs("div",{className:"text-center text-lg text-gray-500 dark:text-[#bfc2cd]",children:[n.jsx("p",{className:"text-xl",children:_("messageList.emptyStateHeading")}),n.jsx("p",{className:"mt-1 text-lg",children:_("messageList.emptyStateSubheading")})]})}):n.jsx("div",{ref:h,className:"message-list flex-1 overflow-y-auto pb-8 pt-4 sm:pt-6",onScroll:F,children:n.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:n.jsxs("div",{className:`message-list__rail mx-auto w-full space-y-7 ${c}`,children:[v.map(A=>n.jsx("div",{className:`flex w-full ${A.role==="user"?"justify-end":"justify-start"}`,style:{contentVisibility:"auto",containIntrinsicSize:"420px"},children:n.jsx(tf,{message:A,onRegenerate:e,onEdit:r,onStartThread:s,onClearThread:a,onSendThreadMessage:i,threadMessages:M.get(A.id),sessionId:o,isThreadSendDisabled:l,availableModels:d,defaultModel:u,selectedModel:f,assistantActions:p})},A.id)),n.jsx("div",{ref:g,className:"h-8"})]})})})}const nf=4e3;function of(t,e,r={}){var A;const{t:s}=Ee(),[a,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):nf,x=((A=r.language)==null?void 0:A.trim())||g||"en-US",b=m.useCallback(N=>N.replace(/\s+/g," ").trim(),[]),k=m.useCallback(N=>{const I=b(N);I&&I!==u.current&&(u.current=I,t(I))},[b,t]),S=m.useCallback(()=>{if(!d.current)return;const N=d.current;d.current="",k(N)},[k]),E=typeof window<"u"&&("webkitSpeechRecognition"in window||"SpeechRecognition"in window),_=m.useCallback(()=>{!e||f.current||(f.current=!0,e())},[e]),v=m.useCallback(()=>{p.current!==null&&(clearTimeout(p.current),p.current=null)},[]),M=m.useCallback(()=>{v(),p.current=setTimeout(()=>{z("Speech recognition silence threshold reached, stopping recording"),c.current?c.current.stop():_()},h)},[v,_,h]),F=m.useCallback(()=>{if(!E){l(s("voice.browserNotSupported"));return}if(!c.current)try{f.current=!1;const N=window.SpeechRecognition||window.webkitSpeechRecognition,I=new N;I.continuous=!0,I.interimResults=!0,I.lang=x,I.maxAlternatives=1,I.onstart=()=>{i(!0),l(null),d.current="",u.current="",z("Speech recognition started"),M()},I.onresult=$=>{let U="",X="";for(let j=$.resultIndex;j<$.results.length;j++){const L=$.results[j][0].transcript;$.results[j].isFinal?U+=L:X+=L}X&&(d.current=b(X)),U&&(d.current="",k(U)),M()},I.onend=()=>{v(),S(),i(!1),c.current=null,z("Speech recognition ended"),_()},I.onerror=$=>{switch(v(),xe("Speech recognition error:",$.error),i(!1),c.current=null,d.current="",_(),$.error){case"no-speech":l(s("voice.error.noSpeech"));break;case"audio-capture":l(s("voice.error.audioCapture"));break;case"not-allowed":l(s("voice.error.notAllowed"));break;case"network":l(s("voice.error.network"));break;default:l(s("voice.error.generic",{error:$.error}))}},I.start(),c.current=I}catch(N){xe("Failed to start speech recognition:",N),l(s("voice.error.startFailed")),i(!1)}},[E,S,_,M,v,x,b,k,s]),y=m.useCallback(()=>{if(z("Stopping speech recognition..."),c.current){const N=c.current;N.onstart=null,N.onerror=null;try{N.stop()}catch(I){z("Recognition already stopped or error stopping:",I),v(),S(),N.onend=null,N.onresult=null,c.current=null,i(!1),_()}}v(),i(!1),l(null),z("Speech recognition stopped, isListening set to false")},[v,S,_]);return{isListening:a,isSupported:E,startListening:F,stopListening:y,error:o}}const lf=300,ui=3,Ss=5,cf=6e4;function fi(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 df(t,e={}){const{enabled:r=Hi(),adapterName:s,sessionId:a,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),b=m.useRef(null),k=m.useRef(null),S=m.useRef(null),E=m.useRef(0),_=m.useRef([]),v=m.useRef([]),M=m.useRef(new Map);m.useEffect(()=>{_.current=c},[c]);const F=m.useCallback(j=>{const L=M.current.get(j);return L?L<=Date.now()?(M.current.delete(j),!1):!0:!1},[]),y=m.useCallback((j,L=!0)=>{const B=j.toLowerCase().trim(),C=v.current.length>0?v.current:_.current;if(!B)return C.slice(0,Ss);const H=C.filter(q=>q.text.toLowerCase().includes(B));return H.length>0?H.slice(0,Ss):L?C.slice(0,Ss):[]},[]),A=m.useCallback(async j=>{if(!r||j.length<ui){d([]),v.current=[],x.current&&clearTimeout(x.current),b.current&&clearTimeout(b.current),f(!1);return}if(!s){d([]),v.current=[],x.current&&clearTimeout(x.current),f(!1);return}if(i===!1||F(s)){d([]),v.current=[],x.current&&clearTimeout(x.current),f(!1);return}k.current&&k.current.abort(),k.current=new AbortController;const L=E.current+1;E.current=L,x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{L===E.current&&f(!0)},150);try{const B={"X-Adapter-Name":s};a&&(B["X-Session-ID"]=a);const C=new URLSearchParams;C.set("q",j),C.set("limit",String(Ss)),o&&C.set("skill",o);const H=`/api/v1/autocomplete?${C.toString()}`,q=await fetch(H,{method:"GET",headers:B,signal:k.current.signal});if(!q.ok){ye("[useAutocomplete] Request failed:",q.status),[404,405,501].includes(q.status)?(M.current.set(s,Date.now()+cf),d([]),v.current=[]):d(y(j));return}const J=await q.json(),K=Array.isArray(J==null?void 0:J.suggestions)?J.suggestions.map(V=>fi(typeof V=="string"?V:V==null?void 0:V.text)).filter(V=>V!==null):[];if(L!==E.current)return;K.length===0?d(y(j,!1)):(d(K),v.current=K),g(-1),z("[useAutocomplete] Received",K.length,"suggestions")}catch(B){if(B instanceof Error&&B.name==="AbortError")return;ye("[useAutocomplete] Error:",B instanceof Error?B.message:String(B)),L===E.current&&d(y(j))}finally{L===E.current&&(x.current&&(clearTimeout(x.current),x.current=null),f(!1))}},[r,s,a,i,o,y,F]);m.useEffect(()=>{h.current&&clearTimeout(h.current);const j=()=>{k.current&&k.current.abort(),x.current&&clearTimeout(x.current),f(!1)},L=()=>{b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{b.current=null,d([]),j()},0)};if(!r||t.length<ui||i===!1||s&&F(s)){L();return}if(S.current){if(t===S.current){L();return}S.current=null}return h.current=setTimeout(()=>{A(t)},lf),()=>{h.current&&clearTimeout(h.current),b.current&&(clearTimeout(b.current),b.current=null)}},[t,A,r,s,i,F]),m.useEffect(()=>()=>{k.current&&k.current.abort(),x.current&&clearTimeout(x.current)},[]);const N=m.useCallback(()=>{g(j=>{const L=_.current.length;return L===0?-1:j<L-1?j+1:0})},[]),I=m.useCallback(()=>{g(j=>{const L=_.current.length;return L===0?-1:j>0?j-1:L-1})},[]),$=m.useCallback(()=>{d([]),v.current=[],g(-1),k.current&&k.current.abort(),x.current&&clearTimeout(x.current),f(!1)},[]),U=m.useCallback(j=>{if(!(l!=null&&l.current))return;const L=()=>{const B=l.current;if(!B)return;const C=typeof j=="string"?j.length:B.value.length;B.focus({preventScroll:!0}),typeof B.setSelectionRange=="function"&&B.setSelectionRange(C,C)};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(L):setTimeout(L,0)},[l]),X=m.useCallback(j=>{S.current=j},[]);return{suggestions:c,isLoading:u,selectedIndex:p,setSelectedIndex:g,selectNext:N,selectPrevious:I,clearSuggestions:$,focusInputAfterSelection:U,suppressUntilQueryChange:X}}const Qt=new Map,uf=new Map,ff=new Map,mf=new Set,hf=()=>{if(typeof window>"u")return null;try{return localStorage.getItem("chat-adapter-name")}catch{return null}},So=t=>typeof t=="object"&&t!==null&&"message"in t,gf=t=>t instanceof Error?t.message:typeof t=="string"?t:So(t)?t.message??"Unknown error":"Unknown error";function pf({conversationId:t,onFilesSelected:e,onUploadError:r,onClose:s,onUploadingChange:a,onUploadSuccess:i,maxFiles:o=le.maxFilesPerConversation,disabled:l=!1}){const{t:c}=Ee(),[d,u]=m.useState(!1),[f,p]=m.useState(0),g=m.useRef(null),h=m.useRef(ff),x=m.useRef(mf),b=m.useRef(new Map),k=m.useRef(!0),S=m.useRef(uf),E=m.useRef(t),_=ge(T=>T.conversations),v=m.useMemo(()=>{if(!t)return new Map;const T=Qt.get(t);return T?new Map(T):new Map},[t,f]),M=m.useMemo(()=>{var R;if(!t)return Array.from(v.entries());const T=_.find(W=>W.id===t),Q=new Set(((R=T==null?void 0:T.attachedFiles)==null?void 0:R.map(W=>W.file_id))||[]);return Array.from(v.entries()).filter(([,W])=>!W.fileId||!Q.has(W.fileId))},[t,_,v]),F=m.useCallback(T=>{if(!T){a==null||a(null,!1),p(ne=>ne+1);return}const Q=Qt.get(T)||new Map,R=_.find(ne=>ne.id===T),W=new Map(Q);if(R){const ne=new Set((R.attachedFiles||[]).map(D=>D.file_id)),fe=new Set((R.attachedFiles||[]).filter(D=>D.processing_status==="completed"||D.processing_status==="failed"||D.processing_status==="error").map(D=>D.file_id));W.forEach((D,G)=>{if(D.fileId&&fe.has(D.fileId)){W.delete(G);return}D.fileId&&x.current.has(D.fileId)&&!ne.has(D.fileId)&&(z(`[FileUpload] Removing progress for deleted file ${D.fileId}`),h.current.delete(D.fileId),W.delete(G))})}W.size>0?(Qt.set(T,W),a==null||a(T,!0)):(Qt.delete(T),a==null||a(T,!1)),p(ne=>ne+1)},[_,a]);m.useEffect(()=>{E.current=t,setTimeout(()=>{F(t)},0)},[t,F]),m.useEffect(()=>{t&&setTimeout(()=>{F(t)},0)},[_,t,F]);const y=m.useCallback((T,Q)=>{if(!T)return;const R=Qt.get(T)||new Map,W=Q(new Map(R));W.size>0?Qt.set(T,W):Qt.delete(T),a==null||a(T,W.size>0),p(ne=>ne+1)},[a]),A=m.useCallback((T,Q)=>{if(!T)return;const R=S.current.get(T)||[],W=Q([...R||[]]),ne=new Set(R.map(fe=>fe.file_id));if(S.current.set(T,W),e(T,W),i){const fe=W.filter(D=>!ne.has(D.file_id));fe.length>0&&i(T,fe)}p(fe=>fe+1)},[e,i]),N=ge(T=>T.removeFileFromConversation),I=ge(T=>T.addFileToConversation);m.useEffect(()=>(k.current=!0,()=>{k.current=!1}),[]);const $=m.useCallback(()=>{k.current=!1,new Map(b.current).forEach(Q=>Q.abort()),setTimeout(()=>{const Q=ge.getState(),R=new Map(Q.conversations.map(ne=>[ne.id,ne])),W=[];h.current.forEach((ne,fe)=>{var D;if(ne){const G=R.get(ne);if(new Set(((D=G==null?void 0:G.attachedFiles)==null?void 0:D.map(ve=>ve.file_id))||[]).has(fe)){x.current.add(fe),h.current.delete(fe);return}}if(x.current.has(fe)){z(`[FileUpload] Skipping cleanup delete for ${fe}; file was previously attached and already handled`),h.current.delete(fe),x.current.delete(fe);return}W.push({fileId:fe,conversationId:ne||null})}),W.length>0&&(s==null||s(),W.forEach(async({fileId:ne,conversationId:fe})=>{try{if(fe)await N(fe,ne);else{const D=hf();Vt.cancelFilePoll(ne),await Vt.deleteFile(ne,void 0,void 0,D??void 0),$a(ne)}}catch(D){if(So(D)){const G=D.message??"";!G.includes("404")&&!G.includes("File not found")&&ye(`Failed to cleanup file ${ne} during component unmount:`,D)}else ye(`Failed to cleanup file ${ne} during component unmount`,D)}}))},300)},[s,N]);m.useEffect(()=>$,[$]);const U=m.useCallback(async T=>{var pe;if(!T||T.length===0)return;const Q=Array.from(T),R=ge.getState(),W=t||R.currentConversationId;if(!W){r==null||r(c("fileUpload.selectBeforeUpload"));return}const ne=R.conversations.find(ce=>ce.id===W);if(!ne){r==null||r(c("fileUpload.conversationNotFound"));return}const fe=ne.attachedFiles||[],D=[],G=Q.filter(ce=>fe.some(Te=>Te.filename===ce.name&&Te.file_size===ce.size)?(D.push(ce.name),!1):!0);if(D.length>0&&(r==null||r(D.length===1?c("fileUpload.duplicateFileError",{filename:D[0]}):c("fileUpload.duplicateFilesError",{count:D.length}))),G.length===0)return;if((S.current.get(W)||[]).length+G.length>o){const ce=c("fileUpload.maxFilesPerConversationError",{count:o});st()&&!vt()&&at.getState().openLoginPrompt(c("fileUpload.maxFilesGuestLimitMessage",{count:o})),r==null||r(ce);return}if(le.maxTotalFiles!==null&&R.conversations.reduce((Te,$e)=>{var _e;return Te+(((_e=$e.attachedFiles)==null?void 0:_e.length)||0)},0)+G.length>le.maxTotalFiles){const Te=c("fileUpload.maxTotalFilesError",{count:le.maxTotalFiles});st()&&!vt()&&at.getState().openLoginPrompt(c("fileUpload.maxTotalFilesGuestLimitMessage",{count:le.maxTotalFiles})),r==null||r(Te);return}if(!ne.adapterName){r==null||r(c("fileUpload.adapterNotConfigured"));return}const ve=ne.adapterName,ue=lt(ne.apiUrl);for(let ce=0;ce<G.length;ce++){const Ae=G[ce],Te=new AbortController;b.current.set(Ae.name,Te);const $e=`${W}-${Ae.name}-${Date.now()}-${ce}`;let _e=null;const Y=Ae.type.startsWith("image/")?URL.createObjectURL(Ae):null;try{const ee=await Vt.uploadFile(Ae,ae=>{if(y(W,Ce=>(Ce.set($e,ae),Ce)),ae.fileId&&!_e){_e=ae.fileId,h.current.set(ae.fileId,W),x.current.add(ae.fileId),Y&&xo(ae.fileId,Y);const Ce={file_id:ae.fileId,filename:Ae.name,mime_type:Ae.type||"application/octet-stream",file_size:Ae.size,processing_status:ae.status==="uploading"?"uploading":ae.status==="processing"?"processing":ae.status==="completed"?"completed":void 0};z(`[FileUpload] Adding file ${ae.fileId} to conversation ${W} immediately (status: ${Ce.processing_status})`),I(W,Ce)}},void 0,ue,ve).catch(ae=>{if(ae.message&&ae.message.includes("was deleted")){_e&&h.current.delete(_e);const Ce=ae.message.match(/File\s+([\w-]+)\s+was deleted/);return Ce&&Ce[1]&&h.current.delete(Ce[1]),z(`File ${Ae.name} was deleted during upload`),null}throw ae});if(ee){const ae=ge.getState().conversations.find(me=>me.id===W),Ce=((pe=ae==null?void 0:ae.attachedFiles)==null?void 0:pe.some(me=>me.file_id===ee.file_id))??!1;if(x.current.has(ee.file_id)&&!Ce){z(`[FileUpload] Skipping final update for deleted file ${ee.file_id}`),h.current.delete(ee.file_id),x.current.delete(ee.file_id),y(W,me=>(me.delete($e),me));continue}h.current.set(ee.file_id,W),x.current.add(ee.file_id),z(`[FileUpload] Updating file ${ee.file_id} in conversation ${W} with final status`),I(W,ee),ee.processing_status==="completed"||ee.processing_status==="failed"||ee.processing_status==="error"?y(W,me=>(me.delete($e),me)):y(W,me=>{const nt=me.get($e);return nt&&me.set($e,{...nt,progress:90,status:"processing",fileId:ee.file_id}),me}),A(W,me=>{if(new Set(me.map(et=>et.file_id)).has(ee.file_id))return me;const Le=[...me,ee];return z(`[FileUpload] Updated uploadedFiles for ${W}: ${Le.length} files`,Le),Le})}else ye(`Upload completed for ${Ae.name} but uploadedAttachment is null`),y(W,ae=>(ae.delete($e),ae))}catch(ee){const ae=gf(ee);if(ee instanceof DOMException&&ee.name==="AbortError"||Te.signal.aborted){z(`Upload cancelled for ${Ae.name}`),_e?h.current.delete(_e):Y&&URL.revokeObjectURL(Y),y(W,me=>(me.delete($e),me));continue}if(ae.includes("was deleted")){z(`File ${Ae.name} was deleted during upload`),_e&&h.current.delete(_e);const me=ae.match(/File\s+([\w-]+)\s+was deleted/);me&&me[1]&&h.current.delete(me[1]),y(W,nt=>(nt.delete($e),nt));continue}k.current?(xe(`Failed to upload file ${Ae.name}:`,ee),xe(`File type: ${Ae.type}, File name: ${Ae.name}`),r==null||r(ae||`Failed to upload ${Ae.name}`)):ye(`Upload error for ${Ae.name} (component unmounted):`,ae),_e?h.current.delete(_e):Y&&URL.revokeObjectURL(Y);const Ce=$e,Se=W;setTimeout(()=>{y(Se,me=>(me.delete(Ce),me))},5e3)}finally{b.current.delete(Ae.name)}}},[I,t,o,r,c,A,y]),X=m.useCallback(T=>{T.preventDefault(),T.stopPropagation(),l||u(!0)},[l]),j=m.useCallback(T=>{T.preventDefault(),T.stopPropagation(),u(!1)},[]),L=m.useCallback(T=>{if(T.preventDefault(),T.stopPropagation(),u(!1),l)return;const Q=T.dataTransfer.files;U(Q)},[l,U]),B=m.useCallback(T=>{const Q=T.target.files;U(Q),g.current&&(g.current.value="")},[U]),C=m.useCallback(()=>{!l&&g.current&&g.current.click()},[l]),H=m.useCallback(T=>{l||(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),C())},[l,C]),q=M.length>0,J=m.useMemo(()=>{const T=new Map;return _.forEach(Q=>{T.set(Q.id,Q.title||c("chatInterface.newChatTitle"))}),T},[_,c]),K=m.useMemo(()=>{const T=[];return Qt.forEach((Q,R)=>{R!==t&&Q.size>0&&T.push({conversationId:R,uploads:Array.from(Q.entries()).map(([W,ne])=>({key:W,progress:ne}))})}),T},[t,f]),V=(T,Q)=>{const R=T.status==="uploading"?c("fileUpload.uploadingStatus"):T.status==="processing"?c("fileUpload.processingStatus"):T.status==="completed"?c("fileUpload.completedStatus"):void 0;return n.jsx(Bs,{filename:T.filename,fileId:T.fileId,status:T.status,statusText:R,errorMessage:T.error||(T.status==="error"?c("fileUpload.processingFailedMessage"):void 0)},Q)},oe=M.length>0?n.jsx("div",{className:"w-full max-w-full overflow-hidden flex flex-wrap gap-2",role:"status","aria-live":"polite",children:M.map(([T,Q])=>V(Q,T))}):null;return n.jsxs("div",{className:"w-full max-w-full overflow-hidden space-y-2",children:[q&&oe,!q&&!l&&n.jsxs("button",{type:"button",onClick:C,onKeyDown:H,onDragOver:X,onDragLeave:j,onDrop:L,disabled:l,className:`
350
+ group relative w-full max-w-full rounded-lg border p-4 transition-all duration-200 text-left overflow-hidden
351
+ ${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]"}
352
+ `,"aria-label":c(l?"fileUpload.disabledAriaLabel":"fileUpload.enabledAriaLabel"),children:[n.jsx("input",{ref:g,type:"file",multiple:!0,onChange:B,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"}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.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:n.jsx(_d,{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"}`})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.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")}),n.jsx("p",{className:"text-xs text-gray-400 dark:text-[#8e8ea0] mt-0.5",children:c("fileUpload.fileTypesAndLimit",{count:o})})]})]})]}),K.length>0&&n.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:[n.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-[#8e8ea0] px-1",children:c("fileUpload.otherConversationsLabel")}),K.map(({conversationId:T,uploads:Q})=>n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("div",{className:"text-[11px] font-medium text-gray-400 dark:text-[#6b6f7a] px-1",children:J.get(T)||"Conversation"}),n.jsx("div",{className:"flex flex-wrap gap-2",children:Q.map(({key:R,progress:W})=>V(W,R))})]},T))]})]})}const mi={"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"},pa=4,js=3,xf=0,bf=0,xa=2;function yf(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 s=["capabilities","features"],a=["autocomplete","supportsAutocomplete","autocomplete_supported"];for(const i of s){const o=e[i];if(!o||typeof o!="object")continue;const l=o;for(const c of a)if(typeof l[c]=="boolean")return l[c]}return null}function wf(t){if(!t)return"bin";if(mi[t])return mi[t];const e=t.split("/");return e.length===2&&e[1]?e[1]:"bin"}function kf(t){return t.replace(/[^a-zA-Z0-9._-]/g,"_").replace(/_+/g,"_")||"pasted-file"}function vf(t){const e=t.lastIndexOf(".");return e===-1||e===t.length-1?null:t.slice(e+1).toLowerCase()}function Sf(t){const e=t.lastIndexOf(".");return e===-1?t:t.slice(0,e)}function ba(t){return!t||t==="processing"||t==="uploading"}function jf(t,e){const r=Date.now(),s=t.name&&t.name.trim().length>0?t.name.trim():"pasted-file",a=kf(Sf(s)),o=vf(s)||wf(t.type),l=`${a}-${r}-${e}.${o}`;return new File([t],l,{type:t.type||"application/octet-stream"})}function hi({onSend:t,disabled:e=!1,placeholder:r=Bi(),autoFocusEnabled:s=!0,suppressMobileAutoFocus:a=!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 pn;const{t:h}=Ee(),[x,b]=m.useState(""),[k,S]=m.useState(!1),[E,_]=m.useState(!1),[v,M]=m.useState(!1),[F,y]=m.useState(!1),[A,N]=m.useState([]),[I,$]=m.useState({}),[U,X]=m.useState(new Map),[j,L]=m.useState(!1),[B,C]=m.useState(!1),[H,q]=m.useState(null),[J,K]=m.useState(null),[V,oe]=m.useState(null),[T,Q]=m.useState({isOpen:!1,fileId:"",filename:"",isDeleting:!1}),R=m.useRef(null),W=m.useRef(null),ne=m.useRef(null),fe=m.useRef(null),D=m.useRef(null),G=m.useRef(new Set),se=m.useRef(""),ve=m.useRef(!1),ue=m.useRef(0),pe=m.useRef(null),{settings:ce,updateSettings:Ae}=qs(),{theme:Te,isDark:$e}=mr(),_e=Te.mode==="dark"?"dark":Te.mode==="light"?"light":"",Y=$e?"dark":"light";Hr(W,{enabled:v,onEscape:()=>M(!1)});const ee=m.useCallback((w,O)=>{w&&$(de=>{if(de[w]===O)return de;const ke={...de};return O?ke[w]=!0:delete ke[w],ke})},[]),[ae,Ce]=m.useState(0),[Se,me]=m.useState(!1),[nt,Le]=m.useState(0),[et,Fe]=m.useState(()=>({top:pa+js,bottom:Math.max(pa-js,0)})),[St,hr]=m.useState(null),Tt=Sr(),Xe=st()&&!Tt,Ht=at(w=>w.showLoginPrompt),{createConversation:jt,currentConversationId:je,conversations:dt,isLoading:ut,syncConversationFiles:qt,stopStreaming:gr,removeFileFromConversation:be}=ge(),Z=dt.find(w=>w.id===je),De=Z?Z.messages.filter(w=>!(w.role==="assistant"&&w.isStreaming)).length:0,Me=dt.reduce((w,O)=>w+O.messages.filter(de=>!(de.role==="assistant"&&de.isStreaming)).length,0),Ye=!!Z&&le.maxMessagesPerConversation!==null&&De>=le.maxMessagesPerConversation,tt=le.maxTotalMessages!==null&&Me>=le.maxTotalMessages,rr=m.useCallback(()=>{Ce(w=>w+1)},[]),jr=Ic(),ft=Ec(),{isListening:bt,isSupported:yt,startListening:Cr,stopListening:Ar,error:Mt}=of(w=>{b(O=>{const de=O.length>0&&!/\s$/.test(O)?" ":"",ke=(O+de+w).slice(0,le.maxMessageLength);return se.current=ke,ke})},rr,{silenceTimeoutMs:jr,language:ft||void 0}),sr=Cc(),Wt=Ac(),ar=Wt&&yt,Ct=jc(),Kr=Hi(),Gr=yf(Z==null?void 0:Z.adapterInfo),{skills:Ft,isLoading:Rt,selectedSkill:qe,selectSkill:pr,clearSkill:nr}=d,Xr=(Z==null?void 0:Z.adapterName)||null,{suggestions:$t,selectedIndex:mt,setSelectedIndex:Zs,selectNext:Yr,selectPrevious:Qr,clearSuggestions:wt,focusInputAfterSelection:Jr,suppressUntilQueryChange:Zr}=df(x,{enabled:Kr&&!bt,apiUrl:Z==null?void 0:Z.apiUrl,adapterName:Xr,sessionId:Z==null?void 0:Z.sessionId,adapterSupportsAutocomplete:Gr,skill:(qe==null?void 0:qe.name)||null,inputRef:R}),Pt=$t.length>0,es=!bt,Nr=es&&Pt&&!Se,ir=x.startsWith("/")?x.slice(1):"",Ir=ir.toLowerCase().replace(/-/g," "),rt=Ir?Ft.filter(w=>w.name.replace(/-/g," ").toLowerCase().includes(Ir)||w.description.toLowerCase().includes(Ir)):Ft,ts=rt.length>0?Math.min(nt,rt.length-1):0,ht=rt[ts]??null,P=(ht==null?void 0:ht.name.replace(/-/g," "))??"",we=Se&&ht&&x.startsWith("/")&&P.toLowerCase().startsWith(ir.toLowerCase())&&P.length>ir.length?P.slice(ir.length):null,te=mt>=0?mt:0,Ie=Pt?$t[te]:null,it=m.useMemo(()=>{if(!Ie)return null;const w=Ie.text||"";if(!x)return w;const O=x;return w.toLowerCase().startsWith(O.toLowerCase())&&w.length>O.length?w.slice(O.length):null},[Ie,x]),Dt=we??it,Er=x.trim().length===0&&!Dt,Fo=m.useCallback(w=>{if(!x)return n.jsx("span",{className:"line-clamp-1 text-current",children:w});if(!w.toLowerCase().startsWith(x.toLowerCase()))return n.jsx("span",{className:"line-clamp-1 text-current",children:w});const O=w.slice(0,x.length),de=w.slice(x.length);return n.jsxs("span",{className:"line-clamp-1",children:[n.jsx("span",{className:"text-gray-500 dark:text-[#8e8ea0]",children:O}),n.jsx("span",{className:"font-semibold text-[#353740] dark:text-[#ececf1]",children:de})]})},[x]),tn=m.useCallback(w=>{var O;pr(w),me(!1),b(""),wt(),Le(0),(O=R.current)==null||O.focus()},[wt,pr]),Ro=m.useCallback(()=>{var w;b("/"),me(!0),Le(0),(w=R.current)==null||w.focus()},[]),rn=m.useCallback(()=>{var w;me(!1),b(""),Le(0),(w=R.current)==null||w.focus()},[]),Kt=m.useCallback(()=>{const w=R.current;if(!w||typeof window>"u")return;const O=Ne=>{const We=Ne+js,Qe=Math.max(Ne-js,0);w.style.paddingTop=`${We}px`,w.style.paddingBottom=`${Qe}px`,Fe({top:We,bottom:Qe})},de=window.getComputedStyle(w),ke=parseFloat(de.lineHeight||"0");!Number.isNaN(ke)&&ke>0?hr(Ne=>Ne===ke?Ne:ke):hr(Ne=>Ne===null?Ne:null),O(pa)},[]),$o=()=>{const w=R.current;return w?w.selectionStart===w.selectionEnd&&w.selectionStart===x.length:!1},sn=(Z==null?void 0:Z.attachedFiles)||[],xr=je?sn:A,Po=dt.reduce((w,O)=>{var de;return w+(((de=O.attachedFiles)==null?void 0:de.length)||0)},0),an=le.maxFilesPerConversation!==null&&le.maxFilesPerConversation>0&&sn.length>=le.maxFilesPerConversation,nn=le.maxTotalFiles!==null&&Po>=le.maxTotalFiles,Lr=((pn=Z==null?void 0:Z.adapterInfo)==null?void 0:pn.isFileSupported)??!1,ea=xr.some(w=>w.processing_status?w.processing_status!=="completed"&&w.processing_status!=="error"&&w.processing_status!=="failed":!0),gt=je?!!I[je]:!1,rs=Object.values(I).some(Boolean),ta=x.trim().length>0,ra=Ye||tt,Oe=e||ea||gt||ra,on=Ct&&Lr,ss=an||nn,_r=!on||e||gt||ra||ss,ln=!F&&(gt||U.size>0),cn=F||gt&&U.size===0;m.useLayoutEffect(()=>{if(R.current){const w=R.current,O=120;if(x.length===0){w.style.height="32px",w.style.overflowY="hidden",Kt();return}w.style.height="auto";const de=w.scrollHeight;w.style.height=`${Math.min(de,O)}px`,w.style.overflowY=de>O?"auto":"hidden",Kt()}},[x,Kt]),m.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const w=R.current;if(!w)return;const O=new ResizeObserver(()=>{Kt()});return O.observe(w),()=>{O.disconnect()}},[Kt]);const dn=()=>{const w=document.activeElement;return w&&w.tagName==="TEXTAREA"},as=m.useCallback(()=>typeof window>"u"?!1:!!(i&&!window.matchMedia("(min-width: 1024px)").matches||a&&window.matchMedia("(max-width: 767px)").matches),[i,a]),ns=m.useCallback(()=>{var w;(w=R.current)==null||w.focus({preventScroll:i})},[i]);m.useEffect(()=>{as()||s&&!Oe&&R.current&&!dn()&&ns()},[s,Oe,as,ns]);const un=!!qe||Ft.length>0&&x.length===0&&!Oe;m.useEffect(()=>{if(typeof window>"u"||!window.matchMedia("(max-width: 767px)").matches||!un||document.activeElement!==R.current)return;const w=window.requestAnimationFrame(()=>{const O=R.current;!O||document.activeElement!==O||(O.blur(),O.focus({preventScroll:!0}))});return()=>window.cancelAnimationFrame(w)},[un]);const sa=m.useRef(ut);m.useEffect(()=>{if(as()){sa.current=ut;return}s&&sa.current&&!ut&&!Oe&&R.current&&setTimeout(()=>{R.current&&!dn()&&ns()},100),sa.current=ut},[s,ut,Oe,as,ns]),m.useEffect(()=>{if(!ar||(ae>ue.current&&(ve.current=!0,ue.current=ae),!ve.current||ae===0))return;const w=se.current.trim(),O=ge.getState();if(z("[MessageInput] Auto-send check after voice completion:",{hasMessage:!!w,isInputDisabled:Oe,isComposing:k,isLoading:O.isLoading}),ve.current=!1,!w)return;if(Oe||k){z("[MessageInput] Auto-send skipped because input is currently disabled or composing");return}const de=O.conversations.find(Qe=>Qe.id===O.currentConversationId),Ne=((de==null?void 0:de.attachedFiles)||[]).map(Qe=>Qe.file_id),We=qe==null?void 0:qe.name;z("[MessageInput] Auto-sending voice message immediately:",w),t(w,Ne.length>0?Ne:void 0,void 0,We),We&&nr(),setTimeout(()=>{me(!1)},0),wt(),setTimeout(()=>{b("")},0),se.current="",R.current&&(R.current.style.height="auto",R.current.style.overflowY="hidden",Kt())},[ar,ae,Oe,k,t,qe,nr,Kt,wt]),m.useEffect(()=>{gt&&F&&setTimeout(()=>{y(!1)},0)},[gt,F]);const is=m.useCallback((w,O)=>{setTimeout(()=>{var Ke,Gt;let de=ge.getState(),ke=O||de.currentConversationId;if(ke||(ke=jt(),de=ge.getState(),ke=de.currentConversationId||ke),!ke){xe("[MessageInput] Unable to sync files: conversation ID missing");return}const Ne=((Gt=(Ke=de.conversations.find(ot=>ot.id===ke))==null?void 0:Ke.attachedFiles)==null?void 0:Gt.map(ot=>ot.file_id))||[],We=new Set([...Ne,...w.map(ot=>ot.file_id)]),Qe=`${ke}-`,ze=[];G.current.forEach((ot,Xt)=>{Xt.startsWith(Qe)&&!We.has(Xt.slice(Qe.length))&&ze.push(Xt)}),ze.forEach(ot=>G.current.delete(ot)),w.forEach(ot=>{const Xt=`${ke}-${ot.file_id}`;G.current.has(Xt)||(G.current.add(Xt),z(`[MessageInput] Adding file ${ot.file_id} to conversation ${ke}`),de.addFileToConversation(ke,ot))})},0)},[jt]);m.useEffect(()=>{if(je!==pe.current)if(pe.current=je||null,je&&Z){const w=Z.attachedFiles||[];setTimeout(()=>{N(w.map(O=>({...O})))},0)}else setTimeout(()=>{N([])},0)},[je,Z]),m.useEffect(()=>{if(je&&Z){const w=Z.attachedFiles||[];w.length>0?setTimeout(()=>{N(O=>{const de=new Set(O.map(Ne=>Ne.file_id)),ke=w.filter(Ne=>!de.has(Ne.file_id));return ke.length>0?(z(`[MessageInput] Syncing ${ke.length} missing files from conversation to UI`),[...O,...ke]):O})},0):w.length===0&&A.length>0&&setTimeout(()=>{N([])},0)}},[je,Z,dt,A.length]);const aa=m.useRef(null),na=m.useRef(""),os=(Z==null?void 0:Z.attachedFiles)||[],ls=os.length>0?`${os.length}:${os.map(w=>w.file_id).join("|")}`:"",fn=os.some(w=>ba(w.processing_status));m.useEffect(()=>{if(!je||!(Z!=null&&Z.adapterName))return;const w=ls!=="";if(w&&(aa.current!==je||na.current!==ls)?(z(`[MessageInput] Syncing files for conversation ${je}...`),aa.current=je,na.current=ls,qt(je).catch(ke=>{xe("[MessageInput] Failed to sync conversation files:",ke)})):w||(aa.current=je,na.current=""),!fn)return;z("[MessageInput] Files still processing, starting poll...");const de=setInterval(async()=>{const Ne=ge.getState().conversations.find(ze=>ze.id===je);if(!Ne){clearInterval(de);return}if((Ne.attachedFiles||[]).filter(ze=>ba(ze.processing_status)).length===0){z("[MessageInput] All files completed processing, stopping poll"),clearInterval(de);return}try{await qt(je)}catch(ze){xe("[MessageInput] Failed to poll file status:",ze)}},3e3);return()=>{clearInterval(de)}},[je,Z==null?void 0:Z.adapterName,ls,fn,qt]),m.useEffect(()=>{setTimeout(()=>{$(w=>{const O=new Set(dt.map(Ne=>Ne.id));let de=!1;const ke={...w};return Object.keys(ke).forEach(Ne=>{O.has(Ne)||(delete ke[Ne],de=!0)}),de?ke:w})},0)},[dt]);const mn=w=>{if(w.preventDefault(),ta&&!Oe&&!k){bt&&Ar();const de=((Z==null?void 0:Z.attachedFiles)||[]).map(Ne=>Ne.file_id),ke=qe==null?void 0:qe.name;t(x.trim(),de.length>0?de:void 0,void 0,ke),ke&&nr(),me(!1),Pr("messageSent",ce.soundEnabled),b(""),se.current="",N([]),y(!1),R.current&&(R.current.style.height="auto",R.current.style.overflowY="hidden",Kt())}},cs=m.useCallback(w=>{if(!w||w.length===0)return;const O=w.length===1?h("messageInput.uploadSuccess.single",{filename:w[0].filename}):h("messageInput.uploadSuccess.multiple",{count:w.length});Pr("success",ce.soundEnabled),K(O),setTimeout(()=>{K(null)},6e3)},[ce.soundEnabled,h]),Do=m.useCallback((w,O)=>{z(`[MessageInput] handleFilesSelected called with ${O.length} files for conversation ${w}:`,O),w&&(w===je&&N(O),is(O,w))},[je,is]),Uo=m.useCallback((w,O)=>{w===je&&cs(O)},[je,cs]),Oo=m.useCallback(w=>{Q({isOpen:!0,fileId:w.file_id,filename:w.filename,isDeleting:!1})},[]),zo=m.useCallback(()=>{Q(w=>w.isDeleting?w:{isOpen:!1,fileId:"",filename:"",isDeleting:!1})},[]),Bo=m.useCallback(async()=>{if(!(!je||!T.fileId)){Q(w=>({...w,isDeleting:!0}));try{await be(je,T.fileId),N(w=>w.filter(O=>O.file_id!==T.fileId)),Q({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}catch(w){const O=w instanceof Error?w.message:h("messageInput.fileRemoveFailed");xe("[MessageInput] Failed to remove file:",w),oe(O),Q({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}}},[je,T.fileId,be,h]),hn=m.useCallback(w=>w.replace(/\s+/g," ").trim(),[]),ds=m.useCallback(w=>{const O=hn(w);b(O),wt(),Zr(O),Jr(O)},[wt,Jr,hn,Zr]),ia=m.useCallback(w=>{if(w<0)return;const O=$t[w]||$t[0];O&&ds(O.text)},[$t,ds]),Vo=w=>{if(Se){if(w.key==="ArrowDown"){w.preventDefault(),Le(O=>rt.length===0?0:(O+1)%rt.length);return}if(w.key==="ArrowUp"){w.preventDefault(),Le(O=>rt.length===0?0:(O-1+rt.length)%rt.length);return}if(w.key==="Home"){w.preventDefault(),Le(0);return}if(w.key==="End"){w.preventDefault(),Le(Math.max(rt.length-1,0));return}if((w.key==="Enter"&&!w.shiftKey||w.key==="Tab")&&ht){w.preventDefault(),tn(ht);return}if(w.key==="Escape"){w.preventDefault(),rn();return}}if(Pt&&es){if(w.key==="ArrowDown"){w.preventDefault(),Yr();return}if(w.key==="ArrowUp"){w.preventDefault(),Qr();return}if(w.key==="Tab"){w.preventDefault();const O=mt>=0?mt:0;ia(O);return}if(w.key==="ArrowRight"&&$o()){if(it&&Ie){w.preventDefault(),ds(Ie.text);return}if(mt>=0){w.preventDefault(),ia(mt);return}}if(w.key==="Enter"&&mt>=0){w.preventDefault(),ia(mt);return}if(w.key==="Escape"){w.preventDefault(),wt();return}}w.key==="Enter"&&!w.shiftKey&&!k&&(w.preventDefault(),mn(w))},Ho=()=>{bt?Ar():(wt(),Cr())},qo=()=>{const w=!ce.voiceEnabled;Ae({voiceEnabled:w}),w&&er.enableAudio()},Wo=m.useCallback(async w=>{if(!Ct||!E||!Lr||Oe)return;const O=w.clipboardData;if(!O||!O.items)return;const ke=Array.from(O.items).filter(ze=>ze.kind==="file");if(ke.length===0)return;const Ne=[];if(ke.forEach((ze,Ke)=>{const Gt=ze.getAsFile();Gt&&Ne.push(jf(Gt,Ke))}),Ne.length===0)return;w.preventDefault(),q(null),K(null),y(!1);let We=null;const Qe=new Set;try{const ze=ge.getState(),Ke=ze.conversations.find(Yt=>Yt.id===ze.currentConversationId);if(((Ke==null?void 0:Ke.attachedFiles)||[]).length+Ne.length>le.maxFilesPerConversation)throw Xe&&at.getState().openLoginPrompt(h("fileUpload.maxFilesGuestLimitMessage",{count:le.maxFilesPerConversation})),new Error(h("fileUpload.maxFilesPerConversationError",{count:le.maxFilesPerConversation}));if(le.maxTotalFiles!==null&&ze.conversations.reduce((At,Tr)=>{var lr;return At+(((lr=Tr.attachedFiles)==null?void 0:lr.length)||0)},0)+Ne.length>le.maxTotalFiles)throw Xe&&at.getState().openLoginPrompt(h("fileUpload.maxTotalFilesGuestLimitMessage",{count:le.maxTotalFiles})),new Error(h("fileUpload.maxTotalFilesError",{count:le.maxTotalFiles}));if(!Ke)throw new Error(h("messageInput.conversationNotFoundShort"));if(!Ke.adapterName)throw new Error(h("fileUpload.adapterNotConfigured"));const Xt=lt(Ke.apiUrl),Xo=Ke.adapterName;We=Ke.id,ee(We,!0);const oa=[];for(let Yt=0;Yt<Ne.length;Yt++){const At=Ne[Yt],Tr=At.name||`Clipboard file ${Yt+1}`,lr=`${Tr}-${Date.now()}-${Yt}`,Mr=At.type.startsWith("image/")?URL.createObjectURL(At):null;Mr&&Qe.add(Mr);let xn=null;X(Ve=>{const Ot=new Map(Ve);return Ot.set(lr,{filename:Tr,progress:0,status:"uploading"}),Ot});const Yo=Ve=>{Ve.fileId&&!xn&&(xn=Ve.fileId,Mr&&(xo(Ve.fileId,Mr),Qe.delete(Mr))),X(Ot=>{const fs=new Map(Ot),bn=fs.get(lr);return bn&&fs.set(lr,{...bn,filename:Tr,progress:Ve.progress,status:Ve.status,fileId:Ve.fileId}),fs})},Qo=()=>{X(Ve=>{const Ot=new Map(Ve);return Ot.delete(lr),Ot})};z(`[MessageInput] Pasting file: ${At.name}, type: ${At.type||"unknown"}, size: ${At.size}`);const us=await Vt.uploadFile(At,Ve=>{z(`[MessageInput] Paste upload progress for ${At.name}: ${Ve.progress}% - ${Ve.status}`),Yo(Ve)},void 0,Xt,Xo);oa.push(us),We&&We===je&&N(Ve=>Ve.some(Ot=>Ot.file_id===us.file_id)?Ve:[...Ve,us]),is([us],We),Qo()}oa.length>0&&cs(oa)}catch(ze){const Ke=ze instanceof Error?ze.message:"Failed to paste file";xe("[MessageInput] Paste error:",ze),Pr("error",ce.soundEnabled),q(Ke),Ke.toLowerCase().includes("maximum")&&oe(Ke),setTimeout(()=>{q(null)},5e3),X(new Map),Qe.forEach(Gt=>URL.revokeObjectURL(Gt))}finally{ee(We,!1)}},[je,E,Lr,Xe,Oe,ee,ce.soundEnabled,cs,is,Ct,h]),gn=bc(Z==null?void 0:Z.adapterName);let Ut;tt?Ut=Xe?h("messageInput.placeholder.guestLimitTotal",{count:le.maxTotalMessages}):h("messageInput.placeholder.workspaceLimitTotal",{count:le.maxTotalMessages}):Ye?Ut=Xe?h("messageInput.placeholder.guestLimitPerConversation",{count:le.maxMessagesPerConversation}):h("messageInput.placeholder.conversationLimitReached",{count:le.maxMessagesPerConversation}):ea||gt?Ut=h("messageInput.placeholder.filesUploading"):gn?Ut=gn:on?Ut=h("messageInput.placeholder.messageOrbit"):Ut=r;const or=[];tt&&le.maxTotalMessages!==null&&(Xe?Ht&&or.push(h("messageInput.limitWarning.guestTotalMessages",{count:le.maxTotalMessages})):or.push(h("messageInput.limitWarning.workspaceTotalMessages",{count:le.maxTotalMessages}))),Ye&&le.maxMessagesPerConversation!==null&&(Xe?Ht&&or.push(h("messageInput.limitWarning.guestPerConversation",{count:le.maxMessagesPerConversation})):or.push(h("messageInput.limitWarning.conversationLimitReached",{count:le.maxMessagesPerConversation}))),V&&or.push(V),m.useEffect(()=>{!Wt||!Mt||Pr("error",ce.soundEnabled)},[Wt,ce.soundEnabled,Mt]),m.useEffect(()=>{if(!V)return;const w=setTimeout(()=>oe(null),5e3);return()=>clearTimeout(w)},[V]),m.useEffect(()=>{if(!F)return;const w=O=>{O.key!=="Escape"||O.defaultPrevented||y(!1)};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[F]),m.useEffect(()=>{var w;(F||gt||U.size>0||rs)&&((w=ne.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[F,gt,U.size,rs]),m.useEffect(()=>{var w;Nr&&((w=fe.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[Nr]),m.useEffect(()=>{var w;Se&&((w=D.current)==null||w.scrollIntoView({behavior:"smooth",block:"end"}))},[Se,rt.length]);const Ko=l,Go=o?"flex justify-center":"";return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:`bg-transparent px-2 py-1.5 md:bg-transparent md:px-0 md:pt-4 md:pb-2 md:dark:bg-transparent sm:px-4 ${Go}`,children:n.jsxs("div",{className:`mx-auto w-full ${Ko}`,children:[Mt&&Wt&&n.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:[n.jsx(La,{className:"h-4 w-4 mt-0.5 flex-shrink-0 text-red-500 dark:text-red-400"}),n.jsx("span",{className:"text-sm text-red-700 dark:text-red-300",children:Mt})]}),H&&n.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:[n.jsx(La,{className:"h-4 w-4 mt-0.5 flex-shrink-0 text-red-500 dark:text-red-400"}),n.jsx("span",{className:"text-sm text-red-700 dark:text-red-300",children:H})]}),J&&n.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:[n.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:n.jsx(ad,{className:"h-3.5 w-3.5 text-emerald-600 dark:text-emerald-400"})}),n.jsx("span",{className:"text-sm text-[#353740] dark:text-[#ececf1]",children:J})]}),or.length>0&&n.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:[n.jsx(Xa,{className:"h-4 w-4 mt-0.5 flex-shrink-0 text-amber-500 dark:text-amber-400"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("ul",{className:"list-none space-y-0.5",children:or.map((w,O)=>n.jsx("li",{className:"text-sm text-amber-800 dark:text-amber-200",children:w},`${w}-${O}`))}),Xe&&(ra||ss)&&Ht&&n.jsx("button",{type:"button",onClick:()=>at.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")})]})]}),n.jsxs("div",{className:"relative w-full",children:[n.jsxs("form",{onSubmit:mn,className:"flex w-full flex-col gap-2 md:gap-3",children:[n.jsxs("div",{className:`grid grid-cols-1 items-center gap-2 md:flex md:flex-row md:flex-nowrap md:gap-2 rounded-xl md:rounded-lg border px-2.5 py-2 md:px-4 md:py-3 shadow-sm transition-all ${E?"border-gray-400 shadow-md dark:border-[#3a3a3a] dark:shadow-lg":"border-gray-300 dark:border-[#242424]"} bg-gray-50 dark:bg-[#111111]`,children:[n.jsxs("div",{className:"col-span-full flex w-full shrink-0 basis-full items-center justify-between gap-2 md:contents",children:[qe&&n.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:[n.jsx(Ga,{className:"h-3.5 w-3.5 shrink-0 text-gray-500 dark:text-gray-400","aria-hidden":"true"}),n.jsx("span",{className:"min-w-0 truncate font-medium capitalize",children:qe.name.replace(/-/g," ")}),n.jsx("button",{type:"button",onClick:()=>{var w;nr(),(w=R.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:n.jsx(Ge,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),!qe&&Ft.length>0&&n.jsxs("button",{type:"button",onClick:Ro,disabled:x.length>0||Oe,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 disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:bg-white disabled:hover:text-gray-600 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 dark:disabled:hover:bg-[#1a1a1a] dark:disabled:hover:text-gray-300 md:self-center","aria-label":h("messageInput.skillsHint.ariaLabel"),title:h("messageInput.skillsHint.title"),children:[n.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")]}),n.jsx(Da,{availableModels:u,defaultModel:f,selectedModel:p,onSelect:w=>g==null?void 0:g(w),wrapperClassName:"relative ml-auto block md:hidden",maxWidthClass:"max-w-[150px]"})]}),n.jsxs("div",{className:"relative flex-1 w-full min-w-0 md:translate-y-0.5",children:[Er&&Ut&&n.jsx("div",{className:"pointer-events-none absolute inset-0 truncate whitespace-nowrap text-base md:text-sm text-gray-500 dark:text-[#8e8ea0]",style:{paddingTop:Math.max(et.top-xf,0),paddingBottom:et.bottom,paddingLeft:`${xa}px`,paddingRight:0,lineHeight:St?`${St}px`:void 0},"aria-hidden":"true",children:Ut}),Dt&&E&&n.jsxs("div",{className:"pointer-events-none absolute inset-0 whitespace-pre-wrap text-base md:text-sm text-gray-400 dark:text-[#8e8ea0]",style:{paddingTop:Math.max(et.top-bf,0),paddingBottom:et.bottom,paddingLeft:`${xa}px`,paddingRight:0,lineHeight:St?`${St}px`:void 0},"aria-hidden":"true",children:[n.jsx("span",{className:"invisible",children:x}),n.jsx("span",{children:Dt})]}),n.jsx("textarea",{ref:R,"aria-label":h("messageInput.textarea.ariaLabel"),value:x,onChange:w=>{const O=w.target.value;b(O),O.startsWith("/")&&Le(0),me(O.startsWith("/")&&Ft.length>0)},onKeyDown:Vo,onPaste:Wo,onCompositionStart:()=>S(!0),onCompositionEnd:()=>S(!1),onFocus:()=>_(!0),onBlur:()=>_(!1),placeholder:Ut,disabled:Oe,rows:1,maxLength:le.maxMessageLength,className:"relative z-10 flex-1 w-full min-w-0 resize-none bg-transparent py-0 text-base md:text-sm text-[#353740] placeholder-transparent focus:outline-none dark:text-[#ececf1] dark:placeholder-transparent",style:{minHeight:"24px",maxHeight:"120px",paddingTop:`${et.top}px`,paddingBottom:`${et.bottom}px`,paddingLeft:`${xa}px`,paddingRight:0,border:"none",outline:"none",boxShadow:"none",WebkitAppearance:"none",MozAppearance:"none",appearance:"none",caretColor:x.trim()||E?"inherit":"transparent"}})]}),n.jsxs("div",{className:"flex w-full flex-shrink-0 items-center justify-between gap-2 md:w-auto md:justify-end",children:[n.jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[o&&!Ct&&n.jsx("div",{className:"hidden md:block h-8 w-8 shrink-0","aria-hidden":"true"}),Ct&&n.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),_r||y(!F)},disabled:_r,onMouseEnter:()=>L(!0),onMouseLeave:()=>L(!1),className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${F||xr.length>0?"bg-gray-200 text-[#353740] dark:bg-[#565869] dark:text-[#ececf1]":_r?"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:Lr?ss&&an&&le.maxFilesPerConversation!==null?h("messageInput.fileUpload.titleLimitPerConversation",{count:le.maxFilesPerConversation}):ss&&nn&&le.maxTotalFiles!==null?h("messageInput.fileUpload.titleLimitWorkspace",{count:le.maxTotalFiles}):Oe?h("messageInput.fileUpload.titleUploading"):xr.length>0?h("messageInput.fileUpload.titleAttached",{count:xr.length}):h("messageInput.fileUpload.attachAriaLabel"):h("messageInput.fileUpload.titleNotSupported"),"aria-label":h("messageInput.fileUpload.attachAriaLabel"),children:_r&&j?n.jsx(Ge,{className:"h-4 w-4"}):n.jsx(kd,{className:"h-4 w-4"})}),x.length>0&&n.jsx("div",{className:"hidden md:block px-2 text-xs text-gray-500 dark:text-[#bfc2cd] md:min-w-[72px] md:text-right",children:n.jsxs("span",{className:x.length>=le.maxMessageLength?"text-red-600 font-semibold":"",children:[x.length,"/",le.maxMessageLength]})})]}),n.jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[n.jsx(Da,{availableModels:u,defaultModel:f,selectedModel:p,onSelect:w=>g==null?void 0:g(w),wrapperClassName:"relative hidden md:block",maxWidthClass:"max-w-[220px]"}),(sr||Wt)&&n.jsxs(n.Fragment,{children:[sr&&n.jsx("button",{type:"button",onClick:qo,className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${ce.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:ce.voiceEnabled?h("messageInput.voiceOutput.titleEnabled"):h("messageInput.voiceOutput.titleDisabled"),"aria-label":ce.voiceEnabled?h("messageInput.voiceOutput.ariaLabelEnabled"):h("messageInput.voiceOutput.ariaLabelDisabled"),children:ce.voiceEnabled?n.jsx(Ys,{className:"h-5 w-5"}):n.jsx(Td,{className:"h-5 w-5"})}),ar&&n.jsx("button",{type:"button",onClick:Ho,disabled:Oe,onMouseEnter:()=>C(!0),onMouseLeave:()=>C(!1),className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${bt?"!flex bg-red-100 text-red-600 dark:bg-red-900/40 dark:text-red-300":Oe?"cursor-not-allowed text-gray-300 dark:text-[#6b6f7a]":"text-gray-500 hover:bg-gray-200 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#565869]"}`,title:h(Oe?"messageInput.voiceInput.titleUploading":bt?"messageInput.voiceInput.titleListening":"messageInput.voiceInput.titleDisabled"),"aria-label":h(bt?"messageInput.voiceInput.ariaLabelListening":"messageInput.voiceInput.ariaLabelDisabled"),children:bt||Oe&&B?n.jsx(ro,{className:"h-5 w-5"}):n.jsx(Is,{className:"h-5 w-5"})})]}),c&&n.jsx("button",{type:"button",onClick:()=>M(!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:n.jsx(_a,{className:"h-5 w-5"})}),(ea||gt)&&n.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center",children:n.jsx(Rs,{className:"h-4 w-4 animate-spin text-gray-500 dark:text-[#bfc2cd]"})}),ut?n.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),gr()},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:n.jsx(Id,{className:"h-4 w-4 md:h-3 md:w-3 fill-current"})}):n.jsx("button",{type:"submit",disabled:!ta||Oe||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 ${ta&&!Oe&&!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:n.jsx(Ms,{className:"h-4 w-4"})})]})]})]}),xr.length>0&&n.jsx("div",{className:"flex flex-wrap gap-2",children:xr.map(w=>{const O=ba(w.processing_status),de=w.processing_status==="failed"||w.processing_status==="error",ke=de?"error":O?w.processing_status==="uploading"?"uploading":"processing":"completed",Ne=O?w.processing_status==="uploading"?h("messageInput.attachedFile.uploadingStatus"):h("messageInput.attachedFile.processingStatus"):void 0;return n.jsx(Bs,{filename:w.filename,fileId:w.file_id,status:ke,statusText:Ne,errorMessage:de?w.error_message||h("messageInput.fileProcessingFailedTitle"):void 0,onRemove:()=>{de?(je&&be(je,w.file_id),N(We=>We.filter(Qe=>Qe.file_id!==w.file_id))):Oo(w)},removeTitle:h(de?"messageInput.attachedFile.removeTitleFailed":"messageInput.attachedFile.removeTitleNormal")},w.file_id)})}),Ct&&(Lr||rs)&&n.jsxs("div",{ref:ne,className:`${ln?"":"rounded-lg border border-gray-200/80 bg-white p-2.5 dark:border-[#3c3f4a] dark:bg-[#2a2b32]"} transition-all duration-200 ${!F&&!gt&&U.size===0&&!rs?"hidden":""}`,children:[F&&n.jsxs("div",{className:"mb-2 flex items-center justify-between px-1",children:[n.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-[#8e8ea0] uppercase tracking-wider",children:h("messageInput.uploadPanel.headingAttach")}),n.jsx("button",{type:"button",onClick:()=>y(!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:n.jsx(Ge,{className:"h-3.5 w-3.5"})})]}),!ln&&gt&&!F&&U.size===0&&n.jsx("div",{className:"mb-2 px-1",children:n.jsx("span",{className:"text-xs font-medium text-gray-500 dark:text-[#8e8ea0] uppercase tracking-wider",children:h("messageInput.uploadPanel.headingUploading")})}),U.size>0&&n.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:Array.from(U.entries()).map(([w,O])=>n.jsx(Bs,{filename:O.filename,fileId:O.fileId,status:O.status,statusText:O.status==="uploading"?h("messageInput.uploadProgress.statusUploading"):O.status==="processing"?h("messageInput.uploadProgress.statusProcessing"):O.status==="completed"?h("messageInput.uploadProgress.statusCompleted"):void 0,errorMessage:O.error},w))}),n.jsx("div",{className:`${cn?"block max-h-[40vh] overflow-y-auto":"hidden"}`,"aria-hidden":!cn,children:n.jsx(pf,{conversationId:je,onFilesSelected:Do,onUploadError:w=>{xe("File upload error:",w),oe(w)},onUploadingChange:ee,onUploadSuccess:Uo,maxFiles:le.maxFilesPerConversation,disabled:_r})})]}),n.jsx("div",{className:"h-3 md:h-1",children:ar&&bt&&n.jsxs("span",{className:"flex items-center gap-2 text-sm md:text-xs text-gray-500 dark:text-[#bfc2cd]",children:[n.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")]})})]}),Se&&n.jsx("div",{ref:D,className:"w-full pt-1",children:n.jsx(ko,{skills:Ft,isLoading:Rt,selectedSkill:qe,activeSkillName:ht==null?void 0:ht.name,query:ir,onActiveSkillChange:w=>{const O=rt.findIndex(de=>de.name===w.name);O>=0&&Le(O)},onSelect:tn,onClose:rn})}),Nr&&n.jsx("div",{ref:fe,role:"listbox","aria-label":h("messageInput.autocompletePanel.ariaLabel"),className:"w-full pt-1",children:$t.map((w,O)=>{const de=O===mt;return n.jsx("button",{type:"button",role:"option","aria-selected":de,className:`flex w-full items-center gap-3 px-3 py-3 md:py-2.5 text-left text-[15px] md:text-sm transition-colors ${de?"bg-gray-100 dark:bg-[#2d2f39]":"hover:bg-gray-50 dark:hover:bg-[#2d2f39]/60"}`,onClick:()=>ds(w.text),onMouseEnter:()=>Zs(O),children:Fo(w.text)},O)})}),n.jsx(Ds,{isOpen:T.isOpen,onClose:zo,onConfirm:Bo,title:h("messageInput.fileDelete.title"),message:h("messageInput.fileDelete.message",{filename:T.filename}),confirmText:h("messageInput.fileDelete.confirmText"),cancelText:h("common.cancel"),type:"danger",isLoading:T.isDeleting})]})]})}),v&&c&&typeof document<"u"&&Hs.createPortal(n.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:n.jsxs("div",{ref:W,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:[n.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-[#2d2f39]",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/20 flex items-center justify-center",children:n.jsx(_a,{className:"w-5 h-5 text-blue-500"})}),n.jsx("h2",{id:"agent-info-title",className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:h("messageInput.agentInfoModal.title")})]}),n.jsx("button",{type:"button",onClick:()=>M(!1),className:"p-2 hover:bg-gray-100 dark:hover:bg-[#25262f] rounded-lg transition-colors","aria-label":h("messageInput.agentInfoModal.closeAriaLabel"),children:n.jsx(Ge,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),n.jsx("div",{className:"p-6",children:n.jsx(_t,{content:c,className:`message-markdown w-full min-w-0 prose prose-slate dark:prose-invert max-w-none text-sm leading-relaxed text-[#434654] dark:text-[#d7dae3] [&>:first-child]:mt-0 [&>:last-child]:mb-0 ${_e}`,syntaxTheme:Y})}),n.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:n.jsx("button",{type:"button",onClick:()=>M(!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)]})}const gi=24e3;function Cf(t){const e=new Uint8Array(t.length*2),r=new DataView(e.buffer);t.forEach((a,i)=>r.setInt16(i*2,Math.round(Math.max(-1,Math.min(1,a))*(a<0?32768:32767)),!0));let s="";return e.forEach(a=>{s+=String.fromCharCode(a)}),btoa(s)}function Af(t){const e=atob(t),r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i);const s=new Float32Array(Math.floor(r.length/2)),a=new DataView(r.buffer);for(let i=0;i<s.length;i++)s[i]=a.getInt16(i*2,!0)/32768;return s}function pi(t,e,r){if(e===r)return t;const s=new Float32Array(Math.floor(t.length*r/e)),a=e/r;for(let i=0;i<s.length;i++){const o=i*a,l=Math.floor(o),c=Math.min(l+1,t.length-1);s[i]=(t[l]||0)+((t[c]||0)-(t[l]||0))*(o-l)}return s}function Nf(t){const e=Math.floor(t/60),r=t%60;return`${e}:${r.toString().padStart(2,"0")}`}function If({conversationId:t,adapterName:e,sessionId:r,adapterNotes:s}){const{t:a}=Ee(),i=m.useRef(null),o=m.useRef(null),l=m.useRef(null),c=m.useRef(null),d=m.useRef(null),u=m.useRef(null),f=m.useRef(null),p=m.useRef(null),g=m.useRef(0),h=m.useRef(new Set),x=m.useRef(!1),b=m.useRef(!1),[k,S]=m.useState("idle"),[E,_]=m.useState(!1),[v,M]=m.useState(!1),[F,y]=m.useState(0),[A,N]=m.useState(!1),I=ge(V=>V.realtimeVoice),$=ge(V=>V.setRealtimeVoiceState),U=ge(V=>V.beginRealtimeVoiceTurn),X=ge(V=>V.appendRealtimeVoiceAssistantDelta),j=ge(V=>V.finishRealtimeVoiceTurn);m.useEffect(()=>{x.current=E},[E]);const L=m.useCallback(()=>{var oe,T,Q,R;b.current=!0;const V=i.current;(V==null?void 0:V.readyState)===WebSocket.OPEN?(V.send(JSON.stringify({type:"interrupt"})),V.onmessage=null,V.onerror=null,V.onclose=null,window.setTimeout(()=>V.close(),150)):V==null||V.close(),i.current=null,(oe=c.current)==null||oe.disconnect(),(T=c.current)==null||T.port.close(),c.current=null,(Q=l.current)==null||Q.getTracks().forEach(W=>W.stop()),l.current=null,h.current.forEach(W=>{try{W.stop()}catch{}}),h.current.clear(),(R=o.current)==null||R.close(),o.current=null,d.current=null,u.current=null,_(!1),M(!1),y(0),S("idle"),$({status:"idle"}),j(t)},[t,j,$]),B=m.useCallback(()=>{var V;h.current.forEach(oe=>{try{oe.stop()}catch{}}),h.current.clear(),g.current=((V=o.current)==null?void 0:V.currentTime)||0,M(!1)},[]);m.useEffect(()=>()=>L(),[L]),m.useEffect(()=>{if(k!=="connected")return;const V=Date.now(),oe=window.setInterval(()=>y(Math.floor((Date.now()-V)/1e3)),1e3);return()=>window.clearInterval(oe)},[k]),m.useEffect(()=>{let V=0;const oe=()=>{var W;const T=v?u.current:d.current,Q=T&&!E?new Uint8Array(T.fftSize):null;Q&&T.getByteTimeDomainData(Q);let R=0;if(Q){for(const ne of Q){const fe=(ne-128)/128;R+=fe*fe}R=Math.min(1,Math.sqrt(R/Q.length)*8)}(W=f.current)==null||W.style.setProperty("transform",`scale(${1+R*.16})`),p.current&&(p.current.style.setProperty("transform",`scale(${1.05+R*.45})`),p.current.style.setProperty("opacity",`${.08+R*.35}`)),V=window.requestAnimationFrame(oe)};return oe(),()=>window.cancelAnimationFrame(V)},[v,E,k]);const C=m.useCallback(async()=>{try{b.current=!1,S("connecting"),y(0),$({status:"connecting",error:void 0,transcript:""});const oe=(await Re()).getRealtimeVoiceWebSocketUrl(e,{sessionId:r}),T=new WebSocket(oe);i.current=T,T.onmessage=Q=>{if(b.current)return;let R;try{R=JSON.parse(Q.data)}catch{return}if(R.type==="connected")S("connected"),M(!1),$({status:"connected",provider:String(R.mode||""),model:String(R.realtime_model||"")});else if(R.type==="audio_chunk"&&typeof R.data=="string"&&o.current&&u.current){const W=o.current,ne=Af(R.data),fe=typeof R.sample_rate=="number"?R.sample_rate:gi,D=W.createBuffer(1,Math.max(1,Math.floor(ne.length*W.sampleRate/fe)),W.sampleRate);D.copyToChannel(pi(ne,fe,W.sampleRate),0);const G=W.createBufferSource();G.buffer=D,G.connect(u.current),h.current.add(G),G.onended=()=>h.current.delete(G),g.current=Math.max(g.current,W.currentTime+.06),G.start(g.current),g.current+=D.duration,M(!0)}else R.type==="transcription"&&typeof R.text=="string"?U(t,R.text):R.type==="assistant_transcript_delta"&&typeof R.delta=="string"?X(t,R.delta):R.type==="done"?(M(!1),j(t,{userMessageId:typeof R.user_message_id=="string"?R.user_message_id:void 0,assistantMessageId:typeof R.assistant_message_id=="string"?R.assistant_message_id:void 0})):R.type==="interrupted"?(B(),j(t)):R.type==="error"&&(S("error"),M(!1),j(t),$({status:"error",error:String(R.message||a("realtimeVoice.errors.connectionFailed"))}))},T.onerror=()=>{b.current||(M(!1),j(t),S("error"),$({status:"error",error:a("realtimeVoice.errors.connectionFailed")}))},T.onclose=()=>{b.current||(M(!1),j(t),S("error"),$({status:"error",error:a("realtimeVoice.errors.connectionFailed")}))},T.onopen=async()=>{const Q=new AudioContext;o.current=Q,g.current=Q.currentTime;const R=Q.createAnalyser();R.fftSize=256,R.smoothingTimeConstant=.8,R.connect(Q.destination),u.current=R,await Q.audioWorklet.addModule("/audio-capture-processor.js");const W=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});l.current=W;const ne=Q.createMediaStreamSource(W),fe=Q.createAnalyser();fe.fftSize=256,fe.smoothingTimeConstant=.8,d.current=fe,ne.connect(fe);const D=new AudioWorkletNode(Q,"audio-capture-processor");c.current=D,D.port.onmessage=G=>{var se;T.readyState===WebSocket.OPEN&&(((se=G.data)==null?void 0:se.type)!=="audio"||!(G.data.data instanceof Float32Array)||x.current||T.send(JSON.stringify({type:"audio_chunk",data:Cf(pi(G.data.data,Q.sampleRate,gi)),format:"pcm"})))},ne.connect(D),D.connect(Q.destination)}}catch(V){const oe=V instanceof DOMException&&(V.name==="NotAllowedError"||V.name==="PermissionDeniedError");S("error"),$({status:"error",error:oe?a("realtimeVoice.errors.microphoneDenied"):V instanceof Error?V.message:a("realtimeVoice.errors.connectionFailed")})}},[e,X,U,B,t,j,r,$,a]),H=m.useCallback(()=>_(V=>!V),[]),q=k==="connected",J=a(k==="connecting"?"realtimeVoice.status.connecting":k==="error"?"realtimeVoice.status.error":q?v?"realtimeVoice.status.speaking":"realtimeVoice.status.listening":"realtimeVoice.status.ready"),K=k==="connecting"?"bg-amber-400 animate-pulse":k==="error"?"bg-red-500":q?"bg-blue-500":"bg-gray-300 dark:bg-[#4a4b54]";return n.jsx("section",{className:"mx-auto flex w-full max-w-[64rem] shrink-0 flex-col","aria-label":a("realtimeVoice.sectionAriaLabel"),children:n.jsxs("div",{className:"relative w-full",children:[I.error&&n.jsxs("div",{role:"alert",className:"mb-2 flex items-start justify-between gap-3 rounded-lg bg-red-50 px-3.5 py-2.5 text-sm text-red-700 dark:bg-red-950/40 dark:text-red-200",children:[n.jsx("p",{children:I.error}),n.jsx("button",{type:"button",onClick:C,className:"shrink-0 whitespace-nowrap font-medium underline underline-offset-2 hover:text-red-900 dark:hover:text-red-100",children:a("realtimeVoice.retry")})]}),A&&s&&n.jsxs("div",{className:"mb-2 rounded-lg border border-gray-200 bg-transparent px-4 py-3 dark:border-[#2f303d]",children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[n.jsx("p",{className:"text-sm font-medium text-[#353740] dark:text-[#ececf1]",children:a("messageInput.agentInfoModal.title")}),n.jsx("button",{type:"button",onClick:()=>N(!1),"aria-label":a("messageInput.agentInfoModal.closeAriaLabel"),title:a("messageInput.agentInfoModal.closeAriaLabel"),className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-gray-500 transition-all active:scale-95 hover:bg-gray-100 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#2f313a]",children:n.jsx(Ge,{className:"h-4 w-4"})})]}),n.jsx(_t,{content:s,className:"message-markdown prose prose-slate max-w-none text-sm leading-relaxed text-[#434654] dark:prose-invert dark:text-[#d7dae3] [&>:first-child]:mt-0 [&>:last-child]:mb-0"})]}),n.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-gray-300 bg-gray-50 px-2.5 py-2 shadow-sm transition-all dark:border-[#242424] dark:bg-[#111111] md:rounded-lg md:px-4 md:py-3",children:[n.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[n.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${K}`,"aria-hidden":"true"}),n.jsxs("span",{"aria-live":"polite",className:"min-w-0 break-words text-sm text-[#353740] dark:text-[#ececf1]",children:[J,I.model?` · ${I.model}`:""]})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-1 md:gap-2",children:[q&&n.jsx("span",{className:"hidden font-mono text-xs tabular-nums text-gray-500 dark:text-[#8a8fa3] sm:inline",children:Nf(F)}),n.jsxs("span",{className:"relative flex h-7 w-7 shrink-0 items-center justify-center","aria-hidden":"true",children:[n.jsx("span",{ref:p,className:`absolute inset-0 rounded-full transition-[background-color] duration-200 ${k==="error"?"bg-red-500":q?"bg-blue-500":"bg-gray-400 dark:bg-[#565869]"}`}),n.jsx("span",{ref:f,className:`relative flex h-6 w-6 items-center justify-center rounded-full transition-[background-color,transform] duration-150 ${k==="error"?"bg-red-500 text-white":q?"bg-blue-600 text-white dark:bg-blue-500":"bg-gray-200 text-gray-500 dark:bg-[#2f313a] dark:text-[#bfc2cd]"}`,children:v?n.jsx(Ys,{className:"h-3.5 w-3.5"}):n.jsx(Is,{className:"h-3.5 w-3.5"})})]}),s&&n.jsx("button",{type:"button",onClick:()=>N(V=>!V),"aria-expanded":A,"aria-label":a("messageInput.agentInfo.ariaLabel"),title:a("messageInput.agentInfo.title"),className:"inline-flex h-8 w-8 items-center justify-center rounded-full text-gray-500 transition-all active:scale-95 hover:bg-gray-200 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#565869]",children:n.jsx(_a,{className:"h-4 w-4"})}),k==="connecting"?n.jsx("span",{className:"inline-flex h-9 w-9 items-center justify-center rounded-full bg-gray-300 text-gray-500 dark:bg-[#565869] dark:text-[#bfc2cd]",children:n.jsx(Rs,{className:"h-4 w-4 animate-spin"})}):q?n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button",onClick:H,"aria-pressed":E,title:a(E?"realtimeVoice.unmuteMic":"realtimeVoice.muteMic"),"aria-label":a(E?"realtimeVoice.unmuteMic":"realtimeVoice.muteMic"),className:`inline-flex h-9 w-9 items-center justify-center rounded-full transition-all active:scale-95 ${E?"bg-red-100 text-red-600 dark:bg-red-900/40 dark:text-red-300":"text-gray-500 hover:bg-gray-200 hover:text-[#353740] dark:text-[#bfc2cd] dark:hover:bg-[#565869]"}`,children:E?n.jsx(ro,{className:"h-4 w-4"}):n.jsx(Is,{className:"h-4 w-4"})}),n.jsx("button",{type:"button",onClick:L,title:a("realtimeVoice.endCall"),"aria-label":a("realtimeVoice.endCall"),className:"inline-flex h-9 w-9 items-center justify-center rounded-full bg-red-500 text-white transition-all active:scale-95 hover:bg-red-600 dark:bg-red-600 dark:hover:bg-red-700",children:n.jsx(Sd,{className:"h-4 w-4"})})]}):n.jsx("button",{type:"button",onClick:C,title:a("realtimeVoice.startCall"),"aria-label":a("realtimeVoice.startCall"),className:"inline-flex h-9 w-9 items-center justify-center rounded-full bg-black text-white transition-all active:scale-95 hover:bg-gray-800 dark:bg-white dark:text-black dark:hover:bg-gray-200",children:n.jsx(Is,{className:"h-4 w-4"})})]})]})]})})}function xi({adapter:t,onSelect:e}){var l;const{t:r}=Ee(),s=(l=t.description)==null?void 0:l.trim(),{isDark:a}=mr(),i=a?"dark":"light",o=()=>e(t);return n.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:[n.jsx("div",{className:"relative",children:n.jsx("div",{className:"min-w-0",children:n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-[15px] font-semibold text-blue-700 dark:text-blue-300 md:text-base",children:t.name}),s?n.jsx("div",{className:"mt-1 text-sm leading-5 text-slate-600 dark:text-slate-300",children:n.jsx(_t,{content:s,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})}):n.jsx("p",{className:"mt-1 text-sm leading-5 text-slate-500 dark:text-slate-400",children:r("agentCard.configureMessage")})]}),n.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:n.jsx(Dn,{className:"h-4 w-4","aria-hidden":"true"})})]})})}),n.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:n.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:n.jsx(Dn,{className:"h-4 w-4","aria-hidden":"true"})})})]})}const cr=t=>{if(typeof t!="string")return;const e=t.trim();return e.length>0?e:void 0},Ef=t=>{if(!t||typeof t!="object")return null;const e=t,r=cr(e.name);if(!r)return null;const s=cr(e.id);if(!s)return console.warn(`[middlewareConfig] Adapter "${r}" is missing a required 'id' field — skipping.`),null;const a=cr(e.apiUrl),i=cr(e.model),o=cr(e.inputPlaceholder),l=typeof e.notes=="string"?e.notes.trim():void 0;let c=cr(e.description)||cr(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:s,name:r};return a&&(d.apiUrl=a),c&&(d.description=c),l&&(d.notes=l),i&&(d.model=i),o&&(d.inputPlaceholder=o),d},jo=t=>Array.isArray(t)?t.map(Ef).filter(e=>e!==null):[];let Jt=null,ya=0;const Lf=3e4;function _f(){if(typeof window<"u"){const t=window.ORBIT_CHAT_CONFIG;if(t!=null&&t.adapters&&Array.isArray(t.adapters)){z("Loading adapters from window.ORBIT_CHAT_CONFIG");const e=jo(t.adapters);return e.length===0?null:e}}return null}async function Ja(){if(Jt&&Date.now()-ya<Lf)return Jt;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(),s=jo(r.adapters);if(s.length>0)return Jt=s,ya=Date.now(),z("Fetched adapters from /api/adapters:",Jt),Jt;z("/api/adapters response did not contain valid adapters, trying fallback")}z(`/api/adapters returned ${e.status}, trying fallback`)}catch(e){z("Could not fetch from /api/adapters, trying fallback:",e)}const t=_f();if(t&&t.length>0)return Jt=t,ya=Date.now(),z("Loaded adapters from config:",Jt),Jt;throw xe("No adapters available from API or config"),new Error("No adapters available. Define adapters in orbitchat.yaml.")}const Tf="h-[96px]";function Mf({onAdapterSelect:t,className:e="",title:r="",subtitle:s="",eyebrow:a=""}){const{t:i}=Ee(),[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(""),[b,k]=m.useState(!1),S=m.useCallback(()=>{const j=p.current;if(!j){k(!1);return}k(j.scrollHeight-j.scrollTop-j.clientHeight>20)},[]),E=()=>typeof window<"u"&&window.matchMedia("(min-width: 768px)").matches,_=()=>{var j;return Array.from(((j=p.current)==null?void 0:j.querySelectorAll('[data-agent-card="true"]'))??[])},v=j=>{const B=_()[j]??null;B&&(B.focus(),B.scrollIntoView({block:"nearest"}))},M=()=>{v(0)},F=()=>{const j=_();j.length!==0&&v(j.length-1)},y=j=>{if(!c&&!u&&I.length>0&&E()){if(j.key==="Tab"&&!j.shiftKey){j.preventDefault(),M();return}if(j.key==="ArrowDown"){j.preventDefault(),M();return}j.key==="ArrowUp"&&(j.preventDefault(),F())}},A=j=>{var H;if(!$||!E()||j.key!=="ArrowDown"&&j.key!=="ArrowUp")return;const L=document.activeElement;if(!(L instanceof HTMLElement)||L.dataset.agentCard!=="true")return;const B=_(),C=B.indexOf(L);if(C!==-1){if(j.preventDefault(),j.key==="ArrowDown"){v((C+1)%B.length);return}if(C===0){(H=g.current)==null||H.focus();return}v(C-1)}},N=h.trim().toLowerCase(),I=N?o.filter(j=>{var H,q;const L=j.name.toLowerCase().includes(N),B=((H=j.description)==null?void 0:H.toLowerCase().includes(N))??!1,C=((q=j.model)==null?void 0:q.toLowerCase().includes(N))??!1;return L||B||C}):o,$=h.trim().length>0,U=$||I.length===1;m.useEffect(()=>{const j=p.current;if(j)return S(),j.addEventListener("scroll",S,{passive:!0}),()=>j.removeEventListener("scroll",S)},[S,I]),m.useEffect(()=>{let j=!0;return(async()=>{try{d(!0),f(null);const C=(await Ja()).slice().sort((H,q)=>H.name.localeCompare(q.name,void 0,{sensitivity:"base"}));j&&l(C)}catch(B){xe("[AgentSelectionList] Failed to load adapters",B),j&&f(i("agentSelectionList.unableToLoad"))}finally{j&&d(!1)}})(),()=>{j=!1}},[i]),m.useEffect(()=>{var j;c||u||o.length===0||(j=g.current)==null||j.focus()},[c,u,o.length]);const X=()=>c?n.jsx("div",{className:"grid gap-4",children:Array.from({length:3}).map((j,L)=>n.jsx("div",{className:`${Tf} animate-pulse rounded-2xl border border-gray-200 bg-transparent dark:border-[#3b3c49]`},L))}):u?n.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?n.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?n.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")}):n.jsxs("div",{className:"relative flex flex-col h-full min-h-0",children:[n.jsx("div",{ref:p,onKeyDown:A,className:"agent-selection-scroll flex-1 min-h-0 overflow-y-auto pr-1 pb-2",children:U?n.jsx("div",{className:"mx-auto flex w-full max-w-xl flex-col gap-3 lg:max-w-2xl",children:I.map(j=>n.jsx(xi,{adapter:j,onSelect:L=>t(L.id)},j.id))}):n.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:I.map(j=>n.jsx(xi,{adapter:j,onSelect:L=>t(L.id)},j.id))})}),b&&n.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 n.jsxs("div",{className:`flex w-full flex-col gap-4 md:gap-6 ${e}`,children:[(a||r||s)&&n.jsxs("div",{className:"flex-shrink-0",children:[a&&n.jsx("p",{className:"text-sm font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-300",children:a}),r&&n.jsx("h2",{className:"mt-2 text-2xl font-bold text-gray-900 dark:text-white",children:r}),s&&n.jsx("p",{className:"mt-2 text-base text-gray-600 dark:text-gray-300",children:s})]}),n.jsx("div",{className:"flex w-full flex-shrink-0 justify-center",children:n.jsx("div",{className:"w-full max-w-xl lg:max-w-2xl",children:n.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:[n.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))]"}),n.jsx($s,{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"}),n.jsx("input",{ref:g,type:"text",placeholder:i("agentSelectionList.searchPlaceholder"),value:h,maxLength:100,disabled:c||!!u||o.length===0,onChange:j=>x(j.target.value),onKeyDown:y,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&&n.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:n.jsx(Ge,{className:"h-3.5 w-3.5"})})]})})}),n.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:X()})]})}function Ua(){return Wa()?Gs()==="entra"?n.jsx(Rf,{}):n.jsx(Ff,{}):null}function Ff(){const{user:t,logout:e,loginWithRedirect:r}=Ba();if(!Sr()||!t)return n.jsx(Co,{onClick:()=>r()});const a=t.name||t.email||"User";return n.jsx(Ao,{displayName:a,onClick:()=>e({logoutParams:{returnTo:window.location.origin}})})}function Rf(){const{instance:t,accounts:e}=za();if(!Sr()||e.length===0)return n.jsx(Co,{onClick:()=>t.loginRedirect({scopes:Ka()}).catch(()=>{})});const s=e[0],a=s.name||s.username||"User";return n.jsx(Ao,{displayName:a,onClick:()=>t.logoutRedirect({postLogoutRedirectUri:window.location.origin}).catch(()=>{})})}function Co({onClick:t}){const{t:e}=Ee();return n.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:[n.jsx(to,{className:"h-4 w-4"}),n.jsx("span",{children:e("common.signIn")})]})}function Ao({displayName:t,onClick:e}){const{t:r}=Ee();return n.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-sm text-gray-600 dark:text-[#bfc2cd]",children:[n.jsx("span",{className:"hidden max-w-[170px] truncate font-medium md:block",title:t,children:t}),n.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:[n.jsx(md,{className:"h-4 w-4"}),n.jsx("span",{className:"hidden md:inline",children:r("common.logOut")})]})]})}function No({placement:t="default",compact:e=!1}){const{t:r}=Ee();if(!Gi())return null;const s=Vc(),a=Hc(),i=qc(),o=Wc(),l=Kc(),c=Gc(),d=Yc(),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",b=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 n.jsx("footer",{className:`shrink-0 bg-white dark:bg-black text-sm ${f} ${u}`.trim(),style:{backgroundColor:a||void 0,color:i||void 0},children:n.jsx("div",{className:h,children:n.jsx("div",{className:x,children:n.jsxs("div",{className:p,children:[s&&n.jsx("p",{className:`${e?"text-xs leading-snug":"text-sm"} text-slate-700 dark:text-slate-200 ${t==="sidebar"?"pt-0.5":""}`.trim(),children:s}),d.length>0&&n.jsx("nav",{"aria-label":r("appFooter.navLinksAriaLabel"),children:n.jsx("ul",{className:`flex flex-wrap items-center ${g} ${e?"gap-1":"gap-1.5 sm:gap-2"}`,children:d.map((k,S)=>{const E=l==="inline"&&S>0;return n.jsxs("li",{className:"flex items-center",children:[E&&n.jsx("span",{className:"mr-1.5 text-slate-400 dark:text-slate-500","aria-hidden":"true",children:"·"}),n.jsx("a",{href:k.url,target:"_blank",rel:"noopener noreferrer",className:b,style:{color:i||void 0},children:k.label})]},k.url)})})})]})})})})}const $f=60*1e3;let wa=null,bi=0;const ka=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},Io=()=>{if(typeof window>"u")return ka("/");const t=ka("/");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 ka(r.pathname||t)}catch{return t}},Vs=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),Pf=async()=>{const t=Date.now();if(wa&&t-bi<$f)return wa;let e=[];try{e=await Ja()}catch(s){ye("[agentRouting] Unable to load adapters for slug resolution",s)}const r=new Map;return e.forEach(s=>{const a=Vs(s.name);a&&r.set(a,s.id);const i=Vs(s.id);i&&i!==a&&r.set(i,s.id)}),wa=r,bi=t,r},Oa=t=>{var i;const e=Io(),r=t.startsWith("/")?t:`/${t}`;let s=r;if(e!=="/"){if(!r.startsWith(e))return null;s=r.slice(e.length)}const a=s.split("/").filter(Boolean);return a.length===0?null:((i=a[0])==null?void 0:i.toLowerCase())||null},Eo=t=>{const e=Io();if(!t)return e;const r=t.replace(/^\/+|\/+$/g,"");return e==="/"?r?`/${r}`:"/":`${e}/${r}`.replace(/\/{2,}/g,"/")},Nt=t=>{if(typeof window>"u")return;const e=Eo(t),r=window.location.pathname;if(e===r)return;const s=window.location.search||"",a=window.location.hash||"";window.history.replaceState(window.history.state,"",`${e}${s}${a}`)},Df=()=>Eo(null),Uf=async t=>{const e=t.trim().toLowerCase();return e&&(await Pf()).get(e)||null};function Of({currentConversation:t,showEmptyState:e,createConversation:r,configureApiSettings:s,clearError:a,clearCurrentConversationAdapter:i}){var fe;const{t:o}=Ee(),l=o("agent.error.singleAdapterMissing"),[c,d]=m.useState(!1),[u,f]=m.useState(null),p=Ks(),g=Va(),h=typeof window<"u"?Oa(window.location.pathname):null,[x,b]=m.useState(h),[k,S]=m.useState(()=>!p&&e&&!h),E=m.useRef(null),_=m.useRef(new Map),v=m.useRef(0),M=3e4,F=!!t,y=(t==null?void 0:t.messages.length)??0,A=((fe=t==null?void 0:t.attachedFiles)==null?void 0:fe.length)??0,N=m.useMemo(()=>F&&(y>0||A>0),[A,y,F]),I=m.useCallback(()=>{He(()=>ge.getState())},[]),$=m.useCallback((D,G)=>{if(!D)return;const se=G||o("agent.error.configurationFailed");let ve=!1;ge.setState(ue=>{const pe=ue.conversations.find(ce=>ce.id===D);return!pe||pe.messages.length>0?ue:(ve=!0,{conversations:ue.conversations.map(ce=>ce.id===D?{...ce,adapterLoadError:se}:ce)})}),ve&&I()},[I,o]),U=m.useCallback(D=>{if(!D)return;let G=!1;ge.setState(se=>{const ve=se.conversations.find(ue=>ue.id===D);return!ve||!ve.adapterLoadError?se:(G=!0,{conversations:se.conversations.map(ue=>ue.id===D?{...ue,adapterLoadError:null}:ue)})}),G&&I()},[I]),X=m.useCallback(D=>D instanceof ho?D.status===401?o("agent.error.authenticationFailed"):D.status===404?o("agent.error.notFound"):D.message:D instanceof Error?D.message:o("agent.error.loadFailed"),[o]),j=m.useCallback(()=>{const D=ge.getState(),G=D.currentConversationId?D.conversations.find(se=>se.id===D.currentConversationId):null;if(!G||G.messages.length>0)try{return r()}catch(se){ye("Cannot create a new conversation for agent selection:",se instanceof Error?se.message:"Unknown error")}return(G==null?void 0:G.id)||null},[r]),L=m.useCallback(async D=>{if(!(D!=null&&D.adapterName))return{ok:!1};try{const G=await Re(),se=new G.ApiClient({apiUrl:D.apiUrl||Pe(),sessionId:null,adapterName:D.adapterName});if(typeof se.getAdapterInfo!="function")return{ok:!1};const ve=await se.getAdapterInfo();return ge.setState(ue=>({conversations:ue.conversations.map(pe=>pe.id===D.id?{...pe,adapterInfo:ve,adapterLoadError:null,updatedAt:new Date}:pe)})),ge.getState().currentConversationId===D.id&&f(null),I(),{ok:!0}}catch(G){const se=X(G),ve=ge.getState();ve.currentConversationId===D.id&&f({conversationId:D.id,message:se});const ue=ve.conversations.find(pe=>pe.id===D.id);return ue&&ue.messages.length===0&&$(D.id,se),{ok:!1,error:G}}},[X,$,I]),B=m.useCallback(async D=>{if(!D)return;const G=ge.getState(),se=G.currentConversationId?G.conversations.find(ve=>ve.id===G.currentConversationId):null;if(se){d(!0),f(null),U(se.id);try{const ve=se.apiUrl||Pe();await s(ve,void 0,D),a();const ue=ge.getState(),pe=ue.conversations.find(ce=>ce.id===ue.currentConversationId);if((pe==null?void 0:pe.adapterName)===D&&(!pe.adapterInfo||pe.adapterInfo.notes===void 0)){const ce=await L(pe);!ce.ok&&ce.error&&xe("Failed to load adapter info after selecting adapter:",ce.error)}}catch(ve){xe("Failed to configure adapter from empty state:",ve);const ue=X(ve);f({conversationId:se.id,message:ue}),$(se.id,ue)}finally{d(!1)}}},[U,a,s,L,X,$]),C=m.useCallback(D=>{p||(j(),S(!1),Nt(Vs(D)),B(D))},[j,B,p]),H=m.useCallback(()=>{p||(i(),Nt(null),S(!0))},[i,p]),q=m.useCallback(()=>{var ve,ue;if(p){const pe=ge.getState(),ce=pe.currentConversationId?pe.conversations.find(Te=>Te.id===pe.currentConversationId):null;if(!!ce&&(ce.messages.length>0||(((ve=ce.attachedFiles)==null?void 0:ve.length)||0)>0))try{r()}catch(Te){ye("Cannot go home (new conversation):",Te instanceof Error?Te.message:"Unknown error")}Nt(null),S(!1);return}b(null);const D=ge.getState(),G=D.currentConversationId?D.conversations.find(pe=>pe.id===D.currentConversationId):null;if(!!G&&(G.messages.length>0||(((ue=G.attachedFiles)==null?void 0:ue.length)||0)>0))try{r()}catch(pe){ye("Cannot go home (new conversation):",pe instanceof Error?pe.message:"Unknown error");return}else G!=null&&G.adapterName&&i();Nt(null),S(!0)},[i,r,p]),K=!p&&e&&!x&&!(t!=null&&t.adapterName)&&!N||!p&&e&&k&&!(t!=null&&t.adapterName)&&!N;m.useEffect(()=>{if(p){Nt(null);return}if(!x){if(K||!(t!=null&&t.adapterName)){Nt(null);return}Nt(Vs(t.adapterName))}},[t==null?void 0:t.adapterName,p,x,K]);const V=m.useCallback(async()=>{if(typeof window>"u")return;const D=++v.current;if(p){Nt(null),b(null);return}const G=Oa(window.location.pathname);if(!G)return;const se=await Uf(G);if(D===v.current){if(!se){j(),Nt(null),i(),S(!0),b(null);return}j(),S(!1),Nt(G),await B(se),b(null)}},[i,j,B,p]),oe=m.useRef(V);m.useEffect(()=>{oe.current=V},[V]),m.useEffect(()=>{const D=window.setTimeout(()=>{oe.current()},0),G=()=>{oe.current()};return window.addEventListener("popstate",G),()=>{window.clearTimeout(D),v.current+=1,window.removeEventListener("popstate",G)}},[]);const T=t==null?void 0:t.id,Q=t==null?void 0:t.adapterName,R=t==null?void 0:t.apiUrl,W=!!(t!=null&&t.adapterInfo);m.useEffect(()=>{if(!p||!g||!e||!T||N||c)return;const D=(Q==null?void 0:Q.trim())||g,G=(Q==null?void 0:Q.trim())!==D||!W;if(!D||!G)return;let se=!1;return(async()=>{d(!0),f(null),U(T);try{const ue=R||Pe();await s(ue,void 0,D),a()}catch(ue){if(!se){const pe=X(ue);f({conversationId:T,message:pe}),$(T,pe)}}finally{se||d(!1)}})(),()=>{se=!0}},[U,a,s,N,X,c,p,$,e,Q,R,W,T,g]),m.useEffect(()=>{(async()=>{const G=t==null?void 0:t.adapterName,se=t?`${t.id}:${G}`:null;if(!(!se||E.current===se))if(G){E.current=se,z("[ChatInterface] Refreshing adapter info from the backend - adapterName:",G);const ve=await L(t);if(ve.ok)z("[ChatInterface] Adapter info loaded successfully");else{const ue=ve.error;xe("[ChatInterface] Failed to load adapter info:",ue);const pe=ue instanceof Error?ue.message:String(ue);if((pe.includes("429")||pe.includes("Too Many Requests"))&&G){const Ae=_.current.get(se);Ae&&clearTimeout(Ae);const Te=setTimeout(()=>{E.current===se&&(E.current=null),_.current.delete(se)},M);_.current.set(se,Te),ye(`[ChatInterface] Adapter info request rate-limited; retrying in ${M/1e3}s`)}else E.current=null}}else z("[ChatInterface] Skipping adapter info refresh: no adapter selected")})()},[L,t]),m.useEffect(()=>{const D=_.current;return()=>{D.forEach(G=>clearTimeout(G)),D.clear()}},[]);const ne=p&&!g?l:(t==null?void 0:t.adapterLoadError)??(u&&u.conversationId===(t==null?void 0:t.id)?u.message:null);return{adapterNotesError:ne,handleAgentCardSelection:C,handleChangeAgent:H,goToAgentSelectionHome:q,hasAdapterConfigurationError:!!ne,isAgentSelectionVisible:k,isConfiguringAdapter:c,isSingleAdapterMode:p,setIsAgentSelectionVisible:S,shouldShowAgentSelectionList:K}}const Lo=m.createContext(null),zf={registerGoHome:()=>{},goHome:()=>{}};function _o(){return m.useContext(Lo)??zf}function yi({adapter:t,syntaxTheme:e,forcedThemeClass:r=""}){var a;const s=(a=t.notes)==null?void 0:a.trim();return s?n.jsxs("section",{"aria-labelledby":"agent-seo-content-title",className:"mx-auto w-full max-w-[56rem] px-1 text-left sm:px-0",children:[n.jsx("h2",{id:"agent-seo-content-title",className:"sr-only",children:t.name}),n.jsx("div",{children:n.jsx(_t,{content:s,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 Bf='meta[name="description"]',Vf='meta[property="og:title"]',Hf='meta[property="og:description"]',qf='meta[property="og:type"]',Wf='link[rel="canonical"]';function wi(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Kf(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 Gf(t,e){const r=t==null?void 0:t.trim();if(r)return r;if(!e)return qa();const s=Kf(e);return s.length>160?`${s.slice(0,157).trimEnd()}...`:s}function Xf(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yf(t){const e=t.trim();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Qf(t){const e=t.trim();if(!e)return null;const r=`^${Xf(e).replace(/\\\*/g,".*")}$`;try{return new RegExp(r,"i")}catch{return null}}function Jf(t){return[Vi(),...wc()].map(Yf).filter(r=>!!r).includes(t)?!0:kc().some(r=>{const s=Qf(r);return s?s.test(t):!1})}function Zf(t){var s,a,i;const e=t==null?void 0:t.trim();if(!e)return null;const r=re.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:((s=r.name)==null?void 0:s.trim())||r.id,description:((a=r.description)==null?void 0:a.trim())||void 0,notes:((i=r.notes)==null?void 0:i.trim())||void 0}:null}function em(t){var s,a,i;if(typeof window>"u")return null;const e=Oa(window.location.pathname);if(!e)return null;const r=re.adapters.find(o=>{const l=wi(o.name||""),c=wi(o.id||"");return e===l||e===c});return r?{id:r.id,name:((s=r.name)==null?void 0:s.trim())||r.id,description:((a=r.description)==null?void 0:a.trim())||void 0,notes:((i=r.notes)==null?void 0:i.trim())||void 0}:null}function Cs(t,e,r){if(typeof document>"u")return null;const s=document.querySelector(t);if(s)return s;const a=document.createElement("meta");return a.setAttribute(e,r),document.head.appendChild(a),a}function tm(){if(typeof document>"u")return null;const t=document.querySelector(Wf);if(t)return t;const e=document.createElement("link");return e.rel="canonical",document.head.appendChild(e),e}function To(t){if(typeof document>"u")return;const e=Ha(),r=t?`${t.name} | ${e}`:e,s=t?Gf(t.description,t.notes):qa();document.title=r;const a=Cs(Bf,"name","description");a&&(a.content=s);const i=Cs(Vf,"property","og:title");i&&(i.content=r);const o=Cs(Hf,"property","og:description");o&&(o.content=s);const l=Cs(qf,"property","og:type");l&&(l.content="website");const c=tm();if(c&&typeof window<"u"){const d=Vi(),u=window.location.origin,f=d?new URL(d.endsWith("/")?d:`${d}/`).origin:"",g=`${u&&Jf(u)?u:f||u}${window.location.pathname}`;c.href=g}}function ki(){return vc()}class Za{static async getAdapterModels(e,r){const s=await Re(),a=new s.ApiClient({apiUrl:"",adapterName:r});if(!a.getAdapterModels)throw new Error("getAdapterModels is not available on this API client");return a.getAdapterModels(e)}static async getAllModels(e){const r=await Re(),s=new r.ApiClient({apiUrl:"",adapterName:e});if(!s.getAllModels)throw new Error("getAllModels is not available on this API client");return s.getAllModels()}static async listAdapterModels(e,r){return(await Za.getAdapterModels(e,r)).models}}const rm="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",vi="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",sm="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 am({onOpenSettings:t,onOpenSidebar:e}){var Tt,Xe,Ht,jt,je,dt,ut,qt,gr;const{t:r}=Ee(),{conversations:s,currentConversationId:a,createConversation:i,canCreateNewConversation:o,sendMessage:l,regenerateResponse:c,editMessageAndRegenerate:d,isLoading:u,configureApiSettings:f,error:p,clearError:g,createThread:h,clearCurrentConversationAdapter:x}=ge(),{settings:b}=qs(),k=Sr(),S=st()&&!k,{theme:E,isDark:_}=mr(),v=E.mode==="dark"?"dark":E.mode==="light"?"light":"",M=_?"dark":"light",F=["application-description agent-home-markdown prose prose-slate dark:prose-invert max-w-none text-sm md:text-base leading-relaxed","text-[#4a4c5a] dark:text-[#bfc2cd]","[&>:first-child]:mt-0 [&>:last-child]:mb-0",v].filter(Boolean).join(" "),y=s.find(be=>be.id===a),A=!!(((Tt=y==null?void 0:y.adapterInfo)==null?void 0:Tt.supportsRealtimeVoice)===!0||y!=null&&y.adapterName&&yc(y.adapterName)),N=s.some(be=>{var Z;return(be.messages.length>0||(((Z=be.attachedFiles)==null?void 0:Z.length)||0)>0)&&!be.adapterLoadError}),I=!y||y.messages.length===0,$=((Xe=y==null?void 0:y.adapterInfo)==null?void 0:Xe.supportsThreading)===!0,U=!!(y!=null&&y.adapterName&&(y!=null&&y.adapterInfo))&&!$,X=go({adapterName:y==null?void 0:y.adapterName,enabled:U,selectionScopeKey:a,supportsThreading:$}),j=Bi(),L=Ha(),B=qa().trim(),C=B.length>0,{registerGoHome:H}=_o(),[q,J]=m.useState([]),[K,V]=m.useState(null);m.useEffect(()=>{const be=y==null?void 0:y.adapterName;let Z=!1;async function De(){if(V(null),!be){J([]);return}try{const Me=await Za.listAdapterModels(be,be);if(Z)return;J(Me),V(Me.length>0?Me[0].name:null)}catch{Z||(J([]),V(null))}}return De(),()=>{Z=!0}},[y==null?void 0:y.adapterName]);const{adapterNotesError:oe,handleAgentCardSelection:T,handleChangeAgent:Q,goToAgentSelectionHome:R,hasAdapterConfigurationError:W,isAgentSelectionVisible:ne,isConfiguringAdapter:fe,isSingleAdapterMode:D,shouldShowAgentSelectionList:G}=Of({currentConversation:y,showEmptyState:I,createConversation:i,configureApiSettings:f,clearError:g,clearCurrentConversationAdapter:x});m.useLayoutEffect(()=>(H(()=>R()),()=>H(null)),[H,R]);const se="max-w-[96rem]",ve="max-w-[64rem]",ue="max-w-[56rem]",pe=`mx-auto w-full ${se}`,ce=o(),Ae=!!(y!=null&&y.adapterName)&&((y==null?void 0:y.messages.length)||0)===0,Te=r(ce?"chatInterface.newConversation.tooltipCanStart":S?"chatInterface.newConversation.tooltipGuestLimited":"chatInterface.newConversation.tooltipCannotStart"),$e=!!(y&&!G),_e=G?"border-transparent dark:border-transparent md:border-transparent md:dark:border-transparent":"",Y=!Ea()&&G?"pt-0 pb-0 md:pt-0 md:pb-1":"",ae=`${sm} ${_e} ${Y}`.trim(),Ce=Gi(),Se=s.some(be=>{var Z;return(be.messages.length>0||(((Z=be.attachedFiles)==null?void 0:Z.length)??0)>0)&&!be.adapterLoadError}),me=Ce&&!Se,nt=G?"pt-0 md:pt-0":"pt-4 md:pt-6",Le=m.useMemo(()=>{var Me,Ye,tt;if(G)return null;const be=Zf(y==null?void 0:y.adapterName)||em();if(!be&&!(y!=null&&y.adapterName))return null;const Z=(Me=y==null?void 0:y.adapterName)==null?void 0:Me.trim(),De=(tt=(Ye=y==null?void 0:y.adapterInfo)==null?void 0:Ye.notes)==null?void 0:tt.trim();return be?{...be,notes:De||be.notes}:Z?{id:Z,name:Z,notes:De||void 0}:null},[(Ht=y==null?void 0:y.adapterInfo)==null?void 0:Ht.notes,y==null?void 0:y.adapterName,G]);m.useEffect(()=>{To(Le)},[Le]),m.useEffect(()=>{let be=null;const Z=()=>{be&&(be(),be=null)};if(b.voiceEnabled){if(er.isAudioEnabled())return z("[ChatInterface] Audio streaming already enabled"),Z;const De=()=>{Z();const Me=async()=>{Z(),await er.enableAudio()?z("[ChatInterface] Audio streaming enabled after user gesture"):(ye("[ChatInterface] User gesture did not enable audio streaming"),De())};document.addEventListener("pointerdown",Me,{once:!0}),document.addEventListener("keydown",Me,{once:!0}),be=()=>{document.removeEventListener("pointerdown",Me),document.removeEventListener("keydown",Me)},z("[ChatInterface] Waiting for user gesture to enable audio streaming")};return De(),Z}return Z(),er.disableAudio(),z("[ChatInterface] Audio streaming disabled via settings"),Z},[b.voiceEnabled]);const et=(be,Z,De,Me)=>{var Ye;l(be,Z,De,K??((Ye=y==null?void 0:y.adapterInfo)==null?void 0:Ye.model)??void 0,Me)},Fe=async(be,Z,De,Me,Ye)=>{var tt;await l(De,void 0,be,Ye??K??((tt=y==null?void 0:y.adapterInfo)==null?void 0:tt.model)??void 0,Me)},St=()=>{try{i()}catch(be){ye("Cannot create new conversation:",be instanceof Error?be.message:"Unknown error")}},hr=m.useCallback(async(be,Z)=>{if(y)try{await ge.getState().deleteThread(y.id,be,Z)}catch(De){xe("Failed to clear thread:",De)}},[y]);return n.jsx("main",{className:"flex-1 flex flex-col bg-transparent overflow-hidden","aria-label":r("chatInterface.workspace.ariaLabel"),children:n.jsx("div",{className:"flex h-full w-full flex-col overflow-hidden px-3 sm:px-5 lg:px-8",children:n.jsxs("div",{className:`mx-auto flex h-full w-full ${se} flex-col overflow-hidden md:pb-4 ${rm}`,children:[p&&n.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:n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsx("p",{children:p}),n.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:"×"})]})}),n.jsxs("div",{className:ae,children:[e&&n.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2 md:hidden",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("button",{onClick:e,disabled:!N,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 ${N?"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:[n.jsx(gd,{className:"h-4 w-4"}),r("chatInterface.mobile.chatsButton")]}),n.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:[n.jsx(zn,{className:"h-4 w-4"}),r("chatInterface.mobile.settingsButton")]})]}),n.jsx("div",{className:"ml-auto flex-shrink-0",children:n.jsx(Ua,{})})]}),n.jsxs("div",{className:"flex flex-col gap-2 md:gap-4 sm:flex-row sm:items-end sm:justify-between",children:[n.jsx("div",{className:"min-w-0 flex-1",children:$e&&n.jsx("div",{className:"space-y-1.5 md:space-y-3",children:n.jsxs("div",{className:"md:space-y-1",children:[n.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[n.jsx("h1",{className:"min-w-0 truncate text-lg md:text-2xl font-semibold text-[#353740] dark:text-[#ececf1]",children:(y==null?void 0:y.title)||r("chatInterface.newChatTitle")}),y&&n.jsx("span",{className:"flex-shrink-0 text-xs md:hidden text-gray-500 dark:text-[#bfc2cd]",children:y.updatedAt.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),y&&n.jsx("div",{className:"hidden md:flex items-center text-sm text-gray-500 dark:text-[#bfc2cd]",children:n.jsx("span",{children:r("chatInterface.updatedAt",{time:y.updatedAt.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})})})]})})}),n.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:[n.jsx("div",{className:"hidden flex-shrink-0 items-center md:inline-flex",children:n.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:n.jsx(zn,{className:"h-4 w-4"})})}),!D&&!G&&!!(y!=null&&y.adapterName)&&n.jsx("button",{type:"button",onClick:()=>{Ae&&Q()},disabled:!Ae,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 ${Ae?"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(Ae?"chatInterface.changeAgent.titleEnabled":"chatInterface.changeAgent.titleDisabled"),children:r("chatInterface.changeAgent.button")}),!G&&n.jsxs("button",{onClick:St,disabled:!ce,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 ${ce?"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:Te,children:[n.jsx(Cd,{className:"h-3.5 w-3.5"}),r("chatInterface.newConversation.button")]}),!Ea()&&n.jsx("div",{className:"order-4 hidden flex-shrink-0 items-center md:inline-flex",children:n.jsx(Ua,{})})]})]})]}),A&&y?n.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[y.messages.length>0?n.jsx(di,{messages:y.messages,onRegenerate:()=>{},onEditMessage:()=>{},onStartThread:async()=>{},onClearThread:async()=>{},onSendThreadMessage:async()=>{},sessionId:y.sessionId,isLoading:!1,contentMaxWidthClass:ve,assistantActions:"copy"}):n.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto pt-4 md:pt-6",children:n.jsxs("div",{className:"mx-auto flex w-full max-w-[64rem] flex-col gap-4 px-3 pb-8 sm:px-5 md:gap-5 md:px-6 md:pb-12 lg:px-8 xl:px-10",children:[n.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:Pn(y.adapterName)||y.adapterName}),Le&&ki()&&n.jsx(yi,{adapter:Le,syntaxTheme:M,forcedThemeClass:v})]})}),n.jsx("div",{className:vi,children:n.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:n.jsx(If,{conversationId:y.id,adapterName:y.adapterName,sessionId:y.sessionId,adapterNotes:((jt=y.adapterInfo)==null?void 0:jt.notes)||(Le==null?void 0:Le.notes)||(Le==null?void 0:Le.description)})})})]}):I?n.jsxs("div",{className:`flex flex-1 flex-col min-h-0 ${nt} ${G?"overflow-hidden":""}`,children:[G?n.jsx("div",{className:"flex-1 flex flex-col md:justify-start min-h-0 overflow-hidden",children:n.jsx("div",{className:"w-full flex flex-col min-h-0 overflow-hidden flex-1",children:n.jsxs("div",{className:"flex flex-col min-h-0 flex-1 gap-3 overflow-hidden md:gap-6",children:[n.jsx("div",{className:`${pe} flex-shrink-0 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between`,children:n.jsxs("div",{className:"flex-1",children:[n.jsx(_t,{content:L,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:M}),C&&n.jsx("div",{className:"mt-2",children:n.jsx(_t,{content:B,className:F,syntaxTheme:M})})]})}),n.jsx(Mf,{onAdapterSelect:T,className:`${pe} md:flex-1 md:min-h-0 md:overflow-hidden`})]})})}):n.jsx("div",{className:"flex flex-1 w-full min-h-0 flex-col overflow-y-auto pt-4 md:pt-6",children:n.jsxs("div",{className:`mx-auto flex w-full ${ue} flex-col items-center gap-4 pb-8 md:gap-5 md:pb-12`,children:[oe?n.jsx("p",{className:"w-full text-center text-sm text-red-600 dark:text-red-400",children:oe}):y!=null&&y.adapterName?n.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:Pn(y.adapterName)||y.adapterName}):fe?n.jsx("p",{className:"w-full text-center text-sm text-gray-500 dark:text-[#bfc2cd]",children:r("chatInterface.empty.configuringAgent")}):null,Le&&ki()&&n.jsx(yi,{adapter:Le,syntaxTheme:M,forcedThemeClass:v}),n.jsx("div",{className:"w-full min-w-0",children:n.jsx(hi,{onSend:et,disabled:u||!y||!(y!=null&&y.adapterName)||W,autoFocusEnabled:!0,desktopOnlyAutoFocus:D,placeholder:j,isCentered:!0,maxWidthClass:ue,adapterNotes:(je=y==null?void 0:y.adapterInfo)==null?void 0:je.notes,skillState:X,availableModels:q,defaultModel:((dt=y==null?void 0:y.adapterInfo)==null?void 0:dt.model)??null,selectedModel:K,onSelectModel:V})})]})}),me&&n.jsx("div",{className:"shrink-0 pt-5 md:pt-6",children:n.jsx(No,{compact:!0})})]}):n.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[n.jsx(di,{messages:y.messages,onRegenerate:be=>{var Z;return c(be,K??((Z=y==null?void 0:y.adapterInfo)==null?void 0:Z.model)??void 0)},onEditMessage:(be,Z)=>{var De;return d(be,Z,K??((De=y==null?void 0:y.adapterInfo)==null?void 0:De.model)??void 0)},onStartThread:async(be,Z)=>{try{await h(be,Z)}catch(De){xe("Failed to create thread:",De)}},onClearThread:hr,onSendThreadMessage:Fe,sessionId:y.sessionId,isLoading:u,contentMaxWidthClass:ve,availableModels:q,defaultModel:((ut=y==null?void 0:y.adapterInfo)==null?void 0:ut.model)??null,selectedModel:K}),n.jsx("div",{className:vi,children:n.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:n.jsx(hi,{onSend:et,disabled:u||!y||!y.adapterName||ne||W,autoFocusEnabled:!0,placeholder:r("chatInterface.docked.placeholder"),maxWidthClass:ve,isCentered:!1,adapterNotes:(qt=y==null?void 0:y.adapterInfo)==null?void 0:qt.notes,skillState:X,availableModels:q,defaultModel:((gr=y==null?void 0:y.adapterInfo)==null?void 0:gr.model)??null,selectedModel:K,onSelectModel:V})})})]})]})})})}function nm({selectedAdapter:t,onAdapterChange:e,disabled:r,showDescriptions:s=!1,variant:a="sidebar",label:i,showLabel:o}){const{t:l}=Ee(),[c,d]=m.useState([]),[u,f]=m.useState(!0),[p,g]=m.useState(null),[h,x]=m.useState(!1);m.useEffect(()=>{let A=!0;async function N(){try{f(!0),g(null);const I=await Ja();A&&d(I)}catch(I){xe("Failed to load adapters:",I),A&&g(l("adapterSelector.failedToLoad"))}finally{A&&f(!1)}}return N(),()=>{A=!1}},[l]);const b=c.find(A=>A.id===t),k=typeof o=="boolean"?o:a==="prominent",S=i||l(a==="prominent"?"adapterSelector.selectAnAgent":"adapterSelector.defaultLabel"),E=m.useMemo(()=>a==="prominent"?"relative w-full text-left":"relative w-full",[a]),_=m.useMemo(()=>{const A="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 a==="prominent"?[A,"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(" ")},[a]),v=m.useMemo(()=>a==="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]",[a]),y=k?`mb-2 block text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-[#bfc2cd] ${a==="prominent"?"!text-sm !font-semibold !text-gray-700 dark:!text-white":""}`:"sr-only";return n.jsxs("div",{className:E,children:[n.jsx("label",{className:y,children:S}),n.jsxs("div",{className:"relative",children:[n.jsx("button",{type:"button",onClick:()=>!r&&x(!h),disabled:r||u||c.length===0,className:`${_} disabled:opacity-50 disabled:cursor-not-allowed`,"aria-label":S,children:n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("div",{className:"flex flex-col min-w-0",children:[n.jsx("span",{className:`truncate font-medium ${b?"text-[#11121a] dark:text-white":"text-gray-500 dark:text-gray-400"}`,children:u?l("adapterSelector.loadingAgents"):p?l("adapterSelector.errorLoadingAgents"):b?b.name:c.length===0?l("adapterSelector.noAgentsAvailable"):l("adapterSelector.selectAnAgent")}),a==="prominent"&&(b==null?void 0:b.description)&&n.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 truncate",children:b.description})]}),n.jsx(vr,{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&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>x(!1)}),n.jsx("div",{className:v,children:n.jsx("div",{className:"max-h-72 overflow-auto py-2",children:c.map(A=>{const N=A.id===t;return n.jsx("button",{type:"button",onClick:()=>{N||e(A.id),x(!1)},className:`w-full px-4 py-3 text-left text-sm transition-colors ${N?"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:n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"font-medium truncate",children:A.name}),s&&A.description&&n.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",style:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:A.description})]})},A.id)})})})]})]}),p&&n.jsx("p",{className:"mt-1 text-xs text-red-600 dark:text-red-400",children:p})]})}const As=100;function Si({onClick:t,label:e,hoverClassName:r,icon:s}){return n.jsx("button",{onClick:t,className:`rounded-lg p-1.5 text-slate-400 transition-colors dark:text-[#6b6f7a] ${r}`,"aria-label":e,children:s})}function im(t,e){const r=new Date(e.getFullYear(),e.getMonth(),e.getDate()),s=new Date(r);s.setDate(s.getDate()-1);const a=new Date(r);a.setDate(a.getDate()-r.getDay());const i=new Date(e.getFullYear(),e.getMonth(),1);return t>=r?"today":t>=s?"yesterday":t>=a?"thisWeek":t>=i?"thisMonth":"earlier"}function om(t){const e=new Date,r=["today","yesterday","thisWeek","thisMonth","earlier"],s=new Map;for(const a of t){const i=im(a.updatedAt,e),o=s.get(i);o?o.push(a):s.set(i,[a])}return r.filter(a=>s.has(a)).map(a=>({label:a,conversations:s.get(a)}))}function ji({onRequestClose:t,onToggleDesktopSidebar:e}){const{t:r}=Ee(),s=Ks(),{conversations:a,currentConversationId:i,selectConversation:o,deleteConversation:l,deleteAllConversations:c,updateConversationTitle:d,getConversationCount:u,configureApiSettings:f,clearError:p}=ge(),g=a.find(Y=>Y.id===i),[h,x]=m.useState(""),[b,k]=m.useState(null),[S,E]=m.useState(""),[_,v]=m.useState({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1}),[M,F]=m.useState({isOpen:!1,isDeleting:!1}),[y,A]=m.useState(!1),[N,I]=m.useState(null),[$,U]=m.useState(!1),[X,j]=m.useState(null),L=m.useRef(null),B=m.useRef(null),C=m.useRef(null),H=!g||g.messages.length===0,q=(N==null?void 0:N.conversationId)===i?N.adapterName:(g==null?void 0:g.adapterName)??null,J=(X==null?void 0:X.conversationId)===i?X.message:null,K=m.useMemo(()=>a.filter(Y=>{var ee;return(Y.messages.length>0||(((ee=Y.attachedFiles)==null?void 0:ee.length)||0)>0)&&!Y.adapterLoadError}),[a]),V=m.useMemo(()=>{if(!h)return K;const Y=h.toLowerCase();return K.filter(ee=>(ee.title||r("chatInterface.newChatTitle")).toLowerCase().includes(Y)||ee.messages.some(ae=>ae.content.toLowerCase().includes(Y))||(ee.attachedFiles||[]).some(ae=>ae.filename.toLowerCase().includes(Y)))},[K,h,r]),oe=m.useMemo(()=>om(V),[V]),T=u(),Q=h.length>0,R=K.length>0;m.useEffect(()=>{if(!i||!B.current)return;const Y=B.current.querySelector('[aria-current="true"]');Y&&Y.scrollIntoView({block:"nearest",behavior:"smooth"})},[i]);const W=m.useCallback(Y=>{var me;if(Y.key!=="ArrowDown"&&Y.key!=="ArrowUp")return;Y.preventDefault();const ee=(me=B.current)==null?void 0:me.querySelectorAll('[role="option"]');if(!ee||ee.length===0)return;const ae=document.activeElement,Ce=Array.from(ee).indexOf(ae);let Se;Y.key==="ArrowDown"?Se=Ce<ee.length-1?Ce+1:0:Se=Ce>0?Ce-1:ee.length-1,ee[Se].focus()},[]),ne=async Y=>{if(!(!H||!Y)){I({conversationId:i??null,adapterName:Y}),j(null),U(!0);try{const ee=(g==null?void 0:g.apiUrl)||Pe();await f(ee,void 0,Y),p(),A(!1)}catch(ee){xe("Failed to configure adapter:",ee),j({conversationId:i??null,message:ee instanceof Error?ee.message:r("sidebar.adapterConfigureFailed")})}finally{U(!1)}}},fe=async Y=>{try{await o(Y),t==null||t()}catch(ee){xe("Failed to select conversation:",ee)}},D=(Y,ee)=>{Y.stopPropagation(),v({isOpen:!0,conversationId:ee.id,conversationTitle:ee.title||r("chatInterface.newChatTitle"),isDeleting:!1})},G=async()=>{v(Y=>({...Y,isDeleting:!0}));try{await l(_.conversationId)}catch(Y){xe("Failed to delete conversation:",Y)}v({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},se=()=>{v({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},ve=(Y,ee)=>{Y.stopPropagation(),k(ee.id),E((ee.title||r("chatInterface.newChatTitle")).slice(0,As))},ue=Y=>{const ee=S.slice(0,As).trim();ee&&d(Y,ee),k(null),E("")},pe=()=>{k(null),E("")},ce=()=>{F({isOpen:!0,isDeleting:!1})},Ae=async()=>{F(Y=>({...Y,isDeleting:!0}));try{await c(),F({isOpen:!1,isDeleting:!1}),t==null||t()}catch(Y){xe("Failed to clear all conversations:",Y),F(ee=>({...ee,isDeleting:!1}))}},Te=()=>{F({isOpen:!1,isDeleting:!1})},$e=Y=>{var ee,ae,Ce;return(ee=Y.adapterName)!=null&&ee.trim()?Y.adapterName:(Ce=(ae=Y.adapterInfo)==null?void 0:ae.adapter_name)!=null&&Ce.trim()?Y.adapterInfo.adapter_name:null};Hr(L,{enabled:y,onEscape:()=>A(!1)});const _e=Y=>{const ee=i===Y.id,ae=s?null:$e(Y),Ce=Y.title||r("chatInterface.newChatTitle");return n.jsx("div",{role:"option","aria-selected":ee,tabIndex:0,onKeyDown:Se=>{(Se.key==="Enter"||Se.key===" ")&&(Se.preventDefault(),fe(Y.id))},onClick:()=>fe(Y.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
353
+ ${ee?"border-sky-400/80 bg-sky-50/70 shadow-[0_0_0_1px_rgba(14,165,233,0.08),0_4px_14px_rgba(15,23,42,0.06)] dark:border-sky-400/45 dark:bg-sky-950/30 dark:shadow-[0_0_0_1px_rgba(56,189,248,0.07),0_6px_18px_rgba(0,0,0,0.28)]":"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":ee?"true":void 0,"aria-label":r("sidebar.conversationCard.openAriaLabel",{title:Ce}),children:b===Y.id?n.jsx("input",{type:"text",value:S,onChange:Se=>E(Se.target.value.slice(0,As)),onKeyDown:Se=>{Se.key==="Enter"&&ue(Y.id),Se.key==="Escape"&&pe(),Se.stopPropagation()},onBlur:()=>ue(Y.id),maxLength:As,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")}):n.jsxs("div",{className:"relative z-10 flex min-w-0 flex-1 flex-col gap-1",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[n.jsx("h3",{className:`flex-1 truncate text-sm leading-snug tracking-[-0.006em] ${ee?"font-semibold text-slate-900 dark:text-[#ececf1]":"font-medium text-slate-700 dark:text-[#c5c8d6]"}`,children:Ce}),n.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:[n.jsx(Si,{onClick:Se=>ve(Se,Y),label:r("sidebar.conversationCard.editAriaLabel",{title:Ce}),hoverClassName:"hover:bg-slate-200/80 hover:text-slate-600 dark:hover:bg-[#3c3f4a] dark:hover:text-[#c5c8d6]",icon:n.jsx(so,{className:"h-3.5 w-3.5"})}),n.jsx(Si,{onClick:Se=>D(Se,Y),label:r("sidebar.conversationCard.deleteAriaLabel",{title:Ce}),hoverClassName:"hover:bg-red-100/80 hover:text-red-600 dark:hover:bg-red-900/30 dark:hover:text-red-400",icon:n.jsx(oo,{className:"h-3.5 w-3.5"})})]})]}),ae&&n.jsx("span",{className:"block max-w-full truncate text-left text-xs font-medium tracking-wide text-blue-700 dark:text-blue-300",children:ae})]})},Y.id)};return n.jsxs(n.Fragment,{children:[!s&&y&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm px-4",children:n.jsxs("div",{ref:L,role:"dialog","aria-modal":"true","aria-labelledby":"select-agent-title",tabIndex:-1,className:"w-full max-w-md rounded-2xl border border-gray-200 bg-white p-6 shadow-2xl dark:border-[#3d4050] dark:bg-[#1a1b1e]",children:[n.jsx("h2",{id:"select-agent-title",className:"mb-4 text-lg font-semibold text-gray-900 dark:text-[#ececf1]",children:r("sidebar.selectAgent.title")}),n.jsxs("div",{className:"space-y-5",children:[n.jsx(nm,{selectedAdapter:q,onAdapterChange:ne,disabled:$,variant:"prominent",showDescriptions:!0,showLabel:!1}),J&&n.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:J}),n.jsx("div",{className:"flex justify-end gap-3 pt-2",children:n.jsx("button",{type:"button",onClick:()=>{j(null),A(!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:$,children:r("common.cancel")})})]})]})}),n.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:[n.jsxs("div",{className:"bg-transparent px-4 pb-4 pt-4 dark:border-[#2d2f39]",children:[n.jsxs("div",{className:"flex items-center gap-2 pb-3",children:[a.length>0&&a.some(Y=>Y.messages.length>0)&&n.jsxs("button",{onClick:ce,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:[n.jsx(Ld,{className:"h-4 w-4"}),r("sidebar.deleteAllConversations.button")]}),e&&n.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:n.jsx(yd,{className:"h-4 w-4"})})]}),J&&!y&&n.jsx("p",{role:"alert",className:"mt-2 text-xs text-red-600 dark:text-red-400",children:J}),R&&n.jsxs("div",{className:"border-t border-gray-200 pt-4 mt-4 dark:border-[#2d2f39]",children:[n.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:[n.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))]"}),n.jsx($s,{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"}),n.jsx("input",{ref:C,type:"text",role:"searchbox","aria-label":r("sidebar.search.ariaLabel"),placeholder:r("sidebar.search.placeholder"),value:h,onChange:Y=>x(Y.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&&n.jsx("button",{type:"button",onClick:()=>{var Y;x(""),(Y=C.current)==null||Y.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:n.jsx(Ge,{className:"h-3.5 w-3.5"})})]}),Q&&n.jsx("p",{"aria-live":"polite",className:"mt-2 text-center text-[11px] tabular-nums text-gray-400 dark:text-[#6e7490]",children:V.length===0?r("sidebar.resultsNone"):r("sidebar.results",{count:V.length})})]})]}),n.jsx("div",{ref:B,role:"listbox","aria-label":r("sidebar.conversations.ariaLabel"),onKeyDown:W,className:"flex-1 overflow-y-auto bg-transparent px-3 py-2",children:V.length===0?null:Q?n.jsx("div",{className:"space-y-1.5",children:V.map(_e)}):n.jsx("div",{className:"space-y-4",children:oe.map(Y=>n.jsxs("section",{"aria-label":r(`sidebar.timeGroups.${Y.label}`),children:[n.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.${Y.label}`)}),n.jsx("div",{className:"space-y-1.5",children:Y.conversations.map(_e)})]},Y.label))})}),(()=>{const Y=Ki();return Y.length===0?null:n.jsx("div",{className:"shrink-0 border-t border-gray-200/80 px-4 py-3 md:hidden dark:border-[#2d2f39]",children:n.jsx("nav",{"aria-label":r("appHeader.navLinksAriaLabel"),children:n.jsx("ul",{className:"flex flex-wrap gap-2",children:Y.map(ee=>n.jsx("li",{children:n.jsx("a",{href:ee.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:ee.label})},ee.url))})})})})(),n.jsx("div",{className:"shrink-0 border-t border-gray-200/80 dark:border-[#2d2f39]",children:n.jsx(No,{placement:"sidebar",compact:!0})})]}),n.jsx(Ds,{isOpen:_.isOpen,onClose:se,onConfirm:G,title:r("sidebar.deleteConfirm.title"),message:r("sidebar.deleteConfirm.message",{title:_.conversationTitle}),confirmText:r("sidebar.deleteConfirm.confirmText"),cancelText:r("common.cancel"),type:"danger",isLoading:_.isDeleting}),n.jsx(Ds,{isOpen:M.isOpen,onClose:Te,onConfirm:Ae,title:r("sidebar.clearAllConfirm.title"),message:r("sidebar.clearAllConfirm.message",{count:T}),confirmText:r("sidebar.clearAllConfirm.confirmText"),cancelText:r("common.cancel"),type:"danger",isLoading:M.isDeleting})]})}const lm="3.13.1",cm={version:lm},en=cm.version,dm=["@@auth0spajs@@","a0.spajs","auth0","com.auth0"];function um(t){const e=t.toLowerCase();return dm.some(r=>e.includes(r.toLowerCase()))}function fm(t){const e=[];for(let r=0;r<t.length;r++){const s=t.key(r);s&&um(s)&&e.push(s)}e.forEach(r=>t.removeItem(r))}function Ci(t){try{fm(t),t.clear()}catch(e){console.warn("[Settings] Failed to clear browser storage during reset.",e)}}function mm(){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(s=>{const a=s.indexOf("="),i=(a>-1?s.slice(0,a):s).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 hm(){Ci(localStorage),Ci(sessionStorage),mm()}function gm({isOpen:t,onClose:e}){const{t:r}=Ee(),{theme:s,updateTheme:a}=mr(),{settings:i,updateSettings:o}=qs(),{activeLanguages:l,currentLanguage:c,setLanguage:d}=ed(),[u,f]=m.useState(!1),[p,g]=m.useState(!1),h=m.useRef(null),x=m.useRef(null),b=m.useMemo(()=>[...l].sort((M,F)=>ps[M].localeCompare(ps[F])),[l]);m.useEffect(()=>{if(!p)return;const M=F=>{F.key==="Escape"&&(F.stopPropagation(),g(!1))};return document.addEventListener("keydown",M,{capture:!0}),()=>document.removeEventListener("keydown",M,{capture:!0})},[p]);const k=M=>{a({mode:M})},S=()=>{o({soundEnabled:!i.soundEnabled})},E=()=>{f(!0)},_=()=>{f(!1)},v=()=>{_(),Qs(),Js(!1),kr(null),at.getState().closeLoginPrompt(),hm(),window.location.reload()};return Hr(h,{enabled:t&&!u,onEscape:e}),Hr(x,{enabled:u,onEscape:_}),t?n.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:[n.jsx("button",{type:"button",onClick:e,"aria-label":r("settings.dialog.closeOverlayAriaLabel"),className:"absolute inset-0"}),n.jsxs("div",{onClick:M=>M.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:[n.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:[n.jsx("h2",{id:"settings-title",className:"text-xl font-semibold text-gray-900 dark:text-gray-100",children:r("settings.dialog.title")}),n.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:n.jsx(Ge,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),n.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:[n.jsxs("div",{className:"space-y-4",children:[n.jsxs("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[n.jsx(bd,{className:"w-5 h-5"}),r("settings.appearance.heading")]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:r("settings.appearance.themeLabel")}),n.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{value:"light",label:r("settings.appearance.themeLight"),icon:Ed},{value:"dark",label:r("settings.appearance.themeDark"),icon:xd},{value:"system",label:r("settings.appearance.themeSystem"),icon:pd}].map(({value:M,label:F,icon:y})=>n.jsxs("button",{onClick:()=>k(M),className:`flex flex-col items-center gap-2 p-3 rounded-lg border-2 transition-all duration-200 ${s.mode===M?"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:[n.jsx(y,{className:"w-5 h-5"}),n.jsx("span",{className:"text-sm font-medium",children:F})]},M))})]}),l.length>1&&n.jsxs("div",{className:"space-y-2",children:[n.jsxs("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2",children:[n.jsx(fd,{className:"w-4 h-4"}),r("settings.language.label")]}),n.jsxs("div",{className:"relative",children:[n.jsxs("button",{type:"button",onClick:()=>g(M=>!M),"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:[n.jsx("span",{className:"font-medium text-gray-900 dark:text-gray-100",children:ps[c]}),n.jsx(vr,{className:`h-4 w-4 flex-shrink-0 text-gray-400 transition-transform duration-200 dark:text-gray-500 ${p?"rotate-180":""}`})]}),p&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),n.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:b.map(M=>{const F=M===c;return n.jsxs("button",{type:"button",role:"option","aria-selected":F,onClick:()=>{d(M),g(!1)},className:`flex w-full items-center justify-between gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors ${F?"bg-blue-50 font-medium text-blue-700 dark:bg-blue-900/20 dark:text-blue-300":"text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-[#25262f]"}`,children:[n.jsx("span",{className:"truncate",children:ps[M]}),F&&n.jsx(ur,{className:"h-4 w-4 flex-shrink-0 text-blue-600 dark:text-blue-400"})]},M)})})]})]})]})]}),n.jsxs("div",{className:"space-y-4",children:[n.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:r("settings.chat.heading")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ys,{className:"w-4 h-4 text-gray-600 dark:text-gray-400"}),n.jsxs("div",{children:[n.jsx("label",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:r("settings.soundEffects.label")}),n.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:r("settings.soundEffects.description")})]})]}),n.jsx("button",{onClick:S,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:n.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${i.soundEnabled?"translate-x-6":"translate-x-1"}`})})]})]}),n.jsxs("div",{className:"space-y-4 pt-4 border-t border-gray-200 dark:border-[#2d2f39]",children:[n.jsxs("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[n.jsx(oo,{className:"w-5 h-5"}),r("settings.dataManagement.heading")]}),n.jsxs("div",{className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:r("settings.dataManagement.description")}),n.jsx("button",{onClick:E,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")})]})]}),n.jsxs("p",{className:"pt-2 text-center text-xs text-gray-400 dark:text-[#858999]",children:["v",en]})]}),u&&n.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/70 p-4",children:n.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:[n.jsxs("div",{className:"flex items-start gap-3",children:[n.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:n.jsx(Xa,{className:"w-5 h-5 text-red-600 dark:text-red-400"})}),n.jsxs("div",{className:"space-y-1.5",children:[n.jsx("p",{id:"reset-dialog-title",className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:r("settings.reset.confirmTitle")}),n.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:r("settings.reset.confirmMessage")})]})]}),n.jsxs("div",{className:"mt-4 flex gap-2 pt-2",children:[n.jsx("button",{onClick:_,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")}),n.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 pm({message:t}){const{t:e}=Ee(),r=Ha();return n.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:n.jsxs("div",{className:"mx-auto flex min-h-[calc(100dvh-3rem)] w-full max-w-5xl flex-col",children:[n.jsxs("header",{className:"flex items-center justify-between gap-4",children:[n.jsx("p",{className:"min-w-0 truncate text-lg font-semibold tracking-tight sm:text-xl",children:r}),n.jsxs("span",{className:"shrink-0 text-xs font-medium text-slate-400 dark:text-[#858999]",children:["v",en]})]}),n.jsx("section",{className:"flex flex-1 items-center justify-center py-12",children:n.jsxs("div",{className:"w-full max-w-lg space-y-8",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsxs("span",{className:"relative flex h-2.5 w-2.5 shrink-0",children:[n.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-amber-400 opacity-60 dark:bg-amber-500"}),n.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-amber-500 dark:bg-amber-400"})]}),n.jsx("span",{className:"text-xs font-semibold uppercase tracking-widest text-amber-700 dark:text-amber-400",children:e("outOfService.statusBadge")})]}),n.jsxs("div",{className:"space-y-4",children:[n.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-slate-950 dark:text-white sm:text-4xl",children:e("outOfService.heading")}),n.jsx("p",{className:"max-w-md whitespace-pre-wrap text-base leading-relaxed text-slate-500 dark:text-slate-400",children:t})]}),n.jsx("div",{className:"border-t border-slate-200 dark:border-[#242424]"}),n.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[n.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:[n.jsx(Ad,{className:"h-4 w-4","aria-hidden":"true"}),e("outOfService.retryButton")]}),n.jsx("span",{className:"hidden text-slate-300 dark:text-slate-700 sm:block","aria-hidden":"true",children:"·"})]})]})})]})})}function xm({children:t}){const{instance:e,accounts:r}=za(),s=gl();return m.useEffect(()=>{Js(s)},[s]),m.useEffect(()=>{if(!s||r.length===0){kr(null);return}const a=r[0];kr(a.username||a.name||a.localAccountId||null)},[s,r]),m.useEffect(()=>{if(!s||r.length===0)return;const a=r[0],i=Ka();return lo(async()=>(await e.acquireTokenSilent({scopes:i,account:a})).accessToken),()=>Qs()},[s,r,e]),n.jsx(n.Fragment,{children:t})}function bm({children:t}){return n.jsx(xm,{children:t})}function ym({children:t}){const{isLoading:e,isAuthenticated:r,getAccessTokenSilently:s,user:a}=Ba();return m.useEffect(()=>{Js(r)},[r]),m.useEffect(()=>{if(!r){kr(null);return}const i=(a==null?void 0:a.sub)||(a==null?void 0:a.email)||(a==null?void 0:a.nickname)||(a==null?void 0:a.name)||null;kr(i)},[r,a]),m.useEffect(()=>(r&&lo(()=>s()),()=>Qs()),[r,s]),e?n.jsx("div",{className:"flex items-center justify-center h-screen bg-white dark:bg-[#212121]",children:n.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 dark:border-gray-100"})}):n.jsx(n.Fragment,{children:t})}function wm({children:t}){return m.useEffect(()=>{Js(!1),kr(null),Qs()},[]),n.jsx(n.Fragment,{children:t})}function km({children:t}){return st()?Gs()==="entra"?n.jsx(bm,{children:t}):n.jsx(ym,{children:t}):n.jsx(wm,{children:t})}function vm(){const t=Wa(),e=st(),r=Sr(),{showLoginPrompt:s,promptMessage:a,closeLoginPrompt:i}=at();return m.useEffect(()=>{s&&(!t||!e||r)&&i()},[s,t,e,r,i]),!t||!e||r||!s?null:Gs()==="entra"?n.jsx(jm,{message:a,onClose:i}):n.jsx(Sm,{message:a,onClose:i})}function Sm({message:t,onClose:e}){const{loginWithRedirect:r}=Ba();return n.jsx(Mo,{message:t,onClose:e,onLogin:()=>r()})}function jm({message:t,onClose:e}){const{instance:r}=za();return n.jsx(Mo,{message:t,onClose:e,onLogin:()=>r.loginRedirect({scopes:Ka()}).catch(()=>{})})}function Mo({message:t,onClose:e,onLogin:r}){const{t:s}=Ee();return n.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center",children:[n.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:e,"aria-hidden":"true"}),n.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:[n.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":s("common.close"),children:n.jsx(Ge,{className:"h-4 w-4"})}),n.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[n.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900/40",children:n.jsx(to,{className:"h-5 w-5 text-blue-600 dark:text-blue-300"})}),n.jsx("h2",{className:"text-lg font-semibold text-gray-900 dark:text-[#ececf1]",children:s("loginPrompt.heading")})]}),n.jsx("p",{className:"mb-6 text-sm leading-relaxed text-gray-600 dark:text-[#bfc2cd]",children:t}),n.jsxs("div",{className:"flex gap-3",children:[n.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:s("common.signIn")}),n.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:s("common.cancel")})]})]})]})}function Cm(){const{t}=Ee(),{goHome:e}=_o(),{isDark:r}=mr(),s=Df(),a=m.useRef(!1),i=Rc(),o=$c(),l=Pc(),c=r?l:o,d=Dc(),u=Uc(),f=!!(d||u),p=Oc(),g=zc(),h=Bc(),x=Ki(),b=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(()=>{a.current},[l,i,o]),Ea()?n.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 ${b}`.trim(),style:{backgroundColor:p||void 0,color:g||void 0},children:n.jsxs("div",{className:"mx-auto flex w-full max-w-[96rem] items-center justify-between gap-3",children:[n.jsx("div",{className:"flex min-w-0 flex-1 items-center justify-center gap-2 md:justify-start md:gap-3",children:n.jsx("a",{href:s,"aria-label":t("appHeader.homeLinkAriaLabel"),onClick:S=>{S.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:n.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}:{}}})})}),n.jsxs("div",{className:"hidden min-w-0 flex-1 items-center justify-end gap-2 sm:gap-4 md:flex",children:[x.length>0&&n.jsx("nav",{"aria-label":t("appHeader.navLinksAriaLabel"),className:"hidden sm:block",children:n.jsx("ul",{className:"flex items-center gap-1.5 sm:gap-2",children:x.map(S=>n.jsx("li",{children:n.jsx("a",{href:S.url,target:"_blank",rel:"noopener noreferrer",className:k,style:{color:g||void 0},children:S.label})},S.url))})}),n.jsx(Ua,{})]})]})}):null}function Am({children:t}){const e=m.useRef(null),r=m.useCallback(a=>{e.current=a},[]),s=m.useCallback(()=>{var a;(a=e.current)==null||a.call(e)},[]);return n.jsx(Lo.Provider,{value:{registerGoHome:r,goHome:s},children:t})}function Nm(){const{t}=Ee(),[e,r]=m.useState(!1),[s,a]=m.useState(!1),[i,o]=m.useState(()=>localStorage.getItem("desktop-sidebar-collapsed")==="true"),l=ge(u=>u.conversations),c=_c();if(m.useEffect(()=>{localStorage.setItem("desktop-sidebar-collapsed",String(i))},[i]),c)return n.jsx(wn,{children:n.jsx(pm,{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 n.jsx(wn,{children:n.jsx(yl,{children:n.jsx(Zc,{children:n.jsx(km,{children:n.jsx(Am,{children:n.jsxs("div",{className:"h-dvh flex flex-col bg-white dark:bg-black text-slate-900 dark:text-slate-100",children:[n.jsxs("div",{className:"flex-1 flex flex-col md:flex-row md:pl-4 min-h-0",children:[d&&(i?n.jsx("div",{className:"hidden md:flex md:w-16 md:h-full shrink-0 items-start justify-center pt-8",children:n.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:n.jsx(wd,{className:"h-4 w-4"})})}):n.jsx("div",{className:"hidden md:h-full md:flex",children:n.jsx(ji,{onToggleDesktopSidebar:()=>o(!0)})})),n.jsxs("div",{className:"flex-1 flex flex-col w-full min-h-0",children:[n.jsx(Cm,{}),n.jsx("div",{className:"flex-1 flex justify-center w-full min-h-0",children:n.jsx(am,{onOpenSettings:()=>r(!0),onOpenSidebar:()=>a(!0)})})]})]}),n.jsx(vm,{}),n.jsx(gm,{isOpen:e,onClose:()=>r(!1)}),s&&n.jsxs("div",{className:"fixed inset-0 z-50 flex md:hidden",children:[n.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:()=>a(!1),"aria-hidden":"true"}),n.jsxs("div",{className:"relative z-10 h-full w-[min(20rem,90vw)] animate-slideIn bg-white dark:bg-black",children:[n.jsx(ji,{onRequestClose:()=>a(!1)}),n.jsx("button",{onClick:()=>a(!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:n.jsx(Ge,{className:"h-5 w-5"})})]})]})]})})})})})})}const va=new pl({auth:{clientId:qi(),authority:`https://login.microsoftonline.com/${Fc()}`,redirectUri:typeof window<"u"?window.location.origin:"/"},cache:{cacheLocation:"sessionStorage"}});function Im({children:t}){const[e,r]=m.useState(!1);return m.useEffect(()=>{va.initialize().then(()=>va.handleRedirectPromise()).catch(s=>{console.error("[EntraAuth] Redirect processing failed:",s)}).finally(()=>r(!0))},[]),e?n.jsx(xl,{instance:va,children:t}):null}function Em({children:t}){if(!Wa()||!st())return n.jsx(n.Fragment,{children:t});if(Gs()==="entra")return n.jsx(Im,{children:t});const r=Tc(),s=qi(),a=Mc();return!r||!s?n.jsx(n.Fragment,{children:t}):n.jsx(bl,{domain:r,clientId:s,authorizationParams:{redirect_uri:window.location.origin,...a?{audience:a}:{}},cacheLocation:"memory",children:t})}To(null);const Ai=Sc(),Ni=document.querySelector('link[rel="icon"]');if(Ni)Ni.href=Ai;else{const t=document.createElement("link");t.rel="icon",t.href=Ai,document.head.appendChild(t)}const Lm=Xc();var Ii,Ei,Li,_i,Ti,Mi;for(const t of Lm){const e=((Ii=t.src)==null?void 0:Ii.trim())||"",r=((Ei=t.content)==null?void 0:Ei.trim())||"",s=((Li=t.id)==null?void 0:Li.trim())||"";if(!e&&!r||s&&document.querySelector(`script[data-orbitchat-startup-script-id="${s}"]`)||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),(_i=t.type)!=null&&_i.trim()&&(i.type=t.type.trim()),(Ti=t.integrity)!=null&&Ti.trim()&&(i.integrity=t.integrity.trim()),t.crossOrigin&&(i.crossOrigin=t.crossOrigin),(Mi=t.referrerPolicy)!=null&&Mi.trim()&&(i.referrerPolicy=t.referrerPolicy.trim()),i.dataset.orbitchatStartupScript="true",s&&(i.dataset.orbitchatStartupScriptId=s),e&&(i.dataset.orbitchatStartupScriptSrc=e),document.head.appendChild(i)}z("🚀 AI Chat Application started");z(`📱 App Version: v${en}`);tl.createRoot(document.getElementById("root")).render(n.jsx(m.StrictMode,{children:n.jsx(Em,{children:n.jsx(Nm,{})})}));export{ec as r,Ee as u};