orbitchat 3.13.3 → 3.13.4
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.
- package/dist/assets/{ChartRenderer-BRRJkee-.js → ChartRenderer-BN_6aZ_Q.js} +1 -1
- package/dist/assets/{MermaidRenderer-D9XVA8wC.js → MermaidRenderer-JnjJzSyx.js} +4 -4
- package/dist/assets/{MusicRenderer-HHwLMgQ4.js → MusicRenderer-CHHA0796.js} +1 -1
- package/dist/assets/{SVGRenderer-Dt9X-Gok.js → SVGRenderer-DEfyMmV3.js} +1 -1
- package/dist/assets/{architectureDiagram-3BPJPVTR-DEQle2Fi.js → architectureDiagram-3BPJPVTR-1l2-cTcG.js} +1 -1
- package/dist/assets/{blockDiagram-GPEHLZMM-BXRRvUa0.js → blockDiagram-GPEHLZMM-CMFB14Z1.js} +1 -1
- package/dist/assets/{c4Diagram-AAUBKEIU-D-HJO0RL.js → c4Diagram-AAUBKEIU-D0d9-0MF.js} +1 -1
- package/dist/assets/channel-DDaxixjZ.js +1 -0
- package/dist/assets/{chunk-2J33WTMH-Bs5C1s4d.js → chunk-2J33WTMH-Bb8ett07.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-CZy1LXx9.js → chunk-4BX2VUAB-iYqRc8DE.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-Co6I8pB-.js → chunk-55IACEB6-Cy9_rMNz.js} +1 -1
- package/dist/assets/{chunk-727SXJPM-DxDXlkpg.js → chunk-727SXJPM-D2RDoxkl.js} +1 -1
- package/dist/assets/{chunk-AQP2D5EJ-qod4Kru_.js → chunk-AQP2D5EJ-C9ljIUFs.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-C6qOAGAs.js → chunk-FMBD7UC4-CKYxpqUz.js} +1 -1
- package/dist/assets/{chunk-ND2GUHAM-DjaQfaGS.js → chunk-ND2GUHAM-CUPVQZVT.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-BYfi764d.js → chunk-QZHKN3VN-yXXoELbr.js} +1 -1
- package/dist/assets/classDiagram-4FO5ZUOK-L76cvGeU.js +1 -0
- package/dist/assets/classDiagram-v2-Q7XG4LA2-L76cvGeU.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-HY4tbCTC.js → cose-bilkent-S5V4N54A-CWA_0N0H.js} +1 -1
- package/dist/assets/{dagre-BM42HDAG-DtXX4iAN.js → dagre-BM42HDAG-BZZ_-FiI.js} +1 -1
- package/dist/assets/{diagram-2AECGRRQ-CLdNcFtL.js → diagram-2AECGRRQ-DLHRroYK.js} +1 -1
- package/dist/assets/{diagram-5GNKFQAL-Bity3v2e.js → diagram-5GNKFQAL-CZdl5FSa.js} +1 -1
- package/dist/assets/{diagram-KO2AKTUF-C1vbvdwG.js → diagram-KO2AKTUF-BtWPLRdS.js} +1 -1
- package/dist/assets/{diagram-LMA3HP47-BQRDgHHR.js → diagram-LMA3HP47-CLxoy6hp.js} +1 -1
- package/dist/assets/{diagram-OG6HWLK6-qT7Wv79J.js → diagram-OG6HWLK6-Dl0w2KDh.js} +1 -1
- package/dist/assets/{erDiagram-TEJ5UH35-C1kW99o5.js → erDiagram-TEJ5UH35-DBuRVkAY.js} +1 -1
- package/dist/assets/{flowDiagram-I6XJVG4X-CfglcudW.js → flowDiagram-I6XJVG4X-DXQz-kf4.js} +1 -1
- package/dist/assets/{ganttDiagram-6RSMTGT7--EYdfWHs.js → ganttDiagram-6RSMTGT7-B41k7QIx.js} +1 -1
- package/dist/assets/{gitGraphDiagram-PVQCEYII-BS2saC0S.js → gitGraphDiagram-PVQCEYII-C3be0Zqb.js} +1 -1
- package/dist/assets/index-6cIIumPX.css +1 -0
- package/dist/assets/index-CsSwh12y.js +338 -0
- package/dist/assets/{infoDiagram-5YYISTIA-CCKIJ6sV.js → infoDiagram-5YYISTIA-CXWZZT08.js} +1 -1
- package/dist/assets/{ishikawaDiagram-YF4QCWOH-u6DxBGlc.js → ishikawaDiagram-YF4QCWOH-BAhxLFD3.js} +1 -1
- package/dist/assets/{journeyDiagram-JHISSGLW-C-Y5JUUR.js → journeyDiagram-JHISSGLW-BtrPWYSd.js} +1 -1
- package/dist/assets/{kanban-definition-UN3LZRKU-5BCiizns.js → kanban-definition-UN3LZRKU-HgK6G3Qc.js} +1 -1
- package/dist/assets/locales-UlLSBpcq.js +1 -0
- package/dist/assets/{mindmap-definition-RKZ34NQL-iwIoHMRz.js → mindmap-definition-RKZ34NQL-D_p6wIOe.js} +1 -1
- package/dist/assets/{pieDiagram-4H26LBE5-CyY7zxxk.js → pieDiagram-4H26LBE5-BXmH3v1p.js} +1 -1
- package/dist/assets/{quadrantDiagram-W4KKPZXB-CBaWNUYB.js → quadrantDiagram-W4KKPZXB-BUHlkfUj.js} +1 -1
- package/dist/assets/{requirementDiagram-4Y6WPE33-BSAv7n7j.js → requirementDiagram-4Y6WPE33-qNwh0OXU.js} +1 -1
- package/dist/assets/{sankeyDiagram-5OEKKPKP-DfnOqgCo.js → sankeyDiagram-5OEKKPKP-DRumfbAk.js} +1 -1
- package/dist/assets/{sequenceDiagram-3UESZ5HK-WIbh5T9q.js → sequenceDiagram-3UESZ5HK-Bw0fembF.js} +1 -1
- package/dist/assets/{stateDiagram-AJRCARHV-z7EKVH4m.js → stateDiagram-AJRCARHV-Dfp1Zpw1.js} +1 -1
- package/dist/assets/{stateDiagram-v2-BHNVJYJU-o-KrgMIT.js → stateDiagram-v2-BHNVJYJU-C7o3ypzf.js} +1 -1
- package/dist/assets/{timeline-definition-PNZ67QCA-s42V53sg.js → timeline-definition-PNZ67QCA-BszV9-Wj.js} +1 -1
- package/dist/assets/{vennDiagram-CIIHVFJN-Cwy5ycGh.js → vennDiagram-CIIHVFJN-BW9jnnvt.js} +1 -1
- package/dist/assets/{wardleyDiagram-YWT4CUSO-3liDEhCW.js → wardleyDiagram-YWT4CUSO-OF7Ta9nn.js} +1 -1
- package/dist/assets/{xychartDiagram-2RQKCTM6-CP6z4lZW.js → xychartDiagram-2RQKCTM6-BexL1-l4.js} +1 -1
- package/dist/index.html +3 -3
- package/package.json +1 -1
- package/dist/assets/channel-BxCKS2iL.js +0 -1
- package/dist/assets/classDiagram-4FO5ZUOK-uDDBf8Gl.js +0 -1
- package/dist/assets/classDiagram-v2-Q7XG4LA2-uDDBf8Gl.js +0 -1
- package/dist/assets/index-C9a-NIQu.js +0 -353
- package/dist/assets/index-CUN-rdx_.css +0 -1
- package/dist/assets/locales-DM19aNS7.js +0 -1
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MermaidRenderer-JnjJzSyx.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-DEfyMmV3.js","assets/locales-UlLSBpcq.js","assets/vendor-markdown-Cy_-N5ZX.js","assets/vendor-markdown-dRWncRqa.css","assets/vendor-auth-aD_bwYde.js","assets/ChartRenderer-BN_6aZ_Q.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-CHHA0796.js","assets/papaparse.min-D13ujVVP.js","assets/docx-preview-DehBmhog.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var cl=Object.defineProperty;var dl=(t,e,s)=>e in t?cl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var at=(t,e,s)=>dl(t,typeof e!="symbol"?e+"":e,s);import{r as m,j as n,a as ul,R as St,b as Qr,d as fl}from"./vendor-react-BbEy7z12.js";import{z as ml,p as hl,j as pl,f as gl,e as xl,a as bl,d as yl}from"./locales-UlLSBpcq.js";import{M as wl,r as En,a as kl,b as vl}from"./vendor-markdown-Cy_-N5ZX.js";import{_ as Ut,h as Sl,v as jl,a as Cl}from"./vendor-syntax-INF7-xC_.js";import{u as Ya,a as Qa,b as Al,P as Nl,M as Il,A as El}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"]'))r(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"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(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 r(a){if(a.ep)return;a.ep=!0;const i=s(a);fetch(a.href,i)}})();const Vi=m.createContext(void 0);function Ln({children:t}){const[e,s]=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}}),[r,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=>{s(l=>({...l,...o}))};return n.jsx(Vi.Provider,{value:{theme:e,updateTheme:i,isDark:r},children:t})}function ps(){const t=m.useContext(Vi);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}const qi=m.createContext(void 0),xa={voiceEnabled:!1,soundEnabled:!1,autoSend:!1};function Ll({children:t}){const[e,s]=m.useState(()=>{const a=localStorage.getItem("chat-settings");if(a)try{const i=JSON.parse(a);return{...xa,...i,voiceEnabled:!1}}catch{return xa}return xa});m.useEffect(()=>{localStorage.setItem("chat-settings",JSON.stringify(e))},[e]);const r=a=>{s(i=>({...i,...a}))};return n.jsx(qi.Provider,{value:{settings:e,updateSettings:r},children:t})}function Jr(){const t=m.useContext(qi);if(!t)throw new Error("useSettings must be used within SettingsProvider");return t}const be=t=>typeof t=="string",Us=()=>{let t,e;const s=new Promise((r,a)=>{t=r,e=a});return s.resolve=t,s.reject=e,s},_n=t=>t==null?"":String(t),_l=(t,e,s)=>{t.forEach(r=>{e[r]&&(s[r]=e[r])})},Tl=/###/g,Tn=t=>t&&t.includes("###")?t.replace(Tl,"."):t,Mn=t=>!t||be(t),Bs=(t,e,s)=>{const r=be(e)?e.split("."):e;let a=0;for(;a<r.length-1;){if(Mn(t))return{};const i=Tn(r[a]);!t[i]&&s&&(t[i]=new s),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++a}return Mn(t)?{}:{obj:t,k:Tn(r[a])}},Fn=(t,e,s)=>{const{obj:r,k:a}=Bs(t,e,Object);if(r!==void 0||e.length===1){r[a]=s;return}let i=e[e.length-1],o=e.slice(0,e.length-1),l=Bs(t,o,Object);for(;l.obj===void 0&&o.length;)i=`${o[o.length-1]}.${i}`,o=o.slice(0,o.length-1),l=Bs(t,o,Object),l!=null&&l.obj&&typeof l.obj[`${l.k}.${i}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${i}`]=s},Ml=(t,e,s,r)=>{const{obj:a,k:i}=Bs(t,e,Object);a[i]=a[i]||[],a[i].push(s)},Pr=(t,e)=>{const{obj:s,k:r}=Bs(t,e);if(s&&Object.prototype.hasOwnProperty.call(s,r))return s[r]},Fl=(t,e,s)=>{const r=Pr(t,s);return r!==void 0?r:Pr(e,s)},Wi=(t,e,s)=>{for(const r in e)r!=="__proto__"&&r!=="constructor"&&(Object.prototype.hasOwnProperty.call(t,r)?be(t[r])||t[r]instanceof String||be(e[r])||e[r]instanceof String?s&&(t[r]=e[r]):Wi(t[r],e[r],s):t[r]=e[r]);return t},qt=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),Rl={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"},$l=t=>be(t)?t.replace(/[&<>"'\/]/g,e=>Rl[e]):t;class Pl{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const s=this.regExpMap.get(e);if(s!==void 0)return s;const r=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,r),this.regExpQueue.push(e),r}}const Dl=[" ",",","?","!",";"],Ul=new Pl(20),Ol=(t,e,s)=>{e=e||"",s=s||"";const r=Dl.filter(o=>!e.includes(o)&&!s.includes(o));if(r.length===0)return!0;const a=Ul.getRegExp(`(${r.map(o=>o==="?"?"\\?":o).join("|")})`);let i=!a.test(t);if(!i){const o=t.indexOf(s);o>0&&!a.test(t.substring(0,o))&&(i=!0)}return i},Ta=(t,e,s=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const r=e.split(s);let a=t;for(let i=0;i<r.length;){if(!a||typeof a!="object")return;let o,l="";for(let c=i;c<r.length;++c)if(c!==i&&(l+=s),l+=r[c],o=a[l],o!==void 0){if(["string","number","boolean"].includes(typeof o)&&c<r.length-1)continue;i+=c-i+1;break}a=o}return a},Ws=t=>t==null?void 0:t.replace(/_/g,"-"),zl={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){var s,r;(r=(s=console==null?void 0:console[t])==null?void 0:s.apply)==null||r.call(s,console,e)}};class Dr{constructor(e,s={}){this.init(e,s)}init(e,s={}){this.prefix=s.prefix||"i18next:",this.logger=e||zl,this.options=s,this.debug=s.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,s,r,a){return a&&!this.debug?null:(e=e.map(i=>be(i)?i.replace(/[\r\n\x00-\x1F\x7F]/g," "):i),be(e[0])&&(e[0]=`${r}${this.prefix} ${e[0]}`),this.logger[s](e))}create(e){return new Dr(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Dr(this.logger,e)}}var Ot=new Dr;class Zr{constructor(){this.observers={}}on(e,s){return e.split(" ").forEach(r=>{this.observers[r]||(this.observers[r]=new Map);const a=this.observers[r].get(s)||0;this.observers[r].set(s,a+1)}),this}off(e,s){if(this.observers[e]){if(!s){delete this.observers[e];return}this.observers[e].delete(s)}}once(e,s){const r=(...a)=>{s(...a),this.off(e,r)};return this.on(e,r),this}emit(e,...s){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([a,i])=>{for(let o=0;o<i;o++)a(...s)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([a,i])=>{for(let o=0;o<i;o++)a(e,...s)})}}class Rn extends Zr{constructor(e,s={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=s,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.includes(e)||this.options.ns.push(e)}removeNamespaces(e){const s=this.options.ns.indexOf(e);s>-1&&this.options.ns.splice(s,1)}getResource(e,s,r,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,s],r&&(Array.isArray(r)?l.push(...r):be(r)&&i?l.push(...r.split(i)):l.push(r)));const c=Pr(this.data,l);return!c&&!s&&!r&&e.includes(".")&&(e=l[0],s=l[1],r=l.slice(2).join(".")),c||!o||!be(r)?c:Ta((u=(d=this.data)==null?void 0:d[e])==null?void 0:u[s],r,i)}addResource(e,s,r,a,i={silent:!1}){const o=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator;let l=[e,s];r&&(l=l.concat(o?r.split(o):r)),e.includes(".")&&(l=e.split("."),a=s,s=l[1]),this.addNamespaces(s),Fn(this.data,l,a),i.silent||this.emit("added",e,s,r,a)}addResources(e,s,r,a={silent:!1}){for(const i in r)(be(r[i])||Array.isArray(r[i]))&&this.addResource(e,s,i,r[i],{silent:!0});a.silent||this.emit("added",e,s,r)}addResourceBundle(e,s,r,a,i,o={silent:!1,skipCopy:!1}){let l=[e,s];e.includes(".")&&(l=e.split("."),a=r,r=s,s=l[1]),this.addNamespaces(s);let c=Pr(this.data,l)||{};o.skipCopy||(r=JSON.parse(JSON.stringify(r))),a?Wi(c,r,i):c={...c,...r},Fn(this.data,l,c),o.silent||this.emit("added",e,s,r)}removeResourceBundle(e,s){this.hasResourceBundle(e,s)&&delete this.data[e][s],this.removeNamespaces(s),this.emit("removed",e,s)}hasResourceBundle(e,s){return this.getResource(e,s)!==void 0}getResourceBundle(e,s){return s||(s=this.options.defaultNS),this.getResource(e,s)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const s=this.getDataByLanguage(e);return!!(s&&Object.keys(s)||[]).find(a=>s[a]&&Object.keys(s[a]).length>0)}toJSON(){return this.data}}var Ki={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,s,r,a){return t.forEach(i=>{var o;e=((o=this.processors[i])==null?void 0:o.process(e,s,r,a))??e}),e}};const Gi=Symbol("i18next/PATH_KEY");function Bl(){const t=[],e=Object.create(null);let s;return e.get=(r,a)=>{var i;return(i=s==null?void 0:s.revoke)==null||i.call(s),a===Gi?t:(t.push(a),s=Proxy.revocable(r,e),s.proxy)},Proxy.revocable(Object.create(null),e).proxy}function vs(t,e){const{[Gi]:s}=t(Bl()),r=(e==null?void 0:e.keySeparator)??".",a=(e==null?void 0:e.nsSeparator)??":",i=(e==null?void 0:e.enableSelector)==="strict";if(s.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(s[0]))return`${s[0]}${a}${s.slice(1).join(r)}`}return s.join(r)}const ba=t=>!be(t)&&typeof t!="boolean"&&typeof t!="number";class Ur extends Zr{constructor(e,s={}){super(),_l(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=s,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Ot.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,s={interpolation:{}}){const r={...s};if(e==null)return!1;const a=this.resolve(e,r);if((a==null?void 0:a.res)===void 0)return!1;const i=ba(a.res);return!(r.returnObjects===!1&&i)}extractFromKey(e,s){let r=s.nsSeparator!==void 0?s.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const a=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let i=s.ns||this.options.defaultNS||[];const o=r&&e.includes(r),l=!this.options.userDefinedKeySeparator&&!s.keySeparator&&!this.options.userDefinedNsSeparator&&!s.nsSeparator&&!Ol(e,r,a);if(o&&!l){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:be(i)?[i]:i};const d=e.split(r);(r!==a||r===a&&this.options.ns.includes(d[0]))&&(i=d.shift()),e=d.join(a)}return{key:e,namespaces:be(i)?[i]:i}}translate(e,s,r){let a=typeof s=="object"?{...s}:s;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=vs(e,{...this.options,...a})),Array.isArray(e)||(e=[String(e)]),e=e.map(O=>typeof O=="function"?vs(O,{...this.options,...a}):String(O));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,g=a.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if((f==null?void 0:f.toLowerCase())==="cimode")return g?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 p=this.resolve(e,a);let h=p==null?void 0:p.res;const x=(p==null?void 0:p.usedKey)||l,b=(p==null?void 0:p.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&&!be(a.count),v=Ur.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,C=y&&a[`defaultValue${this.options.pluralSeparator}zero`]||a[`defaultValue${M}`]||a[`defaultValue${F}`]||a.defaultValue;let I=h;E&&!h&&v&&(I=C);const N=ba(I),R=Object.prototype.toString.apply(I);if(E&&I&&N&&!k.includes(R)&&!(be(S)&&Array.isArray(I))){if(!a.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const O=this.options.returnedObjectHandler?this.options.returnedObjectHandler(x,I,{...a,ns:c}):`key '${l} (${this.language})' returned an object instead of string.`;return i?(p.res=O,p.usedParams=this.getUsedParamsDetails(a),p):O}if(o){const O=Array.isArray(I),X=O?[]:{},j=O?b:x;for(const L in I)if(Object.prototype.hasOwnProperty.call(I,L)){const B=`${j}${o}${L}`;v&&!h?X[L]=this.translate(B,{...a,defaultValue:ba(C)?C[L]:void 0,joinArrays:!1,ns:c}):X[L]=this.translate(B,{...a,joinArrays:!1,ns:c}),X[L]===B&&(X[L]=I[L])}h=X}}else if(E&&be(S)&&Array.isArray(h))h=h.join(S),h&&(h=this.extendTranslation(h,e,a,r));else{let O=!1,X=!1;!this.isValidLookup(h)&&v&&(O=!0,h=C),this.isValidLookup(h)||(X=!0,h=l);const L=(a.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&X?void 0:h,B=v&&C!==h&&this.options.updateMissing;if(X||O||B){if(this.logger.log(B?"updateKey":"missingKey",f,d,_&&!B?`${l}${this.pluralResolver.getSuffix(f,a.count,a)}`:l,B?C: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 A=[];const K=this.languageUtils.getFallbackCodes(this.options.fallbackLng,a.lng||this.language);if(this.options.saveMissingTo==="fallback"&&K&&K[0])for(let J=0;J<K.length;J++)A.push(K[J]);else this.options.saveMissingTo==="all"?A=this.languageUtils.toResolveHierarchy(a.lng||this.language):A.push(a.lng||this.language);const G=(J,q,H)=>{var T;const ne=v&&H!==h?H:L;this.options.missingKeyHandler?this.options.missingKeyHandler(J,d,q,ne,B,a):(T=this.backendConnector)!=null&&T.saveMissing&&this.backendConnector.saveMissing(J,d,q,ne,B,a),this.emit("missingKey",J,d,q,h)};this.options.saveMissing&&(this.options.saveMissingPlurals&&_?A.forEach(J=>{const q=this.pluralResolver.getSuffixes(J,a);y&&a[`defaultValue${this.options.pluralSeparator}zero`]&&!q.includes(`${this.options.pluralSeparator}zero`)&&q.push(`${this.options.pluralSeparator}zero`),q.forEach(H=>{G([J],l+H,a[`defaultValue${H}`]||C)})}):G(A,l,C))}h=this.extendTranslation(h,e,a,p,r),X&&h===l&&this.options.appendNamespaceToMissingKey&&(h=`${d}${u}${l}`),(X||O)&&this.options.parseMissingKeyHandler&&(h=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${l}`:l,O?h:void 0,a))}return i?(p.res=h,p.usedParams=this.getUsedParamsDetails(a),p):h}extendTranslation(e,s,r,a,i){var c,d;if((c=this.i18nFormat)!=null&&c.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||a.usedLng,a.usedNS,a.usedKey,{resolved:a});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const u=be(e)&&(((d=r==null?void 0:r.interpolation)==null?void 0:d.skipOnVariables)!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let f;if(u){const p=e.match(this.interpolator.nestingRegexp);f=p&&p.length}let g=r.replace&&!be(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(g={...this.options.interpolation.defaultVariables,...g}),e=this.interpolator.interpolate(e,g,r.lng||this.language||a.usedLng,r),u){const p=e.match(this.interpolator.nestingRegexp),h=p&&p.length;f<h&&(r.nest=!1)}!r.lng&&a&&a.res&&(r.lng=this.language||a.usedLng),r.nest!==!1&&(e=this.interpolator.nest(e,(...p)=>(i==null?void 0:i[0])===p[0]&&!r.context?(this.logger.warn(`It seems you are nesting recursively key: ${p[0]} in key: ${s[0]}`),null):this.translate(...p,s),r)),r.interpolation&&this.interpolator.reset()}const o=r.postProcess||this.options.postProcess,l=be(o)?[o]:o;return e!=null&&(l!=null&&l.length)&&r.applyPostProcessor!==!1&&(e=Ki.handle(l,e,s,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...a,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),e}resolve(e,s={}){let r,a,i,o,l;return be(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(c=>typeof c=="function"?vs(c,{...this.options,...s}):c)),e.forEach(c=>{if(this.isValidLookup(r))return;const d=this.extractFromKey(c,s),u=d.key;a=u;let f=d.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const g=s.count!==void 0&&!be(s.count),p=g&&!s.ordinal&&s.count===0,h=s.context!==void 0&&(be(s.context)||typeof s.context=="number")&&s.context!=="",x=s.lngs?s.lngs:this.languageUtils.toResolveHierarchy(s.lng||this.language,s.fallbackLng);f.forEach(b=>{var k,S;this.isValidLookup(r)||(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(r))return;o=E;const _=[u];if((M=this.i18nFormat)!=null&&M.addLookupKeys)this.i18nFormat.addLookupKeys(_,u,E,b,s);else{let F;g&&(F=this.pluralResolver.getSuffix(E,s.count,s));const y=`${this.options.pluralSeparator}zero`,C=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(g&&(s.ordinal&&F.startsWith(C)&&_.push(u+F.replace(C,this.options.pluralSeparator)),_.push(u+F),p&&_.push(u+y)),h){const I=`${u}${this.options.contextSeparator||"_"}${s.context}`;_.push(I),g&&(s.ordinal&&F.startsWith(C)&&_.push(I+F.replace(C,this.options.pluralSeparator)),_.push(I+F),p&&_.push(I+y))}}let v;for(;v=_.pop();)this.isValidLookup(r)||(i=v,r=this.getResource(E,b,v,s))}))})}),{res:r,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,s,r,a={}){var i;return(i=this.i18nFormat)!=null&&i.getResource?this.i18nFormat.getResource(e,s,r,a):this.resourceStore.getResource(e,s,r,a)}getUsedParamsDetails(e={}){const s=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=e.replace&&!be(e.replace);let a=r?e.replace:e;if(r&&typeof e.count<"u"&&(a.count=e.count),this.options.interpolation.defaultVariables&&(a={...this.options.interpolation.defaultVariables,...a}),!r){a={...a};for(const i of s)delete a[i]}return a}static hasDefaultValue(e){const s="defaultValue";for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&r.startsWith(s)&&e[r]!==void 0)return!0;return!1}}class $n{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Ot.create("languageUtils")}getScriptPartFromCode(e){if(e=Ws(e),!e||!e.includes("-"))return null;const s=e.split("-");return s.length===2||(s.pop(),s[s.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(s.join("-"))}getLanguagePartFromCode(e){if(e=Ws(e),!e||!e.includes("-"))return e;const s=e.split("-");return this.formatLanguageCode(s[0])}formatLanguageCode(e){if(be(e)&&e.includes("-")){let s;try{s=Intl.getCanonicalLocales(e)[0]}catch{}return s&&this.options.lowerCaseLng&&(s=s.toLowerCase()),s||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(e)}getBestMatchFromCodes(e){if(!e)return null;let s;return e.forEach(r=>{if(s)return;const a=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(a))&&(s=a)}),!s&&this.options.supportedLngs&&e.forEach(r=>{if(s)return;const a=this.getScriptPartFromCode(r);if(this.isSupportedCode(a))return s=a;const i=this.getLanguagePartFromCode(r);if(this.isSupportedCode(i))return s=i;s=this.options.supportedLngs.find(o=>o===i?!0:!o.includes("-")&&!i.includes("-")?!1:!!(o.includes("-")&&!i.includes("-")&&o.slice(0,o.indexOf("-"))===i||o.startsWith(i)&&i.length>1))}),s||(s=this.getFallbackCodes(this.options.fallbackLng)[0]),s}getFallbackCodes(e,s){if(!e)return[];if(typeof e=="function"&&(e=e(s)),be(e)&&(e=[e]),Array.isArray(e))return e;if(!s)return e.default||[];let r=e[s];return r||(r=e[this.getScriptPartFromCode(s)]),r||(r=e[this.formatLanguageCode(s)]),r||(r=e[this.getLanguagePartFromCode(s)]),r||(r=e.default),r||[]}toResolveHierarchy(e,s){const r=this.getFallbackCodes((s===!1?[]:s)||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 be(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))):be(e)&&i(this.formatLanguageCode(e)),r.forEach(o=>{a.includes(o)||i(this.formatLanguageCode(o))}),a}}const Pn={zero:0,one:1,two:2,few:3,many:4,other:5},Dn={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Hl{constructor(e,s={}){this.languageUtils=e,this.options=s,this.logger=Ot.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,s={}){const r=Ws(e==="dev"?"en":e),a=s.ordinal?"ordinal":"cardinal",i=JSON.stringify({cleanedCode:r,type:a});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let o;try{o=new Intl.PluralRules(r,{type:a})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Dn;if(!e.match(/-|_/))return Dn;const c=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(c,s)}return this.pluralRulesCache[i]=o,o}needsPlural(e,s={}){let r=this.getRule(e,s);return r||(r=this.getRule("dev",s)),(r==null?void 0:r.resolvedOptions().pluralCategories.length)>1}getPluralFormsOfKey(e,s,r={}){return this.getSuffixes(e,r).map(a=>`${s}${a}`)}getSuffixes(e,s={}){let r=this.getRule(e,s);return r||(r=this.getRule("dev",s)),r?r.resolvedOptions().pluralCategories.sort((a,i)=>Pn[a]-Pn[i]).map(a=>`${this.options.prepend}${s.ordinal?`ordinal${this.options.prepend}`:""}${a}`):[]}getSuffix(e,s,r={}){const a=this.getRule(e,r);return a?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${a.select(s)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",s,r))}}const Un=(t,e,s,r=".",a=!0)=>{let i=Fl(t,e,s);return!i&&a&&be(s)&&(i=Ta(t,s,r),i===void 0&&(i=Ta(e,s,r))),i},ya=t=>t.replace(/\$/g,"$$$$");class On{constructor(e={}){var s;this.logger=Ot.create("interpolator"),this.options=e,this.format=((s=e==null?void 0:e.interpolation)==null?void 0:s.format)||(r=>r),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:s,escapeValue:r,useRawValueToEscape:a,prefix:i,prefixEscaped:o,suffix:l,suffixEscaped:c,formatSeparator:d,unescapeSuffix:u,unescapePrefix:f,nestingPrefix:g,nestingPrefixEscaped:p,nestingSuffix:h,nestingSuffixEscaped:x,nestingOptionsSeparator:b,maxReplaces:k,alwaysFormat:S}=e.interpolation;this.escape=s!==void 0?s:$l,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=a!==void 0?a:!1,this.prefix=i?qt(i):o||"{{",this.suffix=l?qt(l):c||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":f?qt(f):"-",this.unescapeSuffix=this.unescapePrefix?"":u?qt(u):"",this.nestingPrefix=g?qt(g):p||qt("$t("),this.nestingSuffix=h?qt(h):x||qt(")"),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=(s,r)=>(s==null?void 0:s.source)===r?(s.lastIndex=0,s):new RegExp(r,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,s,r,a){var p;let i,o,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=h=>{if(!h.includes(this.formatSeparator)){const S=Un(s,c,h,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(S,void 0,r,{...a,...s,interpolationkey:h}):S}const x=h.split(this.formatSeparator),b=x.shift().trim(),k=x.join(this.formatSeparator).trim();return this.format(Un(s,c,b,this.options.keySeparator,this.options.ignoreJSONStructure),k,r,{...a,...s,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=((p=a==null?void 0:a.interpolation)==null?void 0:p.skipOnVariables)!==void 0?a.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:h=>ya(h)},{regex:this.regexp,safeValue:h=>this.escapeValue?ya(this.escape(h)):ya(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=be(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!be(o)&&!this.useRawValueToEscape&&(o=_n(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,s,r={}){let a,i,o;const l=(c,d)=>{const u=this.nestingOptionsSeparator;if(!c.includes(u))return c;const f=c.split(new RegExp(`${qt(u)}[ ]*{`));let g=`{${f[1]}`;c=f[0],g=this.interpolate(g,o);const p=g.match(/'/g),h=g.match(/"/g);(((p==null?void 0:p.length)??0)%2===0&&!h||((h==null?void 0:h.length)??0)%2!==0)&&(g=g.replace(/'/g,'"'));try{o=JSON.parse(g),d&&(o={...d,...o})}catch(x){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,x),`${c}${u}${g}`}return o.defaultValue&&o.defaultValue.includes(this.prefix)&&delete o.defaultValue,c};for(;a=this.nestingRegexp.exec(e);){let c=[];o={...r},o=o.replace&&!be(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=s(l.call(this,a[1].trim(),o),o),i&&a[0]===e&&!be(i))return i;be(i)||(i=_n(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,r.lng,{...r,interpolationkey:a[1].trim()}),i.trim())),e=e.replace(a[0],i),this.regexp.lastIndex=0}return e}}const Vl=t=>{let e=t.toLowerCase().trim();const s={};if(t.includes("(")){const r=t.split("(");e=r[0].toLowerCase().trim();const a=r[1].slice(0,-1);e==="currency"&&!a.includes(":")?s.currency||(s.currency=a.trim()):e==="relativetime"&&!a.includes(":")?s.range||(s.range=a.trim()):a.split(";").forEach(o=>{if(o){const[l,...c]=o.split(":"),d=c.join(":").trim().replace(/^'+|'+$/g,""),u=l.trim();s[u]||(s[u]=d),d==="false"&&(s[u]=!1),d==="true"&&(s[u]=!0),isNaN(d)||(s[u]=parseInt(d,10))}})}return{formatName:e,formatOptions:s}},zn=t=>{const e={};return(s,r,a)=>{let i=a;a&&a.interpolationkey&&a.formatParams&&a.formatParams[a.interpolationkey]&&a[a.interpolationkey]&&(i={...i,[a.interpolationkey]:void 0});const o=r+JSON.stringify(i);let l=e[o];return l||(l=t(Ws(r),a),e[o]=l),l(s)}},ql=t=>(e,s,r)=>t(Ws(s),r)(e);class Wl{constructor(e={}){this.logger=Ot.create("formatter"),this.options=e,this.init(e)}init(e,s={interpolation:{}}){this.formatSeparator=s.interpolation.formatSeparator||",";const r=s.cacheInBuiltFormats?zn:ql;this.formats={number:r((a,i)=>{const o=new Intl.NumberFormat(a,{...i});return l=>o.format(l)}),currency:r((a,i)=>{const o=new Intl.NumberFormat(a,{...i,style:"currency"});return l=>o.format(l)}),datetime:r((a,i)=>{const o=new Intl.DateTimeFormat(a,{...i});return l=>o.format(l)}),relativetime:r((a,i)=>{const o=new Intl.RelativeTimeFormat(a,{...i});return l=>o.format(l,i.range||"day")}),list:r((a,i)=>{const o=new Intl.ListFormat(a,{...i});return l=>o.format(l)})}}add(e,s){this.formats[e.toLowerCase().trim()]=s}addCached(e,s){this.formats[e.toLowerCase().trim()]=zn(s)}format(e,s,r,a={}){if(!s||e==null)return e;const i=s.split(this.formatSeparator),o=[];for(let c=0;c<i.length;c++){let d=i[c];for(;d.indexOf("(")>-1&&!d.includes(")")&&c+1<i.length;)d=`${d}${this.formatSeparator}${i[++c]}`;o.push(d)}return o.reduce((c,d)=>{var g;const{formatName:u,formatOptions:f}=Vl(d);if(this.formats[u]){let p=c;try{const h=((g=a==null?void 0:a.formatParams)==null?void 0:g[a.interpolationkey])||{},x=h.locale||h.lng||a.locale||a.lng||r;p=this.formats[u](c,x,{...f,...a,...h})}catch(h){this.logger.warn(h)}return p}else this.logger.warn(`there was no format function for ${u}`);return c},e)}}const Kl=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Gl extends Zr{constructor(e,s,r,a={}){var i,o;super(),this.backend=e,this.store=s,this.services=r,this.languageUtils=r.languageUtils,this.options=a,this.logger=Ot.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,r,a.backend,a)}queueLoad(e,s,r,a){const i={},o={},l={},c={};return e.forEach(d=>{let u=!0;s.forEach(f=>{const g=`${d}|${f}`;!r.reload&&this.store.hasResourceBundle(d,f)?this.state[g]=2:this.state[g]<0||(this.state[g]===1?o[g]===void 0&&(o[g]=!0):(this.state[g]=1,u=!1,o[g]===void 0&&(o[g]=!0),i[g]===void 0&&(i[g]=!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,s,r){const a=e.split("|"),i=a[0],o=a[1];s&&this.emit("failedLoading",i,o,s),!s&&r&&this.store.addResourceBundle(i,o,r,void 0,void 0,{skipCopy:!0}),this.state[e]=s?-1:2,s&&r&&(this.state[e]=0);const l={};this.queue.forEach(c=>{Ml(c.loaded,[i],o),Kl(c,e),s&&c.errors.push(s),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(d=>{l[d]||(l[d]={});const u=c.loaded[d];u.length&&u.forEach(f=>{l[d][f]===void 0&&(l[d][f]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",l),this.queue=this.queue.filter(c=>!c.done)}read(e,s,r,a=0,i=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:s,fcName:r,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,s,r,a+1,i*2,o)},i);return}o(d,u)},c=this.backend[r].bind(this.backend);if(c.length===2){try{const d=c(e,s);d&&typeof d.then=="function"?d.then(u=>l(null,u)).catch(l):l(null,d)}catch(d){l(d)}return}return c(e,s,l)}prepareLoading(e,s,r={},a){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),a&&a();be(e)&&(e=this.languageUtils.toResolveHierarchy(e)),be(s)&&(s=[s]);const i=this.queueLoad(e,s,r,a);if(!i.toLoad.length)return i.pending.length||a(),null;i.toLoad.forEach(o=>{this.loadOne(o)})}load(e,s,r){this.prepareLoading(e,s,{},r)}reload(e,s,r){this.prepareLoading(e,s,{reload:!0},r)}loadOne(e,s=""){const r=e.split("|"),a=r[0],i=r[1];this.read(a,i,"read",void 0,void 0,(o,l)=>{o&&this.logger.warn(`${s}loading namespace ${i} for language ${a} failed`,o),!o&&l&&this.logger.log(`${s}loaded namespace ${i} for language ${a}`,l),this.loaded(e,o,l)})}saveMissing(e,s,r,a,i,o={},l=()=>{}){var c,d,u,f,g;if((d=(c=this.services)==null?void 0:c.utils)!=null&&d.hasLoadedNamespace&&!((f=(u=this.services)==null?void 0:u.utils)!=null&&f.hasLoadedNamespace(s))){this.logger.warn(`did not save key "${r}" as the namespace "${s}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if((g=this.backend)!=null&&g.create){const p={...o,isUpdate:i},h=this.backend.create.bind(this.backend);if(h.length<6)try{let x;h.length===5?x=h(e,s,r,a,p):x=h(e,s,r,a),x&&typeof x.then=="function"?x.then(b=>l(null,b)).catch(l):l(null,x)}catch(x){l(x)}else h(e,s,r,a,l,p)}!e||!e[0]||this.store.addResource(e[0],s,r,a)}}}const wa=()=>({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]),be(t[1])&&(e.defaultValue=t[1]),be(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const s=t[3]||t[2];Object.keys(s).forEach(r=>{e[r]=s[r]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),Bn=t=>(be(t.ns)&&(t.ns=[t.ns]),be(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),be(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs&&!t.supportedLngs.includes("cimode")&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),t),wr=()=>{},Xl=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(s=>{typeof t[s]=="function"&&(t[s]=t[s].bind(t))})};class Hs extends Zr{constructor(e={},s){if(super(),this.options=Bn(e),this.services={},this.logger=Ot,this.modules={external:[]},Xl(this),s&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,s),this;setTimeout(()=>{this.init(e,s)},0)}}init(e={},s){this.isInitializing=!0,typeof e=="function"&&(s=e,e={}),e.defaultNS==null&&e.ns&&(be(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const r=wa();this.options={...r,...this.options,...Bn(e)},this.options.interpolation={...r.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=r.overloadTranslationOptionHandler);const a=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?Ot.init(a(this.modules.logger),this.options):Ot.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=Wl;const u=new $n(this.options);this.store=new Rn(this.options.resources,this.options);const f=this.services;f.logger=Ot,f.resourceStore=this.store,f.languageUtils=u,f.pluralResolver=new Hl(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 On(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new Gl(a(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(g,...p)=>{this.emit(g,...p)}),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 Ur(this.services,this.options),this.translator.on("*",(g,...p)=>{this.emit(g,...p)}),this.modules.external.forEach(g=>{g.init&&g.init(this)})}if(this.format=this.options.interpolation.format,s||(s=wr),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=Us(),c=()=>{const d=(u,f)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),l.resolve(f),s(u,f)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),l}loadResources(e,s=wr){var i,o;let r=s;const a=be(e)?e:this.language;if(typeof e=="function"&&(r=e),!this.options.resources||this.options.partialBundledLanguages){if((a==null?void 0:a.toLowerCase())==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();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),r(d)})}else r(null)}reloadResources(e,s,r){const a=Us();return typeof e=="function"&&(r=e,e=void 0),typeof s=="function"&&(r=s,s=void 0),e||(e=this.languages),s||(s=this.options.ns),r||(r=wr),this.services.backendConnector.reload(e,s,i=>{a.resolve(),r(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"&&Ki.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!["cimode","dev"].includes(e)){for(let s=0;s<this.languages.length;s++){const r=this.languages[s];if(!["cimode","dev"].includes(r)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,s){this.isLanguageChangingTo=e;const r=Us();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,r.resolve((...d)=>this.t(...d)),s&&s(l,(...d)=>this.t(...d))},o=l=>{var u,f;!e&&!l&&this.services.languageDetector&&(l=[]);const c=be(l)?l:l&&l[0],d=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(be(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,g=>{i(g,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),r}getFixedT(e,s,r,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||r||o.keyPrefix);const g={...this.options,...u};Array.isArray(i)&&!f&&(g.ns=i),typeof u.keyPrefix=="function"&&(u.keyPrefix=vs(u.keyPrefix,g));const p=this.options.keySeparator||".";let h;return u.keyPrefix&&Array.isArray(l)?h=l.map(x=>(typeof x=="function"&&(x=vs(x,g)),`${u.keyPrefix}${p}${x}`)):(typeof l=="function"&&(l=vs(l,g)),h=u.keyPrefix?`${u.keyPrefix}${p}${l}`:l),this.t(h,u)};return be(e)?o.lng=e:o.lngs=e,o.ns=s,o.keyPrefix=r,o}t(...e){var s;return(s=this.translator)==null?void 0:s.translate(...e)}exists(...e){var s;return(s=this.translator)==null?void 0:s.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,s={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=s.lng||this.resolvedLanguage||this.languages[0],a=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const o=(l,c)=>{const d=this.services.backendConnector.state[`${l}|${c}`];return d===-1||d===0||d===2};if(s.precheck){const l=s.precheck(this,o);if(l!==void 0)return l}return!!(this.hasResourceBundle(r,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(r,e)&&(!a||o(i,e)))}loadNamespaces(e,s){const r=Us();return this.options.ns?(be(e)&&(e=[e]),e.forEach(a=>{this.options.ns.includes(a)||this.options.ns.push(a)}),this.loadResources(a=>{r.resolve(),s&&s(a)}),r):(s&&s(),Promise.resolve())}loadLanguages(e,s){const r=Us();be(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=>{r.resolve(),s&&s(o)}),r):(s&&s(),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 s=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=((i=this.services)==null?void 0:i.languageUtils)||new $n(wa());return e.toLowerCase().indexOf("-latn")>1?"ltr":s.includes(r.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},s){const r=new Hs(e,s);return r.createInstance=Hs.createInstance,r}cloneInstance(e={},s=wr){const r=e.forkResourceStore;r&&delete e.forkResourceStore;const a={...this.options,...e,isClone:!0},i=new Hs(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)},r){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 Rn(l,a),i.services.resourceStore=i.store}if(e.interpolation){const c={...wa().interpolation,...this.options.interpolation,...e.interpolation},d={...a,interpolation:c};i.services.interpolator=new On(d)}return i.translator=new Ur(i.services,a),i.translator.on("*",(l,...c)=>{i.emit(l,...c)}),i.init(a,s),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=Hs.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 Yl=(t,e,s,r)=>{var i,o,l,c;const a=[s,{code:e,...r||{}}];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);hs(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)},Hn={},Ma=(t,e,s,r)=>{hs(s)&&Hn[s]||(hs(s)&&(Hn[s]=new Date),Yl(t,e,s,r))},Xi=(t,e)=>()=>{if(t.isInitialized)e();else{const s=()=>{setTimeout(()=>{t.off("initialized",s)},0),e()};t.on("initialized",s)}},Fa=(t,e,s)=>{t.loadNamespaces(e,Xi(t,s))},Vn=(t,e,s,r)=>{if(hs(s)&&(s=[s]),t.options.preload&&t.options.preload.indexOf(e)>-1)return Fa(t,s,r);s.forEach(a=>{t.options.ns.indexOf(a)<0&&t.options.ns.push(a)}),t.loadLanguages(e,Xi(t,r))},Ql=(t,e,s={})=>!e.languages||!e.languages.length?(Ma(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(t,{lng:s.lng,precheck:(r,a)=>{if(s.bindI18n&&s.bindI18n.indexOf("languageChanging")>-1&&r.services.backendConnector.backend&&r.isLanguageChangingTo&&!a(r.isLanguageChangingTo,t))return!1}}),hs=t=>typeof t=="string",Jl=t=>typeof t=="object"&&t!==null,Zl=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,ec={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},tc=t=>ec[t],sc=t=>t.replace(Zl,tc);let Ra={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:sc,transDefaultProps:void 0};const rc=(t={})=>{Ra={...Ra,...t}},ac=()=>Ra;let Yi;const nc=t=>{Yi=t},ic=()=>Yi,oc={type:"3rdParty",init(t){rc(t.options.react),nc(t)}},lc=m.createContext();class cc{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(s=>{this.usedNamespaces[s]||(this.usedNamespaces[s]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var ka={exports:{}},va={};/**
|
|
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 qn;function dc(){if(qn)return va;qn=1;var t=ul();function e(f,g){return f===g&&(f!==0||1/f===1/g)||f!==f&&g!==g}var s=typeof Object.is=="function"?Object.is:e,r=t.useState,a=t.useEffect,i=t.useLayoutEffect,o=t.useDebugValue;function l(f,g){var p=g(),h=r({inst:{value:p,getSnapshot:g}}),x=h[0].inst,b=h[1];return i(function(){x.value=p,x.getSnapshot=g,c(x)&&b({inst:x})},[f,p,g]),a(function(){return c(x)&&b({inst:x}),f(function(){c(x)&&b({inst:x})})},[f]),o(p),p}function c(f){var g=f.getSnapshot;f=f.value;try{var p=g();return!s(f,p)}catch{return!0}}function d(f,g){return g()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:l;return va.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:u,va}var Wn;function uc(){return Wn||(Wn=1,ka.exports=dc()),ka.exports}var fc=uc();const mc=(t,e)=>{if(hs(e))return e;if(Jl(e)&&hs(e.defaultValue))return e.defaultValue;if(typeof t=="function")return"";if(Array.isArray(t)){const s=t[t.length-1];return typeof s=="function"?"":s}return t},hc={t:mc,ready:!1},pc=()=>()=>{},Le=(t,e={})=>{var C,I,N;const{i18n:s}=e,{i18n:r,defaultNS:a}=m.useContext(lc)||{},i=s||r||ic();i&&!i.reportNamespaces&&(i.reportNamespaces=new cc),i||Ma(i,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=m.useMemo(()=>{var R;return{...ac(),...(R=i==null?void 0:i.options)==null?void 0:R.react,...e}},[i,e]),{useSuspense:l,keyPrefix:c}=o,d=a||((C=i==null?void 0:i.options)==null?void 0:C.defaultNS),u=hs(d)?[d]:d||["translation"],f=m.useMemo(()=>u,u);(N=(I=i==null?void 0:i.reportNamespaces)==null?void 0:I.addUsedNamespaces)==null||N.call(I,f);const g=m.useRef(0),p=m.useCallback(R=>{if(!i)return pc;const{bindI18n:O,bindI18nStore:X}=o,j=()=>{g.current+=1,R()};return O&&i.on(O,j),X&&i.store.on(X,j),()=>{O&&O.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 hc;const R=!!(i.isInitialized||i.initializedStoreOnce)&&f.every(A=>Ql(A,i,o)),O=e.lng||i.language,X=g.current,j=h.current;if(j&&j.ready===R&&j.lng===O&&j.keyPrefix===c&&j.revision===X)return j;const B={t:i.getFixedT(O,o.nsMode==="fallback"?f:f[0],c,{scopeNs:f}),ready:R,lng:O,keyPrefix:c,revision:X};return h.current=B,B},[i,f,c,o,e.lng]),[b,k]=m.useState(0),{t:S,ready:E}=fc.useSyncExternalStore(p,x,x);m.useEffect(()=>{if(i&&!E&&!l){const R=()=>k(O=>O+1);e.lng?Vn(i,e.lng,f,R):Fa(i,f,R)}},[i,e.lng,f,E,l,b]);const _=i||{},v=m.useRef(null),M=m.useRef(),F=R=>{const O=Object.getOwnPropertyDescriptors(R);O.__original&&delete O.__original;const X=Object.create(Object.getPrototypeOf(R),O);if(!Object.prototype.hasOwnProperty.call(X,"__original"))try{Object.defineProperty(X,"__original",{value:R,writable:!1,enumerable:!1,configurable:!1})}catch{}return X},y=m.useMemo(()=>{const R=_,O=R==null?void 0:R.language;let X=R;R&&(v.current&&v.current.__original===R?M.current!==O?(X=F(R),v.current=X,M.current=O):X=v.current:(X=F(R),v.current=X,M.current=O));const j=!E&&!l?(...B)=>(Ma(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(R=>{const O=()=>R();e.lng?Vn(i,e.lng,f,O):Fa(i,f,O)});return y},gc={de:{translation:yl},en:{translation:bl},es:{translation:xl},fr:{translation:gl},ja:{translation:pl},pt:{translation:hl},zh:{translation:ml}};Je.use(oc).init({resources:gc,lng:"en",fallbackLng:"en",interpolation:{escapeValue:!1},returnNull:!1});var xc={agentMode:{mode:"multi",defaultAdapterId:"simple-chat"},application:{name:"ORBIT Chat",description:"Explore ideas with [ORBIT](https://github.com/schmitech/orbit) 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:500}},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). [Example source](https://github.com/schmitech/orbit/blob/main/examples/prompts/examples/default-conversational-adapter-prompt.md) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/passthrough.yaml)",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 support. [Example source](https://github.com/schmitech/orbit/blob/main/examples/prompts/examples/default-conversational-adapter-prompt.md) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/web-search.yaml)",inputPlaceholder:"Simple chat, ask anything..."},{id:"chat-with-files",name:"Simple AI Chat (Multimodal)",apiUrl:"http://localhost:3000",description:"Extract knowledge from PDFs, images, Word files, and more (similar to ChatGPT Multimodal). [Example prompt](https://github.com/schmitech/orbit/blob/main/examples/prompts/examples/default-file-adapter-prompt.md) · [Sample files](https://github.com/schmitech/orbit/tree/main/examples/sample-files) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/multimodal.yaml)",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. [Example source](https://github.com/schmitech/orbit/blob/main/examples/prompts/examples/default-image-generator-prompt.md) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/image-generator.yaml)",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. [Example source](https://github.com/schmitech/orbit/blob/main/examples/prompts/examples/default-video-generator-prompt.md) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/video-generator.yaml)",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. [Example source](https://github.com/schmitech/orbit/blob/main/examples/city-qa-pairs.json) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/qa.yaml)",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. [Example source](https://github.com/schmitech/orbit/blob/main/examples/city-qa-pairs.json) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/qa.yaml)",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. [Example source](https://github.com/schmitech/orbit/tree/main/examples/intent-templates/sql-intent-template/sqlite/hr) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/hr.yaml)",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. [Example source](https://github.com/schmitech/orbit/tree/main/examples/intent-templates/sql-intent-template/postgres/customer-orders) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/customer-orders.yaml)"},{id:"mcp-business-sample",name:"Business & Revenue Intelligence (MCP)",apiUrl:"http://localhost:3000",description:"Real-time B2B revenue intelligence via MCP tools: analyze customer health, pipelines, product telemetry, support tickets, and churn risk. [Example source](https://github.com/schmitech/orbit/tree/main/examples/mcp-server) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/mcp-agent.yaml)",inputPlaceholder:"Ask about customers, revenue, support tickets, or telemetry..."},{id:"ecomm-analytics",name:"Business Analytics Assistant",apiUrl:"http://localhost:3000",description:"DuckDB analytics assistant: natural language analytics queries over the analytics demo. [Example source](https://github.com/schmitech/orbit/tree/main/examples/intent-templates/duckdb-intent-template/examples/analytics) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/business-analytics.yaml)"},{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. [Example prompt](https://github.com/schmitech/orbit/tree/main/examples/prompts/examples/composite) · [Cross-source templates](https://github.com/schmitech/orbit/tree/main/examples/intent-templates/cross-adapter-template) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/composite.yaml)",inputPlaceholder:"Ask about employees, orders, or sales analytics..."},{id:"intent-duckdb-ev-population",name:"WA State Electric Vehicles Population",apiUrl:"http://localhost:3000",description:"EV population assistant: Washington State BEV/PHEV vehicle data via DuckDB intent templates. [Example source](https://github.com/schmitech/orbit/tree/main/examples/intent-templates/duckdb-intent-template/examples/ev-population) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/ev.yaml)"},{id:"intent-http-jsonplaceholder",name:"REST API Chat",apiUrl:"http://localhost:3000",description:"Natural language queries over the fake REST API. [Example source](https://github.com/schmitech/orbit/tree/main/examples/intent-templates/http-intent-template/examples/jsonplaceholder) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/intent.yaml)"},{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. [Example source](https://github.com/schmitech/orbit/tree/main/examples/intent-templates/http-intent-template/examples/paris-open-data) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/intent.yaml)"},{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. [Example source](https://github.com/schmitech/orbit/tree/main/examples/intent-templates/mongodb-intent-template/sample_mflix) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/mongodb-mflix.yaml)"},{id:"intent-graphql-spacex",name:"GraphQL Chatbot",apiUrl:"http://localhost:3000",description:"SpaceX GraphQL assistant: natural language queries over the SpaceX API. [Example source](https://github.com/schmitech/orbit/tree/main/examples/intent-templates/graphql-intent-template/examples/spacex) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/intent.yaml)",inputPlaceholder:"Ask SpaceX questions..."},{id:"audio-transcription",name:"Audio Transcription",apiUrl:"http://localhost:3000",description:"Audio transcription test. [Example source](https://github.com/schmitech/orbit/blob/main/examples/prompts/audio/audio-transcription-prompt.md) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/audio.yaml)",inputPlaceholder:"Use the microphone for voice..."},{id:"voice-chat",name:"Voice Chat",apiUrl:"http://localhost:3000",description:"Voice chat adapter test. [Example source](https://github.com/schmitech/orbit/blob/main/examples/prompts/audio/voice-chat-prompt.md) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/audio.yaml)",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. [Example source](https://github.com/schmitech/orbit/tree/main/examples/intent-templates/elasticsearch-intent-template/application-logs) · [Adapter config](https://github.com/schmitech/orbit/blob/main/config/adapters/elasticsearch-logs.yaml)"}]};const $a="http://localhost:3000",bc="/favicon.svg",yc="/orbit-logo-light.png",wc="/orbit-logo-dark.png",kc={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 kr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Pa(t,e){if(!kr(t)||!kr(e))return e;const s={...t};return Object.keys(e).forEach(r=>{if(r==="__proto__"||r==="constructor"||r==="prototype")return;const a=s[r],i=e[r];kr(a)&&kr(i)?s[r]=Pa(a,i):i!==void 0&&(s[r]=i)}),s}function vc(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;const s=e.toLowerCase();return s==="false"||s==="0"||s==="off"||s==="disabled"?null:e}function Sc(t){return t==="single"?"single":"multi"}function jc(t){const e=t.trim();if(e.startsWith("["))try{const s=JSON.parse(e);return Array.isArray(s)?s.filter(Boolean):[]}catch{return[]}return e.split(/\s+/).filter(Boolean)}function Cc(){const t=xc||{},e=typeof window<"u"&&window.ORBIT_CHAT_CONFIG||{},s=!!(typeof window<"u"&&window.ORBIT_CHAT_CONFIG);let r=Pa(kc,t);return r=Pa(r,e),(!s||!r.auth.domain)&&(r.auth.domain="dev-3c4dpzhecz4gundm.us.auth0.com"),(!s||!r.auth.clientId)&&(r.auth.clientId="9JSe5xtoi5mLXRuov2K7FHYU10ojCQLH"),!s||r.auth.audience,!s||r.auth.provider,!s||r.auth.tenantId,(!s||r.auth.scopes.length===0)&&(r.auth.scopes=jc("openid profile email User.Read")),r.outOfServiceMessage=vc(r.outOfServiceMessage),r.agentMode.mode=Sc(r.agentMode.mode),r.agentMode.defaultAdapterId=typeof r.agentMode.defaultAdapterId=="string"?r.agentMode.defaultAdapterId.trim():"",r}const te=Cc();function $e(){var e;const t=te.adapters;if(Array.isArray(t)&&t.length>0){const s=(e=t[0].apiUrl)==null?void 0:e.trim();if(s)return s}return $a}function dt(t){const e=t==null?void 0:t.trim();return e&&e.length>0?e:$e()}function Ac(){const t=te.adapters;return Array.isArray(t)&&t.length>0?t[0].id:"default-key"}function Nc(){return te.agentMode.mode}function ea(){return Nc()==="single"}function Ja(){if(!ea())return null;const t=te.agentMode.defaultAdapterId;return t&&te.adapters.some(s=>{var r;return((r=s==null?void 0:s.id)==null?void 0:r.trim())===t})?t:null}function Qi(){const t=Array.isArray(te.i18n.activeLanguages)?te.i18n.activeLanguages.filter(e=>typeof e=="string"):[];return t.length>0?t:["en"]}function Ic(){var e;const t=(e=te.i18n.defaultLanguage)==null?void 0:e.trim();return t&&Qi().includes(t)?t:"en"}function Za(){return te.application.name}function en(){return te.application.description}function Ji(){return te.application.inputPlaceholder}function Kn(t){var a;const e=t==null?void 0:t.trim();if(!e)return null;const s=te.adapters.find(i=>{var o;return((o=i==null?void 0:i.id)==null?void 0:o.trim())===e});return((a=s==null?void 0:s.name)==null?void 0:a.trim())||null}function Ec(t){var a;const e=t==null?void 0:t.trim();if(!e)return null;const s=te.adapters.find(i=>{var o;return((o=i==null?void 0:i.id)==null?void 0:o.trim())===e});return((a=s==null?void 0:s.inputPlaceholder)==null?void 0:a.trim())||null}function Lc(t){const e=t==null?void 0:t.trim();return!!(e&&te.adapters.some(s=>{var r;return((r=s==null?void 0:s.id)==null?void 0:r.trim())===e&&s.realtimeVoice===!0}))}function Zi(){return te.seo.siteUrl.trim()}function _c(){return Array.isArray(te.seo.alternateSiteUrls)?te.seo.alternateSiteUrls.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function Tc(){return Array.isArray(te.seo.hostPatterns)?te.seo.hostPatterns.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function Mc(){return te.seo.exposeAgentNotes}function Fc(){var e;return((e=te.application.favicon)==null?void 0:e.trim())||bc}function Rc(){return te.features.enableUpload}function $c(){return te.features.enableAudioOutput}function Pc(){return te.features.enableAudioInput}function vr(){return te.features.enableFeedbackButtons}function Dc(){return te.features.enableConversationThreads}function eo(){return te.features.enableAutocomplete}function Uc(){return Math.max(1e3,te.voice.silenceTimeoutMs)}function Oc(){return te.voice.recognitionLanguage}function zc(){const t=Ja();if(t)return t;const e=te.adapters;if(Array.isArray(e)&&e.length>0)for(const s of e){const r=typeof(s==null?void 0:s.id)=="string"?s.id.trim():"";if(r)return r}return null}function Bc(){return te.outOfServiceMessage}function tn(){return te.auth.enabled}function it(){const{enabled:t,provider:e,domain:s,clientId:r,tenantId:a}=te.auth;return!t||!r?!1:e==="entra"?!!a:!!s}function Hc(){return te.auth.domain}function to(){return te.auth.clientId}function Vc(){return te.auth.audience}function ta(){return te.auth.provider}function qc(){return te.auth.tenantId}function sn(){const t=te.auth.scopes;return t.length>0?t:["openid","profile","email"]}function Da(){return te.header.enabled}function Wc(){return te.header.logoUrl}function Kc(){var e;return((e=te.header.logoUrlLight)==null?void 0:e.trim())||yc}function Gc(){var e;return((e=te.header.logoUrlDark)==null?void 0:e.trim())||wc}function Xc(){var t;return((t=te.header.logoHeight)==null?void 0:t.trim())||""}function Yc(){var t;return((t=te.header.logoWidth)==null?void 0:t.trim())||""}function Qc(){return te.header.bgColor}function Jc(){return te.header.textColor}function Zc(){return te.header.showBorder}function so(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 ro(){return so(te.header.navLinks)}function ao(){return te.footer.enabled}function ed(){return te.footer.text}function td(){return te.footer.bgColor}function sd(){return te.footer.textColor}function rd(){return te.footer.showBorder}function ad(){return te.footer.layout==="inline"?"inline":"stacked"}function nd(){return te.footer.topPadding==="normal"?"normal":"large"}function id(){const t=te.startupScripts;return Array.isArray(t)?t.filter(e=>!!(e&&typeof e=="object")).map(e=>{const s=typeof e.src=="string"?e.src.trim():"",r=typeof e.content=="string"?e.content.trim():"",a=typeof e.id=="string"?e.id.trim():"";return{...e,src:s||void 0,content:r||void 0,id:a||void 0}}).filter(e=>!!(e.src||e.content)):[]}function od(){return so(te.footer.navLinks)}const no=["de","en","es","fr","ja","pt","zh"],Sr={de:"Deutsch",en:"English",es:"Español",fr:"Français",ja:"日本語",pt:"Português",zh:"中文"};function Fr(t){return no.includes(t)}const io=m.createContext(void 0),oo="orbit-chat-language";function ld(){const t=Qi().filter(Fr);return t.length>0?t:["en"]}function cd(t){const e=localStorage.getItem(oo);if(e&&Fr(e)&&t.includes(e))return e;const s=[...navigator.languages||[],navigator.language].filter(Boolean);for(const a of s){const i=a.split("-")[0].toLowerCase();if(Fr(i)&&t.includes(i))return i}const r=Ic();return Fr(r)&&t.includes(r)?r:t[0]??"en"}function dd({children:t}){const[e]=m.useState(()=>ld()),[s,r]=m.useState(()=>cd(e));m.useEffect(()=>{Je.changeLanguage(s)},[s]),m.useEffect(()=>{localStorage.setItem(oo,s)},[s]);const a=i=>{no.includes(i)&&r(i)};return n.jsx(io.Provider,{value:{currentLanguage:s,activeLanguages:e,setLanguage:a},children:t})}function ud(){const t=m.useContext(io);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 fd=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),lo=(...t)=>t.filter((e,s,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===s).join(" ").trim();/**
|
|
16
|
+
* @license lucide-react v0.469.0 - ISC
|
|
17
|
+
*
|
|
18
|
+
* This source code is licensed under the ISC license.
|
|
19
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
20
|
+
*/var md={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 hd=m.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:s=2,absoluteStrokeWidth:r,className:a="",children:i,iconNode:o,...l},c)=>m.createElement("svg",{ref:c,...md,width:e,height:e,stroke:t,strokeWidth:r?Number(s)*24/Number(e):s,className:lo("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 s=m.forwardRef(({className:r,...a},i)=>m.createElement(hd,{ref:i,iconNode:e,className:lo(`lucide-${fd(t)}`,r),...a}));return s.displayName=`${t}`,s};/**
|
|
31
|
+
* @license lucide-react v0.469.0 - ISC
|
|
32
|
+
*
|
|
33
|
+
* This source code is licensed under the ISC license.
|
|
34
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
35
|
+
*/const Or=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 ms=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 js=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 Gn=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 zr=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 Ua=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 pd=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 Oa=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 Xn=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 sa=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 gd=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 xd=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 bd=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 co=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 yd=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 uo=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 za=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 wd=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 kd=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 vd=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"}]]);/**
|
|
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 Br=ie("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
|
|
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 fo=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"}]]);/**
|
|
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 Sd=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"}]]);/**
|
|
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 jd=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"}]]);/**
|
|
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 Cd=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"}]]);/**
|
|
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 Yn=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"}]]);/**
|
|
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 mo=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"}]]);/**
|
|
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 Rr=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"}]]);/**
|
|
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 Ad=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"}]]);/**
|
|
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 Nd=ie("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
|
|
181
|
+
* @license lucide-react v0.469.0 - ISC
|
|
182
|
+
*
|
|
183
|
+
* This source code is licensed under the ISC license.
|
|
184
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
185
|
+
*/const Id=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"}]]);/**
|
|
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 Ed=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"}]]);/**
|
|
191
|
+
* @license lucide-react v0.469.0 - ISC
|
|
192
|
+
*
|
|
193
|
+
* This source code is licensed under the ISC license.
|
|
194
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
195
|
+
*/const Ld=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"}]]);/**
|
|
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 _d=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"}]]);/**
|
|
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 Td=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"}]]);/**
|
|
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 ho=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"}]]);/**
|
|
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 Md=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"}]]);/**
|
|
216
|
+
* @license lucide-react v0.469.0 - ISC
|
|
217
|
+
*
|
|
218
|
+
* This source code is licensed under the ISC license.
|
|
219
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
220
|
+
*/const Fd=ie("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/**
|
|
221
|
+
* @license lucide-react v0.469.0 - ISC
|
|
222
|
+
*
|
|
223
|
+
* This source code is licensed under the ISC license.
|
|
224
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
225
|
+
*/const Rd=ie("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/**
|
|
226
|
+
* @license lucide-react v0.469.0 - ISC
|
|
227
|
+
*
|
|
228
|
+
* This source code is licensed under the ISC license.
|
|
229
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
230
|
+
*/const po=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"}]]);/**
|
|
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 $d=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"}]]);/**
|
|
236
|
+
* @license lucide-react v0.469.0 - ISC
|
|
237
|
+
*
|
|
238
|
+
* This source code is licensed under the ISC license.
|
|
239
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
240
|
+
*/const Pd=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"}]]);/**
|
|
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 Hr=ie("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
|
|
246
|
+
* @license lucide-react v0.469.0 - ISC
|
|
247
|
+
*
|
|
248
|
+
* This source code is licensed under the ISC license.
|
|
249
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
250
|
+
*/const Qn=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"}]]);/**
|
|
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 Dd=ie("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
|
|
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 Ud=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"}]]);/**
|
|
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 go=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"}]]);/**
|
|
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 xo=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"}]]);/**
|
|
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 bo=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"}]]);/**
|
|
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 Od=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"}]]);/**
|
|
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 rn=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"}]]);/**
|
|
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 zd=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"}]]);/**
|
|
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 ra=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"}]]);/**
|
|
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 Bd=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"}]]);/**
|
|
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 Qe=ie("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/**
|
|
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 Hd=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 Vd(t){const e=t.trim().split(`
|
|
311
|
+
`);if(e.length<2)return!1;const s=e[0].trim();if(!s.startsWith("|")||(s.match(/\|/g)||[]).length<2)return!1;const r=e[1].trim();if(!r.startsWith("|")||!/^[\s|:|-]+$/.test(r)||!r.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 qd(t){return t.replace(/(^|\n)(```|~~~)\s*\n([\s\S]*?)\n\2(\n|$)/g,(e,s,r,a,i)=>Vd(a)?`${s}
|
|
312
|
+
${a.trim()}
|
|
313
|
+
${i}`:e)}function Wd(t){const e={};let s=0;return t=t.replace(/\$\$([\s\S]*?)\$\$/g,(r,a)=>{const i=`__DISPLAY_MATH_${s++}__`;return e[i]=`$$${a}$$`,i}),t=t.replace(/\\\[([\s\S]*?)\\\]/g,(r,a)=>{const i=`__DISPLAY_MATH_${s++}__`;return e[i]=`$$${a}$$`,i}),t=t.replace(/\\\(([\s\S]*?)\\\)/g,(r,a)=>{const i=`__INLINE_MATH_${s++}__`;return e[i]=`$${a}$`,i}),t=t.replace(/(^|\n)(```|~~~)([^\n]*)\n([\s\S]*?)\n\2(\n|$)/g,(r,a,i,o,l,c)=>{const d=`__FENCED_CODE_${s++}__`;return e[d]=`${a}${i}${o}
|
|
314
|
+
${l}
|
|
315
|
+
${i}${c}`,d}),t=t.replace(/`([^`]+)`/g,r=>{const a=`__INLINE_CODE_${s++}__`;return e[a]=r,a}),{masked:t,masks:e}}function Kd(t){const e={};let s=0;return t=t.replace(new RegExp("(?<!\\$)\\$(?!\\$)([^$\\n]+?)(?<!\\$)\\$(?!\\$)","g"),(r,a)=>{const i=a.trim();if(/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?(?:\s?[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion)?$/.test(i))return r;const l=`__INLINE_MATH_${s++}__`;return e[l]=`$${a}$`,l}),{masked:t,masks:e}}const Jn=/\\(?: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 Gd(t){const e=/(__INLINE_MATH_\d+__|__DISPLAY_MATH_\d+__|__CURRENCY_\d+__)/g,s=/^(__INLINE_MATH_\d+__|__DISPLAY_MATH_\d+__|__CURRENCY_\d+__)$/;return t.split(`
|
|
316
|
+
`).map(r=>Jn.test(r)?r.split(e).map(a=>!a||s.test(a)||!Jn.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(""):r).join(`
|
|
317
|
+
`)}function Xd(t){return t.replace(/\$([^$\n]*?)\s*=\s*\$([^$\n]+)\$\s*([^$\n]*?)\$/g,(e,s,r,a)=>{const i=String(s).trimEnd(),o=String(r).trim(),l=String(a).trim(),c=[o,l].filter(Boolean).join(" ");return`$${i} = ${c}$`})}function Yd(t){const e=t.split(`
|
|
318
|
+
`);for(let r=0;r<e.length-1;r++){const a=e[r],i=e[r+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,""),g=f!==""&&/^[>]+$/.test(f),p=/^[-*+]\s*$/.test(u),h=/^\d+\.\s*$/.test(u);if(g||p||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(r,1,k,S),r++)}const s=[];for(let r=0;r<e.length;r++){const a=e[r],i=a.trim(),l=(e[r+1]??"").trim();i.startsWith("|")&&(i.match(/\|/g)||[]).length>=2&&l.startsWith("|")&&/^[\s|:-]+$/.test(l)&&l.includes("-")&&s.length>0&&s[s.length-1].trim()!==""&&s.push(""),s.push(a)}return s.join(`
|
|
319
|
+
`)}const Zn=["aligned","align","align*","array","cases","pmatrix","bmatrix","vmatrix","Vmatrix","matrix","smallmatrix","gather","gather*","multline","multline*","split","flalign","flalign*","eqnarray","equation","equation*"];function Qd(t,e){let s=0,r=`__${e}_${s}__`;for(;Object.prototype.hasOwnProperty.call(t,r);)s++,r=`__${e}_${s}__`;return r}function Jd(t,e){if(!Zn.length)return t;const s=Zn.join("|"),r=new RegExp(String.raw`\\begin\{(${s})\}([\s\S]*?)\\end\{\1\}`,"g");return t.replace(r,(a,i,o,l,c)=>{const d=c.slice(0,l),u=c.slice(l+a.length),f=/(\$\$|\\\[)\s*$/.test(d),g=/^\s*(\$\$|\\\])/.test(u);if(f&&g)return a;const p=d.lastIndexOf("\\["),h=d.lastIndexOf("\\]");if(p>h&&p!==-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 I=u.replace(/\$\$/g,"__DD__").replace(/\\\$/g,"__ES__");if(/^[^$]*\$(?!\$)/.test(I))return a}const F=Qd(e,"LATEX_ENV"),y=a.trim();return e[F]=`
|
|
320
|
+
$$
|
|
321
|
+
${y}
|
|
322
|
+
$$
|
|
323
|
+
`,F})}function Zd(t,e){for(const[s,r]of Object.entries(e)){const a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");t=t.replace(a,()=>r)}return t}const eu=t=>{if(!t||typeof t!="string")return"";try{let e=t.replace(/\r\n/g,`
|
|
324
|
+
`).replace(/\r/g,`
|
|
325
|
+
`);e=qd(e);const{masked:s,masks:r}=Wd(e);e=s,e=e.replace(/<br\s*\/?>/gi,`
|
|
326
|
+
`),e=e.replace(/\\(ne|neq)\$(?=\s*[-+0-9A-Za-z(])/g,"\\$1"),e=Xd(e),e=Yd(e),e=Jd(e,r);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,(g,p,h,x)=>{const b=`__CURRENCY_${i++}__`,k=`__CURRENCY_${i++}__`;return a.set(b,p),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,(g,p,h)=>{if(h.substring(p+g.length).match(/^[a-zA-Z]/)&&!g.match(/[KMBkmb]|[Kk]ilo|[Mm]illion|[Bb]illion$/))return g;const b=`__CURRENCY_${i++}__`;return a.set(b,g),b});const{masked:d,masks:u}=Kd(e);return e=d,Object.assign(r,u),e=Gd(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(g=>{e=e.replace(g,(p,h)=>{if(p.includes("$")||p.includes("__INLINE_MATH_")||p.includes("__DISPLAY_MATH_")||p.includes("__CURRENCY_"))return p;const x=String(h??"").trim();if(/^[A-Za-z]$/.test(x))return p;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?p:p.replace(h,`$${h}$`)})}),e=e.replace(new RegExp("(?<!\\\\)\\$(?!\\$)([^$\\n]*?)(?<!\\\\)\\$(?!\\$)","g"),(g,p)=>{if(g.includes("__CURRENCY_")||g.includes("__INLINE_MATH_")||g.includes("__DISPLAY_MATH_")||p.trim()==="")return g;const h=/^\d+(?:,\d{3})*(?:\.\d{2})?$/.test(p.trim()),x=/\\/.test(p),b=/[+\-*/=<>^_{}()]/.test(p),k=/[a-zA-Z].*\d|\d.*[a-zA-Z]/.test(p),S=/\\(?:alpha|beta|gamma|delta|epsilon|theta|lambda|mu|pi|sigma|omega)/.test(p),E=/\\(?:frac|sqrt|sum|int|lim|log|ln|sin|cos|tan|exp)/.test(p),_=/^[A-Za-z]$/.test(p.trim());return!h&&(x||b||k||S||E||_||p.length>1)?g:`\\$${p}\\$`}),e=e.split(`
|
|
327
|
+
`).map(g=>{const p=g.indexOf("$$");return p===-1||g.trim()==="$$"||g.indexOf("$$",p+2)!==-1?g:g.replace("$$","\\$\\$")}).join(`
|
|
328
|
+
`),a.forEach((g,p)=>{const h=g.replace(/\$/g,"$");e=e.replace(new RegExp(p.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),h)}),e=e.replace(/\\$/g,"$"),e=Zd(e,r),e=e.trimEnd()+`
|
|
329
|
+
`,e}catch(e){return console.warn("Error preprocessing markdown:",e),t}},tu=m.lazy(()=>Ut(()=>import("./MermaidRenderer-JnjJzSyx.js").then(t=>t.au),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.MermaidRenderer}))),su=m.lazy(()=>Ut(()=>import("./SVGRenderer-DEfyMmV3.js"),__vite__mapDeps([6,1,3,5,7,8,9,2,10])).then(t=>({default:t.SVGRenderer}))),ru=m.lazy(()=>Ut(()=>import("./ChartRenderer-BN_6aZ_Q.js"),__vite__mapDeps([11,1,5,4,12,13,14,15,16,17,7,8,9,2,10])).then(t=>({default:t.ChartRenderer}))),au=m.lazy(()=>Ut(()=>import("./MusicRenderer-CHHA0796.js"),__vite__mapDeps([18,2,1,5,7,8,9,10])).then(t=>({default:t.MusicRenderer}))),nu=t=>{var r,a;if(!t)return typeof window<"u"&&((r=window.matchMedia)!=null&&r.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light";const e=t.closest(".markdown-content");if(e){if(e.classList.contains("dark"))return"dark";if(e.classList.contains("light"))return"light"}if(t.closest(".dark"))return"dark";if(t.closest(".light"))return"light";const s=t.closest("[data-theme]");if(s){const i=s.getAttribute("data-theme");if(i==="dark")return"dark";if(i==="light")return"light"}return typeof window<"u"&&((a=window.matchMedia)!=null&&a.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},iu=(t,e)=>{const[s,r]=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 g=nu(t.current);g!==a.current&&(a.current=g,r(g))};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 g=((f=(u=t.current)==null?void 0:u.closest)==null?void 0:f.call(u,".markdown-content"))??null;g&&c.observe(g,{attributes:!0,attributeFilter:["class","data-theme"]}),document.body&&c.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]})}return()=>{o==null||o.removeEventListener("change",l),c==null||c.disconnect()}},[e,t]),e??s},ou={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"},lu=t=>{if(!t)return"";const e=t.match(/(?:^|\s)language-([^\s]+)/);if(!e)return"";const r=e[1].toLowerCase().split("{")[0].split("[")[0].split("<")[0].split(":")[0].trim().replace(/[^a-z0-9+#-]+$/g,"");return r?ou[r]??r:""},cu=t=>St.Children.toArray(t).map(e=>typeof e=="string"||typeof e=="number"?String(e):"").join("").replace(/\n$/,""),ei=({code:t})=>{const{t:e}=Le(),[s,r]=m.useState(!1),a=async()=>{try{await navigator.clipboard.writeText(t),r(!0),setTimeout(()=>r(!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"),r(!0),setTimeout(()=>r(!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(s?"markdown.codeBlock.copied":"markdown.codeBlock.copyTitle"),"aria-label":e(s?"markdown.codeBlock.copied":"markdown.codeBlock.copyAriaLabel"),children:[s?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(s?"markdown.codeBlock.copied":"markdown.codeBlock.copyLabel")})]})},du=({inline:t,className:e="",children:s,enableGraphs:r=!0,enableMermaid:a=!0,enableSVG:i=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d})=>{const{t:u}=Le(),f=m.useRef(null),g=iu(f,d),p=n.jsx("div",{className:"markdown-code-block code-block-container",children:u("markdown.codeBlock.loadingRenderer")});if(t)return n.jsx("code",{className:e,children:s});const h=lu(e),x=cu(s);if(o&&(h==="chart"||h==="chart-json"||h==="chart-table"))return n.jsx("div",{ref:f,children:n.jsx(m.Suspense,{fallback:p,children:n.jsx(ru,{code:x,language:h})})});if(l&&(h==="abc"||h==="music"))return n.jsx("div",{ref:f,children:n.jsx(m.Suspense,{fallback:p,children:n.jsx(au,{code:x})})});if(r){if(h==="mermaid"&&a)return n.jsx("div",{ref:f,children:n.jsx(m.Suspense,{fallback:p,children:n.jsx(tu,{code:x})})});if(h==="svg"&&i)return n.jsx("div",{ref:f,children:n.jsx(m.Suspense,{fallback:p,children:n.jsx(su,{code:x})})})}if(c&&h){const b=g==="light"?jl:Cl;return n.jsxs("div",{ref:f,className:"syntax-highlighted-wrapper code-block-container",children:[n.jsx(ei,{code:x}),n.jsx(Sl,{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(ei,{code:x}),n.jsx("pre",{style:{margin:0,padding:0,background:"transparent",border:"none"},children:n.jsx("code",{children:x})})]})},ti=new Set(["div","pre","blockquote","ul","ol","table","thead","tbody","tr","td","th","h1","h2","h3","h4","h5","h6","section","article","figure"]),si=({children:t,href:e="",className:s="",standalone:r=!1,...a})=>{const i=St.Children.toArray(t).map(f=>typeof f=="string"?f:"").join("").trim(),o=/^https?:\/\//i.test(e),l=!!(o&&i&&ri(i)===ri(e)),c=o?uu(e):null,d=!!(r&&l&&c),u=["markdown-link",d?"markdown-link--card":"markdown-link--inline",s].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 ri(t){return t.trim().replace(/\/$/,"")}function uu(t){try{const e=new URL(t),s=e.hostname.replace(/^www\./i,""),r=`${e.pathname}${e.search}${e.hash}`||"/";return{hostname:s,path:r}}catch{return null}}const zt=({content:t,className:e="",disableMath:s=!1,enableGraphs:r=!0,enableMermaid:a=!0,enableSVG:i=!0,enableCharts:o=!0,enableMusic:l=!0,enableSyntaxHighlighting:c=!0,syntaxTheme:d="dark"})=>{const u=eu(t);if(!u)return null;const f=s?[En]:[En,[kl,{singleDollarTextMath:!0}]],g=[];s||g.push([vl,{throwOnError:!1,errorColor:"#cc0000",strict:!1,trust:!0,macros:{"\\RR":"\\mathbb{R}","\\NN":"\\mathbb{N}","\\ZZ":"\\mathbb{Z}","\\QQ":"\\mathbb{Q}","\\CC":"\\mathbb{C}","\\dx":"\\,dx","\\dy":"\\,dy","\\dt":"\\,dt","\\dz":"\\,dz"}}]);const p={table:({children:h,...x})=>n.jsx("div",{style:{overflowX:"auto",WebkitOverflowScrolling:"touch"},children:n.jsx("table",{...x,children:h})}),a:si,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(du,{inline:E,className:x,enableGraphs:r,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=St.Children.toArray(x.children).filter(v=>!(typeof v=="string"&&v.trim()==="")),k=b.some(v=>{if(!St.isValidElement(v))return!1;const M=v.props;return(M==null?void 0:M["data-block-code"])==="true"?!0:typeof v.type=="string"?ti.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&&ti.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&&St.isValidElement(b[0])&&b[0].type===si){const v=b[0];return n.jsx("p",{...x,children:St.cloneElement(v,{standalone:!0})})}return n.jsx("p",{...x})}};return n.jsx("div",{className:`markdown-content ${e}`,children:n.jsx(wl,{remarkPlugins:f,rehypePlugins:g,components:p,children:u})})},an=()=>te.debug.consoleDebug,z=(...t)=>{an()&&console.log(...t)},we=(...t)=>{an()&&console.warn(...t)},ke=(...t)=>{an()&&console.error(...t)},Ve=(...t)=>{console.error(...t)};function ai(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 jr({audio:t,audioUrl:e,audioFormat:s="mp3",autoPlay:r=!1,maxSizeMB:a=10,downloadFilename:i}){const{t:o}=Le(),{isDark:l}=ps(),c=m.useRef(null),[d,u]=m.useState(!1),[f,g]=m.useState(0),[p,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 G=t.length*3/4/(1024*1024);if(G>a)throw new Error(o("audio.player.audioFileTooLargePlaceholder",{sizeMB:G.toFixed(1),maxMB:a}));if(G>2&&(_(o("audio.player.largeAudioWarning",{sizeMB:G.toFixed(1)})),z("[AudioPlayer] Large audio file detected",{sizeMB:G.toFixed(2)})),!/^[A-Za-z0-9+/=]+$/.test(t.replace(/\s/g,"")))throw new Error(o("audio.player.invalidBase64Error"));const J=atob(t),q=new Uint8Array(J.length);for(let T=0;T<J.length;T++)q[T]=J.charCodeAt(T);const H=ai(s),ne=new Blob([q],{type:H});if(L=URL.createObjectURL(ne),!B){L&&URL.revokeObjectURL(L);return}M(L),b(!1),z("[AudioPlayer] Audio loaded successfully",{format:s,mimeType:H,size:ne.size})}catch(K){ke("[AudioPlayer] Failed to load audio:",K),B&&(S(o("audio.player.loadFailureError")),b(!1))}})(),()=>{B=!1,L&&URL.revokeObjectURL(L)}},[t,s,a,o]),m.useEffect(()=>{if(t||!e)return;let L=null,B=!1;return(async()=>{try{b(!0),S(null);const K=typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null,G=await fetch(e,{headers:K?{"X-Adapter-Name":K}:{}});if(!G.ok)throw new Error(`Server returned ${G.status}`);if(B)return;const J=await G.arrayBuffer();if(B)return;const q=new Blob([J],{type:ai(s)});L=URL.createObjectURL(q),M(L),b(!1)}catch(K){ke("[AudioPlayer] Failed to fetch audio from",e,K),B||(S(o("audio.player.loadFailureError")),b(!1))}})(),()=>{B=!0,L&&URL.revokeObjectURL(L)}},[t,e,s,o]),m.useEffect(()=>{r&&v&&c.current&&c.current.play().catch(L=>{ke("[AudioPlayer] Auto-play failed:",L)})},[r,v]);const F=()=>{c.current&&g(c.current.duration)},y=()=>{c.current&&h(c.current.currentTime)},C=()=>u(!0),I=()=>u(!1),N=()=>{u(!1),h(0)},R=()=>{c.current&&(d?c.current.pause():c.current.play().catch(L=>{ke("[AudioPlayer] Playback failed:",L),S(o("audio.player.playbackFailureError"))}))},O=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.${s}`,L.click()},j=L=>{if(!isFinite(L))return"0:00";const B=Math.floor(L/60),A=Math.floor(L%60);return`${B}:${A.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(ra,{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:C,onPause:I,onEnded:N}),n.jsx("button",{onClick:R,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(Td,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"}):n.jsx(Fd,{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(p)}),n.jsx("input",{type:"range",min:"0",max:f||0,value:p,onChange:O,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)",A=f?p/f*100:0;return`linear-gradient(to right, ${L} 0%, ${L} ${A}%, ${B} ${A}%, ${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(sa,{className:"h-4 w-4 text-gray-700 dark:text-[#ececf1]"})})]})]})}function ni({image:t,imageUrl:e,imageFormat:s="png",revisedPrompt:r}){const{t:a}=Le(),[i,o]=m.useState(!1),[l,c]=m.useState(!1),[d,u]=m.useState(null),f=m.useRef(null);m.useEffect(()=>{if(t||!e)return;let x=!1;return(async()=>{try{const 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/${s}`}),_=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,s]);const p=(t?`data:image/${s};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(),!p)return;const b=document.createElement("a");b.href=p,b.download=`generated-image.${s}`,b.click()};return p?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:r||a("imageDisplay.generatedImageTitle"),children:[n.jsx("img",{src:p,alt:r||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(sa,{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(Hd,{size:14})})]})]}),r&&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(zr,{size:14}):n.jsx(js,{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:r})]})]})]}),i&&typeof document<"u"&&Qr.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(Qe,{size:20})}),n.jsx("img",{src:p,alt:r||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 Sa=[750,1500,3e3,5e3],fu=new Set([403,404,409,425,429,500,502,503,504]),mu=t=>new Promise(e=>setTimeout(e,t));function ii({video:t,videoUrl:e,videoFormat:s="mp4",revisedPrompt:r,adapterName:a}){const{t:i}=Le(),[o,l]=m.useState(!1),[c,d]=m.useState(!1),[u,f]=m.useState(null),g=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<=Sa.length&&(S=await fetch(e,{headers:k?{"X-Adapter-Name":k}:{}}),!(S.ok||!fu.has(S.status)||M===Sa.length));M+=1)if(await mu(Sa[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/${s}`}),v=URL.createObjectURL(_);g.current=v,f(v)}catch(k){console.warn("[VideoDisplay] Failed to fetch video from",e,k)}})(),()=>{b=!0,g.current&&(URL.revokeObjectURL(g.current),g.current=null)}},[e,t,s,a]);const h=(t?`data:video/${s};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.${s}`,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(sa,{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(jd,{size:14})})]})]}),r&&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(zr,{size:14}):n.jsx(js,{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:r})]})]})]}),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(Qe,{size:20})}),n.jsx("video",{src:h,controls:!0,autoPlay:!0,style:{maxWidth:"92vw",maxHeight:"92vh",borderRadius:"8px"},onClick:b=>b.stopPropagation()})]})]}):null}let Vr=null;function yo(t){Vr=t}function aa(){Vr=null}async function nn(){if(!Vr)return null;try{return await Vr()}catch{return null}}let Ba=!1,Ks=null;const Ha=new Set;function wo(){Ha.forEach(t=>t())}function _t(){return Ba}function hu(){return Ks}function na(t){Ba!==t&&(Ba=t,!t&&Ks!==null&&(Ks=null),wo())}function Ss(t){const e=typeof t=="string"&&t.trim().length>0?t.trim():null;Ks!==e&&(Ks=e,wo())}function pu(t){return Ha.add(t),()=>{Ha.delete(t)}}const oi="orbitchat-guest-user-id";function Cr(t){if(typeof t!="string")return null;const e=t.trim();return e.length>0?e:null}function gu(t){const e=t.split(".");if(e.length<2)return null;try{const s=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=s.padEnd(Math.ceil(s.length/4)*4,"="),a=atob(r);return JSON.parse(a)}catch{return null}}function xu(){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,r=>r.toString(16).padStart(2,"0")).join("")}`}function bu(){if(typeof window>"u")return"guest:orbitchat:server";const t=window.localStorage.getItem(oi);if(t&&t.trim().length>0)return t;const e=xu();return window.localStorage.setItem(oi,e),e}async function ko(){const t=hu();if(t)return t;const e=await nn();if(e){const s=gu(e),r=Cr(s==null?void 0:s.sub)||Cr(s==null?void 0:s.user_id)||Cr(s==null?void 0:s.preferred_username)||Cr(s==null?void 0:s.email);if(r)return r}return _t()?"authenticated:orbitchat:unknown":bu()}const yu={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"},li={pdf:"PDF",docx:"Word document",xlsx:"Excel workbook",pptx:"PowerPoint deck",md:"Markdown document",csv:"CSV file"},$r=/[\uE000-\uF8FF]|\\[eE][0-9a-fA-F]{2,3}|\\[fF][0-8][0-9a-fA-F]{2,3}/,wu=/((?:p\.)?generated-docx-preview-num-\d+-\d+:before\s*\{[^}]*?)content\s*:\s*"([^"]*)"\s*;([^}]*?\})/g;function ku(t){var s;return $r.test(t)?`•${((s=t.match(/(?:\\9|\t|\u00A0| )+$/))==null?void 0:s[0])||"\\9"}`:null}function ci(t){Array.from(t.querySelectorAll("style")).forEach(r=>{const a=r.textContent;!a||!$r.test(a)||(r.textContent=a.replace(wu,(i,o,l,c)=>{const d=ku(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(r=>{if(!/\b(symbol|wingdings|webdings)\b/i.test(r.style.fontFamily))return;const a=r.textContent||"";$r.test(a)&&(r.textContent=a.replace($r,"•"),r.style.fontFamily="")})}function vu(t){return(t||"pdf").toLowerCase().replace(/^\./,"")||"pdf"}function Su(t){const e=window.atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)s[r]=e.charCodeAt(r);return s.buffer}function ju(t){return t==="xlsx"||t==="csv"?n.jsx(uo,{className:"h-5 w-5"}):t==="pptx"?n.jsx(po,{className:"h-5 w-5"}):t==="md"?n.jsx(co,{className:"h-5 w-5"}):n.jsx(za,{className:"h-5 w-5"})}function di({document:t,documentUrl:e,documentFormat:s="pdf",revisedPrompt:r,adapterName:a}){const{t:i}=Le(),o=vu(s),[l,c]=m.useState(t||e?"loading":"idle"),[d,u]=m.useState(null),[f,g]=m.useState(null),[p,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),[C,I]=m.useState(null),N=m.useRef(null),R=m.useRef(null),O=m.useRef(null),X=r||li[o]||i("documentDisplay.generatedDocument"),j=m.useMemo(()=>`generated-document.${o}`,[o]),L=yu[o]||"application/octet-stream";m.useEffect(()=>{if(!t&&!e)return;let G=!1;return(async()=>{c("loading"),I(null),h([]),b(""),S(null),_([]),M(0);try{const q=t?Su(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 ko()};T&&(Q["X-Adapter-Name"]=T);const $=await nn();$&&(Q.Authorization=`Bearer ${$}`);const W=await fetch(e,{headers:Q});if(!W.ok)throw new Error(`Server returned ${W.status}`);return W.arrayBuffer()})();if(G)return;const H=new Blob([q],{type:L}),ne=URL.createObjectURL(H);if(N.current&&URL.revokeObjectURL(N.current),N.current=ne,u(ne),g(q.slice(0)),o==="xlsx"){const{default:T}=await Ut(async()=>{const{default:W}=await import("./index-CZz_ECqk.js");return{default:W}},[]),$=(await T(H))[0];b(($==null?void 0:$.sheet)||"First sheet"),h((($==null?void 0:$.data)||[]).slice(0,100).map(W=>W.slice(0,30).map(ae=>ae==null?"":String(ae))))}if(o==="md"&&S(new TextDecoder("utf-8").decode(q)),o==="csv"){const T=new TextDecoder("utf-8").decode(q),{default:Q}=await Ut(async()=>{const{default:W}=await import("./papaparse.min-D13ujVVP.js").then(ae=>ae.p);return{default:W}},__vite__mapDeps([19,1])),$=Q.parse(T,{skipEmptyLines:!0});M($.data.length),_($.data.slice(0,25))}c("ready")}catch(q){if(G)return;console.warn("[DocumentDisplay] Failed to load document from",e,q),I(q instanceof Error?q.message:"Unable to load document"),c("error")}})(),()=>{G=!0,N.current&&(URL.revokeObjectURL(N.current),N.current=null)}},[a,t,e,o,L]),m.useEffect(()=>{if(l!=="ready"||o!=="docx"||!f||!R.current)return;const G=R.current;G.replaceChildren(),Ut(()=>import("./docx-preview-DehBmhog.js"),__vite__mapDeps([20,1])).then(async({renderAsync:J})=>{await J(f.slice(0),G,void 0,{className:"generated-docx-preview",inWrapper:!1,ignoreWidth:!0,ignoreHeight:!0}),ci(G)}).catch(J=>{console.warn("[DocumentDisplay] Failed to render DOCX preview",J),I("Unable to render document preview")})},[f,o,l]),m.useEffect(()=>{if(!F||o!=="docx"||!f||!O.current)return;const G=O.current;G.replaceChildren(),Ut(()=>import("./docx-preview-DehBmhog.js"),__vite__mapDeps([20,1])).then(async({renderAsync:J})=>{await J(f.slice(0),G,void 0,{className:"generated-docx-preview",inWrapper:!1,ignoreWidth:!0,ignoreHeight:!0}),ci(G)}).catch(J=>{console.warn("[DocumentDisplay] Failed to render modal DOCX preview",J)})},[f,o,F]),m.useEffect(()=>{if(!F)return;const G=J=>{J.key==="Escape"&&y(!1)};return window.document.addEventListener("keydown",G),()=>window.document.removeEventListener("keydown",G)},[F]);const B=G=>{if(G==null||G.stopPropagation(),!d)return;const J=window.document.createElement("a");J.href=d,J.download=j,J.click()},A=l==="ready"&&(o==="pdf"||o==="docx"||o==="xlsx"||o==="md"||o==="csv"),K=A&&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:ju(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:[li[o]||`${o.toUpperCase()} document`,l==="loading"?` · ${i("documentDisplay.loadingPreview")}`:"",l==="error"?` · ${C||i("documentDisplay.previewUnavailableShort")}`:""]})]}),K&&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(gd,{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(sa,{className:"h-4 w-4"})})]}),A&&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:R,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:p.length>0?p.map((G,J)=>n.jsx("tr",{className:J===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:G.map((q,H)=>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:q},H))},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(zt,{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((G,J)=>n.jsx("tr",{className:J===0?"bg-gray-50 font-medium dark:bg-white/5":void 0,children:G.map((q,H)=>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:q},H))},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"&&!A&&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:G=>{G.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(Qe,{className:"h-5 w-5"})}),n.jsxs("div",{onClick:G=>G.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:O,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(zt,{content:k,disableMath:!0})})]})]})]})}const Cu=["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 Gs(t,{enabled:e,onEscape:s}){m.useEffect(()=>{if(!e||!t.current)return;const r=t.current,a=document.activeElement,i=Array.from(r.querySelectorAll(Cu)).filter(d=>d.tabIndex!==-1),o=i[0]||r,l=i[i.length-1]||r;o.focus({preventScroll:!0});const c=d=>{if(d.key==="Escape"){s==null||s();return}if(d.key!=="Tab")return;if(i.length===0){d.preventDefault(),r.focus({preventScroll:!0});return}const u=document.activeElement;if(d.shiftKey){(!u||u===o||!r.contains(u))&&(d.preventDefault(),l.focus({preventScroll:!0}));return}(!u||u===l||!r.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,s,t])}function qr({isOpen:t,onClose:e,onConfirm:s,title:r,message:a,confirmText:i,cancelText:o,type:l="danger",isLoading:c=!1}){const d=m.useRef(null);Gs(d,{enabled:t,onEscape:e});const{t:u}=Le(),f=i??u("common.confirm"),g=o??u("common.cancel");if(!t)return null;const p=()=>{c||s()},x=(()=>{switch(l){case"danger":return{icon:"text-red-500",iconBg:"bg-red-100 dark:bg-red-900/20",confirmButton:"bg-red-600 hover:bg-red-700 focus:ring-red-500",border:"border-red-200 dark:border-red-800"};case"warning":return{icon:"text-amber-500",iconBg:"bg-amber-100 dark:bg-amber-900/20",confirmButton:"bg-amber-600 hover:bg-amber-700 focus:ring-amber-500",border:"border-amber-200 dark:border-amber-800"};default:return{icon:"text-blue-500",iconBg:"bg-blue-100 dark:bg-blue-900/20",confirmButton:"bg-blue-600 hover:bg-blue-700 focus:ring-blue-500",border:"border-blue-200 dark:border-blue-800"}}})(),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(rn,{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:r})]}),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(Qe,{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:g}),n.jsx("button",{type:"button",onClick:p,disabled:c,className:`px-4 py-3 md:py-2.5 text-white rounded-lg transition-all font-medium shadow-sm hover:shadow-md transform hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-white dark:focus:ring-offset-gray-800 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none ${x.confirmButton}`,children:c?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:Qr.createPortal(b,document.body)}const Au=["#","*","`","[","]","(",")","{","}","|","<",">"],vo=t=>Au.some(e=>t.includes(e));function So(t){if(!t||t.length<1e3)return!1;const e=/^[A-Za-z0-9+/=]+$/,s=t.replace(/\s+/g,"");if(s.length>1e4&&e.test(s)){const r=/\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=vo(t),i=/[-.,;:!?'"()]/.test(t);if(!r&&!a&&!i)return!0}return!!(s.length>5e4&&e.test(s)&&t.replace(/[A-Za-z0-9+/=\s]/g,"").length<10)}const Nu=/(?:\u202F|\u2009|\u200A|\u200B|\u200C|\u200D|\uFEFF)/g;function Xs(t){if(!t)return t;let e=t.replace(Nu," ");if(So(e))return"";const s=/([A-Za-z0-9+/=]{10000,})/g;return e=e.replace(s,r=>{const a=r.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(r),o=vo(r),l=/[-.,;:!?'"()]/.test(r);if(!i&&!o&&!l)return""}return r}),e}function Va(t,e=5e4){return!t||t.length<=e?t:So(t)?"":t.substring(0,e)+`
|
|
330
|
+
|
|
331
|
+
... (content truncated due to length)`}const Iu={maxFilesPerConversation:te.limits.files.perConversation,maxFileSizeMB:te.limits.files.maxSizeMB,maxTotalFiles:te.limits.files.totalFiles,maxConversations:te.limits.conversations.maxConversations,maxMessagesPerConversation:te.limits.conversations.messagesPerConversation,maxMessagesPerThread:te.limits.conversations.messagesPerThread,maxTotalMessages:te.limits.conversations.totalMessages,maxMessageLength:te.limits.messages.maxLength};function Eu(t){const e=te.guestLimits;switch(t){case"maxConversations":return e.conversations.maxConversations;case"maxMessagesPerConversation":return e.conversations.messagesPerConversation;case"maxMessagesPerThread":return e.conversations.messagesPerThread;case"maxTotalMessages":return e.conversations.totalMessages;case"maxFilesPerConversation":return e.files.perConversation;case"maxTotalFiles":return e.files.totalFiles;case"maxMessageLength":return e.messages.maxLength;case"maxFileSizeMB":return e.files.maxSizeMB;default:return}}const oe=new Proxy(Iu,{get(t,e){if(it()&&!_t()){const s=Eu(e);if(s!==void 0)return s}return t[e]}});function Cs(){return m.useSyncExternalStore(pu,_t,_t)}class Pe extends Error{constructor(s,r){super(s);at(this,"status");at(this,"statusText");this.name="ApiRequestError",this.status=r.status,this.statusText=r.statusText}}async function ze(t={}){const e={"X-User-ID":await ko(),...t},s=await nn();return s&&(e.Authorization=`Bearer ${s}`),e}function Lt(t){return encodeURIComponent(t)}function Lu(t){return!t||t.length===0?"":`?file_ids=${t.map(encodeURIComponent).join(",")}`}async function We(t){const e=`API request failed: ${t.status} ${t.statusText}`;try{if((t.headers.get("content-type")||"").includes("application/json")){const r=await t.json(),a=typeof r.detail=="string"&&r.detail.trim()||typeof r.error=="string"&&r.error.trim()||typeof r.message=="string"&&r.message.trim();if(a)return`${e}: ${a}`}else{const r=(await t.text()).trim();if(r)return`${e}: ${r}`}}catch{}return e}function ui(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 Ar=null;function _u(){let t=null,e=null;const s=(i,o,l)=>{t=o||null,e=l||null},r=(i,o={})=>{const l=new URL(`/api/ws/voice/${Lt(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={})=>r(l,{sessionId:o||void 0,...c}),async*streamChat(l,c,d,u,f,g,p,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),g&&(v.audio_format=g),p&&(v.language=p),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 ze({"Content-Type":"application/json","X-Adapter-Name":i,...o?{"X-Session-ID":o}:{}}),body:JSON.stringify(v)});if(!M.ok)throw new Pe(await We(M),M);if((F=M.headers.get("content-type"))!=null&&F.includes("text/event-stream")){const C=(y=M.body)==null?void 0:y.getReader(),I=new TextDecoder;let N="";if(!C)throw new Error("Response body is not readable");for(;;){const{done:R,value:O}=await C.read();if(R)break;N+=I.decode(O,{stream:!0});const X=N.split(`
|
|
332
|
+
`);N=X.pop()||"";for(const j of X){const L=ui(j);L&&(yield L)}}if(N.trim())for(const R of N.split(`
|
|
333
|
+
`)){const O=ui(R);O&&(yield O)}}else{const C=await M.json();yield{text:C.message||C.response||"",done:!0,audio:C.audio,audioFormat:C.audio_format||C.audioFormat,image:C.image,image_format:C.image_format,image_revised_prompt:C.image_revised_prompt,image_url:C.image_url,video:C.video,video_format:C.video_format,video_revised_prompt:C.video_revised_prompt,video_url:C.video_url,document:C.document,document_format:C.document_format,document_revised_prompt:C.document_revised_prompt,document_url:C.document_url,generated_audio_url:C.generated_audio_url,generated_audio_format:C.generated_audio_format,generated_audio_revised_prompt:C.generated_audio_revised_prompt,model:C.model,assistant_message_id:C.assistant_message_id,threading:C.threading}}},async createThread(l,c){const d=await fetch("/api/threads",{method:"POST",headers:await ze({"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 Pe(await We(d),d);return d.json()},async getThreadInfo(l){const c=await fetch(`/api/threads/${Lt(l)}`,{headers:await ze({"X-Adapter-Name":i})});if(!c.ok)throw new Pe(await We(c),c);return c.json()},async deleteThread(l){const c=await fetch(`/api/threads/${Lt(l)}`,{method:"DELETE",headers:await ze({"X-Adapter-Name":i})});if(!c.ok)throw new Pe(await We(c),c);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 g=await fetch("/api/feedback",{method:"POST",headers:await ze({"Content-Type":"application/json","X-Adapter-Name":i,"X-Session-ID":c}),body:JSON.stringify(f)});if(!g.ok)throw new Pe(await We(g),g);return g.json()},async getSessionFeedback(l){const c=await fetch(`/api/feedback/${Lt(l)}`,{headers:await ze({"X-Adapter-Name":i})});if(!c.ok)throw new Pe(await We(c),c);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/${Lt(c)}`,{method:"DELETE",headers:await ze({"X-Adapter-Name":i})});if(!d.ok)throw new Pe(await We(d),d);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/${Lt(d)}${u}`,{headers:await ze({"X-Adapter-Name":i})});if(!f.ok)throw new Pe(await We(f),f);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=Lu(c),f=await fetch(`/api/admin/conversations/${Lt(d)}${u}`,{method:"DELETE",headers:await ze({"X-Adapter-Name":i})});if(!f.ok)throw new Pe(await We(f),f);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 ze({"X-Adapter-Name":i}),body:c});if(!d.ok)throw new Pe(await We(d),d);return d.json()},async listFiles(){const l=await fetch("/api/files",{headers:await ze({"X-Adapter-Name":i})});if(!l.ok)throw new Pe(await We(l),l);const c=await l.json();return Array.isArray(c)?c:c.files||[]},async getFileInfo(l,c){const d=await fetch(`/api/files/${Lt(l)}`,{headers:await ze({"X-Adapter-Name":i}),signal:c});if(!d.ok)throw new Pe(await We(d),d);return d.json()},async queryFile(l,c,d){const u=await fetch(`/api/files/${Lt(l)}/query`,{method:"POST",headers:await ze({"Content-Type":"application/json","X-Adapter-Name":i}),body:JSON.stringify({query:c,max_results:d})});if(!u.ok)throw new Pe(await We(u),u);return u.json()},async deleteFile(l){const c=await fetch(`/api/files/${Lt(l)}`,{method:"DELETE",headers:await ze({"X-Adapter-Name":i})});if(!c.ok)throw new Pe(await We(c),c);return c.json()},async validateApiKey(){const l=await fetch(`/api/admin/api-keys/${Lt(i)}/status`,{headers:await ze({"X-Adapter-Name":i})});if(!l.ok)throw new Pe(await We(l),l);return l.json()},async getAdapterInfo(){const l="/api/admin/adapters/info",c=g=>{if(!g)return 0;const p=Number(g);if(Number.isFinite(p)&&p>0)return Math.min(p*1e3,3e4);const h=Date.parse(g);if(!Number.isNaN(h)){const x=h-Date.now();if(x>0)return Math.min(x,3e4)}return 0},d=g=>new Promise(p=>setTimeout(p,g)),u=async()=>fetch(l,{headers:await ze({"X-Adapter-Name":i})});let f=await u();if(f.status===429){const g=c(f.headers.get("Retry-After"));g>0&&(await d(g),f=await u())}if(!f.ok){const g=await f.text(),p=`${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 (${p}) for '${i}'.`;throw console.warn("[ProxyApi] Adapter info request failed",{adapter:i,status:f.status,statusText:f.statusText,details:g||void 0}),new Pe(h,f)}return f.json()},async stopChat(l,c){const d=await fetch("/api/v1/chat/stop",{method:"POST",headers:await ze({"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 ze({"X-Adapter-Name":i})});if(!c.ok)throw new Pe(await We(c),c);return c.json()},async getAllModels(){const l=await fetch("/api/admin/models",{headers:await ze({"X-Adapter-Name":i})});if(!l.ok)throw new Pe(await We(l),l);return l.json()},async getAdapterSkills(l){const c=await fetch(`/api/admin/adapters/${encodeURIComponent(l)}/skills`,{headers:await ze({"X-Adapter-Name":i})});if(!c.ok)throw new Pe(await We(c),c);return c.json()},async getAllSkills(){const l=await fetch("/api/admin/skills",{headers:await ze({"X-Adapter-Name":i})});if(!l.ok)throw new Pe(await We(l),l);return l.json()}});return{configureApi:s,getRealtimeVoiceWebSocketUrl:r,streamChat:async function*(i,o,l,c,d,u,f,g,p,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,g,p,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){at(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 Tu(){return Ar||(z("Loading API via Express proxy"),Ar=_u(),z("API loaded successfully"),Ar)}async function Re(){return await Tu()}class fi{static async getAdapterSkills(e,s){const r=await Re(),a=new r.ApiClient({apiUrl:"",adapterName:s});return a.getAdapterSkills?(await a.getAdapterSkills(e)).available_skills:[]}static async getAllSkills(e){const s=await Re(),r=new s.ApiClient({apiUrl:"",adapterName:e});return r.getAllSkills?(await r.getAllSkills()).skills:[]}}const Mu=6e4;function jo(t={}){const{adapterName:e,enabled:s=!0,selectionScopeKey:r,supportsThreading:a=!1}=t,i=s&&!!e&&!a,o=r??e??"__default__",[l,c]=m.useState([]),[d,u]=m.useState(!1),[f,g]=m.useState(null),[p,h]=m.useState({}),x=m.useRef(null),b=m.useRef(new Map),k=m.useCallback(async v=>{var y,C;const M=v,F=b.current.get(M);if(F&&F.expiresAt>Date.now()){c(F.skills),g(v);return}x.current&&x.current.abort(),x.current=new AbortController,u(!0);try{const[I,N]=await Promise.all([fi.getAdapterSkills(v,v),fi.getAllSkills(v)]);if((y=x.current)!=null&&y.signal.aborted)return;const R=N.filter(O=>I.includes(O.name)&&O.enabled);b.current.set(M,{skills:R,expiresAt:Date.now()+Mu}),c(R),g(v),z("[useSkills] Loaded",R.length,"skills for adapter",v)}catch(I){if(I instanceof Error&&I.name==="AbortError")return;we("[useSkills] Failed to load skills:",I instanceof Error?I.message:String(I)),c([]),g(v)}finally{(C=x.current)!=null&&C.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?p[o]??null:null;return{skills:i&&f===e?l:[],isLoading:i?d||f!==e:!1,selectedSkill:_,selectSkill:S,clearSkill:E}}const mi=t=>{let e;const s=new Set,r=(d,u)=>{const f=typeof d=="function"?d(e):d;if(!Object.is(f,e)){const g=e;e=u??(typeof f!="object"||f===null)?f:Object.assign({},e,f),s.forEach(p=>p(e,g))}},a=()=>e,l={setState:r,getState:a,getInitialState:()=>c,subscribe:d=>(s.add(d),()=>s.delete(d))},c=e=t(r,a,l);return l},Fu=(t=>t?mi(t):mi),Ru=t=>t;function $u(t,e=Ru){const s=St.useSyncExternalStore(t.subscribe,St.useCallback(()=>e(t.getState()),[t,e]),St.useCallback(()=>e(t.getInitialState()),[t,e]));return St.useDebugValue(s),s}const hi=t=>{const e=Fu(t),s=r=>$u(e,r);return Object.assign(s,e),s},Co=(t=>t?hi(t):hi),ot=Co(t=>({showLoginPrompt:!1,promptMessage:"",openLoginPrompt:e=>t({showLoginPrompt:!0,promptMessage:e}),closeLoginPrompt:()=>t({showLoginPrompt:!1,promptMessage:""})})),Nr=t=>{const e=t==null?void 0:t.trim();return e||(typeof window<"u"&&window.localStorage?localStorage.getItem("chat-adapter-name"):null)},Ir=new Map,pi=(t,e)=>new Promise(s=>{if(e!=null&&e.aborted){s();return}const r=()=>{clearTimeout(a),e==null||e.removeEventListener("abort",r),s()},a=setTimeout(r,t);e==null||e.addEventListener("abort",r,{once:!0})});class Kt{static cancelFilePoll(e){var s;(s=Ir.get(e))==null||s.abort()}static async uploadFile(e,s,r,a,i){try{const o=oe.maxFileSizeMB*1024*1024;if(e.size>o)throw new Error(`File size exceeds maximum limit of ${oe.maxFileSizeMB}MB`);if(!(["application/pdf","text/plain","text/markdown","text/csv","application/json","text/html","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel","application/vnd.ms-excel.sheet.macroEnabled.12","text/x-python","text/x-python-script","text/x-java-source","text/x-java","text/x-sql","text/javascript","application/javascript","text/typescript","application/typescript","text/x-c++src","text/x-csrc","text/x-c","text/x-go","text/x-rust","text/x-ruby","text/x-php","text/x-shellscript","text/x-sh","text/yaml","text/x-yaml","text/xml","application/xml","text/css","text/x-scss","text/x-sass","text/x-less","image/png","image/jpeg","image/tiff","image/webp","audio/wav","audio/mpeg","audio/mp3","audio/mp4","audio/ogg","audio/flac","audio/webm","audio/x-m4a","audio/aac","text/vtt"].includes(e.type)||/\.(pdf|txt|md|csv|json|html|docx|pptx|xlsx|py|java|sql|js|mjs|ts|tsx|cpp|cxx|cc|c|h|hpp|go|rs|rb|php|sh|bash|zsh|yaml|yml|xml|css|scss|sass|less|png|jpe?g|tiff?|webp|wav|mp3|mp4|ogg|flac|webm|m4a|aac|vtt)$/i.test(e.name)||(e.type==="application/x-zip-compressed"||e.type==="application/zip")&&/\.xlsx$/i.test(e.name)))throw new Error(`File type not supported: ${e.type||"unknown"}`);s&&s({filename:e.name,progress:0,status:"uploading"});const d=await Re(),u=(a==null?void 0:a.trim())||$e(),f=Nr(i);if(!f)throw new Error("Adapter not configured. Please select an adapter from the dropdown.");z(`Using adapter: ${f}`);const g=new d.ApiClient({apiUrl:u,sessionId:null,adapterName:f});if(!g.uploadFile)throw new Error("File upload is not available.");const p=await g.uploadFile(e);s&&s({filename:e.name,progress:75,status:"processing",fileId:p.file_id});let h;const x=new AbortController;Ir.set(p.file_id,x);try{h=await this.pollFileStatus(p.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 ${p.file_id} was deleted during upload`);we(`File status polling failed for ${p.file_id}:`,b);const S=k.includes("processing failed")||k.includes("timeout");h={file_id:p.file_id,filename:p.filename,mime_type:p.mime_type,file_size:p.file_size,processing_status:S?"failed":p.status||"processing",chunk_count:p.chunk_count,error_message:S?k:void 0}}finally{Ir.get(p.file_id)===x&&Ir.delete(p.file_id)}return s&&s({filename:e.name,progress:100,status:h.processing_status==="completed"?"completed":"processing",fileId:p.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."),s&&s({filename:e.name,progress:0,status:"error",error:l}),new Error(l)}}static async uploadFiles(e,s){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,g=>{s&&s(f,g)})}));for(let d=0;d<c.length;d++){const u=c[d],f=o+d;u.status==="fulfilled"?a.push(u.value):(Ve(`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&&we(`[FileUploadService] ${i.length} of ${e.length} files failed to upload:`,i.map(o=>o.file)),a}static async listFiles(e,s,r){try{const a=await Re(),i=(s==null?void 0:s.trim())||$e(),o=Nr(r);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){Ve("Failed to list files:",a);const i=a instanceof Error?a.message:"Failed to list files";throw new Error(i)}}static async getFileInfo(e,s,r,a,i){try{const o=await Re(),l=(r==null?void 0:r.trim())||$e(),c=Nr(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`);Ve(`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,s=30,r=2e3,a,i,o,l){for(let c=0;c<s;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<s-1&&await pi(r,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<s-1){await pi(r,l);continue}throw d}throw new Error(`File processing timeout: ${e} did not complete within ${s*r/1e3} seconds`)}static async deleteFile(e,s,r,a){try{const i=await Re(),o=(r==null?void 0:r.trim())||$e(),l=Nr(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};Ve(`Failed to delete file ${e}:`,i);const o=i instanceof Error?i.message:`Failed to delete file: ${e}`;throw new Error(o)}}}class Pu{constructor(){at(this,"audioQueue",[]);at(this,"isPlaying",!1);at(this,"currentAudio",null);at(this,"audioContext",null);at(this,"isEnabled",!1);at(this,"onPlaybackStart",null);at(this,"onPlaybackEnd",null);at(this,"mimeTypeCache",new Map);at(this,"onChunkPlayed",null);at(this,"blobUrls",[]);at(this,"suppressPlaybackErrors",!1)}async enableAudio(){var e,s;try{if(!this.audioContext){const i=typeof AudioContext<"u"?AudioContext:typeof window<"u"&&window.webkitAudioContext||null;i&&(this.audioContext=new i)}const r=((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 r,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:(s=this.audioContext)==null?void 0:s.state}),!0}catch(r){return ke("[AudioStreamManager] Failed to enable audio:",r),!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 s=typeof AudioContext<"u"?AudioContext:typeof window<"u"&&window.webkitAudioContext||null;if(s)try{this.audioContext=new s}catch(r){return ke("[AudioStreamManager] Failed to create AudioContext:",r),!1}}if(((e=this.audioContext)==null?void 0:e.state)==="suspended")try{await this.audioContext.resume()}catch(s){return z("[AudioStreamManager] AudioContext resume deferred",s),!1}return!0}resolveMimeType(e){const s=this.mimeTypeCache.get(e);if(s)return s;let r;switch(e){case"mp3":r="audio/mpeg";break;case"wav":r="audio/wav";break;case"webm":r="audio/webm";break;case"ogg":r="audio/ogg";break;case"opus":{const a=typeof document<"u"?document.createElement("audio"):null;a!=null&&a.canPlayType("audio/ogg; codecs=opus")?r="audio/ogg; codecs=opus":a!=null&&a.canPlayType("audio/webm; codecs=opus")?r="audio/webm; codecs=opus":r="audio/mp4";break}default:r=`audio/${e}`}return this.mimeTypeCache.set(e,r),z(`[AudioStreamManager] Resolved MIME type for "${e}": ${r}`),r}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((s,r)=>s.chunkIndex-r.chunkIndex),this.isPlaying||this.playNextChunk().catch(s=>{ke("[AudioStreamManager] Playback chain error:",s)})}async playNextChunk(){var s,r;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){ke(`[AudioStreamManager] AudioContext fallback also failed for chunk ${e.chunkIndex}:`,f)}d()}this.currentAudio=null,this.playNextChunk().catch(f=>{ke("[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:(s=e.audio)==null?void 0:s.length,audioContextState:(r=this.audioContext)==null?void 0:r.state,isEnabled:this.isEnabled}),ke(`[AudioStreamManager] Failed to play chunk ${e.chunkIndex}:`,a),this.playNextChunk().catch(o=>{ke("[AudioStreamManager] Playback chain error after recovery:",o)})}}playViaAudioElement(e,s,r){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){r(),l(!0);return}const u=i.error;ke(`[AudioStreamManager] Media error on chunk ${s.chunkIndex}:`,u?{code:u.code,message:u.message,SRC_NOT_SUPPORTED:u.code===MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED}:"unknown"),r(),l(!1)};i.addEventListener("error",c,{once:!0});const d=async()=>{if(!o)try{i.addEventListener("ended",()=>{o||(z(`[AudioStreamManager] Chunk ${s.chunkIndex} finished`),this.onChunkPlayed&&this.onChunkPlayed(s.chunkIndex),r(),l(!0))},{once:!0}),await i.play()}catch(u){if(this.suppressPlaybackErrors){r(),l(!0);return}z(`[AudioStreamManager] audio.play() rejected for chunk ${s.chunkIndex}:`,u),r(),l(!1)}};i.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA?d():i.addEventListener("canplay",()=>d(),{once:!0})})}playViaAudioContext(e,s){return new Promise((r,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){r(!0);return}const l=this.audioContext.createBufferSource();l.buffer=o,l.connect(this.audioContext.destination),l.onended=()=>{z(`[AudioStreamManager] Chunk ${s} finished (AudioContext path)`),this.onChunkPlayed&&this.onChunkPlayed(s),r(!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 ns=new Pu,Du=[{extensions:["pdf"],Icon:za,colorClass:"bg-red-500"},{extensions:["doc","docx"],Icon:za,colorClass:"bg-blue-500"},{extensions:["xls","xlsx","csv"],Icon:uo,colorClass:"bg-emerald-600"},{extensions:["ppt","pptx"],Icon:po,colorClass:"bg-orange-500"},{extensions:["png","jpg","jpeg","webp","tiff","gif"],Icon:yd,colorClass:"bg-violet-500"},{extensions:["wav","mp3","ogg","flac","webm","m4a","aac"],Icon:bd,colorClass:"bg-teal-600"},{extensions:["mp4","mov","avi","mkv"],Icon:wd,colorClass:"bg-pink-600"},{extensions:["zip","rar","7z","tar","gz"],Icon:xd,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:co,colorClass:"bg-slate-500"}],Uu=new Set(["png","jpg","jpeg","webp","tiff","gif"]);function Ou(t){const e=/\.([a-z0-9]+)$/i.exec(t.trim());return e?e[1].toLowerCase():""}function zu(t){const e=Ou(t),s=Du.find(r=>r.extensions.includes(e));return{Icon:(s==null?void 0:s.Icon)??kd,colorClass:(s==null?void 0:s.colorClass)??"bg-gray-400 dark:bg-gray-500",label:e?e.toUpperCase():"",isImage:Uu.has(e)}}const Ys=new Map;function Ao(t,e){const s=Ys.get(t);s&&s!==e&&URL.revokeObjectURL(s),Ys.set(t,e)}function Bu(t){return Ys.get(t)}function qa(t){const e=Ys.get(t);e&&(URL.revokeObjectURL(e),Ys.delete(t))}const Hu=zc()||Ac(),No=()=>{if(ea())return Ja()||void 0},Vs="",Vu=["New Chat","New Conversation"],qu=t=>t&&!Vu.includes(t)?t:Vs,qs=(t,e,s)=>({id:t,sessionId:e,title:Vs,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:s,adapterName:No(),adapterLoadError:null}),Wr=()=>{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},Wu=t=>{localStorage.setItem("chatbot-session-id",t)};let Ku=0;const Dt=t=>{const e=Date.now(),s=++Ku,r=Math.random().toString(36).substr(2,9);return`msg_${e}_${s}_${r}_${t}`},is=()=>{const t=Date.now(),e=Math.random().toString(36).substr(2,9);return`session_${t}_${e}`},Io=t=>{const e=new Set;let s=!1;const r=t.map(a=>{if(!e.has(a.id))return e.add(a.id),a;s=!0;const i={...a,id:Dt(a.role)};return e.add(i.id),we(`[chatStore] Re-keyed duplicate message id ${a.id}`),i});return s?r:t},gi=t=>t.filter(e=>!e.isThreadMessage&&!(e.role==="assistant"&&e.isStreaming)).length,xi=t=>t.flatMap(s=>[s.imageUrl,s.videoUrl,s.documentUrl]).map(s=>{var r;return((r=s==null?void 0:s.match(/\/api\/files\/([^/]+)\/content/))==null?void 0:r[1])??null}).filter(s=>s!==null),Gu=(t,e)=>{if(t instanceof Date)return new Date(t);if(typeof t=="number"&&Number.isFinite(t)){const s=new Date(t);if(!Number.isNaN(s.getTime()))return s}if(typeof t=="string"){const s=new Date(t);if(!Number.isNaN(s.getTime()))return s}return e?new Date(e):new Date},Xu=(t,e)=>{const s=new Map;e.forEach((a,i)=>{a.databaseMessageId&&s.set(a.databaseMessageId,{message:a,index:i})});const r=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&&s.has(l)){const g=s.get(l);c=g.message,r.add(g.index)}else{const g=i<e.length?i:0;if(!r.has(g)&&((f=e[g])==null?void 0:f.role)===o)c=e[g],r.add(g);else for(let p=1;p<e.length;p++){const h=(g+p)%e.length;if(!r.has(h)&&e[h].role===o){c=e[h],r.add(h);break}}}const d=a.timestamp?Gu(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}`:Dt(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 g=a.metadata,p=g==null?void 0:g.retrieved_docs;Array.isArray(p)&&p.length>0&&(u.supportsThreading=!0)}return u})},Yu=(t,e)=>{if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++){const r=t[s],a=e[s];if(r.role!==a.role||r.content!==a.content||(r.databaseMessageId||null)!==(a.databaseMessageId||null)||+r.timestamp!=+a.timestamp)return!1}return!0},Eo=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 s=!1;try{const u=localStorage.getItem("chat-settings");u&&(s=JSON.parse(u).voiceEnabled===!0)}catch{we("Failed to read global voice setting")}const r=t.audioSettings;return{returnAudio:(r==null?void 0:r.enabled)??s??!!e,ttsVoice:(r==null?void 0:r.ttsVoice)||void 0,language:(r==null?void 0:r.language)||"en-US",audioFormat:r==null?void 0:r.audioFormat}},Qu=300;let Er=null;const Ge=t=>{Er&&clearTimeout(Er),Er=setTimeout(()=>{Er=null;try{const e=t(),s=e.conversations.map(r=>({...r,messages:r.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:s,currentConversationId:e.currentConversationId}))}catch(e){e instanceof DOMException&&e.name==="QuotaExceededError"?we("[chatStore] localStorage quota exceeded — skipping save"):Ve("[chatStore] Failed to save state to localStorage:",e)}},Qu)},Ju=32,ks=new Map;let as=null,ut=null,Wt=null,fs=null;function on(t){return t instanceof Pe&&t.status===503}function Lo(t,e){if(on(t))return Je.t("chat.errors.servicePaused");if(t instanceof Error){if(t.message.startsWith("Server error:"))return t.message.substring(14);if(t.message.includes("Could not connect")||t.message.includes("timed out"))return t.message}return e}const Wa=(t,e)=>{const s=ks.get(t);if(s){if(s.timeoutId&&(clearTimeout(s.timeoutId),s.timeoutId=null),s.content){const r=s.content,a=s.messageId;s.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+r}),{...o,messages:l,updatedAt:new Date}})}))}ks.delete(t)}},vt=(t,e,s,r)=>({conversations:t.conversations.map(a=>{var l;if(a.id!==e)return a;const i=[...a.messages],o=r?i.findIndex(c=>c.id===r):i.length-1;return o!==-1&&((l=i[o])==null?void 0:l.role)==="assistant"&&(i[o]={...i[o],...s(i[o])}),{...a,messages:i,updatedAt:new Date}})});let Kr=!1,Gr="";async function Os(){if(Kr&&Gr)return!0;try{const t=await Re(),e=localStorage.getItem("chat-api-url");e&&e===$a&&localStorage.removeItem("chat-api-url");const s=e&&e!==$a?e:$e(),r=Wr(),a=localStorage.getItem("chat-adapter-name")||Hu;return t.configureApi(s,r,a),Gr=s,Kr=!0,!0}catch(t){return Ve("Failed to configure API:",t),!1}}async function bi(t,e,s,r,a,i,o,l,c){let d=!1;const u=new AbortController;as=u,fs=r,ut=null;try{const f=t().conversations.find(b=>b.id===r);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.");Wt=f.sessionId,f.sessionId&&(await Re()).configureApi(dt(f.apiUrl),f.sessionId,f.adapterName);const g=await Re(),{returnAudio:p,ttsVoice:h,language:x}=Eo(f);for await(const b of g.streamChat(a,!0,i.length>0?i:void 0,void 0,void 0,void 0,x,p,h,void 0,void 0,o,void 0,c)){if(b.request_id&&!ut&&(ut=b.request_id,z(`[chatStore] >>> CAPTURED request_id for ${l} stop: ${b.request_id}`)),b.text){const k=Xs(b.text);k?(t().appendToLastMessage(k,r,s),d=!0):b.text.length>100&&we("[chatStore] Filtered out potential base64 audio data from regenerated message content")}if(b.audio&&b.done&&e(k=>vt(k,r,()=>({audio:b.audio,audioFormat:b.audioFormat||"mp3"}),s)),b.image&&b.done&&(d=!0,e(k=>vt(k,r,()=>({image:b.image,imageFormat:b.image_format||"png",imageRevisedPrompt:b.image_revised_prompt,imageUrl:b.image_url}),s))),(b.video||b.video_url)&&b.done&&(d=!0,e(k=>vt(k,r,()=>({video:b.video,videoFormat:b.video_format||"mp4",videoRevisedPrompt:b.video_revised_prompt,videoUrl:b.video_url}),s))),(b.document||b.document_url)&&b.done&&(d=!0,e(k=>vt(k,r,()=>({document:b.document,documentFormat:b.document_format||"pdf",documentRevisedPrompt:b.document_revised_prompt,documentUrl:b.document_url}),s))),b.generated_audio_url&&b.done&&(d=!0,e(k=>vt(k,r,()=>({generatedAudioFormat:b.generated_audio_format||"mp3",generatedAudioRevisedPrompt:b.generated_audio_revised_prompt,generatedAudioUrl:b.generated_audio_url}),s))),b.done){const k=b.threading;k!=null&&k.supports_threading&&e(S=>({conversations:S.conversations.map(E=>E.id!==r?E:{...E,messages:E.messages.map(_=>_.id===s?{..._,supportsThreading:!0,databaseMessageId:k.message_id}:_),updatedAt:new Date})})),b.assistant_message_id&&e(S=>({conversations:S.conversations.map(E=>E.id!==r?E:{...E,messages:E.messages.map(_=>_.id===s&&!_.databaseMessageId?{..._,databaseMessageId:b.assistant_message_id}:_),updatedAt:new Date})})),b.model&&e(S=>vt(S,r,()=>({model:b.model}),s));break}}!d&&!u.signal.aborted&&t().appendToLastMessage("No response received from the server. Please try again later.",r,s)}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{const p=on(f);(p?we:Ve)(`${l==="edit-regenerate"?"Edit-regenerate":"Regenerate"} API ${p?"warning":"error"}:`,f);const x=Lo(f,"Sorry, there was an error regenerating the response.");t().appendToLastMessage(x,r,s)}}as=null,ut=null,Wt=null,fs=null,Wa(r,e),e(f=>{const g=f.conversations.map(h=>h.id===r?{...h,messages:h.messages.map(x=>x.id===s?{...x,isStreaming:!1}:x),updatedAt:new Date}:h),p=g.find(h=>h.id===f.currentConversationId);return{conversations:g,isLoading:p?p.messages.some(h=>h.role==="assistant"&&h.isStreaming):!1}})}const ye=Co((t,e)=>({conversations:[],currentConversationId:null,isLoading:!1,error:null,realtimeVoice:{status:"idle",transcript:""},_pendingRealtimeTurns:{},sessionId:Wr(),getSessionId:()=>e().sessionId,setRealtimeVoiceState:s=>t(r=>({realtimeVoice:{...r.realtimeVoice,...s}})),beginRealtimeVoiceTurn:(s,r)=>{r.trim()&&t(a=>{const i=a._pendingRealtimeTurns[s];let o=i==null?void 0:i.userMessageId,l=i==null?void 0:i.assistantMessageId;return{conversations:a.conversations.map(d=>{if(d.id!==s)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:r}:f),updatedAt:new Date}:(o=Dt("user"),l=Dt("assistant"),{...d,messages:[...d.messages,{id:o,content:r,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?r.slice(0,50):d.title})}),_pendingRealtimeTurns:o&&l?{...a._pendingRealtimeTurns,[s]:{userMessageId:o,assistantMessageId:l}}:a._pendingRealtimeTurns,realtimeVoice:{...a.realtimeVoice,transcript:`You: ${r}
|
|
334
|
+
Assistant: `}}})},appendRealtimeVoiceAssistantDelta:(s,r)=>{r&&t(a=>{const i=a._pendingRealtimeTurns[s];let o=i==null?void 0:i.userMessageId,l=i==null?void 0:i.assistantMessageId;return{conversations:a.conversations.map(d=>{if(d.id!==s)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+r}:f),updatedAt:new Date}:(o=Dt("user"),l=Dt("assistant"),{...d,messages:[...d.messages,{id:o,content:"",role:"user",timestamp:new Date,isStreaming:!0},{id:l,content:r,role:"assistant",timestamp:new Date,isStreaming:!0}],updatedAt:new Date})}),_pendingRealtimeTurns:o&&l?{...a._pendingRealtimeTurns,[s]:{userMessageId:o,assistantMessageId:l}}:a._pendingRealtimeTurns,realtimeVoice:{...a.realtimeVoice,transcript:a.realtimeVoice.transcript+r}}})},finishRealtimeVoiceTurn:(s,r)=>{t(a=>({conversations:a.conversations.map(i=>i.id!==s?i:{...i,messages:i.messages.map(o=>{if(!o.isStreaming)return o;const l=o.role==="user"?r==null?void 0:r.userMessageId:r==null?void 0:r.assistantMessageId;return{...o,isStreaming:!1,...l?{databaseMessageId:l}:{}}}),updatedAt:new Date})})),Ge(e)},configureApiSettings:async(s,r,a)=>{const i=e(),o=i.conversations.find(c=>c.id===i.currentConversationId),l=(o==null?void 0:o.sessionId)||r||Wr();r&&Wu(r),t({sessionId:l});try{const c=await Re();if(!a||!a.trim())throw new Error("Adapter name is required");c.configureApi(s,l,a),Gr=s,Kr=!0;let d;try{const u=new c.ApiClient({apiUrl:s,sessionId:null,adapterName:a});typeof u.getAdapterInfo=="function"&&(d=await u.getAdapterInfo(),z("Adapter info loaded:",d))}catch(u){we("Failed to load adapter info:",u)}if(o)t(u=>({conversations:u.conversations.map(f=>f.id===o.id?{...f,adapterName:a,apiUrl:s,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=is();t(g=>({conversations:[...g.conversations,{id:u,sessionId:f,title:Vs,messages:[],createdAt:new Date,updatedAt:new Date,adapterName:a,apiUrl:s,adapterInfo:d,adapterLoadError:null}],currentConversationId:u}))}}catch(c){throw ke("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 s=e(),r=oe.maxConversations,a=s.conversations.length,i=s.currentConversationId?s.conversations.find(f=>f.id===s.currentConversationId):null;if(r!==null&&a>=r){if(it()&&!_t()){const g=`You've reached the guest limit of ${r} conversation${r===1?"":"s"}. Sign in to unlock more conversations, or delete conversations to start over.`;throw t({error:g}),ot.getState().openLoginPrompt(g),new Error("Guest conversation limit reached")}const f=`Maximum of ${r} 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=is(),d={id:l,sessionId:c,title:Vs,messages:[],createdAt:new Date,updatedAt:new Date,apiUrl:$e(),adapterName:No(),adapterLoadError:null};return t(f=>({conversations:[d,...f.conversations],currentConversationId:l,sessionId:c,isLoading:!1})),Ge(e),l},selectConversation:async s=>{const r=e().conversations.find(a=>a.id===s);if(r){const a=r.messages.some(c=>c.role==="assistant"&&c.isStreaming);t({currentConversationId:s,sessionId:r.sessionId,isLoading:a});const i=r.apiUrl||$e(),o=r.adapterName;if(await Os()&&o){const c=await Re();if(c.configureApi(i,r.sessionId,o),!r.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(g=>g.id===s?{...g,adapterInfo:u,adapterLoadError:null,updatedAt:new Date}:g)})),Ge(e)}}catch(d){we("Failed to load adapter info for conversation:",d)}}e().loadFeedbackForConversation(r.sessionId).catch(()=>{})}Ge(e)},deleteConversation:async s=>{var i,o;const r=e(),a=r.conversations.find(l=>l.id===s);if(z(`🗑️ Deleting conversation ${s}:`,{conversationId:s,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}),r.currentConversationId===s&&ns.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(Kt.cancelFilePoll),[...l,...c].forEach(qa)}if(a!=null&&a.sessionId)try{if(!await Os())Ve("Failed to configure API for conversation deletion");else{const c=a.apiUrl||$e(),d=a.adapterName;d?z(`Using conversation's adapter for deletion: ${d} (conversation: ${s})`):we(`Skipping server deletion for conversation ${s}: adapter not configured`);const u=await Re(),f=new u.ApiClient({apiUrl:c,sessionId:a.sessionId,adapterName:d}),g=((o=a.attachedFiles)==null?void 0:o.map(x=>x.file_id))||[],p=xi(a.messages||[]),h=[...g,...p];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&&we(` - Errors deleting files: ${x.file_deletion_errors.join(", ")}`)}else we("⚠️ deleteConversationWithFiles method not available on API client")}}catch(l){Ve("Failed to clear conversation history from server:",l)}else we(`⚠️ No session ID found for conversation ${s}, skipping server-side deletion`);t(l=>{var u;const c=l.conversations.filter(f=>f.id!==s),d=l.currentConversationId===s?((u=c[0])==null?void 0:u.id)||null:l.currentConversationId;if(c.length===0){const f=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,g=is(),p=qs(f,g,$e());return Ge(e),{conversations:[p],currentConversationId:f,sessionId:g}}return Ge(e),{conversations:c,currentConversationId:d}})},deleteAllConversations:async()=>{const r=[...e().conversations];z(`🗑️ Deleting all conversations (${r.length} total)`),ns.stop(),r.forEach(u=>{var p;const f=((p=u.attachedFiles)==null?void 0:p.map(h=>h.file_id))||[],g=(u.messages||[]).flatMap(h=>(h.attachments||[]).map(x=>x.file_id));[...f,...g].forEach(Kt.cancelFilePoll)});const a=r.map(async u=>{var f;if(u!=null&&u.sessionId)try{if(!await Os()){Ve("Failed to configure API for conversation deletion");return}const p=u.adapterName;if(!p){z(`Skipping server deletion for conversation ${u.id}: adapter not configured`);return}const h=await Re(),x=new h.ApiClient({apiUrl:dt(u.apiUrl),sessionId:u.sessionId,adapterName:p}),b=[...((f=u.attachedFiles)==null?void 0:f.map(k=>k.file_id))||[],...xi(u.messages||[])];x.deleteConversationWithFiles?(await x.deleteConversationWithFiles(u.sessionId,b),z(`✅ Deleted conversation ${u.id} and files`)):we(`deleteConversationWithFiles not available for conversation ${u.id}`)}catch(g){Ve(`Failed to delete conversation ${u.id} from server:`,g)}}),o=(await Promise.allSettled(a)).filter(u=>u.status==="rejected");o.length>0&&Ve(`Some conversations failed to delete from server: ${o.length}`,o);const l=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,c=is(),d=qs(l,c,$e());t({conversations:[d],currentConversationId:l,sessionId:c}),Ge(e)},deleteThread:async(s,r,a)=>{const i=e().conversations.find(f=>f.id===s);if(!i)throw new Error("Conversation not found");if(!i.adapterName)throw new Error("Adapter not configured for this conversation");const o=i.messages.find(f=>f.id===r);if(!(o!=null&&o.threadInfo)||o.threadInfo.thread_id!==a)throw new Error("Thread not found for this message");const l=dt(i.apiUrl||$e()),c=await Re(),d=new c.ApiClient({apiUrl:l,sessionId:i.sessionId,adapterName:i.adapterName});await new(await Ut(async()=>{const{ThreadService:f}=await import("./threadService-B9Db3n0J.js");return{ThreadService:f}},[])).ThreadService(d).deleteThread(a),t(f=>({conversations:f.conversations.map(g=>{var x;if(g.id!==s)return g;const p=g.messages.filter(b=>b.isThreadMessage?!(b.threadId===a||b.parentMessageId===r):!0).map(b=>b.id!==r?b:{...b,threadInfo:void 0,supportsThreading:!0}),h=g.currentThreadId===a||g.currentThreadSessionId===((x=o.threadInfo)==null?void 0:x.thread_session_id);return{...g,messages:p,currentThreadId:h?void 0:g.currentThreadId,currentThreadSessionId:h?void 0:g.currentThreadSessionId,updatedAt:new Date}})})),Ge(e)},sendMessage:async(s,r,a,i,o)=>{var c;let l=null;try{if(e().isLoading){we("Another request is already in progress");return}if(!await Os())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 g=oe.maxConversations;if(it()&&!_t()&&g!==null&&e().conversations.length>g){ot.getState().openLoginPrompt(`You've reached the guest limit of ${g} conversation${g===1?"":"s"}. Sign in to continue chatting.`),t({isLoading:!1});return}const p=r?r.map(y=>{var I;const C=(I=f==null?void 0:f.attachedFiles)==null?void 0:I.find(N=>N.file_id===y);return C||{file_id:y,filename:"",mime_type:"",file_size:0}}).filter(y=>y!==void 0):[];p.length>0&&p.forEach(y=>{e().addFileToConversation(u,y)});const h=a||null;let x,b=null;if(h){if(x=f.messages.find(y=>{var C;return((C=y.threadInfo)==null?void 0:C.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=gi(f.messages),S=oe.maxMessagesPerConversation;if(S!==null&&k>=S){it()&&!_t()&&ot.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.`),we(`[chatStore] Conversation ${u} reached the message limit (${S}).`),t({isLoading:!1});return}const E=oe.maxTotalMessages;if(E!==null&&e().conversations.reduce((C,I)=>C+gi(I.messages),0)>=E){it()&&!_t()&&ot.getState().openLoginPrompt(`You've reached the guest limit of ${E} total messages. Sign in to continue chatting, or delete conversations to start over.`),we(`[chatStore] Workspace reached the total message limit (${E}).`),t({isLoading:!1});return}const _={id:Dt("user"),content:s,role:"user",timestamp:new Date,attachments:p.length>0?p:void 0},v=Dt("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=oe.maxMessagesPerThread;if(y!==null&&f.messages.filter(I=>I.isThreadMessage?(I.threadId===h||I.parentMessageId===x.id)&&!(I.role==="assistant"&&I.isStreaming):!1).length>=y){it()&&!_t()&&ot.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.`),we(`[chatStore] Thread ${h} reached the message limit (${y}).`),t({isLoading:!1});return}}t(y=>{const C=y.conversations.find(N=>N.id===u),I=(C==null?void 0:C.messages.filter(N=>N.role==="assistant"&&N.isStreaming))||[];return I.length>0&&we(`Cleaning up ${I.length} existing streaming messages`),{conversations:y.conversations.map(N=>{if(N.id!==u)return N;const R=N.messages.filter(O=>!(O.role==="assistant"&&O.isStreaming));return{...N,messages:[...R,_,M],updatedAt:new Date,title:N.messages.length===0?s.slice(0,50)+(s.length>50?"...":""):N.title}}),isLoading:!0,error:null}}),l=u;let F=!1;ns.reset();try{const y=e().conversations.find(A=>A.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 C=dt(y.apiUrl),I=y.adapterName,N=b||y.sessionId,R=await Re();R.configureApi(C,N,I),h&&N!==y.sessionId&&z(`[chatStore] Thread mode: using thread session ${N} (original: ${y.sessionId})`);const{returnAudio:O,ttsVoice:X,language:j,audioFormat:L}=Eo(y);z("[chatStore] Audio settings:",{returnAudio:O,ttsVoice:X,language:j,audioFormat:L});const B=new AbortController;as=B,Wt=N,fs=l,ut=null;for await(const A of R.streamChat(s,!0,r,h||void 0,void 0,void 0,j,O,X,void 0,void 0,i,o)){if(A.request_id&&!ut&&(ut=A.request_id,z(`[chatStore] >>> CAPTURED request_id for stop: ${A.request_id}`)),A.audio_chunk&&ns.addChunk({audio:A.audio_chunk,audioFormat:A.audioFormat||"opus",chunkIndex:A.chunk_index??0}),A.text){const K=Xs(A.text);K?(e().appendToLastMessage(K,l,v),F=!0):A.text.length>100&&we("[chatStore] Filtered out potential base64 audio data from message content")}if(A.audio&&A.done&&t(K=>vt(K,l,()=>({audio:A.audio,audioFormat:A.audioFormat||"mp3"}),v)),A.image&&A.done&&(F=!0,t(K=>vt(K,l,()=>({image:A.image,imageFormat:A.image_format||"png",imageRevisedPrompt:A.image_revised_prompt,imageUrl:A.image_url}),v))),(A.video||A.video_url)&&A.done&&(F=!0,t(K=>vt(K,l,()=>({video:A.video,videoFormat:A.video_format||"mp4",videoRevisedPrompt:A.video_revised_prompt,videoUrl:A.video_url}),v))),(A.document||A.document_url)&&A.done&&(F=!0,t(K=>vt(K,l,()=>({document:A.document,documentFormat:A.document_format||"pdf",documentRevisedPrompt:A.document_revised_prompt,documentUrl:A.document_url}),v))),A.generated_audio_url&&A.done&&(F=!0,t(K=>vt(K,l,()=>({generatedAudioFormat:A.generated_audio_format||"mp3",generatedAudioRevisedPrompt:A.generated_audio_revised_prompt,generatedAudioUrl:A.generated_audio_url}),v))),A.done){z("[chatStore] Stream completed, receivedAnyText:",F);const K=A.threading;K!=null&&K.supports_threading&&t(G=>({conversations:G.conversations.map(J=>J.id!==l?J:{...J,messages:J.messages.map(q=>q.id===v?{...q,supportsThreading:!0,databaseMessageId:K.message_id}:q),updatedAt:new Date})})),A.assistant_message_id&&t(G=>({conversations:G.conversations.map(J=>J.id!==l?J:{...J,messages:J.messages.map(q=>q.id===v&&!q.databaseMessageId?{...q,databaseMessageId:A.assistant_message_id}:q),updatedAt:new Date})})),A.model&&t(G=>vt(G,l,()=>({model:A.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{const I=on(y);(I?we:Ve)(`Chat API ${I?"warning":"error"}:`,y);const R=Lo(y,"Sorry, there was an error processing your request.");e().appendToLastMessage(R,l,v)}}as=null,ut=null,Wt=null,fs=null,Wa(l,t),t(y=>{const C=y.conversations.map(N=>N.id===l?{...N,messages:N.messages.map(R=>R.id===v?{...R,isStreaming:!1}:R),updatedAt:new Date}:N),I=C.find(N=>N.id===y.currentConversationId);return{conversations:C,isLoading:I?I.messages.some(N=>N.role==="assistant"&&N.isStreaming):!1}}),Ge(e)}catch(d){Ve("Chat store error:",d),t(u=>({isLoading:!1,...u.currentConversationId===l&&{error:`Failed to send message: ${d instanceof Error?d.message:"Unknown error"}`}}))}},createThread:async(s,r)=>{try{const a=e().conversations.find(g=>g.sessionId===r);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(g=>g.id===s);if(!i)throw new Error("Message not found");const o=i.databaseMessageId||s,l=dt(a.apiUrl||$e()),c=await Re(),d=new c.ApiClient({apiUrl:l,sessionId:r,adapterName:a.adapterName}),f=await new(await Ut(async()=>{const{ThreadService:g}=await import("./threadService-B9Db3n0J.js");return{ThreadService:g}},[])).ThreadService(d).createThread(o,r);t(g=>({conversations:g.conversations.map(p=>p.sessionId!==r?p:{...p,messages:p.messages.map(h=>h.id===s?{...h,threadInfo:f,supportsThreading:!0}:h),currentThreadId:void 0,currentThreadSessionId:void 0})})),z(`[chatStore] Created thread ${f.thread_id} for message ${s}`)}catch(a){throw Ve("Failed to create thread:",a),a}},appendToLastMessage:(s,r,a)=>{const i=Xs(s);if(!i&&s){we("[chatStore] Filtered out base64 audio data from message content");return}const o=Va(i),l=r||e().currentConversationId;if(!l)return;const c=l,d=ks.get(c);d?(d.content+=o,d.messageId=a,d.timeoutId&&clearTimeout(d.timeoutId)):ks.set(c,{content:o,timeoutId:null,messageId:a});const u=()=>{const g=ks.get(c);if(!g||!g.content)return;const p=g.content,h=g.messageId;g.content="",g.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+p}),{...b,messages:k,updatedAt:new Date}})}))},f=ks.get(c);f.timeoutId=setTimeout(u,Ju)},regenerateResponse:async(s,r)=>{let a=null;try{if(e().isLoading){we("Another request is already in progress");return}if(!await Os())throw new Error("API not properly configured");const o=e(),l=o.conversations.find(p=>p.id===o.currentConversationId);if(!l)return;const c=l.messages.findIndex(p=>p.id===s);if(c===-1)return;const d=l.messages[c];if(!d||d.role!=="assistant")return;const u=l.messages[c-1];if(!u||u.role!=="user")return;const f=(u.attachments||[]).map(p=>p.file_id).filter(p=>typeof p=="string"&&p.length>0),g=Dt("assistant");if(t(p=>({conversations:p.conversations.map(h=>h.id===p.currentConversationId?{...h,messages:[...h.messages.slice(0,c),{id:g,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:r,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 bi(e,t,g,a,u.content,f,r,"regenerate",d.databaseMessageId)}catch(i){Ve("Regenerate error:",i),t(o=>({isLoading:!1,...o.currentConversationId===a&&{error:`Failed to regenerate response: ${i instanceof Error?i.message:"Unknown error"}`}}))}},editMessageAndRegenerate:async(s,r,a)=>{let i=null;try{if(e().isLoading){await e().stopStreaming();const x=e().currentConversationId;x&&Wa(x,t)}const o=e(),l=o.conversations.find(x=>x.id===o.currentConversationId);if(!l)return;const c=l.messages.findIndex(x=>x.id===s);if(c===-1)return;const d=l.messages[c];if(d.role!=="user")return;const u=(d.attachments||[]).map(x=>x.file_id).filter(x=>typeof x=="string"&&x.length>0),f=Dt("assistant"),g=l.messages[c+1],p=(g==null?void 0:g.role)==="assistant",h=p?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:r,updatedAt:new Date},{id:f,content:"",role:"assistant",timestamp:new Date,isStreaming:!0,model:a,supportsThreading:p?g.supportsThreading:void 0,databaseMessageId:p?g.databaseMessageId:void 0,threadInfo:p?g.threadInfo:void 0,threadId:p?g.threadId:void 0,parentMessageId:p?g.parentMessageId:void 0,isThreadMessage:p?g.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 bi(e,t,f,i,r,u,a,"edit-regenerate",p?g.databaseMessageId:void 0),Ge(e)}catch(o){Ve("Edit & regenerate error:",o),t(l=>({isLoading:!1,...l.currentConversationId===i&&{error:`Failed to regenerate response: ${o instanceof Error?o.message:"Unknown error"}`}}))}},updateConversationTitle:(s,r)=>{t(a=>({conversations:a.conversations.map(i=>i.id===s?{...i,title:r,updatedAt:new Date}:i)})),Ge(e)},clearError:()=>t({error:null}),cleanupStreamingMessages:()=>{const s=fs;t(r=>{let a=!1;return{conversations:r.conversations.map(o=>o.id===s?(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 s=e(),r=oe.maxConversations;if(!s.currentConversationId)return r===null||s.conversations.length<r;const a=s.conversations.find(l=>l.id===s.currentConversationId);return!!a&&(a.messages.length>0||(((o=a.attachedFiles)==null?void 0:o.length)||0)>0)?r===null||s.conversations.length<r:!1},getConversationCount:()=>e().conversations.length,addFileToConversation:(s,r)=>{z("[chatStore] addFileToConversation called",{conversationId:s,fileId:r.file_id,filename:r.filename}),t(a=>({conversations:a.conversations.map(i=>i.id===s?{...i,attachedFiles:[...(i.attachedFiles||[]).filter(o=>o.file_id!==r.file_id),r],updatedAt:new Date}:i)})),Ge(e)},removeFileFromConversation:async(s,r)=>{z("[chatStore] removeFileFromConversation called",{conversationId:s,fileId:r}),Kt.cancelFilePoll(r);try{const a=e().conversations.find(i=>i.id===s);if(!a)throw new Error("Conversation not found");if(!a.adapterName)throw new Error("Adapter not configured for this conversation. Cannot delete file.");await Kt.deleteFile(r,void 0,dt(a.apiUrl),a.adapterName),z(`[chatStore] Successfully deleted file ${r} from server`)}catch(a){a instanceof Error&&(a.message.includes("404")||a.message.includes("File not found"))?z(`[chatStore] File ${r} was already deleted from server`):ke(`[chatStore] Failed to delete file ${r} from server:`,a)}qa(r),t(a=>({conversations:a.conversations.map(i=>i.id===s?{...i,attachedFiles:(i.attachedFiles||[]).filter(o=>o.file_id!==r),updatedAt:new Date}:i)})),Ge(e)},loadConversationFiles:async s=>{try{const r=e().conversations.find(l=>l.id===s);if(!r)return;if(!r.adapterName){z(`Skipping file load for conversation ${s}: adapter not configured`);return}if(new Set((r.attachedFiles||[]).map(l=>l.file_id)).size===0){z(`No files to sync for conversation ${s}`);return}const i=await Kt.listFiles(void 0,dt(r.apiUrl),r.adapterName),o=new Map(i.map(l=>[l.file_id,{file_id:l.file_id,filename:l.filename,mime_type:l.mime_type,file_size:l.file_size,upload_timestamp:l.upload_timestamp,processing_status:l.processing_status,chunk_count:l.chunk_count}]));t(l=>{const c=l.conversations.find(u=>u.id===s);if(!c)return l;const d=(c.attachedFiles||[]).map(u=>o.get(u.file_id)||u).filter(u=>o.has(u.file_id)||!u.processing_status||u.processing_status==="processing");return{conversations:l.conversations.map(u=>u.id===s?{...u,attachedFiles:d,updatedAt:new Date}:u)}}),Ge(e)}catch(r){Ve(`Failed to load files for conversation ${s}:`,r)}},syncConversationFiles:async s=>{await e().loadConversationFiles(s)},syncConversationsWithBackend:async()=>{try{const s=e();if(s.conversations.length===0)return;const r=await Re(),a=oe.maxMessagesPerConversation!==null&&oe.maxMessagesPerConversation||void 0;let i=!1;const l=(await Promise.all(s.conversations.map(async c=>{var d;if(!c.sessionId)return null;if(!c.adapterName)return we(`[chatStore] Skipping backend sync for conversation ${c.id} - adapter not configured`),null;if(c.messages.length===0)return null;try{const u=new r.ApiClient({apiUrl:dt(c.apiUrl),sessionId:c.sessionId,adapterName:c.adapterName});if(typeof u.getConversationHistory!="function")return i||(i=!0,we("[chatStore] Conversation history endpoint not supported by current API client")),null;const f=await u.getConversationHistory(c.sessionId,a),g=Array.isArray(f==null?void 0:f.messages)?f.messages:[];if(g.length===0)return c.messages.length===0?null:{id:c.id,sessionId:(f==null?void 0:f.session_id)||c.sessionId,messages:[],cleared:!0,updatedAt:new Date};const p=Xu(g,c.messages),h=c.messages.filter(b=>b.isThreadMessage),x=Io(h.length>0?[...p,...h]:p);return Yu(c.messages,x)?null:{id:c.id,sessionId:(f==null?void 0:f.session_id)||c.sessionId,messages:x,cleared:!1,updatedAt:((d=p[p.length-1])==null?void 0:d.timestamp)||new Date}}catch(u){return we(`[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:Vs,updatedAt:f.updatedAt,adapterLoadError:null}:{...u,sessionId:f.sessionId||u.sessionId,messages:f.messages,updatedAt:f.updatedAt,adapterLoadError:null}:u}),currentConversationId:c.currentConversationId}}),Ge(e)}catch(s){we("Failed to synchronize conversations with backend:",s)}},stopStreaming:async()=>{var r;if(!e().isLoading){z("[chatStore] stopStreaming called but not currently loading");return}if(z("[chatStore] Stopping stream...",{hasAbortController:!!as,requestId:ut,sessionId:Wt}),as&&as.abort(),ut&&Wt)try{const a=await Re(),i=await((r=a.stopChat)==null?void 0:r.call(a,Wt,ut));z(`[chatStore] Server-side cancellation result: ${i}`)}catch(a){we("[chatStore] Failed to cancel server-side stream:",a)}else we(`[chatStore] Cannot call stopChat - missing IDs: requestId=${ut}, sessionId=${Wt}`);const s=fs||e().currentConversationId;t(s?a=>({conversations:a.conversations.map(i=>i.id!==s?i:{...i,messages:i.messages.map(o=>o.isStreaming?{...o,isStreaming:!1}:o),updatedAt:new Date}),isLoading:!1}):{isLoading:!1}),as=null,ut=null,Wt=null,fs=null,z("[chatStore] Stream stopped successfully")},clearCurrentConversationAdapter:()=>{const s=e().currentConversationId;s&&(t(r=>({conversations:r.conversations.map(a=>a.id===s?{...a,adapterName:void 0,adapterInfo:void 0,adapterLoadError:null}:a)})),Ge(e))},submitFeedback:async(s,r,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===s);if(!(l!=null&&l.databaseMessageId))return we("[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:dt(o.apiUrl||$e()),sessionId:o.sessionId,adapterName:o.adapterName}).submitFeedback(l.databaseMessageId,o.sessionId,r,a),f=u.feedback_type,g=u.comment??null;return t(p=>({conversations:p.conversations.map(h=>h.id!==i.currentConversationId?h:{...h,messages:h.messages.map(x=>x.id===s?{...x,feedback:f,feedbackComment:g}:x),updatedAt:new Date})})),Ge(e),!0}catch(c){return ke("[chatStore] Failed to submit feedback:",c),!1}},loadFeedbackForConversation:async s=>{var i;const a=e().conversations.find(o=>o.sessionId===s);if(a!=null&&a.adapterName)try{const o=await Re(),l=new o.ApiClient({apiUrl:dt(a.apiUrl||$e()),sessionId:a.sessionId,adapterName:a.adapterName}),c=new Set([s]);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 g of f.feedbacks)u.set(g.message_id,{feedbackType:g.feedback_type,comment:g.comment??null});if(u.size===0)return;t(f=>({conversations:f.conversations.map(g=>g.sessionId!==s?g:{...g,messages:g.messages.map(p=>{if(p.databaseMessageId&&u.has(p.databaseMessageId)){const h=u.get(p.databaseMessageId);return{...p,feedback:h.feedbackType,feedbackComment:h.comment}}return p})})}))}catch(o){ke("[chatStore] Failed to load feedback:",o)}}})),Zu=async()=>{var c;const t=localStorage.getItem("chat-state"),e=$e(),s=!!localStorage.getItem("chat-api-url");let r=Wr(),a=!1;if(t)try{const d=JSON.parse(t),u=p=>{if(p instanceof Date)return p;const h=p?new Date(p):new Date;return Number.isNaN(h.getTime())?new Date:h},g=(Array.isArray(d.conversations)?d.conversations:[]).map(p=>{const x=(Array.isArray(p.messages)?p.messages:[]).filter(E=>!(E.role==="assistant"&&E.isStreaming)).map(E=>({...E,timestamp:u(E.timestamp),isStreaming:!1})),b=Io(x),k={id:p.id,sessionId:p.sessionId||is(),title:qu(p.title),messages:b,createdAt:u(p.createdAt),updatedAt:u(p.updatedAt),attachedFiles:p.attachedFiles||[],adapterName:p.adapterName,apiUrl:p.apiUrl,adapterInfo:p.adapterInfo,adapterLoadError:p.adapterLoadError||null,audioSettings:p.audioSettings,currentThreadId:void 0,currentThreadSessionId:void 0},S=k.messages.length===0&&!k.adapterName;return{...k,apiUrl:S&&!s?e:dt(p.apiUrl)}});if(a=g.length>0,d.currentConversationId&&g.length>0){const p=g.find(h=>h.id===d.currentConversationId);p!=null&&p.sessionId&&(r=p.sessionId)}if(g.length===0){const p=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=is(),x=qs(p,h,$e());ye.setState({conversations:[x],currentConversationId:p,sessionId:h}),r=h}else ye.setState({conversations:g,currentConversationId:d.currentConversationId||((c=g[0])==null?void 0:c.id)||null,sessionId:r}),!d.currentConversationId&&g.length>0&&(ye.setState({currentConversationId:g[0].id,sessionId:g[0].sessionId||r}),r=g[0].sessionId||r);z("📋 Loaded conversations:",ye.getState().conversations.map(p=>{var h;return{id:p.id,title:p.title,sessionId:p.sessionId,messageCount:((h=p.messages)==null?void 0:h.length)||0}})),setTimeout(()=>ye.getState().cleanupStreamingMessages(),100)}catch(d){Ve("Failed to load chat state:",d);const u=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,f=is(),g=qs(u,f,$e());ye.setState({conversations:[g],currentConversationId:u,sessionId:f}),r=f}else{const d=`conv_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,u=is(),f=qs(d,u,$e());ye.setState({conversations:[f],currentConversationId:d,sessionId:u}),r=u}localStorage.removeItem("chat-api-key");const i=ye.getState(),o=i.currentConversationId?i.conversations.find(d=>d.id===i.currentConversationId):null,l=a&&(o!=null&&o.apiUrl)?o.apiUrl:$e();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,r,u),Gr=l,Kr=!0,!(o!=null&&o.adapterInfo))try{const f=new d.ApiClient({apiUrl:l,sessionId:null,adapterName:u});if(typeof f.getAdapterInfo=="function"){const g=await f.getAdapterInfo();z("Adapter info loaded for existing adapter:",g);const p=ye.getState();p.currentConversationId&&(ye.setState({conversations:p.conversations.map(h=>h.id===p.currentConversationId?{...h,adapterInfo:g,adapterLoadError:null,updatedAt:new Date}:h)}),setTimeout(()=>{const h=ye.getState();localStorage.setItem("chat-state",JSON.stringify({conversations:h.conversations,currentConversationId:h.currentConversationId}))},0))}}catch(f){we("Failed to load adapter info for existing adapter:",f)}}catch(d){Ve("Failed to initialize API:",d)}try{await ye.getState().syncConversationsWithBackend()}catch(d){we("Conversation history sync skipped:",d)}};typeof window<"u"&&Zu();function ef(t){return t.replace(/-/g," ")}function _o({skills:t,isLoading:e,selectedSkill:s,activeSkillName:r,query:a="",onSelect:i,onActiveSkillChange:o}){const{t:l}=Le(),c=St.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 St.useEffect(()=>{var g;const f=(g=c.current)==null?void 0:g.querySelector('[data-active="true"]');f==null||f.scrollIntoView({block:"nearest"})},[r,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.jsxs("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,g)=>{const p=(s==null?void 0:s.name)===f.name,h=r===f.name||!r&&(p||!s&&g===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.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:ef(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})]}),p&&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(ms,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]},f.name)})}),!e&&u.length>0&&n.jsxs("div",{className:"flex items-center gap-1 border-t border-gray-100 px-3 py-2 text-[11px] text-gray-500 dark:border-[#1f1f1f] dark:text-[#8b8b99]",children:[n.jsx(Qs,{children:"/"}),l("skillPicker.footer.slashAnytime")]})]})}function Qs({children:t,className:e=""}){return n.jsx("span",{className:`inline-flex h-[17px] min-w-[17px] items-center justify-center rounded border border-gray-300 border-b-2 bg-white px-1 align-middle font-mono text-[10px] leading-none text-current dark:border-[#3a3a3a] dark:bg-[#1f1f1f] ${e}`,"aria-hidden":"true",children:t})}function tf(t){return t.replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Ka({availableModels:t,defaultModel:e,selectedModel:s,onSelect:r,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}=Le(),f=o??u("modelPicker.selectModel"),g=l??u("modelPicker.selectModel"),p=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),C=m.useRef(null),I=s??e,N=m.useMemo(()=>{const A=b.trim().toLowerCase();return A?t.filter(K=>`${K.name} ${K.provider} ${K.model}`.toLowerCase().includes(A)):t},[t,b]),R=m.useCallback(A=>{r(A),x(!1),k(""),requestAnimationFrame(()=>{var K;return(K=F.current)==null?void 0:K.focus()})},[r]),O=m.useCallback(()=>{if(!F.current)return;const A=F.current.getBoundingClientRect(),K=Math.min(352,window.innerWidth-24),G=A.right-K;v({bottom:window.innerHeight-A.top+10,left:Math.min(window.innerWidth-K-12,Math.max(12,G))})},[]),X=m.useCallback(()=>{x(!1),k("")},[]),j=()=>{if(h){X();return}O();const A=t.findIndex(K=>K.name===I);E(Math.max(A,0)),x(!0)};if(m.useEffect(()=>{if(!h)return;const A=setTimeout(()=>{var q;return(q=y.current)==null?void 0:q.focus()},10),K=q=>{var Q,$;const H=q.target,ne=((Q=M.current)==null?void 0:Q.contains(H))??!1,T=(($=C.current)==null?void 0:$.contains(H))??!1;!ne&&!T&&X()},G=q=>{var H;if(q.key==="Escape"){q.preventDefault(),X(),(H=F.current)==null||H.focus();return}if(N.length!==0){if(q.key==="ArrowDown")q.preventDefault(),E(ne=>(ne+1)%N.length);else if(q.key==="ArrowUp")q.preventDefault(),E(ne=>(ne-1+N.length)%N.length);else if(q.key==="Home")q.preventDefault(),E(0);else if(q.key==="End")q.preventDefault(),E(N.length-1);else if(q.key==="Enter"){q.preventDefault();const ne=N[S];ne&&R(ne.name)}}},J=new ResizeObserver(O);return F.current&&J.observe(F.current),window.addEventListener("resize",O,{passive:!0}),document.addEventListener("scroll",O,{capture:!0,passive:!0}),document.addEventListener("pointerdown",K),document.addEventListener("keydown",G),()=>{clearTimeout(A),J.disconnect(),window.removeEventListener("resize",O),document.removeEventListener("scroll",O,{capture:!0}),document.removeEventListener("pointerdown",K),document.removeEventListener("keydown",G)}},[S,X,N,h,O,R]),m.useEffect(()=>{var A,K;h&&((K=(A=C.current)==null?void 0:A.querySelector(`[data-model-index="${S}"]`))==null||K.scrollIntoView({block:"nearest"}))},[S,h]),!e&&t.length===0)return null;const L=h&&_&&typeof document<"u"?Qr.createPortal(n.jsxs("div",{ref:C,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:N.length}),n.jsx("button",{type:"button",onClick:()=>{X(),requestAnimationFrame(()=>{var A;return(A=F.current)==null?void 0:A.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(Qe,{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(Hr,{className:"h-4 w-4 shrink-0 text-gray-400","aria-hidden":"true"}),n.jsx("input",{ref:y,type:"text",value:b,onChange:A=>{k(A.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":p,"aria-activedescendant":N[S]?`${p}-option-${S}`:void 0})]})}),n.jsx("div",{className:"mx-3 border-t border-gray-100 dark:border-white/[0.07]"}),n.jsx("div",{id:p,role:"listbox","aria-label":g,className:"max-h-72 overflow-y-auto p-2",children:N.length===0?n.jsxs("div",{className:"flex flex-col items-center px-4 py-8 text-center",children:[n.jsx(Hr,{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")})]}):N.map((A,K)=>{const G=I===A.name,J=S===K;return n.jsxs("button",{id:`${p}-option-${K}`,"data-model-index":K,role:"option","aria-selected":G,type:"button",onMouseMove:()=>E(K),onClick:()=>R(A.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:A.name}),n.jsxs("span",{className:"mt-0.5 block truncate text-xs text-gray-500 dark:text-gray-400",children:[tf(A.provider),A.model!==A.name?` · ${A.model}`:""]})]}),n.jsx("span",{className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full ${G?"bg-gray-900 text-white dark:bg-white dark:text-gray-900":"text-transparent"}`,children:n.jsx(ms,{className:"h-3 w-3",strokeWidth:3,"aria-hidden":"true"})})]},A.name)})}),N.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:N.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:I??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-1.5 rounded-full border border-gray-300 bg-white ${d} shadow-sm transition-all motion-reduce:transition-none hover:border-gray-400 hover:shadow focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 dark:border-white/20 dark:bg-white/[0.07] dark:hover:border-white/35 dark:hover:bg-white/[0.11] dark:focus-visible:ring-white/20`,"aria-haspopup":"listbox","aria-expanded":h,"aria-controls":h?p:void 0,title:f,children:[B,n.jsx("span",{className:"h-4 w-px shrink-0 bg-gray-300 transition-colors motion-reduce:transition-none group-hover:bg-gray-400 dark:bg-white/20 dark:group-hover:bg-white/35","aria-hidden":"true"}),n.jsx(js,{className:`-mr-0.5 h-4 w-4 shrink-0 text-gray-500 transition-all duration-200 motion-reduce:transition-none dark:text-gray-300 ${h?"rotate-180":"group-hover:translate-y-px"}`,"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:I??void 0,children:B})})}function Xr({filename:t,fileId:e,status:s,statusText:r,errorMessage:a,onRemove:i,removeTitle:o,className:l=""}){const c=s==="uploading"||s==="processing",d=s==="error",u=zu(t),f=e?Bu(e):void 0,g=u.Icon,p=d?a||r:r||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(Br,{className:"h-[18px] w-[18px] animate-spin text-white drop-shadow"})})]}):c?n.jsx(Br,{className:"h-[18px] w-[18px] animate-spin"}):d?n.jsx(Ua,{className:"h-[18px] w-[18px]"}):n.jsx(g,{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}),p&&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:p})]}),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(Qe,{className:"h-3 w-3"})})]})}const ja=2e3;function To({initialValue:t="",onSubmit:e,onCancel:s,isSubmitting:r=!1}){const{t:a}=Le(),[i,o]=m.useState(t??""),l=m.useRef(null);m.useEffect(()=>{const d=l.current;d&&(d.focus(),d.setSelectionRange(d.value.length,d.value.length))},[]),m.useEffect(()=>{const d=l.current;d&&(d.style.height="auto",d.style.height=`${Math.min(d.scrollHeight,120)}px`)},[i]);const c=()=>{r||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(),s())},disabled:r,rows:1,maxLength:ja,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>=ja?"text-red-600 font-semibold":"",children:[i.length,"/",ja]})}),n.jsx("button",{type:"button",onClick:s,disabled:r,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:r,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(Or,{className:"h-3.5 w-3.5"}),a("message.feedback.commentSend")]})]})]})}const sf=[],rf=(t="png")=>{const e=t.toLowerCase().replace(/^image\//,"");return e==="jpg"?"image/jpeg":`image/${e||"png"}`},af=(t,e)=>{const s=atob(t),r=new Uint8Array(s.length);for(let a=0;a<s.length;a+=1)r[a]=s.charCodeAt(a);return new Blob([r],{type:e})},nf=async t=>{const e=URL.createObjectURL(t);try{const s=new Image;s.decoding="async";const r=new Promise((o,l)=>{s.onload=()=>o(s),s.onerror=()=>l(new Error("Failed to load generated image for clipboard copy"))});s.src=e,await r;const a=document.createElement("canvas");a.width=s.naturalWidth,a.height=s.naturalHeight;const i=a.getContext("2d");if(!i)throw new Error("Could not create canvas context for image clipboard copy");return i.drawImage(s,0,0),await new Promise((o,l)=>{a.toBlob(c=>{c?o(c):l(new Error("Could not encode generated image for clipboard copy"))},"image/png")})}finally{URL.revokeObjectURL(e)}},of=async(t,e)=>{const s=rf(t.imageFormat);if(t.image)return af(t.image,s);if(!t.imageUrl)return null;const r=await fetch(t.imageUrl,{headers:e?{"X-Adapter-Name":e}:{}});if(!r.ok)throw new Error(`Could not fetch generated image for clipboard copy: ${r.status}`);const a=await r.blob();return a.type?a:new Blob([a],{type:s})},lf=t=>t.imageUrl?new URL(t.imageUrl,window.location.origin).toString():t.imageRevisedPrompt||t.content;function yi({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(s=>n.jsx("span",{className:`inline-block ${e} animate-bounce rounded-full bg-gray-400 dark:bg-[#bfc2cd]`,style:{animationDelay:`${s}ms`}},s))})}function cf({reply:t}){const{t:e}=Le(),[s,r]=m.useState(!1),[a,i]=m.useState(!1),[o,l]=m.useState(!1),[c,d]=m.useState(!1),u=m.useRef(null),f=ye(x=>x.submitFeedback);m.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const g=()=>{i(!0),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{i(!1),u.current=null},2e3)},p=async x=>{if(!t.databaseMessageId||s)return;const b=t.feedback!==x,k=x==="down"&&b;r(!0);try{if(!await f(t.id,x))return;k?(i(!1),l(!0)):(l(!1),b?g():i(!1))}catch(S){ke("Failed to submit thread reply feedback:",S)}finally{r(!1)}},h=async x=>{if(t.databaseMessageId){d(!0);try{if(!await f(t.id,"down",x))return;l(!1),g()}catch(b){ke("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:()=>p("up"),disabled:s,className:`rounded-md p-1.5 transition-colors ${s?"opacity-50 cursor-not-allowed":""} ${t.feedback==="up"?"text-green-600 dark:text-green-400":"hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]"}`,title:e("message.feedback.good"),"aria-label":e("message.feedback.good"),children:n.jsx(xo,{className:"h-4 w-4"})}),n.jsx("button",{onClick:()=>p("down"),disabled:s,className:`rounded-md p-1.5 transition-colors ${s?"opacity-50 cursor-not-allowed":""} ${t.feedback==="down"?"text-red-600 dark:text-red-400":"hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]"}`,title:e("message.feedback.poor"),"aria-label":e("message.feedback.poor"),children:n.jsx(go,{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(ms,{className:"h-3.5 w-3.5"}),e("message.feedback.thanks")]})]}),t.feedback==="down"&&o&&n.jsx(To,{initialValue:t.feedbackComment,onSubmit:h,onCancel:()=>l(!1),isSubmitting:c})]})}function df({message:t,onRegenerate:e,onEdit:s,onStartThread:r,onClearThread:a,onSendThreadMessage:i,threadMessages:o,sessionId:l,isThreadSendDisabled:c,availableModels:d=[],defaultModel:u=null,selectedModel:f=null,assistantActions:g="full"}){var ir,Qt,Fs;const{t:p}=Le(),[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),[C,I]=m.useState(!1),[N,R]=m.useState(!1),[O,X]=m.useState(!1),[j,L]=m.useState(""),[B,A]=m.useState(!1),[K,G]=m.useState(!1),[J,q]=m.useState(!1),[H,ne]=m.useState(0),[T,Q]=m.useState(!1),[$,W]=m.useState(!1),[ae,he]=m.useState(()=>f??u),U=m.useRef(f),V=m.useRef(((ir=t.threadInfo)==null?void 0:ir.thread_id)||null),se=m.useRef(null),ue=m.useRef(null),pe=m.useRef(null),fe=m.useRef(null),ve=m.useRef(!1),ge=m.useRef(0),Te=m.useRef(""),De=m.useRef(!1),_e=m.useRef(!0),Y=m.useRef(!1),Z=m.useRef(null),le=m.useRef(null),de=t.role==="assistant",Ee=g==="full",me=o??sf,Me=me.filter(P=>!(P.role==="assistant"&&P.isStreaming)).length,Ue=me.some(P=>P.isStreaming),Ze=Cs(),jt=it()&&!Ze,Fe=ye(P=>P.conversations.find(xe=>xe.id===P.currentConversationId)),Tt=!!((t.image||t.imageUrl)&&de&&!t.isStreaming),os=!!((t.video||t.videoUrl)&&de&&!t.isStreaming),Bt=p(Tt?"message.copyImageLabel":"message.copyLabel"),et=Dc(),Gt=oe.maxMessageLength,Mt=oe.maxMessagesPerThread,Ae=Mt!==null&&Me>=Mt,ft=Ae?jt?p("message.thread.limitReachedGuest",{count:Mt}):p("message.thread.limitReachedUser",{count:Mt}):null,{theme:mt,isDark:Xt}=ps(),Se=p("message.thread.placeholder"),Ce=`thread-input-${t.id}`,re=p("messageInput.skillsHint.placeholderBeforeKey"),Be=p("messageInput.skillsHint.placeholderAfterKey"),ht=`${Se} ${re} / ${Be}`,{skills:st,isLoading:As,selectedSkill:Ct,selectSkill:Ns,clearSkill:gs}=jo({adapterName:Fe==null?void 0:Fe.adapterName,enabled:et&&!!t.threadInfo,selectionScopeKey:((Qt=t.threadInfo)==null?void 0:Qt.thread_id)||t.id}),rt=j.startsWith("/")?j.slice(1):"",Is=rt.toLowerCase().replace(/-/g," "),pt=Is?st.filter(P=>P.name.replace(/-/g," ").toLowerCase().includes(Is)||P.description.toLowerCase().includes(Is)):st,Js=pt.length>0?Math.min(H,pt.length-1):0,nt=pt[Js]??null,xs=(nt==null?void 0:nt.name.replace(/-/g," "))??"",Yt=J&&nt&&j.startsWith("/")&&xs.toLowerCase().startsWith(rt.toLowerCase())&&xs.length>rt.length?xs.slice(rt.length):null,Ht=mt.mode==="dark"?"dark":mt.mode==="light"?"light":"",At=Xt?"dark":"light",Zs=m.useMemo(()=>["message-markdown w-full min-w-0","prose prose-slate dark:prose-invert max-w-none",Ht].filter(Boolean).join(" "),[Ht]),er=m.useMemo(()=>["message-markdown w-full min-w-0","prose dark:prose-invert max-w-none",Ht].filter(Boolean).join(" "),[Ht]),Nt=de?Zs:er,tr=`${Zs} text-sm leading-6`,qe=`${er} text-sm leading-6`;m.useEffect(()=>{var P,xe;!V.current&&((P=t.threadInfo)!=null&&P.thread_id)&&A(!0),V.current=((xe=t.threadInfo)==null?void 0:xe.thread_id)||null},[(Fs=t.threadInfo)==null?void 0:Fs.thread_id]),m.useEffect(()=>{t.threadInfo||setTimeout(()=>{L(""),A(!1),G(!1),q(!1),gs()},0)},[t.threadInfo,gs]),m.useEffect(()=>{Me>0&&setTimeout(()=>{A(!0)},0)},[Me]),m.useEffect(()=>()=>{Z.current&&clearTimeout(Z.current),le.current&&clearTimeout(le.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 Es=m.useCallback(()=>{const P=b.trim();if(!P||P===t.content){x(!1);return}s==null||s(t.id,P),x(!1)},[b,t.content,t.id,s]),gt=m.useCallback(()=>{requestAnimationFrame(()=>{fe.current&&(fe.current.scrollTop=fe.current.scrollHeight)})},[]);m.useEffect(()=>{if(!B)return;const P=me.length,xe=P>ge.current,ee=me[me.length-1],Ie=(ee==null?void 0:ee.content)||"",yt=Ie!==Te.current,Jt=(ee==null?void 0:ee.isStreaming)??!1,wt=De.current&&!Jt;xe||Jt&&yt||wt?(gt(),_e.current=!0):_e.current&&yt&>(),ge.current=P,Te.current=Ie,De.current=Jt},[B,me,gt]),m.useEffect(()=>{B&&(gt(),_e.current=!0)},[B,gt]);const ia=de?"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)]",Ft=m.useCallback(()=>{M(!0),Z.current&&clearTimeout(Z.current),Z.current=setTimeout(()=>{M(!1),Z.current=null},2e3)},[]),xt=async()=>{try{if(Tt){if("ClipboardItem"in window&&navigator.clipboard.write)try{const xe=(Fe==null?void 0:Fe.adapterName)||(typeof window<"u"?window.localStorage.getItem("chat-adapter-name"):null),ee=await of(t,xe);if(ee){const Ie=ee.type==="image/png"?ee:await nf(ee);await navigator.clipboard.write([new ClipboardItem({[Ie.type||"image/png"]:Ie})]),Ft();return}}catch(xe){ke("Failed to copy generated image, falling back to text:",xe)}const P=lf(t);if(P){await navigator.clipboard.writeText(P),Ft();return}return}await navigator.clipboard.writeText(t.content),Ft()}catch(P){ke(Tt?"Failed to copy generated image:":"Failed to copy text:",P)}},sr=ye(P=>P.submitFeedback),rr=()=>{I(!0),le.current&&clearTimeout(le.current),le.current=setTimeout(()=>{I(!1),le.current=null},2e3)},ar=async P=>{if(!t.databaseMessageId||F)return;const xe=t.feedback!==P,ee=P==="down"&&xe;y(!0);try{if(!await sr(t.id,P))return;ee?(I(!1),R(!0)):(R(!1),xe?rr():I(!1))}catch(Ie){ke("Failed to submit feedback:",Ie)}finally{y(!1)}},Rt=async P=>{if(t.databaseMessageId){X(!0);try{if(!await sr(t.id,"down",P))return;R(!1),rr()}catch(xe){ke("Failed to submit feedback comment:",xe)}finally{X(!1)}}},Ls=async()=>{if(!i||!t.threadInfo||Ae)return;const P=j.trim();if(!P)return;const xe=j,ee=Ct,Ie=Ct==null?void 0:Ct.name;L(""),G(!0),q(!1),Ie&&gs();try{await i(t.threadInfo.thread_id,t.id,P,Ie,ae??u??void 0),setTimeout(()=>{se.current&&se.current.focus()},100)}catch(yt){ke("Failed to send thread message:",yt),L(xe),ee&&Ns(ee),setTimeout(()=>{se.current&&se.current.focus()},100)}finally{G(!1)}},_s=m.useCallback(P=>{var xe;Ns(P),q(!1),L(ue.current??""),ue.current=null,ne(0),(xe=se.current)==null||xe.focus()},[Ns]),bs=m.useCallback(()=>{var P;q(!1),L(ue.current??""),ue.current=null,ne(0),(P=se.current)==null||P.focus()},[]),nr=m.useCallback(()=>{var P;L(xe=>(ue.current=xe.length>0?xe:null,"/")),q(!0),ne(0),(P=se.current)==null||P.focus()},[]),Ts=P=>{if(J){if(P.key==="ArrowDown"){P.preventDefault(),ne(xe=>pt.length===0?0:(xe+1)%pt.length);return}if(P.key==="ArrowUp"){P.preventDefault(),ne(xe=>pt.length===0?0:(xe-1+pt.length)%pt.length);return}if(P.key==="Home"){P.preventDefault(),ne(0);return}if(P.key==="End"){P.preventDefault(),ne(Math.max(pt.length-1,0));return}if((P.key==="Enter"&&!P.shiftKey||P.key==="Tab")&&nt){P.preventDefault(),_s(nt);return}if(P.key==="Escape"){P.preventDefault(),bs();return}}P.key==="Enter"&&!P.shiftKey&&(P.preventDefault(),Ls())},bt=!t.threadInfo||!i||c||Ue||K||Ae,ls=!Ct&&st.length>0&&!bt&&j.length===0,lt=ls?ht:Se,oa=!!t.threadInfo&&!!a&&Me>0&&!Ue&&!K&&!c,It=async()=>{if(!(!t.threadInfo||!a)){W(!0);try{await a(t.id,t.threadInfo.thread_id),Q(!1),A(!1),L("")}catch(P){ke("Failed to clear thread:",P)}finally{W(!1)}}};m.useEffect(()=>{U.current=f},[f]),m.useEffect(()=>{he(U.current??u)},[u]),m.useEffect(()=>{if(!B||bt){Y.current=K;return}const P=se.current;if(!P){Y.current=K;return}if(!(ve.current||Y.current)){Y.current=K;return}const ee=requestAnimationFrame(()=>{var yt;ve.current&&((yt=pe.current)==null||yt.scrollIntoView({behavior:"auto",block:"nearest",inline:"nearest"})),P.focus();const Ie=P.value.length;P.setSelectionRange(Ie,Ie),ve.current=!1,Y.current=K});return()=>{cancelAnimationFrame(ee),Y.current=K}},[B,bt,K]),m.useEffect(()=>{if(se.current){const xe=se.current;xe.style.height="auto";const ee=xe.scrollHeight;xe.style.height=`${Math.min(ee,120)}px`,xe.style.overflowY=ee>120?"auto":"hidden"}},[j]);const Ms=m.useMemo(()=>{if(t.isStreaming&&(!t.content||t.content==="…"))return n.jsx("div",{className:Nt,children:n.jsx(yi,{})});const P=t.isStreaming&&de?" streaming-cursor":"";return n.jsx("div",{className:P||void 0,children:n.jsx(zt,{content:Va(Xs(t.content||"")),className:Nt,syntaxTheme:At})})},[Nt,t.content,t.isStreaming,de,At]),la=m.useMemo(()=>{const P=ee=>ee instanceof Date?ee.getTime():new Date(ee).getTime();return[...me].sort((ee,Ie)=>P(ee.timestamp)-P(Ie.timestamp)).map(ee=>{const Ie=ee.role==="assistant",yt=Ie?tr:qe,Jt=ee.isStreaming&&Ie?" streaming-cursor":"",wt=ee.isStreaming&&(!ee.content||ee.content==="…")?n.jsx("div",{className:yt,children:n.jsx(yi,{size:"sm"})}):n.jsx("div",{className:Jt||void 0,children:n.jsx(zt,{content:Va(Xs(ee.content||"")),className:yt,syntaxTheme:At})});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:[wt,ee.audio&&Ie&&!ee.isStreaming&&n.jsx(jr,{audio:ee.audio,audioFormat:ee.audioFormat,autoPlay:!1}),(ee.image||ee.imageUrl)&&Ie&&!ee.isStreaming&&n.jsx(ni,{image:ee.image,imageUrl:ee.imageUrl,imageFormat:ee.imageFormat,revisedPrompt:ee.imageRevisedPrompt}),(ee.video||ee.videoUrl)&&Ie&&!ee.isStreaming&&n.jsx(ii,{video:ee.video,videoUrl:ee.videoUrl,videoFormat:ee.videoFormat,revisedPrompt:ee.videoRevisedPrompt,adapterName:Fe==null?void 0:Fe.adapterName}),(ee.document||ee.documentUrl)&&Ie&&!ee.isStreaming&&n.jsx(di,{document:ee.document,documentUrl:ee.documentUrl,documentFormat:ee.documentFormat,revisedPrompt:ee.documentRevisedPrompt,adapterName:Fe==null?void 0:Fe.adapterName}),ee.generatedAudioUrl&&Ie&&!ee.isStreaming&&n.jsx(jr,{audioUrl:ee.generatedAudioUrl,audioFormat:ee.generatedAudioFormat,downloadFilename:`generated-audio.${ee.generatedAudioFormat||"mp3"}`,autoPlay:!1})]}),Ie&&!ee.isStreaming&&ee.model&&n.jsx("div",{className:"px-1 pt-0.5 text-[11px] text-gray-400 dark:text-[#9a9ab0]",children:p("message.generatedBy",{model:ee.model})}),Ie&&!ee.isStreaming&&vr()&&n.jsx(cf,{reply:ee})]})},ee.id)})},[Fe==null?void 0:Fe.adapterName,At,p,tr,me,qe]);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:de?void 0:"flex flex-col items-end",children:[n.jsxs("div",{className:ia,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(),Es()),P.key==="Escape"&&(P.stopPropagation(),x(!1),k(t.content||""))},maxLength:oe.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:p("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:p("common.cancel")}),n.jsxs("button",{onClick:Es,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(Or,{className:"w-3.5 h-3.5"}),p("common.send")]})]})]})]}):Ms,t.attachments&&t.attachments.length>0&&n.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:t.attachments.map(P=>n.jsx(Xr,{filename:P.filename,fileId:P.file_id,status:"completed",statusText:`${(P.file_size/1024).toFixed(1)} KB`},P.file_id))}),t.audio&&de&&!t.isStreaming&&n.jsx(jr,{audio:t.audio,audioFormat:t.audioFormat,autoPlay:!1}),(t.image||t.imageUrl)&&de&&!t.isStreaming&&n.jsx(ni,{image:t.image,imageUrl:t.imageUrl,imageFormat:t.imageFormat,revisedPrompt:t.imageRevisedPrompt}),(t.video||t.videoUrl)&&de&&!t.isStreaming&&n.jsx(ii,{video:t.video,videoUrl:t.videoUrl,videoFormat:t.videoFormat,revisedPrompt:t.videoRevisedPrompt,adapterName:Fe==null?void 0:Fe.adapterName}),(t.document||t.documentUrl)&&de&&!t.isStreaming&&n.jsx(di,{document:t.document,documentUrl:t.documentUrl,documentFormat:t.documentFormat,revisedPrompt:t.documentRevisedPrompt,adapterName:Fe==null?void 0:Fe.adapterName}),t.generatedAudioUrl&&de&&!t.isStreaming&&n.jsx(jr,{audioUrl:t.generatedAudioUrl,audioFormat:t.generatedAudioFormat,downloadFilename:`generated-audio.${t.generatedAudioFormat||"mp3"}`,autoPlay:!1})]}),!de&&!h&&n.jsxs("div",{className:"flex items-center gap-0.5 py-1 text-gray-400 dark:text-[#8e8ea0]",children:[n.jsx("button",{onClick:xt,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:Bt,"aria-label":Bt,children:v?n.jsx(ms,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):n.jsx(Xn,{className:"h-4 w-4"})}),s&&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:p("message.editAriaLabel"),"aria-label":p("message.editAriaLabel"),children:n.jsx(ho,{className:"h-4 w-4"})})]})]}),de&&!t.isStreaming&&t.model&&n.jsx("div",{className:"px-1 pt-0.5 text-[11px] text-gray-400 dark:text-[#9a9ab0]",children:p("message.generatedBy",{model:t.model})}),de&&!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:[!os&&n.jsx("button",{onClick:xt,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:Bt,"aria-label":Bt,children:v?n.jsx(ms,{className:"h-4 w-4 text-emerald-500 dark:text-emerald-400"}):n.jsx(Xn,{className:"h-4 w-4"})}),Ee&&vr()&&n.jsxs("div",{className:"relative flex items-center gap-0.5",children:[n.jsx("button",{onClick:()=>ar("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:p("message.feedback.good"),"aria-label":p("message.feedback.good"),children:n.jsx(xo,{className:"h-4 w-4"})}),n.jsx("button",{onClick:()=>ar("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:p("message.feedback.poor"),"aria-label":p("message.feedback.poor"),children:n.jsx(go,{className:"h-4 w-4"})}),C&&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(ms,{className:"h-3.5 w-3.5"}),n.jsx("span",{children:p("message.feedback.thanks")})]})]})]}),Ee&&vr()&&t.feedback==="down"&&!N&&n.jsx("button",{type:"button",onClick:()=>R(!0),className:"inline-flex items-center rounded-md px-2 py-1 text-xs font-medium transition-colors hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-[#3c3f4a] dark:hover:text-[#ececf1]",children:t.feedbackComment?p("message.feedback.commentEdit"):p("message.feedback.commentPrompt")}),Ee&&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:p("message.regenerateTitle"),"aria-label":p("message.regenerateAriaLabel"),children:n.jsx(Pd,{className:"h-4 w-4"})}),Ee&&et&&t.supportsThreading&&!t.threadInfo&&r&&l&&n.jsxs("button",{type:"button",onClick:()=>{ve.current=!0,A(!0),r(t.id,l)},className:"ml-1 inline-flex items-center gap-1.5 rounded-full border border-blue-200 bg-blue-50 px-2.5 py-1.5 text-xs text-blue-700 shadow-sm transition-all hover:border-blue-300 hover:bg-blue-100 hover:text-blue-800 hover:shadow-md dark:border-blue-500/30 dark:bg-blue-500/10 dark:text-blue-200 dark:hover:border-blue-400/50 dark:hover:bg-blue-500/20 dark:hover:text-blue-100 animate-follow-up-enter whitespace-nowrap",title:p("message.thread.continueDiscussionTitle"),"aria-label":p("message.thread.continueDiscussionAriaLabel"),children:[n.jsx(Yn,{className:"h-3.5 w-3.5 shrink-0"}),n.jsx("span",{children:p("message.thread.continueLabel")})]}),Ee&&et&&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:()=>A(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(Yn,{className:"h-4 w-4"}),n.jsx("span",{className:"truncate",children:p("message.thread.replyCount",{count:Me})}),B?n.jsx(zr,{className:"h-3 w-3"}):n.jsx(js,{className:"h-3 w-3"})]}),oa&&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:p("message.thread.clearTitle"),"aria-label":p("message.thread.clearAriaLabel"),children:p("common.clear")})]})]}),de&&!t.isStreaming&&Ee&&vr()&&t.feedback==="down"&&N&&n.jsx(To,{initialValue:t.feedbackComment,onSubmit:Rt,onCancel:()=>R(!1),isSubmitting:O}),et&&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:fe,className:"thread-replies-scroll mt-2 space-y-2 pb-3",onScroll:()=>{if(!fe.current)return;const{scrollTop:P,scrollHeight:xe,clientHeight:ee}=fe.current;_e.current=xe-P-ee<100},children:Me>0?la:null}),ft&&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:[ft,jt&&n.jsx("div",{className:"mt-2",children:n.jsx("button",{type:"button",onClick:()=>ot.getState().openLoginPrompt(p("message.thread.signInPromptMessage")),className:"inline-flex items-center gap-1 rounded-md bg-blue-600 px-2.5 py-1 text-[11px] font-medium text-white hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600",children:p("message.thread.signInForHigherLimits")})})]}),n.jsxs("div",{ref:pe,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:[Ct&&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("span",{className:"min-w-0 truncate font-medium capitalize",children:Ct.name.replace(/-/g," ")}),n.jsx("button",{type:"button",onClick:()=>gs(),className:"-mr-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-white/10 dark:hover:text-gray-100","aria-label":p("message.thread.removeSkillAriaLabel"),children:n.jsx(Qe,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),!Ct&&st.length>0&&!bt&&n.jsxs("button",{type:"button",onClick:nr,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 md:hidden","aria-label":p("message.thread.skillsHintAriaLabel"),title:p("message.thread.skillsHint"),children:[n.jsx(Qs,{children:"/"}),n.jsx("span",{className:"sr-only",children:p("messageInput.skillsHint.keyLabel")}),p("messageInput.skillsHint.text")]}),n.jsxs("div",{className:"relative flex min-h-8 flex-1 items-center min-w-0",children:[n.jsx("label",{htmlFor:Ce,className:"sr-only",children:p("message.thread.placeholder")}),Yt&&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:Yt})]}),ls&&n.jsxs("div",{className:"pointer-events-none absolute inset-0 truncate whitespace-nowrap px-0 py-0 text-base leading-8 text-slate-500 dark:text-[#70707c] sm:text-sm sm:leading-8","aria-hidden":"true",children:[Se,n.jsxs("span",{className:"ml-1 hidden md:inline",children:[re," ",n.jsx(Qs,{className:"mx-0.5",children:"/"})," ",Be]})]}),n.jsx("textarea",{id:Ce,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] outline-none transition focus:outline-none disabled:opacity-60 dark:text-[#ececf1] sm:text-sm sm:leading-8 ${ls?"placeholder-transparent dark:placeholder-transparent":"placeholder-slate-500 dark:placeholder-[#70707c]"}`,placeholder:lt,"aria-label":p("message.thread.placeholder"),value:j,onChange:P=>{const xe=P.target.value;if(xe.startsWith("/")){L(xe),ne(0),q(!0);return}if(xe.length===0&&ue.current!==null){L(ue.current),ue.current=null,q(!1);return}ue.current=null,L(xe),q(!1)},onKeyDown:Ts,disabled:bt,rows:1,maxLength:Gt,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(Ka,{availableModels:d,defaultModel:u,selectedModel:ae,onSelect:he,maxWidthClass:"max-w-[120px]",triggerPaddingClass:"px-2 py-1",staticPaddingClass:"px-2 py-1",triggerTitle:p("message.thread.selectModelTitle"),listboxLabel:p("message.thread.selectModelTitle")}),j.trim().length>0&&n.jsx("button",{type:"button",onClick:Ls,disabled:bt||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:p("message.thread.sendMessageTitle"),children:n.jsx(Or,{className:"h-5 w-5 sm:h-4 sm:w-4"})})]})]}),J&&n.jsx("div",{className:"w-full pt-1",children:n.jsx(_o,{skills:st,isLoading:As,selectedSkill:Ct,activeSkillName:nt==null?void 0:nt.name,query:rt,onActiveSkillChange:P=>{const xe=pt.findIndex(ee=>ee.name===P.name);xe>=0&&ne(xe)},onSelect:_s,onClose:bs})})]}),Me>0&&n.jsx("div",{className:"mt-2 flex justify-end",children:n.jsxs("button",{type:"button",onClick:()=>A(!1),className:"inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-[#bfc2cd] dark:hover:bg-[#2f313a] dark:hover:text-white","aria-label":p("message.thread.hideRepliesAriaLabel"),children:[n.jsx(zr,{className:"h-3 w-3"}),n.jsx("span",{children:p("message.thread.hideRepliesLabel")})]})})]})]}),n.jsx(qr,{isOpen:T,onClose:()=>{$||Q(!1)},onConfirm:It,title:p("message.confirmation.clearRepliesTitle"),message:p("message.confirmation.clearRepliesMessage"),confirmText:p("common.clear"),cancelText:p("common.cancel"),type:"danger",isLoading:$})]})}let ws=null;function uf(){if(typeof window>"u")return null;const t=window.AudioContext??window.webkitAudioContext;return t?((!ws||ws.state==="closed")&&(ws=new t),ws.state==="suspended"&&ws.resume(),ws):(z("[SoundEffects] AudioContext not supported in this browser"),null)}function ff(t){const e=uf();if(!e)return;const s=e.currentTime;for(const r of t){const a=e.createOscillator(),i=e.createGain();a.connect(i),i.connect(e.destination),a.frequency.value=r.frequency,a.type=r.type;const o=s+r.startTime,l=o+r.duration;i.gain.setValueAtTime(.001,o),i.gain.linearRampToValueAtTime(r.gain,o+.008),i.gain.exponentialRampToValueAtTime(.001,l),a.start(o),a.stop(l+.01)}}const mf={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 zs(t,e){if(!e)return;const s=mf[t];if(!s){z(`[SoundEffects] Unknown sound effect type: ${t}`);return}try{ff(s),z(`[SoundEffects] Playing ${t} sound effect`)}catch(r){z(`[SoundEffects] Failed to play ${t} sound effect:`,r)}}function wi({messages:t,onRegenerate:e,onEditMessage:s,onStartThread:r,onClearThread:a,onSendThreadMessage:i,sessionId:o,isLoading:l,contentMaxWidthClass:c="max-w-[64rem]",availableModels:d,defaultModel:u,selectedModel:f,assistantActions:g="full"}){const p=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}=Jr(),{t:_}=Le(),{topLevelMessages:v,threadLookup:M}=m.useMemo(()=>{const C=new Map,I=[];return t.forEach(N=>{if(N.isThreadMessage&&N.parentMessageId){const R=C.get(N.parentMessageId)||[];C.set(N.parentMessageId,[...R,N]);return}I.push(N)}),{topLevelMessages:I,threadLookup:C}},[t]),F=()=>{if(!h.current)return;const{scrollTop:C,scrollHeight:I,clientHeight:N}=h.current,O=I-C-N<200;S.current=O},y=m.useCallback(()=>{requestAnimationFrame(()=>{h.current&&(h.current.scrollTop=h.current.scrollHeight)})},[]);return m.useEffect(()=>{const C=t.length,I=x.current,N=C>I,R=t[t.length-1],O=(R==null?void 0:R.content)||"",X=O!==b.current,j=(R==null?void 0:R.isStreaming)??!1;N||j&&X?(y(),S.current=!0):S.current&&X&&y(),x.current=C,b.current=O},[t,y]),m.useEffect(()=>{l&&(y(),S.current=!0)},[l,y]),m.useEffect(()=>{if(k.current&&!l){const C=t[t.length-1];(C==null?void 0:C.role)==="assistant"&&C.content&&zs("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(C=>n.jsx("div",{className:`flex w-full ${C.role==="user"?"justify-end":"justify-start"}`,style:{contentVisibility:"auto",containIntrinsicSize:"420px"},children:n.jsx(df,{message:C,onRegenerate:e,onEdit:s,onStartThread:r,onClearThread:a,onSendThreadMessage:i,threadMessages:M.get(C.id),sessionId:o,isThreadSendDisabled:l,availableModels:d,defaultModel:u,selectedModel:f,assistantActions:g})},C.id)),n.jsx("div",{ref:p,className:"h-8"})]})})})}const hf=4e3;function pf(t,e,s={}){var C;const{t:r}=Le(),[a,i]=m.useState(!1),[o,l]=m.useState(null),c=m.useRef(null),d=m.useRef(""),u=m.useRef(""),f=m.useRef(!1),g=m.useRef(null),p=typeof navigator<"u"?navigator.language:"en-US",h=Number.isFinite(s.silenceTimeoutMs)?Math.max(Math.floor(s.silenceTimeoutMs),1e3):hf,x=((C=s.language)==null?void 0:C.trim())||p||"en-US",b=m.useCallback(I=>I.replace(/\s+/g," ").trim(),[]),k=m.useCallback(I=>{const N=b(I);N&&N!==u.current&&(u.current=N,t(N))},[b,t]),S=m.useCallback(()=>{if(!d.current)return;const I=d.current;d.current="",k(I)},[k]),E=typeof window<"u"&&("webkitSpeechRecognition"in window||"SpeechRecognition"in window),_=m.useCallback(()=>{!e||f.current||(f.current=!0,e())},[e]),v=m.useCallback(()=>{g.current!==null&&(clearTimeout(g.current),g.current=null)},[]),M=m.useCallback(()=>{v(),g.current=setTimeout(()=>{z("Speech recognition silence threshold reached, stopping recording"),c.current?c.current.stop():_()},h)},[v,_,h]),F=m.useCallback(()=>{if(!E){l(r("voice.browserNotSupported"));return}if(!c.current)try{f.current=!1;const I=window.SpeechRecognition||window.webkitSpeechRecognition,N=new I;N.continuous=!0,N.interimResults=!0,N.lang=x,N.maxAlternatives=1,N.onstart=()=>{i(!0),l(null),d.current="",u.current="",z("Speech recognition started"),M()},N.onresult=R=>{let O="",X="";for(let j=R.resultIndex;j<R.results.length;j++){const L=R.results[j][0].transcript;R.results[j].isFinal?O+=L:X+=L}X&&(d.current=b(X)),O&&(d.current="",k(O)),M()},N.onend=()=>{v(),S(),i(!1),c.current=null,z("Speech recognition ended"),_()},N.onerror=R=>{switch(v(),ke("Speech recognition error:",R.error),i(!1),c.current=null,d.current="",_(),R.error){case"no-speech":l(r("voice.error.noSpeech"));break;case"audio-capture":l(r("voice.error.audioCapture"));break;case"not-allowed":l(r("voice.error.notAllowed"));break;case"network":l(r("voice.error.network"));break;default:l(r("voice.error.generic",{error:R.error}))}},N.start(),c.current=N}catch(I){ke("Failed to start speech recognition:",I),l(r("voice.error.startFailed")),i(!1)}},[E,S,_,M,v,x,b,k,r]),y=m.useCallback(()=>{if(z("Stopping speech recognition..."),c.current){const I=c.current;I.onstart=null,I.onerror=null;try{I.stop()}catch(N){z("Recognition already stopped or error stopping:",N),v(),S(),I.onend=null,I.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 gf=300,ki=3,Lr=5,xf=6e4;function vi(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 bf(t,e={}){const{enabled:s=eo(),adapterName:r,sessionId:a,adapterSupportsAutocomplete:i,skill:o,inputRef:l}=e,[c,d]=m.useState([]),[u,f]=m.useState(!1),[g,p]=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(),A=v.current.length>0?v.current:_.current;if(!B)return A.slice(0,Lr);const K=A.filter(G=>G.text.toLowerCase().includes(B));return K.length>0?K.slice(0,Lr):L?A.slice(0,Lr):[]},[]),C=m.useCallback(async j=>{if(!s||j.length<ki){d([]),v.current=[],x.current&&clearTimeout(x.current),b.current&&clearTimeout(b.current),f(!1);return}if(!r){d([]),v.current=[],x.current&&clearTimeout(x.current),f(!1);return}if(i===!1||F(r)){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":r};a&&(B["X-Session-ID"]=a);const A=new URLSearchParams;A.set("q",j),A.set("limit",String(Lr)),o&&A.set("skill",o);const K=`/api/v1/autocomplete?${A.toString()}`,G=await fetch(K,{method:"GET",headers:B,signal:k.current.signal});if(!G.ok){we("[useAutocomplete] Request failed:",G.status),[404,405,501].includes(G.status)?(M.current.set(r,Date.now()+xf),d([]),v.current=[]):d(y(j));return}const J=await G.json(),q=Array.isArray(J==null?void 0:J.suggestions)?J.suggestions.map(H=>vi(typeof H=="string"?H:H==null?void 0:H.text)).filter(H=>H!==null):[];if(L!==E.current)return;q.length===0?d(y(j,!1)):(d(q),v.current=q),p(-1),z("[useAutocomplete] Received",q.length,"suggestions")}catch(B){if(B instanceof Error&&B.name==="AbortError")return;we("[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))}},[s,r,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(!s||t.length<ki||i===!1||r&&F(r)){L();return}if(S.current){if(t===S.current){L();return}S.current=null}return h.current=setTimeout(()=>{C(t)},gf),()=>{h.current&&clearTimeout(h.current),b.current&&(clearTimeout(b.current),b.current=null)}},[t,C,s,r,i,F]),m.useEffect(()=>()=>{k.current&&k.current.abort(),x.current&&clearTimeout(x.current)},[]);const I=m.useCallback(()=>{p(j=>{const L=_.current.length;return L===0?-1:j<L-1?j+1:0})},[]),N=m.useCallback(()=>{p(j=>{const L=_.current.length;return L===0?-1:j>0?j-1:L-1})},[]),R=m.useCallback(()=>{d([]),v.current=[],p(-1),k.current&&k.current.abort(),x.current&&clearTimeout(x.current),f(!1)},[]),O=m.useCallback(j=>{if(!(l!=null&&l.current))return;const L=()=>{const B=l.current;if(!B)return;const A=typeof j=="string"?j.length:B.value.length;B.focus({preventScroll:!0}),typeof B.setSelectionRange=="function"&&B.setSelectionRange(A,A)};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:g,setSelectedIndex:p,selectNext:I,selectPrevious:N,clearSuggestions:R,focusInputAfterSelection:O,suppressUntilQueryChange:X}}const ss=new Map,yf=new Map,wf=new Map,kf=new Set,vf=()=>{if(typeof window>"u")return null;try{return localStorage.getItem("chat-adapter-name")}catch{return null}},Mo=t=>typeof t=="object"&&t!==null&&"message"in t,Sf=t=>t instanceof Error?t.message:typeof t=="string"?t:Mo(t)?t.message??"Unknown error":"Unknown error";function jf({conversationId:t,onFilesSelected:e,onUploadError:s,onClose:r,onUploadingChange:a,onUploadSuccess:i,maxFiles:o=oe.maxFilesPerConversation,disabled:l=!1}){const{t:c}=Le(),[d,u]=m.useState(!1),[f,g]=m.useState(0),p=m.useRef(null),h=m.useRef(wf),x=m.useRef(kf),b=m.useRef(new Map),k=m.useRef(!0),S=m.useRef(yf),E=m.useRef(t),_=ye(T=>T.conversations),v=m.useMemo(()=>{if(!t)return new Map;const T=ss.get(t);return T?new Map(T):new Map},[t,f]),M=m.useMemo(()=>{var $;if(!t)return Array.from(v.entries());const T=_.find(W=>W.id===t),Q=new Set((($=T==null?void 0:T.attachedFiles)==null?void 0:$.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),g(ae=>ae+1);return}const Q=ss.get(T)||new Map,$=_.find(ae=>ae.id===T),W=new Map(Q);if($){const ae=new Set(($.attachedFiles||[]).map(U=>U.file_id)),he=new Set(($.attachedFiles||[]).filter(U=>U.processing_status==="completed"||U.processing_status==="failed"||U.processing_status==="error").map(U=>U.file_id));W.forEach((U,V)=>{if(U.fileId&&he.has(U.fileId)){W.delete(V);return}U.fileId&&x.current.has(U.fileId)&&!ae.has(U.fileId)&&(z(`[FileUpload] Removing progress for deleted file ${U.fileId}`),h.current.delete(U.fileId),W.delete(V))})}W.size>0?(ss.set(T,W),a==null||a(T,!0)):(ss.delete(T),a==null||a(T,!1)),g(ae=>ae+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 $=ss.get(T)||new Map,W=Q(new Map($));W.size>0?ss.set(T,W):ss.delete(T),a==null||a(T,W.size>0),g(ae=>ae+1)},[a]),C=m.useCallback((T,Q)=>{if(!T)return;const $=S.current.get(T)||[],W=Q([...$||[]]),ae=new Set($.map(he=>he.file_id));if(S.current.set(T,W),e(T,W),i){const he=W.filter(U=>!ae.has(U.file_id));he.length>0&&i(T,he)}g(he=>he+1)},[e,i]),I=ye(T=>T.removeFileFromConversation),N=ye(T=>T.addFileToConversation);m.useEffect(()=>(k.current=!0,()=>{k.current=!1}),[]);const R=m.useCallback(()=>{k.current=!1,new Map(b.current).forEach(Q=>Q.abort()),setTimeout(()=>{const Q=ye.getState(),$=new Map(Q.conversations.map(ae=>[ae.id,ae])),W=[];h.current.forEach((ae,he)=>{var U;if(ae){const V=$.get(ae);if(new Set(((U=V==null?void 0:V.attachedFiles)==null?void 0:U.map(ue=>ue.file_id))||[]).has(he)){x.current.add(he),h.current.delete(he);return}}if(x.current.has(he)){z(`[FileUpload] Skipping cleanup delete for ${he}; file was previously attached and already handled`),h.current.delete(he),x.current.delete(he);return}W.push({fileId:he,conversationId:ae||null})}),W.length>0&&(r==null||r(),W.forEach(async({fileId:ae,conversationId:he})=>{try{if(he)await I(he,ae);else{const U=vf();Kt.cancelFilePoll(ae),await Kt.deleteFile(ae,void 0,void 0,U??void 0),qa(ae)}}catch(U){if(Mo(U)){const V=U.message??"";!V.includes("404")&&!V.includes("File not found")&&we(`Failed to cleanup file ${ae} during component unmount:`,U)}else we(`Failed to cleanup file ${ae} during component unmount`,U)}}))},300)},[r,I]);m.useEffect(()=>R,[R]);const O=m.useCallback(async T=>{var fe;if(!T||T.length===0)return;const Q=Array.from(T),$=ye.getState(),W=t||$.currentConversationId;if(!W){s==null||s(c("fileUpload.selectBeforeUpload"));return}const ae=$.conversations.find(ve=>ve.id===W);if(!ae){s==null||s(c("fileUpload.conversationNotFound"));return}const he=ae.attachedFiles||[],U=[],V=Q.filter(ve=>he.some(Te=>Te.filename===ve.name&&Te.file_size===ve.size)?(U.push(ve.name),!1):!0);if(U.length>0&&(s==null||s(U.length===1?c("fileUpload.duplicateFileError",{filename:U[0]}):c("fileUpload.duplicateFilesError",{count:U.length}))),V.length===0)return;if((S.current.get(W)||[]).length+V.length>o){const ve=c("fileUpload.maxFilesPerConversationError",{count:o});it()&&!_t()&&ot.getState().openLoginPrompt(c("fileUpload.maxFilesGuestLimitMessage",{count:o})),s==null||s(ve);return}if(oe.maxTotalFiles!==null&&$.conversations.reduce((Te,De)=>{var _e;return Te+(((_e=De.attachedFiles)==null?void 0:_e.length)||0)},0)+V.length>oe.maxTotalFiles){const Te=c("fileUpload.maxTotalFilesError",{count:oe.maxTotalFiles});it()&&!_t()&&ot.getState().openLoginPrompt(c("fileUpload.maxTotalFilesGuestLimitMessage",{count:oe.maxTotalFiles})),s==null||s(Te);return}if(!ae.adapterName){s==null||s(c("fileUpload.adapterNotConfigured"));return}const ue=ae.adapterName,pe=dt(ae.apiUrl);for(let ve=0;ve<V.length;ve++){const ge=V[ve],Te=new AbortController;b.current.set(ge.name,Te);const De=`${W}-${ge.name}-${Date.now()}-${ve}`;let _e=null;const Y=ge.type.startsWith("image/")?URL.createObjectURL(ge):null;try{const Z=await Kt.uploadFile(ge,le=>{if(y(W,de=>(de.set(De,le),de)),le.fileId&&!_e){_e=le.fileId,h.current.set(le.fileId,W),x.current.add(le.fileId),Y&&Ao(le.fileId,Y);const de={file_id:le.fileId,filename:ge.name,mime_type:ge.type||"application/octet-stream",file_size:ge.size,processing_status:le.status==="uploading"?"uploading":le.status==="processing"?"processing":le.status==="completed"?"completed":void 0};z(`[FileUpload] Adding file ${le.fileId} to conversation ${W} immediately (status: ${de.processing_status})`),N(W,de)}},void 0,pe,ue).catch(le=>{if(le.message&&le.message.includes("was deleted")){_e&&h.current.delete(_e);const de=le.message.match(/File\s+([\w-]+)\s+was deleted/);return de&&de[1]&&h.current.delete(de[1]),z(`File ${ge.name} was deleted during upload`),null}throw le});if(Z){const le=ye.getState().conversations.find(me=>me.id===W),de=((fe=le==null?void 0:le.attachedFiles)==null?void 0:fe.some(me=>me.file_id===Z.file_id))??!1;if(x.current.has(Z.file_id)&&!de){z(`[FileUpload] Skipping final update for deleted file ${Z.file_id}`),h.current.delete(Z.file_id),x.current.delete(Z.file_id),y(W,me=>(me.delete(De),me));continue}h.current.set(Z.file_id,W),x.current.add(Z.file_id),z(`[FileUpload] Updating file ${Z.file_id} in conversation ${W} with final status`),N(W,Z),Z.processing_status==="completed"||Z.processing_status==="failed"||Z.processing_status==="error"?y(W,me=>(me.delete(De),me)):y(W,me=>{const Me=me.get(De);return Me&&me.set(De,{...Me,progress:90,status:"processing",fileId:Z.file_id}),me}),C(W,me=>{if(new Set(me.map(Ze=>Ze.file_id)).has(Z.file_id))return me;const Ue=[...me,Z];return z(`[FileUpload] Updated uploadedFiles for ${W}: ${Ue.length} files`,Ue),Ue})}else we(`Upload completed for ${ge.name} but uploadedAttachment is null`),y(W,le=>(le.delete(De),le))}catch(Z){const le=Sf(Z);if(Z instanceof DOMException&&Z.name==="AbortError"||Te.signal.aborted){z(`Upload cancelled for ${ge.name}`),_e?h.current.delete(_e):Y&&URL.revokeObjectURL(Y),y(W,me=>(me.delete(De),me));continue}if(le.includes("was deleted")){z(`File ${ge.name} was deleted during upload`),_e&&h.current.delete(_e);const me=le.match(/File\s+([\w-]+)\s+was deleted/);me&&me[1]&&h.current.delete(me[1]),y(W,Me=>(Me.delete(De),Me));continue}k.current?(ke(`Failed to upload file ${ge.name}:`,Z),ke(`File type: ${ge.type}, File name: ${ge.name}`),s==null||s(le||`Failed to upload ${ge.name}`)):we(`Upload error for ${ge.name} (component unmounted):`,le),_e?h.current.delete(_e):Y&&URL.revokeObjectURL(Y);const de=De,Ee=W;setTimeout(()=>{y(Ee,me=>(me.delete(de),me))},5e3)}finally{b.current.delete(ge.name)}}},[N,t,o,s,c,C,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;O(Q)},[l,O]),B=m.useCallback(T=>{const Q=T.target.files;O(Q),p.current&&(p.current.value="")},[O]),A=m.useCallback(()=>{!l&&p.current&&p.current.click()},[l]),K=m.useCallback(T=>{l||(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),A())},[l,A]),G=M.length>0,J=m.useMemo(()=>{const T=new Map;return _.forEach(Q=>{T.set(Q.id,Q.title||c("chatInterface.newChatTitle"))}),T},[_,c]),q=m.useMemo(()=>{const T=[];return ss.forEach((Q,$)=>{$!==t&&Q.size>0&&T.push({conversationId:$,uploads:Array.from(Q.entries()).map(([W,ae])=>({key:W,progress:ae}))})}),T},[t,f]),H=(T,Q)=>{const $=T.status==="uploading"?c("fileUpload.uploadingStatus"):T.status==="processing"?c("fileUpload.processingStatus"):T.status==="completed"?c("fileUpload.completedStatus"):void 0;return n.jsx(Xr,{filename:T.filename,fileId:T.fileId,status:T.status,statusText:$,errorMessage:T.error||(T.status==="error"?c("fileUpload.processingFailedMessage"):void 0)},Q)},ne=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])=>H(Q,T))}):null;return n.jsxs("div",{className:"w-full max-w-full overflow-hidden space-y-2",children:[G&&ne,!G&&!l&&n.jsxs("button",{type:"button",onClick:A,onKeyDown:K,onDragOver:X,onDragLeave:j,onDrop:L,disabled:l,className:`
|
|
335
|
+
group relative w-full max-w-full rounded-lg border p-4 transition-all duration-200 text-left overflow-hidden
|
|
336
|
+
${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]"}
|
|
337
|
+
`,"aria-label":c(l?"fileUpload.disabledAriaLabel":"fileUpload.enabledAriaLabel"),children:[n.jsx("input",{ref:p,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(zd,{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})})]})]})]}),q.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")}),q.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:$,progress:W})=>H(W,$))})]},T))]})]})}const Si={"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/tiff":"tiff","image/tif":"tif","image/gif":"gif","image/webp":"webp","application/pdf":"pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/msword":"doc","text/plain":"txt","text/markdown":"md","application/json":"json"},Ca=4,_r=3,Cf=0,Af=0,Aa=2;function Nf(t){if(!t||typeof t!="object")return null;const e=t,s=["supportsAutocomplete","isAutocompleteSupported","autocompleteSupported"];for(const i of s)if(typeof e[i]=="boolean")return e[i];const r=["capabilities","features"],a=["autocomplete","supportsAutocomplete","autocomplete_supported"];for(const i of r){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 If(t){if(!t)return"bin";if(Si[t])return Si[t];const e=t.split("/");return e.length===2&&e[1]?e[1]:"bin"}function Ef(t){return t.replace(/[^a-zA-Z0-9._-]/g,"_").replace(/_+/g,"_")||"pasted-file"}function Lf(t){const e=t.lastIndexOf(".");return e===-1||e===t.length-1?null:t.slice(e+1).toLowerCase()}function _f(t){const e=t.lastIndexOf(".");return e===-1?t:t.slice(0,e)}function Na(t){return!t||t==="processing"||t==="uploading"}function Tf(t,e){const s=Date.now(),r=t.name&&t.name.trim().length>0?t.name.trim():"pasted-file",a=Ef(_f(r)),o=Lf(r)||If(t.type),l=`${a}-${s}-${e}.${o}`;return new File([t],l,{type:t.type||"application/octet-stream"})}function ji({onSend:t,disabled:e=!1,placeholder:s=Ji(),autoFocusEnabled:r=!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:g=null,onSelectModel:p}){var An;const{t:h}=Le(),[x,b]=m.useState(""),[k,S]=m.useState(!1),[E,_]=m.useState(!1),[v,M]=m.useState(!1),[F,y]=m.useState(!1),[C,I]=m.useState([]),[N,R]=m.useState({}),[O,X]=m.useState(new Map),[j,L]=m.useState(!1),[B,A]=m.useState(!1),[K,G]=m.useState(null),[J,q]=m.useState(null),[H,ne]=m.useState(null),[T,Q]=m.useState({isOpen:!1,fileId:"",filename:"",isDeleting:!1}),$=m.useRef(null),W=m.useRef(null),ae=m.useRef(null),he=m.useRef(null),U=m.useRef(null),V=m.useRef(null),se=m.useRef(new Set),ue=m.useRef(""),pe=m.useRef(!1),fe=m.useRef(0),ve=m.useRef(null),{settings:ge,updateSettings:Te}=Jr(),{theme:De,isDark:_e}=ps(),Y=De.mode==="dark"?"dark":De.mode==="light"?"light":"",Z=_e?"dark":"light";Gs(W,{enabled:v,onEscape:()=>M(!1)});const le=m.useCallback((w,D)=>{w&&R(ce=>{if(ce[w]===D)return ce;const je={...ce};return D?je[w]=!0:delete je[w],je})},[]),[de,Ee]=m.useState(0),[me,Me]=m.useState(!1),[Ue,Ze]=m.useState(0),[jt,Fe]=m.useState(()=>({top:Ca+_r,bottom:Math.max(Ca-_r,0)})),[Tt,os]=m.useState(null),Bt=Cs(),et=it()&&!Bt,Gt=ot(w=>w.showLoginPrompt),{createConversation:Mt,currentConversationId:Ae,conversations:ft,isLoading:mt,syncConversationFiles:Xt,stopStreaming:Se,removeFileFromConversation:Ce}=ye(),re=ft.find(w=>w.id===Ae),Be=re?re.messages.filter(w=>!(w.role==="assistant"&&w.isStreaming)).length:0,ht=ft.reduce((w,D)=>w+D.messages.filter(ce=>!(ce.role==="assistant"&&ce.isStreaming)).length,0),st=!!re&&oe.maxMessagesPerConversation!==null&&Be>=oe.maxMessagesPerConversation,As=oe.maxTotalMessages!==null&&ht>=oe.maxTotalMessages,Ct=m.useCallback(()=>{Ee(w=>w+1)},[]),Ns=Uc(),gs=Oc(),{isListening:rt,isSupported:Is,startListening:pt,stopListening:Js,error:nt}=pf(w=>{b(D=>{const ce=D.length>0&&!/\s$/.test(D)?" ":"",je=(D+ce+w).slice(0,oe.maxMessageLength);return ue.current=je,je})},Ct,{silenceTimeoutMs:Ns,language:gs||void 0}),xs=$c(),Yt=Pc(),Ht=Yt&&Is,At=Rc(),Zs=eo(),er=Nf(re==null?void 0:re.adapterInfo),{skills:Nt,isLoading:tr,selectedSkill:qe,selectSkill:Es,clearSkill:gt}=d,ia=(re==null?void 0:re.adapterName)||null,{suggestions:Ft,selectedIndex:xt,setSelectedIndex:sr,selectNext:rr,selectPrevious:ar,clearSuggestions:Rt,focusInputAfterSelection:Ls,suppressUntilQueryChange:_s}=bf(x,{enabled:Zs&&!rt,apiUrl:re==null?void 0:re.apiUrl,adapterName:ia,sessionId:re==null?void 0:re.sessionId,adapterSupportsAutocomplete:er,skill:(qe==null?void 0:qe.name)||null,inputRef:$}),bs=Ft.length>0,nr=!rt,Ts=nr&&bs&&!me,bt=x.startsWith("/")?x.slice(1):"",ls=bt.toLowerCase().replace(/-/g," "),lt=ls?Nt.filter(w=>w.name.replace(/-/g," ").toLowerCase().includes(ls)||w.description.toLowerCase().includes(ls)):Nt,oa=lt.length>0?Math.min(Ue,lt.length-1):0,It=lt[oa]??null,Ms=(It==null?void 0:It.name.replace(/-/g," "))??"",la=me&&It&&x.startsWith("/")&&Ms.toLowerCase().startsWith(bt.toLowerCase())&&Ms.length>bt.length?Ms.slice(bt.length):null,ir=xt>=0?xt:0,Qt=bs?Ft[ir]:null,Fs=m.useMemo(()=>{if(!Qt)return null;const w=Qt.text||"";if(!x)return w;const D=x;return w.toLowerCase().startsWith(D.toLowerCase())&&w.length>D.length?w.slice(D.length):null},[Qt,x]),P=la??Fs,xe=x.trim().length===0&&!P,ee=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 D=w.slice(0,x.length),ce=w.slice(x.length);return n.jsxs("span",{className:"line-clamp-1",children:[n.jsx("span",{className:"text-gray-500 dark:text-[#8e8ea0]",children:D}),n.jsx("span",{className:"font-semibold text-[#353740] dark:text-[#ececf1]",children:ce})]})},[x]),Ie=m.useCallback(w=>{var D;Es(w),Me(!1),b(V.current??""),V.current=null,Rt(),Ze(0),(D=$.current)==null||D.focus()},[Rt,Es]),yt=m.useCallback(()=>{var w;b(D=>(V.current=D.length>0?D:null,"/")),Me(!0),Ze(0),(w=$.current)==null||w.focus()},[]),Jt=m.useCallback(()=>{var w;Me(!1),b(V.current??""),V.current=null,Ze(0),(w=$.current)==null||w.focus()},[]),wt=m.useCallback(()=>{const w=$.current;if(!w||typeof window>"u")return;const D=Ne=>{const Xe=Ne+_r,tt=Math.max(Ne-_r,0);w.style.paddingTop=`${Xe}px`,w.style.paddingBottom=`${tt}px`,Fe({top:Xe,bottom:tt})},ce=window.getComputedStyle(w),je=parseFloat(ce.lineHeight||"0");!Number.isNaN(je)&&je>0?os(Ne=>Ne===je?Ne:je):os(Ne=>Ne===null?Ne:null),D(Ca)},[]),Vo=()=>{const w=$.current;return w?w.selectionStart===w.selectionEnd&&w.selectionStart===x.length:!1},un=(re==null?void 0:re.attachedFiles)||[],ys=Ae?un:C,qo=ft.reduce((w,D)=>{var ce;return w+(((ce=D.attachedFiles)==null?void 0:ce.length)||0)},0),fn=oe.maxFilesPerConversation!==null&&oe.maxFilesPerConversation>0&&un.length>=oe.maxFilesPerConversation,mn=oe.maxTotalFiles!==null&&qo>=oe.maxTotalFiles,Rs=((An=re==null?void 0:re.adapterInfo)==null?void 0:An.isFileSupported)??!1,ca=ys.some(w=>w.processing_status?w.processing_status!=="completed"&&w.processing_status!=="error"&&w.processing_status!=="failed":!0),kt=Ae?!!N[Ae]:!1,or=Object.values(N).some(Boolean),da=x.trim().length>0,ua=st||As,Oe=e||ca||kt||ua,hn=At&&Rs,lr=fn||mn,$s=!hn||e||kt||ua||lr,pn=!F&&(kt||O.size>0),gn=F||kt&&O.size===0;m.useLayoutEffect(()=>{if($.current){const w=$.current,D=120;if(x.length===0){w.style.height="32px",w.style.overflowY="hidden",wt();return}w.style.height="auto";const ce=w.scrollHeight;w.style.height=`${Math.min(ce,D)}px`,w.style.overflowY=ce>D?"auto":"hidden",wt()}},[x,wt]),m.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const w=$.current;if(!w)return;const D=new ResizeObserver(()=>{wt()});return D.observe(w),()=>{D.disconnect()}},[wt]);const xn=()=>{const w=document.activeElement;return w&&w.tagName==="TEXTAREA"},cr=m.useCallback(()=>typeof window>"u"?!1:!!(i&&!window.matchMedia("(min-width: 1024px)").matches||a&&window.matchMedia("(max-width: 767px)").matches),[i,a]),dr=m.useCallback(()=>{var w;(w=$.current)==null||w.focus({preventScroll:i})},[i]);m.useEffect(()=>{cr()||r&&!Oe&&$.current&&!xn()&&dr()},[r,Oe,cr,dr]);const bn=!!qe||Nt.length>0&&x.length===0&&!Oe;m.useEffect(()=>{if(typeof window>"u"||!window.matchMedia("(max-width: 767px)").matches||!bn||document.activeElement!==$.current)return;const w=window.requestAnimationFrame(()=>{const D=$.current;!D||document.activeElement!==D||(D.blur(),D.focus({preventScroll:!0}))});return()=>window.cancelAnimationFrame(w)},[bn]);const fa=m.useRef(mt);m.useEffect(()=>{if(cr()){fa.current=mt;return}r&&fa.current&&!mt&&!Oe&&$.current&&setTimeout(()=>{$.current&&!xn()&&dr()},100),fa.current=mt},[r,mt,Oe,cr,dr]),m.useEffect(()=>{if(!Ht||(de>fe.current&&(pe.current=!0,fe.current=de),!pe.current||de===0))return;const w=ue.current.trim(),D=ye.getState();if(z("[MessageInput] Auto-send check after voice completion:",{hasMessage:!!w,isInputDisabled:Oe,isComposing:k,isLoading:D.isLoading}),pe.current=!1,!w)return;if(Oe||k){z("[MessageInput] Auto-send skipped because input is currently disabled or composing");return}const ce=D.conversations.find(tt=>tt.id===D.currentConversationId),Ne=((ce==null?void 0:ce.attachedFiles)||[]).map(tt=>tt.file_id),Xe=qe==null?void 0:qe.name;z("[MessageInput] Auto-sending voice message immediately:",w),t(w,Ne.length>0?Ne:void 0,void 0,Xe),Xe&>(),setTimeout(()=>{Me(!1)},0),Rt(),setTimeout(()=>{b("")},0),ue.current="",$.current&&($.current.style.height="auto",$.current.style.overflowY="hidden",wt())},[Ht,de,Oe,k,t,qe,gt,wt,Rt]),m.useEffect(()=>{kt&&F&&setTimeout(()=>{y(!1)},0)},[kt,F]);const ur=m.useCallback((w,D)=>{setTimeout(()=>{var Ye,Zt;let ce=ye.getState(),je=D||ce.currentConversationId;if(je||(je=Mt(),ce=ye.getState(),je=ce.currentConversationId||je),!je){ke("[MessageInput] Unable to sync files: conversation ID missing");return}const Ne=((Zt=(Ye=ce.conversations.find(ct=>ct.id===je))==null?void 0:Ye.attachedFiles)==null?void 0:Zt.map(ct=>ct.file_id))||[],Xe=new Set([...Ne,...w.map(ct=>ct.file_id)]),tt=`${je}-`,He=[];se.current.forEach((ct,es)=>{es.startsWith(tt)&&!Xe.has(es.slice(tt.length))&&He.push(es)}),He.forEach(ct=>se.current.delete(ct)),w.forEach(ct=>{const es=`${je}-${ct.file_id}`;se.current.has(es)||(se.current.add(es),z(`[MessageInput] Adding file ${ct.file_id} to conversation ${je}`),ce.addFileToConversation(je,ct))})},0)},[Mt]);m.useEffect(()=>{if(Ae!==ve.current)if(ve.current=Ae||null,Ae&&re){const w=re.attachedFiles||[];setTimeout(()=>{I(w.map(D=>({...D})))},0)}else setTimeout(()=>{I([])},0)},[Ae,re]),m.useEffect(()=>{if(Ae&&re){const w=re.attachedFiles||[];w.length>0?setTimeout(()=>{I(D=>{const ce=new Set(D.map(Ne=>Ne.file_id)),je=w.filter(Ne=>!ce.has(Ne.file_id));return je.length>0?(z(`[MessageInput] Syncing ${je.length} missing files from conversation to UI`),[...D,...je]):D})},0):w.length===0&&C.length>0&&setTimeout(()=>{I([])},0)}},[Ae,re,ft,C.length]);const ma=m.useRef(null),ha=m.useRef(""),fr=(re==null?void 0:re.attachedFiles)||[],mr=fr.length>0?`${fr.length}:${fr.map(w=>w.file_id).join("|")}`:"",yn=fr.some(w=>Na(w.processing_status));m.useEffect(()=>{if(!Ae||!(re!=null&&re.adapterName))return;const w=mr!=="";if(w&&(ma.current!==Ae||ha.current!==mr)?(z(`[MessageInput] Syncing files for conversation ${Ae}...`),ma.current=Ae,ha.current=mr,Xt(Ae).catch(je=>{ke("[MessageInput] Failed to sync conversation files:",je)})):w||(ma.current=Ae,ha.current=""),!yn)return;z("[MessageInput] Files still processing, starting poll...");const ce=setInterval(async()=>{const Ne=ye.getState().conversations.find(He=>He.id===Ae);if(!Ne){clearInterval(ce);return}if((Ne.attachedFiles||[]).filter(He=>Na(He.processing_status)).length===0){z("[MessageInput] All files completed processing, stopping poll"),clearInterval(ce);return}try{await Xt(Ae)}catch(He){ke("[MessageInput] Failed to poll file status:",He)}},3e3);return()=>{clearInterval(ce)}},[Ae,re==null?void 0:re.adapterName,mr,yn,Xt]),m.useEffect(()=>{setTimeout(()=>{R(w=>{const D=new Set(ft.map(Ne=>Ne.id));let ce=!1;const je={...w};return Object.keys(je).forEach(Ne=>{D.has(Ne)||(delete je[Ne],ce=!0)}),ce?je:w})},0)},[ft]);const wn=w=>{if(w.preventDefault(),da&&!Oe&&!k){rt&&Js();const ce=((re==null?void 0:re.attachedFiles)||[]).map(Ne=>Ne.file_id),je=qe==null?void 0:qe.name;t(x.trim(),ce.length>0?ce:void 0,void 0,je),je&>(),Me(!1),zs("messageSent",ge.soundEnabled),b(""),ue.current="",I([]),y(!1),$.current&&($.current.style.height="auto",$.current.style.overflowY="hidden",wt())}},hr=m.useCallback(w=>{if(!w||w.length===0)return;const D=w.length===1?h("messageInput.uploadSuccess.single",{filename:w[0].filename}):h("messageInput.uploadSuccess.multiple",{count:w.length});zs("success",ge.soundEnabled),q(D),setTimeout(()=>{q(null)},6e3)},[ge.soundEnabled,h]),Wo=m.useCallback((w,D)=>{z(`[MessageInput] handleFilesSelected called with ${D.length} files for conversation ${w}:`,D),w&&(w===Ae&&I(D),ur(D,w))},[Ae,ur]),Ko=m.useCallback((w,D)=>{w===Ae&&hr(D)},[Ae,hr]),Go=m.useCallback(w=>{Q({isOpen:!0,fileId:w.file_id,filename:w.filename,isDeleting:!1})},[]),Xo=m.useCallback(()=>{Q(w=>w.isDeleting?w:{isOpen:!1,fileId:"",filename:"",isDeleting:!1})},[]),Yo=m.useCallback(async()=>{if(!(!Ae||!T.fileId)){Q(w=>({...w,isDeleting:!0}));try{await Ce(Ae,T.fileId),I(w=>w.filter(D=>D.file_id!==T.fileId)),Q({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}catch(w){const D=w instanceof Error?w.message:h("messageInput.fileRemoveFailed");ke("[MessageInput] Failed to remove file:",w),ne(D),Q({isOpen:!1,fileId:"",filename:"",isDeleting:!1})}}},[Ae,T.fileId,Ce,h]),kn=m.useCallback(w=>w.replace(/\s+/g," ").trim(),[]),pr=m.useCallback(w=>{const D=kn(w);b(D),Rt(),_s(D),Ls(D)},[Rt,Ls,kn,_s]),pa=m.useCallback(w=>{if(w<0)return;const D=Ft[w]||Ft[0];D&&pr(D.text)},[Ft,pr]),Qo=w=>{if(me){if(w.key==="ArrowDown"){w.preventDefault(),Ze(D=>lt.length===0?0:(D+1)%lt.length);return}if(w.key==="ArrowUp"){w.preventDefault(),Ze(D=>lt.length===0?0:(D-1+lt.length)%lt.length);return}if(w.key==="Home"){w.preventDefault(),Ze(0);return}if(w.key==="End"){w.preventDefault(),Ze(Math.max(lt.length-1,0));return}if((w.key==="Enter"&&!w.shiftKey||w.key==="Tab")&&It){w.preventDefault(),Ie(It);return}if(w.key==="Escape"){w.preventDefault(),Jt();return}}if(bs&&nr){if(w.key==="ArrowDown"){w.preventDefault(),rr();return}if(w.key==="ArrowUp"){w.preventDefault(),ar();return}if(w.key==="Tab"){w.preventDefault();const D=xt>=0?xt:0;pa(D);return}if(w.key==="ArrowRight"&&Vo()){if(Fs&&Qt){w.preventDefault(),pr(Qt.text);return}if(xt>=0){w.preventDefault(),pa(xt);return}}if(w.key==="Enter"&&xt>=0){w.preventDefault(),pa(xt);return}if(w.key==="Escape"){w.preventDefault(),Rt();return}}w.key==="Enter"&&!w.shiftKey&&!k&&(w.preventDefault(),wn(w))},Jo=()=>{rt?Js():(Rt(),pt())},Zo=()=>{const w=!ge.voiceEnabled;Te({voiceEnabled:w}),w&&ns.enableAudio()},el=m.useCallback(async w=>{if(!At||!E||!Rs||Oe)return;const D=w.clipboardData;if(!D||!D.items)return;const je=Array.from(D.items).filter(He=>He.kind==="file");if(je.length===0)return;const Ne=[];if(je.forEach((He,Ye)=>{const Zt=He.getAsFile();Zt&&Ne.push(Tf(Zt,Ye))}),Ne.length===0)return;w.preventDefault(),G(null),q(null),y(!1);let Xe=null;const tt=new Set;try{const He=ye.getState(),Ye=He.conversations.find(ts=>ts.id===He.currentConversationId);if(((Ye==null?void 0:Ye.attachedFiles)||[]).length+Ne.length>oe.maxFilesPerConversation)throw et&&ot.getState().openLoginPrompt(h("fileUpload.maxFilesGuestLimitMessage",{count:oe.maxFilesPerConversation})),new Error(h("fileUpload.maxFilesPerConversationError",{count:oe.maxFilesPerConversation}));if(oe.maxTotalFiles!==null&&He.conversations.reduce(($t,Ps)=>{var ds;return $t+(((ds=Ps.attachedFiles)==null?void 0:ds.length)||0)},0)+Ne.length>oe.maxTotalFiles)throw et&&ot.getState().openLoginPrompt(h("fileUpload.maxTotalFilesGuestLimitMessage",{count:oe.maxTotalFiles})),new Error(h("fileUpload.maxTotalFilesError",{count:oe.maxTotalFiles}));if(!Ye)throw new Error(h("messageInput.conversationNotFoundShort"));if(!Ye.adapterName)throw new Error(h("fileUpload.adapterNotConfigured"));const es=dt(Ye.apiUrl),il=Ye.adapterName;Xe=Ye.id,le(Xe,!0);const ga=[];for(let ts=0;ts<Ne.length;ts++){const $t=Ne[ts],Ps=$t.name||`Clipboard file ${ts+1}`,ds=`${Ps}-${Date.now()}-${ts}`,Ds=$t.type.startsWith("image/")?URL.createObjectURL($t):null;Ds&&tt.add(Ds);let Nn=null;X(Ke=>{const Vt=new Map(Ke);return Vt.set(ds,{filename:Ps,progress:0,status:"uploading"}),Vt});const ol=Ke=>{Ke.fileId&&!Nn&&(Nn=Ke.fileId,Ds&&(Ao(Ke.fileId,Ds),tt.delete(Ds))),X(Vt=>{const yr=new Map(Vt),In=yr.get(ds);return In&&yr.set(ds,{...In,filename:Ps,progress:Ke.progress,status:Ke.status,fileId:Ke.fileId}),yr})},ll=()=>{X(Ke=>{const Vt=new Map(Ke);return Vt.delete(ds),Vt})};z(`[MessageInput] Pasting file: ${$t.name}, type: ${$t.type||"unknown"}, size: ${$t.size}`);const br=await Kt.uploadFile($t,Ke=>{z(`[MessageInput] Paste upload progress for ${$t.name}: ${Ke.progress}% - ${Ke.status}`),ol(Ke)},void 0,es,il);ga.push(br),Xe&&Xe===Ae&&I(Ke=>Ke.some(Vt=>Vt.file_id===br.file_id)?Ke:[...Ke,br]),ur([br],Xe),ll()}ga.length>0&&hr(ga)}catch(He){const Ye=He instanceof Error?He.message:"Failed to paste file";ke("[MessageInput] Paste error:",He),zs("error",ge.soundEnabled),G(Ye),Ye.toLowerCase().includes("maximum")&&ne(Ye),setTimeout(()=>{G(null)},5e3),X(new Map),tt.forEach(Zt=>URL.revokeObjectURL(Zt))}finally{le(Xe,!1)}},[Ae,E,Rs,et,Oe,le,ge.soundEnabled,hr,ur,At,h]),vn=Ec(re==null?void 0:re.adapterName);let Et,gr=!1;As?Et=et?h("messageInput.placeholder.guestLimitTotal",{count:oe.maxTotalMessages}):h("messageInput.placeholder.workspaceLimitTotal",{count:oe.maxTotalMessages}):st?Et=et?h("messageInput.placeholder.guestLimitPerConversation",{count:oe.maxMessagesPerConversation}):h("messageInput.placeholder.conversationLimitReached",{count:oe.maxMessagesPerConversation}):ca||kt?Et=h("messageInput.placeholder.filesUploading"):vn?(Et=vn,gr=!0):hn?(Et=h("messageInput.placeholder.messageOrbit"),gr=!0):(Et=s,gr=!0);const Sn=gr&&!qe&&Nt.length>0&&!Oe,jn=h("messageInput.skillsHint.placeholderBeforeKey"),Cn=h("messageInput.skillsHint.placeholderAfterKey"),tl=Sn&&Et?`${Et} ${jn} / ${Cn}`:Et,xr=oe.maxMessageLength-x.length,sl=xr<=oe.maxMessageLength*.1,rl=xr<=0?"font-semibold text-red-600 dark:text-red-400":xr<=oe.maxMessageLength*.02?"font-medium text-amber-700 dark:text-amber-400":"text-gray-500 dark:text-[#bfc2cd]",cs=[];As&&oe.maxTotalMessages!==null&&(et?Gt&&cs.push(h("messageInput.limitWarning.guestTotalMessages",{count:oe.maxTotalMessages})):cs.push(h("messageInput.limitWarning.workspaceTotalMessages",{count:oe.maxTotalMessages}))),st&&oe.maxMessagesPerConversation!==null&&(et?Gt&&cs.push(h("messageInput.limitWarning.guestPerConversation",{count:oe.maxMessagesPerConversation})):cs.push(h("messageInput.limitWarning.conversationLimitReached",{count:oe.maxMessagesPerConversation}))),H&&cs.push(H),m.useEffect(()=>{!Yt||!nt||zs("error",ge.soundEnabled)},[Yt,ge.soundEnabled,nt]),m.useEffect(()=>{if(!H)return;const w=setTimeout(()=>ne(null),5e3);return()=>clearTimeout(w)},[H]),m.useEffect(()=>{if(!F)return;const w=D=>{D.key!=="Escape"||D.defaultPrevented||y(!1)};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[F]),m.useEffect(()=>{var w;(F||kt||O.size>0||or)&&((w=ae.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[F,kt,O.size,or]),m.useEffect(()=>{var w;Ts&&((w=he.current)==null||w.scrollIntoView({behavior:"smooth",block:"nearest"}))},[Ts]),m.useEffect(()=>{var w;me&&((w=U.current)==null||w.scrollIntoView({behavior:"smooth",block:"end"}))},[me,lt.length]);const al=l,nl=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 ${nl}`,children:n.jsxs("div",{className:`mx-auto w-full ${al}`,children:[nt&&Yt&&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(Ua,{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:nt})]}),K&&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(Ua,{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:K})]}),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(pd,{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})]}),cs.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(rn,{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:cs.map((w,D)=>n.jsx("li",{className:"text-sm text-amber-800 dark:text-amber-200",children:w},`${w}-${D}`))}),et&&(ua||lr)&&Gt&&n.jsx("button",{type:"button",onClick:()=>ot.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:wn,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("span",{className:"min-w-0 truncate font-medium capitalize",children:qe.name.replace(/-/g," ")}),n.jsx("button",{type:"button",onClick:()=>{var w;gt(),(w=$.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(Qe,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),!qe&&Nt.length>0&&n.jsxs("button",{type:"button",onClick:yt,disabled: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:hidden","aria-label":h("messageInput.skillsHint.ariaLabel"),title:h("messageInput.skillsHint.title"),children:[n.jsx(Qs,{children:"/"}),n.jsx("span",{className:"sr-only",children:h("messageInput.skillsHint.keyLabel")}),h("messageInput.skillsHint.text")]}),n.jsx(Ka,{availableModels:u,defaultModel:f,selectedModel:g,onSelect:w=>p==null?void 0:p(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:[xe&&Et&&n.jsxs("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(jt.top-Cf,0),paddingBottom:jt.bottom,paddingLeft:`${Aa}px`,paddingRight:0,lineHeight:Tt?`${Tt}px`:void 0},"aria-hidden":"true",children:[Et,Sn&&n.jsxs("span",{className:"ml-1 hidden md:inline",children:[jn," ",n.jsx(Qs,{className:"mx-0.5",children:"/"})," ",Cn]})]}),P&&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(jt.top-Af,0),paddingBottom:jt.bottom,paddingLeft:`${Aa}px`,paddingRight:0,lineHeight:Tt?`${Tt}px`:void 0},"aria-hidden":"true",children:[n.jsx("span",{className:"invisible",children:x}),n.jsx("span",{children:P})]}),n.jsx("textarea",{ref:$,"aria-label":h("messageInput.textarea.ariaLabel"),value:x,onChange:w=>{const D=w.target.value;if(D.startsWith("/")){b(D),Ze(0),Me(Nt.length>0);return}if(D.length===0&&V.current!==null){b(V.current),V.current=null,Me(!1);return}V.current=null,b(D),Me(!1)},onKeyDown:Qo,onPaste:el,onCompositionStart:()=>S(!0),onCompositionEnd:()=>S(!1),onFocus:()=>_(!0),onBlur:()=>_(!1),placeholder:tl??void 0,disabled:Oe,rows:1,maxLength:oe.maxMessageLength,className:"relative z-10 flex-1 w-full min-w-0 resize-none bg-transparent py-0 text-base md:text-sm text-[#353740] placeholder-transparent focus:outline-none dark:text-[#ececf1] dark:placeholder-transparent",style:{minHeight:"24px",maxHeight:"120px",paddingTop:`${jt.top}px`,paddingBottom:`${jt.bottom}px`,paddingLeft:`${Aa}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&&!At&&n.jsx("div",{className:"hidden md:block h-8 w-8 shrink-0","aria-hidden":"true"}),At&&n.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),$s||y(!F)},disabled:$s,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||ys.length>0?"bg-gray-200 text-[#353740] dark:bg-[#565869] dark:text-[#ececf1]":$s?"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:Rs?lr&&fn&&oe.maxFilesPerConversation!==null?h("messageInput.fileUpload.titleLimitPerConversation",{count:oe.maxFilesPerConversation}):lr&&mn&&oe.maxTotalFiles!==null?h("messageInput.fileUpload.titleLimitWorkspace",{count:oe.maxTotalFiles}):Oe?h("messageInput.fileUpload.titleUploading"):ys.length>0?h("messageInput.fileUpload.titleAttached",{count:ys.length}):h("messageInput.fileUpload.attachAriaLabel"):h("messageInput.fileUpload.titleNotSupported"),"aria-label":h("messageInput.fileUpload.attachAriaLabel"),children:$s&&j?n.jsx(Qe,{className:"h-4 w-4"}):n.jsx(_d,{className:"h-4 w-4"})}),sl&&n.jsxs("div",{className:`shrink-0 px-1.5 text-xs tabular-nums transition-colors md:px-2 ${rl}`,title:h("messageInput.characterCount.title",{count:xr}),children:[x.length,"/",oe.maxMessageLength]})]}),n.jsxs("div",{className:"flex items-center gap-1 md:gap-2",children:[n.jsx(Ka,{availableModels:u,defaultModel:f,selectedModel:g,onSelect:w=>p==null?void 0:p(w),wrapperClassName:"relative hidden md:block",maxWidthClass:"max-w-[220px]"}),(xs||Yt)&&n.jsxs(n.Fragment,{children:[xs&&n.jsx("button",{type:"button",onClick:Zo,className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${ge.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:ge.voiceEnabled?h("messageInput.voiceOutput.titleEnabled"):h("messageInput.voiceOutput.titleDisabled"),"aria-label":ge.voiceEnabled?h("messageInput.voiceOutput.ariaLabelEnabled"):h("messageInput.voiceOutput.ariaLabelDisabled"),children:ge.voiceEnabled?n.jsx(ra,{className:"h-5 w-5"}):n.jsx(Bd,{className:"h-5 w-5"})}),Ht&&n.jsx("button",{type:"button",onClick:Jo,disabled:Oe,onMouseEnter:()=>A(!0),onMouseLeave:()=>A(!1),className:`hidden md:flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 ${rt?"!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":rt?"messageInput.voiceInput.titleListening":"messageInput.voiceInput.titleDisabled"),"aria-label":h(rt?"messageInput.voiceInput.ariaLabelListening":"messageInput.voiceInput.ariaLabelDisabled"),children:rt||Oe&&B?n.jsx(mo,{className:"h-5 w-5"}):n.jsx(Rr,{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(Oa,{className:"h-5 w-5"})}),(ca||kt)&&n.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center",children:n.jsx(Br,{className:"h-4 w-4 animate-spin text-gray-500 dark:text-[#bfc2cd]"})}),mt?n.jsx("button",{type:"button",onClick:w=>{w.preventDefault(),Se()},className:"flex h-9 w-9 md:h-8 md:w-8 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 bg-red-500 text-white hover:bg-red-600 dark:bg-red-600 dark:hover:bg-red-700",title:h("messageInput.stop.title"),"aria-label":h("messageInput.stop.ariaLabel"),children:n.jsx(Dd,{className:"h-4 w-4 md:h-3 md:w-3 fill-current"})}):n.jsx("button",{type:"submit",disabled:!da||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 ${da&&!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(Or,{className:"h-4 w-4"})})]})]})]}),ys.length>0&&n.jsx("div",{className:"flex flex-wrap gap-2",children:ys.map(w=>{const D=Na(w.processing_status),ce=w.processing_status==="failed"||w.processing_status==="error",je=ce?"error":D?w.processing_status==="uploading"?"uploading":"processing":"completed",Ne=D?w.processing_status==="uploading"?h("messageInput.attachedFile.uploadingStatus"):h("messageInput.attachedFile.processingStatus"):void 0;return n.jsx(Xr,{filename:w.filename,fileId:w.file_id,status:je,statusText:Ne,errorMessage:ce?w.error_message||h("messageInput.fileProcessingFailedTitle"):void 0,onRemove:()=>{ce?(Ae&&Ce(Ae,w.file_id),I(Xe=>Xe.filter(tt=>tt.file_id!==w.file_id))):Go(w)},removeTitle:h(ce?"messageInput.attachedFile.removeTitleFailed":"messageInput.attachedFile.removeTitleNormal")},w.file_id)})}),At&&(Rs||or)&&n.jsxs("div",{ref:ae,className:`${pn?"":"rounded-lg border border-gray-200/80 bg-white p-2.5 dark:border-[#3c3f4a] dark:bg-[#2a2b32]"} transition-all duration-200 ${!F&&!kt&&O.size===0&&!or?"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(Qe,{className:"h-3.5 w-3.5"})})]}),!pn&&kt&&!F&&O.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")})}),O.size>0&&n.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:Array.from(O.entries()).map(([w,D])=>n.jsx(Xr,{filename:D.filename,fileId:D.fileId,status:D.status,statusText:D.status==="uploading"?h("messageInput.uploadProgress.statusUploading"):D.status==="processing"?h("messageInput.uploadProgress.statusProcessing"):D.status==="completed"?h("messageInput.uploadProgress.statusCompleted"):void 0,errorMessage:D.error},w))}),n.jsx("div",{className:`${gn?"block max-h-[40vh] overflow-y-auto":"hidden"}`,"aria-hidden":!gn,children:n.jsx(jf,{conversationId:Ae,onFilesSelected:Wo,onUploadError:w=>{ke("File upload error:",w),ne(w)},onUploadingChange:le,onUploadSuccess:Ko,maxFiles:oe.maxFilesPerConversation,disabled:$s})})]}),n.jsx("div",{className:"h-3 md:h-1",children:Ht&&rt&&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")]})})]}),me&&n.jsx("div",{ref:U,className:"w-full pt-1",children:n.jsx(_o,{skills:Nt,isLoading:tr,selectedSkill:qe,activeSkillName:It==null?void 0:It.name,query:bt,onActiveSkillChange:w=>{const D=lt.findIndex(ce=>ce.name===w.name);D>=0&&Ze(D)},onSelect:Ie,onClose:Jt})}),Ts&&n.jsx("div",{ref:he,role:"listbox","aria-label":h("messageInput.autocompletePanel.ariaLabel"),className:"w-full pt-1",children:Ft.map((w,D)=>{const ce=D===xt;return n.jsx("button",{type:"button",role:"option","aria-selected":ce,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 ${ce?"bg-gray-100 dark:bg-[#2d2f39]":"hover:bg-gray-50 dark:hover:bg-[#2d2f39]/60"}`,onClick:()=>pr(w.text),onMouseEnter:()=>sr(D),children:ee(w.text)},D)})}),n.jsx(qr,{isOpen:T.isOpen,onClose:Xo,onConfirm:Yo,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"&&Qr.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(Oa,{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(Qe,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})})]}),n.jsx("div",{className:"p-6",children:n.jsx(zt,{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 ${Y}`,syntaxTheme:Z})}),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 Ci=24e3;function Mf(t){const e=new Uint8Array(t.length*2),s=new DataView(e.buffer);t.forEach((a,i)=>s.setInt16(i*2,Math.round(Math.max(-1,Math.min(1,a))*(a<0?32768:32767)),!0));let r="";return e.forEach(a=>{r+=String.fromCharCode(a)}),btoa(r)}function Ff(t){const e=atob(t),s=new Uint8Array(e.length);for(let i=0;i<e.length;i++)s[i]=e.charCodeAt(i);const r=new Float32Array(Math.floor(s.length/2)),a=new DataView(s.buffer);for(let i=0;i<r.length;i++)r[i]=a.getInt16(i*2,!0)/32768;return r}function Ai(t,e,s){if(e===s)return t;const r=new Float32Array(Math.floor(t.length*s/e)),a=e/s;for(let i=0;i<r.length;i++){const o=i*a,l=Math.floor(o),c=Math.min(l+1,t.length-1);r[i]=(t[l]||0)+((t[c]||0)-(t[l]||0))*(o-l)}return r}function Rf(t){const e=Math.floor(t/60),s=t%60;return`${e}:${s.toString().padStart(2,"0")}`}function $f({conversationId:t,adapterName:e,sessionId:s,adapterNotes:r}){const{t:a}=Le(),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),g=m.useRef(null),p=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),[C,I]=m.useState(!1),N=ye(H=>H.realtimeVoice),R=ye(H=>H.setRealtimeVoiceState),O=ye(H=>H.beginRealtimeVoiceTurn),X=ye(H=>H.appendRealtimeVoiceAssistantDelta),j=ye(H=>H.finishRealtimeVoiceTurn);m.useEffect(()=>{x.current=E},[E]);const L=m.useCallback(()=>{var ne,T,Q,$;b.current=!0;const H=i.current;(H==null?void 0:H.readyState)===WebSocket.OPEN?(H.send(JSON.stringify({type:"interrupt"})),H.onmessage=null,H.onerror=null,H.onclose=null,window.setTimeout(()=>H.close(),150)):H==null||H.close(),i.current=null,(ne=c.current)==null||ne.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(),($=o.current)==null||$.close(),o.current=null,d.current=null,u.current=null,_(!1),M(!1),y(0),S("idle"),R({status:"idle"}),j(t)},[t,j,R]),B=m.useCallback(()=>{var H;h.current.forEach(ne=>{try{ne.stop()}catch{}}),h.current.clear(),p.current=((H=o.current)==null?void 0:H.currentTime)||0,M(!1)},[]);m.useEffect(()=>()=>L(),[L]),m.useEffect(()=>{if(k!=="connected")return;const H=Date.now(),ne=window.setInterval(()=>y(Math.floor((Date.now()-H)/1e3)),1e3);return()=>window.clearInterval(ne)},[k]),m.useEffect(()=>{let H=0;const ne=()=>{var W;const T=v?u.current:d.current,Q=T&&!E?new Uint8Array(T.fftSize):null;Q&&T.getByteTimeDomainData(Q);let $=0;if(Q){for(const ae of Q){const he=(ae-128)/128;$+=he*he}$=Math.min(1,Math.sqrt($/Q.length)*8)}(W=f.current)==null||W.style.setProperty("transform",`scale(${1+$*.16})`),g.current&&(g.current.style.setProperty("transform",`scale(${1.05+$*.45})`),g.current.style.setProperty("opacity",`${.08+$*.35}`)),H=window.requestAnimationFrame(ne)};return ne(),()=>window.cancelAnimationFrame(H)},[v,E,k]);const A=m.useCallback(async()=>{try{b.current=!1,S("connecting"),y(0),R({status:"connecting",error:void 0,transcript:""});const ne=(await Re()).getRealtimeVoiceWebSocketUrl(e,{sessionId:s}),T=new WebSocket(ne);i.current=T,T.onmessage=Q=>{if(b.current)return;let $;try{$=JSON.parse(Q.data)}catch{return}if($.type==="connected")S("connected"),M(!1),R({status:"connected",provider:String($.mode||""),model:String($.realtime_model||"")});else if($.type==="audio_chunk"&&typeof $.data=="string"&&o.current&&u.current){const W=o.current,ae=Ff($.data),he=typeof $.sample_rate=="number"?$.sample_rate:Ci,U=W.createBuffer(1,Math.max(1,Math.floor(ae.length*W.sampleRate/he)),W.sampleRate);U.copyToChannel(Ai(ae,he,W.sampleRate),0);const V=W.createBufferSource();V.buffer=U,V.connect(u.current),h.current.add(V),V.onended=()=>h.current.delete(V),p.current=Math.max(p.current,W.currentTime+.06),V.start(p.current),p.current+=U.duration,M(!0)}else $.type==="transcription"&&typeof $.text=="string"?O(t,$.text):$.type==="assistant_transcript_delta"&&typeof $.delta=="string"?X(t,$.delta):$.type==="done"?(M(!1),j(t,{userMessageId:typeof $.user_message_id=="string"?$.user_message_id:void 0,assistantMessageId:typeof $.assistant_message_id=="string"?$.assistant_message_id:void 0})):$.type==="interrupted"?(B(),j(t)):$.type==="error"&&(S("error"),M(!1),j(t),R({status:"error",error:String($.message||a("realtimeVoice.errors.connectionFailed"))}))},T.onerror=()=>{b.current||(M(!1),j(t),S("error"),R({status:"error",error:a("realtimeVoice.errors.connectionFailed")}))},T.onclose=()=>{b.current||(M(!1),j(t),S("error"),R({status:"error",error:a("realtimeVoice.errors.connectionFailed")}))},T.onopen=async()=>{const Q=new AudioContext;o.current=Q,p.current=Q.currentTime;const $=Q.createAnalyser();$.fftSize=256,$.smoothingTimeConstant=.8,$.connect(Q.destination),u.current=$,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 ae=Q.createMediaStreamSource(W),he=Q.createAnalyser();he.fftSize=256,he.smoothingTimeConstant=.8,d.current=he,ae.connect(he);const U=new AudioWorkletNode(Q,"audio-capture-processor");c.current=U,U.port.onmessage=V=>{var se;T.readyState===WebSocket.OPEN&&(((se=V.data)==null?void 0:se.type)!=="audio"||!(V.data.data instanceof Float32Array)||x.current||T.send(JSON.stringify({type:"audio_chunk",data:Mf(Ai(V.data.data,Q.sampleRate,Ci)),format:"pcm"})))},ae.connect(U),U.connect(Q.destination)}}catch(H){const ne=H instanceof DOMException&&(H.name==="NotAllowedError"||H.name==="PermissionDeniedError");S("error"),R({status:"error",error:ne?a("realtimeVoice.errors.microphoneDenied"):H instanceof Error?H.message:a("realtimeVoice.errors.connectionFailed")})}},[e,X,O,B,t,j,s,R,a]),K=m.useCallback(()=>_(H=>!H),[]),G=k==="connected",J=a(k==="connecting"?"realtimeVoice.status.connecting":k==="error"?"realtimeVoice.status.error":G?v?"realtimeVoice.status.speaking":"realtimeVoice.status.listening":"realtimeVoice.status.ready"),q=k==="connecting"?"bg-amber-400 animate-pulse":k==="error"?"bg-red-500":G?"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:[N.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:N.error}),n.jsx("button",{type:"button",onClick:A,className:"shrink-0 whitespace-nowrap font-medium underline underline-offset-2 hover:text-red-900 dark:hover:text-red-100",children:a("realtimeVoice.retry")})]}),C&&r&&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:()=>I(!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(Qe,{className:"h-4 w-4"})})]}),n.jsx(zt,{content:r,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 ${q}`,"aria-hidden":"true"}),n.jsxs("span",{"aria-live":"polite",className:"min-w-0 break-words text-sm text-[#353740] dark:text-[#ececf1]",children:[J,N.model?` · ${N.model}`:""]})]}),n.jsxs("div",{className:"flex shrink-0 items-center gap-1 md:gap-2",children:[G&&n.jsx("span",{className:"hidden font-mono text-xs tabular-nums text-gray-500 dark:text-[#8a8fa3] sm:inline",children:Rf(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:g,className:`absolute inset-0 rounded-full transition-[background-color] duration-200 ${k==="error"?"bg-red-500":G?"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":G?"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(ra,{className:"h-3.5 w-3.5"}):n.jsx(Rr,{className:"h-3.5 w-3.5"})})]}),r&&n.jsx("button",{type:"button",onClick:()=>I(H=>!H),"aria-expanded":C,"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(Oa,{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(Br,{className:"h-4 w-4 animate-spin"})}):G?n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button",onClick:K,"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(mo,{className:"h-4 w-4"}):n.jsx(Rr,{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(Md,{className:"h-4 w-4"})})]}):n.jsx("button",{type:"button",onClick:A,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(Rr,{className:"h-4 w-4"})})]})]})]})})}function Ni({adapter:t,onSelect:e}){var l;const{t:s}=Le(),r=(l=t.description)==null?void 0:l.trim(),{isDark:a}=ps(),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}),r?n.jsx("div",{className:"mt-1 text-sm leading-5 text-slate-600 dark:text-slate-300",children:n.jsx(zt,{content:r,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:s("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":s("agentCard.startConversationAriaLabel",{name:t.name}),children:n.jsx(Gn,{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":s("agentCard.startConversationAriaLabel",{name:t.name}),children:n.jsx(Gn,{className:"h-4 w-4","aria-hidden":"true"})})})]})}const us=t=>{if(typeof t!="string")return;const e=t.trim();return e.length>0?e:void 0},Pf=t=>{if(!t||typeof t!="object")return null;const e=t,s=us(e.name);if(!s)return null;const r=us(e.id);if(!r)return console.warn(`[middlewareConfig] Adapter "${s}" is missing a required 'id' field — skipping.`),null;const a=us(e.apiUrl),i=us(e.model),o=us(e.inputPlaceholder),l=typeof e.notes=="string"?e.notes.trim():void 0;let c=us(e.description)||us(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:r,name:s};return a&&(d.apiUrl=a),c&&(d.description=c),l&&(d.notes=l),i&&(d.model=i),o&&(d.inputPlaceholder=o),d},Fo=t=>Array.isArray(t)?t.map(Pf).filter(e=>e!==null):[];let rs=null,Ia=0;const Df=3e4;function Uf(){if(typeof window<"u"){const t=window.ORBIT_CHAT_CONFIG;if(t!=null&&t.adapters&&Array.isArray(t.adapters)){z("Loading adapters from window.ORBIT_CHAT_CONFIG");const e=Fo(t.adapters);return e.length===0?null:e}}return null}async function ln(){if(rs&&Date.now()-Ia<Df)return rs;try{const e=await fetch("/api/adapters?refresh=1",{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(e.ok){const s=await e.json(),r=Fo(s.adapters);if(r.length>0)return rs=r,Ia=Date.now(),z("Fetched adapters from /api/adapters:",rs),rs;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=Uf();if(t&&t.length>0)return rs=t,Ia=Date.now(),z("Loaded adapters from config:",rs),rs;throw ke("No adapters available from API or config"),new Error("No adapters available. Define adapters in orbitchat.yaml.")}const Of="h-[96px]";function zf({onAdapterSelect:t,className:e="",title:s="",subtitle:r="",eyebrow:a=""}){const{t:i}=Le(),[o,l]=m.useState([]),[c,d]=m.useState(!0),[u,f]=m.useState(null),g=m.useRef(null),p=m.useRef(null),[h,x]=m.useState(""),[b,k]=m.useState(!1),S=m.useCallback(()=>{const j=g.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=g.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&&N.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())}},C=j=>{var K;if(!R||!E()||j.key!=="ArrowDown"&&j.key!=="ArrowUp")return;const L=document.activeElement;if(!(L instanceof HTMLElement)||L.dataset.agentCard!=="true")return;const B=_(),A=B.indexOf(L);if(A!==-1){if(j.preventDefault(),j.key==="ArrowDown"){v((A+1)%B.length);return}if(A===0){(K=p.current)==null||K.focus();return}v(A-1)}},I=h.trim().toLowerCase(),N=I?o.filter(j=>{var K,G;const L=j.name.toLowerCase().includes(I),B=((K=j.description)==null?void 0:K.toLowerCase().includes(I))??!1,A=((G=j.model)==null?void 0:G.toLowerCase().includes(I))??!1;return L||B||A}):o,R=h.trim().length>0,O=R||N.length===1;m.useEffect(()=>{const j=g.current;if(j)return S(),j.addEventListener("scroll",S,{passive:!0}),()=>j.removeEventListener("scroll",S)},[S,N]),m.useEffect(()=>{let j=!0;return(async()=>{try{d(!0),f(null);const B=await ln();j&&l(B)}catch(B){ke("[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=p.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:`${Of} 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")}):N.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:g,onKeyDown:C,className:"agent-selection-scroll flex-1 min-h-0 overflow-y-auto pr-1 pb-2",children:O?n.jsx("div",{className:"mx-auto flex w-full max-w-xl flex-col gap-3 lg:max-w-2xl",children:N.map(j=>n.jsx(Ni,{adapter:j,onSelect:L=>t(L.id)},j.id))}):n.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:N.map(j=>n.jsx(Ni,{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||s||r)&&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}),s&&n.jsx("h2",{className:"mt-2 text-2xl font-bold text-gray-900 dark:text-white",children:s}),r&&n.jsx("p",{className:"mt-2 text-base text-gray-600 dark:text-gray-300",children:r})]}),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(Hr,{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:p,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(Qe,{className:"h-3.5 w-3.5"})})]})})}),n.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:X()})]})}function Ga(){return tn()?ta()==="entra"?n.jsx(Hf,{}):n.jsx(Bf,{}):null}function Bf(){const{user:t,logout:e,loginWithRedirect:s}=Qa();if(!Cs()||!t)return n.jsx(Ro,{onClick:()=>s()});const a=t.name||t.email||"User";return n.jsx($o,{displayName:a,onClick:()=>e({logoutParams:{returnTo:window.location.origin}})})}function Hf(){const{instance:t,accounts:e}=Ya();if(!Cs()||e.length===0)return n.jsx(Ro,{onClick:()=>t.loginRedirect({scopes:sn()}).catch(()=>{})});const r=e[0],a=r.name||r.username||"User";return n.jsx($o,{displayName:a,onClick:()=>t.logoutRedirect({postLogoutRedirectUri:window.location.origin}).catch(()=>{})})}function Ro({onClick:t}){const{t:e}=Le();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(fo,{className:"h-4 w-4"}),n.jsx("span",{children:e("common.signIn")})]})}function $o({displayName:t,onClick:e}){const{t:s}=Le();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:s("authStatus.signOutButton.title"),"aria-label":s("authStatus.signOutButton.ariaLabel"),children:[n.jsx(Sd,{className:"h-4 w-4"}),n.jsx("span",{className:"hidden md:inline",children:s("common.logOut")})]})]})}function Po({placement:t="default",compact:e=!1}){const{t:s}=Le();if(!ao())return null;const r=ed(),a=td(),i=sd(),o=rd(),l=ad(),c=nd(),d=od(),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",g=l==="inline"?"flex w-full flex-col gap-1 items-center justify-center text-center sm:flex-row sm:items-center sm:justify-center":"flex w-full flex-col items-center justify-center gap-1 text-center",p="justify-center",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:g,children:[r&&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:r}),d.length>0&&n.jsx("nav",{"aria-label":s("appFooter.navLinksAriaLabel"),children:n.jsx("ul",{className:`flex flex-wrap items-center ${p} ${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 Vf=60*1e3;let Ea=null,Ii=0;const La=t=>{if(!t||t==="/")return"/";const e=t.trim();if(!e)return"/";const s=e.startsWith("/")?e:`/${e}`;return s==="/"?"/":s.endsWith("/")?s.slice(0,-1):s},Do=()=>{if(typeof window>"u")return La("/");const t=La("/");if(typeof document>"u")return t;const e=document.querySelector("base[href]");if(!e)return t;try{const s=new URL(e.getAttribute("href")||"/",window.location.origin);return La(s.pathname||t)}catch{return t}},Yr=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),qf=async()=>{const t=Date.now();if(Ea&&t-Ii<Vf)return Ea;let e=[];try{e=await ln()}catch(r){we("[agentRouting] Unable to load adapters for slug resolution",r)}const s=new Map;return e.forEach(r=>{const a=Yr(r.name);a&&s.set(a,r.id);const i=Yr(r.id);i&&i!==a&&s.set(i,r.id)}),Ea=s,Ii=t,s},Xa=t=>{var i;const e=Do(),s=t.startsWith("/")?t:`/${t}`;let r=s;if(e!=="/"){if(!s.startsWith(e))return null;r=s.slice(e.length)}const a=r.split("/").filter(Boolean);return a.length===0?null:((i=a[0])==null?void 0:i.toLowerCase())||null},Uo=t=>{const e=Do();if(!t)return e;const s=t.replace(/^\/+|\/+$/g,"");return e==="/"?s?`/${s}`:"/":`${e}/${s}`.replace(/\/{2,}/g,"/")},Pt=t=>{if(typeof window>"u")return;const e=Uo(t),s=window.location.pathname;if(e===s)return;const r=window.location.search||"",a=window.location.hash||"";window.history.replaceState(window.history.state,"",`${e}${r}${a}`)},Wf=()=>Uo(null),Kf=async t=>{const e=t.trim().toLowerCase();return e&&(await qf()).get(e)||null};function Gf({currentConversation:t,showEmptyState:e,createConversation:s,configureApiSettings:r,clearError:a,clearCurrentConversationAdapter:i}){var he;const{t:o}=Le(),l=o("agent.error.singleAdapterMissing"),[c,d]=m.useState(!1),[u,f]=m.useState(null),g=ea(),p=Ja(),h=typeof window<"u"?Xa(window.location.pathname):null,[x,b]=m.useState(h),[k,S]=m.useState(()=>!g&&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,C=((he=t==null?void 0:t.attachedFiles)==null?void 0:he.length)??0,I=m.useMemo(()=>F&&(y>0||C>0),[C,y,F]),N=m.useCallback(()=>{Ge(()=>ye.getState())},[]),R=m.useCallback((U,V)=>{if(!U)return;const se=V||o("agent.error.configurationFailed");let ue=!1;ye.setState(pe=>{const fe=pe.conversations.find(ve=>ve.id===U);return!fe||fe.messages.length>0?pe:(ue=!0,{conversations:pe.conversations.map(ve=>ve.id===U?{...ve,adapterLoadError:se}:ve)})}),ue&&N()},[N,o]),O=m.useCallback(U=>{if(!U)return;let V=!1;ye.setState(se=>{const ue=se.conversations.find(pe=>pe.id===U);return!ue||!ue.adapterLoadError?se:(V=!0,{conversations:se.conversations.map(pe=>pe.id===U?{...pe,adapterLoadError:null}:pe)})}),V&&N()},[N]),X=m.useCallback(U=>U instanceof Pe?U.status===401?o("agent.error.authenticationFailed"):U.status===404?o("agent.error.notFound"):U.message:U instanceof Error?U.message:o("agent.error.loadFailed"),[o]),j=m.useCallback(()=>{const U=ye.getState(),V=U.currentConversationId?U.conversations.find(se=>se.id===U.currentConversationId):null;if(!V||V.messages.length>0)try{return s()}catch(se){we("Cannot create a new conversation for agent selection:",se instanceof Error?se.message:"Unknown error")}return(V==null?void 0:V.id)||null},[s]),L=m.useCallback(async U=>{if(!(U!=null&&U.adapterName))return{ok:!1};try{const V=await Re(),se=new V.ApiClient({apiUrl:U.apiUrl||$e(),sessionId:null,adapterName:U.adapterName});if(typeof se.getAdapterInfo!="function")return{ok:!1};const ue=await se.getAdapterInfo();return ye.setState(pe=>({conversations:pe.conversations.map(fe=>fe.id===U.id?{...fe,adapterInfo:ue,adapterLoadError:null,updatedAt:new Date}:fe)})),ye.getState().currentConversationId===U.id&&f(null),N(),{ok:!0}}catch(V){const se=X(V),ue=ye.getState();ue.currentConversationId===U.id&&f({conversationId:U.id,message:se});const pe=ue.conversations.find(fe=>fe.id===U.id);return pe&&pe.messages.length===0&&R(U.id,se),{ok:!1,error:V}}},[X,R,N]),B=m.useCallback(async U=>{if(!U)return;const V=ye.getState(),se=V.currentConversationId?V.conversations.find(ue=>ue.id===V.currentConversationId):null;if(se){d(!0),f(null),O(se.id);try{const ue=se.apiUrl||$e();await r(ue,void 0,U),a();const pe=ye.getState(),fe=pe.conversations.find(ve=>ve.id===pe.currentConversationId);if((fe==null?void 0:fe.adapterName)===U&&(!fe.adapterInfo||fe.adapterInfo.notes===void 0)){const ve=await L(fe);!ve.ok&&ve.error&&ke("Failed to load adapter info after selecting adapter:",ve.error)}}catch(ue){ke("Failed to configure adapter from empty state:",ue);const pe=X(ue);f({conversationId:se.id,message:pe}),R(se.id,pe)}finally{d(!1)}}},[O,a,r,L,X,R]),A=m.useCallback(U=>{g||(j(),S(!1),Pt(Yr(U)),B(U))},[j,B,g]),K=m.useCallback(()=>{g||(i(),Pt(null),S(!0))},[i,g]),G=m.useCallback(()=>{var ue,pe;if(g){const fe=ye.getState(),ve=fe.currentConversationId?fe.conversations.find(Te=>Te.id===fe.currentConversationId):null;if(!!ve&&(ve.messages.length>0||(((ue=ve.attachedFiles)==null?void 0:ue.length)||0)>0))try{s()}catch(Te){we("Cannot go home (new conversation):",Te instanceof Error?Te.message:"Unknown error")}Pt(null),S(!1);return}b(null);const U=ye.getState(),V=U.currentConversationId?U.conversations.find(fe=>fe.id===U.currentConversationId):null;if(!!V&&(V.messages.length>0||(((pe=V.attachedFiles)==null?void 0:pe.length)||0)>0))try{s()}catch(fe){we("Cannot go home (new conversation):",fe instanceof Error?fe.message:"Unknown error");return}else V!=null&&V.adapterName&&i();Pt(null),S(!0)},[i,s,g]),q=!g&&e&&!x&&!(t!=null&&t.adapterName)&&!I||!g&&e&&k&&!(t!=null&&t.adapterName)&&!I;m.useEffect(()=>{if(g){Pt(null);return}if(!x){if(q||!(t!=null&&t.adapterName)){Pt(null);return}Pt(Yr(t.adapterName))}},[t==null?void 0:t.adapterName,g,x,q]);const H=m.useCallback(async()=>{if(typeof window>"u")return;const U=++v.current;if(g){Pt(null),b(null);return}const V=Xa(window.location.pathname);if(!V)return;const se=await Kf(V);if(U===v.current){if(!se){j(),Pt(null),i(),S(!0),b(null);return}j(),S(!1),Pt(V),await B(se),b(null)}},[i,j,B,g]),ne=m.useRef(H);m.useEffect(()=>{ne.current=H},[H]),m.useEffect(()=>{const U=window.setTimeout(()=>{ne.current()},0),V=()=>{ne.current()};return window.addEventListener("popstate",V),()=>{window.clearTimeout(U),v.current+=1,window.removeEventListener("popstate",V)}},[]);const T=t==null?void 0:t.id,Q=t==null?void 0:t.adapterName,$=t==null?void 0:t.apiUrl,W=!!(t!=null&&t.adapterInfo);m.useEffect(()=>{if(!g||!p||!e||!T||I||c)return;const U=(Q==null?void 0:Q.trim())||p,V=(Q==null?void 0:Q.trim())!==U||!W;if(!U||!V)return;let se=!1;return(async()=>{d(!0),f(null),O(T);try{const pe=$||$e();await r(pe,void 0,U),a()}catch(pe){if(!se){const fe=X(pe);f({conversationId:T,message:fe}),R(T,fe)}}finally{se||d(!1)}})(),()=>{se=!0}},[O,a,r,I,X,c,g,R,e,Q,$,W,T,p]),m.useEffect(()=>{(async()=>{const V=t==null?void 0:t.adapterName,se=t?`${t.id}:${V}`:null;if(!(!se||E.current===se))if(V){E.current=se,z("[ChatInterface] Refreshing adapter info from the backend - adapterName:",V);const ue=await L(t);if(ue.ok)z("[ChatInterface] Adapter info loaded successfully");else{const pe=ue.error;ke("[ChatInterface] Failed to load adapter info:",pe);const fe=pe instanceof Error?pe.message:String(pe);if((fe.includes("429")||fe.includes("Too Many Requests"))&&V){const ge=_.current.get(se);ge&&clearTimeout(ge);const Te=setTimeout(()=>{E.current===se&&(E.current=null),_.current.delete(se)},M);_.current.set(se,Te),we(`[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 U=_.current;return()=>{U.forEach(V=>clearTimeout(V)),U.clear()}},[]);const ae=g&&!p?l:(t==null?void 0:t.adapterLoadError)??(u&&u.conversationId===(t==null?void 0:t.id)?u.message:null);return{adapterNotesError:ae,handleAgentCardSelection:A,handleChangeAgent:K,goToAgentSelectionHome:G,hasAdapterConfigurationError:!!ae,isAgentSelectionVisible:k,isConfiguringAdapter:c,isSingleAdapterMode:g,setIsAgentSelectionVisible:S,shouldShowAgentSelectionList:q}}const Oo=m.createContext(null),Xf={registerGoHome:()=>{},goHome:()=>{}};function zo(){return m.useContext(Oo)??Xf}function Ei({adapter:t,syntaxTheme:e,forcedThemeClass:s=""}){var a;const r=(a=t.notes)==null?void 0:a.trim();return r?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(zt,{content:r,className:`message-markdown prose prose-slate dark:prose-invert max-w-none text-sm leading-relaxed text-[#434654] dark:text-[#d7dae3] [&>:first-child]:mt-0 [&>:last-child]:mb-0 ${s}`,syntaxTheme:e})})]}):null}const Yf='meta[name="description"]',Qf='meta[property="og:title"]',Jf='meta[property="og:description"]',Zf='meta[property="og:type"]',em='link[rel="canonical"]';function Li(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function tm(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 sm(t,e){const s=t==null?void 0:t.trim();if(s)return s;if(!e)return en();const r=tm(e);return r.length>160?`${r.slice(0,157).trimEnd()}...`:r}function rm(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function am(t){const e=t.trim();if(!e)return null;try{return new URL(e).origin}catch{return null}}function nm(t){const e=t.trim();if(!e)return null;const s=`^${rm(e).replace(/\\\*/g,".*")}$`;try{return new RegExp(s,"i")}catch{return null}}function im(t){return[Zi(),..._c()].map(am).filter(s=>!!s).includes(t)?!0:Tc().some(s=>{const r=nm(s);return r?r.test(t):!1})}function om(t){var r,a,i;const e=t==null?void 0:t.trim();if(!e)return null;const s=te.adapters.find(o=>{var l;return((l=o==null?void 0:o.id)==null?void 0:l.trim())===e});return s?{id:s.id,name:((r=s.name)==null?void 0:r.trim())||s.id,description:((a=s.description)==null?void 0:a.trim())||void 0,notes:((i=s.notes)==null?void 0:i.trim())||void 0}:null}function lm(t){var r,a,i;if(typeof window>"u")return null;const e=Xa(window.location.pathname);if(!e)return null;const s=te.adapters.find(o=>{const l=Li(o.name||""),c=Li(o.id||"");return e===l||e===c});return s?{id:s.id,name:((r=s.name)==null?void 0:r.trim())||s.id,description:((a=s.description)==null?void 0:a.trim())||void 0,notes:((i=s.notes)==null?void 0:i.trim())||void 0}:null}function Tr(t,e,s){if(typeof document>"u")return null;const r=document.querySelector(t);if(r)return r;const a=document.createElement("meta");return a.setAttribute(e,s),document.head.appendChild(a),a}function cm(){if(typeof document>"u")return null;const t=document.querySelector(em);if(t)return t;const e=document.createElement("link");return e.rel="canonical",document.head.appendChild(e),e}function Bo(t){if(typeof document>"u")return;const e=Za(),s=t?`${t.name} | ${e}`:e,r=t?sm(t.description,t.notes):en();document.title=s;const a=Tr(Yf,"name","description");a&&(a.content=r);const i=Tr(Qf,"property","og:title");i&&(i.content=s);const o=Tr(Jf,"property","og:description");o&&(o.content=r);const l=Tr(Zf,"property","og:type");l&&(l.content="website");const c=cm();if(c&&typeof window<"u"){const d=Zi(),u=window.location.origin,f=d?new URL(d.endsWith("/")?d:`${d}/`).origin:"",p=`${u&&im(u)?u:f||u}${window.location.pathname}`;c.href=p}}function _i(){return Mc()}class cn{static async getAdapterModels(e,s){const r=await Re(),a=new r.ApiClient({apiUrl:"",adapterName:s});if(!a.getAdapterModels)throw new Error("getAdapterModels is not available on this API client");return a.getAdapterModels(e)}static async getAllModels(e){const s=await Re(),r=new s.ApiClient({apiUrl:"",adapterName:e});if(!r.getAllModels)throw new Error("getAllModels is not available on this API client");return r.getAllModels()}static async listAdapterModels(e,s){return(await cn.getAdapterModels(e,s)).models}}const dm="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",Ti="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",um="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 fm({onOpenSettings:t,onOpenSidebar:e}){var os,Bt,et,Gt,Mt,Ae,ft,mt,Xt;const{t:s}=Le(),{conversations:r,currentConversationId:a,createConversation:i,canCreateNewConversation:o,sendMessage:l,regenerateResponse:c,editMessageAndRegenerate:d,isLoading:u,configureApiSettings:f,error:g,clearError:p,createThread:h,clearCurrentConversationAdapter:x}=ye(),{settings:b}=Jr(),k=Cs(),S=it()&&!k,{theme:E,isDark:_}=ps(),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=r.find(Se=>Se.id===a),C=!!(((os=y==null?void 0:y.adapterInfo)==null?void 0:os.supportsRealtimeVoice)===!0||y!=null&&y.adapterName&&Lc(y.adapterName)),I=r.some(Se=>{var Ce;return(Se.messages.length>0||(((Ce=Se.attachedFiles)==null?void 0:Ce.length)||0)>0)&&!Se.adapterLoadError}),N=!y||y.messages.length===0,R=((Bt=y==null?void 0:y.adapterInfo)==null?void 0:Bt.supportsThreading)===!0,O=!!(y!=null&&y.adapterName&&(y!=null&&y.adapterInfo))&&!R,X=jo({adapterName:y==null?void 0:y.adapterName,enabled:O,selectionScopeKey:a,supportsThreading:R}),j=Ji(),L=Za(),B=en().trim(),A=B.length>0,{registerGoHome:K}=zo(),[G,J]=m.useState([]),[q,H]=m.useState(null);m.useEffect(()=>{const Se=y==null?void 0:y.adapterName;let Ce=!1;async function re(){if(H(null),!Se){J([]);return}try{const Be=await cn.listAdapterModels(Se,Se);if(Ce)return;J(Be),H(Be.length>0?Be[0].name:null)}catch{Ce||(J([]),H(null))}}return re(),()=>{Ce=!0}},[y==null?void 0:y.adapterName]);const{adapterNotesError:ne,handleAgentCardSelection:T,handleChangeAgent:Q,goToAgentSelectionHome:$,hasAdapterConfigurationError:W,isAgentSelectionVisible:ae,isConfiguringAdapter:he,isSingleAdapterMode:U,shouldShowAgentSelectionList:V}=Gf({currentConversation:y,showEmptyState:N,createConversation:i,configureApiSettings:f,clearError:p,clearCurrentConversationAdapter:x});m.useLayoutEffect(()=>(K(()=>$()),()=>K(null)),[K,$]);const se="max-w-[96rem]",ue="max-w-[64rem]",pe="max-w-[56rem]",fe=`mx-auto w-full ${se}`,ve=o(),ge=!!(y!=null&&y.adapterName)&&((y==null?void 0:y.messages.length)||0)===0,Te=s(ve?"chatInterface.newConversation.tooltipCanStart":S?"chatInterface.newConversation.tooltipGuestLimited":"chatInterface.newConversation.tooltipCannotStart"),De=!!(y&&!V),_e=V?"border-transparent dark:border-transparent md:border-transparent md:dark:border-transparent":"",Y=!Da()&&V?"pt-0 pb-0 md:pt-0 md:pb-1":"",le=`${um} ${_e} ${Y}`.trim(),de=ao(),Ee=r.some(Se=>{var Ce;return(Se.messages.length>0||(((Ce=Se.attachedFiles)==null?void 0:Ce.length)??0)>0)&&!Se.adapterLoadError}),me=de&&!Ee,Me=V?"pt-0 md:pt-0":"pt-4 md:pt-6",Ue=m.useMemo(()=>{var Be,ht,st;if(V)return null;const Se=om(y==null?void 0:y.adapterName)||lm();if(!Se&&!(y!=null&&y.adapterName))return null;const Ce=(Be=y==null?void 0:y.adapterName)==null?void 0:Be.trim(),re=(st=(ht=y==null?void 0:y.adapterInfo)==null?void 0:ht.notes)==null?void 0:st.trim();return Se?{...Se,notes:re||Se.notes}:Ce?{id:Ce,name:Ce,notes:re||void 0}:null},[(et=y==null?void 0:y.adapterInfo)==null?void 0:et.notes,y==null?void 0:y.adapterName,V]);m.useEffect(()=>{Bo(Ue)},[Ue]),m.useEffect(()=>{let Se=null;const Ce=()=>{Se&&(Se(),Se=null)};if(b.voiceEnabled){if(ns.isAudioEnabled())return z("[ChatInterface] Audio streaming already enabled"),Ce;const re=()=>{Ce();const Be=async()=>{Ce(),await ns.enableAudio()?z("[ChatInterface] Audio streaming enabled after user gesture"):(we("[ChatInterface] User gesture did not enable audio streaming"),re())};document.addEventListener("pointerdown",Be,{once:!0}),document.addEventListener("keydown",Be,{once:!0}),Se=()=>{document.removeEventListener("pointerdown",Be),document.removeEventListener("keydown",Be)},z("[ChatInterface] Waiting for user gesture to enable audio streaming")};return re(),Ce}return Ce(),ns.disableAudio(),z("[ChatInterface] Audio streaming disabled via settings"),Ce},[b.voiceEnabled]);const Ze=(Se,Ce,re,Be)=>{var ht;l(Se,Ce,re,q??((ht=y==null?void 0:y.adapterInfo)==null?void 0:ht.model)??void 0,Be)},jt=async(Se,Ce,re,Be,ht)=>{var st;await l(re,void 0,Se,ht??q??((st=y==null?void 0:y.adapterInfo)==null?void 0:st.model)??void 0,Be)},Fe=()=>{try{i()}catch(Se){we("Cannot create new conversation:",Se instanceof Error?Se.message:"Unknown error")}},Tt=m.useCallback(async(Se,Ce)=>{if(y)try{await ye.getState().deleteThread(y.id,Se,Ce)}catch(re){ke("Failed to clear thread:",re)}},[y]);return n.jsx("main",{className:"flex-1 flex flex-col bg-transparent overflow-hidden","aria-label":s("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 ${dm}`,children:[g&&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:g}),n.jsx("button",{onClick:p,className:"ml-4 rounded p-1 text-red-500 hover:bg-red-100 hover:text-red-700 dark:text-red-200 dark:hover:bg-red-800/40","aria-label":s("chatInterface.error.dismissAriaLabel"),children:"×"})]})}),n.jsxs("div",{className:le,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:!I,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 ${I?"border-white/50 bg-white/80 text-gray-800 active:scale-[0.97] hover:bg-white dark:border-[#2f303d] dark:bg-[#232430] dark:text-[#ececf1]":"cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400 shadow-none dark:border-[#2f303d] dark:bg-[#181922] dark:text-[#6b6f7a]"}`,"aria-label":s("chatInterface.mobile.openChatsMenuAriaLabel"),children:[n.jsx(Cd,{className:"h-4 w-4"}),s("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":s("chatInterface.mobile.openSettingsAriaLabel"),children:[n.jsx(Qn,{className:"h-4 w-4"}),s("chatInterface.mobile.settingsButton")]})]}),n.jsx("div",{className:"ml-auto flex-shrink-0",children:n.jsx(Ga,{})})]}),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:De&&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)||s("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:s("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":s("chatInterface.settings.ariaLabel"),title:s("chatInterface.settings.title"),children:n.jsx(Qn,{className:"h-4 w-4"})})}),!U&&!V&&!!(y!=null&&y.adapterName)&&n.jsx("button",{type:"button",onClick:()=>{ge&&Q()},disabled:!ge,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 ${ge?"border-blue-300 text-blue-700 hover:bg-blue-50 hover:border-blue-400 focus-visible:ring-blue-500 dark:border-blue-500/40 dark:text-blue-300 dark:hover:bg-blue-900/20 dark:hover:border-blue-400/60 dark:focus-visible:ring-blue-400/60":"cursor-not-allowed border-gray-200 text-gray-400 bg-transparent dark:border-[#3c3f4a] dark:text-[#6b6f7a]"}`,title:s(ge?"chatInterface.changeAgent.titleEnabled":"chatInterface.changeAgent.titleDisabled"),children:s("chatInterface.changeAgent.button")}),!V&&n.jsxs("button",{onClick:Fe,disabled:!ve,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 ${ve?"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(Rd,{className:"h-3.5 w-3.5"}),s("chatInterface.newConversation.button")]}),!Da()&&n.jsx("div",{className:"order-4 hidden flex-shrink-0 items-center md:inline-flex",children:n.jsx(Ga,{})})]})]})]}),C&&y?n.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[y.messages.length>0?n.jsx(wi,{messages:y.messages,onRegenerate:()=>{},onEditMessage:()=>{},onStartThread:async()=>{},onClearThread:async()=>{},onSendThreadMessage:async()=>{},sessionId:y.sessionId,isLoading:!1,contentMaxWidthClass:ue,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:Kn(y.adapterName)||y.adapterName}),Ue&&_i()&&n.jsx(Ei,{adapter:Ue,syntaxTheme:M,forcedThemeClass:v})]})}),n.jsx("div",{className:Ti,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($f,{conversationId:y.id,adapterName:y.adapterName,sessionId:y.sessionId,adapterNotes:((Gt=y.adapterInfo)==null?void 0:Gt.notes)||(Ue==null?void 0:Ue.notes)||(Ue==null?void 0:Ue.description)})})})]}):N?n.jsxs("div",{className:`flex flex-1 flex-col min-h-0 ${Me} ${V?"overflow-hidden":""}`,children:[V?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:`${fe} 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(zt,{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}),A&&n.jsx("div",{className:"mt-2",children:n.jsx(zt,{content:B,className:F,syntaxTheme:M})})]})}),n.jsx(zf,{onAdapterSelect:T,className:`${fe} 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 ${pe} flex-col items-center gap-4 pb-8 md:gap-5 md:pb-12`,children:[ne?n.jsx("p",{className:"w-full text-center text-sm text-red-600 dark:text-red-400",children:ne}):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:Kn(y.adapterName)||y.adapterName}):he?n.jsx("p",{className:"w-full text-center text-sm text-gray-500 dark:text-[#bfc2cd]",children:s("chatInterface.empty.configuringAgent")}):null,Ue&&_i()&&n.jsx(Ei,{adapter:Ue,syntaxTheme:M,forcedThemeClass:v}),n.jsx("div",{className:"w-full min-w-0",children:n.jsx(ji,{onSend:Ze,disabled:u||!y||!(y!=null&&y.adapterName)||W,autoFocusEnabled:!0,desktopOnlyAutoFocus:U,placeholder:j,isCentered:!0,maxWidthClass:pe,adapterNotes:(Mt=y==null?void 0:y.adapterInfo)==null?void 0:Mt.notes,skillState:X,availableModels:G,defaultModel:((Ae=y==null?void 0:y.adapterInfo)==null?void 0:Ae.model)??null,selectedModel:q,onSelectModel:H})})]})}),me&&n.jsx("div",{className:"shrink-0 pt-5 md:pt-6",children:n.jsx(Po,{compact:!0})})]}):n.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[n.jsx(wi,{messages:y.messages,onRegenerate:Se=>{var Ce;return c(Se,q??((Ce=y==null?void 0:y.adapterInfo)==null?void 0:Ce.model)??void 0)},onEditMessage:(Se,Ce)=>{var re;return d(Se,Ce,q??((re=y==null?void 0:y.adapterInfo)==null?void 0:re.model)??void 0)},onStartThread:async(Se,Ce)=>{try{await h(Se,Ce)}catch(re){ke("Failed to create thread:",re)}},onClearThread:Tt,onSendThreadMessage:jt,sessionId:y.sessionId,isLoading:u,contentMaxWidthClass:ue,availableModels:G,defaultModel:((ft=y==null?void 0:y.adapterInfo)==null?void 0:ft.model)??null,selectedModel:q}),n.jsx("div",{className:Ti,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(ji,{onSend:Ze,disabled:u||!y||!y.adapterName||ae||W,autoFocusEnabled:!0,placeholder:s("chatInterface.docked.placeholder"),maxWidthClass:ue,isCentered:!1,adapterNotes:(mt=y==null?void 0:y.adapterInfo)==null?void 0:mt.notes,skillState:X,availableModels:G,defaultModel:((Xt=y==null?void 0:y.adapterInfo)==null?void 0:Xt.model)??null,selectedModel:q,onSelectModel:H})})})]})]})})})}function mm({selectedAdapter:t,onAdapterChange:e,disabled:s,showDescriptions:r=!1,variant:a="sidebar",label:i,showLabel:o}){const{t:l}=Le(),[c,d]=m.useState([]),[u,f]=m.useState(!0),[g,p]=m.useState(null),[h,x]=m.useState(!1);m.useEffect(()=>{let C=!0;async function I(){try{f(!0),p(null);const N=await ln();C&&d(N)}catch(N){ke("Failed to load adapters:",N),C&&p(l("adapterSelector.failedToLoad"))}finally{C&&f(!1)}}return I(),()=>{C=!1}},[l]);const b=c.find(C=>C.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 C="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"?[C,"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:()=>!s&&x(!h),disabled:s||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"):g?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(js,{className:`h-4 w-4 flex-shrink-0 transition-transform text-gray-400 dark:text-gray-300 ${h?"rotate-180":""}`})]})}),h&&!s&&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(C=>{const I=C.id===t;return n.jsx("button",{type:"button",onClick:()=>{I||e(C.id),x(!1)},className:`w-full px-4 py-3 text-left text-sm transition-colors ${I?"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:C.name}),r&&C.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:C.description})]})},C.id)})})})]})]}),g&&n.jsx("p",{className:"mt-1 text-xs text-red-600 dark:text-red-400",children:g})]})}const Mr=100;function Mi({onClick:t,label:e,hoverClassName:s,icon:r}){return n.jsx("button",{onClick:t,className:`rounded-lg p-1.5 text-slate-400 transition-colors dark:text-[#6b6f7a] ${s}`,"aria-label":e,children:r})}function hm(t,e){const s=new Date(e.getFullYear(),e.getMonth(),e.getDate()),r=new Date(s);r.setDate(r.getDate()-1);const a=new Date(s);a.setDate(a.getDate()-s.getDay());const i=new Date(e.getFullYear(),e.getMonth(),1);return t>=s?"today":t>=r?"yesterday":t>=a?"thisWeek":t>=i?"thisMonth":"earlier"}function pm(t){const e=new Date,s=["today","yesterday","thisWeek","thisMonth","earlier"],r=new Map;for(const a of t){const i=hm(a.updatedAt,e),o=r.get(i);o?o.push(a):r.set(i,[a])}return s.filter(a=>r.has(a)).map(a=>({label:a,conversations:r.get(a)}))}function Fi({onRequestClose:t,onToggleDesktopSidebar:e}){const{t:s}=Le(),r=ea(),{conversations:a,currentConversationId:i,selectConversation:o,deleteConversation:l,deleteAllConversations:c,updateConversationTitle:d,getConversationCount:u,configureApiSettings:f,clearError:g}=ye(),p=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,C]=m.useState(!1),[I,N]=m.useState(null),[R,O]=m.useState(!1),[X,j]=m.useState(null),L=m.useRef(null),B=m.useRef(null),A=m.useRef(null),K=!p||p.messages.length===0,G=(I==null?void 0:I.conversationId)===i?I.adapterName:(p==null?void 0:p.adapterName)??null,J=(X==null?void 0:X.conversationId)===i?X.message:null,q=m.useMemo(()=>a.filter(Y=>{var Z;return(Y.messages.length>0||(((Z=Y.attachedFiles)==null?void 0:Z.length)||0)>0)&&!Y.adapterLoadError}),[a]),H=m.useMemo(()=>{if(!h)return q;const Y=h.toLowerCase();return q.filter(Z=>(Z.title||s("chatInterface.newChatTitle")).toLowerCase().includes(Y)||Z.messages.some(le=>le.content.toLowerCase().includes(Y))||(Z.attachedFiles||[]).some(le=>le.filename.toLowerCase().includes(Y)))},[q,h,s]),ne=m.useMemo(()=>pm(H),[H]),T=u(),Q=h.length>0,$=q.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 Z=(me=B.current)==null?void 0:me.querySelectorAll('[role="option"]');if(!Z||Z.length===0)return;const le=document.activeElement,de=Array.from(Z).indexOf(le);let Ee;Y.key==="ArrowDown"?Ee=de<Z.length-1?de+1:0:Ee=de>0?de-1:Z.length-1,Z[Ee].focus()},[]),ae=async Y=>{if(!(!K||!Y)){N({conversationId:i??null,adapterName:Y}),j(null),O(!0);try{const Z=(p==null?void 0:p.apiUrl)||$e();await f(Z,void 0,Y),g(),C(!1)}catch(Z){ke("Failed to configure adapter:",Z),j({conversationId:i??null,message:Z instanceof Error?Z.message:s("sidebar.adapterConfigureFailed")})}finally{O(!1)}}},he=async Y=>{try{await o(Y),t==null||t()}catch(Z){ke("Failed to select conversation:",Z)}},U=(Y,Z)=>{Y.stopPropagation(),v({isOpen:!0,conversationId:Z.id,conversationTitle:Z.title||s("chatInterface.newChatTitle"),isDeleting:!1})},V=async()=>{v(Y=>({...Y,isDeleting:!0}));try{await l(_.conversationId)}catch(Y){ke("Failed to delete conversation:",Y)}v({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},se=()=>{v({isOpen:!1,conversationId:"",conversationTitle:"",isDeleting:!1})},ue=(Y,Z)=>{Y.stopPropagation(),k(Z.id),E((Z.title||s("chatInterface.newChatTitle")).slice(0,Mr))},pe=Y=>{const Z=S.slice(0,Mr).trim();Z&&d(Y,Z),k(null),E("")},fe=()=>{k(null),E("")},ve=()=>{F({isOpen:!0,isDeleting:!1})},ge=async()=>{F(Y=>({...Y,isDeleting:!0}));try{await c(),F({isOpen:!1,isDeleting:!1}),t==null||t()}catch(Y){ke("Failed to clear all conversations:",Y),F(Z=>({...Z,isDeleting:!1}))}},Te=()=>{F({isOpen:!1,isDeleting:!1})},De=Y=>{var Z,le,de;return(Z=Y.adapterName)!=null&&Z.trim()?Y.adapterName:(de=(le=Y.adapterInfo)==null?void 0:le.adapter_name)!=null&&de.trim()?Y.adapterInfo.adapter_name:null};Gs(L,{enabled:y,onEscape:()=>C(!1)});const _e=Y=>{const Z=i===Y.id,le=r?null:De(Y),de=Y.title||s("chatInterface.newChatTitle");return n.jsx("div",{role:"option","aria-selected":Z,tabIndex:0,onKeyDown:Ee=>{(Ee.key==="Enter"||Ee.key===" ")&&(Ee.preventDefault(),he(Y.id))},onClick:()=>he(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
|
|
338
|
+
${Z?"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":Z?"true":void 0,"aria-label":s("sidebar.conversationCard.openAriaLabel",{title:de}),children:b===Y.id?n.jsx("input",{type:"text",value:S,onChange:Ee=>E(Ee.target.value.slice(0,Mr)),onKeyDown:Ee=>{Ee.key==="Enter"&&pe(Y.id),Ee.key==="Escape"&&fe(),Ee.stopPropagation()},onBlur:()=>pe(Y.id),maxLength:Mr,className:"relative z-10 flex-1 rounded-lg border border-sky-300 bg-white px-2 py-1 text-sm text-[#353740] focus:outline-none focus:ring-2 focus:ring-sky-400/50 dark:border-sky-500/40 dark:bg-[#1a1b1e] dark:text-[#ececf1]",autoFocus:!0,"aria-label":s("sidebar.conversationCard.editInputAriaLabel")}):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] ${Z?"font-semibold text-slate-900 dark:text-[#ececf1]":"font-medium text-slate-700 dark:text-[#c5c8d6]"}`,children:de}),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(Mi,{onClick:Ee=>ue(Ee,Y),label:s("sidebar.conversationCard.editAriaLabel",{title:de}),hoverClassName:"hover:bg-slate-200/80 hover:text-slate-600 dark:hover:bg-[#3c3f4a] dark:hover:text-[#c5c8d6]",icon:n.jsx(ho,{className:"h-3.5 w-3.5"})}),n.jsx(Mi,{onClick:Ee=>U(Ee,Y),label:s("sidebar.conversationCard.deleteAriaLabel",{title:de}),hoverClassName:"hover:bg-red-100/80 hover:text-red-600 dark:hover:bg-red-900/30 dark:hover:text-red-400",icon:n.jsx(bo,{className:"h-3.5 w-3.5"})})]})]}),le&&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:le})]})},Y.id)};return n.jsxs(n.Fragment,{children:[!r&&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:s("sidebar.selectAgent.title")}),n.jsxs("div",{className:"space-y-5",children:[n.jsx(mm,{selectedAdapter:G,onAdapterChange:ae,disabled:R,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),C(!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:R,children:s("common.cancel")})})]})]})}),n.jsxs("nav",{"aria-label":s("sidebar.navAriaLabel"),className:"flex h-full md:h-[calc(100%-2rem)] md:mt-4 w-full md:w-72 flex-col border-r border-b border-gray-200 md:border-l md:border-t md:rounded-2xl md:overflow-hidden bg-transparent dark:border-[#2d2f39]",children:[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:ve,className:"flex flex-1 items-center justify-center gap-2 rounded-lg border border-red-200 px-3 py-2 text-sm font-medium text-red-600 transition-all duration-150 hover:bg-red-50 hover:border-red-300 hover:shadow-sm dark:border-red-500/25 dark:text-red-400 dark:hover:bg-red-950/20 dark:hover:border-red-500/40",title:s("sidebar.deleteAllConversations.title"),children:[n.jsx(Od,{className:"h-4 w-4"}),s("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":s("sidebar.collapse.ariaLabel"),title:s("sidebar.collapse.title"),children:n.jsx(Ed,{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}),$&&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(Hr,{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:A,type:"text",role:"searchbox","aria-label":s("sidebar.search.ariaLabel"),placeholder:s("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=A.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":s("sidebar.search.clearAriaLabel"),children:n.jsx(Qe,{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:H.length===0?s("sidebar.resultsNone"):s("sidebar.results",{count:H.length})})]})]}),n.jsx("div",{ref:B,role:"listbox","aria-label":s("sidebar.conversations.ariaLabel"),onKeyDown:W,className:"flex-1 overflow-y-auto bg-transparent px-3 py-2",children:H.length===0?null:Q?n.jsx("div",{className:"space-y-1.5",children:H.map(_e)}):n.jsx("div",{className:"space-y-4",children:ne.map(Y=>n.jsxs("section",{"aria-label":s(`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:s(`sidebar.timeGroups.${Y.label}`)}),n.jsx("div",{className:"space-y-1.5",children:Y.conversations.map(_e)})]},Y.label))})}),(()=>{const Y=ro();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":s("appHeader.navLinksAriaLabel"),children:n.jsx("ul",{className:"flex flex-wrap gap-2",children:Y.map(Z=>n.jsx("li",{children:n.jsx("a",{href:Z.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:Z.label})},Z.url))})})})})(),n.jsx("div",{className:"shrink-0 border-t border-gray-200/80 dark:border-[#2d2f39]",children:n.jsx(Po,{placement:"sidebar",compact:!0})})]}),n.jsx(qr,{isOpen:_.isOpen,onClose:se,onConfirm:V,title:s("sidebar.deleteConfirm.title"),message:s("sidebar.deleteConfirm.message",{title:_.conversationTitle}),confirmText:s("sidebar.deleteConfirm.confirmText"),cancelText:s("common.cancel"),type:"danger",isLoading:_.isDeleting}),n.jsx(qr,{isOpen:M.isOpen,onClose:Te,onConfirm:ge,title:s("sidebar.clearAllConfirm.title"),message:s("sidebar.clearAllConfirm.message",{count:T}),confirmText:s("sidebar.clearAllConfirm.confirmText"),cancelText:s("common.cancel"),type:"danger",isLoading:M.isDeleting})]})}const gm="3.13.4",xm={version:gm},dn=xm.version,bm=["@@auth0spajs@@","a0.spajs","auth0","com.auth0"];function ym(t){const e=t.toLowerCase();return bm.some(s=>e.includes(s.toLowerCase()))}function wm(t){const e=[];for(let s=0;s<t.length;s++){const r=t.key(s);r&&ym(r)&&e.push(r)}e.forEach(s=>t.removeItem(s))}function Ri(t){try{wm(t),t.clear()}catch(e){console.warn("[Settings] Failed to clear browser storage during reset.",e)}}function km(){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(r=>{const a=r.indexOf("="),i=(a>-1?r.slice(0,a):r).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 vm(){Ri(localStorage),Ri(sessionStorage),km()}function Sm({isOpen:t,onClose:e}){const{t:s}=Le(),{theme:r,updateTheme:a}=ps(),{settings:i,updateSettings:o}=Jr(),{activeLanguages:l,currentLanguage:c,setLanguage:d}=ud(),[u,f]=m.useState(!1),[g,p]=m.useState(!1),h=m.useRef(null),x=m.useRef(null),b=m.useMemo(()=>[...l].sort((M,F)=>Sr[M].localeCompare(Sr[F])),[l]);m.useEffect(()=>{if(!g)return;const M=F=>{F.key==="Escape"&&(F.stopPropagation(),p(!1))};return document.addEventListener("keydown",M,{capture:!0}),()=>document.removeEventListener("keydown",M,{capture:!0})},[g]);const k=M=>{a({mode:M})},S=()=>{o({soundEnabled:!i.soundEnabled})},E=()=>{f(!0)},_=()=>{f(!1)},v=()=>{_(),aa(),na(!1),Ss(null),ot.getState().closeLoginPrompt(),vm(),window.location.reload()};return Gs(h,{enabled:t&&!u,onEscape:e}),Gs(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":s("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:s("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":s("settings.dialog.closeButtonAriaLabel"),children:n.jsx(Qe,{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(Id,{className:"w-5 h-5"}),s("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:s("settings.appearance.themeLabel")}),n.jsx("div",{className:"grid grid-cols-3 gap-2",children:[{value:"light",label:s("settings.appearance.themeLight"),icon:Ud},{value:"dark",label:s("settings.appearance.themeDark"),icon:Nd},{value:"system",label:s("settings.appearance.themeSystem"),icon:Ad}].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 ${r.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(vd,{className:"w-4 h-4"}),s("settings.language.label")]}),n.jsxs("div",{className:"relative",children:[n.jsxs("button",{type:"button",onClick:()=>p(M=>!M),"aria-haspopup":"listbox","aria-expanded":g,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 ${g?"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:Sr[c]}),n.jsx(js,{className:`h-4 w-4 flex-shrink-0 text-gray-400 transition-transform duration-200 dark:text-gray-500 ${g?"rotate-180":""}`})]}),g&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>p(!1)}),n.jsx("div",{role:"listbox","aria-label":s("settings.language.label"),className:"absolute z-20 mt-2 max-h-60 w-full overflow-y-auto rounded-lg border border-gray-200 bg-white p-1 shadow-lg ring-1 ring-black/5 dark:border-[#2d2f39] dark:bg-[#1a1b1e] dark:ring-white/5",children:b.map(M=>{const F=M===c;return n.jsxs("button",{type:"button",role:"option","aria-selected":F,onClick:()=>{d(M),p(!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:Sr[M]}),F&&n.jsx(ms,{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:s("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(ra,{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:s("settings.soundEffects.label")}),n.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s("settings.soundEffects.description")})]})]}),n.jsx("button",{onClick:S,role:"switch","aria-checked":i.soundEnabled,"aria-label":s("settings.soundEffects.toggleAriaLabel"),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${i.soundEnabled?"bg-blue-600":"bg-gray-200 dark:bg-[#3c3f4a]"}`,children: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(bo,{className:"w-5 h-5"}),s("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:s("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:s("settings.reset.button")})]})]}),n.jsxs("p",{className:"pt-2 text-center text-xs text-gray-400 dark:text-[#858999]",children:["v",dn]})]}),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(rn,{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:s("settings.reset.confirmTitle")}),n.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:s("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:s("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:s("settings.reset.confirmButton")})]})]})})]})]}):null}function jm({message:t}){const{t:e}=Le(),s=Za();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:s}),n.jsxs("span",{className:"shrink-0 text-xs font-medium text-slate-400 dark:text-[#858999]",children:["v",dn]})]}),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($d,{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 Cm({children:t}){const{instance:e,accounts:s}=Ya(),r=Al();return m.useEffect(()=>{na(r)},[r]),m.useEffect(()=>{if(!r||s.length===0){Ss(null);return}const a=s[0];Ss(a.username||a.name||a.localAccountId||null)},[r,s]),m.useEffect(()=>{if(!r||s.length===0)return;const a=s[0],i=sn();return yo(async()=>(await e.acquireTokenSilent({scopes:i,account:a})).accessToken),()=>aa()},[r,s,e]),n.jsx(n.Fragment,{children:t})}function Am({children:t}){return n.jsx(Cm,{children:t})}function Nm({children:t}){const{isLoading:e,isAuthenticated:s,getAccessTokenSilently:r,user:a}=Qa();return m.useEffect(()=>{na(s)},[s]),m.useEffect(()=>{if(!s){Ss(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;Ss(i)},[s,a]),m.useEffect(()=>(s&&yo(()=>r()),()=>aa()),[s,r]),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 Im({children:t}){return m.useEffect(()=>{na(!1),Ss(null),aa()},[]),n.jsx(n.Fragment,{children:t})}function Em({children:t}){return it()?ta()==="entra"?n.jsx(Am,{children:t}):n.jsx(Nm,{children:t}):n.jsx(Im,{children:t})}function Lm(){const t=tn(),e=it(),s=Cs(),{showLoginPrompt:r,promptMessage:a,closeLoginPrompt:i}=ot();return m.useEffect(()=>{r&&(!t||!e||s)&&i()},[r,t,e,s,i]),!t||!e||s||!r?null:ta()==="entra"?n.jsx(Tm,{message:a,onClose:i}):n.jsx(_m,{message:a,onClose:i})}function _m({message:t,onClose:e}){const{loginWithRedirect:s}=Qa();return n.jsx(Ho,{message:t,onClose:e,onLogin:()=>s()})}function Tm({message:t,onClose:e}){const{instance:s}=Ya();return n.jsx(Ho,{message:t,onClose:e,onLogin:()=>s.loginRedirect({scopes:sn()}).catch(()=>{})})}function Ho({message:t,onClose:e,onLogin:s}){const{t:r}=Le();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":r("common.close"),children:n.jsx(Qe,{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(fo,{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:r("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:s,className:"flex-1 rounded-lg bg-blue-600 px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:bg-blue-500 dark:hover:bg-blue-600",children:r("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:r("common.cancel")})]})]})]})}function Mm(){const{t}=Le(),{goHome:e}=zo(),{isDark:s}=ps(),r=Wf(),a=m.useRef(!1),i=Wc(),o=Kc(),l=Gc(),c=s?l:o,d=Xc(),u=Yc(),f=!!(d||u),g=Qc(),p=Jc(),h=Zc(),x=ro(),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]),Da()?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:g||void 0,color:p||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:r,"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:p||void 0},children:S.label})},S.url))})}),n.jsx(Ga,{})]})]})}):null}function Fm({children:t}){const e=m.useRef(null),s=m.useCallback(a=>{e.current=a},[]),r=m.useCallback(()=>{var a;(a=e.current)==null||a.call(e)},[]);return n.jsx(Oo.Provider,{value:{registerGoHome:s,goHome:r},children:t})}function Rm(){const{t}=Le(),[e,s]=m.useState(!1),[r,a]=m.useState(!1),[i,o]=m.useState(()=>localStorage.getItem("desktop-sidebar-collapsed")==="true"),l=ye(u=>u.conversations),c=Bc();if(m.useEffect(()=>{localStorage.setItem("desktop-sidebar-collapsed",String(i))},[i]),c)return n.jsx(Ln,{children:n.jsx(jm,{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(Ln,{children:n.jsx(Ll,{children:n.jsx(dd,{children:n.jsx(Em,{children:n.jsx(Fm,{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(Ld,{className:"h-4 w-4"})})}):n.jsx("div",{className:"hidden md:h-full md:flex",children:n.jsx(Fi,{onToggleDesktopSidebar:()=>o(!0)})})),n.jsxs("div",{className:"flex-1 flex flex-col w-full min-h-0",children:[n.jsx(Mm,{}),n.jsx("div",{className:"flex-1 flex justify-center w-full min-h-0",children:n.jsx(fm,{onOpenSettings:()=>s(!0),onOpenSidebar:()=>a(!0)})})]})]}),n.jsx(Lm,{}),n.jsx(Sm,{isOpen:e,onClose:()=>s(!1)}),r&&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(Fi,{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(Qe,{className:"h-5 w-5"})})]})]})]})})})})})})}const _a=new Nl({auth:{clientId:to(),authority:`https://login.microsoftonline.com/${qc()}`,redirectUri:typeof window<"u"?window.location.origin:"/"},cache:{cacheLocation:"sessionStorage"}});function $m({children:t}){const[e,s]=m.useState(!1);return m.useEffect(()=>{_a.initialize().then(()=>_a.handleRedirectPromise()).catch(r=>{console.error("[EntraAuth] Redirect processing failed:",r)}).finally(()=>s(!0))},[]),e?n.jsx(Il,{instance:_a,children:t}):null}function Pm({children:t}){if(!tn()||!it())return n.jsx(n.Fragment,{children:t});if(ta()==="entra")return n.jsx($m,{children:t});const s=Hc(),r=to(),a=Vc();return!s||!r?n.jsx(n.Fragment,{children:t}):n.jsx(El,{domain:s,clientId:r,authorizationParams:{redirect_uri:window.location.origin,...a?{audience:a}:{}},cacheLocation:"memory",children:t})}Bo(null);const $i=Fc(),Pi=document.querySelector('link[rel="icon"]');if(Pi)Pi.href=$i;else{const t=document.createElement("link");t.rel="icon",t.href=$i,document.head.appendChild(t)}const Dm=id();var Di,Ui,Oi,zi,Bi,Hi;for(const t of Dm){const e=((Di=t.src)==null?void 0:Di.trim())||"",s=((Ui=t.content)==null?void 0:Ui.trim())||"",r=((Oi=t.id)==null?void 0:Oi.trim())||"";if(!e&&!s||r&&document.querySelector(`script[data-orbitchat-startup-script-id="${r}"]`)||Array.from(document.querySelectorAll("script[data-orbitchat-startup-script]")).some(o=>{const l=e&&o.dataset.orbitchatStartupScriptSrc===e,c=s&&(o.textContent||"").trim()===s;return!!(l||c)}))continue;const i=document.createElement("script");e&&(i.src=e),s&&(i.text=s),i.async=t.async??!0,t.defer!==void 0&&(i.defer=t.defer),(zi=t.type)!=null&&zi.trim()&&(i.type=t.type.trim()),(Bi=t.integrity)!=null&&Bi.trim()&&(i.integrity=t.integrity.trim()),t.crossOrigin&&(i.crossOrigin=t.crossOrigin),(Hi=t.referrerPolicy)!=null&&Hi.trim()&&(i.referrerPolicy=t.referrerPolicy.trim()),i.dataset.orbitchatStartupScript="true",r&&(i.dataset.orbitchatStartupScriptId=r),e&&(i.dataset.orbitchatStartupScriptSrc=e),document.head.appendChild(i)}z("🚀 AI Chat Application started");z(`📱 App Version: v${dn}`);fl.createRoot(document.getElementById("root")).render(n.jsx(m.StrictMode,{children:n.jsx(Pm,{children:n.jsx(Rm,{})})}));export{uc as r,Le as u};
|